implement sharing map locations

Signed-off-by: Shea <[email protected]>
This commit is contained in:
Shea committed 2026-06-09 10:30:53 +03:00
1 parent 9b6f2fbd79
commit d56f9bf6e9
8 files changed
+474 -34

No files matched your search

+2 -1
View File
@@ -431,7 +431,8 @@ function RenderMessageContentInternal({
}
if (msgType === (MsgType.File as string)) return renderFile();
if (msgType === (MsgType.Location as string)) return <MLocation showMaps={showMaps} content={content} />;
if (msgType === (MsgType.Location as string))
return <MLocation showMaps={showMaps} content={content} />;
if (msgType === 'm.bad.encrypted') return <MBadEncrypted />;
// cute events
+16 -14
View File
@@ -35,10 +35,10 @@ import { MessageTextBody } from './layout';
import { unwrapForwardedContent } from './modals/MessageForward';
import { LINKINPUTREGEX } from '$components/editor';
import { MATRIX_TO_BASE } from '$plugins/matrix-to';
import { copyToClipboard } from '$utils/dom';
import { MapContainer, Marker, TileLayer } from 'react-leaflet';
import type { LatLngExpression } from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { copyToClipboard } from '$utils/dom';
export interface BundleContent extends IPreviewUrlResponse {
matched_url: string;
@@ -685,26 +685,28 @@ export function MLocation({ content, showMaps }: MLocationProps) {
rel="noreferrer noopener"
variant="Primary"
radii="Pill"
style={{ flexShrink: '0' }}
before={<Icon src={Icons.External} size="50" />}
>
<Text size="B300">Open Location</Text>
</Chip>
</Box>
{showMaps && (
<MapContainer
center={coords}
zoom={16}
scrollWheelZoom={true}
style={{ height: toRem(400) }}
attributionControl
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap Contributors</a>'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapContainer
center={coords}
zoom={16}
scrollWheelZoom={true}
style={{ height: toRem(400) }}
attributionControl
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={coords} draggable></Marker>
</MapContainer>)}
<Marker position={coords}></Marker>
</MapContainer>
)}
</Box>
);
}
+33 -12
View File
@@ -129,7 +129,7 @@ import {
convertPerMessageProfileToBeeperFormat,
getCurrentlyUsedPerMessageProfileForRoom,
} from '$hooks/usePerMessageProfile';
import { Microphone, Stop } from '@phosphor-icons/react';
import { Microphone, Stop, MapPinPlusIcon } from '@phosphor-icons/react';
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
import { ErrorCode } from '../../cs-errorcode';
import { sanitizeText } from '$utils/sanitize';
@@ -160,6 +160,7 @@ import type {
import { AudioMessageRecorder } from './AudioMessageRecorder';
import * as prefix from '$unstable/prefixes';
import { PollDialog } from './poll-modals';
import { LocationDialog } from './location-modal';
// Returns the event ID of the most recent non-reaction/non-edit event in a thread,
// falling back to the thread root if no replies exist yet.
@@ -389,6 +390,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
);
const [AddMenuAnchor, setAddMenuAnchor] = useState<RectCords>();
const [showPollPicker, setShowPollPicker] = useState(false);
const [showLocationPicker, setShowLocationPicker] = useState(false);
const [scheduleMenuAnchor, setScheduleMenuAnchor] = useState<RectCords>();
const [showSchedulePicker, setShowSchedulePicker] = useState(false);
const [silentReply, setSilentReply] = useState(!mentionInReplies);
@@ -822,16 +824,15 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
} else if (commandName === Command.UnFlip) {
plainText = `${UNFLIP} ${plainText}`;
customHtml = `${UNFLIP} ${customHtml}`;
} else if (commandName === Command.Poll) {
setShowPollPicker(true);
resetEditor(editor);
resetEditorHistory(editor);
sendTypingStatus(false);
return;
} else if (commandName) {
const commandContent = commands[commandName as Command];
if (commandContent) {
commandContent.exe(plainText, customHtml);
if ((commandName as Command) === Command.Poll) setShowPollPicker(true);
else if ((commandName as Command) === Command.Location && plainText.trim().length === 0)
setShowLocationPicker(true);
else {
const commandContent = commands[commandName as Command];
if (commandContent) {
commandContent.exe(plainText, customHtml);
}
}
resetEditor(editor);
resetEditorHistory(editor);
@@ -1561,6 +1562,17 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
>
<Text size="B300">Create Poll</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
onClick={() => {
setAddMenuAnchor(undefined);
setShowLocationPicker(true);
}}
before={<MapPinPlusIcon size="20" />}
>
<Text size="B300">Add Location</Text>
</MenuItem>
<MenuItem
size="300"
radii="300"
@@ -1586,8 +1598,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
variant="SurfaceVariant"
size="300"
radii="300"
title="Upload File"
aria-label="Upload and attach a File"
title={editorOldAddFile ? 'Upload File' : 'Add'}
aria-label={editorOldAddFile ? 'Upload and attach a File' : 'Add more menu'}
>
<Icon src={Icons.PlusCircle} />
</IconButton>
@@ -1843,6 +1855,15 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
clearReplyDraft={() => setReplyDraft(undefined)}
/>
)}
{showLocationPicker && (
<LocationDialog
onCancel={() => setShowLocationPicker(false)}
mx={mx}
room={room}
replyDraft={replyDraft}
clearReplyDraft={() => setReplyDraft(undefined)}
/>
)}
</div>
);
}
@@ -0,0 +1,53 @@
import { style } from '@vanilla-extract/css';
import { color, config, toRem } from 'folds';
export const LocationDialogBody = style({
maxWidth: toRem(500),
borderRadius: config.radii.R500,
padding: config.space.S200,
textAlign: 'justify',
});
export const LocationDialogHeader = style({
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
borderBottomWidth: config.borderWidth.B300,
});
export const LocationDialogTitle = style({
padding: config.space.S400,
alignItems: 'center',
textAlign: 'center',
});
export const LocationInputs = style({
width: '100%',
});
export const LocationInputItem = style({
textAlign: 'center',
width: '100%',
justifyContent: 'center',
flexShrink: '1',
});
export const LocationInputField = style({
textAlign: 'center',
});
export const LocationInputCurLocation = style({
textAlign: 'center',
width: '60%',
justifyContent: 'center',
flexShrink: '1',
});
export const LocationInputClipboard = style({
textAlign: 'center',
width: '40%',
justifyContent: 'center',
flexShrink: '1',
});
export const LocationDialogAnswerInput = style({ width: '100%' });
export const LocationDialogMaxSelectionSlider = style({
width: '100%',
cursor: 'pointer',
appearance: 'none',
height: toRem(6),
borderRadius: config.radii.Pill,
backgroundColor: color.Background.ContainerLine,
accentColor: color.Primary.Main,
});
@@ -0,0 +1,361 @@
import FocusTrap from 'focus-trap-react';
import {
Dialog,
Overlay,
OverlayCenter,
OverlayBackdrop,
Header,
Box,
Text,
IconButton,
Icon,
Icons,
Button,
Input,
toRem,
config,
Chip,
color,
} from 'folds';
import { ClipboardIcon, MapPinAreaIcon, MapPinLineIcon } from '@phosphor-icons/react';
import { stopPropagation } from '$utils/keyboard';
import type { IContent, MatrixClient, Room } from 'matrix-js-sdk';
import * as css from './LocationDialog.css';
import type { IReplyDraft } from '$state/room/roomInputDrafts';
import { MapContainer, Marker, TileLayer, useMapEvents } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import { useCallback, useEffect, useRef, useState, type ChangeEventHandler } from 'react';
import type { LatLngLiteral } from 'leaflet';
import L from 'leaflet';
import { getReplyContent } from '../RoomInput';
import type { RoomMessageEventContent } from '$types/matrix-sdk';
import { settingsAtom } from '$state/settings';
import { useSetting } from '$state/hooks/settings';
import classNames from 'classnames';
type LocationDialogProps = {
onCancel: () => void;
mx: MatrixClient;
room: Room;
replyDraft?: IReplyDraft;
clearReplyDraft?: () => void;
};
enum locationErrors {
none,
permissions = 'You have denied Sable access to you location services',
module = 'Your device does not have a gps module, or it may not be turned on',
unknown = 'The sharing failed for unknown reasons',
clipboard = 'Unable to identify the coordonates from clipboard',
}
export function LocationDialog({
onCancel,
mx,
room,
replyDraft,
clearReplyDraft,
}: LocationDialogProps) {
const [showInteractiveMap] = useSetting(settingsAtom, 'showInteractiveMap');
const [showEncInteractiveMap] = useSetting(settingsAtom, 'showEncInteractiveMap');
const showMaps = room.hasEncryptionStateEvent() ? showEncInteractiveMap : showInteractiveMap;
const initCoords = { lat: 43.959971, lng: -59.790623 };
const [inputPosition, setInputPosition] = useState<{ lat: string; lng: string }>({
lat: initCoords.lat.toPrecision(6),
lng: initCoords.lng.toPrecision(6),
});
const [pinPosition, setPinPosition] = useState<L.LatLngLiteral>(initCoords);
const zoom = useRef<number>(2);
const [locationError, setLocationError] = useState<locationErrors>(locationErrors.none);
const [map, setMap] = useState<L.Map | null>(null);
const onMove = useCallback(() => {
if (map?.getCenter() && map?.getZoom()) {
zoom.current = map?.getZoom();
}
}, [map]);
useEffect(() => {
map?.on('move', onMove);
return () => {
map?.off('move', onMove);
};
}, [map, onMove]);
const movePin = useCallback(
(pos: LatLngLiteral) => {
if (!map) return;
map.eachLayer((layer) => {
if (layer instanceof L.Marker) {
map.removeLayer(layer);
}
});
L.marker(pos).addTo(map);
map.panTo(pos);
},
[map]
);
const MapEvents = () => {
useMapEvents({
click(e) {
// setPinPosition(e.latlng);
if (map) {
movePin(e.latlng);
setInputPosition({ lat: e.latlng.lat.toFixed(6), lng: e.latlng.lng.toFixed(6) });
setPinPosition({ lat: e.latlng.lat, lng: e.latlng.lng });
}
},
});
return false;
};
function getLocation() {
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
};
function success(pos: GeolocationPosition) {
const crd = pos.coords;
const coords = { lat: crd.latitude, lng: crd.longitude };
if (!coords.lat || !coords.lng) {
setLocationError(locationErrors.unknown);
return;
}
setPinPosition(coords);
setInputPosition({ lat: coords.lat.toFixed(6), lng: coords.lng.toFixed(6) });
movePin(coords);
setLocationError(locationErrors.none);
}
function error(err: GeolocationPositionError) {
if (err.code === 1) setLocationError(locationErrors.permissions);
else if (err.code === 2) setLocationError(locationErrors.module);
else setLocationError(locationErrors.unknown);
}
navigator.geolocation.getCurrentPosition(success, error, options);
}
function getClipboard() {
function storeLocation(lat: number, lng: number) {
movePin({ lat, lng });
setInputPosition({ lat: lat.toFixed(6), lng: lng.toFixed(6) });
setPinPosition({ lat, lng });
setLocationError(locationErrors.none);
}
navigator.clipboard.readText().then((result) => {
// OSM format
if (result.toLowerCase().includes('mlat=') && result.toLowerCase().includes('mlon=')) {
const tokenizedResult = result.toLowerCase().split(/[ ,&?;::]/);
const coords: { mlat?: string; mlng?: string } = {
mlat: tokenizedResult.find((item) => item.includes('mlat='))?.substring(5),
mlng: tokenizedResult.find((item) => item.includes('mlon='))?.substring(5),
};
if (coords.mlat && coords.mlng) {
const mlat = Number.parseFloat(coords.mlat);
const mlng = Number.parseFloat(coords.mlng);
if (!Number.isNaN(mlat) && !Number.isNaN(mlng)) {
storeLocation(mlat, mlng);
return;
}
}
}
// Fallback the center of the map on OSM
if (result.toLowerCase().includes('#map=')) {
const coords: string[] = result
.substring(result.toLowerCase().indexOf('#map=') + 5)
.split(/[, /]/);
if (coords.length >= 3 && typeof coords[1] === 'string' && typeof coords[2] === 'string') {
const mlat = Number.parseFloat(coords[1]);
const mlng = Number.parseFloat(coords[2]);
if (!Number.isNaN(mlat) && !Number.isNaN(mlng)) {
storeLocation(mlat, mlng);
return;
}
}
}
// geo tags or just putting the numbers without any formatting next to the other
const coords = result.split(/[, ;:]/).filter((item) => item.length && item !== 'geo');
if (coords.length >= 2 && typeof coords[0] === 'string' && typeof coords[1] === 'string') {
const mlat = Number.parseFloat(coords[0]);
const mlng = Number.parseFloat(coords[1]);
if (!Number.isNaN(mlat) && !Number.isNaN(mlng)) {
storeLocation(mlat, mlng);
return;
}
}
setLocationError(locationErrors.clipboard);
});
}
const handleLat: ChangeEventHandler<HTMLInputElement> = (evt) => {
const val = evt.target.value;
const parsed = Number.parseFloat(val);
setInputPosition({ lat: val, lng: inputPosition.lng });
if (!Number.isNaN(parsed) && parsed >= -90 && parsed <= 90) {
movePin({ lat: parsed, lng: pinPosition.lng });
setPinPosition({ lat: parsed, lng: pinPosition.lng });
}
};
const handleLng: ChangeEventHandler<HTMLInputElement> = (evt) => {
const val = evt.target.value;
const parsed = Number.parseFloat(val);
setInputPosition({ lat: inputPosition.lat, lng: val });
if (!Number.isNaN(parsed) && parsed >= -180 && parsed <= 180) {
movePin({ lat: pinPosition.lat, lng: parsed });
setPinPosition({ lat: pinPosition.lat, lng: parsed });
}
};
const handleSubmit = () => {
const mlat = pinPosition.lat.toFixed(6);
const mlon = pinPosition.lng.toFixed(6);
const content: IContent = {
msgtype: 'm.location',
geo_uri: `geo:${mlat},${mlon};u=0`,
body: `https://www.openstreetmap.org/?mlat=${mlat}&mlon=${mlon}#map=16/${mlat}/${mlon}"`,
};
if (replyDraft && clearReplyDraft) {
content['m.relates_to'] = getReplyContent(replyDraft, room);
clearReplyDraft();
}
mx.sendMessage(room.roomId, content as RoomMessageEventContent).then(() => {
onCancel();
});
};
return (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: onCancel,
clickOutsideDeactivates: true,
escapeDeactivates: stopPropagation,
}}
>
<Dialog variant="Surface" className={css.LocationDialogBody}>
<Header className={css.LocationDialogHeader} variant="Surface" size="500">
<Box grow="Yes" gap="200">
<MapPinLineIcon size="20" />
<Text size="H4">{`Share Location ${replyDraft ? '(reply / thread)' : ''}`} </Text>
</Box>
<IconButton
size="300"
onClick={onCancel}
radii="300"
title="Cancel Sharing Location"
aria-label="Cancel Sharing Location"
>
<Icon src={Icons.Cross} />
</IconButton>
</Header>
<Box direction="Column" gap="200" className={css.LocationDialogTitle}>
<Box direction="Row" style={{ width: '100%' }}>
<Chip
variant={
locationError === locationErrors.none ||
locationError === locationErrors.clipboard
? 'Primary'
: 'Critical'
}
className={classNames(css.LocationInputItem, css.LocationInputCurLocation)}
onClick={getLocation}
before={<MapPinAreaIcon size="18" />}
>
<Text className={css.LocationInputField}>Share Current Location</Text>
</Chip>
<Chip
variant={locationError !== locationErrors.clipboard ? 'Secondary' : 'Critical'}
className={classNames(css.LocationInputItem, css.LocationInputClipboard)}
onClick={getClipboard}
before={<ClipboardIcon size="18" />}
>
<Text className={css.LocationInputField}>Paste Clipboard</Text>
</Chip>
</Box>
{locationError !== locationErrors.none && (
<Box style={{ color: color.Critical.Main }}>
<Icon size="50" src={Icons.Warning} />
<Text size="L400">{locationError}</Text>
</Box>
)}
<Box direction="Row" gap="100" className={css.LocationInputs}>
<Box direction="Column" className={css.LocationInputItem}>
<Text size="T200">Latitude</Text>
<Input
className={css.LocationInputField}
variant={'SurfaceVariant'}
size="300"
radii="300"
type="number"
min={-180}
max={180}
value={inputPosition.lat}
onChange={handleLat}
outlined
/>
</Box>
<Box direction="Column" className={css.LocationInputItem}>
<Text size="T200">Longitude</Text>
<Input
className={css.LocationInputField}
variant={'SurfaceVariant'}
size="300"
radii="300"
type="number"
min={-180}
max={180}
value={inputPosition.lng}
onChange={handleLng}
outlined
/>
</Box>
</Box>
{showMaps && (
<Box
style={{
width: '100%',
height: toRem(400),
borderRadius: config.radii.R400,
overflow: 'hidden',
}}
>
<MapContainer
center={initCoords}
zoom={zoom.current}
scrollWheelZoom={true}
style={{ width: '100%', height: '100%' }}
ref={setMap}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={initCoords} />
<MapEvents />
</MapContainer>
</Box>
)}
<Button
type="submit"
variant="Primary"
title="Share Location"
aria-label="Share Location"
onClick={handleSubmit}
>
<Text size="B400">Share Location</Text>
</Button>
</Box>
</Dialog>
</FocusTrap>
</OverlayCenter>
</Overlay>
);
}
@@ -0,0 +1 @@
export { LocationDialog } from './LocationDialog';
@@ -1164,7 +1164,7 @@ function Embeds() {
<SettingTile
title="Show Interactive maps"
focusId="show-interactive-map"
description="Show an interactive map in messages. This reduces Privacy because it requests map data from OpenStreetMap.org"
description="Show an interactive map in messages. This reduces Privacy because it requests map data from OpenStreetMap.org whenever you need to load a uncached part of the maps."
after={
<Switch
variant="Primary"
@@ -1179,7 +1179,7 @@ function Embeds() {
<SettingTile
title="Show Interactive maps in Encrypted Rooms"
focusId="show-interactive-map-enc"
description="Show an interactive map in Encrtyped rooms. This reduces Privacy because it requests map data from OpenStreetMap.org"
description="Show an interactive map in Encrtyped rooms. This reduces Privacy because it requests map data from OpenStreetMap.org whenever you need to load a uncached part of the maps."
after={
<Switch
variant="Primary"
+6 -5
View File
@@ -1541,7 +1541,8 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
},
[Command.Location]: {
name: Command.Location,
description: 'Share a location as /location <latitude> <longitude>',
description:
'Open location sharing menu or share a location as /location <latitude> <longitude>',
exe: async (payload) => {
const target = payload
.replace(',', ' ')
@@ -1553,9 +1554,10 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
const mlat = target[0];
const mlon = target[1];
const malt = target[2];
if (target.length === 0) return;
if (!mlat || !mlon) {
sendFeedback(
'You need to specify a latitude, a longitude parameter, and optionally an altitude, as for example: /location 43.959971 -59.790623 or use the /sharemylocation to share the current location',
'You need to specify a latitude, and a longitude parameter, as for example: /location 43.959971 -59.790623 or have nothing after the /location to open the map to click which location to share',
room,
mx.getSafeUserId()
);
@@ -1565,7 +1567,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
msgtype: 'm.location',
geo_uri: `geo:${mlat},${mlon}${malt ? `,${malt}` : ''};u=0`,
body: `https://www.openstreetmap.org/?mlat=${mlat}&mlon=${mlon}#map=16/${mlat}/${mlon}"`,
} as unknown as RoomMessageEventContent);
} as RoomMessageEventContent);
},
},
[Command.ShareMyLocation]: {
@@ -1589,7 +1591,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
const mlat = crd.latitude;
const mlon = crd.longitude;
const malt = crd.altitude;
const macc = crd.accuracy;
if (!mlat || !mlon) {
sendFeedback(
'Unable to retrieve the location data for an unknown reason',
@@ -1600,7 +1601,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
}
mx.sendMessage(room.roomId, {
msgtype: 'm.location',
geo_uri: `geo:${mlat},${mlon}${malt ? `,${malt}` : ''};u=${macc}`,
geo_uri: `geo:${mlat},${mlon}${malt ? `,${malt}` : ''};u=0`,
body: `https://www.openstreetmap.org/?mlat=${mlat}&mlon=${mlon}#map=16/${mlat}/${mlon}"`,
} as unknown as RoomMessageEventContent);
}