]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/application.js
Move hash and title sync logic from iframe to parent
[rails.git] / app / assets / javascripts / application.js
1 //= require jquery3
2 //= require jquery_ujs
3 //= require js-cookie/dist/js.cookie
4 //= require popper
5 //= require bootstrap-sprockets
6 //= require osm
7 //= require leaflet/dist/leaflet-src
8 //= require leaflet.osm
9 //= require maplibre-gl/dist/maplibre-gl
10 //= require leaflet.maplibre
11 //= require leaflet.shortbread
12 //= require leaflet.thunderforest
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 px-1 py-0")
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 px-1 py-0 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   const menuIcon = $("#menu-icon");
196   const header = $("header");
197   menuIcon.on("click", function (e) {
198     e.preventDefault();
199     header.toggleClass("closed");
200     menuIcon.prop("ariaExpanded", !header.hasClass("closed"));
201   });
202
203   $("nav.primary li a").on("click", function () {
204     $("header").toggleClass("closed");
205   });
206
207   $("#edit_tab")
208     .attr("title", OSM.i18n.t("javascripts.site.edit_disabled_tooltip"));
209
210   document.addEventListener("turbo:frame-load", function (event) {
211     if (event.target.id === "select_language_list") {
212       const $search = $("#language_search");
213       if ($search.length) {
214         $search.off("input");
215         $search.on("input", function () {
216           const query = $(this).val().toLowerCase();
217           $(".language-item").each(function () {
218             const text = $(this).text().toLowerCase();
219             // Get languageCode from link_to data attribute
220             const code = $(this).find("a").data("languageCode").toLowerCase();
221             // Show the item if the query matches either the language name or code
222             const matches = text.indexOf(query) > -1 || code.indexOf(query) > -1;
223             $(this).toggle(matches);
224           });
225         });
226       }
227       $search
228         .val("")
229         .trigger("input")
230         .trigger("focus");
231     }
232   });
233
234   $("#select_language_dialog").on("shown.bs.modal", function () {
235     $("#language_search")
236       .val("")
237       .trigger("input")
238       .trigger("focus");
239     const $frame = $("#select_language_list");
240     const originalSrc = new URL($frame.attr("src"), window.location.origin);
241
242     // Set `source` query param to current page path + query string
243     originalSrc.searchParams.set("source", window.location.pathname + window.location.search);
244
245     if ($frame.attr("src") !== originalSrc.toString()) {
246       $frame.attr("src", originalSrc.toString());
247     }
248   });
249 });