]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/application.js
Merge remote-tracking branch 'upstream/pull/6958'
[rails.git] / app / assets / javascripts / application.js
1 //= require jquery3
2 //= require jquery_ujs
3 //= require jquery.throttle-debounce
4 //= require js-cookie/dist/js.cookie
5 //= require popper
6 //= require bootstrap-sprockets
7 //= require osm
8 //= require leaflet/dist/leaflet-src
9 //= require leaflet.osm
10 //= require maplibre-gl/dist/maplibre-gl
11 //= require leaflet.maplibre
12 //= require leaflet.shortbread
13 //= require leaflet.thunderforest
14 //= require i18n
15 //= require leaflet.maptiler
16 //= require leaflet.map
17 //= require leaflet.zoom
18 //= require leaflet.locationfilter
19 //= require matomo
20 //= require richtext
21 //= require language_selector
22
23 {
24   const application_data = $("head").data();
25   const locale = application_data.locale;
26
27   OSM.i18n.defaultLocale = OSM.DEFAULT_LOCALE;
28   OSM.i18n.locale = application_data.locale;
29
30   import(OSM.MAKE_PLURAL_CARDINALS).then((plurals) => {
31     // '-' are replaced with '_' in https://github.com/eemeli/make-plural/tree/main/packages/plurals
32     const pluralizer = plurals[locale.replace(/\W+/g, "_")] || plurals[locale.split("-")[0]];
33     if (pluralizer) {
34       OSM.i18n.pluralization.register(locale, (_, count) => [pluralizer(count), "other"]);
35     }
36   });
37
38   OSM.preferred_editor = application_data.preferredEditor;
39   OSM.preferred_languages = application_data.preferredLanguages;
40
41   if (application_data.user) {
42     OSM.user = application_data.user;
43
44     if (application_data.userHome) {
45       OSM.home = application_data.userHome;
46     }
47   }
48
49   if (application_data.location) {
50     OSM.location = application_data.location;
51   }
52 }
53
54 /*
55  * Called as the user scrolls/zooms around to manipulate hrefs of the
56  * view tab and various other links
57  */
58 window.updateLinks = function (loc, zoom, layers, object) {
59   $(".geolink").each(function (index, link) {
60     let href = link.href.split(/[?#]/)[0];
61     const queryArgs = new URLSearchParams(link.search),
62           editlink = $(link).hasClass("editlink");
63
64     for (const arg of ["node", "way", "relation", "changeset", "note"]) {
65       queryArgs.delete(arg);
66     }
67
68     if (object && editlink) {
69       queryArgs.set(object.type, object.id);
70     }
71
72     const query = queryArgs.toString();
73     if (query) href += "?" + query;
74
75     const hashArgs = {
76       lat: loc.lat,
77       lon: "lon" in loc ? loc.lon : loc.lng,
78       zoom: zoom
79     };
80
81     if (layers && !editlink) {
82       hashArgs.layers = layers;
83     }
84
85     href += OSM.formatHash(hashArgs);
86
87     link.href = href;
88   });
89
90   // Disable the button group and also the buttons to avoid
91   // inconsistent behaviour when zooming
92   const editDisabled = zoom < 13;
93   $("#edit_tab")
94     .tooltip({ placement: "bottom" })
95     .tooltip(editDisabled ? "enable" : "disable")
96     .toggleClass("disabled", editDisabled)
97     .find("a")
98     .toggleClass("disabled", editDisabled);
99 };
100
101 $(function () {
102   // NB: Turns Turbo Drive off by default. Turbo Drive must be opt-in on a per-link and per-form basis
103   // See https://turbo.hotwired.dev/reference/drive#turbo.session.drive
104   Turbo.session.drive = false;
105
106   const $expandedSecondaryMenu = $("header nav.secondary > ul"),
107         $collapsedSecondaryMenu = $("#compact-secondary-nav > ul"),
108         secondaryMenuItems = [],
109         breakpointWidth = 768;
110   let moreItemWidth = 0;
111
112   OSM.csrf = {};
113   OSM.csrf[($("meta[name=csrf-param]").attr("content"))] = $("meta[name=csrf-token]").attr("content");
114
115   function updateHeader() {
116     const windowWidth = $(window).width();
117
118     if (windowWidth < breakpointWidth) {
119       expandAllSecondaryMenuItems();
120     } else {
121       if (secondaryMenuItems.length === 0) {
122         $expandedSecondaryMenu.find("li:not(#compact-secondary-nav)").each(function () {
123           secondaryMenuItems.push([this, $(this).width()]);
124         });
125         moreItemWidth = $("#compact-secondary-nav").width();
126       }
127       const availableWidth = $expandedSecondaryMenu.width();
128       secondaryMenuItems.forEach(function (item) {
129         $(item[0]).remove();
130       });
131       let runningWidth = 0,
132           i = 0,
133           requiredWidth;
134       for (; i < secondaryMenuItems.length; i++) {
135         runningWidth += secondaryMenuItems[i][1];
136         if (i < secondaryMenuItems.length - 1) {
137           requiredWidth = runningWidth + moreItemWidth;
138         } else {
139           requiredWidth = runningWidth;
140         }
141         if (requiredWidth > availableWidth) {
142           break;
143         }
144         expandSecondaryMenuItem($(secondaryMenuItems[i][0]));
145       }
146       for (; i < secondaryMenuItems.length; i++) {
147         collapseSecondaryMenuItem($(secondaryMenuItems[i][0]));
148       }
149     }
150   }
151
152   function expandAllSecondaryMenuItems() {
153     secondaryMenuItems.forEach(function (item) {
154       expandSecondaryMenuItem($(item[0]));
155     });
156   }
157
158   function expandSecondaryMenuItem($item) {
159     $item.children("a")
160       .removeClass("dropdown-item")
161       .addClass("nav-link px-1 py-0")
162       .addClass(function () {
163         return $(this).hasClass("active") ? "text-secondary-emphasis" : "text-secondary";
164       });
165     $item.addClass("nav-item").insertBefore("#compact-secondary-nav");
166     toggleCompactSecondaryNav();
167   }
168
169   function collapseSecondaryMenuItem($item) {
170     $item.children("a")
171       .addClass("dropdown-item")
172       .removeClass("nav-link px-1 py-0 text-secondary text-secondary-emphasis");
173     $item.removeClass("nav-item").appendTo($collapsedSecondaryMenu);
174     toggleCompactSecondaryNav();
175   }
176
177   function toggleCompactSecondaryNav() {
178     $("#compact-secondary-nav").toggle(
179       $collapsedSecondaryMenu.find("li").length > 0
180     );
181   }
182
183   /*
184    * Chrome 60 and later seem to fire the "ready" callback
185    * before the DOM is fully ready causing us to measure the
186    * wrong sizes for the header elements - use a 0ms timeout
187    * to defer the measurement slightly as a workaround.
188    */
189   setTimeout(function () {
190     updateHeader();
191
192     $(window).resize(updateHeader);
193     $(document).on("turbo:render", updateHeader);
194   }, 0);
195
196   $("#menu-icon").on("click", function (e) {
197     e.preventDefault();
198     $("header").toggleClass("closed");
199   });
200
201   $("nav.primary li a").on("click", function () {
202     $("header").toggleClass("closed");
203   });
204
205   $("#edit_tab")
206     .attr("title", OSM.i18n.t("javascripts.site.edit_disabled_tooltip"));
207
208   document.addEventListener("turbo:frame-load", function (event) {
209     if (event.target.id === "select_language_list") {
210       const $search = $("#language_search");
211       if ($search.length) {
212         $search.off("input");
213         $search.on("input", function () {
214           const query = $(this).val().toLowerCase();
215           $(".language-item").each(function () {
216             const text = $(this).text().toLowerCase();
217             $(this).toggle(text.indexOf(query) > -1);
218           });
219         });
220       }
221       $search
222         .val("")
223         .trigger("input")
224         .trigger("focus");
225     }
226   });
227
228   $("#select_language_dialog").on("shown.bs.modal", function () {
229     $("#language_search")
230       .val("")
231       .trigger("input")
232       .trigger("focus");
233     const $frame = $("#select_language_list");
234     const originalSrc = new URL($frame.attr("src"), window.location.origin);
235
236     // Set `source` query param to current page path + query string
237     originalSrc.searchParams.set("source", window.location.pathname + window.location.search);
238
239     if ($frame.attr("src") !== originalSrc.toString()) {
240       $frame.attr("src", originalSrc.toString());
241     }
242   });
243 });