AnnotationToggler = Annotation Toggler. It adds a tab menu item to toggle list item (LI) annotations.
ViewAnnotationToggler.js: adds a tab menu item and hot key to turn list item annotations off and on, across all pages..
The hot key is ⇧ Shift+Alt+a.
This script works on the list items in bulleted lists, lists in which each item is preceded by a bullet. Bulleted lists abound upon Wikipedia. They are used in stand-alone lists which are entire articles that are lists, and they are used in embedded lists situated within articles.
Many list items have an annotation, that is, the list item is followed by a description. These descriptions are useful, but they may obscure the items in the list that they describe. Sometimes, it is useful to look at the bare list, without the annotations.
This script turns those descriptions on and off. It provides a tab menu command and a hotkey for doing so.
When you don't need to see the descriptions, turn them off. When you need more detail, hit the toggle again, and the descriptions return. The script stores its status so it doesn't start over between pages — when annotations are turned off, they are off for all pages until you turn them back on again.
Important: this script was developed for use with the Vector skin (it's Wikipedia's default skin), and might not work with other skins. See the top of your Preferences appearance page, to be sure Vector is the chosen skin for your account.
To install this script, add this line to your vector.js page:
importScript("User:The Transhumanist/ViewAnnotationToggler.js");
Save the page and bypass your cache to make sure the changes take effect. By the way, only logged-in users can install scripts.
This section explains the source code, in detail. It is for JavaScript programmers, and for those who want to learn how to program in JavaScript. Hopefully, this will enable you to adapt existing source code into new user scripts with greater ease, and perhaps even compose user scripts from scratch.
You can only use so many comments in the source code before you start to choke or bury the programming itself. So, I've put short summaries in the source code, and have provided in-depth explanations here.
My intention is Threefold:
In addition to plain vanilla JavaScript code, this script relies heavily on the jQuery library.
If you have any comments or questions, feel free to post them at the bottom of this page under Discussions. Be sure to {{ping}} me when you do.
We prep the page by wrapping list item annotations in spans with the class "anno". Then we refer to that class later in hide and show functions which create a menu item that the user can click on. How we do all of this is explained in fine detail below.
An alias is one string defined to mean another. Another term for "alias" is "shortcut". In the script, the following aliases are used:
$
is the alias for jQuery
mw
is the alias for mediawiki
These two aliases are set up like this:
( function ( mw, $ ) {}( mediaWiki, jQuery ) );
That is a "bodyguard function", and is explained in the section below...
The bodyguard function assigns an alias for a name within the function, and reserves that alias for that purpose only. For example, if you want "t" to be interpreted only as "transhumanist".
Since the script uses jQuery, we want to defend jQuery's alias, the "$". The bodyguard function makes it so that "$" means only "jQuery" inside the function, even if it means something else outside the function. That is, it prevents other javascript libraries from overwriting the $() shortcut for jQuery. It does this via scoping.
The bodyguard function is used like a wrapper, with the alias-containing source code inside it. Here's what a jQuery bodyguard function looks like:
1 ( function($) {
2 // you put the body of the script here
3 } ) ( jQuery );
See also: bodyguard function solution.
To extend that to lock in "mw" to mean "mediawiki", use the following (this is what the script uses):
1 ( function(mw, $) {
2 // you put the body of the script here
3 } ) (mediawiki, jQuery);
For the best explanation of the bodyguard function I've found so far, see: Solving "$(document).ready is not a function" and other problems
The ready() event listener/handler makes the rest of the script wait until the page (and its DOM) is loaded and ready to be worked on. If the script tries to do its thing before the page is loaded, there won't be anywhere for it to place the menu item (mw.util.addPortletLink), and the script will fail.
In jQuery, it looks like this: $( document ).ready() {});
The part of the script that is being made to wait goes inside the curly brackets. But you would generally start that on the next line, and put the ending curly bracket, closing parenthesis, and semicolon following that on a line of their own), like this:
1 $(function() {<br>
2 // Body of function (or even the rest of the script) goes here, such as a click handler.<br>
3 });
This is all explained further at the jQuery page for .ready()
For the plain vanilla version see: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
This is a reserved word (aka "keyword"). The keyword var is used to declare variables in variable statements. A variable is a container you can put a value in. To declare the variable portletlink, write this:
var portletlink
A declared variable has no value, until you assign it one. You can combine declaration and assignment, like this:
var portletlink = mw.util.addPortletLink('p-tb', '#', 'Annotations');
Part of the WWW's Document API, this method returns the element with the specified ID. That is, it fetches the entire contents of a unique element. (If the element ID is not unique, it'll fetch the first one only).
A key use of this method is to assign the contents of an element to a variable. (See below).
mw-content-text
is an element ID. Unlike classes, IDs are unique (or are supposed to be).
Unfortunately, this ID is not covered in WP:IDS.
But it is included in the list mw:Manual:Interface/IDs and classes:
It's the part of the HTML page (of a Wikipedia page) that "holds everything between the page title and contentSub on the one hand, and ArticleFeedback and categories on the other hand. present on each page view (includes history view, non-existing pages, print view, ...)."
"cont" is a variable.
It is defined in the following statement:
var cont = document.getElementById('mw-content-text');
That assigned the contents of the page (the content ID'd as mw-content-text) to the variable.
cont.outerHTML
refers to all of cont, including the tags it is enclosed in. That is, the whole element, not just its contents. This is useful when used with .replace, so that a regex can be used to match the tags in a document. (See next section, below).
innerHTML.replace tells regex to search and replace only within the contents of elements, NOT including their tags.
outerHTML.replace tells regex to search and replace within all of the HTML, including the tags. That way, you can search for elements, and not just things inside the elements.
So, this statement in the script:
cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');
Looks for strings with
With this tactic, we isolate the annotations so that we can switch their display on and off later in the script. To isolate them, we wrap the desired content in span tags, with the span including a class. Once they all have the same class, we can manipulate them all at once (like hiding or showing them all).
To do the wrap, we use regex via the .replace method, like this to insert span tags in the desired locations:
cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');
The .outerHTML allows us to match the tags of elements, and not just the contents of elements. If we used .innerHTML, regex would not see the <li> tags, and we would have no way of finding the bulleted list items on the page.
This approach is easier (and more elegant) than using regex to remove the annotations directly, because if you do it that way, you would need to save a copy of the whole page before you removed them, in order to get them back when you "toggle" them back on.
This part controls the main flow of the script (decides what to do under what circumstances):
if ( mw.config.get( 'skin' ) === 'vector' ) {
$( function() {
var annostatus = localStorage.getItem('annostatus');
if ( annostatus === "hide" ) {
annoHide();
} else {
annoShow();
}
} );
}
So, what this does is 3 things:
First, it checks if the Vector skin is being used and runs the rest of the script only if it is.
Then it checks the status of the script, that is, whether it was set to "show" or "hide" the last time it was used.
Then it calls the function that corresponds with the current status (calling either annoHide or annoShow, defaulting to annoShow if there is no status).
This looks up the value for skin (the internal name of the currently used skin) saved in MediaWiki's configuration file.
===
means "equal value and equal type"
In JavaScript, a function is a subroutine. You call a function by its name. The function "example" is called like this:
example();
See also: JavaScript Function Invocation.
The script has 2 custom functions written in it: annoHide, and annoShow. Each one includes a function call to the other, but the main controlling structure of the program checks local storage to see what the program's hide/show status is (in local storage), and calls the corresponding function.
"Function" is another name for "subroutine". Here's how you define a function in JavaScript:
function nameoffunction() {
// do some stuff here
}
The function itself (the instructions that are executed when the function is called) lies between the curly brackets.
A function is not activated until it is called. (See next section).
The localStorage
property allows you to store some data in the browser's memory area for later use, so you don't lose it when changing pages or closing the browser.
What we use it for in the script is to store the script's show/hide status, so we can check it (each time the script starts) to see whether the script is supposed to execute the annoHide or the annoShow function. To create a data item in localStorage named "annostatus" for storing the value "show", we do this:
localStorage.setItem("annostatus", "show");
To store the script's status as "hide", we do this:
localStorage.setItem("annostatus", "hide");
For further detail, see: Using the Web Storage API.
The main power of the script is provided by using two jQuery methods: .hide and .show
Each works on the elements that they are appended to. We append them to "anno", which is the class we assigned earlier to all annotations by wrapping them in span tags, but they must be appended in a specific way, like this:
$( ".anno" ).hide();
and this:
$( ".anno").show();
After the script executes a show or hide, the menu item needs to be updated. The first step is to check that it ("annoSwitch") exists, and if it does, remove it. Like this:
if ( annoSwitch ) {
annoSwitch.parentNode.removeChild(annoSwitch);
}
I have no idea why you can't remove a node directly, instead of removing it as a child of its parentNode. That seems convoluted, but it is the only way I could find that worked. If you know of an easier (more direct) way, please let me know.
mw.util.addPortletLink is a function in the core module "mediaWiki". It adds a menu item to one of Wikipedia's menus. Use "p-tb" to signify the toolbox menu on the sidebar menu.
First you stick it in a variable, for example, "portletlink":
var portletlink = mw.util.addPortletLink('p-tb', '#', 'Annotations \(show\)');
It has up to 7 parameters, with the first 3 being required. Only those 3 are used above.
Important: It won't do anything until you bind it to a click handler (see below).
General usage:
mw.util.addPortletLink( 'portletId', 'href', 'text', 'id', 'tooltip', 'accesskey', 'nextnode');
It's components:
mw.util.addPortletLink
: the ResourceLoader module to add links to the portlets.portletId
: portlet id— the section where the new menu item is to be placed. Valid values:
p-navigation
: Navigation section in left sidebarp-interaction
: Interaction section in left sidebarp-tb
: Toolbox section in left sidebarcoll-print_export
: Print/export section in left sidebarp-personal
Personal toolbar at the top of the pagep-views
Upper right tabs in Vector only (read, edit, history, watch, etc.)p-cactions
Drop-down menu containing move, etc. (in Vector); subject/talk links and action links in other skinshref
: Link to the Wikipedia or external pagetext
: Text that displaysid
: HTML id (optional)tooltip
: Tooltip to display on mouseover (optional)accesskey
: Shortcut key press (optional)nextnode
: Existing portlet link to place the new portlet link before (optional)The optional fields must be included in the above order. To skip a field without changing it, use the value null.
For the documentation on this function, see https://www.mediawiki.orghttps://wikines.com/en/ResourceLoader/Modules#addPortletLink and Help:Customizing toolbars.
Important: It won't do anything until you bind it to a click handler (see below).
To make the above menu item so it does something when you click on it, you have to "bind" it to a handler. Like this:
1 $(portletlink).click( function(e) {
2 e.preventDefault();
3 //do some stuff
4 }
The "handler" is the part between the curly brackets.
To read about function(e), see what does e mean in this function definition?
jQuery's event objects are explained here: http://api.jquery.com/category/events/event-object/
e.preventDefault()
is short for event.preventDefault()
, one of jQuery's event objects.
Improvements needed:
http://stackoverflow.com/questions/9614622/equivalent-of-jquery-hide-to-set-visibility-hidden
It states: There isn't one built in but you could write your own quite easily:
(function($) {
$.fn.invisible = function() {
return this.each(function() {
$(this).css("visibility", "hidden");
});
};
$.fn.visible = function() {
return this.each(function() {
$(this).css("visibility", "visible");
});
};
}(jQuery));
You can then call this like so:
$("#someElem").invisible();
$("#someOther").visible();
Here's a working example.
The current objective is to store global variables, and pass them on to the next page, including the current page upon refresh.
The state of the program can then be controlled from page to page, via conditionals applied upon the global variables.
Methods that persists data across a page refresh include:
localStorage.setItem("annostatus", "hide");
var annostatus = localStorage.getItem('annostatus');
Feature completed. The Transhumanist 09:06, 11 December 2016 (UTC)
Initially, the program toggled hide/show in a rather convoluted way: first it saved the mw-content element by cloning it. Then it deleted the annotations using regex. To get them back, it made a clone of the clone, and then replaced mw-content with the second clone. Here's that version:
https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/anno.js&oldid=759842909
Then based on a suggestion by Anomie, I simplified the script to wrap each annotation in a classed span (class="anno"), and then used jQuery in the subfunctions to .hide and .show the class. Here's the simplification:
https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/anno.js&oldid=760834841
It shrank by several lines of code. The Transhumanist 13:27, 19 January 2017 (UTC)
One way to hide/show a class is to define that class on the page, and then toggle its display property. Where are the instructions on how to do this?
Here are some related links:
I'm thinking of the following approach, but do not know how to implement it:
First, an element (or text) within the viewport must be identified as a locator reference. Then the distance from that to the top of the viewport is measured. After the toggle has been activated, the location of the viewport top can be reset to that distance from that element.
See: https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint and http://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html
This is a rather cludgy way to do it. See the next section instead. 23:40, 3 June 2017 (UTC)
I would like to find the topmost element that starts within the viewport.
You can get the position of an element, relative to the viewport, with code from http://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element. You can then keep that element on the screen with code from http://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html. The two websearches I used to find these were https://duckduckgo.com/?q=js+get+top-left+object and https://duckduckgo.com/?q=js+scroll+element+to+viewport+position. (quote from LongHairedFop (talk) 13:53, 11 December 2016 (UTC))
This approach can be used to create a function to check every element's position against the viewport's position, to determine which element is the topmost in the viewport. One problem is that some elements might be inside other elements, such as navigation sidebars, but most of those will be over on the right of the page, so you can check the x-coordinate to filter those out.)
The goal here is to maintain the position of the scroll, with respect to the topmost list entry on the screen, and have the formatting change while maintaining that position.
Some potentially relevant resources:
p = object.scrollTop
$(window).scrollTop()
vs. $(document).scrollTop()
The functionality I'm trying to add to this script is to reposition the viewport to restore it to where it was in the text after some text has been hidden or unhidden.
I've been searching for any and all pages that can explain any part of the problem, and have listed the ones I've found so far above.
Maybe this approach would work:
Put another way:
I think I've got an approach that could work – for elements above the veiwport, get the difference in height from before hiding annotations to after hiding annotations, then scroll the window up by that amount.
bottom
In code, this would be something like the following
//Select the set of annotations that are above where the viewpoint is scrolled to
var $annos_above = $(".anno").filter( function(){
var rect = this.getBoundingClientRect();
if ( rect.bottom < 0 ) {
return true;
} else {
return false;
}
} );
//For each annotation above the viewport, get the difference in height in the containing element as that annotation is hidden
var scroll_amount = 0;
$annos_above.each( function(){
var height_before = $(this).parent().outerHeight(true);
$(this).hide();
var height_after = $(this).parent().outerHeight(true);
scroll_amount = scroll_amount + (height_after-height_before);
} );
//Hide the remaining annotations
$( ".anno" ).hide();
//Scroll the window by the required amount
window.scrollBy(0, scroll_amount);
- Evad37 05:06, 28 May 2017 (UTC)
@Evad37: I inserted the code that you provided (above) into the script, and the script repositioned the viewport in a surprising way.
It realigned to the script's menu item on the sidebar. I hadn't noticed before that it has been doing this all along. Apparently it does this because of following code near the end of the function:
// now we have to update the menu item
// (referred to in this script as "annoSwitch").
// To do that, first we remove it (if it exists):
if ( annoSwitch ) {
annoSwitch.parentNode.removeChild(annoSwitch);
}
// and then we create it (or its replacement) from scratch:
annoSwitch = mw.util.addPortletLink( 'p-tb', '#', 'Annotations \(show\)', 'ca-anno', 'Show the annotations', 'a' );
Maybe this problem could be fixed with the Window scrollTo() Method, if there was some way to record the scroll position of the window in the first place. If there was, the measurement could be taken before the menu item was updated, and then the position restored via window.scrollTo(xpos, ypos) after the change was completed.
I tried sandwiching the menu item updating operations with y = window.scrollY;
and window.scrollTo(0, y);
, but it is not working for some reason. I placed var y;
at the beginning of the script.
I was very impressed with the solution you dreamed up above, and was wondering if you might have any ideas on how to fix this complication.
I look forward to your reply, The Transhumanist 16:01, 8 July 2017 (UTC)
// get the value of our status variable from memory
// (this tells us what mode to start in)
var annostatus = localStorage.getItem('annostatus');
// run the function corresponding to the current status
if ( annostatus === "hide" ) {
//Create portlet link in (show) state
mw.util.addPortletLink( 'p-tb', '#', 'Annotations \(show\)', 'ca-anno', 'Show the annotations', 'a' );
//then do the hiding
annoHide();
} else {
//Create portlet link in (hide) state
mw.util.addPortletLink( 'p-tb', '#', 'Annotations \(hide\)', 'ca-anno', 'Hide the annotations', 'a' );
//then do the showing
annoShow();
}
$('#ca-anno').click( function ( e ) {
e.preventDefault();
var $portletLink = $('#ca-anno').find('a');
var portletTitle = $portletLink.attr('title');
var portletText = $portletLink.text();
if ( portletText.includes('hide') ) {
//toggle portlet title/text
$portletLink.attr('title', portletTitle.replace('Hide', 'Show')).text(portletText.replace('hide', 'show');
//then do the hiding
annoHide();
} else {
//toggle portlet title/text
$portletLink.attr('title', portletTitle.replace('Show', 'Hide')).text(portletText.replace('show', 'hide');
//then do the showing
annoShow();
} );
} );
And remove the portlet creation/removal code from within annoHide and annoShow. - Evad37 02:32, 9 July 2017 (UTC)
See User:GregU/dashes.js.
Post new discussion threads below.
Hi, @The Transhumanist:. I've discovered an unintended side-effect caused by a line of code in your script, or should I say the line of code.
cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');
This code strips action handlers from DOM elements which are descendants of mw-content-text
. This notably affects 'buttons', such as the 'show/hide' button in the following templates:
Extended content
|
---|
Peekaboo. |
You might be able to prevent this by iterating through <li>
elements, like so:
$("#mw-content-text li").each(function()
{
$(this).html($(this).html().replace(/(.*?)( –.*)/g,'$1<span class="anno">$2</span>'));
});
Let me know if this helps! Regards, GUYWAN ( t · c ) 12:20, 6 June 2019 (UTC)