Decrese dependency on jquery

This commit is contained in:
pietervdvn 2021-07-03 22:24:12 +02:00
parent e3f2c56d3e
commit d0997480c0
8 changed files with 43 additions and 60 deletions

View file

@ -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))
}
}

View file

@ -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<LicenseInfo>(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";

View file

@ -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();

View file

@ -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);
}
}

View file

@ -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();

View file

@ -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 {

View file

@ -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(":");

View file

@ -9,12 +9,10 @@ export class Utils {
*/
public static runningFromConsole = false;
public static readonly assets_path = "./assets/svg/";
public static externalDownloadFunction: (url: string) => Promise<any>;
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<T>(count : number, f: ((i: number) => T)): T[] {
let res : T[] = [];
public static TimesT<T>(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<any>;
public static downloadJson(url: string): Promise<any>{
if(this.externalDownloadFunction !== undefined){
public static downloadJson(url: string): Promise<any> {
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)
}
}
)
}
/**