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