ProgressBar

Create and manage simple progress bars, minimal JavaScript

当前为 2019-10-19 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/391236/742150/ProgressBar.js

  1. // ProgressBar library
  2. //
  3. // Create and manage simple progress bars. CSS, minimal JavaScript.
  4. //
  5. // https://greasyfork.org/scripts/391236-progressbar
  6. // Copyright (C) 2019, Guido Villa
  7. // Original version of the script is taken from IMDb 'My Movies' enhancer:
  8. // Copyright (C) 2008-2018, Ricardo Mendonça Ferreira (ric@mpcnet.com.br)
  9. // Released under the GPL license - http://www.gnu.org/copyleft/gpl.html
  10. //
  11. // For instructions on user scripts, see:
  12. // https://greasyfork.org/help/installing-user-scripts
  13. //
  14. // To use this library in a userscript you must add to script header:
  15. // @require https://greasyfork.org/scripts/391236-progressbar/code/ProgressBar.js
  16. // @grant GM_addStyle
  17. //
  18. // --------------------------------------------------------------------
  19. //
  20. // ==UserScript==
  21. // @namespace https://greasyfork.org/users/373199-guido-villa
  22. // @exclude *
  23. //
  24. // ==UserLibrary==
  25. // @name ProgressBar
  26. // @description Create and manage simple progress bars, minimal JavaScript
  27. // @version 1.1
  28. // @author guidovilla
  29. // @date 19.10.2019
  30. // @copyright 2019, Guido Villa (https://greasyfork.org/users/373199-guido-villa)
  31. // @license GPL-3.0-or-later
  32. // @homepageURL https://greasyfork.org/scripts/391236-progressbar
  33. // @supportURL https://gitlab.com/gv-browser/userscripts/issues
  34. // @contributionURL https://tinyurl.com/gv-donate-2e
  35. // ==/UserScript==
  36. //
  37. // ==/UserLibrary==
  38. //
  39. // --------------------------------------------------------------------
  40. //
  41. // To-do (priority: [H]igh, [M]edium, [L]ow):
  42. // - [H] width must be an integer multiple of background-size, otherwise animation will skip => address
  43. // - [M] speed of the animation depends on width => fix?
  44. // - [m] speed of transition is not constant (time is constant, regardless of the "space" to be travelled) => can it be fixed?
  45. // - [H] wrap in order to hide global variables
  46. // - [M] nicer presentation style (maybe small vertical bars), graphical improvements
  47. // - [M] different styles
  48. // - [M] log if current > finish?
  49. // - [M] handle case finish == 0
  50. //
  51. // Changelog:
  52. // ----------
  53. // 2019.10.19 [1.1] Add possibility to update finish value
  54. // Change default value for "current" parameter in update()
  55. // 2019.10.16 [1.0] First version
  56. // 2019.10.14 [0.1] First test version, private use only
  57. //
  58.  
  59. /* jshint esversion: 6, supernew: true, laxbreak: true */
  60. /* exported EL, Library_Version_PROGRESSBAR */
  61.  
  62. const Library_Version_PROGRESSBAR = '1.1';
  63.  
  64. /* How to use the library
  65.  
  66. - Create a new progress bar:
  67. var pb = new ProgressBar(...)
  68.  
  69. - Change the progress:
  70. pb.update(...)
  71. pb.advance(...)
  72.  
  73. - Remove the progress bar:
  74. pb.close()
  75.  
  76. Details
  77. Progress bars are defined by three main parameters:
  78. - finish: value that defines what is 100%
  79. this is set at creation time and can be changed with update()
  80. - progress: value that defines current completion status (must be <= finish)
  81. initial progress is set a creation time, then it can be updated
  82. with update() and advance()
  83. When progress = -1, the bar shows an indeterminate progress
  84. - message: the message printed inside the bar (e.g. "Loading...")
  85. initial message is set a creation time, then it can be changed
  86. with update() and advance().
  87. The message can contain a few placeholders that are replaced with
  88. actual progress data:
  89. - {#}: replace with current progress number
  90. - {$}: replace with finish value
  91. - {%}: replace with completion percentage (= 100*progress/finish)
  92. E.g.: "Loading {#} of {$}..." => "Loading 7 of 23..."
  93.  
  94. All numbers are integers.
  95.  
  96. Information for changing styles:
  97. The HTML id of the container DIV can be accessed through the 'id' property
  98. of the progress bar object.
  99. All elements that constitute the bar have a generic "pb-progress-bar" class and
  100. a specific "pb-progress-bar-XXX" class different for each element.
  101. Indeterminate progress style is enabled by applying a "pb-indeterminate" class
  102. to the container DIV.
  103.  
  104. Parameters (all parameters are optional):
  105.  
  106. - ProgressBar(finish, msg, options)
  107. Create a new progress bar. Parameters:
  108. - finish: maximum value that can be reached (default is 100)
  109. - msg: message written in the bar, see above for substitutions
  110. default is "Loading {#}/{$}..."
  111. - options: an object that may contain:
  112. - id: HTML id of container DIV (default: autogenerated)
  113. - start: initial progress status (default is 0, i.e. the beginning)
  114. - container: positioned element where the bar will be centered
  115. null (the default): center bar on the screen
  116. - width: width in pixels of the progress bar (default is 226.3)
  117. - height: height in pixels of the progress bar (default is 30)
  118.  
  119. - update(progress, msg, finish)
  120. Optionally update parameters of the progress bar. Only non-undefined,
  121. non-null parameters are changed.
  122.  
  123. - advance(value, msg)
  124. Increment the progress bar status. Parameters:
  125. - value: the increment value, can be negative (default is 1)
  126. - msg: an optional new message (default is: don't change message)
  127.  
  128. - close()
  129. Close the progress bar and remove it from the DOM.
  130.  
  131. */
  132.  
  133.  
  134. var progress_bar_style_has_been_loaded = false;
  135. var progress_bar_index = 0;
  136. // Create progress bar
  137. // eslint-disable-next-line max-statements
  138. function ProgressBar(finish = 100, msg = 'Loading {#}/{$}...', options) {
  139. // style definition
  140. var STYLE = '.pb-progress-bar.pb-progress-bar-box{border:2px solid black;background-color:white;padding:4px;outline:white solid 6px;}'
  141. + '.pb-progress-bar.pb-progress-bar-bar{background-color:green;height:100%;transition:width 300ms linear;}'
  142. + '.pb-progress-bar.pb-progress-bar-txtcont{position:absolute;top:0;left:0;width:100%;height:100%;display:table;}'
  143. + '.pb-progress-bar.pb-progress-bar-txt{display:table-cell;text-align:center;vertical-align:middle;font:16px verdana,sans-serif;color:black;}'
  144. + '.pb-progress-bar.pb-progress-bar-box.pb-indeterminate{background:repeating-linear-gradient(-45deg,#F0F0F0 0 20px,#ccc 20px 40px);background-size:56.56854px;animation:2s linear infinite loading;}'
  145. + '.pb-progress-bar.pb-progress-bar-box.pb-indeterminate .pb-progress-bar-bar{background-color:transparent;transition:none}'
  146. + '@keyframes loading{from{background-position-x:0%;} to{background-position-x:100%;}}';
  147. if (!progress_bar_style_has_been_loaded) {
  148. GM_addStyle(STYLE);
  149. progress_bar_style_has_been_loaded = true;
  150. }
  151.  
  152. var self = this;
  153.  
  154. // basic configuration
  155. this.id = 'pb-progress-bar-' + ++progress_bar_index; // 'id' is public
  156. var start = 0;
  157. var container = null;
  158. var width = 226.27417;
  159. var height = 30;
  160. var message = msg;
  161.  
  162. var current; // completion status of the progress bar
  163.  
  164. var pbBox, pb, pbTxtCont, pbTxt; // elements of the progress bar
  165.  
  166. // helper function to create the elements
  167. function createElement(father, elementType, className, id) {
  168. var elem = document.createElement(elementType);
  169. if (typeof id !== 'undefined') elem.id = id;
  170. elem.className = 'pb-progress-bar ' + className;
  171. father.appendChild(elem);
  172. return elem;
  173. }
  174.  
  175. // initialization function
  176. function init() {
  177. // check for options in the call
  178. if (options && typeof options === 'object') {
  179. if (typeof options.id !== 'undefined') self.id = options.id;
  180. if (typeof options.start !== 'undefined') start = options.start;
  181. if (typeof options.container !== 'undefined') container = options.container;
  182. if (typeof options.width !== 'undefined') width = options.width;
  183. if (typeof options.height !== 'undefined') height = options.height;
  184. }
  185.  
  186. // calculate positioning
  187. var containerWidth, containerHeight,
  188. cntElem,
  189. positioningStyle;
  190.  
  191. function setPositioningVars(cnt, pos, w, h) {
  192. containerWidth = w;
  193. containerHeight = h;
  194. cntElem = cnt;
  195. positioningStyle = pos;
  196. }
  197.  
  198. if (container) {
  199. var rect = container.getBoundingClientRect();
  200. setPositioningVars(container, 'absolute', rect.width, rect.height);
  201. } else {
  202. setPositioningVars(document.body, 'fixed', window.innerWidth, window.innerHeight);
  203. }
  204. var top = containerHeight / 2 - height / 2;
  205. var left = containerWidth / 2 - width / 2;
  206.  
  207. // create the elements
  208. pbBox = createElement(cntElem, 'div', 'pb-progress-bar-box', self.id);
  209. pbBox.style.cssText = 'position:' + positioningStyle
  210. + '; height:' + height + 'px;width:' + width
  211. + 'px;top:' + top + 'px;left:' + left + 'px;';
  212.  
  213. pb = createElement(pbBox, 'div', 'pb-progress-bar-bar');
  214. pbTxtCont = createElement(pbBox, 'div', 'pb-progress-bar-txtcont');
  215. pbTxt = createElement(pbTxtCont, 'div', 'pb-progress-bar-txt');
  216.  
  217. // set the initial progress
  218. self.update(start);
  219. }
  220.  
  221.  
  222. /* PUBLIC members */
  223.  
  224. // optionally update progress status, message, finish
  225. this.update = function(currentVal, newMsg, newFinish) {
  226. if (newMsg) message = newMsg;
  227. if (typeof newFinish !== 'undefined' && newFinish !== null) finish = newFinish;
  228. var newVal;
  229. if (typeof currentVal !== 'undefined' && currentVal !== null) newVal = currentVal;
  230. else newVal = current;
  231. if (newVal > finish) newVal = finish;
  232.  
  233. if (newVal < 0) {
  234. // setting the width to zero is not really needed, but ensures a
  235. // more consistent behaviour in cases where the delay (see
  236. // below) is not enough.
  237. pb.style.width = '0';
  238. // try to make the message better for indeterminate progress
  239. pbTxt.textContent = message
  240. .replace(/ *{#}.*{\$} */g, '')
  241. .replace(/ *{#} */g, '')
  242. .replace(/ *{\$} */g, '')
  243. .replace(/ *{%} *%? */g, '');
  244. pbBox.classList.add('pb-indeterminate');
  245. } else {
  246. pb.style.width = (100*newVal/finish) + '%';
  247. if (current < 0) {
  248. // if exiting from indeterminate progress a small delay is
  249. // needed, otherwise the class may be removed when changing
  250. // the width, and the width transition takes place anyway
  251. setTimeout(function() {
  252. pbBox.classList.remove('pb-indeterminate');
  253. }, 33);
  254. } else {
  255. pbBox.classList.remove('pb-indeterminate');
  256. }
  257. // replace placeholders with actual numbers
  258. pbTxt.textContent = message
  259. .replace(/{#}/g, newVal)
  260. .replace(/{\$}/g, finish)
  261. .replace(/{%}/g, Math.round(100*newVal/finish));
  262. }
  263. current = newVal;
  264. };
  265.  
  266.  
  267. // advance the progress by "value" and optionally change the message
  268. this.advance = function(value = 1, newMsg) {
  269. self.update(current + value, newMsg);
  270. };
  271.  
  272.  
  273. // close/remove the progress bar
  274. this.close = function() {
  275. pbBox.parentNode.removeChild(pbBox);
  276. };
  277.  
  278.  
  279. /* INITIALIZATION */
  280. init();
  281. }