-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathAnnotationCluster.tsx
More file actions
260 lines (222 loc) · 9.38 KB
/
AnnotationCluster.tsx
File metadata and controls
260 lines (222 loc) · 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import React, {
createContext, Fragment, useContext, useEffect, useId, useState, useRef,
useLayoutEffect,
} from 'react';
import { createPortal } from 'react-dom';
import AnnotationClusterProps from './AnnotationClusterProps';
import MapContext from '../context/MapContext';
export const AnnotationClusterIdentifierContext = createContext<string | null>(null);
export const ClusterAnnotationContext = createContext<mapkit.Annotation | undefined>(undefined);
interface ClusterAnnotationData {
contentElement: HTMLDivElement;
annotation: mapkit.Annotation;
coordinate: mapkit.Coordinate;
memberAnnotations: mapkit.Annotation[];
// Fingerprint based on member coordinates for stable identification
fingerprint: string;
// Track a unique ID for React keys
id: string;
}
// Generate a unique ID for each cluster annotation
let clusterIdCounter = 0;
function generateClusterId(): string {
clusterIdCounter += 1;
return `cluster-${clusterIdCounter}`;
}
// Create a fingerprint for a member annotation based on its stable properties
function getAnnotationFingerprint(annotation: mapkit.Annotation): string {
// Use coordinate with reasonable precision (8 decimal places is ~1mm)
return `${annotation.coordinate.latitude.toFixed(8)},${annotation.coordinate.longitude.toFixed(8)}`;
}
// Create a fingerprint for a cluster based on its members' coordinates
function getClusterFingerprint(members: mapkit.Annotation[]): string {
return members
.map(getAnnotationFingerprint)
.sort()
.join('|');
}
// Check if two arrays contain the same annotation references
function haveSameMembers(a: mapkit.Annotation[], b: mapkit.Annotation[]): boolean {
if (a.length !== b.length) return false;
const setA = new Set(a);
return b.every((item) => setA.has(item));
}
// Helper component to measure content size and update callout offset
function ClusterContentMeasurer({ annotation, children }: { annotation: mapkit.Annotation, children: React.ReactNode }) {
const ref = useRef<HTMLDivElement>(null);
const initialCalloutOffset = useRef<DOMPoint | null>(null);
useLayoutEffect(() => {
// Capture the initial callout offset set by the child Annotation component
initialCalloutOffset.current = annotation.calloutOffset;
}, []);
useLayoutEffect(() => {
if (!ref.current) return;
const updateOffset = () => {
const height = ref.current?.offsetHeight || 0;
// Always apply vertical centering, but preserve any user-set horizontal offset
const xOffset = initialCalloutOffset.current?.x ?? 0;
annotation.calloutOffset = new DOMPoint(xOffset, height / 2);
};
// Initial
updateOffset();
// Observer for size changes
const observer = new ResizeObserver(updateOffset);
observer.observe(ref.current);
return () => observer.disconnect();
}, [annotation]);
return <div ref={ref} style={{ pointerEvents: 'auto', display: 'inline-block' }}>{children}</div>;
}
export default function AnnotationCluster({
children,
annotationForCluster,
}: AnnotationClusterProps) {
const clusterIdenfier = useId();
const map = useContext(MapContext);
// Use ref for the existing function to avoid stale closure issues
// Note: MapKit types declare this as returning void, but it actually returns an Annotation
const existingClusterFuncRef = useRef<
((clusterAnnotation: mapkit.Annotation) => mapkit.Annotation | void) | undefined
>(undefined);
const hasStoredExistingFunc = useRef(false);
const [clusterAnnotations, setClusterAnnotations] = useState<ClusterAnnotationData[]>([]);
// Keep a ref in sync with state for use in the callback
const clusterAnnotationsRef = useRef<ClusterAnnotationData[]>([]);
useEffect(() => {
clusterAnnotationsRef.current = clusterAnnotations;
}, [clusterAnnotations]);
// Store the annotationForCluster prop in a ref so the callback always has the latest
const annotationForClusterRef = useRef(annotationForCluster);
useEffect(() => {
annotationForClusterRef.current = annotationForCluster;
}, [annotationForCluster]);
// Coordinates
useEffect(() => {
if (map === null) return undefined;
// Store the existing function only once
if (!hasStoredExistingFunc.current) {
existingClusterFuncRef.current = map.annotationForCluster;
hasStoredExistingFunc.current = true;
}
map.annotationForCluster = (clusterAnnotationData) => {
if (clusterAnnotationData.clusteringIdentifier === clusterIdenfier) {
if (annotationForClusterRef.current) {
// Create a fingerprint based on member coordinates (stable across calls)
const fingerprint = getClusterFingerprint(clusterAnnotationData.memberAnnotations);
// Find existing cluster by fingerprint
const existingEntry = clusterAnnotationsRef.current.find(
(entry) => entry.fingerprint === fingerprint,
);
if (existingEntry) {
// Update coordinate if it changed
const coordChanged = existingEntry.coordinate.latitude
!== clusterAnnotationData.coordinate.latitude
|| existingEntry.coordinate.longitude
!== clusterAnnotationData.coordinate.longitude;
if (coordChanged) {
// IMPORTANT: Always update the annotation's coordinate to match what MapKit expects
existingEntry.annotation.coordinate = new mapkit.Coordinate(
clusterAnnotationData.coordinate.latitude,
clusterAnnotationData.coordinate.longitude,
);
}
// Check if members changed (reference check)
const membersChanged = !haveSameMembers(
existingEntry.memberAnnotations,
clusterAnnotationData.memberAnnotations,
);
// Update state if anything changed to ensure React renders correctly
if (coordChanged || membersChanged) {
setClusterAnnotations((prev) => prev.map((entry) => {
if (entry === existingEntry) {
return {
...entry,
coordinate: clusterAnnotationData.coordinate,
memberAnnotations: clusterAnnotationData.memberAnnotations,
};
}
return entry;
}));
}
return existingEntry.annotation;
}
// Create a new cluster annotation
const contentElement = document.createElement('div');
// Fix offset issues by centering content around a 0x0 container
contentElement.style.width = '0px';
contentElement.style.height = '0px';
contentElement.style.overflow = 'visible';
contentElement.style.display = 'flex';
contentElement.style.justifyContent = 'center';
contentElement.style.alignItems = 'center';
// Ensure pointer events work
contentElement.style.pointerEvents = 'auto';
const a = new mapkit.Annotation(
new mapkit.Coordinate(
clusterAnnotationData.coordinate.latitude,
clusterAnnotationData.coordinate.longitude,
),
() => contentElement,
{
title: clusterAnnotationData.title,
subtitle: clusterAnnotationData.subtitle,
calloutEnabled: true,
},
);
const newEntry: ClusterAnnotationData = {
contentElement,
annotation: a,
coordinate: clusterAnnotationData.coordinate,
memberAnnotations: clusterAnnotationData.memberAnnotations,
fingerprint,
id: generateClusterId(),
};
// Update the ref immediately so subsequent calls in the same cycle can find it
clusterAnnotationsRef.current = [...clusterAnnotationsRef.current, newEntry];
setClusterAnnotations((prev) => [...prev, newEntry]);
return a;
}
return clusterAnnotationData;
}
// Delegate to the previous function if it exists
return existingClusterFuncRef.current
? existingClusterFuncRef.current(clusterAnnotationData)
: clusterAnnotationData;
};
return () => {
// Cleanup: remove cluster annotations that are no longer valid
setClusterAnnotations([]);
clusterAnnotationsRef.current = [];
if (!hasStoredExistingFunc.current || existingClusterFuncRef.current === undefined) {
// @ts-ignore
delete map.annotationForCluster;
} else {
// @ts-ignore
map.annotationForCluster = existingClusterFuncRef.current;
}
};
}, [map, clusterIdenfier]);
return (
<>
{annotationForCluster && clusterAnnotations.map(({
contentElement, annotation, coordinate, memberAnnotations, id,
}) => (
<Fragment key={id}>
{createPortal(
<ClusterAnnotationContext.Provider value={annotation}>
<ClusterContentMeasurer annotation={annotation}>
{annotationForCluster(
memberAnnotations,
coordinate,
)}
</ClusterContentMeasurer>
</ClusterAnnotationContext.Provider>,
contentElement,
)}
</Fragment>
))}
<AnnotationClusterIdentifierContext.Provider value={clusterIdenfier}>
{children}
</AnnotationClusterIdentifierContext.Provider>
</>
);
}