Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Add option to find own location in map views #10083

Merged
merged 18 commits into from
Feb 13, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/components/views/beacon/BeaconViewDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ const BeaconViewDialog: React.FC<IProps> = ({ initialFocusedBeacon, roomId, matr
setFocusedBeaconState({ beacon, ts: Date.now() });
};

const hasOwnBeacon =
liveBeacons.filter((beacon) => beacon?.beaconInfoOwner === matrixClient.getUserId()).length > 0;

return (
<BaseDialog className="mx_BeaconViewDialog" onFinished={onFinished} fixedWidth={false}>
<MatrixClientContext.Provider value={matrixClient}>
Expand All @@ -136,6 +139,7 @@ const BeaconViewDialog: React.FC<IProps> = ({ initialFocusedBeacon, roomId, matr
interactive
onError={setMapDisplayError}
className="mx_BeaconViewDialog_map"
allowGeolocate={!hasOwnBeacon}
>
{({ map }: { map: maplibregl.Map }) => (
<>
Expand Down
21 changes: 1 addition & 20 deletions src/components/views/location/LocationPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@ import { ClientEvent, IClientWellKnown } from "matrix-js-sdk/src/client";
import { _t } from "../../../languageHandler";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import Modal from "../../../Modal";
import SdkConfig from "../../../SdkConfig";
import { tileServerFromWellKnown } from "../../../utils/WellKnownUtils";
import { GenericPosition, genericPositionFromGeolocation, getGeoUri } from "../../../utils/beacon";
import { LocationShareError, findMapStyleUrl } from "../../../utils/location";
import { LocationShareError, findMapStyleUrl, positionFailureMessage } from "../../../utils/location";
import ErrorDialog from "../dialogs/ErrorDialog";
import AccessibleButton from "../elements/AccessibleButton";
import { MapError } from "./MapError";
Expand Down Expand Up @@ -266,21 +265,3 @@ class LocationPicker extends React.Component<ILocationPickerProps, IState> {
}

export default LocationPicker;

function positionFailureMessage(code: number): string {
const brand = SdkConfig.get().brand;
switch (code) {
case 1:
return _t(
"%(brand)s was denied permission to fetch your location. " +
"Please allow location access in your browser settings.",
{ brand },
);
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.");
}
}
1 change: 1 addition & 0 deletions src/components/views/location/LocationViewDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export default class LocationViewDialog extends React.Component<IProps, IState>
onError={this.onError}
interactive
className="mx_LocationViewDialog_map"
allowGeolocate={true}
>
{({ map }) => (
<>
Expand Down
57 changes: 51 additions & 6 deletions src/components/views/location/Map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,38 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import React, { ReactNode, useContext, useEffect } from "react";
import React, { ReactNode, useContext, useEffect, useState } from "react";
import classNames from "classnames";
import * as maplibregl from "maplibre-gl";
import { ClientEvent, IClientWellKnown } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";

import MatrixClientContext from "../../../contexts/MatrixClientContext";
import { useEventEmitterState } from "../../../hooks/useEventEmitter";
import { parseGeoUri } from "../../../utils/location";
import { parseGeoUri, positionFailureMessage } from "../../../utils/location";
import { tileServerFromWellKnown } from "../../../utils/WellKnownUtils";
import { useMap } from "../../../utils/location/useMap";
import { Bounds } from "../../../utils/beacon/bounds";
import Modal from "../../../Modal";
import ErrorDialog from "../dialogs/ErrorDialog";
import { _t } from "../../../languageHandler";

const useMapWithStyle = ({
id,
centerGeoUri,
onError,
interactive,
bounds,
allowGeolocate,
}: {
id: string;
centerGeoUri?: string;
onError?(error: Error): void;
interactive?: boolean;
bounds?: Bounds;
onError(error: Error): void;
allowGeolocate?: boolean;
}): {
map: maplibregl.Map;
map: maplibregl.Map | undefined;
bodyId: string;
} => {
const bodyId = `mx_Map_${id}`;
Expand Down Expand Up @@ -86,12 +91,41 @@ const useMapWithStyle = ({
}
}, [map, bounds]);

const [geolocate] = useState(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the rest of the map configurations this component (or useMap) will react to changes in props. This will only set geolocation according to the initial value of allowGeolocate. If it's easy to make it react to changes in allowGeolocate that would be great, otherwise maybe could add a comment saying explicitly that it will not update geolocation settings after mounting.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took a stab at it. Let me know if this looks ok.

allowGeolocate
? new maplibregl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true,
},
trackUserLocation: false,
})
: null,
);

useEffect(() => {
if (map && geolocate) {
map.addControl(geolocate);
geolocate.on("error", onGeolocateError);
return () => {
Johennes marked this conversation as resolved.
Show resolved Hide resolved
geolocate.off("error", onGeolocateError);
};
}
}, [map, geolocate]);

return {
map,
bodyId,
};
};

const onGeolocateError = (e: GeolocationPositionError): void => {
logger.error("Could not fetch location", e);
Modal.createDialog(ErrorDialog, {
title: _t("Could not fetch location"),
description: positionFailureMessage(e.code) ?? "",
});
};

interface MapProps {
id: string;
interactive?: boolean;
Expand All @@ -105,13 +139,24 @@ interface MapProps {
centerGeoUri?: string;
bounds?: Bounds;
className?: string;
allowGeolocate?: boolean;
onClick?: () => void;
onError?: (error: Error) => void;
children?: (renderProps: { map: maplibregl.Map }) => ReactNode;
}

const Map: React.FC<MapProps> = ({ bounds, centerGeoUri, children, className, id, interactive, onError, onClick }) => {
const { map, bodyId } = useMapWithStyle({ centerGeoUri, onError, id, interactive, bounds });
const Map: React.FC<MapProps> = ({
bounds,
centerGeoUri,
children,
className,
allowGeolocate,
id,
interactive,
onError,
onClick,
}) => {
const { map, bodyId } = useMapWithStyle({ centerGeoUri, onError, id, interactive, bounds, allowGeolocate });

const onMapClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>): void => {
// Eat click events when clicking the attribution button
Expand Down
8 changes: 4 additions & 4 deletions src/i18n/strings/en_EN.json
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,10 @@
"Reset bearing to north": "Reset bearing to north",
"Zoom in": "Zoom in",
"Zoom out": "Zoom out",
"%(brand)s was denied permission to fetch your location. Please allow location access in your browser settings.": "%(brand)s was denied permission to fetch your location. Please allow location access in your browser settings.",
"Failed to fetch your location. Please try again later.": "Failed to fetch your location. Please try again later.",
"Timed out trying to fetch your location. Please try again later.": "Timed out trying to fetch your location. Please try again later.",
"Unknown error fetching location. Please try again later.": "Unknown error fetching location. Please try again later.",
"Are you sure you want to exit during this export?": "Are you sure you want to exit during this export?",
"Unnamed Room": "Unnamed Room",
"Generating a ZIP": "Generating a ZIP",
Expand Down Expand Up @@ -2449,10 +2453,6 @@
"Click to move the pin": "Click to move the pin",
"Click to drop a pin": "Click to drop a pin",
"Share location": "Share location",
"%(brand)s was denied permission to fetch your location. Please allow location access in your browser settings.": "%(brand)s was denied permission to fetch your location. Please allow location access in your browser settings.",
"Failed to fetch your location. Please try again later.": "Failed to fetch your location. Please try again later.",
"Timed out trying to fetch your location. Please try again later.": "Timed out trying to fetch your location. Please try again later.",
"Unknown error fetching location. Please try again later.": "Unknown error fetching location. Please try again later.",
"You don't have permission to share locations": "You don't have permission to share locations",
"You need to have the right permissions in order to share locations in this room.": "You need to have the right permissions in order to share locations in this room.",
"We couldn't send your location": "We couldn't send your location",
Expand Down
1 change: 1 addition & 0 deletions src/utils/location/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ export * from "./locationEventGeoUri";
export * from "./LocationShareErrors";
export * from "./map";
export * from "./parseGeoUri";
export * from "./positionFailureMessage";
36 changes: 36 additions & 0 deletions src/utils/location/positionFailureMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
Copyright 2023 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.
*/

import { _t } from "../../languageHandler";
import SdkConfig from "../../SdkConfig";

export const positionFailureMessage = (code: number): string | undefined => {
const brand = SdkConfig.get().brand;
switch (code) {
case 1:
return _t(
"%(brand)s was denied permission to fetch your location. " +
"Please allow location access in your browser settings.",
{ brand },
);
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.");
}
};
4 changes: 2 additions & 2 deletions src/utils/location/useMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { createMap } from "./map";

interface UseMapProps {
bodyId: string;
onError: (error: Error) => void;
onError?: (error: Error) => void;
interactive?: boolean;
}

Expand All @@ -39,7 +39,7 @@ export const useMap = ({ interactive, bodyId, onError }: UseMapProps): MapLibreM
try {
setMap(createMap(interactive, bodyId, onError));
} catch (error) {
onError(error);
onError?.(error);
}
return () => {
if (map) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

exports[`<LocationViewDialog /> renders map correctly 1`] = `
<Map
allowGeolocate={true}
centerGeoUri="geo:51.5076,-0.1276"
className="mx_LocationViewDialog_map"
id="mx_LocationViewDialog_$2"
Expand Down Expand Up @@ -29,12 +30,27 @@ exports[`<LocationViewDialog /> renders map correctly 1`] = `
MockAttributionControl {},
"top-right",
],
[
MockGeolocateControl {
"_events": {
"error": [Function],
},
"_eventsCount": 1,
"_maxListeners": undefined,
"trigger": [MockFunction],
Symbol(kCapture): false,
},
],
],
"results": [
{
"type": "return",
"value": undefined,
},
{
"type": "return",
"value": undefined,
},
],
},
"fitBounds": [MockFunction],
Expand Down Expand Up @@ -97,12 +113,27 @@ exports[`<LocationViewDialog /> renders map correctly 1`] = `
MockAttributionControl {},
"top-right",
],
[
MockGeolocateControl {
"_events": {
"error": [Function],
},
"_eventsCount": 1,
"_maxListeners": undefined,
"trigger": [MockFunction],
Symbol(kCapture): false,
},
],
],
"results": [
{
"type": "return",
"value": undefined,
},
{
"type": "return",
"value": undefined,
},
],
},
"fitBounds": [MockFunction],
Expand Down
2 changes: 1 addition & 1 deletion test/components/views/messages/MBeaconBody-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ describe("<MBeaconBody />", () => {
beforeEach(() => {
// mock map utils to raise MapStyleUrlNotConfigured error
jest.spyOn(mapUtilHooks, "useMap").mockImplementation(({ onError }) => {
onError(new Error(LocationShareError.MapStyleUrlNotConfigured));
onError?.(new Error(LocationShareError.MapStyleUrlNotConfigured));
return mockMap;
});
});
Expand Down