User:HTan (WMF)/fact cards.js

// --- Variables ---

const fallbackImage = 'Noun_Fact_3331495.svg'; const username = mw.config.get('wgUserName'); const lang = mw.config.get('wgPageContentLanguage'); const articleTitle = mw.config.get('wgPageName'); let allFacts = '';

// --- Functions ---

function isArticleView { return ( mw.config.get( 'wgAction' ) === 'view' ) && ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) && ( mw.config.get('wgArticleId') > 0 ); }

// --- Main program ---

if ( isArticleView ) { console.log( 'Fact Cards - init' );

// --- Builder Create --- const showPopup = function(x, y, selectedText) { const createBtn = document.createElement( 'div' ); createBtn.id = 'mw-fact-popup'; createBtn.textContent = '+ Fact'; createBtn.style.top = ( window.scrollY + y + 20 ) + 'px'; createBtn.style.left = x + 'px'; createBtn.onclick = function(e) { if ( window.OO && window.OO.ui ) { window.OO.ui.confirm( `Adding new Fact "${selectedText}"?` ) .done( function ( confirmed ) {					   if ( confirmed ) {					        saveFacts( selectedText );					    }					    document.querySelector( '#mw-fact-popup' ).remove;					} ); } else { if (window.confirm( `Adding new Fact ${selectedText}?` )) { saveFacts( selectedText ); }				document.querySelector( '#mw-fact-popup' ).remove; }       }        document.body.appendChild( createBtn ); }

document.querySelector( '#bodyContent' ).addEventListener( 'mouseup', function(e) {       const { clientX, clientY } = e;        const selectedText = window.getSelection.toString.trim;        if( selectedText ) {            document.querySelector('#mw-fact-popup')?.remove;            showPopup( clientX, clientY, selectedText );        } else {            document.querySelector('#mw-fact-popup')?.remove;        }    } );

// --- Viewer --- const getFacts = (user, lang, title) => { const titles = `User:${user}/${lang}/${title}/facts`; const params = { action: 'query', prop: 'revisions', titles: titles, rvslots: 'main', rvprop: 'content' }       return ( new mw.Api ).get( params ) .then( response => {               const page = response.query.pages;                const pageId = Object.keys( page )[ 0 ];

return page[ pageId].revisions[0].slots.main[ '*' ]; } )   }

// get all facts from current page getFacts( username, lang, articleTitle ).then( f => {        allFacts = f;        console.log( 'Facts:', f.split('\n\n') );     } )

const saveFacts = ( newFact ) => { const titles = `User:${username}/${lang}/${articleTitle}/facts`; (new mw.Api).post(

{               action: 'edit', title: titles, text: allFacts + '\n\n' + newFact, summary: `Add fact ${newFact}`, token: mw.user.tokens.get( 'csrfToken' ) }       ).then(  => {

mw.notify( `New Fact "${newFact}" has been added` ); // update variables all facts allFacts += '\n\n' + newFact; } );   } }