Skip to content

Add custom annotation to the map. #29223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -307,4 +307,4 @@
"engines": {
"node": ">=20.0.0"
}
}
}
63 changes: 63 additions & 0 deletions res/css/components/views/location/_Marker.pcss
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,69 @@ Please see LICENSE files in the repository root for full details.
color: $accent;
}

.mx_Marker_red {
color: red;
}

.mx_Marker_green {
color: green;
}

.mx_Marker_blue {
color: blue;
}

.mx_Marker_yellow {
color: yellow;
}

.mx_Marker_cyan {
color: cyan;
}

.mx_Marker_magenta {
color: magenta;
}

.mx_Marker_orange {
color: orange;
}

.mx_Marker_purple {
color: purple;
}

.mx_Marker_pink {
color: pink;
}

.mx_Marker_brown {
color: brown;
}

.mx_AnnotationMarker_border {
width: 22px;
height: 22px;
border-radius: 50%;
filter: drop-shadow(0px 3px 5px rgba(0, 0, 0, 0.2));
background-color: currentColor;

display: flex;
justify-content: center;
align-items: center;

/* caret down */
&::before {
content: "";
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid currentColor;
position: absolute;
bottom: -4px;
}
}


.mx_Marker_border {
width: 42px;
height: 42px;
Expand Down
7 changes: 7 additions & 0 deletions src/components/views/location/Annotation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
interface Annotation {
body: string,
geoUri: string,
color?: string,
}

export default Annotation;
70 changes: 70 additions & 0 deletions src/components/views/location/AnnotationDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import React, { useState } from 'react';
import BaseDialog from "../dialogs/BaseDialog";


interface Props {
onFinished: () => void;
onSubmit: (title: string, color: string) => void;
displayBack?: boolean;
}

const colorOptions = [
{ label: 'Red', value: 'red' },
{ label: 'Green', value: 'green' },
{ label: 'Blue', value: 'blue' },
{ label: 'Yellow', value: 'yellow' },
{ label: 'Cyan', value: 'cyan' },
{ label: 'Magenta', value: 'magenta' },
{ label: 'Orange', value: 'orange' },
{ label: 'Purple', value: 'purple' },
{ label: 'Pink', value: 'pink' },
{ label: 'Brown', value: 'brown' },
];

const AnnotationDialog: React.FC<Props> = ({ onSubmit, onFinished }) => {

const [title, setTitle] = useState('');
const [color, setColor] = useState('red'); // Default color

const handleSubmit = () => {
onSubmit(title, color);
onFinished();
};

return (
<BaseDialog
title="Annotation details"
onFinished={onFinished}
hasCancel={true}
className="mx_WidgetCapabilitiesPromptDialog"
>
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter title"
/>

<div>
<label htmlFor="colorSelect" style={{ marginRight: "10px" }}>Choose Color:</label>
<select
id="colorSelect"
value={color}
onChange={(e) => setColor(e.target.value)}
>
{colorOptions.map((color) => (
<option key={color.value} value={color.value} style={{ backgroundColor: color.value }}>
{color.label}
</option>
))}
</select>
</div>

<button onClick={handleSubmit}>Submit</button>
</div>
</BaseDialog>
);
};

export default AnnotationDialog;
71 changes: 71 additions & 0 deletions src/components/views/location/AnnotationMarker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import React, { ReactNode, useState } from "react";
import classNames from "classnames";
import LocationIcon from "@vector-im/compound-design-tokens/assets/web/icons/location-pin-solid";

const OptionalTooltip: React.FC<{
tooltip?: React.ReactNode;
annotationKey: string;
children: React.ReactNode;
onDelete: (key: string) => void; // Optional delete function
}> = ({ tooltip, children, onDelete, annotationKey }) => {
const [isHovered, setIsHovered] = useState(false);

return (
<div
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
style={{ position: "relative" }} // Set position for proper tooltip alignment
>
{tooltip && (
<div style={{ display: "flex", alignItems: "center" }}>
{tooltip}
{isHovered && (
<button
onClick={() => onDelete(annotationKey)}
style={{
marginLeft: "8px", // Space between tooltip and button
backgroundColor: "red", // Customize button style
color: "white",
border: "none",
borderRadius: "3px",
cursor: "pointer"
}}
>
X
</button>
)}
</div>
)}
{children}
</div>
);
};

/**
* Generic location marker
*/

interface Props {
id: string;
useColor?: string;
tooltip?: ReactNode;
onDelete: (annotationKey: string) => void;
}

const AnnotationMarker = React.forwardRef<HTMLDivElement, Props>(({ id, useColor, tooltip, onDelete}, ref) => {
return (
<div
ref={ref}
id={id}
className={classNames("mx_Marker", useColor ? `mx_Marker_${useColor}` : "mx_Marker_defaultColor" )}
>
<OptionalTooltip tooltip={tooltip} annotationKey={id} onDelete={onDelete}>
<div className="mx_AnnotationMarker_border">
<LocationIcon className="mx_Marker_icon" />
</div>
</OptionalTooltip>
</div>
);
});

export default AnnotationMarker;
159 changes: 159 additions & 0 deletions src/components/views/location/AnnotationPin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { MatrixClient, MatrixEvent, Room, StateEvents, TimelineEvents } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";
import Annotation from "./Annotation";

enum CustomEventType {
MapAnnotation = "m.map.annotation"
}

export const fetchAnnotationEvent = async (roomId: string, matrixClient: MatrixClient): Promise<MatrixEvent | null> => {
try {
const room = matrixClient.getRoom(roomId);
if (!room) {
console.error("Room not found");
return null;
}
const annotationEventId = getAnnotationEventId(room);
if (!annotationEventId) {
console.error("Read pins event ID not found");
return null;
}
let localEvent = room.findEventById(annotationEventId);

// Decrypt if necessary
if (localEvent?.isEncrypted()) {
await matrixClient.decryptEventIfNeeded(localEvent, { emit: false });
}

if (localEvent) {
return localEvent; // Return the pinned event itself
}
return null;
} catch (err) {
logger.error(`Error looking up pinned event in room ${roomId}`);
logger.error(err);
}
return null;
};

function getAnnotationEventId(room?: Room): string {
const events = room?.currentState.getStateEvents(CustomEventType.MapAnnotation);
if (!events || events.length === 0) {
return ""; // Return an empty array if no events are found
}
const content = events[0].getContent(); // Get content from the event
const annotationEventId = content.event_id || "";
return annotationEventId;
}

export async function extractAnnotations(roomId: string, matrixClient: MatrixClient): Promise<string | null> {
try {
const pinEvent = await fetchAnnotationEvent(roomId, matrixClient);
if(!pinEvent) {
return null;
}

let rawContent: string = pinEvent.getContent()["body"];
return rawContent;

} catch (error) {
console.error("Error retrieving content from pinned event:", error);
return null;
}
}


// Function to update annotations on the server
export const sendAnnotations = async (roomId: string, content: TimelineEvents[keyof TimelineEvents], matrixClient: MatrixClient) => {
try {

let eventid = await matrixClient.sendEvent(roomId, (CustomEventType.MapAnnotation as unknown) as keyof TimelineEvents, content);
await matrixClient.sendStateEvent(roomId, (CustomEventType.MapAnnotation as unknown) as keyof StateEvents, eventid);
console.log("Annotations updated successfully!");
} catch (error) {
console.error("Failed to update annotations:", error);
throw error; // Rethrow the error for handling in the calling component
}
};


// Function to save a new annotation
// Function to save an annotation
export const saveAnnotation = async (roomId: string, matrixClient: MatrixClient, annotations: Annotation[]) => {
try {
// Convert annotations to a string
const stringifiedAnnotations = JSON.stringify(annotations);
if (!stringifiedAnnotations) {
return [];
}
const content = {
annotations: stringifiedAnnotations, // Use the stringified annotations
} as unknown as TimelineEvents[keyof TimelineEvents];

await sendAnnotations(roomId, content, matrixClient);
} catch (error) {
console.error("Failed to save annotation:", error);
// Handle the error appropriately (e.g., notify the user)
throw error; // Optionally rethrow the error for further handling
}
};

// Function to delete an annotation
export const deleteAnnotation = async (roomId: string, matrixClient: MatrixClient, geoUri: string, annotations: Annotation[]) => {
try {
// Convert annotations to a string
const stringifiedAnnotations = JSON.stringify(annotations);
if (!stringifiedAnnotations) {
return [];
}
const content = {
annotations: stringifiedAnnotations, // Use the stringified annotations
} as unknown as TimelineEvents[keyof TimelineEvents];

await sendAnnotations(roomId, content, matrixClient);
} catch (error) {
console.error("Failed to delete annotation:", error);
throw error; // Optionally rethrow the error for further handling
}
};

// Function to load annotations from the server
export const loadAnnotations = async (roomId: string, matrixClient: MatrixClient): Promise<Annotation[]> => {
try {
const room = matrixClient.getRoom(roomId); // Get the room object
const events = room?.currentState.getStateEvents("m.map.annotation");

if (!events || events.length === 0) {
return []; // Return an empty array if no events are found
}

const event = await fetchAnnotationEvent(roomId, matrixClient);
if (!event) {
return [];
}

const content = event.getContent(); // Get content from the event
const stringifiedAnnotations = content.annotations || [];
if (typeof stringifiedAnnotations !== 'string') {
console.warn("Content is not a string. Returning early.");
return []; // or handle accordingly
}

// Parse the JSON string back to an array of annotations
const annotationsArray: Annotation[] = JSON.parse(stringifiedAnnotations);

if (!Array.isArray(annotationsArray) || annotationsArray.length === 0) {
return []; // Return an empty array if parsing fails or array is empty
}

return annotationsArray.map((annotation: { geoUri: string; body: string; color?: string; }) => ({
geoUri: annotation.geoUri,
body: annotation.body,
color: annotation.color,
}));

} catch (error) {
console.error("Failed to load annotations:", error);
return []; // Return an empty array in case of an error
}
};
Loading
Loading