Add Wikipedia page box

This commit is contained in:
Pieter Vander Vennet 2021-10-02 17:57:54 +02:00
parent df34239256
commit 9df263c362
12 changed files with 3605 additions and 3457 deletions

View file

@ -61,10 +61,30 @@ export class UIEventSource<T> {
run();
return source;
}
/**
* Converts a promise into a UIVentsource, sets the UIEVentSource when the result is calculated.
* If the promise fails, the value will stay undefined
* @param promise
* @constructor
*/
public static FromPromise<T>(promise : Promise<T>): UIEventSource<T>{
const src = new UIEventSource<T>(undefined)
promise?.then(d => src.setData(d))
promise?.catch(err => console.warn("Promise failed:", err))
return src
}
/**
* Converts a promise into a UIVentsource, sets the UIEVentSource when the result is calculated.
* If the promise fails, the value will stay undefined
* @param promise
* @constructor
*/
public static FromPromiseWithErr<T>(promise : Promise<T>): UIEventSource<{success: T} | {error: any}>{
const src = new UIEventSource<{success: T}|{error: any}>(undefined)
promise?.then(d => src.setData({success:d}))
promise?.catch(err => src.setData({error: err}))
return src
}

View file

@ -0,0 +1,49 @@
/**
* Some usefull utility functions around the wikipedia API
*/
import {Utils} from "../../Utils";
import WikipediaBox from "../../UI/WikipediaBox";
export default class Wikipedia {
/**
* When getting a wikipedia page data result, some elements (e.g. navigation, infoboxes, ...) should be removed if 'removeInfoBoxes' is set.
* We do this based on the classes. This set contains a blacklist of the classes to remove
* @private
*/
private static readonly classesToRemove = [
"shortdescription",
"sidebar",
"infobox",
"mw-editsection",
"hatnote" // Often redirects
]
public static async GetArticle(options: {
pageName: string,
language?: "en" | string,
section?: number,
}): Promise<string> {
let section = ""
if (options.section !== undefined) {
section = "&section=" + options.section
}
const url = `https://${options.language ?? "en"}.wikipedia.org/w/api.php?action=parse${section}&format=json&origin=*&prop=text&page=` + options.pageName
const response = await Utils.downloadJson(url)
const html = response["parse"]["text"]["*"];
const div = document.createElement("div")
div.innerHTML = html
const content = Array.from(div.children)[0]
for (const forbiddenClass of Wikipedia.classesToRemove) {
const toRemove = content.getElementsByClassName(forbiddenClass)
for (const toRemoveElement of Array.from(toRemove)) {
toRemoveElement.parentElement?.removeChild(toRemoveElement)
}
}
return content.innerHTML;
}
}