User talk:The Transhumanist/ViewAnnotationToggler.js


 * This script is operational: its main features work; it is under further development

AnnotationToggler = Annotation Toggler. It adds a tab menu item to toggle list item (LI) annotations.

= Script's workshop =
 * This is the work area for developing the script and its documentation. The talk page portion of this page starts at, below.

Description / instruction manual

 * This script is operational: its main features work; it is under further development

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.

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 &mdash; when annotations are turned off, they are off for all pages until you turn them back on again.

General approach
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.

aliases
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

is the alias for mediawiki

These two aliases are set up like this:

That is a "bodyguard function", and is explained in the section below...

Bodyguard function
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:

See also: bodyguard function solution.

To extend that to lock in "mw" to mean "mediawiki", use the following (this is what the script uses):

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
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:

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:

This is all explained further at the jQuery page for

For the plain vanilla version see: http://docs.jquery.com/Tutorials:Introducing_$(document).ready

var
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:

A declared variable has no value, until you assign it one. You can combine declaration and assignment, like this:

document.get.ElementById
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).


 * HTML DOM getElementById Method
 * document.getElementById

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. [It is] present on each page view (includes history view, non-existing pages, print view, ...)."

cont.outerHTML
"cont" is a variable.

It is defined in the following statement:

That assigned the contents of the page (the content ID'd as mw-content-text) to the variable.

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).


 * outerHTML property
 * Element.outerHTML

outerHTML.replace
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:

Looks for strings with  tags in them. If we used innerHTML, it would not find any.


 * outerHTML property
 * innerHTML and outerHTML to Get and Replace HTML content

Wrapping the annotations in span tags
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:

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  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.

Central control structure
This part controls the main flow of the script (decides what to do under what circumstances):

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).


 * JavaScript control structures
 * Control flow and error handling

if and if/else statements

 * JavaScript If...Else Statements
 * if...else
 * https://www.tutorialspoint.com/javascript/javascript_ifelse.htm

mw.config.get ( 'skin' )
This looks up the value for skin (the internal name of the currently used skin) saved in MediaWiki's configuration file.


 * jQuery get Method
 * mw.config

logical operators
means "equal value and equal type"


 * JavaScript Comparison and Logical Operators

localStorage.getItem

 * LocalStorage
 * Storage.getItem

Calling a function
In JavaScript, a function is a subroutine. You call a function by its name. The function "example" is called like this:

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.

Defining a function
"Function" is another name for "subroutine". Here's how you define a function in JavaScript:

The function itself (the instructions that are executed when the function is called) lies between the curly brackets.


 * JavaScript functions
 * Functions

A function is not activated until it is called. (See next section).

localStorage.setItem
The 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:

To store the script's status as "hide", we do this:

For further detail, see: Using the Web Storage API.

How the script hides and shows the annotations
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:

and this:

Checking and clearing the menu item
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:

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.


 * HTML DOM parentNode Property
 * HTML DOM removeChild Method
 * .remove
 * .detach

Creating a menu item with mw.util.addPortletLink
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":

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:

It's components:
 * : the ResourceLoader module to add links to the portlets.
 * : portlet id— the section where the new menu item is to be placed. Valid values:
 * : Navigation section in left sidebar
 * : Interaction section in left sidebar
 * : Toolbox section in left sidebar
 * : Print/export section in left sidebar
 * Personal toolbar at the top of the page
 * Upper right tabs in Vector only (read, edit, history, watch, etc.)
 * Drop-down menu containing move, etc. (in Vector); subject/talk links and action links in other skins
 * : Link to the Wikipedia or external page
 * : Text that displays
 * : HTML id (optional)
 * : Tooltip to display on mouseover (optional)
 * : Shortcut key press (optional)
 * : 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.org/wiki/ResourceLoader/Modules#addPortletLink and Help:Customizing toolbars.

Important: It won't do anything until you bind it to a click handler (see below).

click handler
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:

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/ is short for, one of jQuery's event objects.

Change log

 * 2016-12-08
 * Anchor regexes on  (starting only) element delimiters
 * Version 0.1 – Primary functionality completed - it does as intended: switches between having and not having annotations (Turns on and off, albeit per page)
 * Clones the page's state, to restore it after annotations are removed
 * Uses regex to remove annotations
 * Uses a toggle to switch back and forth between the two states
 * 2016-12-11
 * Version 0.2 – on/off status persists across pages.
 * 2017-01-19
 * Version 0.3 – Simplified the script to wrap annotations and then hide or show them.
 * 2017-07-05
 * Added document ready function, so the script waits until the DOM is loaded before running
 * Changed menu items to "Annotations (show)" and "Annotations (hide)"
 * 2017-07-06
 * Moved the functions to the end of the script to make it easier to follow; marked the sections clearly
 * 2017-07-07
 * Version 0.4 – ready to embark on fixing the viewport
 * 2018-02-23
 * Changed name to ViewAnnotationToggler.js
 * removed activation filter so it works on all pages
 * 2018-03-13
 * Script editor wouldn't work while ViewAnnotationToggler was running, so added a deactivation filter so that this script doesn't run on edit pages.

Desired/completed features

 * Completed features are marked with ✅

Improvements needed:


 * Don't run on move pages
 * Since it hides content, an indicator is needed to show when it is on/off.
 * Fix the conflict with sidebar toggle (it also uses hot-key Shift-Alt-a)
 * load ResourceLoader/Modules
 * Test on many pages of every page type
 * Test on other browsers (tested on Firefox 43.0.4)
 * Port to GreaseMonkey
 * Have separate hot-keys for on and off, to be macro-friendly?
 * Convert annotations, and then clone? (then it will toggle with fixed format)
 * Feature to apply and save fixes (conversions) to wikicode (i.e., replace non-standard annotation punctuation in the page source)

Temporary fix for viewport problem: invisibility
http://stackoverflow.com/questions/9614622/equivalent-of-jquery-hide-to-set-visibility-hidden

It states: There isn't one [(a jQuery function)] built in but you could write your own quite easily:

You can then call this like so:

Here's a working example.

Find/replace annotations of other formats

 * regular hyphens
 * em dashes
 * no-break space-hyphen combos
 * commas
 * hanging hyphens (hyphen, with no annotation)
 * parenthetic annotations?
 * colons

Find/replace annotations of lead list entries (without bullets)

 * Only on pages with the title "Outline of"
 * Match entry that follows heading
 * Match entry that follows "Main"?


 * While in hidden mode, have popup functionality for annotations, when the mouse cursor is hovered over:
 * The topic?
 * The bullet?

Program on/off switch
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:
 * iframe – ?
 * ajax – ?
 * cookies – this requires a server call, and is inefficient
 * localstorage

Feature completed. The Transhumanist 09:06, 11 December 2016 (UTC)

Went from cloning/regex-to-null to show/hide wrapper
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)

Trycatch needed, and more

 * The Transhumanist, where you use local storage.getItem or setItem you should always wrap that in try catch, as it can fail at any moment (even if you checked previously). This can be due to the browser running out of storage space for the domain, or because the browser is running in privacy mode or with an ad blocker extensions or something. Also, your new RegExp calls should be lifted outside of the for loops, so that they aren't continuously recreated. For wpTextbox1.value, realise that sometimes the content might be managed by an editor (The syntaxhighlighting beta does this for instance). We use the jquery.textSelection plugin to abstract way from these differences. Don't check document.title, check mw.config.get( 'wgTitle' ) or mw.config.get( 'wgPageName' ). And when you use mw.util.addPortlink, you have to ensure that the mediawiki.util plugin is loaded already, which you can do by using mw.loader.using. —Th e DJ (talk • contribs) 14:47, 27 October 2017 (UTC)

Links to related discussions

 * Wikipedia talk:WikiProject JavaScript (May/June 2017)
 * User talk:Anomie/Archives/2017(Jan 2017)
 * wrap with span and toggle display property
 * Document.elementFromPoint
 * Reference desk/Archives/Computing/2016 December 9 (Dec 2016)
 * Reference desk/Archives/Computing/2016 December 6 (Dec 2016)
 * Village pump (technical)/Archive 151 (Dec 2016)
 * Village pump (technical)/Archive 151
 * Village pump (technical)/Archive 151
 * Village pump (technical)/Archive 151
 * Village pump (technical)/Archive 151
 * Village pump (technical)/Archive 151
 * Village pump (technical)/Archive 151
 * Village pump (technical)/Archive 151 (annotation toggle - hiding text) (Oct 2016)
 * Village pump (technical)/Archive 151 (regex to hide annotations)
 * Village pump (technical)/Archive 151 (hides annotations)
 * Village pump (technical)/Archive 149 (Sept 2016)
 * Village pump (proposals)/Archive 132 (May 2016)

Injecting/inserting/embedding style
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:
 * The 3 ways to insert CSS into your web pages
 * Four methods of adding CSS to HTML
 * Setting CSS Styles Using JavaScript
 * Inject New CSS Rules
 * CSS Syntax and Selectors
 * Three Ways to Insert CSS
 * Dynamic style - manipulating CSS with JavaScript
 * Add Rules to Stylesheets with JavaScript

Save and reset the viewport position relative to its topmost element
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)

Identify the elements in the viewport
I would like to find the topmost element that starts within the viewport.

Check a particular element to determine if it is in the viewport

 * check if element is in viewport
 * ''How to determine if an element is visible inside the viewport
 * How do I check if an element is really visible with JavaScript?
 * document.elementFromPoint (gets position of topmost element in 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))"
 * From refdesk (computer):


 * http://stackoverflow.com/questions/37882208/get-element-location-relative-to-viewport-with-selenium-python

How to get (and process) all elements on the page
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.)


 * Javascript: How to loop through ALL DOM elements on a page?
 * Get all elements in the body tag using pure javascript

How to get position of an element

 * finding element's position relative to the document
 * jQuery position Method – returns the position (relative to its parent element) of the first matched element.

Find and adjust viewport position

 * Maintaining Scroll Position When Adding Content to the Top of a Container – includes plain JS and jQuery solutions (working from the offset of an element).

Find viewport position
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:


 * The Window Object
 * Document.elementFromPoint
 * Scroll Sneak
 * About the viewport

Get offsets of viewport

 * Window.scrollY & Window.scrollX
 * Window pageXOffset and pageYOffset Properties
 * Can I detect the user viewable area on the browser?

difference between heights

 * http://stackoverflow.com/questions/762394/firefox-get-actual-screen-location-of-viewport – window.outerheight - window.innerheight
 * JavaScript Window - The Browser Object Model – explains how to get window size via window.innerHeight & window.innerWidth

scrollTop

 * scrollTop
 * in plain JS, get or set the horizontal and vertical scroll position of an element or the document
 * HTML DOM scrollTop Property – get the number of pixels the content of a  element is scrolled horizontally and vertically
 * jQuery scrollTop Method
 * Element.scrollTop – property that gets or sets the number of pixels that an element's content is scrolled vertically.
 * scrollTop property –
 * ScrollTop to a div instead of body (SOLVED) –
 * vs.
 * body.scrollTop vs documentElement.scrollTop vs window.pagYOffset vs window.scrollY

Find center of viewport

 * to find center of the viewport and store it in variables
 * Using jQuery to center a DIV on the screen

Set viewport position

 * Window scrollTo Method
 * Window scrollBy Method

A possible solution
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.

Talk-through 1
Maybe this approach would work:


 * 1) We can get the y-offset for the top of the viewport with window.pageYOffset
 * 2) We can get the y-offset for the bottom of the viewport with window.pageYOffset + window.innerHeight
 * 3) this  explains how to get the position of a particular element
 * 4) We can gather all elements on a page to a list using http://stackoverflow.com/questions/4256339/javascript-how-to-loop-through-all-dom-elements-on-a-page
 * 5) Then we can loop through all those elements comparing their position with that of the viewport
 * 6) Once that is done, we should know the topmost element inside the viewport. Record that into a variable.
 * 7) Then that variable is used to get a y-offset after annotations have been hidden/reshown.
 * 8) Use that offset to reposition the viewport using scrollTop

Talk-through 2
Put another way:


 * 1) Determine and store the identity of the element inside the viewport that is closest to the top of the viewport; that is the "targetElement".  To do this, do the following:
 * 2) Declare variable targetElement
 * 3) Determine the position of the top of the viewport; viewportOffset
 * 4) Declare the variable offsetDifference (the distance between targetElement and the top of the viewport), and set it to an initial value of 10,000
 * 5) Make list of all elements on page: someElement
 * 6) Do a for loop on the someElement list
 * 7) Determine element's position
 * 8) If the element is within the viewport
 * 9) And if that element is closer to the top than the last element
 * 10) Set targetElement = that element
 * 11) After annotations are hidden or shown...
 * 12) Set the viewport position relative to the targetElement, by offsetDifference

Adjust viewport position by difference between height of anno elements above viewport before and after the hide or show
From Wikipedia talk:WikiProject JavaScript:

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. In code, this would be something like the following - Evad37 &#91;talk] 05:06, 28 May 2017 (UTC)
 * If an element is above the viewport, getBoundingClientRect will have a negative value for
 * The total height of an element can be obtained by the jQuery .outerHeight(true) method
 * The window can be scrolled using window.scrollBy


 * This looks way more efficient than the approach I've been working on above. Thank you. I'll see what I can do with it. The Transhumanist 23:38, 3 June 2017 (UTC)

Complication
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:

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  and , but it is not working for some reason. I placed  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)
 * I'm not sure if this is the problem, but you probably shouldn't be creating and removing portlet links each time the subroutines run – just define it once, at the start. Something like

And remove the portlet creation/removal code from within annoHide and annoShow. - Evad37 &#91;talk] 02:32, 9 July 2017 (UTC)

Fix annotation delimiters (to ndashes)
See User:GregU/dashes.js.

= Discussions =

Post new discussion threads below.

The Bug Report
Hi,. I've discovered an unintended side-effect caused by a line of code in your script, or should I say the line of code.

This code strips action handlers from DOM elements which are descendants of. This notably affects 'buttons', such as the 'show/hide' button in the following templates:

Peekaboo.

You might be able to prevent this by iterating through  elements, like so:

Let me know if this helps! Regards, GUYWAN ( t &middot; c ) 12:20, 6 June 2019 (UTC)