]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/search.js
Move controller invoking event handlers outside said controllers
[rails.git] / app / assets / javascripts / index / search.js
1 OSM.initializations.push(function (map) {
2   $(".search_form a.btn.switch_link").on("click", function (e) {
3     e.preventDefault();
4     const query = $(this).closest("form").find("input[name=query]").val();
5     let search = "";
6     if (query) search = "?" + new URLSearchParams({ to: query });
7     OSM.router.route("/directions" + search + OSM.formatHash(map));
8   });
9
10   $(".search_form").on("submit", function (e) {
11     e.preventDefault();
12     $("header").addClass("closed");
13     const params = new URLSearchParams({
14       query: this.elements.query.value,
15       zoom: map.getZoom(),
16       minlon: map.getBounds().getWest(),
17       minlat: map.getBounds().getSouth(),
18       maxlon: map.getBounds().getEast(),
19       maxlat: map.getBounds().getNorth()
20     });
21     const search = params.get("query") ? `/search?${params}` : "/";
22     OSM.router.route(search + OSM.formatHash(map));
23   });
24
25   $(".describe_location").on("click", function (e) {
26     e.preventDefault();
27     $("header").addClass("closed");
28     const zoom = map.getZoom();
29     const [lat, lon] = OSM.cropLocation(map.getCenter(), zoom);
30
31     OSM.router.route("/search?" + new URLSearchParams({ lat, lon, zoom }));
32   });
33 });
34 OSM.Search = function (map) {
35   $("#sidebar_content")
36     .on("click", ".search_more a", clickSearchMore)
37     .on("click", ".search_results_entry a.set_position", clickSearchResult);
38
39   const markers = L.layerGroup().addTo(map);
40   let processedResults = 0;
41
42   function clickSearchMore(e) {
43     e.preventDefault();
44     e.stopPropagation();
45
46     const div = $(this).parents(".search_more");
47
48     $(this).hide();
49     div.find(".loader").prop("hidden", false);
50
51     fetchReplace(this, div);
52   }
53
54   function fetchReplace({ href }, $target) {
55     return fetch(href, {
56       method: "POST",
57       body: new URLSearchParams(OSM.csrf)
58     })
59       .then(response => response.text())
60       .then(html => {
61         const result = $(html);
62         $target.replaceWith(result);
63         result.filter("ul").children().each(showSearchResult);
64       });
65   }
66
67   function showSearchResult() {
68     const index = processedResults++;
69     const listItem = $(this);
70     const inverseGoldenAngle = (Math.sqrt(5) - 1) * 180;
71     const color = `hwb(${(index * inverseGoldenAngle) % 360}deg 5% 5%)`;
72     listItem.css("--marker-color", color);
73     const data = listItem.find("a.set_position").data();
74     const marker = L.marker([data.lat, data.lon], { icon: OSM.getMarker({ color, className: "activatable" }) });
75     marker.on("mouseover", () => listItem.addClass("bg-body-secondary"));
76     marker.on("mouseout", () => listItem.removeClass("bg-body-secondary"));
77     marker.on("click", function (e) {
78       OSM.router.click(e.originalEvent, listItem.find("a.set_position").attr("href"));
79     });
80     markers.addLayer(marker);
81     listItem.on("mouseover", () => $(marker.getElement()).addClass("active"));
82     listItem.on("mouseout", () => $(marker.getElement()).removeClass("active"));
83   }
84
85   function panToSearchResult(data) {
86     if (data.minLon && data.minLat && data.maxLon && data.maxLat) {
87       map.fitBounds([[data.minLat, data.minLon], [data.maxLat, data.maxLon]]);
88     } else {
89       map.setView([data.lat, data.lon], data.zoom);
90     }
91   }
92
93   function clickSearchResult(e) {
94     const data = $(this).data();
95
96     panToSearchResult(data);
97
98     // Let clicks to object browser links propagate.
99     if (data.type && data.id) return;
100
101     e.preventDefault();
102     e.stopPropagation();
103   }
104
105   const page = {};
106
107   page.pushstate = page.popstate = function (path) {
108     const params = new URLSearchParams(path.substring(path.indexOf("?")));
109     if (params.has("query")) {
110       $(".search_form input[name=query]").val(params.get("query"));
111     } else if (params.has("lat") && params.has("lon")) {
112       $(".search_form input[name=query]").val(params.get("lat") + ", " + params.get("lon"));
113     }
114     OSM.loadSidebarContent(path, page.load);
115   };
116
117   page.load = function () {
118     $(".search_results_entry[data-href]").each(function (index) {
119       const entry = $(this);
120       fetchReplace(this.dataset, entry.children().first())
121         .then(() => {
122           // go to first result of first geocoder
123           if (index === 0) {
124             const firstResult = entry.find("*[data-lat][data-lon]:first").first();
125             if (firstResult.length) {
126               panToSearchResult(firstResult.data());
127             }
128           }
129         });
130     });
131
132     return map.getState();
133   };
134
135   page.unload = function () {
136     markers.clearLayers();
137     processedResults = 0;
138   };
139
140   return page;
141 };