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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import BingMapsReact from 'bingmaps-react';
import { Button, EditableText, IconButton, Type } from 'browndash-components';
import { action, computed, IReactionDisposer, observable, ObservableMap, reaction, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { Doc, DocListCast, Field, Opt } from '../../../../fields/Doc';
import { DocCss, Highlight, Width } from '../../../../fields/DocSymbols';
import { InkTool } from '../../../../fields/InkField';
import { DocCast, NumCast, StrCast } from '../../../../fields/Types';
import { emptyFunction, returnEmptyDoclist, returnEmptyFilter, returnEmptyString, returnFalse, returnOne, returnTrue, setupMoveUpEvents, Utils } from '../../../../Utils';
import { Docs, DocUtils } from '../../../documents/Documents';
import { DocumentType } from '../../../documents/DocumentTypes';
import { DocumentManager } from '../../../util/DocumentManager';
import { DragManager } from '../../../util/DragManager';
import { LinkManager } from '../../../util/LinkManager';
import { SnappingManager } from '../../../util/SnappingManager';
import { Transform } from '../../../util/Transform';
import { undoable, UndoManager } from '../../../util/UndoManager';
import { MarqueeOptionsMenu } from '../../collections/collectionFreeForm';
import { ViewBoxAnnotatableComponent, ViewBoxAnnotatableProps } from '../../DocComponent';
import { Colors } from '../../global/globalEnums';
import { MarqueeAnnotator } from '../../MarqueeAnnotator';
import { SidebarAnnos } from '../../SidebarAnnos';
import { DocumentView } from '../DocumentView';
import { FieldView, FieldViewProps } from '../FieldView';
import { PinProps, PresBox } from '../trails';
import { MapAnchorMenu } from './MapAnchorMenu';
import './MapBox.scss';
// amongus
/**
* MapBox architecture:
* Main component: MapBox.tsx
* Supporting Components: SidebarAnnos, CollectionStackingView
*
* MapBox is a node that extends the ViewBoxAnnotatableComponent. Similar to PDFBox and WebBox, it supports interaction between sidebar content and document content.
* The main body of MapBox uses Google Maps API to allow location retrieval, adding map markers, pan and zoom, and open street view.
* Dash Document architecture is integrated with Maps API: When drag and dropping documents with ExifData (gps Latitude and Longitude information) available,
* sidebarAddDocument function checks if the document contains lat & lng information, if it does, then the document is added to both the sidebar and the infowindow (a pop up corresponding to a map marker--pin on map).
* The lat and lng field of the document is filled when importing (spec see ConvertDMSToDD method and processFileUpload method in Documents.ts).
* A map marker is considered a document that contains a collection with stacking view of documents, it has a lat, lng location, which is passed to Maps API's custom marker (red pin) to be rendered on the google maps
*/
const bingApiKey = process.env.BING_MAPS; // if you're running local, get a Bing Maps api key here: https://www.bingmapsportal.com/ and then add it to the .env file in the Dash-Web root directory as: _CLIENT_BING_MAPS=<your apikey>
/**
* Consider integrating later: allows for drawing, circling, making shapes on map
*/
// const drawingManager = new window.google.maps.drawing.DrawingManager({
// drawingControl: true,
// drawingControlOptions: {
// position: google.maps.ControlPosition.TOP_RIGHT,
// drawingModes: [
// google.maps.drawing.OverlayType.MARKER,
// // currently we are not supporting the following drawing mode on map, a thought for future development
// google.maps.drawing.OverlayType.CIRCLE,
// google.maps.drawing.OverlayType.POLYLINE,
// ],
// },
// });
@observer
export class MapBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatableProps & FieldViewProps>() {
public static LayoutString(fieldKey: string) {
return FieldView.LayoutString(MapBox, fieldKey);
}
private _dragRef = React.createRef<HTMLDivElement>();
private _mainCont: React.RefObject<HTMLDivElement> = React.createRef();
private _annotationLayer: React.RefObject<HTMLDivElement> = React.createRef();
private _sidebarRef = React.createRef<SidebarAnnos>();
private _ref: React.RefObject<HTMLDivElement> = React.createRef();
private _disposers: { [key: string]: IReactionDisposer } = {};
private _setPreviewCursor: undefined | ((x: number, y: number, drag: boolean, hide: boolean, doc: Opt<Doc>) => void);
@observable private _marqueeing: number[] | undefined;
@observable private _savedAnnotations = new ObservableMap<number, HTMLDivElement[]>();
@computed get allSidebarDocs() {
return DocListCast(this.dataDoc[this.SidebarKey]);
}
// this list contains pushpins and configs
@computed get allAnnotations() {
return DocListCast(this.dataDoc[this.annotationKey]);
}
@computed get allPushpins() {
return this.allAnnotations.filter(anno => anno.type === DocumentType.PUSHPIN);
}
@computed get SidebarShown() {
return this.layoutDoc._layout_showSidebar ? true : false;
}
@computed get sidebarWidthPercent() {
return StrCast(this.layoutDoc._layout_sidebarWidthPercent, '0%');
}
@computed get sidebarColor() {
return StrCast(this.layoutDoc.sidebar_color, StrCast(this.layoutDoc[this.props.fieldKey + '_backgroundColor'], '#e4e4e4'));
}
@computed get SidebarKey() {
return this.fieldKey + '_sidebar';
}
componentDidMount() {
this._unmounting = false;
this.props.setContentView?.(this);
}
_unmounting = false;
componentWillUnmount(): void {
this._unmounting = true;
this.deselectPin();
Object.keys(this._disposers).forEach(key => this._disposers[key]?.());
}
/**
* Called when dragging documents into map sidebar or directly into infowindow; to create a map marker, ref to MapMarkerDocument in Documents.ts
* @param doc
* @param sidebarKey
* @returns
*/
sidebarAddDocument = (doc: Doc | Doc[], sidebarKey?: string) => {
if (!this.layoutDoc._layout_showSidebar) this.toggleSidebar();
const docs = doc instanceof Doc ? [doc] : doc;
docs.forEach(doc => {
let existingPin = this.allPushpins.find(pin => pin.latitude === doc.latitude && pin.longitude === doc.longitude) ?? this.selectedPin;
if (doc.latitude !== undefined && doc.longitude !== undefined && !existingPin) {
existingPin = this.createPushpin(NumCast(doc.latitude), NumCast(doc.longitude), StrCast(doc.map));
}
if (existingPin) {
setTimeout(() => {
// we use a timeout in case this is called from the sidebar which may have just added a link that hasn't made its way into th elink manager yet
if (!LinkManager.Instance.getAllRelatedLinks(doc).some(link => DocCast(link.link_anchor_1)?.mapPin === existingPin || DocCast(link.link_anchor_2)?.mapPin === existingPin)) {
const anchor = this.getAnchor(true, undefined, existingPin);
anchor && DocUtils.MakeLink(anchor, doc, { link_relationship: 'link to map location' });
doc.latitude = existingPin?.latitude;
doc.longitude = existingPin?.longitude;
}
});
}
}); //add to annotation list
return this.addDocument(doc, sidebarKey); // add to sidebar list
};
removeMapDocument = (doc: Doc | Doc[], annotationKey?: string) => {
const docs = doc instanceof Doc ? [doc] : doc;
this.allAnnotations.filter(anno => docs.includes(DocCast(anno.mapPin))).forEach(anno => (anno.mapPin = undefined));
return this.removeDocument(doc, annotationKey, undefined);
};
/**
* Removing documents from the sidebar
* @param doc
* @param sidebarKey
* @returns
*/
sidebarRemoveDocument = (doc: Doc | Doc[], sidebarKey?: string) => this.removeMapDocument(doc, sidebarKey);
/**
* Toggle sidebar onclick the tiny comment button on the top right corner
* @param e
*/
sidebarBtnDown = (e: React.PointerEvent) => {
setupMoveUpEvents(
this,
e,
(e, down, delta) =>
runInAction(() => {
const localDelta = this.props
.ScreenToLocalTransform()
.scale(this.props.NativeDimScaling?.() || 1)
.transformDirection(delta[0], delta[1]);
const fullWidth = this.layoutDoc[Width]();
const mapWidth = fullWidth - this.sidebarWidth();
if (this.sidebarWidth() + localDelta[0] > 0) {
this.layoutDoc._layout_showSidebar = true;
this.layoutDoc._width = fullWidth + localDelta[0];
this.layoutDoc._layout_sidebarWidthPercent = ((100 * (this.sidebarWidth() + localDelta[0])) / (fullWidth + localDelta[0])).toString() + '%';
} else {
this.layoutDoc._layout_showSidebar = false;
this.layoutDoc._width = mapWidth;
this.layoutDoc._layout_sidebarWidthPercent = '0%';
}
return false;
}),
emptyFunction,
() => UndoManager.RunInBatch(this.toggleSidebar, 'toggle sidebar map')
);
};
sidebarWidth = () => (Number(this.sidebarWidthPercent.substring(0, this.sidebarWidthPercent.length - 1)) / 100) * this.props.PanelWidth();
/**
* Handles toggle of sidebar on click the little comment button
*/
@computed get sidebarHandle() {
return (
<div
className="mapBox-overlayButton-sidebar"
key="sidebar"
title="Toggle Sidebar"
style={{
display: !this.props.isContentActive() ? 'none' : undefined,
top: StrCast(this.rootDoc._layout_showTitle) === 'title' ? 20 : 5,
backgroundColor: this.SidebarShown ? Colors.MEDIUM_BLUE : Colors.BLACK,
}}
onPointerDown={this.sidebarBtnDown}>
<FontAwesomeIcon style={{ color: Colors.WHITE }} icon={'comment-alt'} size="sm" />
</div>
);
}
// TODO: Adding highlight box layer to Maps
@action
toggleSidebar = () => {
const prevWidth = this.sidebarWidth();
this.layoutDoc._layout_showSidebar = (this.layoutDoc._layout_sidebarWidthPercent = StrCast(this.layoutDoc._layout_sidebarWidthPercent, '0%') === '0%' ? `${(100 * 0.2) / 1.2}%` : '0%') !== '0%';
this.layoutDoc._width = this.layoutDoc._layout_showSidebar ? NumCast(this.layoutDoc._width) * 1.2 : Math.max(20, NumCast(this.layoutDoc._width) - prevWidth);
};
createNoteAnnotation = () => {
const createFunc = undoable(
action(() => {
const note = this._sidebarRef.current?.anchorMenuClick(this.getAnchor(false), ['latitude', 'longitude', '-linkedTo']);
if (note && this.selectedPin) {
note.latitude = this.selectedPin.latitude;
note.longitude = this.selectedPin.longitude;
note.map = this.selectedPin.map;
}
}),
'create note annotation'
);
if (!this.layoutDoc.layout_showSidebar) {
this.toggleSidebar();
setTimeout(createFunc);
} else createFunc();
};
sidebarDown = (e: React.PointerEvent) => {
setupMoveUpEvents(this, e, this.sidebarMove, emptyFunction, () => setTimeout(this.toggleSidebar), true);
};
sidebarMove = (e: PointerEvent, down: number[], delta: number[]) => {
const bounds = this._ref.current!.getBoundingClientRect();
this.layoutDoc._layout_sidebarWidthPercent = '' + 100 * Math.max(0, 1 - (e.clientX - bounds.left) / bounds.width) + '%';
this.layoutDoc._layout_showSidebar = this.layoutDoc._layout_sidebarWidthPercent !== '0%';
e.preventDefault();
return false;
};
setPreviewCursor = (func?: (x: number, y: number, drag: boolean, hide: boolean, doc: Opt<Doc>) => void) => (this._setPreviewCursor = func);
@action
onMarqueeDown = (e: React.PointerEvent) => {
if (!e.altKey && e.button === 0 && this.props.isContentActive(true) && ![InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) {
setupMoveUpEvents(
this,
e,
action(e => {
MarqueeAnnotator.clearAnnotations(this._savedAnnotations);
this._marqueeing = [e.clientX, e.clientY];
return true;
}),
returnFalse,
() => MarqueeAnnotator.clearAnnotations(this._savedAnnotations),
false
);
}
};
@action finishMarquee = (x?: number, y?: number) => {
this._marqueeing = undefined;
x !== undefined && y !== undefined && this._setPreviewCursor?.(x, y, false, false, this.rootDoc);
};
addDocumentWrapper = (doc: Doc | Doc[], annotationKey?: string) => this.addDocument(doc, annotationKey);
pointerEvents = () => (this.props.isContentActive() && !MarqueeOptionsMenu.Instance.isShown() ? 'all' : 'none');
panelWidth = () => this.props.PanelWidth() / (this.props.NativeDimScaling?.() || 1) - this.sidebarWidth();
panelHeight = () => this.props.PanelHeight() / (this.props.NativeDimScaling?.() || 1);
scrollXf = () => this.props.ScreenToLocalTransform().translate(0, NumCast(this.layoutDoc._layout_scrollTop));
transparentFilter = () => [...this.props.childFilters(), Utils.IsTransparentFilter()];
opaqueFilter = () => [...this.props.childFilters(), Utils.IsOpaqueFilter()];
infoWidth = () => this.props.PanelWidth() / 5;
infoHeight = () => this.props.PanelHeight() / 5;
anchorMenuClick = () => this._sidebarRef.current?.anchorMenuClick;
savedAnnotations = () => this._savedAnnotations;
_bingSearchManager: any;
_bingMap: any;
get MicrosoftMaps() {
return (window as any).Microsoft.Maps;
}
// uses Bing Search to retrieve lat/lng for a location. eg.,
// const results = this.geocodeQuery(map.map, 'Philadelphia, PA');
// to move the map to that location:
// const location = await this.geocodeQuery(this._bingMap, 'Philadelphia, PA');
// this._bingMap.current.setView({
// mapTypeId: this.MicrosoftMaps.MapTypeId.aerial,
// center: new this.MicrosoftMaps.Location(loc.latitude, loc.longitude),
// });
//
bingGeocode = (map: any, query: string) => {
return new Promise<{ latitude: number; longitude: number }>((res, reject) => {
//If search manager is not defined, load the search module.
if (!this._bingSearchManager) {
//Create an instance of the search manager and call the geocodeQuery function again.
this.MicrosoftMaps.loadModule('Microsoft.Maps.Search', () => {
this._bingSearchManager = new this.MicrosoftMaps.Search.SearchManager(map.current);
res(this.bingGeocode(map, query));
});
} else {
this._bingSearchManager.geocode({
where: query,
callback: action((r: any) => res(r.results[0].location)),
errorCallback: (e: any) => reject(),
});
}
});
};
@observable
bingSearchBarContents: any = this.rootDoc.map; // For Bing Maps: The contents of the Bing search bar (string)
geoDataRequestOptions = {
entityType: 'PopulatedPlace',
};
// incrementer: number = 0;
/*
* Creates Pushpin doc and adds it to the list of annotations
*/
@action
createPushpin = undoable((latitude: number, longitude: number, map?: string) => {
// Stores the pushpin as a MapMarkerDocument
const pushpin = Docs.Create.PushpinDocument(
NumCast(latitude),
NumCast(longitude),
false,
[],
{ title: map ?? `lat=${latitude},lng=${longitude}`, map: map }
// ,'pushpinIDamongus'+ this.incrementer++
);
this.addDocument(pushpin, this.annotationKey);
return pushpin;
// mapMarker.infoWindowOpen = true;
}, 'createpin');
// The pin that is selected
@observable selectedPin: Doc | undefined;
@action
deselectPin = () => {
if (this.selectedPin) {
// Removes filter
Doc.setDocFilter(this.rootDoc, 'latitude', this.selectedPin.latitude, 'remove');
Doc.setDocFilter(this.rootDoc, 'longitude', this.selectedPin.longitude, 'remove');
Doc.setDocFilter(this.rootDoc, '-linkedTo', Field.toString(DocCast(this.selectedPin.mapPin)), 'removeAll');
const temp = this.selectedPin;
if (!this._unmounting) {
this._bingMap.current.entities.remove(this.map_docToPinMap.get(temp));
}
const newpin = new this.MicrosoftMaps.Pushpin(new this.MicrosoftMaps.Location(temp.latitude, temp.longitude));
this.MicrosoftMaps.Events.addHandler(newpin, 'click', (e: any) => this.pushpinClicked(temp as Doc));
if (!this._unmounting) {
this._bingMap.current.entities.push(newpin);
}
this.map_docToPinMap.set(temp, newpin);
this.selectedPin = undefined;
this.bingSearchBarContents = this.rootDoc.map;
}
};
getView = async (doc: Doc) => {
if (this._sidebarRef?.current?.makeDocUnfiltered(doc) && !this.SidebarShown) this.toggleSidebar();
return new Promise<Opt<DocumentView>>(res => DocumentManager.Instance.AddViewRenderedCb(doc, dv => res(dv)));
};
/*
* Pushpin onclick
*/
@action
pushpinClicked = (pinDoc: Doc) => {
this.deselectPin();
this.selectedPin = pinDoc;
this.bingSearchBarContents = pinDoc.map;
// Doc.setDocFilter(this.rootDoc, 'latitude', this.selectedPin.latitude, 'match');
// Doc.setDocFilter(this.rootDoc, 'longitude', this.selectedPin.longitude, 'match');
Doc.setDocFilter(this.rootDoc, '-linkedTo', Field.toScriptString(this.selectedPin), 'mapPin' as any);
this.recolorPin(this.selectedPin, 'green');
MapAnchorMenu.Instance.Delete = this.deleteSelectedPin;
MapAnchorMenu.Instance.Center = this.centerOnSelectedPin;
MapAnchorMenu.Instance.LinkNote = this.createNoteAnnotation;
const point = this._bingMap.current.tryLocationToPixel(new this.MicrosoftMaps.Location(this.selectedPin.latitude, this.selectedPin.longitude));
const x = point.x + (this.props.PanelWidth() - this.sidebarWidth()) / 2;
const y = point.y + this.props.PanelHeight() / 2 + 32;
const cpt = this.props.ScreenToLocalTransform().inverse().transformPoint(x, y);
MapAnchorMenu.Instance.jumpTo(cpt[0], cpt[1], true);
document.addEventListener('pointerdown', this.tryHideMapAnchorMenu, true);
};
/**
* Map OnClick
*/
@action
mapOnClick = (e: { location: { latitude: any; longitude: any } }) => {
this.props.select(false);
this.deselectPin();
};
/*
* Updates values of layout doc to match the current map
*/
@action
mapRecentered = () => {
if (
Math.abs(NumCast(this.dataDoc.latitude) - this._bingMap.current.getCenter().latitude) > 1e-7 || //
Math.abs(NumCast(this.dataDoc.longitude) - this._bingMap.current.getCenter().longitude) > 1e-7
) {
this.dataDoc.latitude = this._bingMap.current.getCenter().latitude;
this.dataDoc.longitude = this._bingMap.current.getCenter().longitude;
this.dataDoc.map = '';
this.bingSearchBarContents = '';
}
this.dataDoc.map_zoom = this._bingMap.current.getZoom();
};
/*
* Updates maptype
*/
@action
updateMapType = () => (this.dataDoc.map_type = this._bingMap.current.getMapTypeId());
/*
* For Bing Maps
* Called by search button's onClick
* Finds the geocode of the searched contents and sets location to that location
**/
@action
bingSearch = () => {
return this.bingGeocode(this._bingMap, this.bingSearchBarContents).then(location => {
this.dataDoc.latitude = location.latitude;
this.dataDoc.longitude = location.longitude;
this.dataDoc.map_zoom = this._bingMap.current.getZoom();
this.dataDoc.map = this.bingSearchBarContents;
});
};
/*
* Returns doc w/ relevant info
*/
getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps, existingPin?: Doc) => {
/// this should use SELECTED pushpin for lat/long if there is a selection, otherwise CENTER
const anchor = Docs.Create.ConfigDocument({
title: 'MapAnchor:' + this.rootDoc.title,
text: StrCast(this.selectedPin?.map) || StrCast(this.rootDoc.map) || 'map location',
config_latitude: NumCast((existingPin ?? this.selectedPin)?.latitude ?? this.dataDoc.latitude),
config_longitude: NumCast((existingPin ?? this.selectedPin)?.longitude ?? this.dataDoc.longitude),
config_map_zoom: NumCast(this.dataDoc.map_zoom),
config_map_type: StrCast(this.dataDoc.map_type),
config_map: StrCast((existingPin ?? this.selectedPin)?.map) || StrCast(this.dataDoc.map),
layout_unrendered: true,
mapPin: existingPin ?? this.selectedPin,
annotationOn: this.rootDoc,
});
if (anchor) {
if (!addAsAnnotation) anchor.backgroundColor = 'transparent';
addAsAnnotation && false && this.addDocument(anchor); // only need to add visible annotations to doc, but all anchors are configs for now
PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}), map: true } }, this.rootDoc);
return anchor;
}
return this.rootDoc;
};
map_docToPinMap = new Map<Doc, any>();
map_pinHighlighted = new Map<Doc, boolean>();
/*
* Input: pin doc
* Adds MicrosoftMaps Pushpin to the map (render)
*/
@action
addPushpin = (pin: Doc) => {
const pushPin = pin.infoWindowOpen
? new this.MicrosoftMaps.Pushpin(new this.MicrosoftMaps.Location(pin.latitude, pin.longitude), {})
: new this.MicrosoftMaps.Pushpin(
new this.MicrosoftMaps.Location(pin.latitude, pin.longitude)
// {icon: 'http://icons.iconarchive.com/icons/icons-land/vista-map-markers/24/Map-Marker-Marker-Outside-Chartreuse-icon.png'}
);
this._bingMap.current.entities.push(pushPin);
this.MicrosoftMaps.Events.addHandler(pushPin, 'click', (e: any) => this.pushpinClicked(pin));
// this.MicrosoftMaps.Events.addHandler(pushPin, 'dblclick', (e: any) => this.pushpinDblClicked(pushPin, pin));
this.map_docToPinMap.set(pin, pushPin);
};
/*
* Input: pin doc
* Removes pin from annotations
*/
@action
removePushpin = (pinDoc: Doc) => this.removeMapDocument(pinDoc, this.annotationKey);
/*
* Removes pushpin from map render
*/
deletePushpin = (pinDoc: Doc) => {
if (!this._unmounting) {
this._bingMap.current.entities.remove(this.map_docToPinMap.get(pinDoc));
}
this.map_docToPinMap.delete(pinDoc);
this.selectedPin = undefined;
};
@action
deleteSelectedPin = undoable(() => {
if (this.selectedPin) {
// Removes filter
Doc.setDocFilter(this.rootDoc, 'latitude', this.selectedPin.latitude, 'remove');
Doc.setDocFilter(this.rootDoc, 'longitude', this.selectedPin.longitude, 'remove');
Doc.setDocFilter(this.rootDoc, '-linkedTo', Field.toString(DocCast(this.selectedPin.mapPin)), 'removeAll');
this.removePushpin(this.selectedPin);
}
MapAnchorMenu.Instance.fadeOut(true);
document.removeEventListener('pointerdown', this.tryHideMapAnchorMenu, true);
}, 'delete pin');
tryHideMapAnchorMenu = (e: PointerEvent) => {
let target = document.elementFromPoint(e.x, e.y);
while (target) {
if (target === MapAnchorMenu.top.current) return;
target = target.parentElement;
}
e.stopPropagation();
e.preventDefault();
MapAnchorMenu.Instance.fadeOut(true);
document.removeEventListener('pointerdown', this.tryHideMapAnchorMenu, true);
};
@action
centerOnSelectedPin = () => {
if (this.selectedPin) {
this.dataDoc.latitude = this.selectedPin.latitude;
this.dataDoc.longitude = this.selectedPin.longitude;
this.dataDoc.map = this.selectedPin.map ?? '';
this.bingSearchBarContents = this.selectedPin.map;
}
MapAnchorMenu.Instance.fadeOut(true);
document.removeEventListener('pointerdown', this.tryHideMapAnchorMenu);
};
/**
* View options for bing maps
*/
bingViewOptions = {
// center: { latitude: this.dataDoc.latitude ?? defaultCenter.lat, longitude: this.dataDoc.longitude ?? defaultCenter.lng },
zoom: this.dataDoc.latitude ?? 10,
mapTypeId: 'grayscale',
};
/**
* Map options
*/
bingMapOptions = {
navigationBarMode: 'square',
backgroundColor: '#f1f3f4',
enableInertia: true,
supportedMapTypes: ['grayscale', 'canvasLight'],
disableMapTypeSelectorMouseOver: true,
// showScalebar:true
// disableRoadView:true,
// disableBirdseye:true
streetsideOptions: {
showProblemReporting: false,
showCurrentAddress: false,
},
};
@action
searchbarOnEdit = (newText: string) => (this.bingSearchBarContents = newText);
recolorPin = (pin: Doc, color?: string) => {
this._bingMap.current.entities.remove(this.map_docToPinMap.get(pin));
this.map_docToPinMap.delete(pin);
const newpin = new this.MicrosoftMaps.Pushpin(new this.MicrosoftMaps.Location(pin.latitude, pin.longitude), color ? { color } : {});
this.MicrosoftMaps.Events.addHandler(newpin, 'click', (e: any) => this.pushpinClicked(pin));
this._bingMap.current.entities.push(newpin);
this.map_docToPinMap.set(pin, newpin);
};
/*
* Called when BingMap is first rendered
* Initializes starting values
*/
@observable _mapReady = false;
@action
bingMapReady = (map: any) => {
this._mapReady = true;
this._bingMap = map.map;
if (!this._bingMap.current) {
alert('NO Map!?');
}
this.MicrosoftMaps.Events.addHandler(this._bingMap.current, 'click', this.mapOnClick);
this.MicrosoftMaps.Events.addHandler(this._bingMap.current, 'viewchangeend', undoable(this.mapRecentered, 'Map Layout Change'));
this.MicrosoftMaps.Events.addHandler(this._bingMap.current, 'maptypechanged', undoable(this.updateMapType, 'Map ViewType Change'));
this._disposers.mapLocation = reaction(
() => this.rootDoc.map,
mapLoc => (this.bingSearchBarContents = mapLoc),
{ fireImmediately: true }
);
this._disposers.highlight = reaction(
() => this.allAnnotations.map(doc => doc[Highlight]),
() => {
const allConfigPins = this.allAnnotations.map(doc => ({ doc, pushpin: DocCast(doc.mapPin) })).filter(pair => pair.pushpin);
allConfigPins.forEach(({ doc, pushpin }) => {
if (!pushpin[Highlight] && this.map_pinHighlighted.get(pushpin)) {
this.recolorPin(pushpin);
this.map_pinHighlighted.delete(pushpin);
}
});
allConfigPins.forEach(({ doc, pushpin }) => {
if (doc[Highlight] && !this.map_pinHighlighted.get(pushpin)) {
this.recolorPin(pushpin, 'orange');
this.map_pinHighlighted.set(pushpin, true);
}
});
},
{ fireImmediately: true }
);
this._disposers.location = reaction(
() => ({ lat: this.rootDoc.latitude, lng: this.rootDoc.longitude, zoom: this.rootDoc.map_zoom, mapType: this.rootDoc.map_type }),
locationObject => {
// if (this._bingMap.current)
try {
locationObject?.zoom &&
this._bingMap.current?.setView({
mapTypeId: locationObject.mapType,
zoom: locationObject.zoom,
center: new this.MicrosoftMaps.Location(locationObject.lat, locationObject.lng),
});
} catch (e) {
console.log(e);
}
},
{ fireImmediately: true }
);
};
dragToggle = (e: React.PointerEvent) => {
let dragClone: HTMLDivElement | undefined;
setupMoveUpEvents(
e,
e,
e => {
if (!dragClone) {
dragClone = this._dragRef.current?.cloneNode(true) as HTMLDivElement;
dragClone.style.position = 'absolute';
dragClone.style.zIndex = '10000';
DragManager.Root().appendChild(dragClone);
}
dragClone.style.transform = `translate(${e.clientX - 15}px, ${e.clientY - 15}px)`;
return false;
},
e => {
if (!dragClone) return;
DragManager.Root().removeChild(dragClone);
let target = document.elementFromPoint(e.x, e.y);
while (target) {
if (target === this._ref.current) {
const cpt = this.props.ScreenToLocalTransform().transformPoint(e.clientX, e.clientY);
const x = cpt[0] - (this.props.PanelWidth() - this.sidebarWidth()) / 2;
const y = cpt[1] - 32 /* height of search bar */ - this.props.PanelHeight() / 2;
const location = this._bingMap.current.tryPixelToLocation(new this.MicrosoftMaps.Point(x, y));
this.createPushpin(location.latitude, location.longitude);
break;
}
target = target.parentElement;
}
},
e => {
const createPin = () => this.createPushpin(this.rootDoc.latitude, this.rootDoc.longitude, this.rootDoc.map);
if (this.bingSearchBarContents) {
this.bingSearch().then(createPin);
} else createPin();
}
);
};
searchbarKeyDown = (e: any) => e.key === 'Enter' && this.bingSearch();
static _firstRender = true;
static _rerenderDelay = 0;
_rerenderTimeout: any;
render() {
// bcz: no idea what's going on here, but bings maps have some kind of bug
// such that we need to delay rendering a second map on startup until the first map is rendered.
this.rootDoc[DocCss];
if (MapBox._firstRender) {
MapBox._firstRender = false;
MapBox._rerenderDelay = 500;
} else if (MapBox._rerenderDelay) {
// prettier-ignore
this._rerenderTimeout = this._rerenderTimeout ??
setTimeout(action(() => {
MapBox._rerenderDelay = 0;
this.rootDoc[DocCss] = this.rootDoc[DocCss] + 1;
}), MapBox._rerenderDelay);
return null;
}
const renderAnnotations = (childFilters?: () => string[]) => null;
return (
<div className="mapBox" ref={this._ref}>
<div
className="mapBox-wrapper"
onWheel={e => e.stopPropagation()}
onPointerDown={async e => {
e.button === 0 && !e.ctrlKey && e.stopPropagation();
}}
style={{ width: `calc(100% - ${this.sidebarWidthPercent})`, pointerEvents: this.pointerEvents() }}>
<div style={{ mixBlendMode: 'multiply' }}>{renderAnnotations(this.transparentFilter)}</div>
{renderAnnotations(this.opaqueFilter)}
{SnappingManager.GetIsDragging() ? null : renderAnnotations()}
<div className="mapBox-searchbar">
<EditableText
// editing
setVal={(newText: string | number) => typeof newText === 'string' && this.searchbarOnEdit(newText)}
onEnter={e => this.bingSearch()}
placeholder={this.bingSearchBarContents || 'enter city/zip/...'}
textAlign="center"
/>
<IconButton
icon={
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="magnifying-glass" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" color="#DFDFDF">
<path
fill="currentColor"
d="M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352a144 144 0 1 0 0-288 144 144 0 1 0 0 288z"></path>
</svg>
}
onClick={this.bingSearch}
type={Type.TERT}
/>
<div style={{ width: 30, height: 30 }} ref={this._dragRef} onPointerDown={this.dragToggle}>
<Button tooltip="drag to place a pushpin" icon={<FontAwesomeIcon size={'lg'} icon={'bullseye'} />} />
</div>
</div>
<BingMapsReact
onMapReady={this.bingMapReady} //
bingMapsKey={bingApiKey}
height="100%"
mapOptions={this.bingMapOptions}
width="100%"
viewOptions={this.bingViewOptions}
/>
<div>
{!this._mapReady
? null
: this.allAnnotations
.filter(anno => !anno.layout_unrendered)
.map((pushpin, i) => (
<DocumentView
key={i}
{...this.props}
renderDepth={this.props.renderDepth + 1}
Document={pushpin}
DataDoc={undefined}
PanelWidth={returnOne}
PanelHeight={returnOne}
NativeWidth={returnOne}
NativeHeight={returnOne}
onKey={undefined}
onDoubleClick={undefined}
onBrowseClick={undefined}
childFilters={returnEmptyFilter}
childFiltersByRanges={returnEmptyFilter}
searchFilterDocs={returnEmptyDoclist}
isDocumentActive={returnFalse}
isContentActive={returnFalse}
addDocTab={returnFalse}
ScreenToLocalTransform={Transform.Identity}
fitContentsToBox={undefined}
focus={returnOne}
/>
))}
</div>
{/* <MapBoxInfoWindow
key={Docs.Create.MapMarkerDocument(NumCast(40), NumCast(40), false, [], {})[Id]}
{...OmitKeys(this.props, ['NativeWidth', 'NativeHeight', 'setContentView']).omit}
place={Docs.Create.MapMarkerDocument(NumCast(40), NumCast(40), false, [], {})}
markerMap={this.markerMap}
PanelWidth={this.infoWidth}
PanelHeight={this.infoHeight}
moveDocument={this.moveDocument}
isAnyChildContentActive={this.isAnyChildContentActive}
whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
/> */}
{!this._marqueeing || !this._mainCont.current || !this._annotationLayer.current ? null : (
<MarqueeAnnotator
rootDoc={this.rootDoc}
anchorMenuClick={this.anchorMenuClick}
scrollTop={0}
down={this._marqueeing}
scaling={returnOne}
addDocument={this.addDocumentWrapper}
docView={this.props.docViewPath().lastElement()}
finishMarquee={this.finishMarquee}
savedAnnotations={this.savedAnnotations}
annotationLayer={this._annotationLayer.current}
selectionText={returnEmptyString}
mainCont={this._mainCont.current}
/>
)}
</div>
{/* </LoadScript > */}
<div className="mapBox-sidebar" style={{ width: `${this.sidebarWidthPercent}`, backgroundColor: `${this.sidebarColor}` }}>
<SidebarAnnos
ref={this._sidebarRef}
{...this.props}
fieldKey={this.fieldKey}
rootDoc={this.rootDoc}
layoutDoc={this.layoutDoc}
dataDoc={this.dataDoc}
usePanelWidth={true}
showSidebar={this.SidebarShown}
nativeWidth={NumCast(this.layoutDoc._nativeWidth)}
whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
PanelWidth={this.sidebarWidth}
sidebarAddDocument={this.sidebarAddDocument}
moveDocument={this.moveDocument}
removeDocument={this.sidebarRemoveDocument}
/>
</div>
{this.sidebarHandle}
</div>
);
}
}
|