Compare commits

...

4 Commits

Author SHA1 Message Date
5440126898 fix: Fix bug with route preview
All checks were successful
release-tag / release-image (push) Successful in 2m28s
2025-05-28 11:31:37 +03:00
a6a5288262 fix: Fix for correct usage 2025-05-28 11:08:28 +03:00
b837aae711 feat: Add language switcher for preview route 2025-05-27 20:57:14 +03:00
ede6681c28 feat: Update css file 2025-05-27 03:43:46 +03:00
25 changed files with 1396 additions and 970 deletions

View File

@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<link rel="icon" type="image/png" href="/favicon-ship.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
@ -19,9 +19,7 @@
name="twitter:image"
content="https://refine.dev/img/refine_social.png"
/>
<title>
Белые ночи
</title>
<title>Белые ночи</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>

BIN
public/favicon-ship.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -70,6 +70,7 @@ type LinkedItemsProps<T> = {
disableCreation?: boolean;
updatedLinkedItems?: T[];
refresh?: number;
cityId?: number;
};
const reorder = (list: any[], startIndex: number, endIndex: number) => {
@ -131,6 +132,7 @@ export const LinkedItemsContents = <
disableCreation = false,
updatedLinkedItems,
refresh,
cityId,
}: LinkedItemsProps<T>) => {
const { language } = languageStore;
const { setArticleModalOpenAction, setArticleIdAction } = articleStore;
@ -216,7 +218,7 @@ export const LinkedItemsContents = <
useEffect(() => {
if (type === "edit") {
axiosInstance
.get(`${import.meta.env.VITE_KRBL_API}/${childResource}/`)
.get(`${import.meta.env.VITE_KRBL_API}/${childResource}/`, {})
.then((response) => {
setItems(response?.data || []);
setIsLoading(false);
@ -445,7 +447,7 @@ export const LinkedItemsContents = <
availableItems?.find((item) => item.id === selectedItemId) || null
}
onChange={(_, newValue) => setSelectedItemId(newValue?.id || null)}
options={availableItems}
options={availableItems.filter((item) => item.city_id == cityId)}
getOptionLabel={(item) => String(item[fields[0].data])}
renderInput={(params) => (
<TextField {...params} label={`Выберите ${title}`} fullWidth />
@ -456,6 +458,7 @@ export const LinkedItemsContents = <
.toLowerCase()
.split(" ")
.filter((word) => word.length > 0);
return options.filter((option) => {
const optionWords = String(option[fields[0].data])
.toLowerCase()

View File

@ -143,8 +143,17 @@ export const Header: React.FC<RefineThemedLayoutV2HeaderProps> = observer(
justifyContent="flex-end"
alignItems="center"
spacing={2}
color="white"
sx={{
"& .MuiSelect-select": {
color: "white",
},
}}
>
<FormControl
variant="standard"
sx={{ width: "min-content", color: "white" }}
>
<FormControl variant="standard" sx={{ width: "min-content" }}>
{city_id && cities && (
<Select
defaultValue={city_id}

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

@ -1,11 +1,16 @@
import {ProjectIcon} from './Icons'
import { Ship } from "lucide-react";
import { ProjectIcon } from "./Icons";
export default function SidebarTitle({ collapsed }: { collapsed: boolean }) {
return (
<div style={{display: 'flex', alignItems: 'center', whiteSpace: 'nowrap'}}>
<ProjectIcon style={{color: '#7f6b58'}} />
<div
style={{ display: "flex", alignItems: "center", whiteSpace: "nowrap" }}
>
<Ship size={40} style={{ color: "#7f6b58" }} />
{!collapsed && <span style={{marginLeft: 8, fontWeight: 'bold'}}>Белые ночи</span>}
{!collapsed && (
<span style={{ marginLeft: 8, fontWeight: "bold" }}>Белые ночи</span>
)}
</div>
)
);
}

View File

@ -14,12 +14,12 @@
cursor: pointer;
padding: 0;
margin: 0;
width: 35px;
height: 35px;
color: #544044;
width: 32px;
height: 32px;
color: rgba(79, 138, 95, 1);
border-radius: 10%;
transition: all 0.3s ease;
}
.backup-button:hover {
background-color: rgba(84, 64, 68, 0.5);
background-color: rgba(79, 138, 95, 0.05);
}

View File

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

View File

@ -1,11 +1,14 @@
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";
class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean }> {
class ErrorBoundary extends Component<
{ children: ReactNode },
{ hasError: boolean }
> {
state = { hasError: false };
static getDerivedStateFromError() {
@ -21,9 +24,19 @@ class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boole
}
}
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 +46,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]);
}, [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 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,28 +116,38 @@ 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;
@ -112,22 +157,30 @@ export function InfiniteCanvas({children} : Readonly<{children?: ReactNode}>) {
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 +188,6 @@ export function InfiniteCanvas({children} : Readonly<{children?: ReactNode}>) {
console.log(position, scale, rotation);
}, [position, scale, rotation]);
return (
<ErrorBoundary>
{applicationRef?.app && (
@ -146,7 +198,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 +218,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,13 +16,16 @@ 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;
originalStationData?: StationData[];
originalSightData?: SightData[];
routeData?: RouteData;
stationData?: StationData[];
stationData?: StationDataWithLanguage;
sightData?: SightData[];
isRouteLoading: boolean;
@ -57,9 +60,11 @@ const MapDataContext = createContext<{
saveChanges: () => {},
});
export function MapDataProvider({
children,
}: Readonly<{ children: ReactNode }>) {
type StationDataWithLanguage = {
[key: string]: StationData[];
};
export const MapDataProvider = observer(
({ children }: Readonly<{ children: ReactNode }>) => {
const { id: routeId } = useParams<{ id: string }>();
const apiUrl = useApiUrl();
@ -69,43 +74,75 @@ export function MapDataProvider({
const [originalSightData, setOriginalSightData] = useState<SightData[]>();
const [routeData, setRouteData] = useState<RouteData>();
const [stationData, setStationData] = useState<StationData[]>();
const [stationData, setStationData] = useState<StationDataWithLanguage>({
RU: [],
EN: [],
ZH: [],
});
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,
ruStationResponse,
enStationResponse,
zhStationResponse,
sightResponse,
] = await Promise.all([
axiosInstanceForGet(language).get(`/route/${routeId}`),
axiosInstanceForGet("ru").get(`/route/${routeId}/station`),
axiosInstanceForGet("en").get(`/route/${routeId}/station`),
axiosInstanceForGet("zh").get(`/route/${routeId}/station`),
axiosInstanceForGet(language).get(`/route/${routeId}/sight`),
]);
setOriginalRouteData(routeResponse.data as RouteData);
setOriginalStationData(ruStationResponse.data as StationData[]);
setStationData({
ru: ruStationResponse.data as StationData[],
en: enStationResponse.data as StationData[],
zh: zhStationResponse.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]);
useEffect(() => {
// combine changes with original data
if (originalRouteData)
setRouteData({ ...originalRouteData, ...routeChanges });
if (originalStationData) setStationData(originalStationData);
if (originalSightData) setSightData(originalSightData);
}, [
originalRouteData,
originalStationData,
originalSightData,
routeChanges,
stationChanges,
@ -169,7 +206,7 @@ export function MapDataProvider({
return station;
});
} else {
const foundStation = stationData?.find(
const foundStation = stationData.ru?.find(
(station) => station.id === stationId
);
if (foundStation) {
@ -228,12 +265,12 @@ export function MapDataProvider({
const value = useMemo(
() => ({
originalRouteData: originalRouteData,
originalStationData: originalStationData,
originalSightData: originalSightData,
routeData: routeData,
stationData: stationData,
sightData: sightData,
originalRouteData,
originalStationData,
originalSightData,
routeData,
stationData,
sightData,
isRouteLoading,
isStationLoading,
isSightLoading,
@ -258,9 +295,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,11 +5,28 @@ 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(() => {
@ -17,7 +34,10 @@ export function RightSidebar() {
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]);
@ -27,9 +47,10 @@ export function RightSidebar() {
}
}, [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);
@ -42,16 +63,15 @@ export function RightSidebar() {
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}) {
function pan({ x, y }: { x: number; y: number }) {
const coordinates = coordinatesToLocal(x, y);
setTransform(coordinates.x, coordinates.y);
}
@ -63,12 +83,18 @@ export function RightSidebar() {
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>
@ -81,14 +107,17 @@ export function RightSidebar() {
onChange={(e) => setMinScale(Number(e.target.value))}
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 }}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
color: "#fff"
}
"& .MuiInputLabel-root": {
color: "#fff",
},
"& .MuiInputBase-input": {
color: "#fff",
},
}}
slotProps={{
input: {
min: 0,
max: 360
}
max: 360,
},
}}
/>
@ -148,14 +183,17 @@ export function RightSidebar() {
variant="filled"
value={Math.round(localCenter.x * 100000) / 100000}
onChange={(e) => {
setLocalCenter(prev => ({...prev, x: Number(e.target.value)}))
setLocalCenter((prev) => ({ ...prev, x: Number(e.target.value) }));
pan({ x: Number(e.target.value), y: localCenter.y });
}}
style={{ backgroundColor: "#222", borderRadius: 4 }}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
color: "#fff"
}
"& .MuiInputLabel-root": {
color: "#fff",
},
"& .MuiInputBase-input": {
color: "#fff",
},
}}
/>
<TextField
@ -164,14 +202,17 @@ export function RightSidebar() {
variant="filled"
value={Math.round(localCenter.y * 100000) / 100000}
onChange={(e) => {
setLocalCenter(prev => ({...prev, 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 }}
sx={{
'& .MuiInputLabel-root.Mui-focused': {
color: "#fff"
}
"& .MuiInputLabel-root": {
color: "#fff",
},
"& .MuiInputBase-input": {
color: "#fff",
},
}}
/>
</Stack>

View File

@ -1,22 +1,37 @@
import { FederatedMouseEvent, Graphics } from "pixi.js";
import { BACKGROUND_COLOR, PATH_COLOR, STATION_RADIUS, STATION_OUTLINE_WIDTH, UP_SCALE } from "./Constants";
import {
BACKGROUND_COLOR,
PATH_COLOR,
STATION_RADIUS,
STATION_OUTLINE_WIDTH,
UP_SCALE,
} from "./Constants";
import { useTransform } from "./TransformContext";
import { useCallback, useEffect, useRef, useState } from "react";
import { StationData } from "./types";
import { useMapData } from "./MapDataContext";
import { coordinatesToLocal } from "./utils";
import { observer } from "mobx-react-lite";
import { languageStore } from "@stores";
interface StationProps {
station: StationData;
ruLabel: string | null;
}
export function Station({
station
}: Readonly<StationProps>) {
export const Station = observer(
({ station, ruLabel }: Readonly<StationProps>) => {
const draw = useCallback((g: Graphics) => {
g.clear();
const coordinates = coordinatesToLocal(station.latitude, station.longitude);
g.circle(coordinates.x * UP_SCALE, coordinates.y * UP_SCALE, STATION_RADIUS);
const coordinates = coordinatesToLocal(
station.latitude,
station.longitude
);
g.circle(
coordinates.x * UP_SCALE,
coordinates.y * UP_SCALE,
STATION_RADIUS
);
g.fill({ color: PATH_COLOR });
g.stroke({ color: BACKGROUND_COLOR, width: STATION_OUTLINE_WIDTH });
}, []);
@ -24,21 +39,28 @@ export function Station({
return (
<pixiContainer>
<pixiGraphics draw={draw} />
<StationLabel station={station}/>
<StationLabel station={station} ruLabel={ruLabel} />
</pixiContainer>
);
}
);
export function StationLabel({
station
}: Readonly<StationProps>) {
export const StationLabel = observer(
({ station, ruLabel }: Readonly<StationProps>) => {
const { language } = languageStore;
const { rotation, scale } = useTransform();
const { setStationOffset } = useMapData();
const [position, setPosition] = useState({ x: station.offset_x, y: station.offset_y });
const [position, setPosition] = useState({
x: station.offset_x,
y: station.offset_y,
});
const [isDragging, setIsDragging] = useState(false);
const [startPosition, setStartPosition] = useState({ x: 0, y: 0 });
const [startMousePosition, setStartMousePosition] = useState({ x: 0, y: 0 });
const [startMousePosition, setStartMousePosition] = useState({
x: 0,
y: 0,
});
if (!station) {
console.error("station is null");
@ -49,22 +71,22 @@ export function StationLabel({
setIsDragging(true);
setStartPosition({
x: position.x,
y: position.y
y: position.y,
});
setStartMousePosition({
x: e.globalX,
y: e.globalY
y: e.globalY,
});
e.stopPropagation();
};
const handlePointerMove = (e: FederatedMouseEvent) => {
if (!isDragging) return;
const dx = (e.globalX - startMousePosition.x);
const dy = (e.globalY - startMousePosition.y);
const dx = e.globalX - startMousePosition.x;
const dy = e.globalY - startMousePosition.y;
const newPosition = {
x: startPosition.x + dx,
y: startPosition.y + dy
y: startPosition.y + dy,
};
setPosition(newPosition);
setStationOffset(station.id, newPosition.x, newPosition.y);
@ -79,7 +101,7 @@ export function StationLabel({
return (
<pixiContainer
eventMode='static'
eventMode="static"
interactive
onPointerDown={handlePointerDown}
onGlobalPointerMove={handlePointerMove}
@ -96,14 +118,31 @@ export function StationLabel({
text={station.name}
position={{
x: position.x / scale,
y: position.y/scale
y: position.y / scale,
}}
style={{
fontSize: 48,
fontWeight: 'bold',
fill: "#ffffff"
fontSize: 26,
fontWeight: "bold",
fill: "#ffffff",
}}
/>
{ruLabel && (
<pixiText
anchor={{ x: 0.5, y: -1 }}
text={ruLabel}
position={{
x: position.x / scale,
y: position.y / scale,
}}
style={{
fontSize: 16,
fontWeight: "bold",
fill: "#CCCCCC",
}}
/>
)}
</pixiContainer>
);
}
);

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;
@ -71,54 +87,81 @@ export const TransformProvider = ({ children }: { children: ReactNode }) => {
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 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) {
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,9 @@ import { LeftSidebar } from "./LeftSidebar";
import { RightSidebar } from "./RightSidebar";
import { Widgets } from "./Widgets";
import { coordinatesToLocal } from "./utils";
import { LanguageSwitch } from "@/components/LanguageSwitch";
import { languageStore } from "@stores";
import { observer } from "mobx-react-lite";
extend({
Container,
@ -32,7 +31,7 @@ extend({
Sprite,
Texture,
TilingSprite,
Text
Text,
});
export const RoutePreview = () => {
@ -40,26 +39,36 @@ 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}[]>([]);
export const RouteMap = observer(() => {
const { language } = languageStore;
const { setPosition, screenToLocal, setTransform, screenCenter } =
useTransform();
const { routeData, stationData, sightData, originalRouteData } = useMapData();
console.log(stationData);
const [points, setPoints] = useState<{ x: number; y: number }[]>([]);
const [isSetup, setIsSetup] = useState(false);
const parentRef = useRef<HTMLDivElement>(null);
@ -67,7 +76,11 @@ 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]);
@ -78,13 +91,14 @@ export function RouteMap() {
}
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}
to: { x: -Infinity, y: -Infinity },
};
for (const point of points) {
boundingBox.from.x = Math.min(boundingBox.from.x, point.x);
@ -94,7 +108,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 +117,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,28 +130,31 @@ 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"
>
<Application resizeTo={parentRef} background="#fff">
<InfiniteCanvas>
<TravelPath points={points} />
{stationData?.map((obj) => (
<Station station={obj} key={obj.id}/>
))}
{sightData?.map((obj, index) => (
<Sight sight={obj} id={index} key={obj.id}/>
{stationData[language].map((obj, index) => (
<Station
station={obj}
key={obj.id}
ruLabel={language === "ru" ? null : stationData.ru[index].name}
/>
))}
<pixiGraphics
@ -148,5 +168,5 @@ export function RouteMap() {
</InfiniteCanvas>
</Application>
</div>
)
}
);
});

View File

@ -280,13 +280,19 @@ export const RouteCreate = () => {
<TextField
{...register("scale_min", {
// required: 'Это поле является обязательным',
setValueAs: (value) => Number(value),
setValueAs: (value) => {
if (Number(value) < 0) {
return 0;
}
return Number(value);
},
})}
error={!!(errors as any)?.scale_min}
helperText={(errors as any)?.scale_min?.message}
margin="normal"
fullWidth
slotProps={{ inputLabel: { shrink: true } }}
inputProps={{ min: 0 }}
type="number"
label={"Масштаб (мин)"}
name="scale_min"
@ -295,13 +301,19 @@ export const RouteCreate = () => {
<TextField
{...register("scale_max", {
// required: 'Это поле является обязательным',
setValueAs: (value) => Number(value),
setValueAs: (value) => {
if (Number(value) < 0) {
return 0;
}
return Number(value);
},
})}
error={!!(errors as any)?.scale_max}
helperText={(errors as any)?.scale_max?.message}
margin="normal"
fullWidth
slotProps={{ inputLabel: { shrink: true } }}
inputProps={{ min: 0 }}
type="number"
label={"Масштаб (макс)"}
name="scale_max"

View File

@ -9,7 +9,7 @@ import {
} from "@mui/material";
import { Edit, useAutocomplete } from "@refinedev/mui";
import { useForm } from "@refinedev/react-hook-form";
import { Controller } from "react-hook-form";
import { Controller, useWatch } from "react-hook-form";
import { useNavigate, useParams } from "react-router";
import { LinkedItems } from "../../components/LinkedItems";
import {
@ -76,6 +76,11 @@ export const RouteEdit = observer(() => {
...META_LANGUAGE(language),
});
const carrierId = useWatch({ control, name: "carrier_id" });
const cityId = carrierAutocompleteProps.options.find(
(option) => option.id === carrierId
)?.city_id;
const { autocompleteProps: governorAppealAutocompleteProps } =
useAutocomplete({
resource: "article",
@ -312,7 +317,12 @@ export const RouteEdit = observer(() => {
<TextField
{...register("scale_min", {
// required: 'Это поле является обязательным',
setValueAs: (value) => Number(value),
setValueAs: (value) => {
if (Number(value) < 0) {
return 0;
}
return Number(value);
},
})}
error={!!(errors as any)?.scale_min}
helperText={(errors as any)?.scale_min?.message}
@ -327,7 +337,12 @@ export const RouteEdit = observer(() => {
<TextField
{...register("scale_max", {
// required: 'Это поле является обязательным',
setValueAs: (value) => Number(value),
setValueAs: (value) => {
if (Number(value) < 0) {
return 0;
}
return Number(value);
},
})}
error={!!(errors as any)?.scale_max}
helperText={(errors as any)?.scale_max?.message}
@ -393,18 +408,19 @@ export const RouteEdit = observer(() => {
parentResource="route"
childResource="station"
fields={stationFields}
title="станции"
title="остановки"
dragAllowed={true}
cityId={cityId}
/>
<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

@ -433,7 +433,7 @@ export const SightCreate = observer(() => {
renderInput={(params) => (
<TextField
{...params}
label="Выберите водный знак (Левый верх)"
label="Выберите водяной знак (Левый верх)"
margin="normal"
variant="outlined"
error={!!errors.watermark_lu}
@ -475,7 +475,7 @@ export const SightCreate = observer(() => {
renderInput={(params) => (
<TextField
{...params}
label="Выберите водный знак (Правый верх)"
label="Выберите водяной знак (Правый верх)"
margin="normal"
variant="outlined"
error={!!errors.watermark_rd}

View File

@ -606,7 +606,7 @@ export const SightEdit = observer(() => {
renderInput={(params) => (
<TextField
{...params}
label="Выберите водный знак (Левый верх)"
label="Выберите водяной знак (Левый верх)"
margin="normal"
variant="outlined"
error={!!errors.arms}
@ -650,7 +650,7 @@ export const SightEdit = observer(() => {
renderInput={(params) => (
<TextField
{...params}
label="Выберите водный знак (Правый вверх)"
label="Выберите водяной знак (Правый вверх)"
margin="normal"
variant="outlined"
error={!!errors.arms}
@ -1479,7 +1479,7 @@ export const SightEdit = observer(() => {
renderInput={(params) => (
<TextField
{...params}
label="Выберите водный знак (Левый верх)"
label="Выберите водяной знак (Левый верх)"
margin="normal"
variant="outlined"
error={!!errors.arms}
@ -1523,7 +1523,7 @@ export const SightEdit = observer(() => {
renderInput={(params) => (
<TextField
{...params}
label="Выберите водный знак (Правый вверх)"
label="Выберите водяной знак (Правый вверх)"
margin="normal"
variant="outlined"
error={!!errors.arms}

View File

@ -192,6 +192,8 @@ export const StationEdit = observer(() => {
},
});
const cityId = watch("city_id");
return (
<Edit saveButtonProps={saveButtonProps}>
<Box
@ -353,6 +355,7 @@ export const StationEdit = observer(() => {
fields={sightFields}
title="достопримечательности"
dragAllowed={false}
cityId={cityId}
/>
)}
</Edit>

View File

@ -7,14 +7,41 @@ import {
ShowButton,
useDataGrid,
} from "@refinedev/mui";
import React, { useEffect } from "react";
import React, { useEffect, useState } from "react";
import { VEHICLE_TYPES } from "../../lib/constants";
import { localeText } from "../../locales/ru/localeText";
import { observer } from "mobx-react-lite";
import { languageStore } from "../../store/LanguageStore";
import { axiosInstance } from "@providers";
export const VehicleList = observer(() => {
const [carriers, setCarriers] = useState<any[]>([]);
const [cities, setCities] = useState<any[]>([]);
useEffect(() => {
axiosInstance
.get("/carrier")
.then((res) => {
setCarriers(res.data);
})
.catch((err) => {
console.log(err);
});
}, []);
useEffect(() => {
axiosInstance
.get("/city")
.then((res) => {
setCities(res.data);
})
.catch((err) => {
console.log(err);
});
}, []);
const { language } = languageStore;
const { dataGridProps } = useDataGrid({
@ -71,6 +98,36 @@ export const VehicleList = observer(() => {
);
},
},
{
field: "carrier-name",
headerName: "Перевозчик",
type: "string",
minWidth: 150,
display: "flex",
align: "left",
headerAlign: "left",
renderCell: (params) => {
const value = params.row.carrier_id;
return carriers.find((carrier) => carrier.id === value)?.full_name;
},
},
{
field: "city-name",
headerName: "Город",
type: "string",
minWidth: 150,
display: "flex",
align: "left",
headerAlign: "left",
renderCell: (params) => {
const value = params.row.carrier_id;
return cities.find(
(city) =>
city.id ===
carriers.find((carrier) => carrier.id === value)?.city_id
)?.name;
},
},
// {
// field: "city",
// headerName: "Город",
@ -93,7 +150,7 @@ export const VehicleList = observer(() => {
return (
<>
<EditButton hideText recordItemId={row.id} />
<ShowButton hideText recordItemId={row.id} />
{/* <ShowButton hideText recordItemId={row.id} /> */}
<DeleteButton
hideText
confirmTitle="Вы уверены?"
@ -104,7 +161,7 @@ export const VehicleList = observer(() => {
},
},
],
[]
[carriers, cities]
);
return (

View File

@ -3,7 +3,7 @@ import dataProvider from "@refinedev/simple-rest";
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 +22,22 @@ axiosInstance.interceptors.request.use((config) => {
return config;
});
export const axiosInstanceForGet = (language: string) => {
const axiosInstance = axios.create({
baseURL: import.meta.env.VITE_KRBL_API,
});
axiosInstance.interceptors.request.use((config) => {
const token = localStorage.getItem(TOKEN_KEY);
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
config.headers["X-Language"] = language;
return config;
});
return axiosInstance;
};
const apiUrl = import.meta.env.VITE_KRBL_API;
export const customDataProvider = dataProvider(apiUrl, axiosInstance);