Include Tools

Общие инструменты для всех страничек

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

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

  1. // ==UserScript==
  2. // @name Include Tools
  3. // @namespace scriptomatika
  4. // @author mouse-karaganda
  5. // @description Общие инструменты для всех страничек
  6. // @version 1.27
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. var paramWindow = (typeof unsafeWindow === 'object') ? unsafeWindow : window;
  11.  
  12. (function(unsafeWindow) {
  13. var console = unsafeWindow.console;
  14. var jQuery = unsafeWindow.jQuery;
  15.  
  16. unsafeWindow.__krokodil = {
  17. /**
  18. * Отрисовывает элемент
  19. */
  20. renderElement: function(config) {
  21. // Определяем параметры по умолчанию
  22. var newRenderType = this.setRenderType(config.renderType);
  23. var newConfig = {
  24. // ~~~ название тега ~~~ //
  25. tagName: config.tagName || 'div',
  26. // ~~~ атрибуты тега ~~~ //
  27. attr: config.attr || {},
  28. // ~~~ идентификатор ~~~ //
  29. id: config.id,
  30. // ~~~ имя класса ~~~ //
  31. cls: config.cls,
  32. // ~~~ встроенные стили тега ~~~ //
  33. style: config.style || {},
  34. // ~~~ встроенные данные ~~~ //
  35. dataset: config.dataset || {},
  36. // ~~~ содержимое элемента ~~~ //
  37. innerHTML: this.join(config.innerHTML || ''),
  38. // ~~~ обработчики событий элемента ~~~ //
  39. listeners: config.listeners || {},
  40. // ~~~ родительский элемент для нового ~~~ //
  41. renderTo: this.getIf(config.renderTo),
  42. // ~~~ способ отрисовки: append (по умолчанию), insertBefore, insertAfter, insertFirst, none ~~~ //
  43. renderType: newRenderType
  44. };
  45. var newElement;
  46. if (newConfig.tagName == 'text') {
  47. // Создаем текстовый узел
  48. newElement = document.createTextNode(newConfig.innerHTML);
  49. } else {
  50. // Создаем элемент
  51. newElement = document.createElement(newConfig.tagName);
  52. // Добавляем атрибуты
  53. this.attr(newElement, newConfig.attr);
  54. // Добавляем идентификатор, если указан
  55. if (newConfig.id) {
  56. this.attr(newElement, { 'id': newConfig.id });
  57. }
  58. //console.log('newElement == %o, config == %o, id == ', newElement, newConfig, newConfig.id);
  59. // Добавляем атрибут класса
  60. if (newConfig.cls) {
  61. this.attr(newElement, { 'class': newConfig.cls });
  62. }
  63. // Наполняем содержимым
  64. newElement.innerHTML = newConfig.innerHTML;
  65. // Задаем стиль
  66. this.css(newElement, newConfig.style);
  67. // Задаем встроенные данные
  68. this.extend(newElement.dataset, newConfig.dataset);
  69. // Навешиваем события
  70. var confListeners = newConfig.listeners;
  71. for (var ev in confListeners) {
  72. if (ev != 'scope') {
  73. //console.log('this.on(newElement == %o, ev == %o, newConfig.listeners[ev] == %o, newConfig.listeners.scope == %o)', newElement, ev, newConfig.listeners[ev], newConfig.listeners.scope);
  74. this.on(newElement, ev, newConfig.listeners[ev], newConfig.listeners.scope);
  75. }
  76. }
  77. //console.log('После: tag == %o, listeners == %o', newConfig.tagName, confListeners);
  78. }
  79. // Отрисовываем элемент
  80. var target, returnRender = true;
  81. while (returnRender) {
  82. switch (newConfig.renderType) {
  83. // Не отрисовывать, только создать
  84. case this.enumRenderType['none']: {
  85. returnRender = false;
  86. break;
  87. };
  88. // Вставить перед указанным
  89. case this.enumRenderType['insertBefore']: {
  90. target = newConfig.renderTo || document.body.firstChild;
  91. // если элемент не задан - вернемся к способу по умолчанию
  92. if (target) {
  93. target.parentNode.insertBefore(newElement, target);
  94. returnRender = false;
  95. } else {
  96. newConfig.renderType = this.enumRenderType['default'];
  97. }
  98. break;
  99. };
  100. // Вставить после указанного
  101. case this.enumRenderType['insertAfter']: {
  102. // если элемент не задан - вернемся к способу по умолчанию
  103. if (newConfig.renderTo && newConfig.renderTo.nextSibling) {
  104. target = newConfig.renderTo.nextSibling;
  105. target.parentNode.insertBefore(newElement, target);
  106. returnRender = false;
  107. } else {
  108. newConfig.renderType = this.enumRenderType['default'];
  109. }
  110. break;
  111. };
  112. // Вставить как первый дочерний
  113. case this.enumRenderType['prepend']: {
  114. // если элемент не задан - вернемся к способу по умолчанию
  115. if (newConfig.renderTo && newConfig.renderTo.firstChild) {
  116. target = newConfig.renderTo.firstChild;
  117. target.parentNode.insertBefore(newElement, target);
  118. returnRender = false;
  119. } else {
  120. newConfig.renderType = this.enumRenderType['default'];
  121. }
  122. break;
  123. };
  124. // Вставить как последний дочерний
  125. case this.enumRenderType['append']:
  126. default: {
  127. var parent = newConfig.renderTo || document.body;
  128. parent.appendChild(newElement);
  129. returnRender = false;
  130. };
  131. }
  132. }
  133. // Возвращаем элемент
  134. return newElement;
  135. },
  136. /**
  137. * Отрисовать несколько одинаковых элементов подряд
  138. */
  139. renderElements: function(count, config) {
  140. for (var k = 0; k < count; k++) {
  141. this.renderElement(config);
  142. }
  143. },
  144. /**
  145. * Отрисовать текстовый узел
  146. */
  147. renderText: function(config) {
  148. // Упрощенные настройки
  149. var newConfig = {
  150. tagName: 'text',
  151. innerHTML: config.text,
  152. renderTo: config.renderTo,
  153. renderType: config.renderType
  154. };
  155. var newElement = this.renderElement(newConfig);
  156. return newElement;
  157. },
  158. /**
  159. * Отрисовать элемент style
  160. * @param {String} text Любое количество строк через запятую
  161. */
  162. renderStyle: function(text) {
  163. var stringSet = arguments;
  164. var tag = this.renderElement({
  165. tagName: 'style',
  166. attr: { type: 'text/css' },
  167. innerHTML: this.format('\n\t{0}\n', this.join(stringSet, '\n\t'))
  168. });
  169. return tag;
  170. },
  171. /**
  172. * Возможные способы отрисовки
  173. */
  174. enumRenderType: {
  175. 'append': 0,
  176. 'prepend': 1,
  177. 'insertBefore': 2,
  178. 'insertAfter': 3,
  179. 'none': 4,
  180. 'default': 0
  181. },
  182. // Назначает способ отрисовки
  183. setRenderType: function(renderType) {
  184. if (typeof renderType != 'string') {
  185. return this.enumRenderType['default'];
  186. }
  187. if (this.enumRenderType[renderType] == undefined) {
  188. return this.enumRenderType['default'];
  189. }
  190. return this.enumRenderType[renderType];
  191. },
  192. /**
  193. * Карта кодов клавиш
  194. */
  195. keyMap: {
  196. // Клавиши со стрелками
  197. arrowLeft: 37,
  198. arrowUp: 38,
  199. arrowRight: 39,
  200. arrowDown: 40
  201. },
  202. /**
  203. * Карта кодов символов
  204. */
  205. charMap: {
  206. arrowLeft: 8592, // ←
  207. arrowRight: 8594 // →
  208. },
  209. /**
  210. * Ждём, пока отрисуется элемент, и выполняем действия
  211. * @param {String} selector css-селектор для поиска элемента (строго строка)
  212. * @param {Function} callback Функция, выполняющая действия над элементом. this внутри неё — искомый DOM-узел
  213. * @param {Number} maxIterCount Максимальное количество попыток найти элемент
  214. */
  215. missingElement: function(selector, callback, maxIterCount) {
  216. var setLog = false;
  217. // Итерации 5 раз в секунду
  218. var missingOne = 100;
  219. // Ограничим количество попыток разумными пределами
  220. var defaultCount = 3000;
  221. if (!this.isNumber(maxIterCount)) {
  222. maxIterCount = defaultCount;
  223. }
  224. if (0 > maxIterCount || maxIterCount > defaultCount) {
  225. maxIterCount = defaultCount;
  226. }
  227. // Запускаем таймер на поиск
  228. var iterCount = 0;
  229. var elementTimer = setInterval(this.createDelegate(function() {
  230. // Сообщение об ожидании
  231. var secondsMsg = this.numberWithCase(iterCount, 'секунду', 'секунды', 'секунд');
  232. if (iterCount % 10 == 0) {
  233. if (setLog) console.log('missing: Ждём [%o] %s', selector, secondsMsg);
  234. }
  235. var element = this.getAll(selector);
  236. // Определим, что вышел элемент
  237. var elementStop = !!element;
  238. // Определим, что кончилось количество попыток
  239. var iterStop = (iterCount >= maxIterCount);
  240. if (elementStop || iterStop) {
  241. clearInterval(elementTimer);
  242. var elementExists = true;
  243. // Если элемент так и не появился
  244. if (!elementStop && iterStop) {
  245. if (setLog) console.log('missing: Закончились попытки [%o]', selector);
  246. elementExists = false;
  247. return;
  248. }
  249. // Появился элемент - выполняем действия
  250. if (setLog) console.log('missing: Появился элемент [%o] == %o', selector, element);
  251. if (this.isFunction(callback)) {
  252. if (this.isIterable(element) && (element.length == 1)) {
  253. element = element[0];
  254. }
  255. callback.call(element, elementExists);
  256. }
  257. }
  258. iterCount++;
  259. }, this), missingOne);
  260. },
  261. /**
  262. * Добавить свойства в объект
  263. */
  264. extend: function(target, newProperties) {
  265. if (typeof newProperties == 'object') {
  266. for (var i in newProperties) {
  267. target[i] = newProperties[i];
  268. }
  269. }
  270. return target;
  271. },
  272. /**
  273. * Создать класс-наследник от базового класса или объекта
  274. */
  275. inherit: function(base, newConfig) {
  276. var newProto = (typeof base == 'function') ? new base() : this.extend({}, base);
  277. this.extend(newProto, newConfig);
  278. return function() {
  279. var F = function() {};
  280. F.prototype = newProto;
  281. return new F();
  282. };
  283. },
  284. /**
  285. * Получить элемент по селектору
  286. */
  287. get: function(selector, parent) {
  288. parent = this.getIf(parent);
  289. return (parent || unsafeWindow.document).querySelector(selector);
  290. },
  291. /**
  292. * Получить массив элементов по селектору
  293. */
  294. getAll: function(selector, parent) {
  295. parent = this.getIf(parent);
  296. return (parent || unsafeWindow.document).querySelectorAll(selector);
  297. },
  298. /**
  299. * Получить элемент, если задан элемент или селектор
  300. */
  301. getIf: function(element) {
  302. return this.isString(element) ? this.get(element) : element;
  303. },
  304. /**
  305. * Получить массив элементов, если задан массив элементов или селектор
  306. */
  307. getIfAll: function(elements) {
  308. return this.isString(elements) ? this.getAll(elements) : this.toIterable(elements);
  309. },
  310. /**
  311. * Назначим атрибуты элементу или извлечем их
  312. */
  313. attr: function(element, attributes) {
  314. var nativeEl = this.getIf(element);
  315. if (typeof attributes == 'string') {
  316. // извлечем атрибут
  317. var result = '';
  318. if (nativeEl.getAttribute) {
  319. result = nativeEl.getAttribute(attributes);
  320. }
  321. if (!result) {
  322. result = '';
  323. }
  324. return result;
  325. } else if (typeof attributes == 'object') {
  326. // назначим атрибуты всем элементам по селектору
  327. nativeEl = this.getIfAll(element);
  328. for (var i = 0; i < nativeEl.length; i++) {
  329. // назначим атрибуты из списка
  330. for (var at in attributes) {
  331. try {
  332. if (attributes[at] == '') {
  333. // Удалим пустой атрибут
  334. nativeEl[i].removeAttribute(at);
  335. } else {
  336. // Запишем осмысленный атрибут
  337. nativeEl[i].setAttribute(at, attributes[at]);
  338. }
  339. } catch (e) {
  340. console.error(e);
  341. }
  342. }
  343. }
  344. }
  345. },
  346. /**
  347. * Назначим стили элементу или извлечем их
  348. */
  349. css: function(element, properties) {
  350. var nativeEl = this.getIf(element);
  351. if (typeof properties == 'string') {
  352. // извлечем стиль
  353. var result = '';
  354. if (nativeEl.style) {
  355. var calcStyle = window.getComputedStyle(nativeEl, null) || nativeEl.currentStyle;
  356. result = calcStyle[properties];
  357. }
  358. if (!result) {
  359. result = '';
  360. }
  361. return result;
  362. } else if (typeof properties == 'object') {
  363. // присвоим стили всем элементам по селектору
  364. nativeEl = this.getIfAll(element);
  365. try {
  366. for (var i = 0; i < nativeEl.length; i++) {
  367. // назначим стили из списка
  368. this.extend(nativeEl[i].style, properties);
  369. }
  370. } catch (e) {
  371. console.error(e);
  372. }
  373. }
  374. },
  375. /**
  376. * Показать элемент
  377. */
  378. show: function(element, inline) {
  379. var current = this.getIf(element);
  380. if (current) {
  381. var style = current.style;
  382. style.display = inline ? 'inline' : 'block';
  383. }
  384. },
  385. /**
  386. * Спрятать элемент
  387. */
  388. hide: function(element, soft) {
  389. var current = this.getIf(element);
  390. if (current) {
  391. if (!!soft) {
  392. current.style.visibility = 'hidden';
  393. } else {
  394. current.style.display = 'none';
  395. }
  396. }
  397. },
  398. /**
  399. * Спрятать элемент, убрав его за границу экрана
  400. */
  401. hideFixed: function(element) {
  402. var current = this.getIf(element);
  403. if (current) {
  404. this.css(current, {
  405. position: 'fixed',
  406. left: '-2000px',
  407. top: '-2000px'
  408. });
  409. }
  410. },
  411. /**
  412. * Удалить элемент
  413. */
  414. del: function(element) {
  415. var current = this.getIf(element);
  416. if (current && current.parentNode) {
  417. current.parentNode.removeChild(current);
  418. }
  419. },
  420. /**
  421. * Изменить видимость элемента
  422. */
  423. toggle: function(element, inline) {
  424. this.isVisible(element) ? this.hide(element) : this.show(element, inline);
  425. },
  426. /**
  427. * Проверить, виден ли элемент
  428. */
  429. isVisible: function(element) {
  430. return this.getIf(element).style.display != 'none';
  431. },
  432. /**
  433. * Навесить обработчик
  434. */
  435. on: function(element, eventType, handler, scope) {
  436. var elements;
  437. if (!element) {
  438. return false;
  439. }
  440. if (this.isString(element)) {
  441. element = this.getIfAll(element);
  442. if (!(element && this.isIterable(element)))
  443. return false;
  444. }
  445. if (!this.isIterable(element)) {
  446. element = this.toIterable(element);
  447. }
  448. var eventHandler = handler;
  449. if (scope) {
  450. eventHandler = this.createDelegate(handler, scope, handler.arguments);
  451. }
  452. this.each(element, function(currentEl) {
  453. if (currentEl.addEventListener) {
  454. currentEl.addEventListener(eventType, eventHandler, false);
  455. }
  456. else if (currentEl.attachEvent) {
  457. currentEl.attachEvent('on' + eventType, eventHandler);
  458. }
  459. }, this);
  460. },
  461. /**
  462. * Запустить событие
  463. */
  464. fireEvent: function(element, eventType, keys, bubbles, cancelable) {
  465. // Определим необходимые параметры
  466. var eventBubbles = this.isBoolean(bubbles) ? bubbles : true;
  467. var eventCancelable = this.isBoolean(cancelable) ? cancelable : true;
  468. // Для клика создадим MouseEvent
  469. var isMouse = /click|dblclick|mouseup|mousedown/i.test(eventType);
  470. // Приведем к нужному виду клавиши
  471. keys = keys || {};
  472. this.each(['ctrlKey', 'altKey', 'shiftKey', 'metaKey'], function(letter) {
  473. if (!keys[letter]) {
  474. keys[letter] = false;
  475. }
  476. });
  477. // запустим для всех элементов по селектору
  478. var nativeEl = this.getIfAll(element);
  479. this.each(nativeEl, function(elem) {
  480. var evt = document.createEvent(isMouse ? 'MouseEvents' : 'HTMLEvents');
  481. if (isMouse) {
  482. // Событие мыши
  483. // event.initMouseEvent(type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget);
  484. evt.initMouseEvent(eventType, eventBubbles, eventCancelable, window, 0, 0, 0, 0, 0, keys.ctrlKey, keys.altKey, keys.shiftKey, keys.metaKey, 0, null);
  485. } else {
  486. // Событие общего типа
  487. // event.initEvent(type, bubbles, cancelable);
  488. evt.initEvent(eventType, eventBubbles, eventCancelable);
  489. }
  490. //var evt = (isMouse ? new MouseEvent() : new UIEvent());
  491. elem.dispatchEvent(evt);
  492. //console.log('dispatchEvent elem == %o, event == %o', elem, evt);
  493. }, this);
  494. },
  495. /**
  496. * Остановить выполнение события
  497. */
  498. stopEvent: function(e) {
  499. var event = e || window.event;
  500. if (!event) {
  501. return false;
  502. }
  503. event.preventDefault = event.preventDefault || function() {
  504. this.returnValue = false;
  505. };
  506. event.stopPropagation = event.stopPropagation || function() {
  507. this.cancelBubble = true;
  508. };
  509. event.preventDefault();
  510. event.stopPropagation();
  511. return true;
  512. },
  513. /**
  514. * Выделить текст в поле ввода
  515. */
  516. selectText: function(element, start, end) {
  517. var current = this.getIf(element);
  518. if (!current) {
  519. return;
  520. }
  521. if (!end) {
  522. end = start;
  523. }
  524. // firefox
  525. if ('selectionStart' in element) {
  526. element.setSelectionRange(start, end);
  527. element.focus(); // to make behaviour consistent with IE
  528. }
  529. // ie win
  530. else if(document.selection) {
  531. var range = element.createTextRange();
  532. range.collapse(true);
  533. range.moveStart('character', start);
  534. range.moveEnd('character', end - start);
  535. range.select();
  536. }
  537. },
  538. /**
  539. * Определяет, является ли значение строкой
  540. */
  541. isString : function(v) {
  542. return typeof v === 'string';
  543. },
  544. /**
  545. * Определяет, является ли значение числом
  546. */
  547. isNumber: function(v) {
  548. return typeof v === 'number' && isFinite(v);
  549. },
  550. /**
  551. * Определяет, является ли значение булевым
  552. */
  553. isBoolean: function(v) {
  554. return typeof v === 'boolean';
  555. },
  556. /**
  557. * Определяет, является ли значение объектом
  558. */
  559. isObject : function(v) {
  560. return typeof v === 'object';
  561. },
  562. /**
  563. * Определяет, является ли значение функцией
  564. */
  565. isFunction: function(v) {
  566. return typeof v === 'function';
  567. },
  568. /**
  569. * Определяет, является ли значение датой
  570. */
  571. isDate: function(v) {
  572. var result = true;
  573. this.each([
  574. 'getDay',
  575. 'getMonth',
  576. 'getFullYear',
  577. 'getHours',
  578. 'getMinutes'
  579. ], function(property) {
  580. result == result && this.isFunction(v[property]);
  581. }, this);
  582. return result;
  583. },
  584. /**
  585. * Переведем число в удобочитаемый вид с пробелами
  586. */
  587. numberToString: function(v) {
  588. var partLen = 3;
  589. try {
  590. v = Number(v);
  591. } catch (e) {
  592. return v;
  593. }
  594. v = String(v);
  595. var pointPos;
  596. pointPos = (pointPos = v.indexOf('.')) > 0 ? (pointPos) : (v.length);
  597. var result = v.substring(pointPos);
  598. v = v.substr(0, pointPos);
  599. var firstPart = true;
  600. while (v.length > 0) {
  601. var startPos = v.length - partLen;
  602. if (startPos < 0) {
  603. startPos = 0;
  604. }
  605. if (!firstPart) {
  606. result = ' ' + result;
  607. }
  608. firstPart = false;
  609. result = v.substr(startPos, partLen) + result;
  610. v = v.substr(0, v.length - partLen);
  611. }
  612. return result;
  613. },
  614. /**
  615. * Число с текстом в нужном падеже
  616. * @param {Number} number Число, к которому нужно дописать текст
  617. * @param {String} textFor1 Текст для количества 1
  618. * @param {String} textFor2 Текст для количества 2
  619. * @param {String} textFor10 Текст для количества 10
  620. */
  621. numberWithCase: function(number, textFor1, textFor2, textFor10) {
  622. // Определяем, какой текст подставить, по последней цифре
  623. var lastDigit = number % 10;
  624. var result = {
  625. number: number,
  626. text: ''
  627. };
  628. // Текст для количества 1
  629. if (this.inArray(lastDigit, [ 1 ])) {
  630. result.text = textFor1;
  631. }
  632. // Текст для количества 2
  633. if (this.inArray(lastDigit, [ 2, 3, 4 ])) {
  634. result.text = textFor2;
  635. }
  636. // Текст для количества 10
  637. if (this.inArray(lastDigit, [ 5, 6, 7, 8, 9, 0 ])) {
  638. result.text = textFor10;
  639. }
  640. // Текст для количества от 11 до 19
  641. var twoLastDigits = number % 100;
  642. if (10 < twoLastDigits && twoLastDigits < 20) {
  643. result.text = textFor10;
  644. }
  645. return this.template('{number} {text}', result);
  646. },
  647. /**
  648. * Определить, является ли тип значения скалярным
  649. */
  650. isScalar: function(v) {
  651. return this.isString(v) || this.isNumber(v) || this.isBoolean(v);
  652. },
  653. /**
  654. * Определить, является ли тип значения перечислимым
  655. */
  656. isIterable: function(v) {
  657. var result = !!v;
  658. if (result) {
  659. result = result && this.isNumber(v.length);
  660. result = result && !this.isString(v);
  661. // У формы есть свойство length - пропускаем её
  662. result = result && !(v.tagName && v.tagName.toUpperCase() == 'FORM');
  663. }
  664. return result;
  665. },
  666. /**
  667. * Сделать значение перечислимым
  668. */
  669. toIterable: function(value) {
  670. if (!value) {
  671. return value;
  672. }
  673. return this.isIterable(value) ? value : [value];
  674. },
  675. /**
  676. * Задать область видимости (scope) для функции
  677. */
  678. createDelegate: function(func, scope, args) {
  679. var method = func;
  680. return function() {
  681. var callArgs = args || arguments;
  682. return method.apply(scope || window, callArgs);
  683. };
  684. },
  685. /**
  686. * Проверим, является ли значение элементом массива или объекта
  687. */
  688. inArray: function(value, array) {
  689. return this.each(array, function(key) {
  690. if (key === value) {
  691. return true;
  692. }
  693. }) !== true;
  694. },
  695. /**
  696. * Найдем значение в массиве и вернем индекс
  697. */
  698. findInArray: function(value, array) {
  699. var result = this.each(array, function(key) {
  700. if (key === value) {
  701. return true;
  702. }
  703. });
  704. return this.isNumber(result) ? result : -1;
  705. },
  706. /**
  707. * Запустить функцию для всех элементов массива или объекта
  708. * @param {Array} array Массив, в котором значения будут перебираться по индексу элемента
  709. * @param {Object} array Объект, в котором значения будут перебираться по имени поля
  710. * @returns {Number} Индекс элемента, на котором досрочно завершилось выполнение, если array - массив
  711. * @returns {String} Имя поля, на котором досрочно завершилось выполнение, если array - объект
  712. * @returns {Boolean} True, если выполнение не завершалось досрочно
  713. */
  714. each: function(array, fn, scope) {
  715. if (!array) {
  716. return;
  717. }
  718. if (this.isIterable(array)) {
  719. for (var i = 0, len = array.length; i < len; i++) {
  720. if (this.isBoolean( fn.call(scope || array[i], array[i], i, array) )) {
  721. return i;
  722. };
  723. }
  724. } else {
  725. for (var key in array) {
  726. if (this.isBoolean( fn.call(scope || array[key], array[key], key, array) )) {
  727. return key;
  728. };
  729. }
  730. }
  731. return true;
  732. },
  733. /**
  734. * Разбить строку, укоротив её и склеив части указанным разделителем
  735. * @param {String} original Исходная строка
  736. * @param {Number} maxLength Максимальная длина, до которой нужно усечь исходную строку
  737. * @param {Number} tailLength Длина второй короткой части
  738. * @param {String} glue Разделитель, который склеит две части укороченной строки
  739. */
  740. splitWithGlue: function(original, maxLength, tailLength, glue) {
  741. // Разделитель по умолчанию
  742. if (!this.isString(glue)) {
  743. glue = '...';
  744. }
  745. // По умолчанию строка завершается разделителем
  746. if (!this.isNumber(tailLength)) {
  747. tailLength = 0;
  748. }
  749. var result = original;
  750. if (result.length > maxLength) {
  751. result = this.template('{head}{glue}{tail}', {
  752. head: original.substring(0, maxLength - (tailLength + glue.length)),
  753. glue: glue,
  754. tail: original.substring(original.length - tailLength)
  755. });
  756. }
  757. return result;
  758. },
  759. /**
  760. * форматирование строки, используя объект
  761. */
  762. template: function(strTarget, objSource) {
  763. var s = arguments[0];
  764. for (var prop in objSource) {
  765. var reg = new RegExp("\\{" + prop + "\\}", "gm");
  766. s = s.replace(reg, objSource[prop]);
  767. }
  768. return s;
  769. },
  770. /**
  771. * форматирование строки, используя числовые индексы
  772. */
  773. format: function() {
  774. var original = arguments[0];
  775. this.each(arguments, function(sample, index) {
  776. if (index > 0) {
  777. var currentI = index - 1;
  778. var reg = new RegExp("\\{" + currentI + "\\}", "gm");
  779. original = original.replace(reg, sample);
  780. }
  781. });
  782. return original;
  783. },
  784. /**
  785. * Быстрый доступ к форматированию
  786. */
  787. fmt: function() {
  788. return this.format.apply(this, arguments);
  789. },
  790. /**
  791. * Выдать строку заданной длины с заполнением символом
  792. */
  793. leftPad: function (val, size, character) {
  794. var result = String(val);
  795. if (!character) {
  796. character = ' ';
  797. }
  798. while (result.length < size) {
  799. result = character + result;
  800. }
  801. return result;
  802. },
  803. /**
  804. * Определить, какая часть окна ушла вверх при прокрутке
  805. */
  806. getScrollOffset: function () {
  807. var d = unsafeWindow.top.document;
  808. return top.pageYOffset ? top.pageYOffset : (
  809. (d.documentElement && d.documentElement.scrollTop) ? (d.documentElement.scrollTop) : (d.body.scrollTop)
  810. );
  811. },
  812. /**
  813. * Определить размер окна
  814. */
  815. getWindowSize: function () {
  816. var d = unsafeWindow.top.document;
  817. return {
  818. width: /*top.innerWidth ? top.innerWidth :*/ (
  819. (d.documentElement.clientWidth) ? (d.documentElement.clientWidth) : (d.body.offsetWidth)
  820. ),
  821. height: /*top.innerHeight ? top.innerHeight :*/ (
  822. (d.documentElement.clientHeight) ? (d.documentElement.clientHeight) : (d.body.offsetHeight)
  823. )
  824. };
  825. },
  826. /**
  827. * Склеить строки
  828. */
  829. join: function(rows, glue) {
  830. return Array.prototype.slice.call(this.toIterable(rows), 0).join(glue || '');
  831. },
  832. /**
  833. * Вернем значение cookie
  834. */
  835. getCookie: function(name) {
  836. var value = null;
  837. // Проверим, есть ли кука с таким именем
  838. var cookie = unsafeWindow.document.cookie;
  839. var regKey = new RegExp(name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + '=(.*?)((; ?)|$)');
  840. var hasMatch = cookie.match(regKey);
  841. if (hasMatch && hasMatch[1]) {
  842. value = decodeURIComponent(hasMatch[1]);
  843. }
  844. return value;
  845. },
  846. /**
  847. * Установим значение cookie
  848. * @param {Object} options Объект с дополнительными значениями
  849. * - expires Срок действия куки: {Number} количество дней или {Data} дата окончания срока
  850. * - path Путь, отсчитывая от которого будет действовать кука
  851. * - domain Домен, в пределах которого будет действовать кука
  852. * - secure Кука для https-соединения
  853. */
  854. setCookie: function(name, value, options) {
  855. // Можно опустить значение куки, если нужно удалить
  856. if (!value) {
  857. value = '';
  858. }
  859. options = options || {};
  860. // Проверяем, задана дата или количество дней
  861. var expires = '';
  862. if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
  863. var date;
  864. if (typeof options.expires == 'number') {
  865. date = new Date();
  866. date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
  867. } else {
  868. date = options.expires;
  869. }
  870. expires = '; expires=' + date.toUTCString();
  871. }
  872. // Проставляем другие опции
  873. var path = options.path ? '; path=' + (options.path) : '';
  874. var domain = options.domain ? '; domain=' + (options.domain) : '';
  875. var secure = (options.secure === true) ? '; secure' : '';
  876. unsafeWindow.document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  877. },
  878. /**
  879. * Картинка с большим пальцем
  880. */
  881. getThumbHand: function() {
  882. var thumbSource;
  883. thumbSource = ( // рука
  884. 'data:image/png;base64,\
  885. iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA0UlEQVR42r3SPwsBYRzA8buSlMFi\
  886. MymDd+A1WEiSUDarwS6TwSyjgUkkfxZh4J0YpQwKk8L36R56uu5Rd1ee+izXPd/nN/xMw+cx/xXI\
  887. ooYxhm4DSbRRxAQ5N4EUmqjKKZ4YOAXmeCjfj1ICddyxwVVGxL0dep+AGK2gBA5oYPZjuoWYSheY\
  888. Iq+52EUMAWS8BHxNUJbfo9ij5XWCEl4Y6QIrpG2X4uggjIh84KQLnFHB2uH1kGHtglis7x5scVF+\
  889. uom6Ye3ByxYIoo+lGvB8fAfecvkwEbIZfswAAAAASUVORK5CYII=');
  890. thumbSource = ( // сообщение
  891. 'data:image/png;base64,\
  892. iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABL0lEQVQ4y2P4//8/AyWYgWoGRLTv\
  893. EALipUD8E4j/48G7gFgFmwEbVx689f/3n7//8YEtJ++DDLkNxGxwA4AcHiD+8/ffv/8fvv37//LT\
  894. v//PPv77/+T9v/8P3/37f+/Nv/+3X/39f+cVxPDqBcdBhpghGyCXM/UAWPIFUOOzD//+PwZqfvD2\
  895. 3/+7UM3XX/z9f/UZxIDOVWdBBnhjNeApUPOjd1DNr//9v/USovkKUPPFJ7gNgHsB5Pz7QFvvvP77\
  896. /yZQ87Xnf/9fBmq+8ARkwB+wAbWLToAMsMQaiCBDkAHINRce/wUbjBaInLii8Q8syubuuAo36P3n\
  897. H2A+UPwy1mjEhoEK7zx/9xWm8TsQ1xKdEoGKe2duuwLS+AWIC0lKykANSkB8D4hT6JcXBswAAPeL\
  898. DyK+4moLAAAAAElFTkSuQmCC');
  899. return thumbSource;
  900. },
  901. /**
  902. * Отладка
  903. */
  904. thumb: function(text) {
  905. var bgImage = this.format('background: url("{0}") no-repeat;', this.getThumbHand());
  906. console.log('%c ', bgImage, text);
  907. },
  908. /**
  909. * Удалим значение cookie
  910. */
  911. removeCookie: function(name) {
  912. this.setCookie(name, null, { expires: -1 });
  913. },
  914. /**
  915. * Отладка
  916. */
  917. groupDir: function(name, object) {
  918. console.group(name);
  919. console.dir(object);
  920. console.groupEnd();
  921. },
  922. /**
  923. * Отладка: ошибка с пользовательским сообщением
  924. */
  925. errorist: function(error, text, parameters) {
  926. var params = Array.prototype.slice.call(arguments, 1);
  927. params.unshift('#FFEBEB');
  928. this.coloredLog(params);
  929. console.error(error);
  930. },
  931. /**
  932. * Отладка: вывод цветной строки
  933. */
  934. coloredLog: function(color, text) {
  935. var params = Array.prototype.slice.call(arguments, 2);
  936. params.unshift('background-color: ' + color + ';');
  937. params.unshift('%c' + text);
  938. console.log.apply(console, params);
  939. },
  940. /**
  941. * XPath-запрос
  942. */
  943. xpath: function(selector) {
  944. var nodes = document.evaluate(selector, document, null, XPathResult.ANY_TYPE, null);
  945. var thisNode = nodes.iterateNext();
  946. while (thisNode) {
  947. //console.log(thisNode.textContent);
  948. thisNode = nodes.iterateNext();
  949. }
  950. },
  951. /**
  952. * Упаковать для хранилища
  953. */
  954. packToStorage: function(objBox) {
  955. var clone = this.extend({}, objBox);
  956. this.each(clone, function(property, index) {
  957. if (typeof property == 'function') {
  958. clone[index] = property.toString();
  959. }
  960. if (typeof property == 'object') {
  961. clone[index] = this.packToStorage(property);
  962. }
  963. }, this);
  964. return JSON.stringify(clone);
  965. },
  966. /**
  967. * Распаковать из хранилища
  968. */
  969. unpackFromStorage: function(objBox) {
  970. var result = {};
  971. try {
  972. result = JSON.parse(objBox);
  973. } catch (e) {
  974. try {
  975. result = eval('(' + objBox + ')');
  976. } catch (e) {
  977. result = objBox;
  978. }
  979. }
  980. if (typeof result == 'object') {
  981. for (var property in result) {
  982. result[property] = this.unpackFromStorage(result[property]);
  983. }
  984. }
  985. return result;
  986. }
  987. };
  988.  
  989. // Добавляем обратный порядок в jQuery
  990. if (typeof jQuery != 'undefined') {
  991. if (typeof jQuery.fn.reverse != 'function') {
  992. jQuery.fn.reverse = function() {
  993. return jQuery(this.get().reverse());
  994. };
  995. }
  996. if (typeof jQuery.fn.softHide != 'function') {
  997. jQuery.fn.softHide = function() {
  998. return jQuery(this).css({ visibility: 'hidden' });
  999. };
  1000. }
  1001. }
  1002.  
  1003. unsafeWindow.NodeList.prototype.size = () => this.length;
  1004.  
  1005. // форматирование строки
  1006. unsafeWindow.String.prototype.format = unsafeWindow.__krokodil.format;
  1007.  
  1008. //отладка
  1009. unsafeWindow.console.groupDir = unsafeWindow.__krokodil.groupDir;
  1010. unsafeWindow.console.coloredLog = unsafeWindow.__krokodil.coloredLog;
  1011. unsafeWindow.console.errorist = unsafeWindow.__krokodil.errorist;
  1012.  
  1013. //unsafeWindow.__krokodil.thumb('Include Tools');
  1014. //console.coloredLog('#fffbd6', 'Include Tools');
  1015. //console.errorist('Include Tools');
  1016. console.log('💬 Include Tools');
  1017.  
  1018. })(paramWindow);