]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/element.js
Fix next page boundary condition for user notes
[rails.git] / app / assets / javascripts / index / element.js
1 (function () {
2   let abortController = null;
3   const languagesToRequest = [...new Set(OSM.preferred_languages.map(l => l.toLowerCase()))];
4   const wikisToRequest = [...new Set([...OSM.preferred_languages, "en"].map(l => l.split("-")[0] + "wiki"))];
5   const isOfExpectedLanguage = ({ language }) => languagesToRequest[0].startsWith(language) || language === "mul";
6
7   $(document).on("click", "a[href='#versions-navigation-active-page-item']", function (e) {
8     scrollToActiveVersion();
9     $("#versions-navigation-active-page-item a.page-link").trigger("focus");
10     e.preventDefault();
11   });
12
13   $(document).on("click", "button.wdt-preview", e => previewWikidataValue($(e.currentTarget)));
14
15   OSM.Element = type => function () {
16     const page = {};
17     let scrollStartObserver, scrollEndObserver;
18
19     page.pushstate = page.popstate = function (path, id, version) {
20       OSM.loadSidebarContent(path, function () {
21         initVersionsNavigation();
22         page._addObject(type, id, version);
23         abortController = new AbortController();
24       });
25     };
26
27     page.load = function (path, id, version) {
28       initVersionsNavigation();
29       page._addObject(type, id, version, true);
30       abortController = new AbortController();
31     };
32
33     page.unload = function () {
34       page._removeObject();
35       scrollStartObserver?.disconnect();
36       scrollStartObserver = null;
37       scrollEndObserver?.disconnect();
38       scrollEndObserver = null;
39       abortController?.abort();
40     };
41
42     page._addObject = function () {};
43     page._removeObject = function () {};
44
45     function initVersionsNavigation() {
46       scrollToActiveVersion();
47
48       const $scrollableList = $("#versions-navigation-list-middle");
49       const [scrollableFirstItem] = $scrollableList.children().first();
50       const [scrollableLastItem] = $scrollableList.children().last();
51
52       if (scrollableFirstItem) {
53         scrollStartObserver = createScrollObserver("#versions-navigation-list-start", "2px 0px");
54         scrollStartObserver.observe(scrollableFirstItem);
55       }
56
57       if (scrollableLastItem) {
58         scrollEndObserver = createScrollObserver("#versions-navigation-list-end", "-2px 0px");
59         scrollEndObserver.observe(scrollableLastItem);
60       }
61     }
62
63     function createScrollObserver(shadowTarget, shadowOffset) {
64       const threshold = 0.95;
65       return new IntersectionObserver(([entry]) => {
66         const floating = entry.intersectionRatio < threshold;
67         $(shadowTarget)
68           .css("box-shadow", floating ? `rgba(0, 0, 0, 0.075) ${shadowOffset} 2px` : "")
69           .css("z-index", floating ? "5" : ""); // floating z-index should be larger than z-index of Bootstrap's .page-link:focus, which is 3
70       }, { threshold });
71     }
72
73     return page;
74   };
75
76   OSM.MappedElement = type => function (map) {
77     const page = OSM.Element(type)(map);
78
79     page._addObject = function (type, id, version, center) {
80       const hashParams = OSM.parseHash();
81       map.addObject({ type: type, id: parseInt(id, 10), version: version && parseInt(version, 10) }, function (bounds) {
82         if (!hashParams.center && bounds.isValid() &&
83             (center || !map.getBounds().contains(bounds))) {
84           OSM.router.withoutMoveListener(function () {
85             map.fitBounds(bounds);
86           });
87         }
88       });
89     };
90
91     page._removeObject = function () {
92       map.removeObject();
93     };
94
95     return page;
96   };
97
98   function scrollToActiveVersion() {
99     const [scrollableList] = $("#versions-navigation-list-middle");
100
101     if (!scrollableList) return;
102
103     const [activeStartItem] = $("#versions-navigation-list-start #versions-navigation-active-page-item");
104     const [activeScrollableItem] = $("#versions-navigation-list-middle #versions-navigation-active-page-item");
105
106     if (activeStartItem) {
107       scrollableList.scrollLeft = 0;
108     } else if (activeScrollableItem) {
109       scrollableList.scrollLeft = Math.round(activeScrollableItem.offsetLeft - (scrollableList.offsetWidth / 2) + (activeScrollableItem.offsetWidth / 2));
110     } else {
111       scrollableList.scrollLeft = scrollableList.scrollWidth - scrollableList.offsetWidth;
112     }
113   }
114
115   function previewWikidataValue($btn) {
116     if (!OSM.WIKIDATA_API_URL) return;
117     const items = $btn.data("qids");
118     if (!items?.length) return;
119     $btn.prop("disabled", true);
120     fetch(OSM.WIKIDATA_API_URL + "?" + new URLSearchParams({
121       action: "wbgetentities",
122       format: "json",
123       origin: "*",
124       ids: items.join("|"),
125       props: "labels|sitelinks/urls|claims|descriptions",
126       languages: languagesToRequest.join("|"),
127       languagefallback: 1,
128       sitefilter: wikisToRequest.join("|")
129     }), {
130       headers: { "Api-User-Agent": "OSM-TagPreview (https://github.com/openstreetmap/openstreetmap-website)" },
131       signal: abortController?.signal
132     })
133       .then(response => response.ok ? response.json() : Promise.reject(response))
134       .then(({ entities }) => {
135         if (!entities) return Promise.reject(entities);
136         $btn
137           .closest("tr")
138           .after(
139             items
140               .filter(qid => entities[qid])
141               .map(qid => getLocalizedResponse(entities[qid]))
142               .filter(data => data.label || data.icon || data.description || data.article)
143               .map(data => renderWikidataResponse(data, $btn.siblings(`a[href*="wikidata.org/entity/${data.qid}"]`)))
144           );
145       })
146       .catch(() => $btn.prop("disabled", false));
147   }
148
149   function getLocalizedResponse(entity) {
150     const rank = ({ rank }) => ({ preferred: 1, normal: 0, deprecated: -1 })[rank] ?? 0;
151     const toBestClaim = (out, claim) => (rank(claim) > rank(out)) ? claim : out;
152     const toFirstOf = (property) => (out, localization) => out ?? property[localization];
153     const data = {
154       qid: entity.id,
155       label: languagesToRequest.reduce(toFirstOf(entity.labels), null),
156       icon: [
157         "P8972", // small logo or icon
158         "P154", // logo image
159         "P14" // traffic sign
160       ].reduce((out, prop) => out ?? entity.claims[prop]?.reduce(toBestClaim)?.mainsnak?.datavalue?.value, null),
161       description: languagesToRequest.reduce(toFirstOf(entity.descriptions), null),
162       article: wikisToRequest.reduce(toFirstOf(entity.sitelinks), null)
163     };
164     if (data.article) data.article.language = data.article.site.replace("wiki", "");
165     return data;
166   }
167
168   function renderWikidataResponse({ icon, label, article, description }, $link) {
169     const localeName = new Intl.DisplayNames(OSM.preferred_languages, { type: "language" });
170     const cell = $("<td>")
171       .attr("colspan", 2)
172       .addClass("bg-body-tertiary");
173
174     if (icon && OSM.WIKIMEDIA_COMMONS_URL) {
175       let src = OSM.WIKIMEDIA_COMMONS_URL + "Special:Redirect/file/" + encodeURIComponent(icon) + "?mobileaction=toggle_view_desktop";
176       if (!icon.endsWith(".svg")) src += "&width=128";
177       $("<a>")
178         .attr("href", OSM.WIKIMEDIA_COMMONS_URL + "File:" + encodeURIComponent(icon) + `?uselang=${OSM.i18n.locale}`)
179         .append($("<img>").attr({ src, height: "32" }))
180         .addClass("float-end mb-1 ms-2")
181         .appendTo(cell);
182     }
183     if (label) {
184       const link = $link.clone()
185         .text(label.value)
186         .attr("dir", "auto")
187         .appendTo(cell);
188       if (!isOfExpectedLanguage(label)) {
189         link.attr("lang", label.language);
190         link.after($("<sup>").text(" " + localeName.of(label.language)));
191       }
192     }
193     if (article) {
194       const link = $("<a>")
195         .attr("href", article.url + `?uselang=${OSM.i18n.locale}`)
196         .text(label ? OSM.i18n.t("javascripts.element.wikipedia") : article.title)
197         .attr("dir", "auto")
198         .appendTo(cell);
199       if (label) {
200         link.before(" (");
201         link.after(")");
202       }
203       if (!isOfExpectedLanguage(article)) {
204         link.attr("lang", article.language);
205         link.after($("<sup>").text(" " + localeName.of(article.language)));
206       }
207     }
208     if (description) {
209       const text = $("<div>")
210         .text(description.value)
211         .addClass("small")
212         .attr("dir", "auto")
213         .appendTo(cell);
214       if (!isOfExpectedLanguage(description)) {
215         text.attr("lang", description.language);
216       }
217     }
218     return $("<tr>").append(cell);
219   }
220 }());