-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWME-SU.js
More file actions
1854 lines (1680 loc) · 94.4 KB
/
Copy pathWME-SU.js
File metadata and controls
1854 lines (1680 loc) · 94.4 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name WME Straighten Up!
// @namespace https://greasyfork.org/users/166843
// @version 2026.04.06.01
// @description Straighten selected WME segment(s) by aligning along straight line between two end points and removing geometry nodes.
// @author JS55CT
// @match http*://*.waze.com/*editor*
// @exclude http*://*.waze.com/user/editor*
// @require https://greasyfork.org/scripts/509664/code/WME%20Utils%20-%20Bootstrap.js
// @require https://greasyfork.org/scripts/24851-wazewrap/code/WazeWrap.js
// @require https://cdn.jsdelivr.net/npm/@turf/turf@7/turf.min.js
// @grant GM_xmlhttpRequest
// @connect greasyfork.org
// @license GPLv3
// ==/UserScript==
// Original credit to jonny3D and impulse200, dBsooner
/* global I18n, GM_info, GM_xmlhttpRequest, WazeWrap, bootstrap, turf */
(async function () {
'use strict';
// ── Script metadata ──────────────────────────────────────────────────
const SHOW_UPDATE_MESSAGE = true;
const SCRIPT_VERSION_CHANGES = ['Small Bug Fix for Shortcuts at load time!'];
const SCRIPT_VERSION = GM_info.script.version.toString();
const DOWNLOAD_URL = 'https://greasyfork.org/scripts/388349-wme-straighten-up/code/WME%20Straighten%20Up!.user.js';
const SCRIPT_PAGE_URL = 'https://greasyfork.org/scripts/388349-wme-straighten-up/';
const SETTINGS_STORE_NAME = 'WMESU';
const LOAD_BEGIN_TIME = performance.now();
// ── Debug & execution state ──────────────────────────────────────────
let debug = false; // Set to false before release
let wmeSdk; // WME SDK instance - assigned by bootstrap()
// ── UI element cache ─────────────────────────────────────────────────
const elemCache = {
b: document.createElement('b'),
br: document.createElement('br'),
div: document.createElement('div'),
li: document.createElement('li'),
ol: document.createElement('ol'),
option: document.createElement('option'),
p: document.createElement('p'),
select: document.createElement('select'),
'wz-button': document.createElement('wz-button'),
'wz-card': document.createElement('wz-card'),
'wz-chip': document.createElement('wz-chip'),
'wz-chip-select': document.createElement('wz-chip-select'),
'wz-checkable-chip': document.createElement('wz-checkable-chip'),
};
// ── Settings & timeouts ──────────────────────────────────────────────
let settings = {};
const timeouts = { saveSettingsToStorage: undefined };
/**
* Batch-fetches node objects from SDK by ID array
* @param {number[]} nodeIds - Array of node IDs
* @returns {Object[]} Array of node objects from SDK
*/
function getNodesByIds(nodeIds) {
return nodeIds.map((nodeId) => wmeSdk.DataModel.Nodes.getById({ nodeId }));
}
/**
* Batch-fetches segment objects from SDK by ID array
* @param {number[]} segmentIds - Array of segment IDs
* @returns {Object[]} Array of segment objects from SDK
*/
function getSegmentsByIds(segmentIds) {
const segments = segmentIds.map((segmentId) => {
const seg = wmeSdk.DataModel.Segments.getById({ segmentId });
return seg;
});
return segments;
}
/**
* Detects if selected segments form a continuous connected path
* Returns true if segments have multiple disconnected components
* @param {Object[]} segments - Array of segment objects
* @returns {boolean} True if multiple connected components detected (non-continuous)
*/
function hasMultipleConnectedComponents(segments) {
if (!segments || segments.length <= 1) {
return false;
}
try {
// Build a map of node IDs to segments that use that node
const nodeToSegments = {};
segments.forEach((seg) => {
if (!seg?.fromNodeId || !seg?.toNodeId) {
logWarning(`Segment ${seg?.id} missing node IDs, skipping connectivity check`);
return;
}
if (!nodeToSegments[seg.fromNodeId]) nodeToSegments[seg.fromNodeId] = [];
if (!nodeToSegments[seg.toNodeId]) nodeToSegments[seg.toNodeId] = [];
nodeToSegments[seg.fromNodeId].push(seg.id);
nodeToSegments[seg.toNodeId].push(seg.id);
});
// Track which segments belong to which connected component using union-find
const componentMap = new Map(); // segmentId -> componentId
let componentCount = 0;
// Assign segments to connected components
const visited = new Set();
for (const segment of segments) {
if (visited.has(segment.id)) continue;
// BFS to find all segments in this connected component
const queue = [segment.id];
const component = componentCount++;
while (queue.length > 0) {
const segId = queue.shift();
if (visited.has(segId)) continue;
visited.add(segId);
componentMap.set(segId, component);
// Find the actual segment object
const seg = segments.find((s) => s.id === segId);
if (!seg) continue;
// Find other segments connected through this segment's nodes
const connectedNodeIds = [seg.fromNodeId, seg.toNodeId];
connectedNodeIds.forEach((nodeId) => {
if (nodeToSegments[nodeId]) {
nodeToSegments[nodeId].forEach((connectedSegId) => {
if (!visited.has(connectedSegId)) {
queue.push(connectedSegId);
}
});
}
});
}
}
const isNonContinuous = componentCount > 1;
logDebug(`Segment connectivity check: ${componentCount} connected component(s) - ${isNonContinuous ? 'NON-CONTINUOUS' : 'continuous'}`);
return isNonContinuous;
} catch (err) {
logError('Error checking segment connectivity:', err);
return false; // Assume continuous on error to allow proceeding
}
}
// ===== SHORTCUT VALIDATION & MIGRATION =====
/**
* Validates and migrates shortcut from any format to { raw, combo }
* Handles old string format, new object format, and invalid data
* @param {*} shortcutValue - Shortcut value from any source (string, object, etc)
* @param {string} source - Source label for logging ("localStorage", "server", etc)
* @returns {{ raw: string|null, combo: string|null }} - Validated/migrated shortcut
*/
function validateAndMigrateShortcut(shortcutValue, source = 'settings') {
if (!shortcutValue) {
return { raw: null, combo: null };
}
// Handle stringified JSON (edge case)
if (typeof shortcutValue === 'string') {
try {
// Try to parse if it's a stringified object
if (shortcutValue.startsWith('{')) {
shortcutValue = JSON.parse(shortcutValue);
} else {
// Old format: string value from previous version (e.g., "A+X")
logDebug(`Detected old shortcut format (${source}): "${shortcutValue}"`);
const raw = comboToRawKeycodes(shortcutValue);
const combo = shortcutKeycodesToCombo(raw);
if (raw && combo) {
logDebug(`Migrated shortcut from old format: RAW="${raw}", COMBO="${combo}"`);
return { raw, combo };
} else {
logWarning(`Failed to migrate old shortcut format (${source}), resetting to null`);
return { raw: null, combo: null };
}
}
} catch (e) {
logWarning(`Failed to parse shortcut string (${source}), resetting to null`);
return { raw: null, combo: null };
}
}
if (typeof shortcutValue === 'object' && shortcutValue !== null) {
// New format: should be { raw, combo }
if (typeof shortcutValue.raw === 'string' && typeof shortcutValue.combo === 'string') {
// Valid new format
logDebug(`Loaded shortcut (${source}, valid): RAW="${shortcutValue.raw}", COMBO="${shortcutValue.combo}"`);
return { raw: shortcutValue.raw, combo: shortcutValue.combo };
}
if ((shortcutValue.raw === null || shortcutValue.raw === undefined) && (shortcutValue.combo === null || shortcutValue.combo === undefined)) {
// Valid: no shortcut set
logDebug(`Loaded shortcut (${source}): (none)`);
return { raw: null, combo: null };
}
// Invalid structure
logWarning(`Invalid shortcut format (${source}), resetting to null`);
return { raw: null, combo: null };
}
// Invalid type
logWarning(`Invalid shortcut type (${source}): ${typeof shortcutValue}, resetting to null`);
return { raw: null, combo: null };
}
// ===== SHORTCUT HANDLING WITH SDK FIX =====
// The SDK returns different formats at different times, so we normalize to both RAW and COMBO formats
// RAW: "modifier,keycode" (e.g., "0,48", "4,88", "3,75") - for consistent storage
// COMBO: "key" or "MOD+key" (e.g., "0", "A+X", "CS+K") - for display and SDK registration
const MOD_LOOKUP = { C: 1, S: 2, A: 4 };
const MOD_FLAGS = [
{ flag: 1, char: 'C' },
{ flag: 2, char: 'S' },
{ flag: 4, char: 'A' },
];
const KEYCODE_MAP = Object.fromEntries([...Array.from({ length: 26 }, (_, i) => [65 + i, String.fromCharCode(65 + i)]), ...Array.from({ length: 10 }, (_, i) => [48 + i, String(i)])]);
/**
* Converts SDK combo/raw format to normalized RAW format "modifier,keycode"
* Handles inconsistent SDK return values (sometimes combo, sometimes raw)
*/
function comboToRawKeycodes(comboStr) {
if (!comboStr || typeof comboStr !== 'string') return comboStr;
// Already in raw form (modifier,keycode)
if (/^\d+,\d+$/.test(comboStr)) return comboStr;
// Single digit/letter (no modifiers) - SDK returns "0" but we need "0,48"
if (/^[A-Z0-9]$/.test(comboStr)) {
return `0,${comboStr.charCodeAt(0)}`;
}
// Combo format like "A+X", "CS+K", etc.
const match = comboStr.match(/^([ACS]+)\+([A-Z0-9])$/);
if (!match) return comboStr;
const [, modStr, keyStr] = match;
const modValue = modStr.split('').reduce((acc, m) => acc | (MOD_LOOKUP[m] || 0), 0);
return `${modValue},${keyStr.charCodeAt(0)}`;
}
/**
* Converts RAW format "modifier,keycode" to human-readable COMBO format
* Used for display and SDK registration
*/
function shortcutKeycodesToCombo(keycodeStr) {
if (!keycodeStr || keycodeStr === 'None') return null;
// Already in combo form
if (/^([ACS]+\+)?[A-Z0-9]$/.test(keycodeStr)) return keycodeStr;
// Handle raw format "modifier,keycode"
const parts = keycodeStr.split(',');
if (parts.length !== 2) return keycodeStr;
const intMod = parseInt(parts[0], 10);
const keyNum = parseInt(parts[1], 10);
if (isNaN(intMod) || isNaN(keyNum)) return keycodeStr;
const modLetters = MOD_FLAGS.filter(({ flag }) => intMod & flag)
.map(({ char }) => char)
.join('');
const keyChar = KEYCODE_MAP[keyNum] || String(keyNum);
return modLetters ? `${modLetters}+${keyChar}` : keyChar;
}
/**
* Logs a message to console with script name prefix
* @param {string} message - Message to log
* @param {*} data - Optional data object to log
*/
function log(message, data = '') {
console.log(`${GM_info.script.name}:`, message, data);
}
/**
* Logs an error to console with Error object
* @param {string} message - Error message
* @param {*} data - Optional error details
*/
function logError(message, data = '') {
console.error(`${GM_info.script.name}:`, new Error(message), data);
}
/**
* Logs a warning to console
* @param {string} message - Warning message
* @param {*} data - Optional warning details
*/
function logWarning(message, data = '') {
console.warn(`${GM_info.script.name}:`, message, data);
}
/**
* Logs a debug message (only when debug=true)
* @param {string} message - Debug message
* @param {*} data - Optional debug data
*/
function logDebug(message, data = '') {
if (debug) log(message, data);
}
/**
* Deep or shallow merge objects (like jQuery.extend)
* @param {boolean|object} [deep=false] - If true, do deep merge; otherwise first param is source
* @param {...object} objects - Objects to merge
* @returns {object} Merged object
*/
function $extend(...args) {
const extended = {},
deep = Object.prototype.toString.call(args[0]) === '[object Boolean]' ? args[0] : false,
merge = function (obj) {
Object.keys(obj).forEach((prop) => {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') extended[prop] = $extend(true, extended[prop], obj[prop]);
else if (obj[prop] !== undefined && obj[prop] !== null) extended[prop] = obj[prop];
}
});
};
for (let i = deep ? 1 : 0, { length } = args; i < length; i++) {
if (args[i]) merge(args[i]);
}
return extended;
}
/**
* Creates a DOM element with attributes and event listeners
* @param {string} type - Element type cached in elemCache (div, button, p, etc.)
* @param {object} attrs - Attributes to set (class, id, textContent, innerHTML, disabled, checked, etc.)
* @param {object[]} eventListener - Array of {eventName: callback} objects to attach as listeners
* @returns {Element} Configured DOM element
*/
function createElem(type = '', attrs = {}, eventListener = []) {
const el = elemCache[type]?.cloneNode(false) || elemCache.div.cloneNode(false),
applyEventListeners = function ([evt, cb]) {
return this.addEventListener(evt, cb);
};
Object.keys(attrs).forEach((attr) => {
if (attrs[attr] !== undefined && attrs[attr] !== 'undefined' && attrs[attr] !== null && attrs[attr] !== 'null') {
if (attr === 'disabled' || attr === 'checked' || attr === 'selected' || attr === 'textContent' || attr === 'innerHTML') el[attr] = attrs[attr];
else el.setAttribute(attr, attrs[attr]);
}
});
if (eventListener.length > 0) {
eventListener.forEach((obj) => {
Object.entries(obj).map(applyEventListeners.bind(el));
});
}
return el;
}
/**
* Clears a pending timeout
* @param {Object} obj - Timeout info {timeout: 'name', toIndex: optional}
*/
function checkTimeout(obj) {
if (obj.toIndex) {
if (timeouts[obj.timeout]?.[obj.toIndex]) {
window.clearTimeout(timeouts[obj.timeout][obj.toIndex]);
delete timeouts[obj.timeout][obj.toIndex];
}
} else {
if (timeouts[obj.timeout]) window.clearTimeout(timeouts[obj.timeout]);
timeouts[obj.timeout] = undefined;
}
}
/**
* Loads user settings from localStorage and merges with server settings
* Validates and migrates old shortcut format if needed
* @async
* @returns {Promise<void>}
*/
async function loadSettingsFromStorage() {
const defaultSettings = {
conflictingNames: 'warning',
longJnMove: 'warning',
microDogLegs: 'warning',
nonContinuousSelection: 'warning',
sanityCheck: 'warning',
simplifyTolerance: 1, // Tolerance in meters: 1 (Low) to 10 (Max)
runStraightenUpShortcut: { raw: null, combo: null }, // Store both formats like ZoomShortcuts
lastSaved: 0,
lastVersion: undefined,
},
loadedSettings = JSON.parse(localStorage.getItem(SETTINGS_STORE_NAME));
settings = $extend(true, {}, defaultSettings, loadedSettings);
// Validate and migrate shortcut format from localStorage
const migrated = validateAndMigrateShortcut(settings.runStraightenUpShortcut, 'localStorage');
const needsMigration = JSON.stringify(settings.runStraightenUpShortcut) !== JSON.stringify(migrated);
settings.runStraightenUpShortcut = migrated;
// Save migrated settings so we don't need to migrate again on next load
if (needsMigration) {
settings.lastSaved = Date.now();
localStorage.setItem(SETTINGS_STORE_NAME, JSON.stringify(settings));
logDebug('Settings migrated and saved to localStorage');
}
timeouts.saveSettingsToStorage = window.setTimeout(saveSettingsToStorage, 5000);
return Promise.resolve();
}
/**
* Saves user settings to localStorage
* Queries SDK for current shortcut state to detect user changes
*/
function saveSettingsToStorage() {
checkTimeout({ timeout: 'saveSettingsToStorage' });
if (localStorage) {
// Query SDK for current shortcut value (in case user changed it)
if (wmeSdk && wmeSdk.Shortcuts && wmeSdk.Shortcuts.getAllShortcuts) {
try {
const allShortcuts = wmeSdk.Shortcuts.getAllShortcuts();
const suShortcut = allShortcuts.find((s) => s.shortcutId === 'runStraightenUpShortcut');
if (suShortcut) {
const sdkValue = suShortcut.shortcutKeys;
const raw = comboToRawKeycodes(sdkValue);
const combo = shortcutKeycodesToCombo(raw);
const newShortcut = { raw, combo };
// Only log and update if value actually changed
if (JSON.stringify(settings.runStraightenUpShortcut) !== JSON.stringify(newShortcut)) {
logDebug(`Shortcut changed in SDK: "${sdkValue}" → raw="${raw}", combo="${combo}"`);
settings.runStraightenUpShortcut = newShortcut;
}
}
} catch (err) {
logError('Failed to query shortcut from SDK:', err);
}
}
settings.lastVersion = SCRIPT_VERSION;
settings.lastSaved = Date.now();
localStorage.setItem(SETTINGS_STORE_NAME, JSON.stringify(settings));
logDebug('Settings saved.');
}
}
/**
* Displays "What's New" update notification on version change
*/
function showScriptInfoAlert() {
if (SHOW_UPDATE_MESSAGE && SCRIPT_VERSION !== settings.lastVersion) {
let releaseNotes = "<p>What's New:</p>";
if (SCRIPT_VERSION_CHANGES.length > 0) {
releaseNotes += '<ul>';
for (let idx = 0; idx < SCRIPT_VERSION_CHANGES.length; idx++) releaseNotes += `<li>${SCRIPT_VERSION_CHANGES[idx]}</li>`;
releaseNotes += '</ul>';
} else {
releaseNotes += '<ul><li>Nothing major.</li></ul>';
}
WazeWrap.Interface.ShowScriptUpdate(GM_info.script.name, SCRIPT_VERSION, releaseNotes, SCRIPT_PAGE_URL);
// Update version after alert is shown
settings.lastVersion = SCRIPT_VERSION;
settings.lastSaved = Date.now();
localStorage.setItem(SETTINGS_STORE_NAME, JSON.stringify(settings));
}
}
/**
* Determines direction indicator between two coordinates
* @param {number} a - First coordinate
* @param {number} b - Second coordinate
* @returns {number} -1 (a>b), 0 (equal), 1 (a<b)
*/
function getDeltaDirect(a, b) {
let d = 0.0;
if (a < b) d = 1.0;
else if (a > b) d = -1.0;
return d;
}
/**
* Checks if selected segments share at least one street ID (primary or alternate)
* First segment establishes the "acceptable street IDs" pool (primary + all alternates)
* All subsequent segments must have at least one street ID matching that pool
* @param {Object[]} segmentSelectionArr - Array of segment objects
* @returns {boolean} True if all segments have name continuity with first segment
*/
function checkNameContinuity(segmentSelectionArr = []) {
const streetIds = [],
streetIdsForEach = (streetId) => {
streetIds.push(streetId);
};
for (let idx = 0, { length } = segmentSelectionArr; idx < length; idx++) {
if (idx > 0) {
if (segmentSelectionArr[idx].primaryStreetId > 0 && streetIds.includes(segmentSelectionArr[idx].primaryStreetId))
// eslint-disable-next-line no-continue
continue;
const segStreetIds = segmentSelectionArr[idx].alternateStreetIds || [];
if (segStreetIds.length > 0) {
let included = false;
for (let idx2 = 0, len = segStreetIds.length; idx2 < len; idx2++) {
included = streetIds.includes(segStreetIds[idx2]);
if (included) break;
}
if (included === true)
// eslint-disable-next-line no-continue
continue;
else return false;
}
return false;
}
if (idx === 0) {
if (segmentSelectionArr[idx].primaryStreetId > 0) streetIds.push(segmentSelectionArr[idx].primaryStreetId);
const segStreetIds0 = segmentSelectionArr[idx].alternateStreetIds || [];
if (segStreetIds0.length > 0) segStreetIds0.forEach(streetIdsForEach);
}
}
return true;
}
/**
* Calculates distance between two WGS84 (EPSG:4326) coordinates using Turf.js
* Wrapper around turf.distance() for compatibility with existing code
* @param {number} lon1 - Longitude 1
* @param {number} lat1 - Latitude 1
* @param {number} lon2 - Longitude 2
* @param {number} lat2 - Latitude 2
* @param {string} [measurement='kilometers'] - Unit: 'meters', 'miles', 'feet', 'kilometers', 'nautical miles', 'degrees', or 'radians'
* @returns {number} Distance in specified unit
*/
function distanceBetweenPoints(lon1, lat1, lon2, lat2, measurement = 'kilometers') {
// Turf.distance expects [lon, lat] coordinates
const from = [lon1, lat1];
const to = [lon2, lat2];
// Map measurement names to Turf units (turf uses 'meters', 'miles', 'feet', etc.)
const unitMap = {
meters: 'meters',
miles: 'miles',
feet: 'feet',
kilometers: 'kilometers',
nm: 'nauticalmiles',
'nautical miles': 'nauticalmiles',
degrees: 'degrees',
radians: 'radians',
};
const turfUnit = unitMap[measurement] || 'kilometers';
return turf.distance(from, to, { units: turfUnit });
}
/**
* Calculates angle at point2 using dot product of vectors
* Used for detecting nearly-straight geometry nodes
* @param {number[]} point1 - First point [lon, lat]
* @param {number[]} point2 - Middle point (vertex) [lon, lat]
* @param {number[]} point3 - Third point [lon, lat]
* @returns {number} Angle in degrees (0-180)
*/
/**
* Detects micro dog legs: geometry nodes within 2m of junction nodes
* Indicates possible mapping issues that should be fixed before straightening
* @param {number[]} distinctNodes - Array of node IDs to check
* @param {number} singleSegmentId - Optional: only check this segment
* @returns {boolean} True if micro dog legs detected
*/
/**
* Checks if any geometry nodes are within 2m of segment junction nodes
* Used by both single-segment and multi-segment straightening paths
* @param {Object[]} segments - Array of segment objects to check
* @returns {boolean} True if any geometry node is < 2m from a junction
*/
function checkSegmentsForMicroDogLegs(segments) {
if (!segments || segments.length === 0) return false;
for (let segIdx = 0; segIdx < segments.length; segIdx++) {
const seg = segments[segIdx];
if (!seg || !seg.geometry || !seg.geometry.coordinates) continue;
const coords = seg.geometry.coordinates;
if (coords.length < 3) continue; // Need at least 3 nodes to have geometry nodes
const fromNodeCoord = coords[0];
const toNodeCoord = coords[coords.length - 1];
// Check each geometry node (skip first and last which are endpoints)
for (let i = 1; i < coords.length - 1; i++) {
const coord = coords[i];
const distToFromNode = distanceBetweenPoints(coord[0], coord[1], fromNodeCoord[0], fromNodeCoord[1], 'meters');
const distToToNode = distanceBetweenPoints(coord[0], coord[1], toNodeCoord[0], toNodeCoord[1], 'meters');
const minDist = Math.min(distToFromNode, distToToNode);
if (minDist < 2) {
logDebug(`Micro dog leg: Segment ${seg.id}, node ${i} is ${minDist.toFixed(2)}m from junction`);
return true;
}
}
}
return false;
}
/**
* Main straightening algorithm: aligns segments along line from endpoint to endpoint
* Removes intermediate geometry nodes and moves junction nodes to align with endpoints
* Performs multiple validation checks (name continuity, micro dog legs, long moves, etc.)
* @param {boolean} sanityContinue - User confirmed sanity check (>10 segments)
* @param {boolean} nonContinuousContinue - User confirmed non-continuous selection
* @param {boolean} conflictingNamesContinue - User confirmed conflicting street names
* @param {boolean} microDogLegsContinue - User confirmed micro dog legs present
* @param {boolean} longJnMoveContinue - User confirmed long junction node moves
* @param {Object} passedObj - Pre-calculated straightening data (internal use)
* @returns {void}
*/
function doStraightenSegments(sanityContinue, nonContinuousContinue, conflictingNamesContinue, microDogLegsContinue, longJnMoveContinue, passedObj) {
log('doStraightenSegments called');
// ════════════════════════════════════════════════════════════════════════════════
// SECTION 1: RETRIEVE SELECTION
// Gets the currently selected segments from the WME editor
// ════════════════════════════════════════════════════════════════════════════════
const selection = wmeSdk.Editing.getSelection();
const segments = selection && selection.objectType === 'segment' && selection.ids ? getSegmentsByIds(selection.ids) : [];
const segmentSelection = {
segments: segments,
multipleConnectedComponents: hasMultipleConnectedComponents(segments),
};
// ════════════════════════════════════════════════════════════════════════════════
// SECTION 2: EXECUTE STRAIGHTENING (if all validations passed)
// Only runs when passedObj exists, meaning user has confirmed all warning dialogs
// Applies the pre-calculated geometry updates and node movements
// ════════════════════════════════════════════════════════════════════════════════
if (longJnMoveContinue && passedObj) {
logDebug('Processing with passed object (continuing from confirmation)');
const { segmentsToRemoveGeometryArr, nodesToMoveArr, distinctNodes, endPointNodeIds } = passedObj;
logDebug(`${I18n.t('wmesu.log.StraighteningSegments')}: ${distinctNodes.join(', ')} (${distinctNodes.length})`);
logDebug(`${I18n.t('wmesu.log.EndPoints')}: ${endPointNodeIds.join(' & ')}`);
logDebug(`Segments to update: ${segmentsToRemoveGeometryArr?.length || 0}, Nodes to move: ${nodesToMoveArr?.length || 0}`);
if (segmentsToRemoveGeometryArr?.length > 0) {
logDebug(`Updating geometry for ${segmentsToRemoveGeometryArr.length} segment(s)`);
// Use SDK method to update segment geometry
segmentsToRemoveGeometryArr.forEach((obj) => {
try {
wmeSdk.DataModel.Segments.updateSegment({
segmentId: obj.segment.id,
geometry: obj.newGeo,
});
logDebug(`Removed geometry from segment ${obj.segment.id}: ${obj.segment.geometry.coordinates.length} → ${obj.newGeo.coordinates.length} nodes`);
} catch (err) {
logError(`Failed to update segment ${obj.segment.id}:`, err);
}
});
}
if (nodesToMoveArr?.length > 0) {
// Use SDK method to move nodes
let straightened = false;
nodesToMoveArr.forEach((node) => {
if (Math.abs(node.geometry.coordinates[0] - node.nodeGeo.coordinates[0]) > 0.00000001 || Math.abs(node.geometry.coordinates[1] - node.nodeGeo.coordinates[1]) > 0.00000001) {
try {
wmeSdk.DataModel.Nodes.moveNode({
id: node.node.id,
geometry: node.nodeGeo,
});
straightened = true;
} catch (err) {
logError(`Failed to move node ${node.node.id}:`, err);
}
}
});
if (!straightened) {
logDebug(I18n.t('wmesu.log.AllNodesStraight'));
WazeWrap.Alerts.info(GM_info.script.name, I18n.t('wmesu.log.AllNodesStraight'));
}
}
} else if (segmentSelection.segments.length > 1) {
// ════════════════════════════════════════════════════════════════════════════════
// SECTION 3: MULTI-SEGMENT PROCESSING WITH VALIDATION CHECKS
// ════════════════════════════════════════════════════════════════════════════════
logDebug(`Processing ${segmentSelection.segments.length} segments`);
// Arrays to collect segments and nodes that need updating
const segmentsToRemoveGeometryArr = [], // Segments needing geometry node removal
nodesToMoveArr = []; // Junction nodes that need repositioning
// ────────────────────────────────────────────────────────────────────────────────
// VALIDATION CHECK 1: SANITY CHECK
// Prevents accidental mass edits by requiring confirmation for >10 segments
// Flag: sanityContinue - stays true once confirmed, prevents repeated prompts
// ────────────────────────────────────────────────────────────────────────────────
if (segmentSelection.segments.length > 10 && !sanityContinue) {
logDebug('Sanity check: more than 10 segments');
if (settings.sanityCheck === 'error') {
WazeWrap.Alerts.error(GM_info.script.name, I18n.t('wmesu.error.TooManySegments'));
return;
}
if (settings.sanityCheck === 'warning') {
WazeWrap.Alerts.confirm(
GM_info.script.name,
I18n.t('wmesu.prompts.SanityCheckConfirm'),
() => {
doStraightenSegments(true, false, false, false, false, undefined);
},
() => {},
I18n.t('wmesu.common.Yes'),
I18n.t('wmesu.common.No'),
);
return;
}
}
sanityContinue = true;
// ────────────────────────────────────────────────────────────────────────────────
// VALIDATION CHECK 2: NON-CONTINUOUS SEGMENTS
// Detects if selected segments are not all connected to each other
// Can cause unexpected results when straightening disconnected groups
// Flag: nonContinuousContinue - stays true once confirmed
// ────────────────────────────────────────────────────────────────────────────────
if (segmentSelection.multipleConnectedComponents === true && !nonContinuousContinue) {
if (settings.nonContinuousSelection === 'error') {
WazeWrap.Alerts.error(GM_info.script.name, I18n.t('wmesu.error.NonContinuous'));
return;
}
if (settings.nonContinuousSelection === 'warning') {
WazeWrap.Alerts.confirm(
GM_info.script.name,
I18n.t('wmesu.prompts.NonContinuousConfirm'),
() => {
doStraightenSegments(sanityContinue, true, false, false, false, undefined);
},
() => {},
I18n.t('wmesu.common.Yes'),
I18n.t('wmesu.common.No'),
);
return;
}
}
nonContinuousContinue = true;
// ────────────────────────────────────────────────────────────────────────────────
// VALIDATION CHECK 3: NAME CONTINUITY
// Ensures all selected segments share at least one street name (primary or alternate)
// Straightening segments with different street names could create mapping errors
// Flag: conflictingNamesContinue - stays true once confirmed
// ────────────────────────────────────────────────────────────────────────────────
if (settings.conflictingNames !== 'nowarning') {
const continuousNames = checkNameContinuity(segmentSelection.segments);
if (!continuousNames && !conflictingNamesContinue && settings.conflictingNames === 'error') {
WazeWrap.Alerts.error(GM_info.script.name, I18n.t('wmesu.error.ConflictingNames'));
return;
}
if (!continuousNames && !conflictingNamesContinue && settings.conflictingNames === 'warning') {
WazeWrap.Alerts.confirm(
GM_info.script.name,
I18n.t('wmesu.prompts.ConflictingNamesConfirm'),
() => {
doStraightenSegments(sanityContinue, nonContinuousContinue, true, false, false, undefined);
},
() => {},
I18n.t('wmesu.common.Yes'),
I18n.t('wmesu.common.No'),
);
return;
}
}
conflictingNamesContinue = true;
// ════════════════════════════════════════════════════════════════════════════════
// SECTION 4: DATA PREPARATION & GEOMETRY SIMPLIFICATION
// Collects all endpoint nodes and prepares simplified geometry
// ════════════════════════════════════════════════════════════════════════════════
// allNodeIds: every node ID from every segment's from/to endpoints (includes duplicates)
// dupNodeIds: node IDs that appear multiple times (junction nodes connecting segments)
// endPointNodeIds: node IDs appearing only once (true start/end of selection)
const allNodeIds = [],
dupNodeIds = [];
let endPointNodeIds,
longMove = false;
// Collect all endpoint nodes and prepare geometry for simplification
for (let idx = 0, { length } = segmentSelection.segments; idx < length; idx++) {
allNodeIds.push(segmentSelection.segments[idx].fromNodeId);
allNodeIds.push(segmentSelection.segments[idx].toNodeId);
// Process all segments (already filtered by objectType === 'segment')
const newGeo = structuredClone(segmentSelection.segments[idx].geometry);
// Remove the geometry nodes
if (newGeo.coordinates.length > 2) {
newGeo.coordinates.splice(1, newGeo.coordinates.length - 2);
segmentsToRemoveGeometryArr.push({ segment: segmentSelection.segments[idx], geometry: segmentSelection.segments[idx].geometry, newGeo });
}
}
// Identify which nodes appear more than once (these are junction nodes connecting segments)
allNodeIds.forEach((nodeId, idx) => {
if (allNodeIds.indexOf(nodeId, idx + 1) > -1) {
if (!dupNodeIds.includes(nodeId)) dupNodeIds.push(nodeId);
}
});
// distinctNodes: unique node IDs in the selection (removes duplicates)
// These will be used to calculate straightening positions for all junction nodes
const distinctNodes = [...new Set(allNodeIds)];
// ────────────────────────────────────────────────────────────────────────────────
// VALIDATION CHECK 4: MICRO DOG LEGS
// Detects if any geometry nodes are within 2m of segment endpoints (potential mapping issues)
// Straightening with micro dog legs could make the issues worse
// Flag: microDogLegsContinue - stays true once confirmed
// ────────────────────────────────────────────────────────────────────────────────
if (!microDogLegsContinue && checkSegmentsForMicroDogLegs(segmentSelection.segments) === true) {
if (settings.microDogLegs === 'error') {
WazeWrap.Alerts.error(GM_info.script.name, I18n.t('wmesu.error.MicroDogLegs'));
return;
}
if (settings.microDogLegs === 'warning') {
WazeWrap.Alerts.confirm(
GM_info.script.name,
I18n.t('wmesu.prompts.MicroDogLegsConfirm'),
() => {
doStraightenSegments(sanityContinue, nonContinuousContinue, conflictingNamesContinue, true, false, undefined);
},
() => {},
I18n.t('wmesu.common.Yes'),
I18n.t('wmesu.common.No'),
);
return;
}
}
microDogLegsContinue = true;
// ════════════════════════════════════════════════════════════════════════════════
// SECTION 5: IDENTIFY ENDPOINTS & CALCULATE STRAIGHTENING LINE
// Determines which nodes are the true endpoints and calculates the straightening line
// ════════════════════════════════════════════════════════════════════════════════
// Determine endpoint nodes based on segment connectivity
// If continuous: endpoints are nodes that appear only once (not junctions)
// If discontinuous: endpoints are first segment's start and last segment's end
if (segmentSelection.multipleConnectedComponents === false) endPointNodeIds = distinctNodes.filter((nodeId) => !dupNodeIds.includes(nodeId));
else endPointNodeIds = [segmentSelection.segments[0].fromNodeId, segmentSelection.segments[segmentSelection.segments.length - 1].toNodeId];
// Get the actual endpoint node objects and their coordinates
const endPointNodeObjs = getNodesByIds(endPointNodeIds),
endPointNode1Geo = structuredClone(endPointNodeObjs[0].geometry),
endPointNode2Geo = structuredClone(endPointNodeObjs[1].geometry);
// Normalize endpoints so endpoint1 is always westward (lower longitude) of endpoint2
// This ensures consistent straightening direction regardless of selection order
if (getDeltaDirect(endPointNode1Geo.coordinates[0], endPointNode2Geo.coordinates[0]) < 0) {
let [t] = endPointNode1Geo.coordinates;
[endPointNode1Geo.coordinates[0]] = endPointNode2Geo.coordinates;
endPointNode2Geo.coordinates[0] = t;
[, t] = endPointNode1Geo.coordinates;
[, endPointNode1Geo.coordinates[1]] = endPointNode2Geo.coordinates;
endPointNode2Geo.coordinates[1] = t;
endPointNodeIds.push(endPointNodeIds[0]);
endPointNodeIds.splice(0, 1);
endPointNodeObjs.push(endPointNodeObjs[0]);
endPointNodeObjs.splice(0, 1);
}
// Create straightening line as a Turf LineString for Turf.js perpendicular projection
// This line passes through both endpoint nodes and represents the straightening target
const straighteningLine = turf.lineString([endPointNode1Geo.coordinates, endPointNode2Geo.coordinates]);
// ════════════════════════════════════════════════════════════════════════════════
// SECTION 6: CALCULATE NODE POSITIONS & DETECT LONG MOVES
// For each junction node: calculate its perpendicular projection onto the straightening line
// Also determines if any node would move >10m (triggers separate validation)
// Uses turf.nearestPointOnLine() to project each node onto the straightening line
// ════════════════════════════════════════════════════════════════════════════════
distinctNodes.forEach((nodeId) => {
if (!endPointNodeIds.includes(nodeId)) {
const node = wmeSdk.DataModel.Nodes.getById({ nodeId }),
nodeGeo = structuredClone(node.geometry);
// Use Turf to calculate perpendicular projection of this node onto the straightening line
const nodePoint = turf.point(node.geometry.coordinates);
const projectedPoint = turf.nearestPointOnLine(straighteningLine, nodePoint);
const projectedCoords = projectedPoint.geometry.coordinates;
nodeGeo.coordinates[0] = projectedCoords[0];
nodeGeo.coordinates[1] = projectedCoords[1];
const connectedSegObjs = {};
const segmentIds = node.segmentIds || [];
for (let idx = 0, { length } = segmentIds; idx < length; idx++) {
const segId = segmentIds[idx];
connectedSegObjs[segId] = structuredClone(wmeSdk.DataModel.Segments.getById({ segmentId: segId }).geometry);
}
// Calculate distance node would move to check for long moves (>10m)
const originalCoords = node.geometry.coordinates;
const moveDistance = distanceBetweenPoints(originalCoords[0], originalCoords[1], projectedCoords[0], projectedCoords[1], 'meters');
if (moveDistance > 10) longMove = true;
nodesToMoveArr.push({
node,
geometry: node.geometry,
nodeGeo,
connectedSegObjs,
});
}
});
// ────────────────────────────────────────────────────────────────────────────────
// VALIDATION CHECK 5: LONG JUNCTION NODE MOVES
// Prevents accidentally moving junction nodes more than 10m (could create misalignment)
// Flag: longJnMoveContinue - stays true once confirmed
// When confirmed with passedObj, the actual updates are applied (Section 2)
// ────────────────────────────────────────────────────────────────────────────────
if (longMove && settings.longJnMove === 'error') {
WazeWrap.Alerts.error(GM_info.script.name, I18n.t('wmesu.error.LongJnMove'));
return;
}
if (longMove && settings.longJnMove === 'warning') {
WazeWrap.Alerts.confirm(
GM_info.script.name,
I18n.t('wmesu.prompts.LongJnMoveConfirm'),
() => {
doStraightenSegments(sanityContinue, nonContinuousContinue, conflictingNamesContinue, microDogLegsContinue, true, {
segmentsToRemoveGeometryArr,
nodesToMoveArr,
distinctNodes,
endPointNodeIds,
});
},
() => {},
I18n.t('wmesu.common.Yes'),
I18n.t('wmesu.common.No'),
);
return;
}
doStraightenSegments(sanityContinue, nonContinuousContinue, conflictingNamesContinue, microDogLegsContinue, true, {
segmentsToRemoveGeometryArr,
nodesToMoveArr,
distinctNodes,
endPointNodeIds,
});
} else if (segmentSelection.segments.length === 1) {
// ════════════════════════════════════════════════════════════════════════════════
// SECTION 7: SINGLE SEGMENT PROCESSING
// For a single segment: only removes geometry nodes (no junction node movement needed)
// Still performs micro dog leg check before proceeding
// ════════════════════════════════════════════════════════════════════════════════
const seg = segmentSelection.segments[0];
// ────────────────────────────────────────────────────────────────────────────────
// VALIDATION CHECK 4B: MICRO DOG LEGS (single segment variant)
// Check if any geometry node is within 2m of a segment endpoint
// ────────────────────────────────────────────────────────────────────────────────
if (!microDogLegsContinue && checkSegmentsForMicroDogLegs([seg]) === true) {
if (settings.microDogLegs === 'error') {
WazeWrap.Alerts.error(GM_info.script.name, I18n.t('wmesu.error.MicroDogLegs'));
return;
}
if (settings.microDogLegs === 'warning') {
WazeWrap.Alerts.confirm(
GM_info.script.name,
I18n.t('wmesu.prompts.MicroDogLegsConfirm'),
() => {
doStraightenSegments(sanityContinue, nonContinuousContinue, conflictingNamesContinue, true, false, undefined);
},
() => {},
I18n.t('wmesu.common.Yes'),
I18n.t('wmesu.common.No'),
);
return;
}
}
microDogLegsContinue = true;
const newGeo = structuredClone(seg.geometry);
// Remove the geometry nodes using SDK method
if (newGeo.coordinates.length > 2) {
const beforeCount = seg.geometry.coordinates.length;
newGeo.coordinates.splice(1, newGeo.coordinates.length - 2);
wmeSdk.DataModel.Segments.updateSegment({
segmentId: seg.id,
geometry: newGeo,
});
logDebug(`Straightened segment ${seg.id}: ${beforeCount} → ${newGeo.coordinates.length} nodes`);
}
} else {
// ════════════════════════════════════════════════════════════════════════════════
// SECTION 8: NO VALID SEGMENTS SELECTED
// Alert user to select at least one segment before running the script