User:Þjarkur/Nudge me to read in another language.js

/*

Nudge me to read in another language

A script that nudges you to read more in the language you're interested in by displaying the beginning of that language's article while you read the English language Wikipedia.

Set your desired language with: > window.nudge_me_to_read_in_this_language_code = 'es'

CC0

(function {  if (mw.config.get('wgAction') !== 'view') return;  if (mw.config.get('wgNamespaceNumber') !== 0) return;  var url = new URL(window.location.href)  if(mw.config.get('wgDiffOldId')) return;  if(mw.config.get('wgRevisionId') !== mw.config.get('wgCurRevisionId')) return;

/* Default to Spanish */ var nudge_me_to_read_in_this_language_code = window.nudge_me_to_read_in_this_language_code || 'es'; var project_url = `https://${nudge_me_to_read_in_this_language_code}.wikipedia.org` var article_url = $(`#p-lang a[href^="${project_url}"]`).attr('href')

if (!article_url) return; if($('#toc:not(.tocright #toc)').length < 1) return; /* Redirect to the article in 3% of cases */ if(Math.random<0.03){ window.location.href = article_url return }

var title = article_url.match(/\/wiki\/(.+)/)[1]

$.get(`${project_url}/w/api.php?action=parse&origin=*&format=json&page=${title}`, function (data) {

/* Wrap in an element (for some reason I couldn't query :root) */ var html = $(' ' + data.parse.text['*'] + ' ')

/* Remove images, hatnotes, and sections that are not the intro */ html .find('.noprint, .mw-empty-elt, table, .infobox, .thumb, .image, h2 +, h2, .mw-parser-output > *:not(p), p > div') .remove

/* Remove "Citation needed" */ html .find('sup a[href^="/wiki/Wikipedia:"], sup a[href^="#"]') .closest('sup') .remove

/* Remove empty divs */ html .find('p:empty') .remove

console.log(html)

/* Find the first paragraph */ paragraph = html.find('p').first

/* Turn relative urls into absolute urls */ paragraph.find('a[href^="/"]').each(function {      $(this).attr('href', project_url + $(this).attr('href'))    })

// /* "Continue reading" button */ //paragraph.append(`[Continue reading...] `) paragraph.attr('class','noprint') // paragraph.css({   //   background: '#fff4d6',    //   padding: '10px',    //   border: '1px solid #fbda9e',    //   borderRadius: '3px',    //   fontSize: '14px',    //   lineHeight: '1.6',    //   marginBottom: '20px',    // })

// /* Calculate scroll position */ // var offsetBefore = $('#firstHeading').offset.top $('#toc').before(paragraph) // var offsetAfter = $('#firstHeading').offset.top // if ($(window).scrollTop < offsetBefore) { //  $(window).scrollTop($(window).scrollTop + (offsetAfter - offsetBefore)) // }   // $('#mw-panel').css({ marginTop: (offsetAfter - offsetBefore) + 'px' }) }) })