Include Tools

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

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址