]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index_modules/element.js
Remove history submodules from OSM scope
[rails.git] / app / assets / javascripts / index_modules / element.js
1 let abortController = null;
2 const languagesToRequest = [...new Set(OSM.preferred_languages.map(l => l.toLowerCase()))];
3 const wikisToRequest = [...new Set([...OSM.preferred_languages, "en"].map(l => l.split("-")[0] + "wiki"))];
4 const isOfExpectedLanguage = ({ language }) => languagesToRequest[0].startsWith(language) || language === "mul";
5
6 export function element(type) {
7   return function () {
8     const page = {};
9
10     page.pushstate = page.popstate = function (path, id, version) {
11       OSM.loadSidebarContent(path, function () {
12         page._addObject(type, id, version);
13         $(".numbered_pagination").trigger("numbered_pagination:enable");
14         abortController = new AbortController();
15       });
16     };
17
18     page.load = function (path, id, version) {
19       page._addObject(type, id, version, true);
20       $(".numbered_pagination").trigger("numbered_pagination:enable");
21       abortController = new AbortController();
22     };
23
24     page.unload = function () {
25       page._removeObject();
26       $(".numbered_pagination").trigger("numbered_pagination:disable");
27       abortController?.abort();
28     };
29
30     page._addObject = function () {};
31     page._removeObject = function () {};
32
33     return page;
34   };
35 };
36
37 export function mappedElement(type) {
38   return function (map) {
39     const page = element(type)(map);
40
41     page._addObject = function (type, id, version, center) {
42       const hashParams = OSM.parseHash();
43       map.addObject({ type: type, id: parseInt(id, 10), version: version && parseInt(version, 10) }, function (bounds) {
44         if (!hashParams.center && bounds.isValid() &&
45             (center || !map.getBounds().contains(bounds))) {
46           OSM.router.withoutMoveListener(function () {
47             map.fitBounds(bounds);
48           });
49         }
50       });
51     };
52
53     page._removeObject = function () {
54       map.removeObject();
55     };
56
57     return page;
58   };
59 };
60
61 {
62   $(document).on("click", "button.wdt-preview", e => previewWikidataValue($(e.currentTarget)));
63
64   function previewWikidataValue($btn) {
65     if (!OSM.WIKIDATA_API_URL) return;
66     const items = $btn.data("qids");
67     if (!items?.length) return;
68     $btn.prop("disabled", true);
69     fetch(OSM.WIKIDATA_API_URL + "?" + new URLSearchParams({
70       action: "wbgetentities",
71       format: "json",
72       origin: "*",
73       ids: items.join("|"),
74       props: "labels|sitelinks/urls|claims|descriptions",
75       languages: languagesToRequest.join("|"),
76       languagefallback: 1,
77       sitefilter: wikisToRequest.join("|")
78     }), {
79       headers: { "Api-User-Agent": "OSM-TagPreview (https://github.com/openstreetmap/openstreetmap-website)" },
80       signal: abortController?.signal
81     })
82       .then(response => response.ok ? response.json() : Promise.reject(response))
83       .then(({ entities }) => {
84         if (!entities) return Promise.reject(entities);
85         $btn
86           .closest("tr")
87           .after(
88             items
89               .filter(qid => entities[qid])
90               .map(qid => getLocalizedResponse(entities[qid]))
91               .filter(data => data.label || data.icon || data.description || data.article)
92               .map(data => renderWikidataResponse(data, $btn.siblings(`a[href*="wikidata.org/entity/${data.qid}"]`)))
93           );
94       })
95       .catch(() => $btn.prop("disabled", false));
96   }
97
98   function getLocalizedResponse(entity) {
99     const siteScheme = OSM.isDark("bs") ? "Q6545942" : "Q101608434";
100     const scheme = ({ qualifiers }) => qualifiers?.P8798?.some(q => q?.datavalue?.value?.id === siteScheme) ?? 0;
101     const rank = ({ rank }) => ({ preferred: 2, normal: 0, deprecated: -2 })[rank] ?? 0;
102     const toBestClaim = (out, claim) => (rank(claim) + scheme(claim) > rank(out) + scheme(out)) ? claim : out;
103     const toFirstOf = (property) => (out, localization) => out ?? property[localization];
104     const data = {
105       qid: entity.id,
106       label: languagesToRequest.reduce(toFirstOf(entity.labels), null),
107       icon: [
108         "P8972", // small logo or icon
109         "P154", // logo image
110         "P14" // traffic sign
111       ].reduce((out, prop) => out ?? entity.claims[prop]?.reduce(toBestClaim)?.mainsnak?.datavalue?.value, null),
112       description: languagesToRequest.reduce(toFirstOf(entity.descriptions), null),
113       article: wikisToRequest.reduce(toFirstOf(entity.sitelinks), null)
114     };
115     if (data.article) data.article.language = data.article.site.replace("wiki", "");
116     return data;
117   }
118
119   function renderWikidataResponse({ icon, label, article, description }, $link) {
120     const localeName = new Intl.DisplayNames(OSM.preferred_languages, { type: "language" });
121     const cell = $("<td>")
122       .attr("colspan", 2)
123       .addClass("bg-body-tertiary");
124
125     if (icon && OSM.WIKIMEDIA_COMMONS_URL) {
126       let src = OSM.WIKIMEDIA_COMMONS_URL + "Special:Redirect/file/" + encodeURIComponent(icon) + "?mobileaction=toggle_view_desktop";
127       if (!icon.endsWith(".svg")) src += "&width=128";
128       $("<a>")
129         .attr("href", OSM.WIKIMEDIA_COMMONS_URL + "File:" + encodeURIComponent(icon) + `?uselang=${OSM.i18n.locale}`)
130         .append($("<img>").attr({ src, height: "32" }))
131         .addClass("float-end mb-1 ms-2")
132         .appendTo(cell);
133     }
134     if (label) {
135       const link = $link.clone()
136         .text(label.value)
137         .attr("dir", "auto")
138         .appendTo(cell);
139       if (!isOfExpectedLanguage(label)) {
140         link.attr("lang", label.language);
141         link.after($("<sup>").text(" " + localeName.of(label.language)));
142       }
143     }
144     if (article) {
145       const link = $("<a>")
146         .attr("href", article.url + `?uselang=${OSM.i18n.locale}`)
147         .text(label ? OSM.i18n.t("javascripts.element.wikipedia") : article.title)
148         .attr("dir", "auto")
149         .appendTo(cell);
150       if (label) {
151         link.before(" (");
152         link.after(")");
153       }
154       if (!isOfExpectedLanguage(article)) {
155         link.attr("lang", article.language);
156         link.after($("<sup>").text(" " + localeName.of(article.language)));
157       }
158     }
159     if (description) {
160       const text = $("<div>")
161         .text(description.value)
162         .addClass("small")
163         .attr("dir", "auto")
164         .appendTo(cell);
165       if (!isOfExpectedLanguage(description)) {
166         text.attr("lang", description.language);
167       }
168     }
169     return $("<tr>").append(cell);
170   }
171 }