-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.tsx
More file actions
275 lines (248 loc) · 10.3 KB
/
index.tsx
File metadata and controls
275 lines (248 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import { Alert, Card, ConfigProvider, Modal, Splitter, Tabs } from 'antd'
import { useCallback, useEffect, useRef, useState, useMemo } from 'react'
import { Feature, Geometry, GeoJsonProperties } from 'geojson'
import { useTranslation } from 'react-i18next'
import { useAppDispatch, useAppSelector } from '../../state/hooks'
import { useDocContext } from '../../state/DocContext'
import { useAppContext } from '../../state/AppContext'
import { AppDispatch } from '../../state/store'
import { ExistingTrackProps, NewTrackProps } from '../../types'
import { timeBoundsFor } from '../../helpers/timeBounds'
import { loadJson } from '../../helpers/loaders/loadJson'
import { loadOpRep } from '../../helpers/loaders/loadOpRep'
import Layers from '../Layers'
import Properties from '../Properties'
import Map from '../spatial/Map'
import GraphModal from '../GraphModal'
import { LoadTrackModel } from '../LoadTrackModal'
import './index.css'
import ControlPanel from '../ControlPanel'
import { GraphsPanel } from '../GraphsPanel'
import { TimeSupport } from '../../helpers/time-support'
import field from '../../data/buoyfield1'
import track1 from '../../data/track1'
import track2 from '../../data/track2'
import track3 from '../../data/track3'
import zones from '../../data/zones'
import points from '../../data/points'
import backdrops from '../../data/backdrop'
import { selectFeatures } from '../../state/geoFeaturesSlice'
interface FileHandler {
blobType: string
handle: (text: string, features: Feature<Geometry, GeoJsonProperties>[], dispatch: AppDispatch, existingTrackDetails?: ExistingTrackProps, newTrackDetails?: NewTrackProps) => void
}
export interface TimeState {
filterApplied: boolean
start: number
step: string
end: number
// the outer limits
hardStart: number
hardEnd: number
}
const fileHandlers: FileHandler[] = [
{ blobType: 'application/json', handle: loadJson },
{ blobType: 'text/plain', handle: loadOpRep }
]
function Document({ filePath, withSampleData }: { filePath?: string, withSampleData?: boolean }) {
const features = useAppSelector(selectFeatures)
const documentContents = useAppSelector(state => state.fColl.present.data)
const dispatch = useAppDispatch()
const { t } = useTranslation()
const { setTime, time, message, setMessage, interval } = useDocContext()
const [timeBounds, setTimeBounds] = useState<[number, number] | null>(null)
const [graphOpen, setGraphOpen] = useState(false)
const [isDragging, setIsDragging] = useState(false)
const [dirty, setDirty] = useState(false)
const loadedRef = useRef<boolean>(false)
const [splitterHeights, setSplitterHeights] = useState<number[] | null>(null)
const [splitterWidths, setSplitterWidths] = useState<number[] | null>(null)
const [pendingOpRepFiles, setPendingOpRepFiles] = useState<File[] | null>(null)
useEffect(() => {
setDirty(true)
}, [features])
useEffect(() => {
if (!loadedRef.current && withSampleData) {
// (temporarily) load bulk selection
const newData: Feature[] = [
track1, track2, track3, field, ...zones, ...points, ...backdrops
]
dispatch({ type: 'fColl/featuresAdded', payload: newData })
loadedRef.current = true
}
}, [dispatch, loadedRef, withSampleData])
useEffect(() => {
if (features && features.length) {
const timeBoundsVal = timeBoundsFor(features)
if(timeBoundsVal) {
setTimeBounds(timeBoundsVal)
const timePayload = { filterApplied: false, start: timeBoundsVal[0], step: '00h30m', end: timeBoundsVal[1], hardStart: timeBoundsVal[0], hardEnd: timeBoundsVal[1] }
setTime(timePayload)
} else {
setTimeBounds(null)
setTime({...time, filterApplied: false, start: 0, end: 0})
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [features, setTime])
const { isDarkMode } = useAppContext()
const antdTheme = useMemo(() => ({
token: {
colorBgContainer: isDarkMode ? '#2a2a2a' : '#ffffff',
colorText: isDarkMode ? '#f0f0f0' : 'rgba(0, 0, 0, 0.88)',
colorBorder: isDarkMode ? '#444444' : '#d9d9d9'
},
components: {
Splitter: {
splitBarSize: 10,
},
Table: {
headerBg: isDarkMode ? '#333' : '#555',
headerColor: '#fff'
}
}
}), [isDarkMode])
const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
// only allow files to be dropped
if (event.dataTransfer.types.includes('Files')) {
event.preventDefault()
setIsDragging(true)
}
}
const handleDragLeave = () => {
setIsDragging(false)
}
const handleDrop = async (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault()
setIsDragging(false)
const files = event.dataTransfer.files
const filesArray = Array.from(files)
type FileAndHandler = {
file: File
handler: FileHandler | undefined
}
const filesAndHandlers = filesArray.map((file): FileAndHandler => ({ file, handler: fileHandlers.find(handler => handler.blobType === file.type) }))
const textFiles = filesAndHandlers.filter(({ handler }) => handler?.blobType === 'text/plain')
const otherFiles = filesAndHandlers.filter(({ handler }) => handler?.blobType !== 'text/plain')
if (textFiles.length > 0) {
setPendingOpRepFiles(textFiles.map(({ file }) => file))
}
for (let j = 0; j < otherFiles.length; j++) {
const { file, handler } = otherFiles[j]
if (handler) {
try {
handler.handle(await file.text(), features, dispatch)
} catch (e) {
console.error('handler error', file, handler, e)
setMessage({ title: t('documents.error'), severity: 'error', message: t('documents.handlingError') + e })
}
}
}
}
const loadNewTrack = async (values: NewTrackProps) => {
if (pendingOpRepFiles) {
// concatenate all of the file contents into one long string
let fileContents = ''
for(let i = 0; i < pendingOpRepFiles.length; i++) {
fileContents += await pendingOpRepFiles[i].text() + '\n'
}
loadOpRep(fileContents, features, dispatch, undefined, values)
}
setPendingOpRepFiles(null)
}
const handleDialogCancel = () => {
setPendingOpRepFiles(null)
}
const addToTrack = async (trackId: string) => {
if (pendingOpRepFiles) {
for (let i = 0; i< pendingOpRepFiles.length; i++){
loadOpRep(await pendingOpRepFiles[i].text(), features, dispatch, { trackId }, undefined)
}
}
setPendingOpRepFiles(null)
}
const doSave = useCallback(async () => {
if (filePath && window.electron) {
// just store the current JSON FeatureCollection
const doc = JSON.stringify(documentContents)
await window.electron.saveFile(filePath, doc)
} else {
window.alert(t('documents.localSaveNotSupported'))
}
}, [filePath, documentContents, t])
const detailTabs = [ {
key: '1',
label: t('document.detail'),
children: <Properties />
},
{
key: '2',
label: t('document.graphs'),
children: <GraphsPanel width={splitterWidths ? splitterWidths[0] : 300} height={splitterHeights ? splitterHeights[2] : 400} />
}]
const handleSplitterVerticalResize = (sizes: number[]) => {
setSplitterHeights(sizes)
}
const handleSplitterHorizontalResize = (sizes: number[]) => {
setSplitterWidths(sizes)
}
const handleScroll = (event: React.WheelEvent) => {
// check if we are in time filter mode
if (!time.filterApplied) return
const fwd = event.deltaY > 0
const timeNow = new Date(time.start)
const newStart = fwd
? TimeSupport.increment(timeNow, interval)
: TimeSupport.decrement(timeNow, interval)
const newEnd = TimeSupport.increment(newStart, interval)
if (newEnd.getTime() >= time.hardStart && newStart.getTime() <= time.hardEnd) {
const newTime = {
...time,
start: newStart.getTime(),
end: newEnd.getTime(),
}
setTime(newTime)
}
}
return (
<div style={{height: '100%' }} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onDrop={handleDrop}>
{isDragging && <><div className="modal-back"/> <div className="drag-overlay">+</div></>}
{ !!message && <Modal title={message?.title} open={!!message} onCancel={() => setMessage(null)} okType='primary' onOk={() => setMessage(null)}>
<Alert showIcon type={message?.severity} description={message?.message} />
</Modal> }
<ConfigProvider theme={antdTheme}>
{ /* introduce div, so we can catch wheel event */ }
<div style={{width: '100%', height: '100%', overflow: 'hidden'}} onWheel={handleScroll}>
<Splitter style={{ height: '100%', boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)' }} onResizeEnd={handleSplitterHorizontalResize}>
<Splitter.Panel key='left' collapsible defaultSize='300' min='200' max='600'>
<Splitter layout="vertical" style={{ height: '100%', boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)' }} onResizeEnd={handleSplitterVerticalResize}>
<Splitter.Panel style={{minHeight: '170px'}} defaultSize='170' min='170' max='170' resizable={false}>
<Card title={t('document.controlPanel')}>
<ControlPanel isDirty={dirty} handleSave={doSave} bounds={timeBounds}/>
</Card>
</Splitter.Panel>
<Splitter.Panel style={{overflow: 'visible'}} >
<Card title={t('document.layers')} style={{width: '100%', height: '100%'}}>
{features && <Layers splitterWidths={splitterHeights ? splitterHeights[1] : 330} openGraph={() => setGraphOpen(true)} />}
</Card>
</Splitter.Panel>
<Splitter.Panel>
<Tabs style={{ width: '100%', height: '100%' }} defaultActiveKey="1" id="detail-tabs" items={detailTabs} />
</Splitter.Panel>
</Splitter>
</Splitter.Panel>
<Splitter.Panel key='right'>
<Map>
<></>
</Map>
</Splitter.Panel>
</Splitter>
</div>
<GraphModal open={graphOpen} doClose={() => setGraphOpen(false)} />
</ConfigProvider>
<LoadTrackModel visible={!!pendingOpRepFiles} cancel={handleDialogCancel}
newTrack={loadNewTrack} addToTrack={addToTrack} />
</div>
)
}
export default Document