Skip to content

Commit 1397652

Browse files
author
Kerry
authored
Extract location utils from components (matrix-org#8152)
* extract util functions from MLocationBody Signed-off-by: Kerry Archibald <[email protected]> * disassemble mlocationbody Signed-off-by: Kerry Archibald <[email protected]> * tidy and add copyrights Signed-off-by: Kerry Archibald <[email protected]> * move types and utils from components/location to utils Signed-off-by: Kerry Archibald <[email protected]> * i18n Signed-off-by: Kerry Archibald <[email protected]> * empty line Signed-off-by: Kerry Archibald <[email protected]>
1 parent 0d513b3 commit 1397652

20 files changed

+496
-350
lines changed

src/components/views/context_menus/MessageContextMenu.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ import { ComposerInsertPayload } from "../../../dispatcher/payloads/ComposerInse
4747
import { WidgetLayoutStore } from '../../../stores/widgets/WidgetLayoutStore';
4848
import EndPollDialog from '../dialogs/EndPollDialog';
4949
import { isPollEnded } from '../messages/MPollBody';
50-
import { createMapSiteLink } from "../messages/MLocationBody";
5150
import { ViewRoomPayload } from "../../../dispatcher/payloads/ViewRoomPayload";
51+
import { createMapSiteLink } from '../../../utils/location';
5252

5353
export function canCancel(status: EventStatus): boolean {
5454
return status === EventStatus.QUEUED || status === EventStatus.NOT_SENT || status === EventStatus.ENCRYPTING;

src/components/views/location/LocationPicker.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,16 @@ import MatrixClientContext from '../../../contexts/MatrixClientContext';
2828
import Modal from '../../../Modal';
2929
import ErrorDialog from '../dialogs/ErrorDialog';
3030
import { tileServerFromWellKnown } from '../../../utils/WellKnownUtils';
31-
import { findMapStyleUrl } from './findMapStyleUrl';
3231
import { LocationShareType, ShareLocationFn } from './shareLocation';
3332
import { Icon as LocationIcon } from '../../../../res/img/element-icons/location.svg';
34-
import { LocationShareError } from './LocationShareErrors';
3533
import AccessibleButton from '../elements/AccessibleButton';
3634
import { MapError } from './MapError';
3735
import { getUserNameColorClass } from '../../../utils/FormattingUtils';
3836
import LiveDurationDropdown, { DEFAULT_DURATION_MS } from './LiveDurationDropdown';
3937
import { GenericPosition, genericPositionFromGeolocation, getGeoUri } from '../../../utils/beacon';
4038
import SdkConfig from '../../../SdkConfig';
39+
import { LocationShareError, findMapStyleUrl } from '../../../utils/location';
40+
4141
export interface ILocationPickerProps {
4242
sender: RoomMember;
4343
shareType: LocationShareType;

src/components/views/location/LocationViewDialog.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@ import { ClientEvent, IClientWellKnown, MatrixClient } from 'matrix-js-sdk/src/c
2121
import { replaceableComponent } from "../../../utils/replaceableComponent";
2222
import BaseDialog from "../dialogs/BaseDialog";
2323
import { IDialogProps } from "../dialogs/IDialogProps";
24-
import { createMap, LocationBodyContent, locationEventGeoUri, parseGeoUri } from '../messages/MLocationBody';
24+
import { LocationBodyContent } from '../messages/MLocationBody';
2525
import { tileServerFromWellKnown } from '../../../utils/WellKnownUtils';
26+
import { parseGeoUri, locationEventGeoUri, createMap } from '../../../utils/location';
2627

2728
interface IProps extends IDialogProps {
2829
matrixClient: MatrixClient;

src/components/views/location/MapError.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ import React from 'react';
1818

1919
import { Icon as WarningBadge } from '../../../../res/img/element-icons/warning-badge.svg';
2020
import { _t } from '../../../languageHandler';
21+
import { getLocationShareErrorMessage, LocationShareError } from '../../../utils/location';
2122
import AccessibleButton from '../elements/AccessibleButton';
2223
import Heading from '../typography/Heading';
23-
import { getLocationShareErrorMessage, LocationShareError } from './LocationShareErrors';
2424

2525
interface Props {
2626
onFinished: () => void;

src/components/views/messages/MLocationBody.tsx

Lines changed: 7 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,11 @@ limitations under the License.
1616

1717
import React from 'react';
1818
import maplibregl from 'maplibre-gl';
19-
import { logger } from "matrix-js-sdk/src/logger";
2019
import { MatrixEvent } from 'matrix-js-sdk/src/models/event';
2120
import {
2221
M_ASSET,
2322
LocationAssetType,
2423
ILocationContent,
25-
M_LOCATION,
2624
} from 'matrix-js-sdk/src/@types/location';
2725
import { ClientEvent, IClientWellKnown } from 'matrix-js-sdk/src/client';
2826

@@ -31,14 +29,19 @@ import { IBodyProps } from "./IBodyProps";
3129
import { _t } from '../../../languageHandler';
3230
import MemberAvatar from '../avatars/MemberAvatar';
3331
import Modal from '../../../Modal';
32+
import {
33+
parseGeoUri,
34+
locationEventGeoUri,
35+
createMap,
36+
getLocationShareErrorMessage,
37+
LocationShareError,
38+
} from '../../../utils/location';
3439
import LocationViewDialog from '../location/LocationViewDialog';
3540
import TooltipTarget from '../elements/TooltipTarget';
3641
import { Alignment } from '../elements/Tooltip';
3742
import AccessibleButton from '../elements/AccessibleButton';
3843
import { tileServerFromWellKnown } from '../../../utils/WellKnownUtils';
3944
import MatrixClientContext from '../../../contexts/MatrixClientContext';
40-
import { findMapStyleUrl } from '../location/findMapStyleUrl';
41-
import { getLocationShareErrorMessage, LocationShareError } from '../location/LocationShareErrors';
4245

4346
interface IState {
4447
error: Error;
@@ -238,114 +241,3 @@ function ZoomButtons(props: IZoomButtonsProps): React.ReactElement<HTMLDivElemen
238241
</div>;
239242
}
240243

241-
export function createMap(
242-
coords: GeolocationCoordinates,
243-
interactive: boolean,
244-
bodyId: string,
245-
markerId: string,
246-
onError: (error: Error) => void,
247-
): maplibregl.Map {
248-
try {
249-
const styleUrl = findMapStyleUrl();
250-
const coordinates = new maplibregl.LngLat(coords.longitude, coords.latitude);
251-
252-
const map = new maplibregl.Map({
253-
container: bodyId,
254-
style: styleUrl,
255-
center: coordinates,
256-
zoom: 15,
257-
interactive,
258-
});
259-
260-
new maplibregl.Marker({
261-
element: document.getElementById(markerId),
262-
anchor: 'bottom',
263-
offset: [0, -1],
264-
})
265-
.setLngLat(coordinates)
266-
.addTo(map);
267-
268-
map.on('error', (e) => {
269-
logger.error(
270-
"Failed to load map: check map_style_url in config.json has a "
271-
+ "valid URL and API key",
272-
e.error,
273-
);
274-
onError(new Error(LocationShareError.MapStyleUrlNotReachable));
275-
});
276-
277-
return map;
278-
} catch (e) {
279-
logger.error("Failed to render map", e);
280-
onError(e);
281-
}
282-
}
283-
284-
/**
285-
* Find the geo-URI contained within a location event.
286-
*/
287-
export function locationEventGeoUri(mxEvent: MatrixEvent): string {
288-
// unfortunately we're stuck supporting legacy `content.geo_uri`
289-
// events until the end of days, or until we figure out mutable
290-
// events - so folks can read their old chat history correctly.
291-
// https://github.com/matrix-org/matrix-doc/issues/3516
292-
const content = mxEvent.getContent();
293-
const loc = M_LOCATION.findIn(content) as { uri?: string };
294-
return loc ? loc.uri : content['geo_uri'];
295-
}
296-
297-
export function parseGeoUri(uri: string): GeolocationCoordinates {
298-
function parse(s: string): number {
299-
const ret = parseFloat(s);
300-
if (Number.isNaN(ret)) {
301-
return undefined;
302-
} else {
303-
return ret;
304-
}
305-
}
306-
307-
const m = uri.match(/^\s*geo:(.*?)\s*$/);
308-
if (!m) return;
309-
const parts = m[1].split(';');
310-
const coords = parts[0].split(',');
311-
let uncertainty: number;
312-
for (const param of parts.slice(1)) {
313-
const m = param.match(/u=(.*)/);
314-
if (m) uncertainty = parse(m[1]);
315-
}
316-
return {
317-
latitude: parse(coords[0]),
318-
longitude: parse(coords[1]),
319-
altitude: parse(coords[2]),
320-
accuracy: uncertainty,
321-
altitudeAccuracy: undefined,
322-
heading: undefined,
323-
speed: undefined,
324-
};
325-
}
326-
327-
function makeLink(coords: GeolocationCoordinates): string {
328-
return (
329-
"https://www.openstreetmap.org/" +
330-
`?mlat=${coords.latitude}` +
331-
`&mlon=${coords.longitude}` +
332-
`#map=16/${coords.latitude}/${coords.longitude}`
333-
);
334-
}
335-
336-
export function createMapSiteLink(event: MatrixEvent): string {
337-
const content: Object = event.getContent();
338-
const mLocation = content[M_LOCATION.name];
339-
if (mLocation !== undefined) {
340-
const uri = mLocation["uri"];
341-
if (uri !== undefined) {
342-
return makeLink(parseGeoUri(uri));
343-
}
344-
} else {
345-
const geoUri = content["geo_uri"];
346-
if (geoUri) {
347-
return makeLink(parseGeoUri(geoUri));
348-
}
349-
}
350-
return null;
351-
}

src/i18n/strings/en_EN.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,8 @@
734734
"Invite to %(spaceName)s": "Invite to %(spaceName)s",
735735
"Share your public space": "Share your public space",
736736
"Unknown App": "Unknown App",
737+
"This homeserver is not configured to display maps.": "This homeserver is not configured to display maps.",
738+
"This homeserver is not configured correctly to display maps, or the configured map server may be unreachable.": "This homeserver is not configured correctly to display maps, or the configured map server may be unreachable.",
737739
"Are you sure you want to exit during this export?": "Are you sure you want to exit during this export?",
738740
"Generating a ZIP": "Generating a ZIP",
739741
"Fetched %(count)s events out of %(total)s|other": "Fetched %(count)s events out of %(total)s",
@@ -2144,8 +2146,6 @@
21442146
"Failed to fetch your location. Please try again later.": "Failed to fetch your location. Please try again later.",
21452147
"Timed out trying to fetch your location. Please try again later.": "Timed out trying to fetch your location. Please try again later.",
21462148
"Unknown error fetching location. Please try again later.": "Unknown error fetching location. Please try again later.",
2147-
"This homeserver is not configured to display maps.": "This homeserver is not configured to display maps.",
2148-
"This homeserver is not configured correctly to display maps, or the configured map server may be unreachable.": "This homeserver is not configured correctly to display maps, or the configured map server may be unreachable.",
21492149
"We couldn't send your location": "We couldn't send your location",
21502150
"%(brand)s could not send your location. Please try again later.": "%(brand)s could not send your location. Please try again later.",
21512151
"%(displayName)s's live location": "%(displayName)s's live location",

src/components/views/location/LocationShareErrors.ts renamed to src/utils/location/LocationShareErrors.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17-
import { _t } from "../../../languageHandler";
17+
import { _t } from "../../languageHandler";
1818

1919
export enum LocationShareError {
2020
MapStyleUrlNotConfigured = 'MapStyleUrlNotConfigured',

src/components/views/location/findMapStyleUrl.ts renamed to src/utils/location/findMapStyleUrl.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ limitations under the License.
1616

1717
import { logger } from "matrix-js-sdk/src/logger";
1818

19-
import SdkConfig from "../../../SdkConfig";
20-
import { getTileServerWellKnown } from "../../../utils/WellKnownUtils";
19+
import SdkConfig from "../../SdkConfig";
20+
import { getTileServerWellKnown } from "../WellKnownUtils";
2121
import { LocationShareError } from "./LocationShareErrors";
2222

2323
/**

src/utils/location/index.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
export * from './findMapStyleUrl';
18+
export * from './locationEventGeoUri';
19+
export * from './LocationShareErrors';
20+
export * from './map';
21+
export * from './parseGeoUri';
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import { MatrixEvent } from "matrix-js-sdk/src/matrix";
18+
import { M_LOCATION } from "matrix-js-sdk/src/@types/location";
19+
20+
/**
21+
* Find the geo-URI contained within a location event.
22+
*/
23+
export const locationEventGeoUri = (mxEvent: MatrixEvent): string => {
24+
// unfortunately we're stuck supporting legacy `content.geo_uri`
25+
// events until the end of days, or until we figure out mutable
26+
// events - so folks can read their old chat history correctly.
27+
// https://github.com/matrix-org/matrix-doc/issues/3516
28+
const content = mxEvent.getContent();
29+
const loc = M_LOCATION.findIn(content) as { uri?: string };
30+
return loc ? loc.uri : content['geo_uri'];
31+
};

0 commit comments

Comments
 (0)