Content deleted Content added
m Replaced deprecated <source> tags with <syntaxhighlight> |
|||
(175 intermediate revisions by 4 users not shown) | |||
Line 1:
{{User:The Transhumanist/Workshop boilerplate/Lead hatnote}}
: '''''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 [[#Discussions]], 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 {{keypress|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.
{{User:The Transhumanist/Workshop boilerplate/Install}}
{{User:The Transhumanist/Workshop boilerplate/Explanatory notes}} <!--includes h2 heading-->
=== 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:
<code>$</code> is the alias for jQuery
<code>mw</code> is the alias for mediawiki
These two aliases are set up like this:
<syntaxhighlight lang="javascript">
( function ( mw, $ ) {}( mediaWiki, jQuery ) );
</syntaxhighlight>
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:
<syntaxhighlight lang="javascript">
1 ( function($) {
2 // you put the body of the script here
3 } ) ( jQuery );
</syntaxhighlight>
''See also: [http://stackoverflow.com/questions/8666467/how-to-declare-this-function-in-jquery-document-ready-is-not-working bodyguard function solution].''
To extend that to lock in "mw" to mean "mediawiki", use the following (this is what the script uses):
<syntaxhighlight lang="javascript">
1 ( function(mw, $) {
2 // you put the body of the script here
3 } ) (mediawiki, jQuery);
</syntaxhighlight>
''For the best explanation of the bodyguard function I've found so far, see: [http://codeimpossible.com/2010/01/13/solving-document-ready-is-not-a-function-and-other-problems/ 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 [[Document Object Model|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: [http://learn.jquery.com/using-j\query-core/document-ready/ <code>$( document ).ready() {});</code>]
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:
<syntaxhighlight lang="javascript">
1 $(function() {<br>
2 // Body of function (or even the rest of the script) goes here, such as a click handler.<br>
3 });
</syntaxhighlight>
''This is all explained further at [https://api.jquery.com/ready/ the jQuery page for <code>.ready()</code>]''
For the plain vanilla version see: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
=== Prep work ===
==== var ====
This is a [[reserved word]] [https://www.w3schools.com/js/js_reserved.asp ] (aka "keyword"). The keyword [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var 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:
<syntaxhighlight lang="javascript">
var portletlink
</syntaxhighlight>
A declared variable has no value, until you assign it one. You can combine declaration and assignment, like this:
<syntaxhighlight lang="javascript">
var portletlink = mw.util.addPortletLink('p-tb', '#', 'Annotations');
</syntaxhighlight>
==== document.get.ElementById() ====
Part of the [https://developer.mozilla.org/en-US/docs/Web/API/Document 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).
* [https://www.w3schools.com/jsref/met_document_getelementbyid.asp HTML DOM getElementById() Method]
* [https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById document.getElementById()]
A key use of this method is to assign the contents of an element to a variable. (''[[#cont.outerHTML|See below]]'').
==== "mw-content-text" ====
<code>mw-content-text</code> 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:
<syntaxhighlight lang="javascript">
var cont = document.getElementById('mw-content-text');
</syntaxhighlight>
That assigned the contents of the page (the content ID'd as mw-content-text) to the variable.
<code>cont.outerHTML</code> 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).''
* [http://help.dottoro.com/ljloliex.php outerHTML property]
* [https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML 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:
<syntaxhighlight lang="javascript">
cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');
</syntaxhighlight>
Looks for strings with <li> tags in them. If we used innerHTML, it would not find any.
* [http://help.dottoro.com/ljloliex.php outerHTML property]
* [http://coursesweb.net/javascript/innerhtml-outerhtml-get-replace-html-content_t 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:
<syntaxhighlight lang="javascript">
cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');
</syntaxhighlight>
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 <nowiki><li></nowiki> 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):
<syntaxhighlight lang="javascript">
if ( mw.config.get( 'skin' ) === 'vector' ) {
$( function() {
var annostatus = localStorage.getItem('annostatus');
if ( annostatus === "hide" ) {
annoHide();
} else {
annoShow();
}
} );
}
</syntaxhighlight>
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).
* [https://en.wikibooks.org/wiki/JavaScript/Control_structures JavaScript control structures]
* [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling Control flow and error handling]
==== if and if/else statements ====
* [https://www.w3schools.com/js/js_if_else.asp JavaScript If...Else Statements]
* [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else if...else]
* <nowiki>https://www.tutorialspoint.com/javascript/javascript_ifelse.htm</nowiki>
==== 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.
* [https://www.w3schools.com/jquery/ajax_get.asp jQuery get() Method]
* [https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config mw.config]
==== logical operators ====
<code>===</code> means "equal value and equal type"
* [https://www.w3schools.com/js/js_comparisons.asp JavaScript Comparison and Logical Operators]
==== localStorage.getItem ====
* [https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage LocalStorage]
* [https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem 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:
<syntaxhighlight lang="javascript">
example();
</syntaxhighlight>
''See also: [http://www.w3schools.com/js/js_function_invocation.asp 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.
=== Subroutines (functions) ===
==== Defining a function ====
"Function" is another name for "[[subroutine]]". Here's how you define a function in JavaScript:
<syntaxhighlight lang="javascript">
function nameoffunction() {
// do some stuff here
}
</syntaxhighlight>
The function itself (the instructions that are executed when the function is called) lies between the curly brackets.
* [https://www.w3schools.com/js/js_functions.asp JavaScript functions]
* [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions Functions]
A function is not activated until it is called. ''(See next section).''
==== localStorage.setItem ====
The [https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage <code>localStorage</code> 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:
<syntaxhighlight lang="javascript">
localStorage.setItem("annostatus", "show");
</syntaxhighlight>
To store the script's status as "hide", we do this:
<syntaxhighlight lang="javascript">
localStorage.setItem("annostatus", "hide");
</syntaxhighlight>
''For further detail, see: [https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API 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: [http://api.jquery.com/hide/ .hide] and [http://api.jquery.com/show/ .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:
<syntaxhighlight lang="javascript">
$( ".anno" ).hide();
</syntaxhighlight>
and this:
<syntaxhighlight lang="javascript">
$( ".anno").show();
</syntaxhighlight>
==== 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:
<syntaxhighlight lang="javascript">
if ( annoSwitch ) {
annoSwitch.parentNode.removeChild(annoSwitch);
}
</syntaxhighlight>
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.
* [https://www.w3schools.com/jsref/prop_node_parentnode.asp HTML DOM parentNode Property]
* [https://www.w3schools.com/jsref/met_node_removechild.asp HTML DOM removeChild() Method]
* [https://api.jquery.com/remove/ .remove()]
* [https://api.jquery.com/detach/ .detach()]
==== Creating a menu item with mw.util.addPortletLink ====
[[mw:ResourceLoader/Core modules#addPortletLink|mw.util.addPortletLink]] is a function in the core module "[[mw:ResourceLoader/Core modules#MediaWiki|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":
<syntaxhighlight lang="javascript">
var portletlink = mw.util.addPortletLink('p-tb', '#', 'Annotations \(show\)');
</syntaxhighlight>
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:
<syntaxhighlight lang="javascript">
mw.util.addPortletLink( 'portletId', 'href', 'text', 'id', 'tooltip', 'accesskey', 'nextnode');
</syntaxhighlight>
It's components:
* <code>mw.util.addPortletLink</code>: the ResourceLoader module to add links to the portlets.
* <code>portletId</code>: portlet id— the section where the new menu item is to be placed. Valid values:
** <code>p-navigation</code>: Navigation section in left sidebar
** <code>p-interaction</code>: Interaction section in left sidebar
** <code>p-tb</code>: Toolbox section in left sidebar
** <code>coll-print_export</code>: Print/export section in left sidebar
** <code>p-personal</code> Personal toolbar at the top of the page
** <code>p-views</code> Upper right tabs in Vector only (read, edit, history, watch, etc.)
** <code>p-cactions</code> Drop-down menu containing move, etc. (in Vector); subject/talk links and action links in other skins
* <code>href</code>: Link to the Wikipedia or external page
* <code>text</code>: Text that displays
* <code>id</code>: HTML id (optional)
* <code>tooltip</code>: Tooltip to display on mouseover (optional)
* <code>accesskey</code>: Shortcut key press (optional)
* <code>nextnode</code>: 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 <var>null</var>.
''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:
<syntaxhighlight lang="javascript">
1 $(portletlink).click( function(e) {
2 e.preventDefault();
3 //do some stuff
4 }
</syntaxhighlight>
The "handler" is the part between the curly brackets.
To read about function(e), see ''[http://stackoverflow.com/questions/9705172/what-does-e-mean-in-this-function-definition what does e mean in this function definition?]'' <br>
jQuery's event objects are explained here: http://api.jquery.com/category/events/event-object/<br>
<code>e.preventDefault()</code> is short for <code>[http://api.jquery.com/event.preventDefault/ event.preventDefault()]</code>, one of jQuery's event objects.
== Change log ==
* 2016-12-08
** Anchor regexes on <nowiki><li></nowiki> (starting only) element delimiters
Line 9 ⟶ 384:
*** Uses regex to remove annotations
*** Uses a toggle to switch back and forth between the two states
* 2016-12-11
** Version 0.2 – [https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/anno.js&oldid=754184988 on/off status persists across pages].
* 2017-01-19
** Version 0.3 – [https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/anno.js&oldid=760834841 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 – [https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/anno.js&oldid=789519032 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.
== Task list ==
=== Bug reports ===
=== Desired/completed features ===
: ''Completed features are marked with {{done}}''
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)
Line 36 ⟶ 422:
* Feature to apply and save fixes (conversions) to wikicode (i.e., replace non-standard annotation punctuation in the page source)
=== Have the viewport stay anchored on its top entry when the toggle is used ===
==== 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:
<syntaxhighlight lang="javascript">
(function($) {
$.fn.invisible = function() {
return this.each(function() {
$(this).css("visibility", "hidden");
});
};
$.fn.visible = function() {
return this.each(function() {
$(this).css("visibility", "visible");
});
};
}(jQuery));
</syntaxhighlight>
You can then call this like so:
<syntaxhighlight lang="javascript">
$("#someElem").invisible();
$("#someOther").visible();
</syntaxhighlight>
Here's a [http://jsfiddle.net/nGhjQ/ 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 "{{tl|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.
Line 65 ⟶ 492:
Feature completed. [[User talk:The Transhumanist|<i>The Transhumanist</i>]] 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.
https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/anno.js&oldid=760834841
It shrank by several lines of code. [[User talk:The Transhumanist|<i>The Transhumanist</i>]] 13:27, 19 January 2017 (UTC)
== Development notes ==
=== 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 [https://phabricator.wikimedia.org/source/mediawiki/browse/master/resources/src/jquery/jquery.textSelection.js 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 [https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/mw.loader mw.loader.using]. —[[User:TheDJ|Th<span style="color: green">e</span>DJ]] ([[User talk:TheDJ|talk]] • [[Special:Contributions/TheDJ|contribs]]) 14:47, 27 October 2017 (UTC)
=== Links to related discussions ===
* [[Wikipedia talk:WikiProject JavaScript#I'm stumped: How do you save a ___location in the viewport to reposition the viewport later?]] (May/June 2017)
* [[User talk:Anomie/Archives/2017#I'm stumped]](Jan 2017)
** wrap with span and toggle display property
** [https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint Document.elementFromPoint()]
* [[Wikipedia:Reference desk/Archives/Computing/2016 December 9#Scroll position in JavaScript]] (Dec 2016)
* [[Wikipedia:Reference desk/Archives/Computing/2016 December 6#JavaScript question]] (Dec 2016)
* [[Wikipedia:Village pump (technical)/Archive 151#Program on/off switch in JavaScript]] (Dec 2016)
* [[Wikipedia:Village pump (technical)/Archive 151#Loading a RL module]]
* [[Wikipedia:Village pump (technical)/Archive 151#trying to create a toggled script]]
* [[Wikipedia:Village pump (technical)/Archive 151#Program on/off switch in JavaScript]]
* [[Wikipedia:Village pump (technical)/Archive 151#Loading a RL module]]
* [[Wikipedia:Village pump (technical)/Archive 151#trying to create a toggled script]]
* [[Wikipedia:Village pump (technical)/Archive 151#How to replace text?]]
* [[Wikipedia:Village pump (technical)/Archive 151#Trials and tribulatons in Javascript]] (annotation toggle - hiding text) (Oct 2016)
** [[Wikipedia:Village pump (technical)/Archive 151#Writ Keeper test script]] (regex to hide annotations)
** [[Wikipedia:Village pump (technical)/Archive 151#TheDJ test script]] (hides annotations)
* [[Wikipedia:Village pump (technical)/Archive 149#Annotation toggle]] (Sept 2016)
* [[Wikipedia:Village pump (proposals)/Archive 132#Interactive chess boards]] (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:
* [http://www.csstutorial.net/css_misc_inserting.php The 3 ways to insert CSS into your web pages]
* [http://matthewjamestaylor.com/blog/adding-css-to-html-with-link-embed-inline-and-import Four methods of adding CSS to HTML]
* [https://www.kirupa.com/html5/setting_css_styles_using_javascript.htm Setting CSS Styles Using JavaScript]
* [https://css-tricks.com/snippets/javascript/inject-new-css-rules/ Inject New CSS Rules]
* [http://www.w3schools.com/css/css_syntax.asp CSS Syntax and Selectors]
* [http://www.w3schools.com/css/css_howto.asp Three Ways to Insert CSS]
* [https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript Dynamic style - manipulating CSS with JavaScript]
* [https://davidwalsh.name/add-rules-stylesheets 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 =====
* [https://gist.github.com/jjmu15/8646226 check if element is in viewport]
* ''[https://www.axure.com/c/forum/7-0-general-discussion/17662-how-determine-if-element-visible-inside-viewport.html How to determine if an element is visible inside the viewport]
* ''[http://stackoverflow.com/questions/704758/how-do-i-check-if-an-element-is-really-visible-with-javascript How do I check if an element is really visible with JavaScript?]''
* [https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint document.elementFromPoint] (gets position of topmost element in viewport)
* From refdesk (computer):
<blockquote>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 [[User:LongHairedFop|LongHairedFop]] ([[User talk:LongHairedFop|talk]]) 13:53, 11 December 2016 (UTC))</blockquote>
* 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.)
* [http://stackoverflow.com/questions/4256339/javascript-how-to-loop-through-all-dom-elements-on-a-page Javascript: How to loop through ALL DOM elements on a page?]
* [http://stackoverflow.com/questions/12823264/get-all-elements-in-the-body-tag-using-pure-javascript Get all elements in the body tag using pure javascript]
===== How to get position of an element =====
* [https://www.stackoverflow.com/questions/5598743/finding-elements-position-relative-to-the-document finding element's position relative to the document]
* [https://www.w3schools.com/jquery/css_position.asp jQuery position() Method] – returns the position (relative to its parent element) of the first matched element.
==== Find and adjust viewport position ====
* [http://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html 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:
* [https://www.w3schools.com/jsref/obj_window.asp The Window Object]
* [https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint Document.elementFromPoint()]
* ''[http://mrcoles.com/media/js/scroll-sneak.js Scroll Sneak]''
* [http://www.w3schools.com/css/css_rwd_viewport.asp About the viewport]
===== Get offsets of viewport =====
* [https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY Window.scrollY] & [https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollX Window.scrollX]
* [https://www.w3schools.com/jsref/prop_win_pagexoffset.asp Window pageXOffset and pageYOffset Properties]
* ''[http://stackoverflow.com/questions/9271747/can-i-detect-the-user-viewable-area-on-the-browser 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
* [https://www.w3schools.com/js/js_window.asp JavaScript Window - The Browser Object Model] – explains how to get window size via window.innerHeight & window.innerWidth
===== scrollTop =====
* [https://api.jquery.com/scrollTop/ scrollTop()]
* [https://plainjs.com/javascript/styles/get-and-set-scroll-position-of-an-element-26/ in plain JS, get or set the horizontal and vertical scroll position of an element or the document]
* [https://www.w3schools.com/jsref/prop_element_scrolltop.asp HTML DOM scrollTop Property] – get the number of pixels the content of a <nowiki><div></nowiki> element is scrolled horizontally and vertically
* [https://www.w3schools.com/jquery/css_scrolltop.asp jQuery scrollTop() Method]
* [https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop Element.scrollTop] – property that '''gets''' or '''sets''' the number of pixels that an element's content is scrolled vertically.
* [https://msdn.microsoft.com/en-us/library/ms534618(VS.85).aspx scrollTop property] – <code>p = object.scrollTop</code>
* '''[https://www.sitepoint.com/community/t/scrolltop-to-a-div-instead-of-body-solved/213672 ScrollTop to a div instead of body (SOLVED)]''' –
* [http://stackoverflow.com/questions/5371139/window-scrolltop-vs-document-scrolltop <code>$(window).scrollTop()</code> vs. <code>$(document).scrollTop()</code>]
* [http://stackoverflow.com/questions/19618545/body-scrolltop-vs-documentelement-scrolltop-vs-window-pagyoffset-vs-window-scrol body.scrollTop vs documentElement.scrollTop vs window.pagYOffset vs window.scrollY]
===== Find center of viewport =====
* [http://stackoverflow.com/questions/23453613/to-find-center-of-the-viewport-and-store-it-in-variables to find center of the viewport and store it in variables]
* [http://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen Using jQuery to center a DIV on the screen]
==== Set viewport position ====
* [https://www.w3schools.com/jsref/met_win_scrollto.asp Window scrollTo() Method]
* [https://www.w3schools.com/jsref/met_win_scrollby.asp 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 [[#Save and reset the viewport position relative to its topmost element|above]].
===== Talk-through 1 =====
{{Further|Pseudocode}}
Maybe this approach would work:
# We can get the y-offset for the top of the viewport with [https://www.w3schools.com/jsref/prop_win_pagexoffset.asp window.pageYOffset]
# We can get the y-offset for the bottom of the viewport with [https://www.w3schools.com/jsref/prop_win_pagexoffset.asp window.pageYOffset] + [https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight window.innerHeight]
# ''[http://stackoverflow.com/questions/5598743/finding-elements-position-relative-to-the-document this]'' explains how to get the position of a particular element
# 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
# Then we can loop through all those elements comparing their position with that of the viewport
# Once that is done, we should know the topmost element inside the viewport. Record that into a variable.
# Then that variable is used to get a y-offset after annotations have been hidden/reshown.
# Use that offset to reposition the viewport using [https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop scrollTop]
===== Talk-through 2 =====
{{Further|Pseudocode}}
Put another way:
# 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:
## Declare variable targetElement
## Determine the position of the top of the viewport; viewportOffset
## Declare the variable offsetDifference (the distance between targetElement and the top of the viewport), and set it to an initial value of 10,000
## Make list of all elements on page: someElement
## Do a for loop on the someElement list
### Determine element's position
### If the element is within the viewport
#### And if that element is closer to the top than the last element
##### Set targetElement = that element
# After annotations are hidden or shown...
# 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'm stumped: How do you save a ___location in the viewport to reposition the viewport later?]]:
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.
*If an element is above the viewport, [https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect getBoundingClientRect] will have a negative value for <code>bottom</code>
*The total height of an element can be obtained by the jQuery [http://api.jquery.com/outerheight/ .outerHeight(true)] method
*The window can be scrolled using [https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy window.scrollBy()]
In code, this would be something like the following
<syntaxhighlight lang="javascript">
//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);
</syntaxhighlight>
- <u>'''[[User:Evad37|Evad]]''37'''''</u> <span style="font-size:95%;">[[[d:w:User talk:Evad37|talk]]]</span> 05:06, 28 May 2017 (UTC)
: This looks way more efficient than [[User_talk:The_Transhumanist/anno.js#A_possible_solution|the approach I've been working on above]]. Thank you. I'll see what I can do with it. [[User talk:The Transhumanist|<i>The Transhumanist</i>]] 23:38, 3 June 2017 (UTC)
==== Complication ====
{{ping|Evad37}} I inserted the code that you provided (above) into [[User:The Transhumanist/anno.js|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:
<syntaxhighlight lang="javascript">
// 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' );
</syntaxhighlight>
Maybe this problem could be fixed with the [https://www.w3schools.com/jsref/met_win_scrollto.asp 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 <code>y = window.scrollY;
</code> and <code>window.scrollTo(0, y);</code>, but it is not working for some reason. I placed <code>var y;</code> 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, [[User talk:The Transhumanist|<i>The Transhumanist</i>]] 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
<syntaxhighlight lang="javascript">
// 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();
} );
} );
</syntaxhighlight>
And remove the portlet creation/removal code from within annoHide and annoShow. - <u>'''[[User:Evad37|Evad]]''37'''''</u> <span style="font-size:95%;">[[[d:w:User talk:Evad37|talk]]]</span> 02:32, 9 July 2017 (UTC)
=== Find/verify non-li list-lead entries ===
=== Fix annotation delimiters (to ndashes) ===
See [[User:GregU/dashes.js]].
= Discussions =
Post new discussion threads below.
== The Bug Report ==
Hi, {{ping|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.
<syntaxhighlight lang="JavaScript>
cont.outerHTML = cont.outerHTML.replace(/(<li>.*?)( –.*)/g,'$1<span class="anno">$2</span>');
</syntaxhighlight>
This code strips action handlers from DOM elements which are descendants of <code>mw-content-text</code>. This notably affects 'buttons', such as the 'show/hide' button in the following templates:
{{collapse top}}
Peekaboo.
{{collapse bottom}}
{{Fragaria|state=expanded}}
You ''might'' be able to prevent this by iterating through <code><li></code> elements, like so:
<syntaxhighlight lang="JavaScript">
$("#mw-content-text li").each(function()
{
$(this).html($(this).html().replace(/(.*?)( –.*)/g,'$1<span class="anno">$2</span>'));
});
</syntaxhighlight>
Let me know if this helps! Regards, <span style="font-family:Times New Roman">[[User:Guywan|''GUYWAN'']] ( [[User talk:Guywan|''t'']] · [[Special:Contributions/Guywan|''c'']] )</span> 12:20, 6 June 2019 (UTC)
|