-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap-state-2d.js
More file actions
366 lines (306 loc) · 12.6 KB
/
Copy pathmap-state-2d.js
File metadata and controls
366 lines (306 loc) · 12.6 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Map State Manager
// Tracks map position, zoom, transforms, and interaction state
class MapState2D {
constructor(mapCanvas) {
this.mapCanvas = mapCanvas;
// Map position and zoom
this.center = null;
this.zoom = 0;
this.viewMode = 'map';
// Transform tracking
this.canvasTransform = { translateX: 0, translateY: 0, scale: 1 };
this.parentTransform = { translateX: 0, translateY: 0, scale: 1 };
this.parentIsZero = true;
// Interaction state
this.isPotentiallyZooming = false;
this.zoomInteractionTimeout = null;
// Change listeners
this.changeListeners = new Set();
// Mutation observer for transform changes
this.observer = null;
}
/**
* Initialize the map state tracker
* @returns {boolean} True if initialization succeeded
*/
initialize() {
// Get initial state
this.updateCanvasTransform();
this.updateParentTransform();
this.updatePositionFromUrl();
// Set up observers and event listeners
this.setupObserver();
this.setupEventListeners();
return true;
}
/**
* Add a listener for map state changes
* @param {Function} callback - Called when state changes
*/
addChangeListener(callback) {
this.changeListeners.add(callback);
}
/**
* Remove a change listener
* @param {Function} callback - Callback to remove
*/
removeChangeListener(callback) {
this.changeListeners.delete(callback);
}
/**
* Notify all listeners of state changes
* @param {string} changeType - Type of change that occurred
*/
notifyListeners(changeType) {
for (const listener of this.changeListeners) {
try {
listener(changeType, this);
} catch (e) {
log.error('state', 'Error in map state change listener:', e);
}
}
}
// Update canvas transform information
updateCanvasTransform() {
const canvasStyle = window.getComputedStyle(this.mapCanvas.mapCanvas);
const canvasTransformStr = canvasStyle.transform;
if (canvasTransformStr && canvasTransformStr !== 'none') {
const transformValues = this.parseTransform(canvasTransformStr);
if (this.isTransformDifferent("canvas", transformValues, this.canvasTransform)) {
this.canvasTransform = transformValues;
this.notifyListeners('canvasTransform');
}
}
}
// Update parent transform information
updateParentTransform() {
const parentStyle = window.getComputedStyle(this.mapCanvas.parent);
const parentTransformStr = parentStyle.transform;
let transformValues;
if (parentTransformStr && parentTransformStr !== 'none') {
transformValues = this.parseTransform(parentTransformStr);
} else {
transformValues = { translateX: 0, translateY: 0, scale: 1 };
}
if (this.isTransformDifferent("parent", transformValues, this.parentTransform)) {
this.parentTransform = transformValues;
// Check if parent transform went to zero
const wasZero = this.parentIsZero;
this.parentIsZero = Math.abs(this.parentTransform.translateX) < 1 && Math.abs(this.parentTransform.translateY) < 1;
// If parent just went to zero, update position from URL
if (!wasZero && this.parentIsZero) {
log.detail('state', "Parent transform went to zero - updating center from URL");
this.updatePositionFromUrl();
}
this.notifyListeners('parentTransform');
}
}
// Check if transform values are different (for logging)
isTransformDifferent(name, newTransform, oldTransform) {
const different = newTransform.translateX !== oldTransform.translateX ||
newTransform.translateY !== oldTransform.translateY ||
newTransform.scale !== oldTransform.scale;
if (different) {
log.detail('state', `${name} transform changes`, newTransform);
}
return different;
}
// Parse a transform string into component values
parseTransform(transformStr) {
try {
// Handle matrix format: matrix(a, b, c, d, tx, ty)
if (transformStr.startsWith('matrix')) {
const matrixMatch = transformStr.match(/matrix\(([^)]+)\)/);
if (matrixMatch && matrixMatch[1]) {
const values = matrixMatch[1].split(',').map(v => parseFloat(v.trim()));
if (values.length === 6) {
const translateX = values[4];
const translateY = values[5];
const scale = Math.sqrt(values[0] * values[0] + values[1] * values[1]);
return { translateX, translateY, scale };
}
}
}
// Handle translate and scale separately
let translateX = 0;
let translateY = 0;
let scale = 1;
// Extract translate values
const translateMatch = transformStr.match(/translate\(([^)]+)\)/);
if (translateMatch && translateMatch[1]) {
const values = translateMatch[1].split(',').map(v => parseFloat(v.trim()));
if (values.length >= 1) translateX = values[0];
if (values.length >= 2) translateY = values[1];
}
// Extract translateX/Y values
const translateXMatch = transformStr.match(/translateX\(([^)]+)\)/);
if (translateXMatch && translateXMatch[1]) {
translateX = parseFloat(translateXMatch[1]);
}
const translateYMatch = transformStr.match(/translateY\(([^)]+)\)/);
if (translateYMatch && translateYMatch[1]) {
translateY = parseFloat(translateYMatch[1]);
}
// Extract scale value
const scaleMatch = transformStr.match(/scale\(([^)]+)\)/);
if (scaleMatch && scaleMatch[1]) {
scale = parseFloat(scaleMatch[1]);
}
return { translateX, translateY, scale };
} catch (e) {
log.error('state', "Error parsing transform:", e);
return { translateX: 0, translateY: 0, scale: 1 };
}
}
// Update position information from URL
updatePositionFromUrl() {
// Only proceed if parent transform is zero or near zero
if (!this.parentIsZero) {
return;
}
const position = URLParser.extractMapParameters();
if (!position) return;
this.viewMode = position.mode;
let hasChanges = false;
// Update center
if (!this.center || this.center.lat !== position.lat || this.center.lng !== position.lng) {
this.center = { lat: position.lat, lng: position.lng };
hasChanges = true;
}
// Handle zoom or meters value
let calculatedZoom;
if (position.zoom !== undefined) {
calculatedZoom = Math.round(position.zoom);
} else if (position.meters !== undefined) {
const parentDimensions = this.mapCanvas.getParentDimensions();
calculatedZoom = Math.round(CoordinateTransformer.convertMetersToZoom(position.meters, position.lat, parentDimensions.height));
log.detail('state', `Converted ${position.meters}m to zoom ${calculatedZoom} (viewport: ${parentDimensions.height}px)`);
} else {
return;
}
// Update zoom
if (this.zoom !== calculatedZoom) {
this.zoom = calculatedZoom;
hasChanges = true;
}
if (hasChanges) {
this.notifyListeners('position');
}
}
/**
* Convert lat/lng to canvas pixel coordinates (2D mode)
* @param {number} lat - Latitude
* @param {number} lng - Longitude
* @returns {Object|null} Canvas coordinates {x, y} or null if error
*/
mapLatLngToCanvas(lat, lng) {
if (!this.center) return null;
// Calculate pixel offset from center using shared coordinate transformer
const offset = CoordinateTransformer.calculatePixelOffset(
this.center.lat, this.center.lng, lat, lng, this.zoom
);
if (!offset) return null;
// Get overlay canvas center in display coordinates
const parentDimensions = this.mapCanvas.getParentDimensions();
const canvasCenterX = parentDimensions.width / 2;
const canvasCenterY = parentDimensions.height / 2;
// Apply canvas transform and tile alignment
const x = canvasCenterX + offset.x - this.canvasTransform.translateX;
const y = canvasCenterY + offset.y - this.canvasTransform.translateY;
return { x, y };
}
// Handle map interactions that might result in a zoom
handlePotentialZoomInteraction() {
this.isPotentiallyZooming = true;
log.detail('state', "potential zoom interaction, suspending redraw");
if (this.zoomInteractionTimeout) {
clearTimeout(this.zoomInteractionTimeout);
}
this.zoomInteractionTimeout = setTimeout(() => {
log.detail('state', "zoom interaction timeout, redrawing");
this.zoomInteractionTimeout = null;
this.isPotentiallyZooming = false;
this.updatePositionFromUrl();
this.updateCanvasTransform();
this.updateParentTransform();
this.notifyListeners('zoomResolved');
}, 1000);
}
// Handle URL changes
handleUrlChanged() {
if (this.parentIsZero) {
log.detail('state', "onMapsUrlChanged: Parent transform is zero - updating center from URL");
this.updatePositionFromUrl();
if (this.zoomInteractionTimeout !== null) {
log.detail('state', "zoom resolved, redrawing");
clearTimeout(this.zoomInteractionTimeout);
this.zoomInteractionTimeout = null;
this.isPotentiallyZooming = false;
this.updateCanvasTransform();
this.updateParentTransform();
this.notifyListeners('zoomResolved');
}
}
}
// Set up MutationObserver to watch for transform changes
setupObserver() {
this.observer = new MutationObserver((mutations) => {
let shouldUpdateCanvasTransform = false;
let shouldUpdateParentTransform = false;
for (const mutation of mutations) {
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
if (mutation.target === this.mapCanvas.mapCanvas) {
shouldUpdateCanvasTransform = true;
} else if (mutation.target === this.mapCanvas.parent) {
shouldUpdateParentTransform = true;
}
}
}
if (shouldUpdateCanvasTransform) {
this.updateCanvasTransform();
}
if (shouldUpdateParentTransform) {
this.updateParentTransform();
}
});
// Observe the maps canvas for attribute changes
this.observer.observe(this.mapCanvas.mapCanvas, {
attributes: true,
attributeFilter: ['style', 'width', 'height']
});
// Observe the canvas parent for transform changes
if (this.mapCanvas.parent) {
this.observer.observe(this.mapCanvas.parent, {
attributes: true,
attributeFilter: ['style', 'class']
});
}
log.detail('init', "MapState2D MutationObserver set up");
}
// Set up event listeners for map interactions
setupEventListeners() {
window.addEventListener('wokemaps_urlChanged', () => this.handleUrlChanged());
window.addEventListener('wokemaps_potentialZoomInteraction', () => this.handlePotentialZoomInteraction());
log.detail('init', 'MapState2D event listeners initialized');
}
// Clean up observers and listeners
cleanup() {
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
if (this.zoomInteractionTimeout) {
clearTimeout(this.zoomInteractionTimeout);
this.zoomInteractionTimeout = null;
}
this.changeListeners.clear();
}
// Check if map state is valid
isValid() {
return this.mapCanvas.isValid();
}
}
// Export for use in other files
if (typeof window !== 'undefined') {
window.MapState2D = MapState2D;
}