feat: Add language switcher for preview route

This commit is contained in:
Илья Куприец 2025-05-27 20:57:14 +03:00
parent ede6681c28
commit b837aae711
13 changed files with 1113 additions and 852 deletions

View File

@ -121,7 +121,7 @@ export const StationEditModal = observer(() => {
>
<Box sx={style}>
<Edit
title={<Typography variant="h5">Редактирование станции</Typography>}
title={<Typography variant="h5">Редактирование остановки</Typography>}
saveButtonProps={saveButtonProps}
>
<Box

View File

@ -94,9 +94,9 @@
},
"station": {
"titles": {
"create": "Создать станцию",
"edit": "Редактировать станцию",
"show": "Показать станцию"
"create": "Создать остановку",
"edit": "Редактировать остановку",
"show": "Показать остановку"
}
},
"snapshots": {

View File

@ -1,11 +1,15 @@
import { FederatedMouseEvent, FederatedWheelEvent } from "pixi.js";
import { Component, ReactNode, useEffect, useState } from "react";
import { Component, ReactNode, useEffect, useState, useRef } from "react";
import { useTransform } from "./TransformContext";
import { useMapData } from "./MapDataContext";
import { SCALE_FACTOR } from "./Constants";
import { useApplication } from "@pixi/react";
import { languageStore } from "@/store/LanguageStore";
class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean }> {
class ErrorBoundary extends Component<
{ children: ReactNode },
{ hasError: boolean }
> {
state = { hasError: false };
static getDerivedStateFromError() {
@ -19,11 +23,21 @@ class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boole
render() {
return this.state.hasError ? <p>Whoopsie Daisy!</p> : this.props.children;
}
}
}
export function InfiniteCanvas({children} : Readonly<{children?: ReactNode}>) {
const { position, setPosition, scale, setScale, rotation, setRotation, setScreenCenter, screenCenter } = useTransform();
export function InfiniteCanvas({
children,
}: Readonly<{ children?: ReactNode }>) {
const {
position,
setPosition,
scale,
setScale,
rotation,
setRotation,
setScreenCenter,
screenCenter,
} = useTransform();
const { routeData, originalRouteData } = useMapData();
const applicationRef = useApplication();
@ -33,43 +47,65 @@ export function InfiniteCanvas({children} : Readonly<{children?: ReactNode}>) {
const [startRotation, setStartRotation] = useState(0);
const [startPosition, setStartPosition] = useState({ x: 0, y: 0 });
// Флаг для предотвращения конфликта между пользовательским вводом и данными маршрута
const [isUserInteracting, setIsUserInteracting] = useState(false);
// Реф для отслеживания последнего значения originalRouteData?.rotate
const lastOriginalRotation = useRef<number | undefined>(undefined);
useEffect(() => {
const canvas = applicationRef?.app.canvas;
if (!canvas) return;
const canvasRect = canvas.getBoundingClientRect();
const canvasLeft = canvasRect?.left ?? 0;
const canvasTop = canvasRect?.top ?? 0;
const canvasLeft = canvasRect.left;
const canvasTop = canvasRect.top;
const centerX = window.innerWidth / 2 - canvasLeft;
const centerY = window.innerHeight / 2 - canvasTop;
setScreenCenter({x: centerX, y: centerY});
}, [applicationRef?.app.canvas, window.innerWidth, window.innerHeight]);
setScreenCenter({ x: centerX, y: centerY });
}, [applicationRef?.app.canvas, setScreenCenter]);
const handlePointerDown = (e: FederatedMouseEvent) => {
setIsDragging(true);
setIsUserInteracting(true); // Устанавливаем флаг взаимодействия пользователя
setStartPosition({
x: position.x,
y: position.y
y: position.y,
});
setStartMousePosition({
x: e.globalX,
y: e.globalY
y: e.globalY,
});
setStartRotation(rotation);
e.stopPropagation();
};
// Устанавливаем rotation только при изменении originalRouteData и отсутствии взаимодействия пользователя
useEffect(() => {
setRotation((originalRouteData?.rotate ?? 0) * Math.PI / 180);
}, [originalRouteData?.rotate]);
// Get canvas element and its dimensions/position
const newRotation = originalRouteData?.rotate ?? 0;
// Обновляем rotation только если:
// 1. Пользователь не взаимодействует с канвасом
// 2. Значение действительно изменилось
if (!isUserInteracting && lastOriginalRotation.current !== newRotation) {
setRotation((newRotation * Math.PI) / 180);
lastOriginalRotation.current = newRotation;
}
}, [originalRouteData?.rotate, isUserInteracting, setRotation]);
const handlePointerMove = (e: FederatedMouseEvent) => {
if (!isDragging) return;
if (e.shiftKey) {
const center = screenCenter ?? {x: 0, y: 0};
const startAngle = Math.atan2(startMousePosition.y - center.y, startMousePosition.x - center.x);
const currentAngle = Math.atan2(e.globalY - center.y, e.globalX - center.x);
const center = screenCenter ?? { x: 0, y: 0 };
const startAngle = Math.atan2(
startMousePosition.y - center.y,
startMousePosition.x - center.x
);
const currentAngle = Math.atan2(
e.globalY - center.y,
e.globalX - center.x
);
// Calculate rotation difference in radians
const rotationDiff = currentAngle - startAngle;
@ -81,53 +117,71 @@ export function InfiniteCanvas({children} : Readonly<{children?: ReactNode}>) {
const sinDelta = Math.sin(rotationDiff);
setPosition({
x: center.x * (1 - cosDelta) + startPosition.x * cosDelta + (center.y - startPosition.y) * sinDelta,
y: center.y * (1 - cosDelta) + startPosition.y * cosDelta + (startPosition.x - center.x) * sinDelta
x:
center.x * (1 - cosDelta) +
startPosition.x * cosDelta +
(center.y - startPosition.y) * sinDelta,
y:
center.y * (1 - cosDelta) +
startPosition.y * cosDelta +
(startPosition.x - center.x) * sinDelta,
});
} else {
setRotation(startRotation);
setPosition({
x: startPosition.x - startMousePosition.x + e.globalX,
y: startPosition.y - startMousePosition.y + e.globalY
y: startPosition.y - startMousePosition.y + e.globalY,
});
}
e.stopPropagation();
};
// Handle mouse up
const handlePointerUp = (e: FederatedMouseEvent) => {
setIsDragging(false);
// Сбрасываем флаг взаимодействия через небольшую задержку
// чтобы избежать немедленного срабатывания useEffect
setTimeout(() => {
setIsUserInteracting(false);
}, 100);
e.stopPropagation();
};
// Handle mouse wheel for zooming
const handleWheel = (e: FederatedWheelEvent) => {
e.stopPropagation();
setIsUserInteracting(true); // Устанавливаем флаг при зуме
// Get mouse position relative to canvas
const mouseX = e.globalX - position.x;
const mouseY = e.globalY - position.y;
// Calculate new scale
const scaleMin = (routeData?.scale_min ?? 10)/SCALE_FACTOR;
const scaleMax = (routeData?.scale_max ?? 20)/SCALE_FACTOR;
const scaleMin = (routeData?.scale_min ?? 10) / SCALE_FACTOR;
const scaleMax = (routeData?.scale_max ?? 20) / SCALE_FACTOR;
let zoomFactor = e.deltaY > 0 ? 0.9 : 1.1; // Zoom out/in
//const newScale = scale * zoomFactor;
const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1; // Zoom out/in
const newScale = Math.max(scaleMin, Math.min(scaleMax, scale * zoomFactor));
zoomFactor = newScale / scale;
const actualZoomFactor = newScale / scale;
if (scale === newScale) {
// Сбрасываем флаг, если зум не изменился
setTimeout(() => {
setIsUserInteracting(false);
}, 100);
return;
}
// Update position to zoom towards mouse cursor
setPosition({
x: position.x + mouseX * (1 - zoomFactor),
y: position.y + mouseY * (1 - zoomFactor)
x: position.x + mouseX * (1 - actualZoomFactor),
y: position.y + mouseY * (1 - actualZoomFactor),
});
setScale(newScale);
// Сбрасываем флаг взаимодействия через задержку
setTimeout(() => {
setIsUserInteracting(false);
}, 100);
};
useEffect(() => {
@ -135,7 +189,6 @@ export function InfiniteCanvas({children} : Readonly<{children?: ReactNode}>) {
console.log(position, scale, rotation);
}, [position, scale, rotation]);
return (
<ErrorBoundary>
{applicationRef?.app && (
@ -146,7 +199,7 @@ export function InfiniteCanvas({children} : Readonly<{children?: ReactNode}>) {
g.rect(0, 0, canvas?.width ?? 0, canvas?.height ?? 0);
g.fill("#111");
}}
eventMode={'static'}
eventMode={"static"}
interactive
onPointerDown={handlePointerDown}
onGlobalPointerMove={handlePointerMove}
@ -166,7 +219,6 @@ export function InfiniteCanvas({children} : Readonly<{children?: ReactNode}>) {
{/* Show center of the screen.
<pixiGraphics
eventMode="none"
draw={(g) => {
g.clear();
const center = screenCenter ?? {x: 0, y: 0};

View File

@ -1,18 +1,59 @@
import { Stack, Typography, Button } from "@mui/material";
import { useNavigate, useNavigationType } from "react-router";
export function LeftSidebar() {
const navigate = useNavigate();
const navigationType = useNavigationType(); // PUSH, POP, REPLACE
const handleBack = () => {
if (navigationType === "PUSH") {
navigate(-1);
} else {
navigate("/route");
}
};
return (
<Stack direction="column" width="300px" p={2} bgcolor="primary.main">
<Stack direction="column" alignItems="center" justifyContent="center" my={10}>
<button
onClick={handleBack}
type="button"
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
gap: 10,
color: "#fff",
backgroundColor: "#222",
borderRadius: 10,
width: "100%",
border: "none",
cursor: "pointer",
}}
>
<p>Назад</p>
</button>
<Stack
direction="column"
alignItems="center"
justifyContent="center"
my={10}
>
<img src={"/Emblem.svg"} alt="logo" width={100} height={100} />
<Typography sx={{ mb: 2 }} textAlign="center">
При поддержке Правительства
Санкт-Петербурга
<Typography sx={{ mb: 2, color: "#fff" }} textAlign="center">
При поддержке Правительства Санкт-Петербурга
</Typography>
</Stack>
<Stack direction="column" alignItems="center" justifyContent="center" my={10} spacing={2}>
<Stack
direction="column"
alignItems="center"
justifyContent="center"
my={10}
spacing={2}
>
<Button variant="outlined" color="warning" fullWidth>
Достопримечательности
</Button>
@ -21,13 +62,28 @@ export function LeftSidebar() {
</Button>
</Stack>
<Stack direction="column" alignItems="center" justifyContent="center" my={10}>
<img src={"/GET.png"} alt="logo" width="80%" style={{margin: "0 auto"}}/>
<Stack
direction="column"
alignItems="center"
justifyContent="center"
my={10}
>
<img
src={"/GET.png"}
alt="logo"
width="80%"
style={{ margin: "0 auto" }}
/>
</Stack>
<Typography variant="h6" textAlign="center" mt="auto">#ВсемПоПути</Typography>
<Typography
variant="h6"
textAlign="center"
mt="auto"
sx={{ color: "#fff" }}
>
#ВсемПоПути
</Typography>
</Stack>
);
}

View File

@ -1,4 +1,4 @@
import { useCustom, useApiUrl } from "@refinedev/core";
import { useApiUrl } from "@refinedev/core";
import { useParams } from "react-router";
import {
createContext,
@ -16,6 +16,9 @@ import {
StationPatchData,
} from "./types";
import { axiosInstance } from "../../providers/data";
import { languageStore, META_LANGUAGE } from "@/store/LanguageStore";
import { observer } from "mobx-react-lite";
import { axiosInstanceForGet } from "@/providers/data";
const MapDataContext = createContext<{
originalRouteData?: RouteData;
@ -57,9 +60,8 @@ const MapDataContext = createContext<{
saveChanges: () => {},
});
export function MapDataProvider({
children,
}: Readonly<{ children: ReactNode }>) {
export const MapDataProvider = observer(
({ children }: Readonly<{ children: ReactNode }>) => {
const { id: routeId } = useParams<{ id: string }>();
const apiUrl = useApiUrl();
@ -72,30 +74,48 @@ export function MapDataProvider({
const [stationData, setStationData] = useState<StationData[]>();
const [sightData, setSightData] = useState<SightData[]>();
const [routeChanges, setRouteChanges] = useState<RouteData>({} as RouteData);
const [stationChanges, setStationChanges] = useState<StationPatchData[]>([]);
const [routeChanges, setRouteChanges] = useState<Partial<RouteData>>({});
const [stationChanges, setStationChanges] = useState<StationPatchData[]>(
[]
);
const [sightChanges, setSightChanges] = useState<SightPatchData[]>([]);
const { language } = languageStore;
const [isRouteLoading, setIsRouteLoading] = useState(true);
const [isStationLoading, setIsStationLoading] = useState(true);
const [isSightLoading, setIsSightLoading] = useState(true);
const { data: routeQuery, isLoading: isRouteLoading } = useCustom({
url: `${apiUrl}/route/${routeId}`,
method: "get",
});
const { data: stationQuery, isLoading: isStationLoading } = useCustom({
url: `${apiUrl}/route/${routeId}/station`,
method: "get",
});
const { data: sightQuery, isLoading: isSightLoading } = useCustom({
url: `${apiUrl}/route/${routeId}/sight`,
method: "get",
});
useEffect(() => {
// if not undefined, set original data
if (routeQuery?.data) setOriginalRouteData(routeQuery.data as RouteData);
if (stationQuery?.data)
setOriginalStationData(stationQuery.data as StationData[]);
if (sightQuery?.data) setOriginalSightData(sightQuery.data as SightData[]);
console.log("queries", routeQuery, stationQuery, sightQuery);
}, [routeQuery, stationQuery, sightQuery]);
const fetchData = async () => {
try {
setIsRouteLoading(true);
setIsStationLoading(true);
setIsSightLoading(true);
const [routeResponse, stationResponse, sightResponse] =
await Promise.all([
axiosInstanceForGet.get(`/route/${routeId}`),
axiosInstanceForGet.get(`/route/${routeId}/station`),
axiosInstanceForGet.get(`/route/${routeId}/sight`),
]);
setOriginalRouteData(routeResponse.data as RouteData);
setOriginalStationData(stationResponse.data as StationData[]);
setOriginalSightData(sightResponse.data as SightData[]);
setIsRouteLoading(false);
setIsStationLoading(false);
setIsSightLoading(false);
} catch (error) {
console.error("Error fetching data:", error);
setIsRouteLoading(false);
setIsStationLoading(false);
setIsSightLoading(false);
}
};
fetchData();
}, [routeId, language]);
useEffect(() => {
// combine changes with original data
@ -258,9 +278,12 @@ export function MapDataProvider({
);
return (
<MapDataContext.Provider value={value}>{children}</MapDataContext.Provider>
<MapDataContext.Provider value={value}>
{children}
</MapDataContext.Provider>
);
}
}
);
export const useMapData = () => {
const context = useContext(MapDataContext);

View File

@ -5,70 +5,96 @@ import { useTransform } from "./TransformContext";
import { coordinatesToLocal, localToCoordinates } from "./utils";
export function RightSidebar() {
const { routeData, setScaleRange, saveChanges, originalRouteData, setMapRotation, setMapCenter } = useMapData();
const { rotation, position, screenToLocal, screenCenter, rotateToAngle, setTransform } = useTransform();
const {
routeData,
setScaleRange,
saveChanges,
originalRouteData,
setMapRotation,
setMapCenter,
} = useMapData();
const {
rotation,
position,
screenToLocal,
screenCenter,
rotateToAngle,
setTransform,
} = useTransform();
const [minScale, setMinScale] = useState<number>(1);
const [maxScale, setMaxScale] = useState<number>(10);
const [localCenter, setLocalCenter] = useState<{x: number, y: number}>({x: 0, y: 0});
const [localCenter, setLocalCenter] = useState<{ x: number; y: number }>({
x: 0,
y: 0,
});
const [rotationDegrees, setRotationDegrees] = useState<number>(0);
useEffect(() => {
if(originalRouteData) {
if (originalRouteData) {
setMinScale(originalRouteData.scale_min ?? 1);
setMaxScale(originalRouteData.scale_max ?? 10);
setRotationDegrees(originalRouteData.rotate ?? 0);
setLocalCenter({x: originalRouteData.center_latitude ?? 0, y: originalRouteData.center_longitude ?? 0});
setLocalCenter({
x: originalRouteData.center_latitude ?? 0,
y: originalRouteData.center_longitude ?? 0,
});
}
}, [originalRouteData]);
useEffect(() => {
if(minScale && maxScale) {
if (minScale && maxScale) {
setScaleRange(minScale, maxScale);
}
}, [minScale, maxScale]);
useEffect(() => {
setRotationDegrees((Math.round(rotation * 180 / Math.PI) % 360 + 360) % 360);
setRotationDegrees(
((Math.round((rotation * 180) / Math.PI) % 360) + 360) % 360
);
}, [rotation]);
useEffect(() => {
setMapRotation(rotationDegrees);
}, [rotationDegrees]);
useEffect(() => {
const center = screenCenter ?? {x: 0, y: 0};
const center = screenCenter ?? { x: 0, y: 0 };
const localCenter = screenToLocal(center.x, center.y);
const coordinates = localToCoordinates(localCenter.x, localCenter.y);
setLocalCenter({x: coordinates.latitude, y: coordinates.longitude});
setLocalCenter({ x: coordinates.latitude, y: coordinates.longitude });
}, [position]);
useEffect(() => {
setMapCenter(localCenter.x, localCenter.y);
}, [localCenter]);
function setRotationFromDegrees(degrees: number) {
rotateToAngle(degrees * Math.PI / 180);
rotateToAngle((degrees * Math.PI) / 180);
}
function pan({x, y}: {x: number, y: number}) {
const coordinates = coordinatesToLocal(x,y);
function pan({ x, y }: { x: number; y: number }) {
const coordinates = coordinatesToLocal(x, y);
setTransform(coordinates.x, coordinates.y);
}
if(!routeData) {
if (!routeData) {
console.error("routeData is null");
return null;
}
return (
<Stack
position="absolute" right={8} top={8} bottom={8} p={2}
position="absolute"
right={8}
top={8}
bottom={8}
p={2}
gap={1}
minWidth="400px" bgcolor="primary.main"
border="1px solid #e0e0e0" borderRadius={2}
minWidth="400px"
bgcolor="primary.main"
border="1px solid #e0e0e0"
borderRadius={2}
>
<Typography variant="h6" sx={{ mb: 2 }} textAlign="center">
<Typography variant="h6" sx={{ mb: 2, color: "#fff" }} textAlign="center">
Детали о достопримечательностях
</Typography>
@ -79,16 +105,19 @@ export function RightSidebar() {
variant="filled"
value={minScale}
onChange={(e) => setMinScale(Number(e.target.value))}
style={{backgroundColor: "#222", borderRadius: 4}}
style={{ backgroundColor: "#222", borderRadius: 4 }}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
color: "#fff"
}
"& .MuiInputLabel-root": {
color: "#fff",
},
"& .MuiInputBase-input": {
color: "#fff",
},
}}
slotProps={{
input: {
min: 0.1
}
min: 0.1,
},
}}
/>
<TextField
@ -97,16 +126,19 @@ export function RightSidebar() {
variant="filled"
value={maxScale}
onChange={(e) => setMaxScale(Number(e.target.value))}
style={{backgroundColor: "#222", borderRadius: 4}}
style={{ backgroundColor: "#222", borderRadius: 4, color: "#fff" }}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
color: "#fff"
}
"& .MuiInputLabel-root": {
color: "#fff",
},
"& .MuiInputBase-input": {
color: "#fff",
},
}}
slotProps={{
input: {
min: 0.1
}
min: 0.1,
},
}}
/>
</Stack>
@ -123,21 +155,24 @@ export function RightSidebar() {
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
if (e.key === "Enter") {
e.currentTarget.blur();
}
}}
style={{backgroundColor: "#222", borderRadius: 4}}
style={{ backgroundColor: "#222", borderRadius: 4 }}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
color: "#fff"
}
"& .MuiInputLabel-root": {
color: "#fff",
},
"& .MuiInputBase-input": {
color: "#fff",
},
}}
slotProps={{
input: {
min: 0,
max: 360
}
max: 360,
},
}}
/>
@ -146,32 +181,38 @@ export function RightSidebar() {
type="number"
label="Центр карты, широта"
variant="filled"
value={Math.round(localCenter.x*100000)/100000}
value={Math.round(localCenter.x * 100000) / 100000}
onChange={(e) => {
setLocalCenter(prev => ({...prev, x: Number(e.target.value)}))
pan({x: Number(e.target.value), y: localCenter.y});
setLocalCenter((prev) => ({ ...prev, x: Number(e.target.value) }));
pan({ x: Number(e.target.value), y: localCenter.y });
}}
style={{backgroundColor: "#222", borderRadius: 4}}
style={{ backgroundColor: "#222", borderRadius: 4 }}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
color: "#fff"
}
"& .MuiInputLabel-root": {
color: "#fff",
},
"& .MuiInputBase-input": {
color: "#fff",
},
}}
/>
<TextField
type="number"
label="Центр карты, высота"
variant="filled"
value={Math.round(localCenter.y*100000)/100000}
value={Math.round(localCenter.y * 100000) / 100000}
onChange={(e) => {
setLocalCenter(prev => ({...prev, y: Number(e.target.value)}))
pan({x: localCenter.x, y: Number(e.target.value)});
setLocalCenter((prev) => ({ ...prev, y: Number(e.target.value) }));
pan({ x: localCenter.x, y: Number(e.target.value) });
}}
style={{backgroundColor: "#222", borderRadius: 4}}
style={{ backgroundColor: "#222", borderRadius: 4 }}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
color: "#fff"
}
"& .MuiInputLabel-root": {
color: "#fff",
},
"& .MuiInputBase-input": {
color: "#fff",
},
}}
/>
</Stack>

View File

@ -1,21 +1,34 @@
import { createContext, ReactNode, useContext, useMemo, useState } from "react";
import {
createContext,
ReactNode,
useContext,
useMemo,
useState,
useCallback,
} from "react";
import { SCALE_FACTOR, UP_SCALE } from "./Constants";
const TransformContext = createContext<{
position: { x: number, y: number },
scale: number,
rotation: number,
screenCenter?: { x: number, y: number },
position: { x: number; y: number };
scale: number;
rotation: number;
screenCenter?: { x: number; y: number };
setPosition: React.Dispatch<React.SetStateAction<{ x: number, y: number }>>,
setScale: React.Dispatch<React.SetStateAction<number>>,
setRotation: React.Dispatch<React.SetStateAction<number>>,
screenToLocal: (x: number, y: number) => { x: number, y: number },
localToScreen: (x: number, y: number) => { x: number, y: number },
rotateToAngle: (to: number, fromPosition?: {x: number, y: number}) => void,
setTransform: (latitude: number, longitude: number, rotationDegrees?: number, scale?: number) => void,
setScreenCenter: React.Dispatch<React.SetStateAction<{ x: number, y: number } | undefined>>
setPosition: React.Dispatch<React.SetStateAction<{ x: number; y: number }>>;
setScale: React.Dispatch<React.SetStateAction<number>>;
setRotation: React.Dispatch<React.SetStateAction<number>>;
screenToLocal: (x: number, y: number) => { x: number; y: number };
localToScreen: (x: number, y: number) => { x: number; y: number };
rotateToAngle: (to: number, fromPosition?: { x: number; y: number }) => void;
setTransform: (
latitude: number,
longitude: number,
rotationDegrees?: number,
scale?: number
) => void;
setScreenCenter: React.Dispatch<
React.SetStateAction<{ x: number; y: number } | undefined>
>;
}>({
position: { x: 0, y: 0 },
scale: 1,
@ -28,7 +41,7 @@ const TransformContext = createContext<{
localToScreen: () => ({ x: 0, y: 0 }),
rotateToAngle: () => {},
setTransform: () => {},
setScreenCenter: () => {}
setScreenCenter: () => {},
});
// Provider component
@ -36,9 +49,10 @@ export const TransformProvider = ({ children }: { children: ReactNode }) => {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [scale, setScale] = useState(1);
const [rotation, setRotation] = useState(0);
const [screenCenter, setScreenCenter] = useState<{x: number, y: number}>();
const [screenCenter, setScreenCenter] = useState<{ x: number; y: number }>();
function screenToLocal(screenX: number, screenY: number) {
const screenToLocal = useCallback(
(screenX: number, screenY: number) => {
// Translate point relative to current pan position
const translatedX = (screenX - position.x) / scale;
const translatedY = (screenY - position.y) / scale;
@ -51,13 +65,15 @@ export const TransformProvider = ({ children }: { children: ReactNode }) => {
return {
x: rotatedX / UP_SCALE,
y: rotatedY / UP_SCALE
y: rotatedY / UP_SCALE,
};
}
},
[position.x, position.y, scale, rotation]
);
// Inverse of screenToLocal
function localToScreen(localX: number, localY: number) {
const localToScreen = useCallback(
(localX: number, localY: number) => {
const upscaledX = localX * UP_SCALE;
const upscaledY = localY * UP_SCALE;
@ -66,59 +82,86 @@ export const TransformProvider = ({ children }: { children: ReactNode }) => {
const rotatedX = upscaledX * cosRotation - upscaledY * sinRotation;
const rotatedY = upscaledX * sinRotation + upscaledY * cosRotation;
const translatedX = rotatedX*scale + position.x;
const translatedY = rotatedY*scale + position.y;
const translatedX = rotatedX * scale + position.x;
const translatedY = rotatedY * scale + position.y;
return {
x: translatedX,
y: translatedY
y: translatedY,
};
}
},
[position.x, position.y, scale, rotation]
);
function rotateToAngle(to: number, fromPosition?: {x: number, y: number}) {
setRotation(to);
const rotateToAngle = useCallback(
(to: number, fromPosition?: { x: number; y: number }) => {
const rotationDiff = to - rotation;
const center = screenCenter ?? {x: 0, y: 0};
const center = screenCenter ?? { x: 0, y: 0 };
const cosDelta = Math.cos(rotationDiff);
const sinDelta = Math.sin(rotationDiff);
fromPosition ??= position;
const currentFromPosition = fromPosition ?? position;
setPosition({
x: center.x * (1 - cosDelta) + fromPosition.x * cosDelta + (center.y - fromPosition.y) * sinDelta,
y: center.y * (1 - cosDelta) + fromPosition.y * cosDelta + (fromPosition.x - center.x) * sinDelta
});
}
function setTransform(latitude: number, longitude: number, rotationDegrees?: number, useScale ?: number) {
const selectedRotation = rotationDegrees ? (rotationDegrees * Math.PI / 180) : rotation;
const selectedScale = useScale ? useScale/SCALE_FACTOR : scale;
const center = screenCenter ?? {x: 0, y: 0};
console.log("center", center.x, center.y);
const newPosition = {
x: -latitude * UP_SCALE * selectedScale,
y: -longitude * UP_SCALE * selectedScale
x:
center.x * (1 - cosDelta) +
currentFromPosition.x * cosDelta +
(center.y - currentFromPosition.y) * sinDelta,
y:
center.y * (1 - cosDelta) +
currentFromPosition.y * cosDelta +
(currentFromPosition.x - center.x) * sinDelta,
};
const cos = Math.cos(selectedRotation);
const sin = Math.sin(selectedRotation);
// Update both rotation and position in a single batch to avoid stale closure
setRotation(to);
setPosition(newPosition);
},
[rotation, position, screenCenter]
);
const setTransform = useCallback(
(
latitude: number,
longitude: number,
rotationDegrees?: number,
useScale?: number
) => {
const selectedRotation =
rotationDegrees !== undefined
? (rotationDegrees * Math.PI) / 180
: rotation;
const selectedScale =
useScale !== undefined ? useScale / SCALE_FACTOR : scale;
const center = screenCenter ?? { x: 0, y: 0 };
console.log("center", center.x, center.y);
const newPosition = {
x: -latitude * UP_SCALE * selectedScale,
y: -longitude * UP_SCALE * selectedScale,
};
const cosRot = Math.cos(selectedRotation);
const sinRot = Math.sin(selectedRotation);
// Translate point relative to center, rotate, then translate back
const dx = newPosition.x;
const dy = newPosition.y;
newPosition.x = (dx * cos - dy * sin) + center.x;
newPosition.y = (dx * sin + dy * cos) + center.y;
newPosition.x = dx * cosRot - dy * sinRot + center.x;
newPosition.y = dx * sinRot + dy * cosRot + center.y;
// Batch state updates to avoid intermediate renders
setPosition(newPosition);
setRotation(selectedRotation);
setScale(selectedScale);
}
},
[rotation, scale, screenCenter]
);
const value = useMemo(() => ({
const value = useMemo(
() => ({
position,
scale,
rotation,
@ -130,8 +173,19 @@ export const TransformProvider = ({ children }: { children: ReactNode }) => {
screenToLocal,
localToScreen,
setTransform,
setScreenCenter
}), [position, scale, rotation, screenCenter]);
setScreenCenter,
}),
[
position,
scale,
rotation,
screenCenter,
rotateToAngle,
screenToLocal,
localToScreen,
setTransform,
]
);
return (
<TransformContext.Provider value={value}>
@ -144,7 +198,7 @@ export const TransformProvider = ({ children }: { children: ReactNode }) => {
export const useTransform = () => {
const context = useContext(TransformContext);
if (!context) {
throw new Error('useTransform must be used within a TransformProvider');
throw new Error("useTransform must be used within a TransformProvider");
}
return context;
};

View File

@ -3,37 +3,32 @@ import { useCallback } from "react";
import { PATH_COLOR, PATH_WIDTH } from "./Constants";
import { coordinatesToLocal } from "./utils";
interface TravelPathProps {
points: {x: number, y: number}[];
points: { x: number; y: number }[];
}
export function TravelPath({
points
}: Readonly<TravelPathProps>) {
const draw = useCallback((g: Graphics) => {
export function TravelPath({ points }: Readonly<TravelPathProps>) {
const draw = useCallback(
(g: Graphics) => {
g.clear();
const coordStart = coordinatesToLocal(points[0].x, points[0].y);
g.moveTo(coordStart.x, coordStart.y);
for (let i = 1; i < points.length - 1; i++) {
for (let i = 1; i <= points.length - 1; i++) {
const coordinates = coordinatesToLocal(points[i].x, points[i].y);
g.lineTo(coordinates.x, coordinates.y);
}
g.stroke({
color: PATH_COLOR,
width: PATH_WIDTH
width: PATH_WIDTH,
});
}, [points]);
},
[points]
);
if(points.length === 0) {
if (points.length === 0) {
console.error("points is empty");
return null;
}
return (
<pixiGraphics
draw={draw}
/>
);
return <pixiGraphics draw={draw} />;
}

View File

@ -3,29 +3,41 @@ import { Stack, Typography } from "@mui/material";
export function Widgets() {
return (
<Stack
direction="column" spacing={2}
direction="column"
spacing={2}
position="absolute"
top={32} left={32}
sx={{ pointerEvents: 'none' }}
top={32}
left={32}
sx={{ pointerEvents: "none" }}
>
<Stack bgcolor="primary.main"
width={361} height={96}
p={2} m={2}
<Stack
bgcolor="primary.main"
width={361}
height={96}
p={2}
m={2}
borderRadius={2}
alignItems="center"
justifyContent="center"
>
<Typography variant="h6">Станция</Typography>
<Typography variant="h6" sx={{ color: "#fff" }}>
Станция
</Typography>
</Stack>
<Stack bgcolor="primary.main"
width={223} height={262}
p={2} m={2}
<Stack
bgcolor="primary.main"
width={223}
height={262}
p={2}
m={2}
borderRadius={2}
alignItems="center"
justifyContent="center"
>
<Typography variant="h6">Погода</Typography>
<Typography variant="h6" sx={{ color: "#fff" }}>
Погода
</Typography>
</Stack>
</Stack>
)
);
}

View File

@ -1,18 +1,14 @@
import { useRef, useEffect, useState } from "react";
import {
Application,
ApplicationRef,
extend
} from '@pixi/react';
import { Application, ApplicationRef, extend } from "@pixi/react";
import {
Container,
Graphics,
Sprite,
Texture,
TilingSprite,
Text
} from 'pixi.js';
Text,
} from "pixi.js";
import { Stack } from "@mui/material";
import { MapDataProvider, useMapData } from "./MapDataContext";
import { TransformProvider, useTransform } from "./TransformContext";
@ -25,6 +21,7 @@ import { LeftSidebar } from "./LeftSidebar";
import { RightSidebar } from "./RightSidebar";
import { Widgets } from "./Widgets";
import { coordinatesToLocal } from "./utils";
import { LanguageSwitch } from "@/components/LanguageSwitch";
extend({
Container,
@ -32,7 +29,7 @@ extend({
Sprite,
Texture,
TilingSprite,
Text
Text,
});
export const RoutePreview = () => {
@ -40,26 +37,34 @@ export const RoutePreview = () => {
<MapDataProvider>
<TransformProvider>
<Stack direction="row" height="100vh" width="100vw" overflow="hidden">
<div
style={{
position: "absolute",
top: 0,
left: "50%",
transform: "translateX(-50%)",
zIndex: 1000,
}}
>
<LanguageSwitch />
</div>
<LeftSidebar />
<Stack direction="row" flex={1} position="relative" height="100%">
<Widgets />
<RouteMap />
<RightSidebar />
</Stack>
</Stack>
</TransformProvider>
</MapDataProvider>
);
};
export function RouteMap() {
const { setPosition, screenToLocal, setTransform, screenCenter } = useTransform();
const {
routeData, stationData, sightData, originalRouteData
} = useMapData();
const [points, setPoints] = useState<{x: number, y: number}[]>([]);
const { setPosition, screenToLocal, setTransform, screenCenter } =
useTransform();
const { routeData, stationData, sightData, originalRouteData } = useMapData();
const [points, setPoints] = useState<{ x: number; y: number }[]>([]);
const [isSetup, setIsSetup] = useState(false);
const parentRef = useRef<HTMLDivElement>(null);
@ -67,24 +72,29 @@ export function RouteMap() {
useEffect(() => {
if (originalRouteData) {
const path = originalRouteData?.path;
const points = path?.map(([x, y]: [number, number]) => ({x: x * UP_SCALE, y: y * UP_SCALE})) ?? [];
const points =
path?.map(([x, y]: [number, number]) => ({
x: x * UP_SCALE,
y: y * UP_SCALE,
})) ?? [];
setPoints(points);
}
}, [originalRouteData]);
useEffect(() => {
if(isSetup || !screenCenter) {
if (isSetup || !screenCenter) {
return;
}
if (
originalRouteData?.center_latitude === originalRouteData?.center_longitude &&
originalRouteData?.center_latitude ===
originalRouteData?.center_longitude &&
originalRouteData?.center_latitude === 0
) {
if (points.length > 0) {
let boundingBox = {
from: {x: Infinity, y: Infinity},
to: {x: -Infinity, y: -Infinity}
from: { x: Infinity, y: Infinity },
to: { x: -Infinity, y: -Infinity },
};
for (const point of points) {
boundingBox.from.x = Math.min(boundingBox.from.x, point.x);
@ -94,7 +104,7 @@ export function RouteMap() {
}
const newCenter = {
x: -(boundingBox.from.x + boundingBox.to.x) / 2,
y: -(boundingBox.from.y + boundingBox.to.y) / 2
y: -(boundingBox.from.y + boundingBox.to.y) / 2,
};
setPosition(newCenter);
setIsSetup(true);
@ -103,7 +113,10 @@ export function RouteMap() {
originalRouteData?.center_latitude &&
originalRouteData?.center_longitude
) {
const coordinates = coordinatesToLocal(originalRouteData?.center_latitude, originalRouteData?.center_longitude);
const coordinates = coordinatesToLocal(
originalRouteData?.center_latitude,
originalRouteData?.center_longitude
);
setTransform(
coordinates.x,
@ -113,34 +126,36 @@ export function RouteMap() {
);
setIsSetup(true);
}
}, [points, originalRouteData?.center_latitude, originalRouteData?.center_longitude, originalRouteData?.rotate, isSetup, screenCenter]);
}, [
points,
originalRouteData?.center_latitude,
originalRouteData?.center_longitude,
originalRouteData?.rotate,
isSetup,
screenCenter,
]);
if (!routeData || !stationData || !sightData) {
console.error("routeData, stationData or sightData is null");
return <div>Loading...</div>;
}
return (
<div style={{width: "100%", height:"100%"}} ref={parentRef}>
<Application
resizeTo={parentRef}
background="#fff"
>
<div style={{ width: "100%", height: "100%" }} ref={parentRef}>
<Application resizeTo={parentRef} background="#fff">
<InfiniteCanvas>
<TravelPath points={points}/>
<TravelPath points={points} />
{stationData?.map((obj) => (
<Station station={obj} key={obj.id}/>
<Station station={obj} key={obj.id} />
))}
{sightData?.map((obj, index) => (
<Sight sight={obj} id={index} key={obj.id}/>
<Sight sight={obj} id={index} key={obj.id} />
))}
<pixiGraphics
draw={(g) => {
g.clear();
const localCenter = screenToLocal(0,0);
const localCenter = screenToLocal(0, 0);
g.circle(localCenter.x, localCenter.y, 10);
g.fill("#fff");
}}
@ -148,5 +163,5 @@ export function RouteMap() {
</InfiniteCanvas>
</Application>
</div>
)
);
}

View File

@ -393,18 +393,18 @@ export const RouteEdit = observer(() => {
parentResource="route"
childResource="station"
fields={stationFields}
title="станции"
title="остановки"
dragAllowed={true}
/>
<LinkedItems<VehicleItem>
{/* <LinkedItems<VehicleItem>
type="edit"
parentId={routeId}
parentResource="route"
childResource="vehicle"
fields={vehicleFields}
title="транспортные средства"
/>
/> */}
</>
)}

View File

@ -80,17 +80,17 @@ export const RouteShow = observer(() => {
parentResource="route"
childResource="station"
fields={stationFields}
title="станции"
title="остановки"
/>
<LinkedItems<VehicleItem>
{/* <LinkedItems<VehicleItem>
type="show"
parentId={record.id}
parentResource="route"
childResource="vehicle"
fields={vehicleFields}
title="транспортные средства"
/>
/> */}
<LinkedItems<SightItem>
type="show"
@ -103,8 +103,7 @@ export const RouteShow = observer(() => {
</>
)}
<Box sx={{ display: 'flex', justifyContent: 'flex-start' }}>
<Box sx={{ display: "flex", justifyContent: "flex-start" }}>
<Button
variant="contained"
color="primary"

View File

@ -4,6 +4,7 @@ import { TOKEN_KEY } from "@providers";
import axios from "axios";
import { languageStore } from "@stores";
export const axiosInstance = axios.create({
baseURL: import.meta.env.VITE_KRBL_API,
});
@ -22,6 +23,19 @@ axiosInstance.interceptors.request.use((config) => {
return config;
});
export const axiosInstanceForGet = axios.create({
baseURL: import.meta.env.VITE_KRBL_API,
});
axiosInstanceForGet.interceptors.request.use((config) => {
const token = localStorage.getItem(TOKEN_KEY);
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
config.headers["X-Language"] = languageStore.language;
return config;
});
const apiUrl = import.meta.env.VITE_KRBL_API;
export const customDataProvider = dataProvider(apiUrl, axiosInstance);