/
wikipedia-query.js
322 lines (322 loc) · 8.85 KB
/
wikipedia-query.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import { LitElement, html, css } from "lit";
import { IntersectionObserverMixin } from "@lrnwebcomponents/intersection-element/lib/IntersectionObserverMixin.js";
/**
* `wikipedia-query`
* `Query and present information from wikipedia.`
* @demo demo/index.html
* @element wikipedia-query
*/
class WikipediaQuery extends IntersectionObserverMixin(LitElement) {
/**
* LitElement constructable styles enhancement
*/
static get styles() {
return [
css`
:host {
display: block;
--wikipedia-query-body-height: 160px;
--wikipedia-query-background-color: #f8f8f8;
}
:host [hidden] {
display: none;
}
#result {
height: var(--wikipedia-query-body-height);
overflow: scroll;
border: 1px grey solid;
padding: 8px 16px;
}
citation-element {
background-color: var(--wikipedia-query-background-color);
padding: 16px 8px;
font-size: 12px;
}
`,
];
}
constructor() {
super();
this.hideTitle = false;
const FALLBACK_LANG = "en";
const language =
document.body.getAttribute("xml:lang") ||
document.body.getAttribute("lang") ||
document.documentElement.getAttribute("xml:lang") ||
document.documentElement.getAttribute("lang") ||
navigator.language ||
FALLBACK_LANG;
this.language = language.split("-")[0];
this.headers = {
cache: "force-cache",
};
let date = new Date(Date.now());
this.__now =
date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
}
/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/
static get tag() {
return "wikipedia-query";
}
// LitElement render function
render() {
return html` ${this.elementVisible
? html` <h3 .hidden="${this.hideTitle}" part="heading-3">
${this._title}
</h3>
<div id="result"></div>
<citation-element
creator="{Wikipedia contributors}"
scope="sibling"
license="by-sa"
title="${this.search} --- {Wikipedia}{,} The Free Encyclopedia"
source="https://${this
.language}.wikipedia.org/w/index.php?title=${this.search}"
date="${this.__now}"
></citation-element>`
: ``}`;
}
updateArticle(search, headers, language) {
fetch(
`https://${language}.wikipedia.org/w/api.php?origin=*&action=query&titles=${search}&prop=extracts&format=json`,
headers,
)
.then((response) => {
if (response.ok) return response.json();
})
.then((json) => {
this.handleResponse(json);
});
}
/**
* LitElement properties updated
*/
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
// element is visible, now we can search
if (propName == "elementVisible" && this[propName]) {
import("@lrnwebcomponents/citation-element/citation-element.js");
}
if (
["elementVisible", "search", "headers", "language"].includes(
propName,
) &&
this.search &&
this.headers &&
this.elementVisible &&
this.language
) {
clearTimeout(this._debounce);
this._debounce = setTimeout(() => {
this.updateArticle(this.search, this.headers, this.language);
}, 10);
}
if (propName == "search") {
if (this.title) {
this._title = this.title;
} else {
this._title = this[propName].replace("_", " ") + " Wikipedia article";
}
}
if (propName == "title") {
if (this.title) {
this._title = this.title;
}
}
});
}
static get properties() {
let props = {};
if (super.properties) {
props = super.properties;
}
return {
...props,
title: {
type: String,
},
__now: {
type: String,
},
_title: {
type: String,
},
headers: {
type: Object,
},
/**
* hideTitle
*/
hideTitle: {
type: Boolean,
attribute: "hide-title",
},
/**
* Search string.
*/
search: {
type: String,
},
/**
* Two letter language abbreviation used by
* Wikipedia (ex: Spanish = "es").
*/
language: {
type: String,
},
};
}
/**
* Process response from wikipedia.
*/
handleResponse(response) {
// the key of pages is a number so need to look for it
if (typeof response !== typeof undefined && response.query) {
for (var key in response.query.pages) {
// skip anything that's prototype object
if (!response.query.pages.hasOwnProperty(key)) continue;
// load object response, double check we have an extract
if (
response.query.pages[key].extract &&
this.shadowRoot &&
this.shadowRoot.querySelector("#result")
) {
let html = response.query.pages[key].extract;
html = html.replace(/<script[\s\S]*?>/gi, "<script>");
html = html.replace(/<\/script>/gi, "</script>");
html = html.replace(/<style[\s\S]*?>/gi, "<style>");
html = html.replace(/<\/style>/gi, "</style>");
// need to innerHTML this or it won't set
this.shadowRoot.querySelector("#result").innerHTML = html;
}
}
}
}
/**
* Implements haxHooks to tie into life-cycle if hax exists.
*/
haxHooks() {
return {
gizmoRegistration: "haxgizmoRegistration",
};
}
/**
* @see haxHooks: gizmoRegistration
*/
haxgizmoRegistration(store) {
window.dispatchEvent(
new CustomEvent("i18n-manager-register-element", {
detail: {
namespace: `wikipedia-query.haxProperties`,
localesPath: new URL(`./locales`, import.meta.url).href,
locales: ["es", "fr"],
},
}),
);
// ensure that this is a valid type of gizmo for endpoints
// this is nessecary because wikipedia-query wants to be the sole
// provider of display for things coming off the API
store.validGizmoTypes.push("wikipedia");
if (
store.appList.filter((el, i) => {
// ensure we don't double load the endpoint if already defined
if (el.connection.url === this.language + ".wikipedia.org") {
return true;
}
return false;
}).length === 0
) {
window.dispatchEvent(
new CustomEvent("hax-register-app", {
bubbles: false,
composed: false,
cancelable: false,
detail: this.haxAppDetails,
}),
);
}
}
// return valid appStore spec for how to connect to the wikipedia API
get haxAppDetails() {
return {
details: {
title: "Wikipedia",
icon: "account-balance",
color: "grey",
author: "Wikimedia",
description: "Encyclopedia of the world.",
status: "available",
tags: [
"Search",
"source",
"wikipedia",
"content",
"encyclopedia",
"wiki",
],
},
connection: {
protocol: "https",
url: this.language + ".wikipedia.org",
data: {
action: "query",
list: "search",
format: "json",
origin: "*",
},
operations: {
browse: {
method: "GET",
endPoint: "w/api.php",
pagination: {
style: "offset",
props: {
offset: "sroffset",
},
},
search: {
srsearch: {
title: "Search",
type: "string",
},
},
data: {},
resultMap: {
image:
"https://" +
this.language +
".wikipedia.org/static/images/project-logos/enwiki.png",
defaultGizmoType: "wikipedia",
items: "query.search",
preview: {
title: "title",
details: "snippet",
id: "title",
},
gizmo: {
_url_source:
"https://" + this.language + ".wikipedia.org/wiki/<%= id %>",
id: "title",
title: "title",
caption: "snippet",
description: "snippet",
},
},
},
},
},
};
}
/**
* haxProperties integration via file reference
*/
static get haxProperties() {
return new URL(`./lib/${this.tag}.haxProperties.json`, import.meta.url)
.href;
}
}
customElements.define(WikipediaQuery.tag, WikipediaQuery);
export { WikipediaQuery };