-
Notifications
You must be signed in to change notification settings - Fork 1
/
better-osm-org.user.js
6411 lines (5962 loc) · 265 KB
/
better-osm-org.user.js
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 Better osm.org
// @name:ru Better osm.org
// @version 0.5.5
// @description Several improvements for advanced users of osm.org
// @description:ru Скрипт, добавляющий на osm.org полезные картографам функции
// @author deevroman
// @match https://www.openstreetmap.org/*
// @exclude https://www.openstreetmap.org/api*
// @exclude https://www.openstreetmap.org/diary/new
// @exclude https://www.openstreetmap.org/message/new/*
// @exclude https://www.openstreetmap.org/reports/new/*
// @exclude https://www.openstreetmap.org/profile/edit
// @match https://master.apis.dev.openstreetmap.org/*
// @exclude https://master.apis.dev.openstreetmap.org/api/*
// @match https://taginfo.openstreetmap.org/*
// @match https://taginfo.geofabrik.de/*
// @match http://localhost:3000/*
// @exclude http://localhost:3000/api/*
// @match https://www.hdyc.neis-one.org/*
// @match https://hdyc.neis-one.org/*
// @match https://osmcha.org/*
// @license WTFPL
// @namespace https://github.com/deevroman/better-osm-org
// @updateURL https://github.com/deevroman/better-osm-org/raw/master/better-osm-org.user.js
// @downloadURL https://github.com/deevroman/better-osm-org/raw/master/better-osm-org.user.js
// @icon https://www.google.com/s2/favicons?sz=64&domain=openstreetmap.org
// @require https://github.com/deevroman/GM_config/raw/fixed-for-chromium/gm_config.js#sha256=ea04cb4254619543f8bca102756beee3e45e861077a75a5e74d72a5c131c580b
// @require https://raw.githubusercontent.com/deevroman/osmtags-editor/main/osm-auth.iife.min.js#sha256=dcd67312a2714b7a13afbcc87d2f81ee46af7c3871011427ddba1e56900b4edd
// @grant GM_registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_listValues
// @grant GM_deleteValue
// @grant GM.getValue
// @grant GM.setValue
// @grant GM_getResourceURL
// @grant GM_addElement
// @grant GM.xmlHttpRequest
// @grant GM_info
// @connect planet.openstreetmap.org
// @connect planet.maps.mail.ru
// @connect www.hdyc.neis-one.org
// @connect hdyc.neis-one.org
// @connect resultmaps.neis-one.org
// @connect www.openstreetmap.org
// @connect osmcha.org
// @connect overpass-api.de
// @connect raw.githubusercontent.com
// @sandbox JavaScript
// @resource OAUTH_HTML https://github.com/deevroman/better-osm-org/raw/master/finish-oauth.html
// @resource OSMCHA_ICON https://github.com/deevroman/better-osm-org/raw/master/icons/osmcha.ico
// @resource NODE_ICON https://github.com/deevroman/better-osm-org/raw/master/icons/Osm_element_node.svg
// @resource WAY_ICON https://github.com/deevroman/better-osm-org/raw/master/icons/Osm_element_way.svg
// @resource RELATION_ICON https://github.com/deevroman/better-osm-org/raw/master/icons/Taginfo_element_relation.svg
// @resource OSMCHA_LIKE https://github.com/OSMCha/osmcha-frontend/raw/94f091d01ce5ea2f42eb41e70cdb9f3b2d67db88/src/assets/thumbs-up.svg
// @resource OSMCHA_DISLIKE https://github.com/OSMCha/osmcha-frontend/raw/94f091d01ce5ea2f42eb41e70cdb9f3b2d67db88/src/assets/thumbs-down.svg
// @run-at document-end
// ==/UserScript==
//<editor-fold desc="config" defaultstate="collapsed">
/*global osmAuth*/
/*global GM*/
/*global GM_info*/
/*global GM_config*/
/*global GM_addElement*/
/*global GM_getValue*/
/*global GM_setValue*/
/*global GM_listValues*/
/*global GM_deleteValue*/
/*global GM_getResourceURL*/
/*global GM_registerMenuCommand*/
/*global unsafeWindow*/
/*global exportFunction*/
/*global cloneInto*/
GM_config.init(
{
'id': 'Config',
'title': ' ',
'fields':
{
'OffMapDim': {
'label': 'Off map dim in dark mode 🆕',
'type': 'checkbox',
'default': false,
'labelPos': 'right'
},
'DarkModeForMap': {
'label': 'Invert map colors in dark mode 🆕',
'type': 'checkbox',
'default': false,
'labelPos': 'right'
},
'CompactChangesetsHistory':
{
'section': ["Viewing edits"],
'label': 'Compact changesets history',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right',
},
'VersionsDiff':
{
'label': 'Add tags diff in history',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right',
},
'ChangesetQuickLook':
{
'label': 'Add QuickLook for small changesets ',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'ShowChangesetGeometry':
{
'label': 'Show geometry of objects in changeset β',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'MassChangesetsActions':
{
'label': 'Add actions for changesets list (mass revert, filtering, ...)',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'ResolveNotesButtons':
{
'section': ["Working with notes"],
'label': 'Show addition resolve buttons',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'HideNoteHighlight':
{
'label': 'Hide note highlight',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'SatelliteLayers':
{
'label': 'Add satellite layers for notes page (Firefox only)',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'RevertButton':
{
'section': ["New actions"],
'label': 'Revert&Osmcha changeset button',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'Deletor':
{
'label': 'Button for node deletion',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'OneClickDeletor':
{
'label': 'Delete node without confirmation',
'type': 'checkbox',
'default': false,
'labelPos': 'right'
},
// 'HideLinesForDataView':
// {
// 'label': 'Hide lines in Data View (experimental)',
// 'type': 'checkbox',
// 'default': 'unchecked'
// },
'HDYCInProfile':
{
'section': ["Other"],
'label': 'Add HDYC to user profile',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'NavigationViaHotkeys':
{
'label': 'Add hotkeys <a href="https://github.com/deevroman/better-osm-org#Hotkeys" target="_blank">(List)</a>', // add help button with list
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'NewEditorsLinks':
{
'label': 'Add new editors (Rapid, ... ?)',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'RelationVersionViewer':
{
'label': 'Add relation version view via overpass',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'ResetSearchFormFocus': {
'label': 'Reset search form focus',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'Swipes': {
'label': 'Add swipes between user changesets',
'type': 'checkbox',
'default': false,
'labelPos': 'right'
},
'ResizableSidebar': {
'label': 'Add slider for sidebar width',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
},
'ClickableAvatar': {
'label': 'Click by avatar for open changesets',
'type': 'checkbox',
'default': 'checked',
'labelPos': 'right'
}
},
frameStyle: `
border: 1px solid #000;
height: min(85%, 700px);
width: max(25%, 380px);
z-index: 9999;
opacity: 0;
position: absolute;
margin-left: auto;
margin-right: auto;
`
});
let onInit = config => new Promise(resolve => {
let isInit = () => setTimeout(() =>
config.isInit ? resolve() : isInit(), 0);
isInit();
});
let init = onInit(GM_config);
const prod_server = {
apiBase: "https://www.openstreetmap.org/api/0.6/",
apiUrl: "https://www.openstreetmap.org/api/0.6",
url: "https://www.openstreetmap.org",
origin: "https://www.openstreetmap.org"
}
const ohm_prod_server = {
apiBase: "https://www.openhistoricalmap.org/api/0.6/",
apiUrl: "https://www.openhistoricalmap.org/api/0.6",
url: "https://www.openhistoricalmap.org",
origin: "https://www.openhistoricalmap.org"
}
const dev_server = {
apiBase: "https://master.apis.dev.openstreetmap.org/api/0.6/",
apiUrl: "https://master.apis.dev.openstreetmap.org/api/0.6",
url: "https://master.apis.dev.openstreetmap.org",
origin: "https://master.apis.dev.openstreetmap.org",
}
const local_server = {
apiBase: "http://localhost:3000/api/0.6/",
apiUrl: "http://localhost:3000/api/0.6",
url: "http://localhost:3000",
origin: "http://localhost:3000",
}
let osm_server = dev_server;
const planetOrigin = "https://planet.maps.mail.ru"
//</editor-fold>
function tagsToXml(doc, node, tags) {
for (const [k, v] of Object.entries(tags)) {
let tag = doc.createElement('tag');
tag.setAttribute('k', k);
tag.setAttribute('v', v);
node.appendChild(tag);
}
}
function makeAuth() {
return osmAuth.osmAuth({
apiUrl: osm_server.apiUrl,
url: osm_server.url,
client_id: "FwA",
client_secret: "ZUq",
redirect_uri: GM_getResourceURL("OAUTH_HTML"),
scope: "write_api",
auto: true
});
}
const mainTags = ["shop", "building", "amenity", "man_made", "highway", "natural", "aeroway", "historic", "railway", "tourism", "landuse", "leisure"]
function addRevertButton() {
if (!location.pathname.includes("/changeset")) return
if (document.querySelector('#revert_button_class')) return true;
const sidebar = document.querySelector("#sidebar_content h2");
if (sidebar) {
hideSearchForm();
// sidebar.classList.add("changeset-header")
let changeset_id = sidebar.innerHTML.match(/(\d+)/)[0];
sidebar.innerHTML += ` <a href="https://revert.monicz.dev/?changesets=${changeset_id}" target=_blank rel="noreferrer" id=revert_button_class title="Open osm-revert">↩️</a>
<a href="https://osmcha.org/changesets/${changeset_id}" target="_blank" rel="noreferrer"><img src="${GM_getResourceURL("OSMCHA_ICON", false)}" id="osmcha_link"></a>`;
document.querySelector("#revert_button_class").style.textDecoration = "none"
const osmcha_link = document.querySelector("#osmcha_link");
osmcha_link.style.height = "1em";
osmcha_link.style.cursor = "pointer";
osmcha_link.style.marginTop = "-3px";
osmcha_link.title = "Open changeset in OSMCha (or press O)\n(shift + O for open Achavi)";
if (isDarkMode()) {
osmcha_link.style.filter = "invert(0.7)";
}
// find deleted user
// todo extract
let metainfoHTML = document.querySelector(".browse-section > .details")
let time = Array.from(metainfoHTML.children).find(i => i.localName === "time")
if (Array.from(metainfoHTML.children).some(e => e.localName === "a")) {
let a = Array.from(metainfoHTML.children).find(i => i.localName === "a")
metainfoHTML.innerHTML = ""
metainfoHTML.appendChild(time)
metainfoHTML.appendChild(document.createTextNode(" "))
metainfoHTML.appendChild(a)
metainfoHTML.appendChild(document.createTextNode(" "))
getCachedUserInfo(a.textContent).then((res) => {
a.before(makeBadge(res))
a.before(document.createTextNode(" "))
})
} else {
let time = Array.from(metainfoHTML.children).find(i => i.localName === "time")
metainfoHTML.innerHTML = ""
metainfoHTML.appendChild(time)
let findBtn = document.createElement("span")
findBtn.textContent = " 🔍 "
findBtn.value = changeset_id
findBtn.datetime = time.dateTime
findBtn.style.cursor = "pointer"
findBtn.onclick = findChangesetInDiff
metainfoHTML.appendChild(findBtn)
}
// compact changeset tags
if (!document.querySelector(".browse-tag-list[compacted]")) {
document.querySelectorAll(".browse-tag-list tr").forEach(i => {
const key = i.querySelector("th")
if (key.textContent === "host") {
if (i.querySelector("td").textContent === "https://www.openstreetmap.org/edit") {
i.style.display = "none"
}
} else if (key.textContent.startsWith("ideditor:")) {
key.title = key.textContent
key.textContent = key.textContent.replace("ideditor:", "iD:")
}
})
document.querySelector(".browse-tag-list")?.setAttribute("compacted", "true")
}
}
const textarea = document.querySelector("#sidebar_content textarea");
if (textarea) {
textarea.rows = 1;
let comment = document.querySelector("#sidebar_content button[name=comment]")
if (comment) {
comment.hidden = true
textarea.addEventListener("input", () => {
comment.hidden = false
}
)
textarea.addEventListener("click", () => {
textarea.rows = textarea.rows + 2
comment.hidden = false
}, {once: true}
)
comment.onclick = () => {
[500, 1000, 2000, 4000].map(i => setTimeout(setupRevertButton, i));
}
}
}
const tagsHeader = document.querySelector("#sidebar_content h4");
if (tagsHeader) {
tagsHeader.remove()
}
const primaryButtons = document.querySelector("[name=subscribe], [name=unsubscribe]")
if (primaryButtons && osm_server.url === prod_server.url) {
const changeset_id = sidebar.innerHTML.match(/(\d+)/)[0];
async function uncheck(changeset_id) {
return await GM.xmlHttpRequest({
url: `https://osmcha.org/api/v1/changesets/${changeset_id}/uncheck/`,
headers: {
"Authorization": "Token " + GM_getValue("OSMCHA_TOKEN"),
},
method: "PUT",
});
}
const likeImgRes = GM_getResourceURL("OSMCHA_LIKE", false)
const dislikeImgRes = GM_getResourceURL("OSMCHA_DISLIKE", false)
const likeBtn = document.createElement("span")
const likeImg = document.createElement("img")
likeImg.title = "OSMCha review like"
likeImg.src = likeImgRes
likeImg.style.height = "1.1em"
likeImg.style.cursor = "pointer"
likeImg.style.filter = "grayscale(1)"
likeImg.style.marginTop = "-8px"
likeBtn.onclick = async e => {
const osmchaToken = GM_getValue("OSMCHA_TOKEN")
if (!osmchaToken) {
alert("Please, login into OSMCha")
window.open("https://osmcha.org")
return;
}
if (e.target.hasAttribute("active")) {
await uncheck(changeset_id)
await updateReactions()
return
}
if (document.querySelector(".check_user")) {
await uncheck(changeset_id)
await updateReactions()
}
await GM.xmlHttpRequest({
url: `https://osmcha.org/api/v1/changesets/${changeset_id}/set-good/`,
headers: {
"Authorization": "Token " + GM_getValue("OSMCHA_TOKEN"),
},
method: "PUT",
});
await updateReactions()
}
likeBtn.appendChild(likeImg)
const dislikeBtn = document.createElement("span")
const dislikeImg = document.createElement("img")
dislikeImg.title = "OSMCha review like"
dislikeImg.src = likeImgRes // dirty hack for different graystyle colors
dislikeImg.style.height = "1.1em"
dislikeImg.style.cursor = "pointer"
dislikeImg.style.filter = "grayscale(1)"
dislikeImg.style.transform = "rotate(180deg)"
dislikeImg.style.marginTop = "3px"
dislikeBtn.appendChild(dislikeImg)
dislikeBtn.onclick = async e => {
const osmchaToken = GM_getValue("OSMCHA_TOKEN")
if (!osmchaToken) {
alert("Please, login into OSMCha")
window.open("https://osmcha.org")
return;
}
if (e.target.hasAttribute("active")) {
await uncheck(changeset_id)
await updateReactions()
return
}
if (document.querySelector(".check_user")) {
await uncheck(changeset_id)
await updateReactions()
}
await GM.xmlHttpRequest({
url: `https://osmcha.org/api/v1/changesets/${changeset_id}/set-harmful/`,
headers: {
"Authorization": "Token " + GM_getValue("OSMCHA_TOKEN"),
},
method: "PUT",
});
await updateReactions()
}
async function updateReactions() {
const res = await GM.xmlHttpRequest({
url: "https://osmcha.org/api/v1/changesets/" + changeset_id,
method: "GET",
headers: {
"Authorization": "Token " + GM_getValue("OSMCHA_TOKEN"),
},
responseType: "json"
})
if (res.status === 404) {
console.warn("Changeset not found in OSMCha database")
return;
}
const json = res.response;
if (json['properties']['check_user']) {
document.querySelector(".check_user")?.remove()
likeImg.style.filter = "grayscale(1)"
dislikeImg.style.filter = "grayscale(1)"
const username = document.createElement("span")
username.classList.add("check_user")
username.textContent = json['properties']['check_user']
if (json['properties']['harmful'] === true) {
dislikeImg.style.filter = ""
dislikeImg.style.transform = ""
dislikeImg.src = dislikeImgRes
dislikeImg.setAttribute("active", "true")
username.style.color = "red"
dislikeBtn.after(username)
} else {
likeImg.style.filter = ""
likeImg.setAttribute("active", "true")
username.style.color = "green"
likeBtn.after(username)
}
} else {
likeImg.style.filter = "grayscale(1)"
dislikeImg.style.filter = "grayscale(1)"
dislikeImg.style.transform = "rotate(180deg)"
dislikeImg.src = likeImgRes
likeImg.removeAttribute("active")
dislikeImg.removeAttribute("active")
document.querySelector(".check_user")?.remove()
}
}
setTimeout(updateReactions, 0);
primaryButtons.before(likeBtn)
primaryButtons.before(document.createTextNode("\xA0"))
primaryButtons.before(dislikeBtn)
primaryButtons.before(document.createTextNode("\xA0"))
}
document.querySelectorAll('#sidebar_content li[id^=c] small > a[href^="/user/"]').forEach(elem => {
getCachedUserInfo(elem.textContent).then(info => {
elem.before(makeBadge(info))
})
})
}
function setupRevertButton() {
if (!location.pathname.includes("/changeset")) return;
let timerId = setInterval(() => {
if (addRevertButton()) clearInterval(timerId)
}, 100);
setTimeout(() => {
clearInterval(timerId);
console.debug('stop try add revert button');
}, 3000);
addRevertButton();
}
function hideSearchForm() {
if (location.pathname.includes("/search") || location.pathname.includes("/directions")) return;
if (!document.querySelector("#sidebar .search_forms")?.hasAttribute("hidden")) {
document.querySelector("#sidebar .search_forms")?.setAttribute("hidden", "true")
}
function showSearchForm() {
document.querySelector("#sidebar .search_forms")?.removeAttribute("hidden");
cleanAllObjects()
}
document.querySelector("#sidebar_content .btn-close")?.addEventListener("click", showSearchForm)
document.querySelector("h1 .icon-link")?.addEventListener("click", showSearchForm)
}
let sidebarObserver = null;
let timestampMode = "natural_text"
function makeTimesSwitchable() {
document.querySelectorAll("time:not([natural_text])").forEach(j => {
j.setAttribute("natural_text", j.textContent)
if (timestampMode !== "natural_text") {
j.textContent = j.getAttribute("datetime")
}
})
function switchTimestamp() {
if (window.getSelection().type === "Range") {
return
}
document.querySelectorAll("time:not([natural_text])").forEach(j => {
j.setAttribute("natural_text", j.textContent)
})
function switchElement(j) {
if (j.textContent === j.getAttribute("natural_text")) {
j.textContent = j.getAttribute("datetime")
timestampMode = "datetime"
} else {
j.textContent = j.getAttribute("natural_text")
timestampMode = "natural_text"
}
}
document.querySelectorAll("time").forEach(switchElement)
}
document.querySelectorAll("time:not([switchable])").forEach(i => i.addEventListener("click", switchTimestamp))
document.querySelectorAll("time:not([switchable])").forEach(i => i.setAttribute("switchable", "true"))
}
function setupCompactChangesetsHistory() {
if (!location.pathname.includes("/history") && !location.pathname.includes("/changeset")) {
return;
}
if (location.pathname.includes("/changeset/")) {
if (document.querySelector("#sidebar_content ul")) {
document.querySelector("#sidebar_content ul").querySelectorAll("a:not(.page-link)").forEach(i => i.setAttribute("target", "_blank"));
}
}
let styleText = `
.changesets p {
margin-bottom: 0;
font-weight: 788;
font-style: italic;
font-size: 14px !important;
}
@media (prefers-color-scheme: dark) {
.changesets time {
color: darkgray;
}
.changesets p {
font-weight: 400;
}
.changeset_id.custom-changeset-id-click {
color: #767676 !important;
}
}
.browse-section > p:nth-of-type(1) {
font-size: 14px !important;
font-style: italic;
}
.map-layout #sidebar {
width: 450px;
}
/*for id copied*/
.copied {
background-color: red;
transition:all 0.3s;
}
.was-copied {
background-color: none;
transition:all 0.3s;
}
#sidebar_content h2:not(.changeset-header) {
font-size: 1rem;
}
#sidebar {
border-top: solid;
border-top-width: 1px;
border-top-color: rgba(var(--bs-secondary-bg-rgb), var(--bs-bg-opacity)) !important;
}
`;
GM_addElement(document.head, "style", {
textContent: styleText,
});
// увы, инвалидация в этом месте ломает зум при загрузке объекте самим сайтом
// try {
// getMap()?.invalidateSize()
// } catch (e) {
// }
function handleNewChangesets() {
// remove useless
document.querySelectorAll("#sidebar .changesets .col").forEach((e) => {
e.childNodes[0].textContent = ""
})
makeTimesSwitchable();
hideSearchForm();
}
handleNewChangesets();
sidebarObserver?.disconnect();
sidebarObserver = new MutationObserver(handleNewChangesets);
if (document.querySelector('#sidebar_content')) {
sidebarObserver.observe(document.querySelector('#sidebar_content'), {childList: true, subtree: true});
}
}
function addResolveNotesButtons() {
if (!location.pathname.includes("/note")) return
if (document.querySelector('.resolve-note-done')) return true;
if (document.querySelector('#timeback-btn')) return true;
blurSearchField();
document.querySelectorAll(".overflow-hidden a").forEach(i => {
i.setAttribute("target", "_blank")
})
makeTimesSwitchable()
try {
// timeback button
let timestamp = document.querySelector("#sidebar_content time").dateTime;
let timeSource = "note creation date"
const mapsmeDate = document.querySelector(".overflow-hidden")?.textContent?.match(/OSM data version: (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)/);
if (mapsmeDate) {
timestamp = mapsmeDate[1];
timeSource = "MAPS.ME snapshot date"
}
const organicmapsDate = document.querySelector(".overflow-hidden")?.textContent?.match(/OSM snapshot date: (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)/);
if (organicmapsDate) {
timestamp = organicmapsDate[1];
timeSource = "Organic Maps snapshot date"
}
const lat = document.querySelector("#sidebar_content .latitude").textContent.replace(",", ".");
const lon = document.querySelector("#sidebar_content .longitude").textContent.replace(",", ".");
const zoom = 18;
const query =
`// via ${timeSource}
[date:"${timestamp}"];
(
node({{bbox}});
way({{bbox}});
//relation({{bbox}});
);
(._;>;);
out meta;
`;
let btn = document.createElement("a")
btn.id = "timeback-btn";
btn.textContent = " 🕰";
btn.style.cursor = "pointer"
document.querySelector("#sidebar_content time").after(btn);
btn.onclick = () => {
window.open(`https://overpass-turbo.eu/?Q=${encodeURI(query)}&C=${lat};${lon};${zoom}&R`)
}
} catch {
console.error("setup timeback button fail");
}
if (!document.querySelector("#sidebar_content textarea.form-control")) {
return;
}
const auth = makeAuth();
let note_id = location.pathname.match(/note\/(\d+)/)[1];
let b = document.createElement("button");
b.classList.add("resolve-note-done", "btn", "btn-primary");
b.textContent = "👌";
document.querySelectorAll("form.mb-3")[0].before(b);
document.querySelectorAll("form.mb-3")[0].before(document.createElement("p"));
document.querySelector("form.mb-3 .form-control").rows = 3;
document.querySelector(".resolve-note-done").onclick = () => {
auth.xhr({
method: 'POST',
path: osm_server.apiBase + 'notes/' + note_id + "/close.json?text=" + encodeURI("👌"),
prefix: false,
}, (err) => {
if (err) {
alert(err);
}
window.location.reload();
}
);
}
}
function setupResolveNotesButtons(path) {
if (!path.includes("/note")) return;
let timerId = setInterval(addResolveNotesButtons, 100);
setTimeout(() => {
clearInterval(timerId);
console.debug('stop try add resolve note button');
}, 3000);
addResolveNotesButtons();
}
function addDeleteButton() {
if (!location.pathname.includes("/node/")) return;
if (location.pathname.includes("/history")) return;
if (document.querySelector('.delete_object_button_class')) return true;
let match = location.pathname.match(/(node|way)\/(\d+)/);
if (!match) return;
let object_type = match[1];
let object_id = match[2];
const auth = makeAuth();
let link = document.createElement('a');
link.text = ['ru-RU', 'ru'].includes(navigator.language) ? "Выпилить!" : "Delete";
link.href = "";
link.classList.add("delete_object_button_class");
// skip deleted
if (document.querySelectorAll(".browse-section h4").length < 2 && document.querySelector(".browse-section .latitude") === null) {
link.setAttribute("hidden", true);
return;
}
// skip having a parent
if (document.querySelectorAll(".browse-section details").length !== 0) {
return;
}
if (!document.querySelector(".secondary-actions")) return;
document.querySelector(".secondary-actions").appendChild(link);
link.after(document.createTextNode("\xA0"));
link.before(document.createTextNode("\xA0· "));
if (!document.querySelector(".secondary-actions .edit_tags_class")) {
const tagsEditorExtensionWaiter = new MutationObserver(() => {
if (document.querySelector(".secondary-actions .edit_tags_class")) {
tagsEditorExtensionWaiter.disconnect()
const tmp = document.createComment('')
const node1 = document.querySelector(".delete_object_button_class")
const node2 = document.querySelector(".edit_tags_class")
node2.replaceWith(tmp)
node1.replaceWith(node2)
tmp.replaceWith(node1)
console.log("Delete button replaced for Tags editor extension capability")
}
})
tagsEditorExtensionWaiter.observe(document.querySelector(".secondary-actions"), {
childList: true,
subtree: true
})
setTimeout(() => tagsEditorExtensionWaiter.disconnect(), 3000)
}
function deleteObject(e) {
e.preventDefault();
link.classList.add("dbclicked");
console.log("Opening changeset");
auth.xhr({
method: 'GET',
path: osm_server.apiBase + object_type + '/' + object_id,
prefix: false,
}, function (err, objectInfo) {
if (err) {
console.log(err);
return;
}
let tagsHint = ""
const tags = Array.from(objectInfo.children[0].children[0]?.children)
for (const i of tags) {
if (mainTags.includes(i.getAttribute("k"))) {
tagsHint = tagsHint + ` ${i.getAttribute("k")}=${i.getAttribute("v")}`;
break
}
}
for (const i of tags) {
if (i.getAttribute("k") === "name") {
tagsHint = tagsHint + ` ${i.getAttribute("k")}=${i.getAttribute("v")}`;
break
}
}
const changesetTags = {
'created_by': 'better osm.org',
'comment': tagsHint !== "" ? `Delete${tagsHint}` : `Delete ${object_type} ${object_id}`
};
let changesetPayload = document.implementation.createDocument(null, 'osm');
let cs = changesetPayload.createElement('changeset');
changesetPayload.documentElement.appendChild(cs);
tagsToXml(changesetPayload, cs, changesetTags);
const chPayloadStr = new XMLSerializer().serializeToString(changesetPayload);
auth.xhr({
method: 'PUT',
path: osm_server.apiBase + 'changeset/create',
prefix: false,
content: chPayloadStr
}, function (err1, result) {
const changesetId = result;
console.log(changesetId);
objectInfo.children[0].children[0].setAttribute('changeset', changesetId);
auth.xhr({
method: 'DELETE',
path: osm_server.apiBase + object_type + '/' + object_id,
prefix: false,
content: objectInfo
}, function (err2) {
if (err2) {
console.log({changesetError: err2});
}
auth.xhr({
method: 'PUT',
path: osm_server.apiBase + 'changeset/' + changesetId + '/close',
prefix: false
}, function (err3) {
if (!err3) {
window.location.reload();
}
});
});
});
});
}
if (GM_config.get("OneClickDeletor")) {
link.onclick = deleteObject;
} else {
link.onclick = (e) => {
e.preventDefault();
setTimeout(() => {
if (!link.classList.contains("dbclicked")) {
link.text = "Double click please";
}
}, 200);
}
link.ondblclick = deleteObject
}
}
function setupDeletor(path) {
if (!path.includes("/node/") /*&& !url.includes("/way/")*/) return;
let timerId = setInterval(addDeleteButton, 100);
setTimeout(() => {
clearInterval(timerId);
console.debug('stop try add delete button');
}, 3000);
addDeleteButton();
}
let mapDataSwitcherUnderSupervision = false
function hideNoteHighlight() {
let g = document.querySelector("g");
if (!g || g.childElementCount === 0) return;
let mapDataCheckbox = document.querySelector(".layers-ui li:nth-child(2) > label:nth-child(1) > input:nth-child(1)")
if (!mapDataCheckbox.checked) {
if (mapDataSwitcherUnderSupervision) return;
mapDataSwitcherUnderSupervision = true
mapDataCheckbox.addEventListener("click", () => {
mapDataSwitcherUnderSupervision = false
hideNoteHighlight();
}, {once: true})
return;
}
if (g.childNodes[g.childElementCount - 1].getAttribute("stroke") === "#FF6200"
&& g.childNodes[g.childElementCount - 1].getAttribute("d").includes("a20,20 0 1,0 -40,0 ")) {
g.childNodes[g.childElementCount - 1].remove();
document.querySelector("img.leaflet-marker-icon:last-child").style.filter = "contrast(120%)";
}
}
function setupHideNoteHighlight(path) {
if (!path.includes("/note/")) return;
let timerId = setInterval(hideNoteHighlight, 1000);
setTimeout(() => {
clearInterval(timerId);
console.debug('stop removing note highlight');
}, 5000);
hideNoteHighlight();
}
//<editor-fold desc="satellite switching">
const OSMPrefix = "https://tile.openstreetmap.org/"
const ESRIPrefix = "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/"
const ESRIBetaPrefix = "https://clarity.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile/"
let SatellitePrefix = ESRIPrefix
let SAT_MODE = "🛰"
let MAPNIK_MODE = "🗺️"
let currentTilesMode = MAPNIK_MODE;
let tilesObserver = undefined;
function invertTilesMode(mode) {
return mode === "🛰" ? "🗺️" : "🛰";
}
function parseOSMTileURL(url) {
let match = url.match(new RegExp(`${OSMPrefix}(\\d+)\\/(\\d+)\\/(\\d+)\\.png`))
if (!match) {
return false
}
return {
x: match[2],
y: match[3],
z: match[1],
}
}
function parseESRITileURL(url) {
let match = url.match(new RegExp(`${SatellitePrefix}(\\d+)\\/(\\d+)\\/(\\d+)`))
if (!match) {
return false
}
return {
x: match[3],
y: match[2],
z: match[1],