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