summaryrefslogtreecommitdiffstats
path: root/sdnr/wt/odlux/apps/networkMapApp/src/components/customize/customizationView.tsx
blob: 82e7b795b4f3010c5c667f0ec044e9012513dbec (plain)
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/**
 * ============LICENSE_START========================================================================
 * ONAP : ccsdk feature sdnr wt odlux
 * =================================================================================================
 * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property. All rights reserved.
 * =================================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 * ============LICENSE_END==========================================================================
 */

import { Button, Grid, InputLabel, makeStyles, MenuItem, Select, Slider, TextField, Typography } from '@material-ui/core';
import { NetworkMapSettings, ThemeElement } from '../../model/settings';
import * as React from 'react'
import connect, { Connect, IDispatcher } from '../../../../../framework/src/flux/connect';
import { IApplicationStoreState } from '../../../../../framework/src/store/applicationStore';
import { updateSettings } from '../../actions/settingsAction';
import ThemeEntry from './themeElement'
import * as mapboxgl from 'mapbox-gl';
import { OSM_STYLE } from '../../config';
import mapLayerService from '../../utils/mapLayers';
import { requestRest } from '../../../../../framework/src/services/restService';
import { NavigateToApplication } from '../../../../../framework/src/actions/navigationActions';

type props = Connect<typeof mapProps, typeof mapDispatch>;
let map: mapboxgl.Map;
let myMapRef = React.createRef<HTMLDivElement>();
const default_boundingbox = "12.882544785787754,52.21421979821472,13.775455214211949,52.80406241672602";


const mapProps = (state: IApplicationStoreState) => ({
  settings: state.network.settings,
});

const mapDispatch = (dispatcher: IDispatcher) => ({
  updateSettings: (mapSettings: NetworkMapSettings) => dispatcher.dispatch(updateSettings(mapSettings)),
  navigateToApplication: (applicationName: string) => dispatcher.dispatch(new NavigateToApplication(applicationName)),


});

const styles = makeStyles({
  sectionMargin: {
    marginTop: "30px",
    marginBottom: "15px"
  },
  elementMargin: {

    marginLeft: "10px"
  }
});

const CustomizationView: React.FunctionComponent<props> = (props) => {

  const [opacity, setOpacity] = React.useState(Number(props.settings.mapSettings?.networkMap.tileOpacity) || 100);
  const [theme, setTheme] = React.useState(props.settings.mapSettings?.networkMap.styling.theme || '');
  const [latitude, setLatitude] = React.useState<number>(Number(props.settings.mapSettings?.networkMap.startupPosition.latitude)|| 52.5);
  const [longitude, setLongitude] = React.useState<number>(Number(props.settings.mapSettings?.networkMap.startupPosition.longitude)|| 13.35);
  const [zoom, setZoom] = React.useState<number>(Number(props.settings.mapSettings?.networkMap.startupPosition.zoom) || 10);


  //used to make opacity available within the map event-listeners
  //(hook state values are snapshotted at initalization and not updated afterwards, thus use a ref here)
  const myOpacityRef = React.useRef(opacity);
  const setOpacityState = (data:any) => {
    myOpacityRef.current = data;
    setOpacity(data);
  };

  const classes = styles();
  const currentTheme = props.settings.themes.networkMapThemes.themes.find(el => el.key === theme);


  React.useEffect(() => {
    mapLayerService.settings = props.settings.themes;

    map = new mapboxgl.Map({
      container: myMapRef.current!,
      style: OSM_STYLE as any,
      center: [longitude, latitude],
      zoom: zoom,
      accessToken: ''
    });

    map.on('load', (ev) => {

      mapLayerService.addBaseSources(map, null, null);
      if(props.settings.mapSettings?.networkMap.styling.theme !== theme){
        mapLayerService.addBaseLayers(map, currentTheme);

      }else{
        mapLayerService.addBaseLayers(map);
      }

      mapLayerService.changeMapOpacity(map, myOpacityRef.current);

      getData();
    });

    map.on('moveend', () => {
      const center = map.getCenter();
      setZoom(Number(map.getZoom().toFixed(4)));
      setLatitude(Number(center.lat.toFixed(4)));
      setLongitude(Number(center.lng.toFixed(4)));
    });

  }, []);

  React.useEffect(() => {
    recenterMap();
  }, [latitude, longitude, zoom]);

  const setState = () => {
    if (props.settings.mapSettings?.networkMap.styling) {
      setTheme(props.settings.mapSettings.networkMap.styling.theme);
      mapLayerService.changeTheme(map, props.settings.mapSettings.networkMap.styling.theme);
    }

    const propOpacity = props.settings.mapSettings?.networkMap.tileOpacity;
    if (propOpacity) {
      setOpacityState(propOpacity);
    }
  }

  React.useEffect(() => {
    setState();
  }, [props.settings.mapSettings]);

  const onOpacityChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, newValue: number) => {
    setOpacity(newValue);
    mapLayerService.changeMapOpacity(map, newValue);

  };

  const onChangeTheme = (e: any) => {

    const newTheme = e.target.value;
    setTheme(newTheme);
    mapLayerService.changeTheme(map, newTheme);
  }

  const onCancel = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    e.preventDefault();
    props.navigateToApplication("network");
  }

  const onSaveSettings = async (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    e.preventDefault();

    const updatedSettings: NetworkMapSettings = {
      networkMap: {
        tileOpacity: opacity.toString(),
        styling: { theme: theme },
        startupPosition: {
          latitude: latitude.toString(),
          longitude: longitude.toString(),
          zoom: zoom.toString()
        }
      }
    };

    console.log(updatedSettings);
    
    await props.updateSettings(updatedSettings)
    props.navigateToApplication("network");

  }

  const recenterMap = () => {

    if (!isNaN(latitude) && !isNaN(longitude) && !isNaN(zoom))

      map.flyTo({
        center: [
          longitude,
          latitude
        ], zoom: zoom,
        essential: false
      });
  }



  const getData = () => {

    //get data of boundingbox from networkmap

    const links = requestRest<any>("/topology/network/links/geojson/" + default_boundingbox);
    const sites = requestRest<any>("/topology/network/sites/geojson/" + default_boundingbox);

    Promise.all([links, sites]).then(results => {
      if (map.getSource('lines')) {
        (map.getSource('lines') as mapboxgl.GeoJSONSource).setData(results[0]);
      }

      if (map.getSource('points')) {
        (map.getSource('points') as mapboxgl.GeoJSONSource).setData(results[1]);
      }

      if (map.getSource('selectedPoints')) {
        (map.getSource('selectedPoints') as mapboxgl.GeoJSONSource).setData(results[1].features[0]);
      }
    });
  }

  /**
   * Style property names to readable text
   * @param text propretyName
   * @returns readable text
   */
  const styleText = (text: string) => {
    const textParts = text.split(/(?=[A-Z])/); //split on uppercase character
    const newText = textParts.join(" ");
    return newText.charAt(0).toUpperCase() + newText.slice(1);
  }


  return (<>
    <h3>Settings</h3>
    <div style={{ display: 'flex', flexDirection: 'row', flexGrow: 1, height: "100%", position: 'relative' }}>
      <div style={{ width: "60%", flexDirection: 'column', position:'relative' }}>
        <Typography variant="body1" style={{ fontWeight: "bold" }} gutterBottom>Startup Position</Typography>
        <div style={{ display: 'flex', flexDirection: 'row' }}>
          <TextField type="number" value={latitude} onChange={(e) => setLatitude(e.target.value as any)} style={{ marginLeft: 10 }} label="Latitude" />
          <TextField type="number" value={longitude} onChange={(e) => setLongitude(e.target.value as any)} style={{ marginLeft: 5 }} label="Longitude" />
          <TextField type="number" value={zoom} onChange={(e) => setZoom(e.target.value as any)} style={{ marginLeft: 5 }} label="Zoom" />
        </div>

        <Typography className={classes.sectionMargin} variant="body1" style={{ fontWeight: "bold" }} gutterBottom>
          Tile Opacity
        </Typography>
        <Grid className={classes.elementMargin} container spacing={2} style={{ width: '50%' }}>
          <Grid item>0</Grid>
          <Grid item xs>
            <Slider color="secondary" min={0} max={100} value={opacity} onChange={onOpacityChange} aria-labelledby="continuous-slider" />
          </Grid>
          <Grid item>100</Grid>
        </Grid>

        <Typography className={classes.sectionMargin} variant="body1" style={{ fontWeight: "bold" }} gutterBottom>
          Style of properties
      </Typography>
        <InputLabel id="theme-select-label">Theme</InputLabel>
        <Select
          className={classes.elementMargin}
          value={theme}
          onChange={onChangeTheme}
          labelId="theme-select-label"
          style={{ marginLeft: 10 }}>
          {
            props.settings.themes.networkMapThemes.themes.map(el => <MenuItem value={el.key}>{el.key}</MenuItem>)
          }

        </Select>

        {
          currentTheme && <div style={{ marginLeft: 60 }}>
            { //skip the 'key' (theme name) entry
              Object.keys(currentTheme).slice(1).map(el => <ThemeEntry text={styleText(el)} color={(currentTheme as any)[el]} />)
            }
          </div>
        }


        <div className={classes.sectionMargin} style={{ position: 'absolute', right: 0, top: '60%' }}>
          <Button className={classes.elementMargin} variant="contained"
            color="primary" onClick={onCancel}>Cancel</Button>

          <Button className={classes.elementMargin} variant="contained"
            color="secondary" onClick={onSaveSettings}>Save</Button>
        </div>
      </div>
      <div id="map" ref={myMapRef} style={{ width: "35%", height: "50%" }}>

      </div>
    </div>

  </>)

}

export default connect(mapProps, mapDispatch)(CustomizationView);