Include Tools

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

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

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