nestjs rewrite

This commit is contained in:
popovspiridon99
2025-08-01 11:08:33 +09:00
parent 1f9a3a8e03
commit 145827ab6d
28 changed files with 1220 additions and 623 deletions

View File

@ -1,5 +1,4 @@
import { useEffect, useRef, useState } from 'react'
import { jsPDF } from "jspdf"
import 'ol/ol.css'
import { Modify } from 'ol/interaction'
import { ImageStatic, Vector as VectorSource } from 'ol/source'
@ -8,20 +7,20 @@ import { IRectCoords, SatelliteMapsProvider } from '../../interfaces/map'
import { Extent, getCenter } from 'ol/extent'
import { highlightStyleRed, highlightStyleYellow } from './MapStyles'
import { customMapSource, googleMapsSatelliteSource, yandexMapsSatelliteSource } from './MapSources'
import { Geometry, LineString, SimpleGeometry } from 'ol/geom'
import { Geometry, SimpleGeometry } from 'ol/geom'
import { fromExtent } from 'ol/geom/Polygon'
import { Coordinate } from 'ol/coordinate'
import { addInteractions, handleImageDrop, loadFeatures, processFigure, processLine } from './mapUtils'
import useSWR, { SWRConfiguration } from 'swr'
import { fetcher } from '../../http/axiosInstance'
import { BASE_URL } from '../../constants'
import { ActionIcon, Autocomplete, CloseButton, Flex, Select as MantineSelect, MantineStyleProp, rem, useMantineColorScheme, Portal, Menu, Button, Group, Divider, LoadingOverlay, Stack, Container, Modal, Transition, Text, Select, Switch, Checkbox, Radio, ScrollAreaAutosize } from '@mantine/core'
import { IconArrowsMaximize, IconArrowsMinimize, IconBoxMultiple, IconBoxPadding, IconChevronCompactLeft, IconChevronDown, IconChevronLeft, IconChevronsDown, IconHelp, IconPlus, IconSearch, IconUpload, IconWindowMaximize, IconWindowMinimize } from '@tabler/icons-react'
import { ActionIcon, Autocomplete, CloseButton, Flex, Select as MantineSelect, MantineStyleProp, rem, useMantineColorScheme, Portal, Menu, Button, Group, Divider, LoadingOverlay, Stack, Container, Transition, } from '@mantine/core'
import { IconBoxMultiple, IconBoxPadding, IconChevronDown, IconChevronLeft, IconPlus, IconSearch, IconUpload, } from '@tabler/icons-react'
import { ICitySettings, IFigure, ILine } from '../../interfaces/gis'
import axios from 'axios'
import MapToolbar from './MapToolbar/MapToolbar'
import MapStatusbar from './MapStatusbar/MapStatusbar'
import { setAlignMode, setSatMapsProvider, setTypeRoles, useMapStore, setMapLabel, clearPrintArea, setPreviousView, setMode, setPrintScale, PrintScale, setPrintScaleLine } from '../../store/map'
import { setAlignMode, setSatMapsProvider, setTypeRoles, useMapStore, setMapLabel, } from '../../store/map'
import { useThrottle } from '@uidotdev/usehooks'
import ObjectTree from '../Tree/ObjectTree'
import { setCurrentObjectId, setSelectedDistrict, setSelectedRegion, setSelectedYear, useObjectsStore } from '../../store/objects'
@ -33,11 +32,8 @@ import GeoJSON from 'ol/format/GeoJSON'
import MapLegend from './MapLegend/MapLegend'
import GisService from '../../services/GisService'
import MapMode from './MapMode'
import ScaleLine from 'ol/control/ScaleLine'
import { getPointResolution } from 'ol/proj'
import { PrintFormat, PrintOrientation, printResolutions, setPrintOrientation, setPrintResolution, usePrintStore } from '../../store/print'
import { printDimensions, satMapsProviders, scaleOptions, schemas } from '../../constants/map'
import { modals } from "@mantine/modals";
import { satMapsProviders, schemas } from '../../constants/map'
import MapPrint from './MapPrint/MapPrint'
const swrOptions: SWRConfiguration = {
revalidateOnFocus: false
@ -69,17 +65,23 @@ const MapComponent = ({
mode, map, currentTool, alignMode, satMapsProvider,
selectedObjectType, file, measureDraw,
polygonExtent, rectCoords, draw, snap, translate,
nodeLayerSource, drawingLayerSource,
drawingLayerSource,
satLayer, staticMapLayer, figuresLayer, linesLayer,
regionsLayer, districtBoundLayer, baseLayer,
previousView, printArea, printSource, printAreaDraw, printScale, printScaleLine,
printAreaDraw,
} = useMapStore().id[id]
const { printOrientation, printResolution, printFormat } = usePrintStore()
// Tab settings
const objectsPane: ITabsPane[] = [{ title: 'Объекты', value: 'objects', view: <ObjectTree map_id={id} /> }, { title: 'Неразмещенные', value: 'unplaced', view: <></> }, { title: 'Другие', value: 'other', view: <></> },]
const paramsPane: ITabsPane[] = [{ title: 'История изменений', value: 'history', view: <></> }, { title: 'Параметры', value: 'parameters', view: <ObjectParameters map_id={id} /> }, { title: 'Вычисляемые', value: 'calculated', view: <></> }]
const objectsPane: ITabsPane[] = [
{ title: 'Объекты', value: 'objects', view: <ObjectTree map_id={id} /> },
{ title: 'Неразмещенные', value: 'unplaced', view: <></> },
{ title: 'Другие', value: 'other', view: <></> },
]
const paramsPane: ITabsPane[] = [
{ title: 'История изменений', value: 'history', view: <></> },
{ title: 'Параметры', value: 'parameters', view: <ObjectParameters map_id={id} /> },
{ title: 'Вычисляемые', value: 'calculated', view: <></> }
]
// Map
const mapElement = useRef<HTMLDivElement | null>(null)
@ -124,7 +126,6 @@ const MapComponent = ({
// map.current?.setView(new View({
// extent: bounds.getExtent()
// }))
console.log(bounds.getFeatures().length)
})
}
}, [selectedDistrict, selectedYear])
@ -183,26 +184,26 @@ const MapComponent = ({
backdropFilter: 'blur(8px)',
}
const { data: nodes } = useSWR('/nodes/all', () => fetcher('/nodes/all', BASE_URL.ems), { revalidateOnFocus: false })
// const { data: nodes } = useSWR('/nodes/all', () => fetcher('/nodes/all', BASE_URL.ems), { revalidateOnFocus: false })
useEffect(() => {
// Draw features based on database data
if (Array.isArray(nodes)) {
nodes.map(node => {
if (node.shape_type === 'LINE') {
const coordinates: Coordinate[] = []
if (Array.isArray(node.shape)) {
node.shape.map((point: { x: number, y: number }) => {
const coordinate = [point.x as number, point.y as number] as Coordinate
coordinates.push(coordinate)
})
}
//console.log(coordinates)
nodeLayerSource.addFeature(new Feature({ geometry: new LineString(coordinates) }))
}
})
}
}, [nodes, nodeLayerSource])
// useEffect(() => {
// // Draw features based on database data
// if (Array.isArray(nodes)) {
// nodes.map(node => {
// if (node.shape_type === 'LINE') {
// const coordinates: Coordinate[] = []
// if (Array.isArray(node.shape)) {
// node.shape.map((point: { x: number, y: number }) => {
// const coordinate = [point.x as number, point.y as number] as Coordinate
// coordinates.push(coordinate)
// })
// }
// //console.log(coordinates)
// nodeLayerSource.addFeature(new Feature({ geometry: new LineString(coordinates) }))
// }
// })
// }
// }, [nodes, nodeLayerSource])
const [searchObject, setSearchObject] = useState<string | undefined>("")
const throttledSearchObject = useThrottle(searchObject, 500)
@ -271,11 +272,15 @@ const MapComponent = ({
}
}, [currentObjectId])
const { data: regionsData } = useSWR(`/general/regions/all`, (url) => fetcher(url, BASE_URL.ems), swrOptions)
const { data: regionsData } = useSWR(`/general/regions`, (url) => fetcher(url, BASE_URL.ems), swrOptions)
const { data: districtsData } = useSWR(selectedRegion ? `/general/districts/all?region_id=${selectedRegion}` : null, (url) => fetcher(url, BASE_URL.ems), swrOptions)
const { data: districtsData } = useSWR(selectedRegion ? `/general/districts/?region_id=${selectedRegion}` : null, (url) => fetcher(url, BASE_URL.ems), swrOptions)
const { data: searchData } = useSWR(throttledSearchObject !== "" && selectedDistrict && selectedYear ? `/general/search/objects?q=${throttledSearchObject}&id_city=${selectedDistrict}&year=${selectedYear}` : null, (url) => fetcher(url, BASE_URL.ems), swrOptions)
const { data: searchData } = useSWR(
throttledSearchObject !== "" && selectedDistrict && selectedYear ? `/general/search/objects?q=${throttledSearchObject}&id_city=${selectedDistrict}&year=${selectedYear}` : null,
(url) => fetcher(url, BASE_URL.ems),
swrOptions
)
const { data: figuresData, isValidating: figuresValidating } = useSWR(
selectedDistrict && selectedYear ? `/gis/figures/all?city_id=${selectedDistrict}&year=${selectedYear}&offset=0&limit=${10000}` : null,
@ -385,7 +390,7 @@ const MapComponent = ({
if (selectedDistrict && districtData) {
const settings = getCitySettings()
const imageUrl = `${import.meta.env.VITE_API_EMS_URL}/static/${selectedDistrict}`
const imageUrl = `${import.meta.env.VITE_API_EMS_URL}/tiles/static/${selectedDistrict}`
const img = new Image()
img.src = imageUrl
img.onload = () => {
@ -420,6 +425,8 @@ const MapComponent = ({
}
}, [selectedDistrict, districtData, staticMapLayer])
// Light/dark theme
useEffect(() => {
if (baseLayer) {
baseLayer.on('prerender', function (e) {
@ -446,12 +453,6 @@ const MapComponent = ({
}
}, [colorScheme])
const scaleLine = useRef(new ScaleLine({
bar: true,
text: true,
minWidth: 125
}))
useEffect(() => {
if (map) {
if (mode === 'print') {
@ -462,197 +463,9 @@ const MapComponent = ({
}
}, [mode, map, printAreaDraw])
useEffect(() => {
if (printArea) {
// backup view before entering print mode
setPreviousView(id, map?.getView())
map?.setTarget('print-portal')
printSource.clear()
map?.getView().setCenter(getCenter(printArea))
map?.getView().fit(printArea, {
size: printOrientation === 'horizontal' ? [594, 420] : [420, 594]
})
map?.removeInteraction(printAreaDraw)
}
}, [printArea, map])
const exportToPDF = (format: PrintFormat, resolution: number, orientation: PrintOrientation) => {
const dim = printDimensions[format]
const width = Math.round((dim[orientation === 'horizontal' ? 0 : 1] * resolution) / 25.4)
const height = Math.round((dim[orientation === 'horizontal' ? 1 : 0] * resolution) / 25.4)
if (!map) return
// Store original size and scale
const originalSize = map.getSize()
const originalResolution = map.getView().getResolution()
if (!originalSize || !originalResolution) return
// Calculate new resolution to fit high DPI
const scaleFactor = width / originalSize[0]
const newResolution = originalResolution / scaleFactor
// console.log(`New resolution: ${newResolution}`)
const center = map.getView().getCenter()
let scaleResolution
if (center) {
scaleResolution = Number(printScale) / getPointResolution(map.getView().getProjection(), Number(resolution) / 25.4, center)
// console.log(`Scaled resolution: ${scaleResolution}`)
}
console.log(width, height)
// Set new high-resolution rendering
map.setSize([width, height])
map.getView().setResolution(newResolution)
map.renderSync()
map.once("rendercomplete", function () {
const mapCanvas = document.createElement("canvas")
mapCanvas.width = width
mapCanvas.height = height
const mapContext = mapCanvas.getContext("2d")
if (!mapContext) return
const canvas = document.querySelector('canvas')
if (canvas) {
if (canvas.width > 0) {
const opacity = canvas.parentElement?.style.opacity || "1"
mapContext.globalAlpha = parseFloat(opacity)
const transform = canvas.style.transform
const matrixMatch = transform.match(/^matrix\(([^)]+)\)$/)
if (matrixMatch) {
const matrix = matrixMatch[1].split(",").map(Number)
mapContext.setTransform(...matrix as [number, number, number, number, number, number])
}
mapContext.drawImage(canvas, 0, 0)
}
}
mapContext.globalAlpha = 1
mapContext.setTransform(1, 0, 0, 1, 0, 0)
// Restore original map settings
map.setSize(originalSize)
map.getView().setResolution(originalResolution)
map.renderSync()
// Generate PDF
const pdf = new jsPDF(orientation === 'horizontal' ? "landscape" : 'portrait', undefined, format)
pdf.addImage(mapCanvas.toDataURL("image/jpeg"), "JPEG", 0, 0, orientation === 'horizontal' ? dim[0] : dim[1], orientation === 'horizontal' ? dim[1] : dim[0])
const filename = `${selectedYear}-${selectedRegion}-${selectedDistrict}-${new Date().toISOString()}.pdf`
pdf.save(filename, {
returnPromise: true
}).then(() => {
})
})
}
useEffect(() => {
if (printScaleLine) {
map?.addControl(scaleLine.current)
} else {
map?.removeControl(scaleLine.current)
}
}, [printScaleLine])
const [fullscreen, setFullscreen] = useState(false)
return (
<>
<Modal.Root scrollAreaComponent={ScrollAreaAutosize} keepMounted size='auto' opened={!!printArea} onClose={() => {
clearPrintArea(id)
map?.setTarget(mapElement.current as HTMLDivElement)
map?.addInteraction(printAreaDraw)
}} fullScreen={fullscreen}>
<Modal.Overlay />
<Modal.Content style={{ transition: 'all .3s ease' }}>
<Modal.Header>
<Modal.Title>
Предпросмотр области печати
</Modal.Title>
<Flex ml='auto' gap='md'>
<ActionIcon title='Помощь' ml='auto' variant='transparent'>
<IconHelp color='gray' />
</ActionIcon>
<ActionIcon title={fullscreen ? 'Свернуть' : 'Развернуть'} variant='transparent' onClick={() => setFullscreen(!fullscreen)}>
{fullscreen ? <IconWindowMinimize color='gray' /> : <IconWindowMaximize color='gray' />}
</ActionIcon>
<Modal.CloseButton title='Закрыть' />
</Flex>
</Modal.Header>
<Modal.Body>
<Stack align='center'>
<Text w='100%'>Область печати можно передвигать.</Text>
<div id='print-portal' style={{
width: printOrientation === 'horizontal' ? '594px' : '420px',
height: printOrientation === 'horizontal' ? '420px' : '594px'
}}>
</div>
<Flex w='100%' wrap='wrap' gap='lg' justify='space-between'>
<Radio.Group
label='Ориентация'
value={printOrientation}
onChange={(value) => setPrintOrientation(value as PrintOrientation)}
>
<Stack>
<Radio value='horizontal' label='Горизонтальная' />
<Radio value='vertical' label='Вертикальная' />
</Stack>
</Radio.Group>
<Select
allowDeselect={false}
label="Разрешение"
placeholder="Выберите разрешение"
data={printResolutions}
value={printResolution.toString()}
onChange={(value) => setPrintResolution(Number(value))}
/>
<Select
allowDeselect={false}
label="Масштаб"
placeholder="Выберите масштаб"
data={scaleOptions}
value={printScale}
onChange={(value) => setPrintScale(id, value as PrintScale)}
/>
<Checkbox
checked={printScaleLine}
label="Масштабная линия"
onChange={(event) => setPrintScaleLine(id, event.currentTarget.checked)}
/>
</Flex>
<Flex w='100%' gap='sm' align='center'>
<Button ml='auto' onClick={() => {
if (previousView) {
exportToPDF(printFormat, printResolution, printOrientation)
}
}}>
Печать
</Button>
</Flex>
</Stack>
</Modal.Body>
</Modal.Content>
</Modal.Root>
<MapPrint id={id} mapElement={mapElement} />
{active &&
<Portal target='#header-portal'>

View File

@ -1,7 +1,9 @@
import { Accordion, ColorSwatch, Flex, MantineStyleProp, ScrollAreaAutosize, Stack, Text, useMantineColorScheme } from '@mantine/core'
import useSWR from 'swr';
import { fetcher } from '../../../http/axiosInstance';
import { BASE_URL } from '../../../constants';
import { Accordion, ActionIcon, Collapse, ColorSwatch, Flex, MantineStyleProp, ScrollAreaAutosize, Stack, Text, useMantineColorScheme } from '@mantine/core'
import useSWR from 'swr'
import { fetcher } from '../../../http/axiosInstance'
import { BASE_URL } from '../../../constants'
import { useDisclosure } from '@mantine/hooks'
import { IconChevronDown } from '@tabler/icons-react'
const MapLegend = ({
selectedDistrict,
@ -12,7 +14,7 @@ const MapLegend = ({
selectedYear: number | null,
style: MantineStyleProp
}) => {
const { colorScheme } = useMantineColorScheme();
const { colorScheme } = useMantineColorScheme()
const { data: existingObjectsList } = useSWR(
selectedYear && selectedDistrict ? `/general/objects/list?year=${selectedYear}&city_id=${selectedDistrict}&planning=0` : null,
@ -30,28 +32,38 @@ const MapLegend = ({
}
)
const [opened, { toggle }] = useDisclosure(false)
return (
<ScrollAreaAutosize offsetScrollbars maw='300px' w='100%' fz='xs' mt='auto' style={{...style, zIndex: 1, backdropFilter: 'blur(8px)', backgroundColor: colorScheme === 'light' ? '#FFFFFFAA' : '#000000AA', borderRadius: '4px' }}>
<ScrollAreaAutosize maw='300px' w='100%' fz='xs' mt='auto' style={{ ...style, zIndex: 1, backdropFilter: 'blur(8px)', backgroundColor: colorScheme === 'light' ? '#FFFFFFAA' : '#000000AA', borderRadius: '4px' }}>
<Stack gap='sm' p='sm'>
<Text fz='xs'>
Легенда
</Text>
<Flex align='center'>
<Text fz='xs'>
Легенда
</Text>
<Accordion defaultValue={['existing', 'planning']} multiple>
<Accordion.Item value='existing' key='existing'>
<Accordion.Control>Существующие</Accordion.Control>
<Accordion.Panel>
{existingObjectsList && <LegendGroup objectsList={existingObjectsList} border='solid' />}
</Accordion.Panel>
</Accordion.Item>
<ActionIcon ml='auto' variant='subtle' onClick={toggle} >
<IconChevronDown style={{ transform: opened ? 'rotate(0deg)' : 'rotate(180deg)' }} />
</ActionIcon>
</Flex>
<Accordion.Item value='planning' key='planning'>
<Accordion.Control>Планируемые</Accordion.Control>
<Accordion.Panel>
{planningObjectsList && <LegendGroup objectsList={planningObjectsList} border='dotted' />}
</Accordion.Panel>
</Accordion.Item>
</Accordion>
<Collapse in={opened}>
<Accordion defaultValue={['existing', 'planning']} multiple>
<Accordion.Item value='existing' key='existing'>
<Accordion.Control>Существующие</Accordion.Control>
<Accordion.Panel>
{existingObjectsList && <LegendGroup objectsList={existingObjectsList} border='solid' />}
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value='planning' key='planning'>
<Accordion.Control>Планируемые</Accordion.Control>
<Accordion.Panel>
{planningObjectsList && <LegendGroup objectsList={planningObjectsList} border='dotted' />}
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Collapse>
</Stack>
</ScrollAreaAutosize>
)

View File

@ -0,0 +1,125 @@
import { useEffect, useRef } from 'react'
import 'ol/ol.css'
import { Container, Stack, Tabs } from '@mantine/core'
import OlMap from 'ol/Map'
import { v4 as uuidv4 } from 'uuid'
import TileLayer from 'ol/layer/Tile'
import { OSM } from 'ol/source'
import View from 'ol/View'
import { transform } from 'ol/proj'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import Feature from 'ol/Feature'
import { LineString } from 'ol/geom'
import { Stroke, Style, Text } from 'ol/style'
const center = [14443331.466543002, 8878970.176309839]
const style = new Style({
stroke: new Stroke({ color: 'blue', width: 2 }),
text: new Text({
font: 'bold 14px',
placement: 'line',
offsetY: -14
}),
})
const MapLineTest = () => {
const lines = [
{ name: 'A', points: [[100, 100], [200, 200]] },
{ name: 'B', points: [[200, 200], [300, 200]] },
{ name: 'X', points: [[200, 200], [300, 300]] },
{ name: 'L', points: [[300, 300], [350, 300]] },
{ name: 'N', points: [[300, 300], [250, 300]] },
{ name: 'I', points: [[300, 200], [300, 100]] },
{ name: 'J', points: [[300, 100], [250, 50]] },
{ name: 'C', points: [[300, 200], [400, 150]] },
{ name: 'D', points: [[400, 150], [400, 100]] },
]
const map = useRef<OlMap | null>(null)
const vectorLayer = useRef(new VectorLayer({
source: new VectorSource(),
style: feature => {
style.getText()?.setText(feature.get('label'))
return style
}
}))
const mapElement = useRef<HTMLDivElement | null>(null)
useEffect(() => {
map.current = new OlMap({
controls: [],
layers: [
new TileLayer({ source: new OSM(), properties: { id: uuidv4(), name: 'OpenStreetMap' } }),
vectorLayer.current
]
})
map.current.setTarget(mapElement.current as HTMLDivElement)
map.current.setView(new View({
center: transform([129.7466541, 62.083504], 'EPSG:4326', 'EPSG:3857'),
zoom: 16,
maxZoom: 21,
}))
}, [])
useEffect(() => {
if (map.current) {
const graph = new Map<string, { node: string, distance: number }[]>()
// build graph adjacency list
lines.forEach(({ points }) => {
const [start, end] = points.map(pt => pt.join(','))
const distance = Math.hypot(points[1][0] - points[0][0], points[1][1] - points[0][1])
if (!graph.has(start)) graph.set(start, [])
if (!graph.has(end)) graph.set(end, [])
graph.get(start)?.push({ node: end, distance })
graph.get(end)?.push({ node: start, distance })
})
// perform DFS to calculate distances from "A"
const startNode = lines[0].points[0].join(',')
const distances = new Map<string, number>()
const dfs = (node: string, currentDist: number) => {
if (distances.has(node) && distances.get(node)! <= currentDist) return
distances.set(node, currentDist)
for (const { node: neighbor, distance } of graph.get(node) || []) {
dfs(neighbor, currentDist + distance)
}
}
dfs(startNode, 0)
// render features
lines.forEach(({ name, points }) => {
const lineCoords = points.map(point => [point[0] + center[0], point[1] + center[1]])
const feature = new Feature(new LineString(lineCoords))
const lastNode = points[1].join(',')
const label = `${name} ${feature.getGeometry()?.getLength().toFixed(2)} (${distances.get(lastNode)?.toFixed(1) ?? '∞'})`
feature.set('label', label)
vectorLayer.current.getSource()?.addFeature(feature)
})
}
}, [])
return (
<Container fluid w='100%' pos='relative' p={0}>
<Tabs h='100%' variant='default' value={'map'} keepMounted={true}>
<Stack gap={0} h='100%'>
<Tabs.List>
<Tabs.Tab value={'map'}>Map</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value={'map'} h='100%' pos='relative'>
<Container pos='absolute' fluid p={0} w='100%' h='100%' ref={mapElement}></Container>
</Tabs.Panel>
</Stack>
</Tabs>
</Container>
)
}
export default MapLineTest

View File

@ -0,0 +1,234 @@
import { ActionIcon, Button, Checkbox, Flex, Modal, Radio, ScrollAreaAutosize, Select, Stack, Text } from '@mantine/core'
import { IconHelp, IconWindowMaximize, IconWindowMinimize } from '@tabler/icons-react'
import React, { useEffect, useRef, useState } from 'react'
import { clearPrintArea, PrintScale, setPreviousView, setPrintScale, setPrintScaleLine, useMapStore } from '../../../store/map'
import { PrintFormat, PrintOrientation, printResolutions, setPrintOrientation, setPrintResolution, usePrintStore } from '../../../store/print'
import { printDimensions, scaleOptions } from '../../../constants/map'
import { useObjectsStore } from '../../../store/objects'
// import { getPointResolution } from 'ol/proj'
import jsPDF from 'jspdf'
import { getCenter } from 'ol/extent'
import ScaleLine from 'ol/control/ScaleLine'
const MapPrint = ({
id,
mapElement
}: {
id: string
mapElement: React.MutableRefObject<HTMLDivElement | null>
}) => {
const [fullscreen, setFullscreen] = useState(false)
const { printOrientation, printResolution, printFormat } = usePrintStore()
const { selectedYear, selectedRegion, selectedDistrict } = useObjectsStore().id[id]
const {
map,
previousView, printArea, printSource, printAreaDraw, printScale, printScaleLine,
} = useMapStore().id[id]
const exportToPDF = (format: PrintFormat, resolution: number, orientation: PrintOrientation) => {
const dim = printDimensions[format]
const width = Math.round((dim[orientation === 'horizontal' ? 0 : 1] * resolution) / 25.4)
const height = Math.round((dim[orientation === 'horizontal' ? 1 : 0] * resolution) / 25.4)
if (!map) return
// Store original size and scale
const originalSize = map.getSize()
const originalResolution = map.getView().getResolution()
if (!originalSize || !originalResolution) return
// Calculate new resolution to fit high DPI
const scaleFactor = width / originalSize[0]
const newResolution = originalResolution / scaleFactor
// console.log(`New resolution: ${newResolution}`)
// const center = map.getView().getCenter()
// let scaleResolution = 1
// if (center) {
// scaleResolution = Number(printScale) / getPointResolution(map.getView().getProjection(), Number(resolution) / 25.4, center)
// // console.log(`Scaled resolution: ${scaleResolution}`)
// }
console.log(width, height)
// Set new high-resolution rendering
map.setSize([width, height])
map.getView().setResolution(newResolution)
map.renderSync()
map.once("rendercomplete", function () {
const mapCanvas = document.createElement("canvas")
mapCanvas.width = width
mapCanvas.height = height
const mapContext = mapCanvas.getContext("2d")
if (!mapContext) return
const canvas = document.querySelector('canvas')
if (canvas) {
if (canvas.width > 0) {
const opacity = canvas.parentElement?.style.opacity || "1"
mapContext.globalAlpha = parseFloat(opacity)
const transform = canvas.style.transform
const matrixMatch = transform.match(/^matrix\(([^)]+)\)$/)
if (matrixMatch) {
const matrix = matrixMatch[1].split(",").map(Number)
mapContext.setTransform(...matrix as [number, number, number, number, number, number])
}
mapContext.drawImage(canvas, 0, 0)
}
}
mapContext.globalAlpha = 1
mapContext.setTransform(1, 0, 0, 1, 0, 0)
// Restore original map settings
map.setSize(originalSize)
map.getView().setResolution(originalResolution)
map.renderSync()
const dimensions = {
w: orientation === 'horizontal' ? dim[0] : dim[1],
h: orientation === 'horizontal' ? dim[1] : dim[0]
}
// Generate PDF
const pdf = new jsPDF(orientation === 'horizontal' ? "landscape" : 'portrait', undefined, format)
pdf.addImage(mapCanvas.toDataURL("image/jpeg"), "JPEG", 0, 0, dimensions.w, dimensions.h)
const filename = `${selectedYear}-${selectedRegion}-${selectedDistrict}-${new Date().toISOString()}.pdf`
pdf.save(filename, {
returnPromise: true
}).then(() => {
})
})
}
const scaleLine = useRef(new ScaleLine({
bar: true,
text: true,
minWidth: 125
}))
useEffect(() => {
if (printArea) {
// backup view before entering print mode
setPreviousView(id, map?.getView())
map?.setTarget('print-portal')
printSource.clear()
map?.getView().setCenter(getCenter(printArea))
map?.getView().fit(printArea, {
size: printOrientation === 'horizontal' ? [594, 420] : [420, 594]
})
map?.removeInteraction(printAreaDraw)
}
}, [printArea, map])
useEffect(() => {
if (printScaleLine && printArea) {
map?.addControl(scaleLine.current)
} else {
map?.removeControl(scaleLine.current)
}
}, [printScaleLine, printArea])
return (
<Modal.Root
scrollAreaComponent={ScrollAreaAutosize}
keepMounted size='auto'
opened={!!printArea}
onClose={() => {
clearPrintArea(id)
map?.setTarget(mapElement.current as HTMLDivElement)
map?.addInteraction(printAreaDraw)
}} fullScreen={fullscreen}>
<Modal.Overlay />
<Modal.Content style={{ transition: 'all .3s ease' }}>
<Modal.Header>
<Modal.Title>
Предпросмотр области печати
</Modal.Title>
<Flex ml='auto' gap='md'>
<ActionIcon title='Помощь' ml='auto' variant='transparent'>
<IconHelp color='gray' />
</ActionIcon>
<ActionIcon title={fullscreen ? 'Свернуть' : 'Развернуть'} variant='transparent' onClick={() => setFullscreen(!fullscreen)}>
{fullscreen ? <IconWindowMinimize color='gray' /> : <IconWindowMaximize color='gray' />}
</ActionIcon>
<Modal.CloseButton title='Закрыть' />
</Flex>
</Modal.Header>
<Modal.Body>
<Stack align='center'>
<Text w='100%'>Область печати можно передвигать.</Text>
<div id='print-portal' style={{
width: printOrientation === 'horizontal' ? '594px' : '420px',
height: printOrientation === 'horizontal' ? '420px' : '594px'
}}>
</div>
<Flex w='100%' wrap='wrap' gap='lg' justify='space-between'>
<Radio.Group
label='Ориентация'
value={printOrientation}
onChange={(value) => setPrintOrientation(value as PrintOrientation)}
>
<Stack>
<Radio value='horizontal' label='Горизонтальная' />
<Radio value='vertical' label='Вертикальная' />
</Stack>
</Radio.Group>
<Select
allowDeselect={false}
label="Разрешение"
placeholder="Выберите разрешение"
data={printResolutions}
value={printResolution.toString()}
onChange={(value) => setPrintResolution(Number(value))}
/>
<Select
allowDeselect={false}
label="Масштаб"
placeholder="Выберите масштаб"
data={scaleOptions}
value={printScale}
onChange={(value) => setPrintScale(id, value as PrintScale)}
/>
<Checkbox
checked={printScaleLine}
label="Масштабная линия"
onChange={(event) => setPrintScaleLine(id, event.currentTarget.checked)}
/>
</Flex>
<Flex w='100%' gap='sm' align='center'>
<Button ml='auto' onClick={() => {
if (previousView) {
exportToPDF(printFormat, printResolution, printOrientation)
}
}}>
Печать
</Button>
</Flex>
</Stack>
</Modal.Body>
</Modal.Content>
</Modal.Root>
)
}
export default MapPrint

View File

@ -6,7 +6,7 @@ import { BASE_URL } from '../../constants'
const ObjectData = (object_data: IObjectData) => {
const { data: typeData } = useSWR(
object_data.type ? `/general/types/all` : null,
object_data.type ? `/general/types` : null,
(url) => fetcher(url, BASE_URL.ems),
{
revalidateOnFocus: false

View File

@ -16,7 +16,7 @@ const ObjectParameter = ({
map_id
}: ObjectParameterProps) => {
const { data: paramData } = useSWR(
`/general/params/all?param_id=${param.id_param}`,
`/general/params/?param_id=${param.id_param}`,
(url) => fetcher(url, BASE_URL.ems).then(res => res[0] as IParam),
{
revalidateOnFocus: false,

View File

@ -15,7 +15,7 @@ const ObjectParameters = ({
const { currentObjectId } = useObjectsStore().id[map_id]
const { data: valuesData, isValidating: valuesValidating } = useSWR(
currentObjectId ? `/general/values/all?object_id=${currentObjectId}` : null,
currentObjectId ? `/general/values/?object_id=${currentObjectId}` : null,
(url) => fetcher(url, BASE_URL.ems),
{
revalidateOnFocus: false,