import React from "react";
import type { CometChat } from "@cometchat/chat-sdk-javascript";
import type {
CometChatMessagePlugin,
CometChatMessagePluginContext,
CometChatMessageOption,
} from "@cometchat/chat-uikit-react";
// Extract location data from the custom message
function getLocationData(message: CometChat.BaseMessage) {
const customMessage = message as CometChat.CustomMessage;
const data = customMessage.getCustomData() as {
latitude?: number;
longitude?: number;
address?: string;
} | undefined;
return {
latitude: data?.latitude ?? 0,
longitude: data?.longitude ?? 0,
address: data?.address ?? "",
};
}
export const LocationPlugin: CometChatMessagePlugin = {
id: "location",
messageTypes: ["location"],
messageCategories: ["custom"],
renderBubble(message: CometChat.BaseMessage, context: CometChatMessagePluginContext) {
const { latitude, longitude, address } = getLocationData(message);
const mapUrl = `https://maps.googleapis.com/maps/api/staticmap?center=${latitude},${longitude}&zoom=15&size=300x200&markers=${latitude},${longitude}&key=YOUR_API_KEY`;
return (
<div className="location-bubble">
<img
src={mapUrl}
alt={address || "Location"}
style={{ borderRadius: 8, width: "100%", maxWidth: 300 }}
/>
{address && (
<p style={{ margin: "8px 0 0", fontSize: 13, color: "#666" }}>
{address}
</p>
)}
<a
href={`https://maps.google.com/?q=${latitude},${longitude}`}
target="_blank"
rel="noopener noreferrer"
style={{ fontSize: 12, color: "#6851FF" }}
>
Open in Maps
</a>
</div>
);
},
getOptions(
message: CometChat.BaseMessage,
context: CometChatMessagePluginContext
): CometChatMessageOption[] {
const options: CometChatMessageOption[] = [];
// Copy coordinates
options.push({
id: "copy-location",
title: "Copy Location",
onClick: (msg) => {
const { latitude, longitude } = getLocationData(msg);
void navigator.clipboard.writeText(`${latitude}, ${longitude}`);
context.showToast?.("Location copied to clipboard");
},
});
// Delete (sender only)
options.push({
id: "delete",
title: context.getLocalizedString?.("delete") ?? "Delete",
senderOnly: true,
onClick: (msg) => context.onDeleteMessage?.(msg),
});
return options;
},
getLastMessagePreview(
message: CometChat.BaseMessage
): string {
const { address } = getLocationData(message);
return address ? `📍 ${address}` : "📍 Location";
},
};