From d0997480c0e0edffdf8dc4087442b14948dcde72 Mon Sep 17 00:00:00 2001 From: pietervdvn Date: Sat, 3 Jul 2021 22:24:12 +0200 Subject: [PATCH] Decrese dependency on jquery --- Logic/FeatureSource/GeoJsonSource.ts | 11 +++----- Logic/ImageProviders/Mapillary.ts | 3 ++- Logic/ImageProviders/Wikimedia.ts | 5 ++-- Logic/Osm/Geocoding.ts | 20 ++++++--------- Logic/Osm/OsmObject.ts | 5 ++-- Logic/Osm/Overpass.ts | 15 +++-------- Logic/Web/LiveQueryHandler.ts | 6 ++--- Utils.ts | 38 ++++++++++++++-------------- 8 files changed, 43 insertions(+), 60 deletions(-) diff --git a/Logic/FeatureSource/GeoJsonSource.ts b/Logic/FeatureSource/GeoJsonSource.ts index 58bc6292a..b462c87da 100644 --- a/Logic/FeatureSource/GeoJsonSource.ts +++ b/Logic/FeatureSource/GeoJsonSource.ts @@ -1,6 +1,5 @@ import FeatureSource from "./FeatureSource"; import {UIEventSource} from "../UIEventSource"; -import * as $ from "jquery"; import Loc from "../../Models/Loc"; import State from "../../State"; import {Utils} from "../../Utils"; @@ -152,12 +151,8 @@ export default class GeoJsonSource implements FeatureSource { private LoadJSONFrom(url: string) { const eventSource = this.features; const self = this; - $.getJSON(url, function (json, status) { - if (status !== "success") { - self.onFail(status, url); - return; - } - + Utils.downloadJson(url) + .then(json => { if (json.elements === [] && json.remarks.indexOf("runtime error") > 0) { self.onFail("Runtime error (timeout)", url) return; @@ -193,7 +188,7 @@ export default class GeoJsonSource implements FeatureSource { eventSource.setData(eventSource.data.concat(newFeatures)) - }).fail(msg => self.onFail(msg, url)) + }).catch(msg => self.onFail(msg, url)) } } diff --git a/Logic/ImageProviders/Mapillary.ts b/Logic/ImageProviders/Mapillary.ts index cad71f93b..ebb27fcb0 100644 --- a/Logic/ImageProviders/Mapillary.ts +++ b/Logic/ImageProviders/Mapillary.ts @@ -4,6 +4,7 @@ import ImageAttributionSource from "./ImageAttributionSource"; import BaseUIElement from "../../UI/BaseUIElement"; import {UIEventSource} from "../UIEventSource"; import Svg from "../../Svg"; +import {Utils} from "../../Utils"; export class Mapillary extends ImageAttributionSource { @@ -43,7 +44,7 @@ export class Mapillary extends ImageAttributionSource { const key = Mapillary.ExtractKeyFromURL(url) const metadataURL = `https://a.mapillary.com/v3/images/${key}?client_id=TXhLaWthQ1d4RUg0czVxaTVoRjFJZzowNDczNjUzNmIyNTQyYzI2` const source = new UIEventSource(undefined) - $.getJSON(metadataURL, function (data) { + Utils.downloadJson(metadataURL).then(data => { const license = new LicenseInfo(); license.artist = data.properties?.username; license.licenseShortName = "CC BY-SA 4.0"; diff --git a/Logic/ImageProviders/Wikimedia.ts b/Logic/ImageProviders/Wikimedia.ts index 9d74b7769..2899e5bb8 100644 --- a/Logic/ImageProviders/Wikimedia.ts +++ b/Logic/ImageProviders/Wikimedia.ts @@ -1,4 +1,3 @@ -import * as $ from "jquery" import ImageAttributionSource from "./ImageAttributionSource"; import BaseUIElement from "../../UI/BaseUIElement"; import Svg from "../../Svg"; @@ -43,7 +42,7 @@ export class Wikimedia extends ImageAttributionSource { } const self = this; console.log("Loading a wikimedia category: ", url) - $.getJSON(url, (response) => { + Utils.downloadJson(url).then((response) => { let imageOverview = new ImagesInCategory(); let members = response.query?.categorymembers; if (members === undefined) { @@ -78,7 +77,7 @@ export class Wikimedia extends ImageAttributionSource { static GetWikiData(id: number, handleWikidata: ((Wikidata) => void)) { const url = "https://www.wikidata.org/wiki/Special:EntityData/Q" + id + ".json"; - $.getJSON(url, (response) => { + Utils.downloadJson(url).then (response => { const entity = response.entities["Q" + id]; const commons = entity.sitelinks.commonswiki; const wd = new Wikidata(); diff --git a/Logic/Osm/Geocoding.ts b/Logic/Osm/Geocoding.ts index f2ee260f2..259f688dc 100644 --- a/Logic/Osm/Geocoding.ts +++ b/Logic/Osm/Geocoding.ts @@ -1,5 +1,6 @@ -import $ from "jquery" import State from "../../State"; +import {Utils} from "../../Utils"; + export class Geocoding { private static readonly host = "https://nominatim.openstreetmap.org/search?"; @@ -9,17 +10,12 @@ export class Geocoding { osm_type: string, osm_id: string}[]) => void), onFail: (() => void)) { const b = State.state.leafletMap.data.getBounds(); - console.log(b); - $.getJSON( - Geocoding.host + "format=json&limit=1&viewbox=" + + const url = Geocoding.host + "format=json&limit=1&viewbox=" + `${b.getEast()},${b.getNorth()},${b.getWest()},${b.getSouth()}`+ - "&accept-language=nl&q=" + query, - function (data) { - handleResult(data); - }).fail(() => { - onFail(); - }); + "&accept-language=nl&q=" + query; + Utils.downloadJson( + url) + .then(handleResult) + .catch(onFail); } - - } diff --git a/Logic/Osm/OsmObject.ts b/Logic/Osm/OsmObject.ts index b9d1b9076..6f9ec95b3 100644 --- a/Logic/Osm/OsmObject.ts +++ b/Logic/Osm/OsmObject.ts @@ -1,4 +1,3 @@ -import * as $ from "jquery" import {Utils} from "../../Utils"; import * as polygon_features from "../../assets/polygon-features.json"; import {UIEventSource} from "../UIEventSource"; @@ -151,7 +150,7 @@ export abstract class OsmObject { const minlat = bounds[1][0] const maxlat = bounds[0][0]; const url = `${OsmObject.backendURL}api/0.6/map.json?bbox=${minlon},${minlat},${maxlon},${maxlat}` - $.getJSON(url, data => { + Utils.downloadJson(url).then( data => { const elements: any[] = data.elements; const objects = OsmObject.ParseObjects(elements) callback(objects); @@ -274,7 +273,7 @@ export abstract class OsmObject { const self = this; const full = this.type !== "way" ? "" : "/full"; const url = `${OsmObject.backendURL}api/0.6/${this.type}/${this.id}${full}`; - $.getJSON(url, function (data) { + Utils.downloadJson(url).then(data => { const element = data.elements.pop(); diff --git a/Logic/Osm/Overpass.ts b/Logic/Osm/Overpass.ts index 7a4cbfb79..59a4869f4 100644 --- a/Logic/Osm/Overpass.ts +++ b/Logic/Osm/Overpass.ts @@ -1,8 +1,8 @@ -import * as $ from "jquery" import * as OsmToGeoJson from "osmtogeojson"; import Bounds from "../../Models/Bounds"; import {TagsFilter} from "../Tags/TagsFilter"; import ExtractRelations from "./ExtractRelations"; +import {Utils} from "../../Utils"; /** * Interfaces overpass to get all the latest data @@ -27,14 +27,8 @@ export class Overpass { console.log("Using testing URL") query = Overpass.testUrl; } - $.getJSON(query, - function (json, status) { - if (status !== "success") { - console.log("Query failed") - onFail(status); - return; - } - + Utils.downloadJson(query) + .then(json => { if (json.elements === [] && json.remarks.indexOf("runtime error") > 0) { console.log("Timeout or other runtime error"); onFail("Runtime error (timeout)") @@ -47,8 +41,7 @@ export class Overpass { const osmTime = new Date(json.osm3s.timestamp_osm_base); continuation(geojson, osmTime); - - }).fail(onFail) + }).catch(onFail) } buildQuery(bbox: string): string { diff --git a/Logic/Web/LiveQueryHandler.ts b/Logic/Web/LiveQueryHandler.ts index 9b8fc77c5..b7da5df3b 100644 --- a/Logic/Web/LiveQueryHandler.ts +++ b/Logic/Web/LiveQueryHandler.ts @@ -1,6 +1,6 @@ - import {UIEventSource} from "../UIEventSource"; -import * as $ from "jquery" +import {Utils} from "../../Utils"; + /** * Fetches data from random data sources, used in the metatagging */ @@ -25,7 +25,7 @@ export default class LiveQueryHandler { LiveQueryHandler[url] = source; console.log("Fetching live data from a third-party (unknown) API:",url) - $.getJSON(url, function (data) { + Utils.downloadJson(url).then(data => { for (const shorthandDescription of shorthandsSet) { const descr = shorthandDescription.trim().split(":"); diff --git a/Utils.ts b/Utils.ts index 81576df9f..05ebcbaab 100644 --- a/Utils.ts +++ b/Utils.ts @@ -9,12 +9,10 @@ export class Utils { */ public static runningFromConsole = false; public static readonly assets_path = "./assets/svg/"; - - + public static externalDownloadFunction: (url: string) => Promise; private static knownKeys = ["addExtraTags", "and", "calculatedTags", "changesetmessage", "clustering", "color", "condition", "customCss", "dashArray", "defaultBackgroundId", "description", "descriptionTail", "doNotDownload", "enableAddNewPoints", "enableBackgroundLayerSelection", "enableGeolocation", "enableLayers", "enableMoreQuests", "enableSearch", "enableShareScreen", "enableUserBadge", "freeform", "hideFromOverview", "hideInAnswer", "icon", "iconOverlays", "iconSize", "id", "if", "ifnot", "isShown", "key", "language", "layers", "lockLocation", "maintainer", "mappings", "maxzoom", "maxZoom", "minNeededElements", "minzoom", "multiAnswer", "name", "or", "osmTags", "passAllFeatures", "presets", "question", "render", "roaming", "roamingRenderings", "rotation", "shortDescription", "socialImage", "source", "startLat", "startLon", "startZoom", "tagRenderings", "tags", "then", "title", "titleIcons", "type", "version", "wayHandling", "widenFactor", "width"] private static extraKeys = ["nl", "en", "fr", "de", "pt", "es", "name", "phone", "email", "amenity", "leisure", "highway", "building", "yes", "no", "true", "false"] - static EncodeXmlValue(str) { if (typeof str !== "string") { str = "" + str @@ -72,10 +70,10 @@ export class Utils { return res; } - public static TimesT(count : number, f: ((i: number) => T)): T[] { - let res : T[] = []; + public static TimesT(count: number, f: ((i: number) => T)): T[] { + let res: T[] = []; for (let i = 0; i < count; i++) { - res .push(f(i)); + res.push(f(i)); } return res; } @@ -158,7 +156,7 @@ export class Utils { public static SubstituteKeys(txt: string, tags: any) { for (const key in tags) { - if(!tags.hasOwnProperty(key)) { + if (!tags.hasOwnProperty(key)) { continue } txt = txt.replace(new RegExp("{" + key + "}", "g"), tags[key]) @@ -292,10 +290,10 @@ export class Utils { public static UnMinify(minified: string): string { - if(minified === undefined || minified === null){ + if (minified === undefined || minified === null) { return undefined; } - + const parts = minified.split("|"); let result = parts.shift(); const keys = Utils.knownKeys.concat(Utils.extraKeys); @@ -323,34 +321,36 @@ export class Utils { } return result; } - - public static externalDownloadFunction: (url: string) => Promise; - - public static downloadJson(url: string): Promise{ - if(this.externalDownloadFunction !== undefined){ + + public static downloadJson(url: string): Promise { + if (this.externalDownloadFunction !== undefined) { return this.externalDownloadFunction(url) } return new Promise( (resolve, reject) => { - try{ + try { const xhr = new XMLHttpRequest(); xhr.onload = () => { if (xhr.status == 200) { - resolve(JSON.parse(xhr.response)) + try { + resolve(JSON.parse(xhr.response)) + } catch (e) { + reject("Not a valid json: " + xhr.response) + } } else { reject(xhr.statusText) } }; xhr.open('GET', url); - xhr.setRequestHeader("accept","application/json") + xhr.setRequestHeader("accept", "application/json") xhr.send(); - }catch(e){ + } catch (e) { reject(e) } } ) - + } /**