Include Tools

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

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

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

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