Files
ThreadNet-Web/src/components/views/location/LocationPicker.tsx
T

244 lines
8.1 KiB
TypeScript
Raw Normal View History

2021-12-06 09:45:12 +00:00
/*
Copyright 2021 The Matrix.org Foundation C.I.C.
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.
*/
2021-12-17 12:26:02 +00:00
import React, { SyntheticEvent } from 'react';
2021-12-06 09:45:12 +00:00
import maplibregl from 'maplibre-gl';
2021-12-09 09:10:23 +00:00
import { logger } from "matrix-js-sdk/src/logger";
import { RoomMember } from 'matrix-js-sdk/src/models/room-member';
import { ClientEvent, IClientWellKnown } from 'matrix-js-sdk/src/client';
2021-12-06 09:45:12 +00:00
import DialogButtons from "../elements/DialogButtons";
import { _t } from '../../../languageHandler';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import MemberAvatar from '../avatars/MemberAvatar';
import MatrixClientContext from '../../../contexts/MatrixClientContext';
import Modal from '../../../Modal';
import ErrorDialog from '../dialogs/ErrorDialog';
import { findMapStyleUrl } from '../messages/MLocationBody';
import { tileServerFromWellKnown } from '../../../utils/WellKnownUtils';
2021-12-06 09:45:12 +00:00
interface IProps {
sender: RoomMember;
onChoose(uri: string, ts: number): boolean;
2021-12-17 12:26:02 +00:00
onFinished(ev?: SyntheticEvent): void;
2021-12-06 09:45:12 +00:00
}
interface IState {
position?: GeolocationPosition;
error: Error;
}
/*
* An older version of this file allowed manually picking a location on
* the map to share, instead of sharing your current location.
* Since the current designs do not cover this case, it was removed from
* the code but you should be able to find it in the git history by
* searching for the commit that remove manualPosition from this file.
*/
2021-12-06 09:45:12 +00:00
@replaceableComponent("views.location.LocationPicker")
class LocationPicker extends React.Component<IProps, IState> {
public static contextType = MatrixClientContext;
public context!: React.ContextType<typeof MatrixClientContext>;
private map?: maplibregl.Map = null;
private geolocate?: maplibregl.GeolocateControl = null;
private marker?: maplibregl.Marker = null;
2021-12-06 09:45:12 +00:00
2021-12-17 12:26:02 +00:00
constructor(props: IProps) {
2021-12-06 09:45:12 +00:00
super(props);
this.state = {
position: undefined,
error: undefined,
};
}
private getMarkerId = () => {
return "mx_MLocationPicker_marker";
};
2021-12-06 09:45:12 +00:00
componentDidMount() {
this.context.on(ClientEvent.ClientWellKnown, this.updateStyleUrl);
2021-12-06 09:45:12 +00:00
try {
this.map = new maplibregl.Map({
container: 'mx_LocationPicker_map',
style: findMapStyleUrl(),
center: [0, 0],
zoom: 1,
});
// Add geolocate control to the map.
this.geolocate = new maplibregl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
},
trackUserLocation: true,
});
this.map.addControl(this.geolocate);
2021-12-06 09:45:12 +00:00
this.marker = new maplibregl.Marker({
element: document.getElementById(this.getMarkerId()),
anchor: 'bottom',
offset: [0, -1],
})
.setLngLat(new maplibregl.LngLat(0, 0))
.addTo(this.map);
this.map.on('error', (e) => {
2021-12-17 12:26:02 +00:00
logger.error(
"Failed to load map: check map_style_url in config.json "
+ "has a valid URL and API key",
e.error,
);
this.setState({ error: e.error });
});
this.map.on('load', () => {
this.geolocate.trigger();
});
this.geolocate.on('error', this.onGeolocateError);
this.geolocate.on('geolocate', this.onGeolocate);
} catch (e) {
logger.error("Failed to render map", e);
this.setState({ error: e });
}
2021-12-06 09:45:12 +00:00
}
componentWillUnmount() {
this.geolocate?.off('error', this.onGeolocateError);
this.geolocate?.off('geolocate', this.onGeolocate);
this.context.off(ClientEvent.ClientWellKnown, this.updateStyleUrl);
2021-12-06 09:45:12 +00:00
}
private updateStyleUrl = (clientWellKnown: IClientWellKnown) => {
const style = tileServerFromWellKnown(clientWellKnown)?.["map_style_url"];
if (style) {
this.map?.setStyle(style);
}
};
2021-12-06 10:13:06 +00:00
private onGeolocate = (position: GeolocationPosition) => {
2021-12-06 09:45:12 +00:00
this.setState({ position });
this.marker?.setLngLat(
new maplibregl.LngLat(
position.coords.longitude,
position.coords.latitude,
),
);
};
private onGeolocateError = (e: GeolocationPositionError) => {
this.props.onFinished();
logger.error("Could not fetch location", e);
Modal.createTrackedDialog(
'Could not fetch location',
'',
ErrorDialog,
{
title: _t("Could not fetch location"),
description: positionFailureMessage(e.code),
},
);
2021-12-06 09:45:12 +00:00
};
private onOk = () => {
const position = this.state.position;
2021-12-06 10:13:06 +00:00
2021-12-06 09:45:12 +00:00
this.props.onChoose(
2021-12-17 10:58:24 +00:00
position ? getGeoUri(position) : undefined,
2021-12-06 10:13:06 +00:00
position ? position.timestamp : undefined,
2021-12-06 09:45:12 +00:00
);
this.props.onFinished();
};
render() {
const error = this.state.error ?
<div className="mx_LocationPicker_error">
{ _t("Failed to load map") }
</div> : null;
return (
<div className="mx_LocationPicker">
<div id="mx_LocationPicker_map" />
{ error }
<div className="mx_LocationPicker_footer">
<form onSubmit={this.onOk}>
<DialogButtons
primaryButton={_t('Share location')}
cancelButtonClass="mx_LocationPicker_cancelButton"
primaryIsSubmit={true}
2021-12-06 09:45:12 +00:00
onPrimaryButtonClick={this.onOk}
onCancel={this.props.onFinished}
primaryDisabled={!this.state.position}
/>
2021-12-06 09:45:12 +00:00
</form>
</div>
<div className="mx_MLocationBody_marker" id={this.getMarkerId()}>
<div className="mx_MLocationBody_markerBorder">
<MemberAvatar
member={this.props.sender}
width={27}
height={27}
viewUserOnClick={false}
/>
</div>
2022-03-01 09:53:28 +01:00
<div
className="mx_MLocationBody_pointer"
/>
</div>
2021-12-06 09:45:12 +00:00
</div>
);
}
}
2021-12-17 10:58:24 +00:00
export function getGeoUri(position: GeolocationPosition): string {
2021-12-17 12:26:02 +00:00
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const alt = (
2021-12-21 16:56:28 +00:00
Number.isFinite(position.coords.altitude)
2021-12-17 12:26:02 +00:00
? `,${position.coords.altitude}`
: ""
);
const acc = (
2021-12-21 16:56:28 +00:00
Number.isFinite(position.coords.accuracy)
2021-12-17 12:26:02 +00:00
? `;u=${ position.coords.accuracy }`
: ""
);
return `geo:${lat},${lon}${alt}${acc}`;
2021-12-17 10:58:24 +00:00
}
2021-12-06 09:45:12 +00:00
export default LocationPicker;
function positionFailureMessage(code: number): string {
switch (code) {
case 1: return _t(
"Element was denied permission to fetch your location. " +
"Please allow location access in your browser settings.",
);
case 2: return _t(
"Failed to fetch your location. Please try again later.",
);
case 3: return _t(
"Timed out trying to fetch your location. Please try again later.",
);
case 4: return _t(
"Unknown error fetching location. Please try again later.",
);
}
}