diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 936b21f79..ea54c8cdd 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -431,7 +431,8 @@ function RenderMessageContentInternal({ } if (msgType === (MsgType.File as string)) return renderFile(); - if (msgType === (MsgType.Location as string)) return ; + if (msgType === (MsgType.Location as string)) + return ; if (msgType === 'm.bad.encrypted') return ; // cute events diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index de102dcad..2f8193072 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -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={} > Open Location {showMaps && ( - - + + - - )} + + + )} ); } diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 02644cf7e..223b8c6fc 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -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( ); const [AddMenuAnchor, setAddMenuAnchor] = useState(); const [showPollPicker, setShowPollPicker] = useState(false); + const [showLocationPicker, setShowLocationPicker] = useState(false); const [scheduleMenuAnchor, setScheduleMenuAnchor] = useState(); const [showSchedulePicker, setShowSchedulePicker] = useState(false); const [silentReply, setSilentReply] = useState(!mentionInReplies); @@ -822,16 +824,15 @@ export const RoomInput = forwardRef( } 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( > Create Poll + { + setAddMenuAnchor(undefined); + setShowLocationPicker(true); + }} + before={} + > + Add Location + ( 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'} > @@ -1843,6 +1855,15 @@ export const RoomInput = forwardRef( clearReplyDraft={() => setReplyDraft(undefined)} /> )} + {showLocationPicker && ( + setShowLocationPicker(false)} + mx={mx} + room={room} + replyDraft={replyDraft} + clearReplyDraft={() => setReplyDraft(undefined)} + /> + )} ); } diff --git a/src/app/features/room/location-modal/LocationDialog.css.tsx b/src/app/features/room/location-modal/LocationDialog.css.tsx new file mode 100644 index 000000000..43134d47f --- /dev/null +++ b/src/app/features/room/location-modal/LocationDialog.css.tsx @@ -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, +}); diff --git a/src/app/features/room/location-modal/LocationDialog.tsx b/src/app/features/room/location-modal/LocationDialog.tsx new file mode 100644 index 000000000..f786eb10c --- /dev/null +++ b/src/app/features/room/location-modal/LocationDialog.tsx @@ -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(initCoords); + const zoom = useRef(2); + const [locationError, setLocationError] = useState(locationErrors.none); + + const [map, setMap] = useState(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 = (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 = (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 ( + }> + + + +
+ + + {`Share Location ${replyDraft ? '(reply / thread)' : ''}`} + + + + +
+ + + } + > + Share Current Location + + } + > + Paste Clipboard + + + {locationError !== locationErrors.none && ( + + + {locationError} + + )} + + + Latitude + + + + Longitude + + + + {showMaps && ( + + + + + + + + + )} + + +
+
+
+
+ ); +} diff --git a/src/app/features/room/location-modal/index.ts b/src/app/features/room/location-modal/index.ts new file mode 100644 index 000000000..2bb5d84b6 --- /dev/null +++ b/src/app/features/room/location-modal/index.ts @@ -0,0 +1 @@ +export { LocationDialog } from './LocationDialog'; diff --git a/src/app/features/settings/general/General.tsx b/src/app/features/settings/general/General.tsx index 50cbd4bd5..e39732965 100644 --- a/src/app/features/settings/general/General.tsx +++ b/src/app/features/settings/general/General.tsx @@ -1164,7 +1164,7 @@ function Embeds() { { }, [Command.Location]: { name: Command.Location, - description: 'Share a location as /location ', + description: + 'Open location sharing menu or share a location as /location ', 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); }