My Function library

enter something useful

当前为 2015-12-10 提交的版本,查看 最新版本

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

  1. "use strict";
  2. //// ==UserScript==
  3. // @name My Function library
  4. // @namespace http://use.i.E.your.homepage/
  5. // @version 0.30
  6. // @description enter something useful
  7. // @grant GM_getValue
  8. // @grant GM_setValue
  9. // @grant GM_deleteValue
  10. // @run-at document-start
  11.  
  12. // @created 2015-04-06
  13. // @released 2014-00-00
  14. // @updated 2015-12-10
  15. // @history @version 0.25 - first version: public@released - 2015-04-12
  16. // @history @version 0.30 - first version: public@released - 2015-12-10
  17. // @compatible Greasemonkey, Tampermonkey
  18. // @license GNU GPL v3 (http://www.gnu.org/copyleft/gpl.html)
  19. // @copyright 2014+, Magnus Fohlström
  20. // ==/UserScript==
  21.  
  22. /*global $, jQuery*/
  23. /*jshint -W014, -W030, -W082*/
  24. // -W014, laxbreak, Bad line breaking before '+'
  25. // -W030, Expected assignment or function call instead saw an expression
  26. // -W082, a function declaration inside a block statement
  27.  
  28. window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
  29. console.debug('Error: ' + errorMsg + '\nScript: ' + url + '\nLine: ' + lineNumber
  30. + '\nColumn: ' + column + '\nStackTrace: ' + errorObj);
  31. };
  32. /**
  33. * @namespace waitUntilExists_Intervals
  34. */
  35. $.fn.waitUntilExists = function (handler, shouldRunHandlerOnce, isChild){
  36. var found = 'found',
  37. $this = $(this.selector),
  38. $elements = $this.not(function () { return $(this).data(found); }).each(handler).data(found, true);
  39. if( !isChild ) {
  40. (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] =
  41. window.setInterval(function () {
  42. $this.waitUntilExists(
  43. handler, shouldRunHandlerOnce, true);
  44. }, 500);
  45. }
  46. else if (shouldRunHandlerOnce && $elements.length){
  47. window.clearInterval(window.waitUntilExists_Intervals[this.selector]);
  48. }
  49. return $this;
  50. };
  51. $.fn.extend({
  52. exists : function(){
  53. return this.length === 0 ? 0 : this.length;
  54. },
  55. swapClass : function( replace, newClass ){
  56. this.className.replace(replace, newClass);
  57. },
  58. toggleClasses : function( add, remove, if_none ){
  59. var $this = $( this.selector );
  60. if_none !== undefined && !$this.hasClass( add ) && !$this.hasClass( remove ) && $this.addClass( if_none );
  61. $this.addClass( add ).removeClass( remove );
  62. },
  63. hasId : function( id ){
  64. return id === this.attr('id');
  65. },
  66. hasQuery : function( query ){
  67. return d.querySelector( query ).length;
  68. },
  69. isTag : function( tag ){
  70. var e = this[0] || $('<undefined/>');
  71. //noinspection JSValidateTypes
  72. return e.nodeName !== undefined && e.nodeName.toLowerCase() === tag.toLowerCase();
  73. },
  74. isNode : function( node ){
  75. var e = this[0] || $('<undefined/>');
  76. //noinspection JSValidateTypes
  77. return e.nodeName !== undefined && e.nodeName.toLowerCase() === node.toLowerCase();
  78. },
  79. attrs : function( search, type, chklen ){ //bool name value length or 1 2 3 4
  80. var attribs = this[0].attributes;
  81. c.i('attribs',attribs)
  82. if( arguments.length === 0 ) {
  83. var obj = {};
  84. $.each( attribs, function(){
  85. this.specified && ( obj[ this.name ] = this.value );
  86. });
  87. return obj;
  88. } else if( search != undefined ) {
  89. var name = '', val = '';
  90. $.each( attribs, function(){
  91. if( this.specified && type == 'length' ){
  92. if( this.name.length > chklen ){
  93. name = this.name;
  94. return false;
  95. }
  96. }
  97. else if( this.specified && this.name.inElem( search ) ){
  98. name = this.name;
  99. val = this.value;
  100. return false;
  101. }
  102. });
  103. return ( type == 'bool' || type == 1) ? name.length ? true : false :
  104. ( type == 'name' || type == 2) ? name :
  105. ( type == 'value' || type == 3) ? val :
  106. ( type == 'length' || type == 4) && name;
  107. }
  108. },
  109. findClass : function( Class ){
  110. return this.find('.' + Class )
  111. },
  112. href : function( newURL ){
  113. return arguments.length === 0 ? this.attr('href') : this.attr('href', newURL );
  114. }
  115. });
  116.  
  117.  
  118. $.extend({
  119. confirm: function (title, message, yesText, noText, yesCallback) {
  120. //dialog needs jQueryUI
  121. $("<div></div>").dialog( {
  122. buttons: [{
  123. text: yesText,
  124. click: function() {
  125. yesCallback();
  126. $( this ).remove();
  127. }
  128. },
  129. {
  130. text: noText,
  131. click: function() {
  132. $( this ).remove();
  133. }
  134. }
  135. ],
  136. close: function (event, ui) { $(this).remove(); },
  137. resizable: false,
  138. title: title,
  139. modal: true
  140. }).text(message).parent().addClass("alert");
  141. }
  142. });
  143. $.extend($.expr[':'], {
  144. isEmptyTrimmed: function(el){
  145. return !$.trim($(el).html());
  146. }
  147. });
  148.  
  149. /*
  150. $.confirm(
  151. "CONFIRM", //title
  152. "Delete " + filename + "?", //message
  153. "Delete", //button text
  154. deleteOk //"yes" callback
  155. );
  156. */
  157.  
  158. //ScrollZoomTune("div.thumb .title a",1,-25,1,'slow');
  159. function ScrollZoomTune(selection, zooms, tune, ani, speed){
  160. var body = $('body'), sel = $( selection), position;
  161. //noinspection JSValidateTypes
  162. sel.size() !== 0 && (
  163. body.css('zoom',zooms),
  164. position = sel.position().top + tune,
  165. ani === 1 ?
  166. body.animate({ scrollTop: position * zooms }, speed ) :
  167. body.scrollTop( position * zooms )
  168. );
  169. }
  170.  
  171. function inURL( search ){
  172. var winLoc = window.location.href;
  173. return winLoc.search(search) !== -1;
  174. }
  175.  
  176. function loadDoc( href ){
  177. $(location).attr('href', href );
  178. }
  179.  
  180. function checkDividedIsInteger( num, div ){
  181. return ( num % div === 0 );
  182. }
  183.  
  184. function isEven( value ){
  185. return ( value % 2 === 0 );
  186. }
  187.  
  188. function fn_arrayElemExistsInDom( array ) {
  189. var found = false;
  190. jQuery.each( array, function( i, value ) {
  191. $( value ).length && ( found = true );
  192. });
  193. return found;
  194. }
  195.  
  196. function toggleClassState( config, Class, state, elem ){
  197. config[ Class ] = typeof state === 'string' ? !config[ Class ] : state;
  198. $( elem || 'html' )[ config[ Class ] ? 'addClass' : 'removeClass' ]( Class );
  199. }
  200.  
  201. function wrapWithTag( tag, text, selection ){
  202. var thisAttr = selection !== undefined && selection.startsWith('.') ? 'class' : selection.startsWith('#') && 'id',
  203. thisTag = $('<' + tag + '/>', { text: text });
  204. return thisAttr.length ? thisTag.attr( thisAttr, selection.splice( 1 ) ) : thisTag;
  205. }
  206.  
  207. // will return true if the value is a primitive value
  208. function isPrimitiveType( value ){
  209. switch ( typeof value ) {
  210. case 'string': case 'number': case 'boolean': case 'undefined': {
  211. return true;
  212. }
  213. case 'object': {
  214. return !value;
  215. }
  216. }
  217. return false;
  218. }
  219.  
  220. String.prototype.advSplit = function(chr,nbr) {
  221. var str = this.split(chr),
  222. strLen = str.length,
  223. chrLen = chr.length,
  224. newStr = ['',''],
  225. newArr = [];
  226.  
  227. $.each( str, function( index ) {
  228. newStr[ index < nbr ? 0 : 1 ] += str[ index ] + chr;
  229. });
  230.  
  231. $.each( newStr, function( index ) {
  232. newStr[ index ] = newStr[ index ].slice(0, - chrLen);
  233. newStr[ index ].length > 0 && newArr.push( newStr[ index] );
  234. });
  235.  
  236. return newArr;
  237. };
  238.  
  239. String.prototype.advSplitJoin = function(chr,nbr,ips) {
  240.  
  241. var str = this.split(chr),
  242. strLen = str.length,
  243. ipsLen = ips.length,
  244. newStr = '',
  245. newStrLen;
  246.  
  247. $.each( str, function( index ) {
  248. var add = index < strLen - 1 ? chr : '';
  249. newStr += index + 1 === nbr ? str[index] + ips : str[index] + add;
  250. });
  251.  
  252. newStrLen = newStr.length;
  253. newStr.slice( newStrLen - ipsLen ) === ips && ( newStr = newStr.slice( 0, newStrLen - ipsLen ) );
  254.  
  255. return newStr;
  256. };
  257.  
  258. String.prototype.lpad = function(padString, length) {
  259. var str = this;
  260. while ( str.length < length ) {
  261. str = padString + str; }
  262. return str;
  263. };
  264.  
  265. String.prototype.reduceWhiteSpace = function() {
  266. return this.replace(/\s+/g, ' ');
  267. };
  268.  
  269. String.prototype.formatString = function(){
  270. return this.toString()
  271. .split('!').join(' !').split('!;').join("!important;")
  272. .split(/\s+/g).join(' ')
  273. .split('{').join('{\n\t')
  274. .split('; ').join(';')
  275.  
  276. .split('( ').join('(')
  277. .split(' )').join(')')
  278.  
  279. .split(';').join(';\n\t')
  280. .split('*/').join('*/\n')
  281. .split(')*(').join(') * (')
  282. .split('}').join('}\n');
  283. };
  284.  
  285. String.prototype.inURL = function(){
  286. var winLoc = window.location.href;
  287. return winLoc.search(this) !== -1;
  288. };
  289.  
  290. String.prototype.inString = function(string){
  291. return string !== undefined ? string.search(this) !== -1 : false;
  292. };
  293.  
  294. String.prototype.inElem = function(search){
  295. return this !== undefined ? this.search(search) !== -1 : false;
  296. };
  297.  
  298. String.prototype.undef = function(replace){
  299. return this === undefined ? replace : this;
  300. };
  301.  
  302. String.prototype.extract = function( startChar, endChar, inside ){
  303. var str = this,
  304. startCharIndex = str.indexOf( startChar ),
  305. endCharIndex = str.indexOf( endChar );
  306.  
  307. str = ( inside === 'yes' || inside === 1 || inside === true || inside === 'inside' ) ?
  308. str.replace( startChar, '').replace( endChar, '') : str.substr( startCharIndex, endCharIndex);
  309.  
  310. return str;
  311. };
  312.  
  313. String.prototype.toLocation = function() {
  314. var a = document.createElement('a');
  315. a.href = this;
  316. return a;
  317. };
  318.  
  319. String.prototype.count = function( char, UpperCase ) {
  320. var numberOf = this.toString().match( new RegExp( char, ( UpperCase ? "gi" : "g" ) ) );
  321. return numberOf !== null ? numberOf.length : 0;
  322. };
  323.  
  324. String.prototype.startsWith = function( str ){
  325. return this.slice(0, str.length) == str;
  326. };
  327.  
  328. String.prototype.endsWith = function( str ){
  329. return this.slice(-str.length) == str;
  330. };
  331.  
  332. /*
  333. String.prototype.replaceAll = function( target, replacement ) {
  334. return this.split(target).join(replacement);
  335. };
  336. */
  337.  
  338. /**
  339. * @return {string}
  340. */
  341. function Undefined(check,replace){
  342. return check === undefined ? replace.toString() : check.toString();
  343. }
  344.  
  345. function GM_lister( remove ){
  346. var keys = GM_listValues();
  347. for (var i = 0, key = null; key = keys[i]; i++) {
  348. GM_listValues()[i] !== undefined && c.i('GM_ListItem: ' + GM_listValues()[i] + ':', GM_getValue(key));
  349. ( remove === true || remove === 'yes' || remove === 1 ) && GM_deleteValue(key);
  350. }
  351. }
  352.  
  353. function filterClick( e, $this ){
  354. return e.which == 1 && e.target == $this;
  355. }
  356.  
  357. function roundFloat(num,dec){
  358. var d = 1;
  359. for (var i=0; i<dec; i++){
  360. d += "0";
  361. }
  362. return Math.round(num * d) / d;
  363. }
  364.  
  365. function randomFloatBetween( min, max, dec ){
  366. dec = typeof( dec ) == 'undefined' ? 2 : dec;
  367. return parseFloat( Math.min( min + ( Math.random() * ( max - min ) ), max ).toFixed( dec ) );
  368. }
  369.  
  370. function refreshElement( elem , speed ){ //refreshElement('.videoPlayer','slow');
  371. var $elem = $( elem ), data = $elem.html();
  372. $elem.empty().html( data ).fadeIn( speed );
  373. }
  374.  
  375. function getGlobal(){
  376. return (function(){
  377. return this;
  378. })();
  379. }
  380.  
  381. //VideoTitleA("div.thumb .title a",'on');
  382. var VideoTitleA = function( elem , state ){
  383. $( elem ).each(function(){
  384. var $this = $(this),
  385. strTitle = $this.attr('title'),
  386. strText = $this.attr('data-text'),
  387. strHtml = $this.text();
  388. state === 'on' ? $this.text(strTitle).attr('data-text',strHtml) : $this.text(strText);
  389. });
  390. },
  391. isNumeric = function( value ){
  392. return /^\d+$/.test( value );
  393. },
  394. obj2Str = function( obj ){
  395. var objArr = $.makeArray(obj);
  396. return objArr[0].outerHTML;
  397. },
  398. /**
  399. * @return {string}
  400. */
  401. MultiString = function(f){
  402. return f.toString().split('\n').slice(1, -1).join('\n');
  403. },
  404. w = window,
  405. glob = w,
  406. $w = $(w),
  407. $l = window.location,
  408. locDoc = window.location.href,
  409. d = document,
  410. $d = $(d),
  411. c = {
  412. defaultState: 3,
  413. cute : function( type, msg, color ) {
  414. color = color || "black";
  415. var newColor, bgc = "White";
  416. switch ( color ) {
  417. case "success": newColor = "Green"; bgc = "LimeGreen"; break;
  418. case "info": newColor = "DodgerBlue"; bgc = "Turquoise"; break;
  419. case "error": newColor = "Red"; bgc = "Black"; break;
  420. case "start": newColor = "OliveDrab"; bgc = "PaleGreen"; break;
  421. case "warning": newColor = "Tomato"; bgc = "Black"; break;
  422. case "end": newColor = "Orchid"; bgc = "MediumVioletRed"; break;
  423. default: //noinspection SillyAssignmentJS
  424. newColor = color;
  425. }
  426.  
  427. typeof msg == "object" ?
  428. window.console[ type ]( msg )
  429. : typeof color == "object" ? (
  430. window.console[ type ]("%c" + msg, "color: PowderBlue;font-weight:bold; background-color: RoyalBlue;"),
  431. window.console[ type ]( newColor )
  432. ):
  433. window.console[ type ]("%c" + msg, "color:" + newColor + "; background-color: " + bgc + ";")
  434. },
  435. show: function( showThis, type ){
  436. var State = GM_getValue( type + 'StateValue' ) || this.defaultState;
  437. return showThis !== 0 && State !== 0 && State === ( showThis || State ) || State === 'all';
  438. },
  439. pre: function( type, name, fn, line, color ){
  440. line = line == undefined ? '' : line + ': ';
  441. var Fn = function(){ return fn !== undefined ? fn : ''; };
  442. typeof fn == "object" ?
  443. window.console[ type ]( name, Fn() ) : c.cute( type, line + name + ': ' + Fn(), color );
  444. },
  445. l: function( name, fn, line, color, showThis ){
  446. var type = 'log';
  447. this.show( showThis, type ) && this.pre( type, name, fn, line, color );
  448. },
  449. h: function( name, fn, line, color, showThis ){
  450. var type = 'handled';
  451. this.show( showThis, type ) && this.pre( type, name, fn, line, color );
  452. },
  453. //c.l('name', 'fn'=='fn', 'line', 'blue')
  454. i: function( name, fn, line, color, showThis ){
  455. var type = 'info';
  456. this.show( showThis, type ) && this.pre( type, name, fn, line, color );
  457. },
  458. d: function( name, fn, line, color, showThis ){
  459. var type = 'debug';
  460. this.show( showThis, type ) && this.pre( type, name, fn, line, color );
  461. }
  462. },
  463. advTimer = {
  464. start : function( name, ms ){
  465. advTimer[name] = ms;
  466. setTimeout(function(){ advTimer[name] = 0; }, ms );
  467. },
  468. check : function( name ){
  469. advTimer[name] || ( advTimer[name] = 0 );
  470. return advTimer[name];
  471. },
  472. stop : function( name ){
  473. advTimer[name] = 0;
  474. }
  475. },
  476. g = {
  477. locDoc : window.location.href,
  478. ms : 0,
  479. timer : function(ms){
  480. g.ms = ms;
  481. setTimeout(function(){ g.ms = 0; },ms);
  482. },
  483. lap : {
  484. data : {},
  485. tid : function(){ return performance.now(); },
  486. set : function(name){ this.data[name] = this.tid(); },
  487. get : function(name){ this.print(name); },
  488. end : function(name){ this.print(name); this.del(name); },
  489. del : function(name){ delete this.data[name]; },
  490. print: function(name){ c.i( name, this.tid() - this.data[name] + 'ms'); }
  491. },
  492. GM : {
  493. engine : function( mode, val, range ){
  494. switch (mode){
  495. case 'set': GM_setValue( val.name, val.default );
  496. break;
  497. case 'get': range ? config[ val.name ] = GM_getValue( val.name ):
  498. ui.config[ val.name ] = GM_getValue( val.name );
  499. break;
  500. case 'del': GM_deleteValue( val.name );
  501. }
  502. },
  503. manager : function( mode, array, range ){
  504. $.each( array, function( i, val ){ this.engine( mode, val, range === undefined ); });
  505. mode === 'del' && ( GM_deleteValue( 'firstRun' ), GM_deleteValue( 'yourVer' ) );
  506. }
  507. }
  508. },
  509. testPerformance = function(name, fn, testCycles ) {
  510. g.lap.set( name );
  511. var i = 0;
  512. for ( i ; i < testCycles; i++ ){
  513. fn;
  514. }
  515. g.lap.end( name );
  516. };
  517.  
  518. var perf = function (testName, fn) {
  519. var startTime = new Date().getTime();
  520. fn();
  521. var endTime = new Date().getTime();
  522. console.log(testName + ": " + (endTime - startTime) + "ms");
  523. };
  524.  
  525. $(document).on('click','*',function(e){
  526. this == e.target && c.i('target:', e.target ); });
  527.  
  528. c.i('my Function Library ö');
  529. /*
  530. isScrolledIntoView = (elem) ->
  531. docViewTop = $(window).scrollTop()
  532. docViewBottom = docViewTop + $(window).height()
  533. elemTop = $(elem).offset().top
  534. elemBottom = elemTop + $(elem).height()
  535.  
  536. (elemBottom - 200 < docViewBottom) and (elemBottom + $(elem).height() > docViewBottom )
  537. */