450a8f2ece4772eac272672e5d2c0668e6b1de6a
[sheet.git] / writer.js
1 document.addEventListener('DOMContentLoaded', () => {
2         var wpinput = document.getElementById('wptitle');
3         var wpbutton = wpinput.parentNode.appendChild(document.createElement('button'));
4         wpbutton.type = 'button';
5         wpbutton.append('Copy');
6         wpbutton.onclick = () => {
7                 let wptitle = wpinput.value || document.getElementById('form').value;
8                 let wplang = document.getElementById('lang').value.substr(0, 2); // crude iso-639-3→2
9                 let wpapi = `https://${wplang}.wikipedia.org/w/api.php`;
10                 let wppage = wpapi+'?action=parse&format=json&origin=*&prop=text&page='+wptitle;
11                 fetch(wppage).then(res => res.json()).then(json => {
12                         if (json.error) throw `error returned: ${json.error.info}`;
13                         wpinput.value = json.parse.title;
14                         let imginput = document.getElementById('source');
15                         if (imginput.value) return;
16                         let wpimages = json.parse.text['*'].match(/<img\s[^>]+>/g);
17                         let wpselect = wpinput.parentNode.appendChild(document.createElement('ul'));
18                         wpselect.className = 'popup';
19                         wpimages.forEach(img => {
20                                 let selectitem = wpselect.appendChild(document.createElement('li'));
21                                 selectitem.insertAdjacentHTML('beforeend', img);
22                                 selectitem.onclick = e => {
23                                         let imgsrc = e.target.src
24                                                 .replace(/^(?=\/\/)/, 'https:')
25                                                 .replace(/\/thumb(\/.+)\/[^\/]+$/, '$1');
26                                         imginput.value = imgsrc;
27                                         wpselect.remove();
28                                         return false;
29                                 };
30                         });
31                 }).catch(error => alert(error));
32                 return false;
33         };
34 });