User:Splarka/portalpreview.js

From Meta, a Wikimedia project coordination wiki

Jump to: navigation, search

Note: After saving, you may have to bypass your browser's cache to see the changes. Mozilla / Firefox / Safari: hold down Shift while clicking Reload, or press Ctrl-Shift-R (Cmd-Shift-R on Apple Mac); IE: hold Ctrl while clicking Refresh, or press Ctrl-F5; Konqueror: simply click the Reload button, or press F5; Opera users may need to completely clear their cache in Tools→Preferences.

/* Portal previewer [0.0.3], Original from http://meta.wikimedia.org/wiki/User:Splarka/portalpreview.js
 
Lets you preview the portal templates on meta. 
Detects if the wgPageName starts with 'Www.' per http://meta.wikimedia.org/wiki/Special:PrefixIndex/Www.
 
Notes:
* Now opens popup window immediately (rather than wait for callback).
* Might require disabling popup blockers (or adding this site to your trusted list for popups).
* Requires popup because:
** Convenient way to document.write without annoying frames.
** Maintains document XHTML integrety (wouldn't work as a div in page).
** Doesn't leave current edit window or action (prevents possible loss of data).
* On action edit, will now preview the textarea contents rather than top revision.
* knick-knack paddywhack, give a dog a bone.
*/
 
var portalpreviewwindow; //popup global
if(wgPageName.indexOf('Www.') == 0) addOnloadHook(function() {
  if(wgAction == 'edit' || wgAction == 'submit') {
    addPortletLink('p-cactions','javascript:portalPreviewTextarea();','live preview portal textarea','ca-tpv','Preview contents of this textarea (Warning: may contain arbitrary javascript)');
  } else {
    addPortletLink('p-cactions','javascript:portalPreview();','preview portal','ca-tpv','Preview this portal in a popup (Warning: may contain arbitrary javascript)');
  }
})
 
function portalPreview() {
  portalPreviewPop();
  var url = wgServer + wgScriptPath + '/api.php?action=query&format=json&callback=portalPreviewCB&prop=revisions&rvprop=content&titles=' + encodeURIComponent(wgPageName);
  importScriptURI(url);
}
 
function portalPreviewCB(obj) {
  var html = '';
  if(!obj['query'] || !obj['query']['pages']) return
  var pages = obj['query']['pages'];
  for(var i in pages) {
    for(var j in pages[i]['revisions']) {
      html = pages[i]['revisions'][j]['*'];
    }
  }
  portalPreviewPop(html);
}
 
function portalPreviewTextarea() {
  var txt = document.getElementById('wpTextbox1');
  if(!txt) return
  var html = txt.value;
  portalPreviewPop();
  portalPreviewPop(html);
}
 
function portalPreviewPop(html) {
  //split so popup can be called earlier in ajax-like query.
  if(!html) {
    portalpreviewwindow = window.open('', 'portal_preview', config='height=600,width=800,toolbar=0,menubar=0,location=1,directories=0,status=0');
  } else {
    portalpreviewwindow.document.write(html);
    portalpreviewwindow.document.close();
  }
}