word edit: separate javascript include
[sheet.git] / writer.js
diff --git a/writer.js b/writer.js
new file mode 100644 (file)
index 0000000..450a8f2
--- /dev/null
+++ b/writer.js
@@ -0,0 +1,34 @@
+document.addEventListener('DOMContentLoaded', () => {
+       var wpinput = document.getElementById('wptitle');
+       var wpbutton = wpinput.parentNode.appendChild(document.createElement('button'));
+       wpbutton.type = 'button';
+       wpbutton.append('Copy');
+       wpbutton.onclick = () => {
+               let wptitle = wpinput.value || document.getElementById('form').value;
+               let wplang = document.getElementById('lang').value.substr(0, 2); // crude iso-639-3→2
+               let wpapi = `https://${wplang}.wikipedia.org/w/api.php`;
+               let wppage = wpapi+'?action=parse&format=json&origin=*&prop=text&page='+wptitle;
+               fetch(wppage).then(res => res.json()).then(json => {
+                       if (json.error) throw `error returned: ${json.error.info}`;
+                       wpinput.value = json.parse.title;
+                       let imginput = document.getElementById('source');
+                       if (imginput.value) return;
+                       let wpimages = json.parse.text['*'].match(/<img\s[^>]+>/g);
+                       let wpselect = wpinput.parentNode.appendChild(document.createElement('ul'));
+                       wpselect.className = 'popup';
+                       wpimages.forEach(img => {
+                               let selectitem = wpselect.appendChild(document.createElement('li'));
+                               selectitem.insertAdjacentHTML('beforeend', img);
+                               selectitem.onclick = e => {
+                                       let imgsrc = e.target.src
+                                               .replace(/^(?=\/\/)/, 'https:')
+                                               .replace(/\/thumb(\/.+)\/[^\/]+$/, '$1');
+                                       imginput.value = imgsrc;
+                                       wpselect.remove();
+                                       return false;
+                               };
+                       });
+               }).catch(error => alert(error));
+               return false;
+       };
+});