Include Tools

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

当前为 2019-03-12 提交的版本,查看 最新版本

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

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