1/* eslint-disable */ 2;(function() { 3 4 if (typeof window.BX === 'function') 5 { 6 return; 7 } 8 9/** 10 * Babel external helpers 11 * (c) 2018 Babel 12 * @license MIT 13 */ 14(function (global) { 15 var babelHelpers = global.babelHelpers = {}; 16 17 function _typeof(obj) { 18 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { 19 babelHelpers.typeof = _typeof = function (obj) { 20 return typeof obj; 21 }; 22 } else { 23 babelHelpers.typeof = _typeof = function (obj) { 24 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; 25 }; 26 } 27 28 return _typeof(obj); 29 } 30 31 babelHelpers.typeof = _typeof; 32 var REACT_ELEMENT_TYPE; 33 34 function _createRawReactElement(type, props, key, children) { 35 if (!REACT_ELEMENT_TYPE) { 36 REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7; 37 } 38 39 var defaultProps = type && type.defaultProps; 40 var childrenLength = arguments.length - 3; 41 42 if (!props && childrenLength !== 0) { 43 props = { 44 children: void 0 45 }; 46 } 47 48 if (props && defaultProps) { 49 for (var propName in defaultProps) { 50 if (props[propName] === void 0) { 51 props[propName] = defaultProps[propName]; 52 } 53 } 54 } else if (!props) { 55 props = defaultProps || {}; 56 } 57 58 if (childrenLength === 1) { 59 props.children = children; 60 } else if (childrenLength > 1) { 61 var childArray = new Array(childrenLength); 62 63 for (var i = 0; i < childrenLength; i++) { 64 childArray[i] = arguments[i + 3]; 65 } 66 67 props.children = childArray; 68 } 69 70 return { 71 $$typeof: REACT_ELEMENT_TYPE, 72 type: type, 73 key: key === undefined ? null : '' + key, 74 ref: null, 75 props: props, 76 _owner: null 77 }; 78 } 79 80 babelHelpers.jsx = _createRawReactElement; 81 82 function _asyncIterator(iterable) { 83 var method; 84 85 if (typeof Symbol === "function") { 86 if (Symbol.asyncIterator) { 87 method = iterable[Symbol.asyncIterator]; 88 if (method != null) return method.call(iterable); 89 } 90 91 if (Symbol.iterator) { 92 method = iterable[Symbol.iterator]; 93 if (method != null) return method.call(iterable); 94 } 95 } 96 97 throw new TypeError("Object is not async iterable"); 98 } 99 100 babelHelpers.asyncIterator = _asyncIterator; 101 102 function _AwaitValue(value) { 103 this.wrapped = value; 104 } 105 106 babelHelpers.AwaitValue = _AwaitValue; 107 108 function AsyncGenerator(gen) { 109 var front, back; 110 111 function send(key, arg) { 112 return new Promise(function (resolve, reject) { 113 var request = { 114 key: key, 115 arg: arg, 116 resolve: resolve, 117 reject: reject, 118 next: null 119 }; 120 121 if (back) { 122 back = back.next = request; 123 } else { 124 front = back = request; 125 resume(key, arg); 126 } 127 }); 128 } 129 130 function resume(key, arg) { 131 try { 132 var result = gen[key](arg); 133 var value = result.value; 134 var wrappedAwait = value instanceof babelHelpers.AwaitValue; 135 Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { 136 if (wrappedAwait) { 137 resume("next", arg); 138 return; 139 } 140 141 settle(result.done ? "return" : "normal", arg); 142 }, function (err) { 143 resume("throw", err); 144 }); 145 } catch (err) { 146 settle("throw", err); 147 } 148 } 149 150 function settle(type, value) { 151 switch (type) { 152 case "return": 153 front.resolve({ 154 value: value, 155 done: true 156 }); 157 break; 158 159 case "throw": 160 front.reject(value); 161 break; 162 163 default: 164 front.resolve({ 165 value: value, 166 done: false 167 }); 168 break; 169 } 170 171 front = front.next; 172 173 if (front) { 174 resume(front.key, front.arg); 175 } else { 176 back = null; 177 } 178 } 179 180 this._invoke = send; 181 182 if (typeof gen.return !== "function") { 183 this.return = undefined; 184 } 185 } 186 187 if (typeof Symbol === "function" && Symbol.asyncIterator) { 188 AsyncGenerator.prototype[Symbol.asyncIterator] = function () { 189 return this; 190 }; 191 } 192 193 AsyncGenerator.prototype.next = function (arg) { 194 return this._invoke("next", arg); 195 }; 196 197 AsyncGenerator.prototype.throw = function (arg) { 198 return this._invoke("throw", arg); 199 }; 200 201 AsyncGenerator.prototype.return = function (arg) { 202 return this._invoke("return", arg); 203 }; 204 205 babelHelpers.AsyncGenerator = AsyncGenerator; 206 207 function _wrapAsyncGenerator(fn) { 208 return function () { 209 return new babelHelpers.AsyncGenerator(fn.apply(this, arguments)); 210 }; 211 } 212 213 babelHelpers.wrapAsyncGenerator = _wrapAsyncGenerator; 214 215 function _awaitAsyncGenerator(value) { 216 return new babelHelpers.AwaitValue(value); 217 } 218 219 babelHelpers.awaitAsyncGenerator = _awaitAsyncGenerator; 220 221 function _asyncGeneratorDelegate(inner, awaitWrap) { 222 var iter = {}, 223 waiting = false;
224 225 function pump(key, value) { 226 waiting = true; 227 value = new Promise(function (resolve) { 228 resolve(inner[key](value)); 229 }); 230 return { 231 done: false, 232 value: awaitWrap(value) 233 }; 234 } 235 236 ; 237 238 if (typeof Symbol === "function" && Symbol.iterator) { 239 iter[Symbol.iterator] = function () { 240 return this; 241 }; 242 } 243 244 iter.next = function (value) { 245 if (waiting) { 246 waiting = false; 247 return value; 248 } 249 250 return pump("next", value); 251 }; 252 253 if (typeof inner.throw === "function") { 254 iter.throw = function (value) { 255 if (waiting) { 256 waiting = false; 257 throw value; 258 } 259 260 return pump("throw", value); 261 }; 262 } 263 264 if (typeof inner.return === "function") { 265 iter.return = function (value) { 266 return pump("return", value); 267 }; 268 } 269 270 return iter; 271 } 272 273 babelHelpers.asyncGeneratorDelegate = _asyncGeneratorDelegate; 274 275 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { 276 try { 277 var info = gen[key](arg); 278 var value = info.value; 279 } catch (error) { 280 reject(error); 281 return; 282 } 283 284 if (info.done) { 285 resolve(value); 286 } else { 287 Promise.resolve(value).then(_next, _throw); 288 } 289 } 290 291 function _asyncToGenerator(fn) { 292 return function () { 293 var self = this, 294 args = arguments; 295 return new Promise(function (resolve, reject) { 296 var gen = fn.apply(self, args); 297 298 function _next(value) { 299 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); 300 } 301 302 function _throw(err) { 303 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); 304 } 305 306 _next(undefined); 307 }); 308 }; 309 } 310 311 babelHelpers.asyncToGenerator = _asyncToGenerator; 312 313 function _classCallCheck(instance, Constructor) { 314 if (!(instance instanceof Constructor)) { 315 throw new TypeError("Cannot call a class as a function"); 316 } 317 } 318 319 babelHelpers.classCallCheck = _classCallCheck; 320 321 function _defineProperties(target, props) { 322 for (var i = 0; i < props.length; i++) { 323 var descriptor = props[i]; 324 descriptor.enumerable = descriptor.enumerable || false; 325 descriptor.configurable = true; 326 if ("value" in descriptor) descriptor.writable = true; 327 Object.defineProperty(target, descriptor.key, descriptor); 328 } 329 } 330 331 function _createClass(Constructor, protoProps, staticProps) { 332 if (protoProps) _defineProperties(Constructor.prototype, protoProps); 333 if (staticProps) _defineProperties(Constructor, staticProps); 334 return Constructor; 335 } 336 337 babelHelpers.createClass = _createClass; 338 339 function _defineEnumerableProperties(obj, descs) { 340 for (var key in descs) { 341 var desc = descs[key]; 342 desc.configurable = desc.enumerable = true; 343 if ("value" in desc) desc.writable = true; 344 Object.defineProperty(obj, key, desc); 345 } 346 347 if (Object.getOwnPropertySymbols) { 348 var objectSymbols = Object.getOwnPropertySymbols(descs); 349 350 for (var i = 0; i < objectSymbols.length; i++) { 351 var sym = objectSymbols[i]; 352 var desc = descs[sym]; 353 desc.configurable = desc.enumerable = true; 354 if ("value" in desc) desc.writable = true; 355 Object.defineProperty(obj, sym, desc); 356 } 357 } 358 359 return obj; 360 } 361 362 babelHelpers.defineEnumerableProperties = _defineEnumerableProperties; 363 364 function _defaults(obj, defaults) { 365 var keys = Object.getOwnPropertyNames(defaults); 366 367 for (var i = 0; i < keys.length; i++) { 368 var key = keys[i]; 369 var value = Object.getOwnPropertyDescriptor(defaults, key); 370 371 if (value && value.configurable && obj[key] === undefined) { 372 Object.defineProperty(obj, key, value); 373 } 374 } 375 376 return obj; 377 } 378 379 babelHelpers.defaults = _defaults; 380 381 function _defineProperty(obj, key, value) { 382 if (key in obj) { 383 Object.defineProperty(obj, key, { 384 value: value, 385 enumerable: true, 386 configurable: true, 387 writable: true 388 }); 389 } else { 390 obj[key] = value; 391 } 392 393 return obj; 394 } 395 396 babelHelpers.defineProperty = _defineProperty; 397 398 function _extends() { 399 babelHelpers.extends = _extends = Object.assign || function (target) { 400 for (var i = 1; i < arguments.length; i++) { 401 var source = arguments[i]; 402 403 for (var key in source) { 404 if (Object.prototype.hasOwnProperty.call(source, key)) { 405 target[key] = source[key]; 406 } 407 } 408 } 409 410 return target; 411 }; 412 413 return _extends.apply(this, arguments); 414 } 415 416 babelHelpers.extends = _extends; 417 418 function _objectSpread(target) { 419 for (var i = 1; i < arguments.length; i++) { 420 var source = arguments[i] != null ? arguments[i] : {}; 421 var ownKeys = Object.keys(source); 422 423 if (typeof Object.getOwnPropertySymbols === 'function') { 424 ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { 425 return Object.getOwnPropertyDescriptor(source, sym).enumerable; 426 })); 427 } 428 429 ownKeys.forEach(function (key) { 430 babelHelpers.defineProperty(target, key, source[key]); 431 }); 432 } 433 434 return target; 435 } 436 437 babelHelpers.objectSpread = _objectSpread; 438 439 function _inherits(subClass, superClass) { 440 if (typeof superClass !== "function" && superClass !== null) { 441 throw new TypeError("Super expression must either be null or a function"); 442 } 443 444 subClass.prototype = Object.create(superClass && superClass.prototype, {
445 constructor: { 446 value: subClass, 447 writable: true, 448 configurable: true 449 } 450 }); 451 if (superClass) babelHelpers.setPrototypeOf(subClass, superClass); 452 } 453 454 babelHelpers.inherits = _inherits; 455 456 function _inheritsLoose(subClass, superClass) { 457 subClass.prototype = Object.create(superClass.prototype); 458 subClass.prototype.constructor = subClass; 459 subClass.__proto__ = superClass; 460 } 461 462 babelHelpers.inheritsLoose = _inheritsLoose; 463 464 function _getPrototypeOf(o) { 465 babelHelpers.getPrototypeOf = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { 466 return o.__proto__ || Object.getPrototypeOf(o); 467 }; 468 return _getPrototypeOf(o); 469 } 470 471 babelHelpers.getPrototypeOf = _getPrototypeOf; 472 473 function _setPrototypeOf(o, p) { 474 babelHelpers.setPrototypeOf = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { 475 o.__proto__ = p; 476 return o; 477 }; 478 479 return _setPrototypeOf(o, p); 480 } 481 482 babelHelpers.setPrototypeOf = _setPrototypeOf; 483 484 function isNativeReflectConstruct() { 485 if (typeof Reflect === "undefined" || !Reflect.construct) return false; 486 if (Reflect.construct.sham) return false; 487 if (typeof Proxy === "function") return true; 488 489 try { 490 Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); 491 return true; 492 } catch (e) { 493 return false; 494 } 495 } 496 497 function _construct(Parent, args, Class) { 498 if (isNativeReflectConstruct()) { 499 babelHelpers.construct = _construct = Reflect.construct; 500 } else { 501 babelHelpers.construct = _construct = function _construct(Parent, args, Class) { 502 var a = [null]; 503 a.push.apply(a, args); 504 var Constructor = Function.bind.apply(Parent, a); 505 var instance = new Constructor(); 506 if (Class) babelHelpers.setPrototypeOf(instance, Class.prototype); 507 return instance; 508 }; 509 } 510 511 return _construct.apply(null, arguments); 512 } 513 514 babelHelpers.construct = _construct; 515 516 function _isNativeFunction(fn) { 517 return Function.toString.call(fn).indexOf("[native code]") !== -1; 518 } 519 520 babelHelpers.isNativeFunction = _isNativeFunction; 521 522 function _wrapNativeSuper(Class) { 523 var _cache = typeof Map === "function" ? new Map() : undefined; 524 525 babelHelpers.wrapNativeSuper = _wrapNativeSuper = function _wrapNativeSuper(Class) { 526 if (Class === null || !babelHelpers.isNativeFunction(Class)) return Class; 527 528 if (typeof Class !== "function") { 529 throw new TypeError("Super expression must either be null or a function"); 530 } 531 532 if (typeof _cache !== "undefined") { 533 if (_cache.has(Class)) return _cache.get(Class); 534 535 _cache.set(Class, Wrapper); 536 } 537 538 function Wrapper() { 539 return babelHelpers.construct(Class, arguments, babelHelpers.getPrototypeOf(this).constructor); 540 } 541 542 Wrapper.prototype = Object.create(Class.prototype, { 543 constructor: { 544 value: Wrapper, 545 enumerable: false, 546 writable: true, 547 configurable: true 548 } 549 }); 550 return babelHelpers.setPrototypeOf(Wrapper, Class); 551 }; 552 553 return _wrapNativeSuper(Class); 554 } 555 556 babelHelpers.wrapNativeSuper = _wrapNativeSuper; 557 558 function _instanceof(left, right) { 559 if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { 560 return right[Symbol.hasInstance](left); 561 } else { 562 return left instanceof right; 563 } 564 } 565 566 babelHelpers.instanceof = _instanceof; 567 568 function _interopRequireDefault(obj) { 569 return obj && obj.__esModule ? obj : { 570 default: obj 571 }; 572 } 573 574 babelHelpers.interopRequireDefault = _interopRequireDefault; 575 576 function _interopRequireWildcard(obj) { 577 if (obj && obj.__esModule) { 578 return obj; 579 } else { 580 var newObj = {}; 581 582 if (obj != null) { 583 for (var key in obj) { 584 if (Object.prototype.hasOwnProperty.call(obj, key)) { 585 var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; 586 587 if (desc.get || desc.set) { 588 Object.defineProperty(newObj, key, desc); 589 } else { 590 newObj[key] = obj[key]; 591 } 592 } 593 } 594 } 595 596 newObj.default = obj; 597 return newObj; 598 } 599 } 600 601 babelHelpers.interopRequireWildcard = _interopRequireWildcard; 602 603 function _newArrowCheck(innerThis, boundThis) {
604 if (innerThis !== boundThis) { 605 throw new TypeError("Cannot instantiate an arrow function"); 606 } 607 } 608 609 babelHelpers.newArrowCheck = _newArrowCheck; 610 611 function _objectDestructuringEmpty(obj) { 612 if (obj == null) throw new TypeError("Cannot destructure undefined"); 613 } 614 615 babelHelpers.objectDestructuringEmpty = _objectDestructuringEmpty; 616 617 function _objectWithoutPropertiesLoose(source, excluded) { 618 if (source == null) return {}; 619 var target = {}; 620 var sourceKeys = Object.keys(source); 621 var key, i; 622 623 for (i = 0; i < sourceKeys.length; i++) { 624 key = sourceKeys[i]; 625 if (excluded.indexOf(key) >= 0) continue; 626 target[key] = source[key]; 627 } 628 629 return target; 630 } 631 632 babelHelpers.objectWithoutPropertiesLoose = _objectWithoutPropertiesLoose; 633 634 function _objectWithoutProperties(source, excluded) { 635 if (source == null) return {}; 636 var target = babelHelpers.objectWithoutPropertiesLoose(source, excluded); 637 var key, i; 638 639 if (Object.getOwnPropertySymbols) { 640 var sourceSymbolKeys = Object.getOwnPropertySymbols(source); 641 642 for (i = 0; i < sourceSymbolKeys.length; i++) { 643 key = sourceSymbolKeys[i]; 644 if (excluded.indexOf(key) >= 0) continue; 645 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; 646 target[key] = source[key]; 647 } 648 } 649 650 return target; 651 } 652 653 babelHelpers.objectWithoutProperties = _objectWithoutProperties; 654 655 function _assertThisInitialized(self) { 656 if (self === void 0) { 657 throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); 658 } 659 660 return self; 661 } 662 663 babelHelpers.assertThisInitialized = _assertThisInitialized; 664 665 function _possibleConstructorReturn(self, call) { 666 if (call && (typeof call === "object" || typeof call === "function")) { 667 return call; 668 } 669 670 return babelHelpers.assertThisInitialized(self); 671 } 672 673 babelHelpers.possibleConstructorReturn = _possibleConstructorReturn; 674 675 function _superPropBase(object, property) { 676 while (!Object.prototype.hasOwnProperty.call(object, property)) { 677 object = babelHelpers.getPrototypeOf(object); 678 if (object === null) break; 679 } 680 681 return object; 682 } 683 684 babelHelpers.superPropBase = _superPropBase; 685 686 function _get(target, property, receiver) { 687 if (typeof Reflect !== "undefined" && Reflect.get) { 688 babelHelpers.get = _get = Reflect.get; 689 } else { 690 babelHelpers.get = _get = function _get(target, property, receiver) { 691 var base = babelHelpers.superPropBase(target, property); 692 if (!base) return; 693 var desc = Object.getOwnPropertyDescriptor(base, property); 694 695 if (desc.get) { 696 return desc.get.call(receiver); 697 } 698 699 return desc.value; 700 }; 701 } 702 703 return _get(target, property, receiver || target); 704 } 705 706 babelHelpers.get = _get; 707 708 function set(target, property, value, receiver) { 709 if (typeof Reflect !== "undefined" && Reflect.set) { 710 set = Reflect.set; 711 } else { 712 set = function set(target, property, value, receiver) { 713 var base = babelHelpers.superPropBase(target, property); 714 var desc; 715 716 if (base) { 717 desc = Object.getOwnPropertyDescriptor(base, property); 718 719 if (desc.set) { 720 desc.set.call(receiver, value); 721 return true; 722 } else if (!desc.writable) { 723 return false; 724 } 725 } 726 727 desc = Object.getOwnPropertyDescriptor(receiver, property); 728 729 if (desc) { 730 if (!desc.writable) { 731 return false; 732 } 733 734 desc.value = value; 735 Object.defineProperty(receiver, property, desc); 736 } else { 737 babelHelpers.defineProperty(receiver, property, value); 738 } 739 740 return true; 741 }; 742 } 743 744 return set(target, property, value, receiver); 745 } 746 747 function _set(target, property, value, receiver, isStrict) { 748 var s = set(target, property, value, receiver || target); 749 750 if (!s && isStrict) { 751 throw new Error('failed to set property'); 752 } 753 754 return value; 755 } 756 757 babelHelpers.set = _set; 758 759 function _taggedTemplateLiteral(strings, raw) { 760 if (!raw) { 761 raw = strings.slice(0); 762 } 763 764 return Object.freeze(Object.defineProperties(strings, { 765 raw: { 766 value: Object.freeze(raw) 767 } 768 })); 769 } 770 771 babelHelpers.taggedTemplateLiteral = _taggedTemplateLiteral; 772 773 function _taggedTemplateLiteralLoose(strings, raw) { 774 if (!raw) {
775 raw = strings.slice(0); 776 } 777 778 strings.raw = raw; 779 return strings; 780 } 781 782 babelHelpers.taggedTemplateLiteralLoose = _taggedTemplateLiteralLoose; 783 784 function _temporalRef(val, name) { 785 if (val === babelHelpers.temporalUndefined) { 786 throw new ReferenceError(name + " is not defined - temporal dead zone"); 787 } else { 788 return val; 789 } 790 } 791 792 babelHelpers.temporalRef = _temporalRef; 793 794 function _readOnlyError(name) { 795 throw new Error("\"" + name + "\" is read-only"); 796 } 797 798 babelHelpers.readOnlyError = _readOnlyError; 799 800 function _classNameTDZError(name) { 801 throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); 802 } 803 804 babelHelpers.classNameTDZError = _classNameTDZError; 805 babelHelpers.temporalUndefined = {}; 806 807 function _slicedToArray(arr, i) { 808 return babelHelpers.arrayWithHoles(arr) || babelHelpers.iterableToArrayLimit(arr, i) || babelHelpers.nonIterableRest(); 809 } 810 811 babelHelpers.slicedToArray = _slicedToArray; 812 813 function _slicedToArrayLoose(arr, i) { 814 return babelHelpers.arrayWithHoles(arr) || babelHelpers.iterableToArrayLimitLoose(arr, i) || babelHelpers.nonIterableRest(); 815 } 816 817 babelHelpers.slicedToArrayLoose = _slicedToArrayLoose; 818 819 function _toArray(arr) { 820 return babelHelpers.arrayWithHoles(arr) || babelHelpers.iterableToArray(arr) || babelHelpers.nonIterableRest(); 821 } 822 823 babelHelpers.toArray = _toArray; 824 825 function _toConsumableArray(arr) { 826 return babelHelpers.arrayWithoutHoles(arr) || babelHelpers.iterableToArray(arr) || babelHelpers.nonIterableSpread(); 827 } 828 829 babelHelpers.toConsumableArray = _toConsumableArray; 830 831 function _arrayWithoutHoles(arr) { 832 if (Array.isArray(arr)) { 833 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; 834 835 return arr2; 836 } 837 } 838 839 babelHelpers.arrayWithoutHoles = _arrayWithoutHoles; 840 841 function _arrayWithHoles(arr) { 842 if (Array.isArray(arr)) return arr; 843 } 844 845 babelHelpers.arrayWithHoles = _arrayWithHoles; 846 847 function _iterableToArray(iter) { 848 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); 849 } 850 851 babelHelpers.iterableToArray = _iterableToArray; 852 853 function _iterableToArrayLimit(arr, i) { 854 var _arr = []; 855 var _n = true; 856 var _d = false; 857 var _e = undefined; 858 859 try { 860 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { 861 _arr.push(_s.value); 862 863 if (i && _arr.length === i) break; 864 } 865 } catch (err) { 866 _d = true; 867 _e = err; 868 } finally { 869 try { 870 if (!_n && _i["return"] != null) _i["return"](); 871 } finally { 872 if (_d) throw _e; 873 } 874 } 875 876 return _arr; 877 } 878 879 babelHelpers.iterableToArrayLimit = _iterableToArrayLimit; 880 881 function _iterableToArrayLimitLoose(arr, i) { 882 var _arr = []; 883 884 for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { 885 _arr.push(_step.value); 886 887 if (i && _arr.length === i) break; 888 } 889 890 return _arr; 891 } 892 893 babelHelpers.iterableToArrayLimitLoose = _iterableToArrayLimitLoose; 894 895 function _nonIterableSpread() { 896 throw new TypeError("Invalid attempt to spread non-iterable instance"); 897 } 898 899 babelHelpers.nonIterableSpread = _nonIterableSpread; 900 901 function _nonIterableRest() { 902 throw new TypeError("Invalid attempt to destructure non-iterable instance"); 903 } 904 905 babelHelpers.nonIterableRest = _nonIterableRest; 906 907 function _skipFirstGeneratorNext(fn) { 908 return function () { 909 var it = fn.apply(this, arguments); 910 it.next(); 911 return it; 912 }; 913 } 914 915 babelHelpers.skipFirstGeneratorNext = _skipFirstGeneratorNext; 916 917 function _toPropertyKey(key) { 918 if (typeof key === "symbol") { 919 return key; 920 } else { 921 return String(key); 922 } 923 } 924 925 babelHelpers.toPropertyKey = _toPropertyKey; 926 927 function _initializerWarningHelper(descriptor, context) { 928 throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and set to use loose mode. ' + 'To use proposal-class-properties in spec mode with decorators, wait for ' + 'the next major version of decorators in stage 2.'); 929 } 930 931 babelHelpers.initializerWarningHelper = _initializerWarningHelper; 932 933 function _initializerDefineProperty(target, property, descriptor, context) { 934 if (!descriptor) return; 935 Object.defineProperty(target, property, { 936 enumerable: descriptor.enumerable, 937 configurable: descriptor.configurable, 938 writable: descriptor.writable, 939 value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 940 }); 941 } 942 943 babelHelpers.initializerDefineProperty = _initializerDefineProperty; 944 945 function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { 946 var desc = {}; 947 Object['ke' + 'ys'](descriptor).forEach(function (key) { 948 desc[key] = descriptor[key]; 949 }); 950 desc.enumerable = !!desc.enumerable; 951 desc.configurable = !!desc.configurable; 952 953 if ('value' in desc || desc.initializer) { 954 desc.writable = true; 955 } 956 957 desc = decorators.slice().reverse().reduce(function (desc, decorator) { 958 return decorator(target, property, desc) || desc; 959 }, desc); 960 961 if (context && desc.initializer !== void 0) { 962 desc.value = desc.initializer ? desc.initializer.call(context) : void 0; 963 desc.initializer = undefined; 964 } 965 966 if (desc.initializer === void 0) { 967 Object['define' + 'Property'](target, property, desc); 968 desc = null; 969 } 970 971 return desc; 972 } 973 974 babelHelpers.applyDecoratedDescriptor = _applyDecoratedDescriptor; 975 var id = 0; 976 977 function _classPrivateFieldKey(name) { 978 return "__private_" + id++ + "_" + name; 979 } 980 981 babelHelpers.classPrivateFieldLooseKey = _classPrivateFieldKey; 982 983 function _classPrivateFieldBase(receiver, privateKey) { 984 if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { 985 throw new TypeError("attempted to use private field on non-instance"); 986 } 987 988 return receiver; 989 } 990 991 babelHelpers.classPrivateFieldLooseBase = _classPrivateFieldBase; 992 993 function _classPrivateFieldGet(receiver, privateMap) { 994 if (!privateMap.has(receiver)) { 995 throw new TypeError("attempted to get private field on non-instance"); 996 } 997 998 return privateMap.get(receiver).value; 999 } 1000 1001 babelHelpers.classPrivateFieldGet = _classPrivateFieldGet; 1002 1003 function _classPrivateFieldSet(receiver, privateMap, value) { 1004 if (!privateMap.has(receiver)) { 1005 throw new TypeError("attempted to set private field on non-instance"); 1006 } 1007 1008 var descriptor = privateMap.get(receiver); 1009 1010 if (!descriptor.writable) { 1011 throw new TypeError("attempted to set read only private field"); 1012 } 1013 1014 descriptor.value = value; 1015 return value; 1016 } 1017 1018 babelHelpers.classPrivateFieldSet = _classPrivateFieldSet; 1019})(typeof global === "undefined" ? window : global); 1020 1021/** 1022 * Copyright (c) 2014-present, Facebook, Inc. 1023 * 1024 * This source code is licensed under the MIT license found in the 1025 * LICENSE file in the root directory of this source tree. 1026 */ 1027 1028!(function(global) { 1029 "use strict"; 1030 1031 var Op = Object.prototype; 1032 var hasOwn = Op.hasOwnProperty; 1033 var undefined; // More compressible than void 0. 1034 var $Symbol = typeof Symbol === "function" ? Symbol : {}; 1035 var iteratorSymbol = $Symbol.iterator || "@@iterator"; 1036 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; 1037 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; 1038 1039 // Define the runtime globally (as expected by generated code) as either 1040 // module.exports (if we're in a module) or a new, empty object. 1041 var runtime = global.regeneratorRuntime = {}; 1042 1043 function wrap(innerFn, outerFn, self, tryLocsList) { 1044 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. 1045 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; 1046 var generator = Object.create(protoGenerator.prototype); 1047 var context = new Context(tryLocsList || []); 1048 1049 // The ._invoke method unifies the implementations of the .next, 1050 // .throw, and .return methods. 1051 generator._invoke = makeInvokeMethod(innerFn, self, context); 1052 1053 return generator; 1054 } 1055 runtime.wrap = wrap; 1056 1057 // Try/catch helper to minimize deoptimizations. Returns a completion 1058 // record like context.tryEntries[i].completion. This interface could
vendor: 10,591 bytes, lines 1059-1352
1059 // have been (and was previously) designed to take a closure to be 1060 // invoked without arguments, but in all the cases we care about we 1061 // already have an existing method we want to call, so there's no need 1062 // to create a new function object. We can even get away with assuming 1063 // the method takes exactly one argument, since that happens to be true 1064 // in every case, so we don't have to touch the arguments object. The 1065 // only additional allocation required is the completion record, which 1066 // has a stable shape and so hopefully should be cheap to allocate. 1067 function tryCatch(fn, obj, arg) { 1068 try { 1069 return { type: "normal", arg: fn.call(obj, arg) }; 1070 } catch (err) { 1071 return { type: "throw", arg: err }; 1072 } 1073 } 1074 1075 var GenStateSuspendedStart = "suspendedStart"; 1076 var GenStateSuspendedYield = "suspendedYield"; 1077 var GenStateExecuting = "executing"; 1078 var GenStateCompleted = "completed"; 1079 1080 // Returning this object from the innerFn has the same effect as 1081 // breaking out of the dispatch switch statement. 1082 var ContinueSentinel = {}; 1083 1084 // Dummy constructor functions that we use as the .constructor and 1085 // .constructor.prototype properties for functions that return Generator 1086 // objects. For full spec compliance, you may wish to configure your 1087 // minifier not to mangle the names of these two functions. 1088 function Generator() {} 1089 function GeneratorFunction() {} 1090 function GeneratorFunctionPrototype() {} 1091 1092 // This is a polyfill for %IteratorPrototype% for environments that 1093 // don't natively support it. 1094 var IteratorPrototype = {}; 1095 IteratorPrototype[iteratorSymbol] = function () { 1096 return this; 1097 }; 1098 1099 var getProto = Object.getPrototypeOf; 1100 var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); 1101 if (NativeIteratorPrototype && 1102 NativeIteratorPrototype !== Op && 1103 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { 1104 // This environment has a native %IteratorPrototype%; use it instead 1105 // of the polyfill. 1106 IteratorPrototype = NativeIteratorPrototype; 1107 } 1108 1109 var Gp = GeneratorFunctionPrototype.prototype = 1110 Generator.prototype = Object.create(IteratorPrototype); 1111 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; 1112 GeneratorFunctionPrototype.constructor = GeneratorFunction; 1113 GeneratorFunctionPrototype[toStringTagSymbol] = 1114 GeneratorFunction.displayName = "GeneratorFunction"; 1115 1116 // Helper for defining the .next, .throw, and .return methods of the 1117 // Iterator interface in terms of a single ._invoke method. 1118 function defineIteratorMethods(prototype) { 1119 ["next", "throw", "return"].forEach(function(method) { 1120 prototype[method] = function(arg) { 1121 return this._invoke(method, arg); 1122 }; 1123 }); 1124 } 1125 1126 runtime.isGeneratorFunction = function(genFun) { 1127 var ctor = typeof genFun === "function" && genFun.constructor; 1128 return ctor 1129 ? ctor === GeneratorFunction || 1130 // For the native GeneratorFunction constructor, the best we can 1131 // do is to check its .name property. 1132 (ctor.displayName || ctor.name) === "GeneratorFunction" 1133 : false; 1134 }; 1135 1136 runtime.mark = function(genFun) { 1137 if (Object.setPrototypeOf) { 1138 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); 1139 } else { 1140 genFun.__proto__ = GeneratorFunctionPrototype; 1141 if (!(toStringTagSymbol in genFun)) { 1142 genFun[toStringTagSymbol] = "GeneratorFunction"; 1143 } 1144 } 1145 genFun.prototype = Object.create(Gp); 1146 return genFun; 1147 }; 1148 1149 // Within the body of any async function, `await x` is transformed to 1150 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test 1151 // `hasOwn.call(value, "__await")` to determine if the yielded value is 1152 // meant to be awaited. 1153 runtime.awrap = function(arg) { 1154 return { __await: arg }; 1155 }; 1156 1157 function AsyncIterator(generator) { 1158 function invoke(method, arg, resolve, reject) { 1159 var record = tryCatch(generator[method], generator, arg); 1160 if (record.type === "throw") { 1161 reject(record.arg); 1162 } else { 1163 var result = record.arg; 1164 var value = result.value; 1165 if (value && 1166 typeof value === "object" && 1167 hasOwn.call(value, "__await")) { 1168 return Promise.resolve(value.__await).then(function(value) { 1169 invoke("next", value, resolve, reject); 1170 }, function(err) { 1171 invoke("throw", err, resolve, reject); 1172 }); 1173 } 1174 1175 return Promise.resolve(value).then(function(unwrapped) { 1176 // When a yielded Promise is resolved, its final value becomes 1177 // the .value of the Promise<{value,done}> result for the 1178 // current iteration. If the Promise is rejected, however, the 1179 // result for this iteration will be rejected with the same 1180 // reason. Note that rejections of yielded Promises are not 1181 // thrown back into the generator function, as is the case 1182 // when an awaited Promise is rejected. This difference in 1183 // behavior between yield and await is important, because it 1184 // allows the consumer to decide what to do with the yielded 1185 // rejection (swallow it and continue, manually .throw it back 1186 // into the generator, abandon iteration, whatever). With 1187 // await, by contrast, there is no opportunity to examine the 1188 // rejection reason outside the generator function, so the 1189 // only option is to throw it from the await expression, and 1190 // let the generator function handle the exception. 1191 result.value = unwrapped; 1192 resolve(result); 1193 }, reject); 1194 } 1195 } 1196 1197 var previousPromise; 1198 1199 function enqueue(method, arg) { 1200 function callInvokeWithMethodAndArg() { 1201 return new Promise(function(resolve, reject) { 1202 invoke(method, arg, resolve, reject); 1203 }); 1204 } 1205 1206 return previousPromise = 1207 // If enqueue has been called before, then we want to wait until 1208 // all previous Promises have been resolved before calling invoke, 1209 // so that results are always delivered in the correct order. If 1210 // enqueue has not been called before, then it is important to 1211 // call invoke immediately, without waiting on a callback to fire, 1212 // so that the async generator function has the opportunity to do 1213 // any necessary setup in a predictable way. This predictability 1214 // is why the Promise constructor synchronously invokes its 1215 // executor callback, and why async functions synchronously 1216 // execute code before the first await. Since we implement simple 1217 // async functions in terms of async generators, it is especially 1218 // important to get this right, even though it requires care. 1219 previousPromise ? previousPromise.then( 1220 callInvokeWithMethodAndArg, 1221 // Avoid propagating failures to Promises returned by later 1222 // invocations of the iterator. 1223 callInvokeWithMethodAndArg 1224 ) : callInvokeWithMethodAndArg(); 1225 } 1226 1227 // Define the unified helper method that is used to implement .next, 1228 // .throw, and .return (see defineIteratorMethods). 1229 this._invoke = enqueue; 1230 } 1231 1232 defineIteratorMethods(AsyncIterator.prototype); 1233 AsyncIterator.prototype[asyncIteratorSymbol] = function () { 1234 return this; 1235 }; 1236 runtime.AsyncIterator = AsyncIterator; 1237 1238 // Note that simple async functions are implemented on top of 1239 // AsyncIterator objects; they just return a Promise for the value of 1240 // the final result produced by the iterator. 1241 runtime.async = function(innerFn, outerFn, self, tryLocsList) { 1242 var iter = new AsyncIterator( 1243 wrap(innerFn, outerFn, self, tryLocsList) 1244 ); 1245 1246 return runtime.isGeneratorFunction(outerFn) 1247 ? iter // If outerFn is a generator, return the full iterator. 1248 : iter.next().then(function(result) { 1249 return result.done ? result.value : iter.next(); 1250 }); 1251 }; 1252 1253 function makeInvokeMethod(innerFn, self, context) { 1254 var state = GenStateSuspendedStart; 1255 1256 return function invoke(method, arg) { 1257 if (state === GenStateExecuting) { 1258 throw new Error("Generator is already running"); 1259 } 1260 1261 if (state === GenStateCompleted) { 1262 if (method === "throw") { 1263 throw arg; 1264 } 1265 1266 // Be forgiving, per 25.3.3.3.3 of the spec: 1267 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume 1268 return doneResult(); 1269 } 1270 1271 context.method = method; 1272 context.arg = arg; 1273 1274 while (true) { 1275 var delegate = context.delegate; 1276 if (delegate) { 1277 var delegateResult = maybeInvokeDelegate(delegate, context); 1278 if (delegateResult) { 1279 if (delegateResult === ContinueSentinel) continue; 1280 return delegateResult; 1281 } 1282 } 1283 1284 if (context.method === "next") { 1285 // Setting context._sent for legacy support of Babel's 1286 // function.sent implementation. 1287 context.sent = context._sent = context.arg; 1288 1289 } else if (context.method === "throw") { 1290 if (state === GenStateSuspendedStart) { 1291 state = GenStateCompleted; 1292 throw context.arg; 1293 } 1294 1295 context.dispatchException(context.arg); 1296 1297 } else if (context.method === "return") { 1298 context.abrupt("return", context.arg); 1299 } 1300 1301 state = GenStateExecuting; 1302 1303 var record = tryCatch(innerFn, self, context); 1304 if (record.type === "normal") { 1305 // If an exception is thrown from innerFn, we leave state === 1306 // GenStateExecuting and loop back for another invocation. 1307 state = context.done 1308 ? GenStateCompleted 1309 : GenStateSuspendedYield; 1310 1311 if (record.arg === ContinueSentinel) { 1312 continue; 1313 } 1314 1315 return { 1316 value: record.arg, 1317 done: context.done 1318 }; 1319 1320 } else if (record.type === "throw") { 1321 state = GenStateCompleted; 1322 // Dispatch the exception by looping back around to the 1323 // context.dispatchException(context.arg) call above. 1324 context.method = "throw"; 1325 context.arg = record.arg; 1326 } 1327 } 1328 }; 1329 } 1330 1331 // Call delegate.iterator[context.method](context.arg) and handle the 1332 // result, either by returning a { value, done } result from the 1333 // delegate iterator, or by modifying context.method and context.arg, 1334 // setting context.delegate to null, and returning the ContinueSentinel. 1335 function maybeInvokeDelegate(delegate, context) { 1336 var method = delegate.iterator[context.method]; 1337 if (method === undefined) { 1338 // A .throw or .return when the delegate iterator has no .throw 1339 // method always terminates the yield* loop. 1340 context.delegate = null; 1341 1342 if (context.method === "throw") { 1343 if (delegate.iterator.return) { 1344 // If the delegate iterator has a return method, give it a 1345 // chance to clean up. 1346 context.method = "return"; 1347 context.arg = undefined; 1348 maybeInvokeDelegate(delegate, context); 1349 1350 if (context.method === "throw") { 1351 // If maybeInvokeDelegate(context) changed context.method from 1352 // "return" to "throw", let that override the TypeError below.
vendor: 4,172 bytes, lines 1353-1506
1353 return ContinueSentinel; 1354 } 1355 } 1356 1357 context.method = "throw"; 1358 context.arg = new TypeError( 1359 "The iterator does not provide a 'throw' method"); 1360 } 1361 1362 return ContinueSentinel; 1363 } 1364 1365 var record = tryCatch(method, delegate.iterator, context.arg); 1366 1367 if (record.type === "throw") { 1368 context.method = "throw"; 1369 context.arg = record.arg; 1370 context.delegate = null; 1371 return ContinueSentinel; 1372 } 1373 1374 var info = record.arg; 1375 1376 if (! info) { 1377 context.method = "throw"; 1378 context.arg = new TypeError("iterator result is not an object"); 1379 context.delegate = null; 1380 return ContinueSentinel; 1381 } 1382 1383 if (info.done) { 1384 // Assign the result of the finished delegate to the temporary 1385 // variable specified by delegate.resultName (see delegateYield). 1386 context[delegate.resultName] = info.value; 1387 1388 // Resume execution at the desired location (see delegateYield). 1389 context.next = delegate.nextLoc; 1390 1391 // If context.method was "throw" but the delegate handled the 1392 // exception, let the outer generator proceed normally. If 1393 // context.method was "next", forget context.arg since it has been 1394 // "consumed" by the delegate iterator. If context.method was 1395 // "return", allow the original .return call to continue in the 1396 // outer generator. 1397 if (context.method !== "return") { 1398 context.method = "next"; 1399 context.arg = undefined; 1400 } 1401 1402 } else { 1403 // Re-yield the result returned by the delegate method. 1404 return info; 1405 } 1406 1407 // The delegate iterator is finished, so forget it and continue with 1408 // the outer generator. 1409 context.delegate = null; 1410 return ContinueSentinel; 1411 } 1412 1413 // Define Generator.prototype.{next,throw,return} in terms of the 1414 // unified ._invoke helper method. 1415 defineIteratorMethods(Gp); 1416 1417 Gp[toStringTagSymbol] = "Generator"; 1418 1419 // A Generator should always return itself as the iterator object when the 1420 // @@iterator function is called on it. Some browsers' implementations of the 1421 // iterator prototype chain incorrectly implement this, causing the Generator 1422 // object to not be returned from this call. This ensures that doesn't happen. 1423 // See https://github.com/facebook/regenerator/issues/274 for more details. 1424 Gp[iteratorSymbol] = function() { 1425 return this; 1426 }; 1427 1428 Gp.toString = function() { 1429 return "[object Generator]"; 1430 }; 1431 1432 function pushTryEntry(locs) { 1433 var entry = { tryLoc: locs[0] }; 1434 1435 if (1 in locs) { 1436 entry.catchLoc = locs[1]; 1437 } 1438 1439 if (2 in locs) { 1440 entry.finallyLoc = locs[2]; 1441 entry.afterLoc = locs[3]; 1442 } 1443 1444 this.tryEntries.push(entry); 1445 } 1446 1447 function resetTryEntry(entry) { 1448 var record = entry.completion || {}; 1449 record.type = "normal"; 1450 delete record.arg; 1451 entry.completion = record; 1452 } 1453 1454 function Context(tryLocsList) { 1455 // The root entry object (effectively a try statement without a catch 1456 // or a finally block) gives us a place to store values thrown from 1457 // locations where there is no enclosing try statement. 1458 this.tryEntries = [{ tryLoc: "root" }]; 1459 tryLocsList.forEach(pushTryEntry, this); 1460 this.reset(true); 1461 } 1462 1463 runtime.keys = function(object) { 1464 var keys = []; 1465 for (var key in object) { 1466 keys.push(key); 1467 } 1468 keys.reverse(); 1469 1470 // Rather than returning an object with a next method, we keep 1471 // things simple and return the next function itself. 1472 return function next() { 1473 while (keys.length) { 1474 var key = keys.pop(); 1475 if (key in object) { 1476 next.value = key; 1477 next.done = false; 1478 return next; 1479 } 1480 } 1481 1482 // To avoid creating an additional object, we just hang the .value 1483 // and .done properties off the next function object itself. This 1484 // also ensures that the minifier will not anonymize the function. 1485 next.done = true; 1486 return next; 1487 }; 1488 }; 1489 1490 function values(iterable) { 1491 if (iterable) { 1492 var iteratorMethod = iterable[iteratorSymbol]; 1493 if (iteratorMethod) { 1494 return iteratorMethod.call(iterable); 1495 } 1496 1497 if (typeof iterable.next === "function") { 1498 return iterable; 1499 } 1500 1501 if (!isNaN(iterable.length)) { 1502 var i = -1, next = function next() { 1503 while (++i < iterable.length) { 1504 if (hasOwn.call(iterable, i)) { 1505 next.value = iterable[i]; 1506 next.done = false;
vendor: 6,037 bytes, lines 1507-1760
1507 return next; 1508 } 1509 } 1510 1511 next.value = undefined; 1512 next.done = true; 1513 1514 return next; 1515 }; 1516 1517 return next.next = next; 1518 } 1519 } 1520 1521 // Return an iterator with no values. 1522 return { next: doneResult }; 1523 } 1524 runtime.values = values; 1525 1526 function doneResult() { 1527 return { value: undefined, done: true }; 1528 } 1529 1530 Context.prototype = { 1531 constructor: Context, 1532 1533 reset: function(skipTempReset) { 1534 this.prev = 0; 1535 this.next = 0; 1536 // Resetting context._sent for legacy support of Babel's 1537 // function.sent implementation. 1538 this.sent = this._sent = undefined; 1539 this.done = false; 1540 this.delegate = null; 1541 1542 this.method = "next"; 1543 this.arg = undefined; 1544 1545 this.tryEntries.forEach(resetTryEntry); 1546 1547 if (!skipTempReset) { 1548 for (var name in this) { 1549 // Not sure about the optimal order of these conditions: 1550 if (name.charAt(0) === "t" && 1551 hasOwn.call(this, name) && 1552 !isNaN(+name.slice(1))) { 1553 this[name] = undefined; 1554 } 1555 } 1556 } 1557 }, 1558 1559 stop: function() { 1560 this.done = true; 1561 1562 var rootEntry = this.tryEntries[0]; 1563 var rootRecord = rootEntry.completion; 1564 if (rootRecord.type === "throw") { 1565 throw rootRecord.arg; 1566 } 1567 1568 return this.rval; 1569 }, 1570 1571 dispatchException: function(exception) { 1572 if (this.done) { 1573 throw exception; 1574 } 1575 1576 var context = this; 1577 function handle(loc, caught) { 1578 record.type = "throw"; 1579 record.arg = exception; 1580 context.next = loc; 1581 1582 if (caught) { 1583 // If the dispatched exception was caught by a catch block, 1584 // then let that catch block handle the exception normally. 1585 context.method = "next"; 1586 context.arg = undefined; 1587 } 1588 1589 return !! caught; 1590 } 1591 1592 for (var i = this.tryEntries.length - 1; i >= 0; --i) { 1593 var entry = this.tryEntries[i]; 1594 var record = entry.completion; 1595 1596 if (entry.tryLoc === "root") { 1597 // Exception thrown outside of any try block that could handle 1598 // it, so set the completion value of the entire function to 1599 // throw the exception. 1600 return handle("end"); 1601 } 1602 1603 if (entry.tryLoc <= this.prev) { 1604 var hasCatch = hasOwn.call(entry, "catchLoc"); 1605 var hasFinally = hasOwn.call(entry, "finallyLoc"); 1606 1607 if (hasCatch && hasFinally) { 1608 if (this.prev < entry.catchLoc) { 1609 return handle(entry.catchLoc, true); 1610 } else if (this.prev < entry.finallyLoc) { 1611 return handle(entry.finallyLoc); 1612 } 1613 1614 } else if (hasCatch) { 1615 if (this.prev < entry.catchLoc) { 1616 return handle(entry.catchLoc, true); 1617 } 1618 1619 } else if (hasFinally) { 1620 if (this.prev < entry.finallyLoc) { 1621 return handle(entry.finallyLoc); 1622 } 1623 1624 } else { 1625 throw new Error("try statement without catch or finally"); 1626 } 1627 } 1628 } 1629 }, 1630 1631 abrupt: function(type, arg) { 1632 for (var i = this.tryEntries.length - 1; i >= 0; --i) { 1633 var entry = this.tryEntries[i]; 1634 if (entry.tryLoc <= this.prev && 1635 hasOwn.call(entry, "finallyLoc") && 1636 this.prev < entry.finallyLoc) { 1637 var finallyEntry = entry; 1638 break; 1639 } 1640 } 1641 1642 if (finallyEntry && 1643 (type === "break" || 1644 type === "continue") && 1645 finallyEntry.tryLoc <= arg && 1646 arg <= finallyEntry.finallyLoc) { 1647 // Ignore the finally entry if control is not jumping to a 1648 // location outside the try/catch block. 1649 finallyEntry = null; 1650 } 1651 1652 var record = finallyEntry ? finallyEntry.completion : {}; 1653 record.type = type; 1654 record.arg = arg; 1655 1656 if (finallyEntry) { 1657 this.method = "next"; 1658 this.next = finallyEntry.finallyLoc; 1659 return ContinueSentinel; 1660 } 1661 1662 return this.complete(record); 1663 }, 1664 1665 complete: function(record, afterLoc) { 1666 if (record.type === "throw") { 1667 throw record.arg; 1668 } 1669 1670 if (record.type === "break" || 1671 record.type === "continue") { 1672 this.next = record.arg; 1673 } else if (record.type === "return") { 1674 this.rval = this.arg = record.arg; 1675 this.method = "return"; 1676 this.next = "end"; 1677 } else if (record.type === "normal" && afterLoc) { 1678 this.next = afterLoc; 1679 } 1680 1681 return ContinueSentinel; 1682 }, 1683 1684 finish: function(finallyLoc) { 1685 for (var i = this.tryEntries.length - 1; i >= 0; --i) { 1686 var entry = this.tryEntries[i]; 1687 if (entry.finallyLoc === finallyLoc) { 1688 this.complete(entry.completion, entry.afterLoc); 1689 resetTryEntry(entry); 1690 return ContinueSentinel; 1691 } 1692 } 1693 }, 1694 1695 "catch": function(tryLoc) { 1696 for (var i = this.tryEntries.length - 1; i >= 0; --i) { 1697 var entry = this.tryEntries[i]; 1698 if (entry.tryLoc === tryLoc) { 1699 var record = entry.completion; 1700 if (record.type === "throw") { 1701 var thrown = record.arg; 1702 resetTryEntry(entry); 1703 } 1704 return thrown; 1705 } 1706 } 1707 1708 // The context.catch method must only be called with a location 1709 // argument that corresponds to a known catch block. 1710 throw new Error("illegal catch attempt"); 1711 }, 1712 1713 delegateYield: function(iterable, resultName, nextLoc) { 1714 this.delegate = { 1715 iterator: values(iterable), 1716 resultName: resultName, 1717 nextLoc: nextLoc 1718 }; 1719 1720 if (this.method === "next") { 1721 // Deliberately forget the last sent value so that we don't 1722 // accidentally pass it on to the delegate. 1723 this.arg = undefined; 1724 } 1725 1726 return ContinueSentinel; 1727 } 1728 }; 1729})( 1730 // In sloppy mode, unbound `this` refers to the global object, fallback to 1731 // Function constructor if we're in global strict mode. That is sadly a form 1732 // of indirect eval which violates Content Security Policy. 1733 (function() { return this })() || Function("return this")() 1734); 1735 1736if (window._main_polyfill_core) 1737{ 1738 console.warn('main.polyfill.core is loaded more than once on this page'); 1739} 1740 1741window._main_polyfill_core = true; 1742 1743 1744(function (exports) { 1745 'use strict'; 1746 1747 const bxTmp = window.BX; 1748 window.BX = function (node) { 1749 if (window.BX.type.isNotEmptyString(node)) { 1750 return document.getElementById(node); 1751 } 1752 if (window.BX.type.isDomNode(node)) { 1753 return node; 1754 } 1755 if (window.BX.type.isFunction(node)) { 1756 return window.BX.ready(node); 1757 } 1758 return null; 1759 }; 1760 if (bxTmp) {
1761 Object.keys(bxTmp).forEach(key => { 1762 window.BX[key] = bxTmp[key]; 1763 }); 1764 } 1765 exports = window.BX; 1766 1767 function getTag(value) { 1768 return Object.prototype.toString.call(value); 1769 } 1770 1771 const objectCtorString = Function.prototype.toString.call(Object); 1772 class Type { 1773 static isString(value) { 1774 return typeof value === 'string'; 1775 } 1776 static isStringFilled(value) { 1777 return Type.isString(value) && value !== ''; 1778 } 1779 static isFunction(value) { 1780 return typeof value === 'function'; 1781 } 1782 static isObject(value) { 1783 return Boolean(value) && (typeof value === 'object' || typeof value === 'function'); 1784 } 1785 static isObjectLike(value) { 1786 return Boolean(value) && typeof value === 'object'; 1787 } 1788 static isPlainObject(value) { 1789 if (!Type.isObjectLike(value) || getTag(value) !== '[object Object]') { 1790 return false; 1791 } 1792 const proto = Object.getPrototypeOf(value); 1793 if (proto === null) { 1794 return true; 1795 } 1796 const ctor = proto.hasOwnProperty('constructor') && proto.constructor; 1797 return typeof ctor === 'function' && Function.prototype.toString.call(ctor) === objectCtorString; 1798 } 1799 static isBoolean(value) { 1800 return value === true || value === false; 1801 } 1802 static isNumber(value) { 1803 return !Number.isNaN(value) && typeof value === 'number'; 1804 } 1805 static isInteger(value) { 1806 return Type.isNumber(value) && value % 1 === 0; 1807 } 1808 static isFloat(value) { 1809 return Type.isNumber(value) && !Type.isInteger(value); 1810 } 1811 static isNil(value) { 1812 return value === null || value === undefined; 1813 } 1814 static isArray(value) { 1815 return !Type.isNil(value) && Array.isArray(value); 1816 } 1817 static isArrayFilled(value) { 1818 return Type.isArray(value) && value.length > 0; 1819 } 1820 static isArrayLike(value) { 1821 if (Type.isNil(value) || Type.isFunction(value) || !('length' in value)) { 1822 return false; 1823 } 1824 const { 1825 length 1826 } = value; 1827 return Type.isNumber(length) && length > -1 && length <= Number.MAX_SAFE_INTEGER; 1828 } 1829 static isDate(value) { 1830 return Type.isObjectLike(value) && getTag(value) === '[object Date]'; 1831 } 1832 static isDomNode(value) { 1833 return Type.isObjectLike(value) && !Type.isPlainObject(value) && 'nodeType' in value; 1834 } 1835 static isElementNode(value) { 1836 return Type.isDomNode(value) && value.nodeType === Node.ELEMENT_NODE; 1837 } 1838 static isEventTargetLike(value) { 1839 return Type.isObjectLike(value) && Type.isFunction(value.addEventListener) && Type.isFunction(value.removeEventListener) && Type.isFunction(value.dispatchEvent); 1840 } 1841 static isTextNode(value) { 1842 return Type.isDomNode(value) && value.nodeType === Node.TEXT_NODE; 1843 } 1844 static isMap(value) { 1845 return Type.isObjectLike(value) && getTag(value) === '[object Map]'; 1846 } 1847 static isSet(value) { 1848 return Type.isObjectLike(value) && getTag(value) === '[object Set]'; 1849 } 1850 static isWeakMap(value) { 1851 return Type.isObjectLike(value) && getTag(value) === '[object WeakMap]'; 1852 } 1853 static isWeakSet(value) { 1854 return Type.isObjectLike(value) && getTag(value) === '[object WeakSet]'; 1855 } 1856 static isPrototype(value) { 1857 if (!Type.isObjectLike(value)) { 1858 return false; 1859 } 1860 const ctor = value.constructor; 1861 const proto = Type.isFunction(ctor) ? ctor.prototype : Object.prototype; 1862 return proto === value; 1863 } 1864 static isRegExp(value) { 1865 return Type.isObjectLike(value) && getTag(value) === '[object RegExp]'; 1866 } 1867 static isNull(value) { 1868 return value === null; 1869 } 1870 static isUndefined(value) { 1871 return typeof value === 'undefined'; 1872 } 1873 static isArrayBuffer(value) { 1874 return Type.isObjectLike(value) && getTag(value) === '[object ArrayBuffer]'; 1875 } 1876 static isTypedArray(value) { 1877 const regExpTypedTag = /^\[object (?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)]$/; 1878 return Type.isObjectLike(value) && regExpTypedTag.test(getTag(value)); 1879 } 1880 static isBlob(value) { 1881 return Type.isObjectLike(value) && Type.isNumber(value.size) && Type.isString(value.type) && Type.isFunction(value.slice); 1882 } 1883 static isFile(value) { 1884 if (!Type.isBlob(value) || !('name' in value) || !Type.isString(value.name)) { 1885 return false; 1886 } 1887 if ('lastModified' in value && Type.isNumber(value.lastModified)) { 1888 return true; 1889 } 1890 return 'lastModifiedDate' in value && Type.isObjectLike(value.lastModifiedDate); 1891 } 1892 static isFormData(value) { 1893 return value instanceof FormData; 1894 } 1895 static isJsonValue(value) { 1896 return Type.isPlainObject(value) || Type.isString(value) || Type.isNumber(value) || Type.isBoolean(value) || Type.isNull(value) || Type.isArray(value); 1897 } 1898 } 1899 1900 class Reflection { 1901 static getClass(className) { 1902 if (Type.isString(className) && Boolean(className)) { 1903 let classFn = null; 1904 let currentNamespace = window; 1905 const namespaces = className.split('.'); 1906 for (const namespace of namespaces) { 1907 if (!currentNamespace[namespace]) { 1908 return null; 1909 } 1910 currentNamespace = currentNamespace[namespace]; 1911 classFn = currentNamespace; 1912 } 1913 return classFn; 1914 } 1915 if (Type.isFunction(className)) { 1916 return className; 1917 } 1918 return null; 1919 } 1920 static namespace(namespaceName) { 1921 let parts = namespaceName.split('.'); 1922 let parent = window.BX; 1923 if (parts[0] === 'BX') { 1924 parts = parts.slice(1); 1925 } 1926 for (const part of parts) { 1927 if (Type.isUndefined(parent[part])) { 1928 parent[part] = {}; 1929 } 1930 parent = parent[part]; 1931 } 1932 return parent; 1933 } 1934 } 1935 1936 const reEscape = /["&'<>]/g; 1937 const reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g; 1938 const escapeEntities = { 1939 '&': '&', 1940 '<': '<', 1941 '>': '>', 1942 "'": ''', 1943 '"': '"' 1944 }; 1945 const unescapeEntities = { 1946 '&': '&', 1947 '&': '&', 1948 '<': '<', 1949 '<': '<', 1950 '>': '>', 1951 '>': '>', 1952 ''': "'", 1953 ''': "'", 1954 '"': '"', 1955 '"': '"' 1956 }; 1957 class Text { 1958 static encode(value) { 1959 if (Type.isString(value)) { 1960 return value.replaceAll(reEscape, item => escapeEntities[item]); 1961 } 1962 return value; 1963 } 1964 static decode(value) { 1965 if (Type.isString(value)) { 1966 return value.replaceAll(reUnescape, item => unescapeEntities[item]); 1967 } 1968 return value; 1969 } 1970 static getRandom(length = 8) { 1971 return Array.from({ 1972 length 1973 }, () => Math.trunc(Math.random() * 36).toString(36)).join(''); 1974 } 1975 static toNumber(value) { 1976 const parsedValue = Number.parseFloat(String(value)); 1977 if (Type.isNumber(parsedValue)) { 1978 return parsedValue; 1979 } 1980 return 0; 1981 } 1982 static toInteger(value) { 1983 return Text.toNumber(Number.parseInt(String(value), 10)); 1984 } 1985 static toBoolean(value, trueValues = []) { 1986 const transformedValue = Type.isString(value) ? value.toLowerCase() : value; 1987 const truthyValues = ['true', 'y', '1', 1, true, ...trueValues]; 1988 return truthyValues.includes(transformedValue); 1989 } 1990 static toCamelCase(str) { 1991 if (!Type.isStringFilled(str)) { 1992 return str; 1993 } 1994 const regex = /[\s_-]+(.)?/g; 1995 if (!regex.test(str)) { 1996 return /^[A-Z]+$/.test(str) ? str.toLowerCase() : str[0].toLowerCase() + str.slice(1); 1997 } 1998 const result = str.toLowerCase().replaceAll(regex, (match, letter) => { 1999 return letter ? letter.toUpperCase() : ''; 2000 }); 2001 return result[0].toLowerCase() + result.slice(1); 2002 } 2003 static toPascalCase(str) { 2004 if (!Type.isStringFilled(str)) { 2005 return str; 2006 } 2007 return this.capitalize(this.toCamelCase(str)); 2008 } 2009 static toKebabCase(str) { 2010 if (!Type.isStringFilled(str)) { 2011 return str; 2012 } 2013 const matches = str.match(/[A-Z]{2,}(?=[A-Z][a-z]+\d*|\b)|[A-Z]?[a-z]+\d*|[A-Z]|\d+/g); 2014 if (!matches) { 2015 return str; 2016 } 2017 return matches.map(x => x.toLowerCase()).join('-'); 2018 } 2019 static capitalize(str) { 2020 if (!Type.isStringFilled(str)) { 2021 return str; 2022 } 2023 return str[0].toUpperCase() + str.slice(1); 2024 } 2025 } 2026 2027 const aliases = { 2028 mousewheel: ['DOMMouseScroll'], 2029 bxchange: ['change', 'cut', 'paste', 'drop', 'keyup'], 2030 animationend: ['animationend', 'oAnimationEnd', 'webkitAnimationEnd', 'MSAnimationEnd'], 2031 transitionend: ['webkitTransitionEnd', 'otransitionend', 'oTransitionEnd', 'msTransitionEnd', 'transitionend'], 2032 fullscreenchange: ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], 2033 fullscreenerror: ['fullscreenerror', 'webkitfullscreenerror', 'mozfullscreenerror', 'MSFullscreenError'] 2034 }; 2035 2036 class Registry { 2037 registry = new WeakMap(); 2038 set(target, event, listener) { 2039 if (!Type.isEventTargetLike(target)) { 2040 return; 2041 } 2042 const events = this.get(target); 2043 if (!Type.isSet(events[event])) { 2044 events[event] = new Set(); 2045 } 2046 events[event].add(listener); 2047 this.registry.set(target, events); 2048 } 2049 get(target) { 2050 return this.registry.get(target) || {}; 2051 } 2052 has(target, event, listener) { 2053 if (event && listener) { 2054 const events = this.registry.get(target); 2055 return this.registry.has(target) && Boolean(events && events[event]?.has(listener)); 2056 } 2057 return this.registry.has(target); 2058 } 2059 delete(target, event, listener) { 2060 if (!Type.isEventTargetLike(target)) { 2061 return; 2062 } 2063 if (Type.isString(event) && Type.isFunction(listener)) { 2064 const events = this.registry.get(target); 2065 if (Type.isPlainObject(events) && Type.isSet(events[event])) { 2066 events[event].delete(listener); 2067 } 2068 return; 2069 } 2070 if (Type.isString(event)) { 2071 const events = this.registry.get(target); 2072 if (Type.isPlainObject(events) && Type.isSet(events[event])) { 2073 events[event] = new Set(); 2074 } 2075 return; 2076 } 2077 this.registry.delete(target); 2078 } 2079 } 2080 var registry = new Registry(); 2081 2082 function isOptionSupported(name) { 2083 let isSupported = false;
2084 try { 2085 const options = Object.defineProperty({}, name, { 2086 get() { 2087 isSupported = true; 2088 } 2089 }); 2090 window.addEventListener('test', null, options); 2091 } catch { 2092 } 2093 return isSupported; 2094 } 2095 function fetchSupportedListenerOptions(options) { 2096 if (!Type.isPlainObject(options)) { 2097 return options; 2098 } 2099 return Object.keys(options).reduce((acc, name) => { 2100 if (isOptionSupported(name)) { 2101 acc[name] = options[name]; 2102 } 2103 return acc; 2104 }, {}); 2105 } 2106 2107 function bind$1(target, eventName, handler, options) { 2108 if (!Type.isEventTargetLike(target) || handler === null) { 2109 return; 2110 } 2111 const listenerOptions = fetchSupportedListenerOptions(options); 2112 if (eventName in aliases) { 2113 aliases[eventName].forEach(key => { 2114 target.addEventListener(key, handler, listenerOptions); 2115 registry.set(target, eventName, handler); 2116 }); 2117 return; 2118 } 2119 target.addEventListener(eventName, handler, listenerOptions); 2120 registry.set(target, eventName, handler); 2121 } 2122 2123 function unbind$1(target, eventName, handler, options) { 2124 if (!Type.isEventTargetLike(target) || handler === null) { 2125 return; 2126 } 2127 const listenerOptions = fetchSupportedListenerOptions(options); 2128 if (eventName in aliases) { 2129 aliases[eventName].forEach(key => { 2130 target.removeEventListener(key, handler, listenerOptions); 2131 registry.delete(target, key, handler); 2132 }); 2133 return; 2134 } 2135 target.removeEventListener(eventName, handler, listenerOptions); 2136 registry.delete(target, eventName, handler); 2137 } 2138 2139 function unbindAll$1(target, eventName) { 2140 const events = registry.get(target); 2141 Object.keys(events).forEach(currentEvent => { 2142 events[currentEvent].forEach(handler => { 2143 if (!Type.isString(eventName) || eventName === currentEvent) { 2144 unbind$1(target, currentEvent, handler); 2145 } 2146 }); 2147 }); 2148 } 2149 2150 function bindOnce$1(target, eventName, handler, options) { 2151 if (handler === null) { 2152 return; 2153 } 2154 const once = function once(event) { 2155 unbind$1(target, eventName, once, options); 2156 if (Type.isFunction(handler)) { 2157 handler(event); 2158 } else if (Type.isObject(handler) && Type.isFunction(handler.handleEvent)) { 2159 handler.handleEvent(event); 2160 } 2161 }; 2162 bind$1(target, eventName, once, options); 2163 } 2164 2165 let debugState = true; 2166 function enableDebug() { 2167 debugState = true; 2168 } 2169 function disableDebug() { 2170 debugState = false; 2171 } 2172 function isDebugEnabled() { 2173 return debugState; 2174 } 2175 function debug$1(...args) { 2176 if (!isDebugEnabled() || !Type.isObject(window.console)) { 2177 return; 2178 } 2179 let limit = 5; 2180 if (typeof args[args.length - 1] === 'number') { 2181 limit = args.pop(); 2182 } 2183 if (Type.isFunction(window.console.log)) { 2184 window.console.log('BX.debug:', ...args); 2185 if (args[0] instanceof Error && args[0].stack) { 2186 const errorStack = args[0].stack.split('\n').slice(0, limit).join('\n'); 2187 window.console.log(`BX.debug error stack trace:\n${errorStack}`); 2188 } 2189 } 2190 const stack = new Error('debug').stack; 2191 if (stack && Type.isFunction(window.console.log)) { 2192 const formattedStack = stack.split('\n').slice(1, limit + 1).join('\n'); 2193 window.console.log(`BX.debug trace:\n${formattedStack}`); 2194 } 2195 } 2196 2197 var debugNs = Object.freeze({ 2198 __proto__: null, 2199 get debugState () { return debugState; }, 2200 default: debug$1, 2201 disableDebug: disableDebug, 2202 enableDebug: enableDebug, 2203 isDebugEnabled: isDebugEnabled 2204 }); 2205 2206 const extensionsStorage = new Map(); 2207 2208 const ajaxController = 'main.bitrix.main.controller.loadext.getextensions'; 2209 function loadAssets(options) { 2210 return new Promise((resolve, reject) => { 2211 const getParameters = { 2212 e: (options?.extension || []).join(',') 2213 }; 2214 BX.ajax.runAction(ajaxController, { 2215 data: options, 2216 getParameters 2217 }).then(result => { 2218 resolve(result?.data); 2219 }).catch(err => { 2220 reject(err); 2221 }); 2222 }); 2223 } 2224 2225 function fetchInlineScripts(acc, item) { 2226 if (item.isInternal) { 2227 acc.push(item.JS); 2228 } 2229 return acc; 2230 } 2231 function fetchExternalScripts(acc, item) { 2232 if (!item.isInternal) { 2233 acc.push(item.JS); 2234 } 2235 return acc; 2236 } 2237 function fetchExternalStyles(acc, item) { 2238 if (Type.isString(item) && item !== '') { 2239 acc.push(item); 2240 } 2241 return acc; 2242 } 2243 function fetchExtensionSettings(html) { 2244 if (Type.isStringFilled(html)) { 2245 const scripts = html.match(/<script type="extension\/settings" \b[^>]*>([\S\s]*?)<\/script>/g); 2246 if (Type.isArrayFilled(scripts)) { 2247 return scripts.map(script => { 2248 const [, extension] = script.match(/data-extension="(.[\d._a-z-]+)"/); 2249 return { 2250 extension, 2251 script 2252 }; 2253 }); 2254 } 2255 } 2256 return []; 2257 } 2258 function loadAll(items) { 2259 const itemsList = Type.isArray(items) ? items : [items]; 2260 if (itemsList.length === 0) { 2261 return Promise.resolve(); 2262 } 2263 return new Promise((resolve, reject) => { 2264 BX.load(itemsList, resolve, document, reject); 2265 }); 2266 } 2267 2268 function parseExtensionHtml(html) { 2269 const result = window.BX.processHTML(html); 2270 const inlinePreScripts = []; 2271 const inlineAfterScripts = []; 2272 result.SCRIPT.reduce((accumulator, element) => { 2273 return fetchInlineScripts(accumulator, element); 2274 }
2274, []).forEach(script => { 2275 if (script.startsWith('BX.Runtime.registerExtension')) { 2276 inlineAfterScripts.push(script); 2277 } else { 2278 inlinePreScripts.push(script); 2279 } 2280 }); 2281 return { 2282 inlinePreScripts, 2283 inlineAfterScripts, 2284 externalScripts: result.SCRIPT.reduce((accumulator, element) => { 2285 return fetchExternalScripts(accumulator, element); 2286 }, []), 2287 externalStyles: result.STYLE.reduce((accumulator, element) => { 2288 return fetchExternalStyles(accumulator, element); 2289 }, []), 2290 settingsScripts: fetchExtensionSettings(result.HTML) 2291 }; 2292 } 2293 2294 function waitOnline() { 2295 return new Promise(resolve => { 2296 Event.bindOnce(window, 'online', () => resolve()); 2297 }); 2298 } 2299 2300 const TIMEOUTS = [1000, 3000, 5000]; 2301 async function tryLoad(extensions, callback) { 2302 for (let i = 0; i <= TIMEOUTS.length; i++) { 2303 try { 2304 return await callback(); 2305 } catch { 2306 if (navigator.onLine === false) { 2307 console.warn(`Wait online for load ${extensions.join(', ')}`); 2308 await waitOnline(); 2309 i--; 2310 continue; 2311 } 2312 if (i === TIMEOUTS.length) { 2313 throw new Error(`${extensions.join(', ')} loading failed...`); 2314 } 2315 const delay = TIMEOUTS[i]; 2316 const displayRetryCount = i + 1; 2317 console.warn(`Retry load #${displayRetryCount}: ${extensions.join(', ')}`); 2318 await new Promise(resolve => { 2319 setTimeout(resolve, delay); 2320 }); 2321 } 2322 } 2323 throw new Error('Unexpected end of retry loop'); 2324 } 2325 2326 async function processExtensions(map) { 2327 const loadableExtensions = [...map.keys()]; 2328 const rawAssets = (await tryLoad(loadableExtensions, () => loadAssets({ 2329 extension: loadableExtensions 2330 }))) ?? []; 2331 rawAssets.forEach(rawAsset => { 2332 const preparedHtml = rawAsset.html ?? '';
2333 const extensionAssets = parseExtensionHtml(preparedHtml); 2334 extensionAssets.settingsScripts.forEach(({ 2335 script 2336 }) => { 2337 document.body.insertAdjacentHTML('beforeend', script); 2338 }); 2339 extensionAssets.inlinePreScripts.forEach(script => { 2340 window.BX.evalGlobal(script); 2341 }); 2342 const loadableExtensionEntry = map.get(rawAsset.extension); 2343 void Promise.all([tryLoad(loadableExtensions, () => loadAll(extensionAssets.externalScripts)), tryLoad(loadableExtensions, () => loadAll(extensionAssets.externalStyles))]).then(() => { 2344 extensionAssets.inlineAfterScripts.forEach(script => { 2345 window.BX.evalGlobal(script); 2346 }); 2347 const namespace = rawAsset?.config?.namespace ?? 'window'; 2348 loadableExtensionEntry.resolve(namespace); 2349 }).catch(error => { 2350 loadableExtensionEntry.reject(error); 2351 }); 2352 }); 2353 } 2354 2355 const queue = new Map(); 2356 let timerId = null; 2357 async function loadExtension(...name) { 2358 if (Type.isNumber(timerId)) { 2359 clearTimeout(timerId); 2360 } 2361 const requestedNames = name.flat(); 2362 const extensionsToLoad = requestedNames.filter(extensionName => { 2363 return !extensionsStorage.has(extensionName); 2364 }); 2365 extensionsToLoad.forEach(extensionName => { 2366 let resolve = null; 2367 let reject = null; 2368 const loadableExtensionEntry = { 2369 promise: new Promise((sourceResolve, sourceReject) => { 2370 resolve = sourceResolve; 2371 reject = sourceReject; 2372 }), 2373 resolve, 2374 reject 2375 }; 2376 extensionsStorage.set(extensionName, loadableExtensionEntry.promise); 2377 queue.set(extensionName, loadableExtensionEntry); 2378 }); 2379 timerId = setTimeout(() => { 2380 if (queue.size > 0) { 2381 void processExtensions(new Map(queue.entries())); 2382 queue.clear(); 2383 } 2384 }); 2385 const namespaces = await Promise.all(requestedNames.map(extensionName => { 2386 return extensionsStorage.get(extensionName); 2387 })); 2388 return namespaces.reduce((acc, namespace) => { 2389 return { 2390 ...acc, 2391 ...Reflection.getClass(namespace) 2392 }; 2393 }, {}); 2394 } 2395 2396 const cloneableTags = new Set(['[object Object]', '[object Array]', '[object RegExp]', '[object Arguments]', '[object Date]', '[object Error]', '[object Map]', '[object Set]', '[object ArrayBuffer]', '[object DataView]', '[object Float32Array]', '[object Float64Array]', '[object Int8Array]', '[object Int16Array]', '[object Int32Array]', '[object Uint8Array]', '[object Uint16Array]', '[object Uint32Array]', '[object Uint8ClampedArray]']); 2397 function isCloneable(value) { 2398 const isCloneableValue = Type.isObjectLike(value) && cloneableTags.has(getTag(value)); 2399 return isCloneableValue || Type.isDomNode(value); 2400 } 2401 function internalClone(value, map) { 2402 if (map.has(value)) { 2403 return map.get(value); 2404 } 2405 if (isCloneable(value)) { 2406 if (Type.isArray(value)) { 2407 const cloned = [...value]; 2408 map.set(value, cloned); 2409 value.forEach((item, index) => { 2410 cloned[index] = internalClone(item, map); 2411 }); 2412 return map.get(value); 2413 } 2414 if (Type.isDomNode(value)) { 2415 return value.cloneNode(true); 2416 } 2417 if (Type.isMap(value)) { 2418 const result = new Map(); 2419 map.set(value, result); 2420 value.forEach((item, key) => { 2421 result.set(internalClone(key, map), internalClone(item, map)); 2422 }); 2423 return result; 2424 } 2425 if (Type.isSet(value)) { 2426 const result = new Set(); 2427 map.set(value, result); 2428 value.forEach(item => { 2429 result.add(internalClone(item, map)); 2430 }); 2431 return result; 2432 } 2433 if (Type.isDate(value)) { 2434 return new Date(value); 2435 } 2436 if (Type.isRegExp(value)) { 2437 const regExpFlags = /\w*$/; 2438 const flags = regExpFlags.exec(value); 2439 let result = new RegExp(value.source); 2440 if (flags && Type.isArray(flags)) { 2441 result = new RegExp(value.source, flags[0]); 2442 } 2443 result.lastIndex = value.lastIndex; 2444 return result; 2445 } 2446 const proto = Object.getPrototypeOf(value); 2447 const result = Object.assign(Object.create(proto), value); 2448 map.set(value, result); 2449 Object.keys(value).forEach(key => { 2450 result[key] = internalClone(value[key], map); 2451 }); 2452 return result; 2453 } 2454 return value; 2455 } 2456 function clone$1(value) { 2457 return internalClone(value, new WeakMap()); 2458 } 2459 2460 function merge(current, target) { 2461 return Object.entries(target).reduce((acc, [key, value]) => { 2462 if (!Type.isDomNode(acc[key]) && Type.isObjectLike(acc[key]) && Type.isObjectLike(value)) { 2463 acc[key] = merge(acc[key], value); 2464 return acc; 2465 } 2466 acc[key] = value; 2467 return acc; 2468 }, current); 2469 } 2470 2471 function createComparator(fields, orders = []) { 2472 return (a, b) => { 2473 const field = fields[0]; 2474 const order = orders[0] || 'asc'; 2475 if (Type.isUndefined(field)) { 2476 return 0; 2477 } 2478 let valueA = a[field]; 2479 let valueB = b[field]; 2480 if (Type.isString(valueA) && Type.isString(valueB)) { 2481 valueA = valueA.toLowerCase(); 2482 valueB = valueB.toLowerCase(); 2483 } 2484 if (valueA < valueB) { 2485 return order === 'asc' ? -1 : 1; 2486 } 2487 if (valueA > valueB) { 2488 return order === 'asc' ? 1 : -1; 2489 } 2490 return createComparator(fields.slice(1), orders.slice(1))(a, b); 2491 }; 2492 } 2493 2494 function registerExtension(options) { 2495 if (!extensionsStorage.has(options.name)) { 2496 const namespace = options?.namespace ?? 'window'; 2497 extensionsStorage.set(options.name, Promise.resolve(namespace)); 2498 } 2499 } 2500 2501 class Runtime { 2502 static debug = debug$1; 2503 static loadExtension = loadExtension; 2504 static registerExtension = registerExtension; 2505 static clone = clone$1; 2506 static debounce(func, wait = 0, context = null) { 2507 let timeoutId = null; 2508 return function debounced(...args) { 2509 if (Type.isNumber(timeoutId)) { 2510 clearTimeout(timeoutId); 2511 } 2512 timeoutId = setTimeout(() => { 2513 func.apply(context || this, args); 2514 }, wait); 2515 }; 2516 } 2517 static throttle(func, wait = 0, context = null) { 2518 let timer = null; 2519 let invoke = false;
2520 return function wrapper(...args) { 2521 invoke = true; 2522 if (!timer) { 2523 const q = function q() { 2524 if (invoke) { 2525 func.apply(context || this, args); 2526 invoke = false; 2527 timer = setTimeout(q, wait); 2528 } else { 2529 timer = null; 2530 } 2531 }; 2532 q(); 2533 } 2534 }; 2535 } 2536 static html(node, html, params = {}) { 2537 if (Type.isNil(html) && Type.isDomNode(node)) { 2538 return node.innerHTML; 2539 } 2540 const parsedHtml = BX.processHTML(html); 2541 const externalCss = parsedHtml.STYLE.reduce((acc, item) => fetchExternalStyles(acc, item), []); 2542 const externalJs = parsedHtml.SCRIPT.reduce((acc, item) => fetchExternalScripts(acc, item), []); 2543 const inlineJs = parsedHtml.SCRIPT.reduce((acc, item) => fetchInlineScripts(acc, item), []); 2544 if (Type.isDomNode(node) && (params.htmlFirst || externalJs.length === 0 && externalCss.length === 0)) { 2545 if (params.useAdjacentHTML) { 2546 node.insertAdjacentHTML('beforeend', parsedHtml.HTML); 2547 } else { 2548 node.innerHTML = parsedHtml.HTML; 2549 } 2550 } 2551 return Promise.all([loadAll(externalJs), loadAll(externalCss)]).then(() => { 2552 if (Type.isDomNode(node) && (externalJs.length > 0 || externalCss.length > 0)) { 2553 if (params.useAdjacentHTML) { 2554 node.insertAdjacentHTML('beforeend', parsedHtml.HTML); 2555 } else { 2556 node.innerHTML = parsedHtml.HTML; 2557 } 2558 } 2559 inlineJs.forEach(script => BX.evalGlobal(script)); 2560 if (Type.isFunction(params.callback)) { 2561 params.callback(); 2562 } 2563 }); 2564 } 2565 static merge(...targets) { 2566 if (Type.isArray(targets[0])) { 2567 targets.unshift([]); 2568 } else if (Type.isObject(targets[0])) { 2569 targets.unshift({}); 2570 } 2571 return targets.reduce((acc, item) => { 2572 return merge(acc, item); 2573 }, targets[0]); 2574 } 2575 static orderBy(collection, fields = [], orders = []) { 2576 const comparator = createComparator(fields, orders); 2577 return Object.values(collection).sort(comparator); 2578 } 2579 static destroy(target, errorMessage = 'Object is destroyed') { 2580 if (Type.isObject(target)) { 2581 const onPropertyAccess = () => { 2582 throw new Error(errorMessage); 2583 }; 2584 const ownProperties = Object.keys(target); 2585 const prototypeProperties = (() => { 2586 const targetPrototype = Object.getPrototypeOf(target); 2587 if (Type.isObject(targetPrototype)) { 2588 return Object.getOwnPropertyNames(targetPrototype); 2589 } 2590 return []; 2591 })(); 2592 const uniquePropertiesList = [...new Set([...ownProperties, ...prototypeProperties])]; 2593 uniquePropertiesList.filter(name => { 2594 const descriptor = Object.getOwnPropertyDescriptor(target, name); 2595 return !/__(.+)__/.test(name) && (!Type.isObject(descriptor) || descriptor.configurable === true); 2596 }
2596).forEach(name => { 2597 Object.defineProperty(target, name, { 2598 get: onPropertyAccess, 2599 set: onPropertyAccess, 2600 configurable: false 2601 }); 2602 }); 2603 Object.setPrototypeOf(target, null); 2604 } 2605 } 2606 } 2607 2608 const isError = Symbol.for('BX.BaseError.isError'); 2609 class BaseError { 2610 [isError]; 2611 message; 2612 code; 2613 customData; 2614 constructor(message, code, customData) { 2615 this[isError] = true; 2616 this.message = ''; 2617 this.code = null; 2618 this.customData = null; 2619 this.setMessage(message); 2620 this.setCode(code); 2621 this.setCustomData(customData); 2622 } 2623 getMessage() { 2624 return this.message; 2625 } 2626 setMessage(message) { 2627 if (Type.isString(message)) { 2628 this.message = message; 2629 } 2630 return this; 2631 } 2632 getCode() { 2633 return this.code; 2634 } 2635 setCode(code) { 2636 if (Type.isStringFilled(code) || code === null) { 2637 this.code = code; 2638 } 2639 return this; 2640 } 2641 getCustomData() { 2642 return this.customData; 2643 } 2644 setCustomData(customData) { 2645 if (!Type.isUndefined(customData)) { 2646 this.customData = customData; 2647 } 2648 return this; 2649 } 2650 toString() { 2651 const code = this.getCode(); 2652 const message = this.getMessage(); 2653 if (!Type.isStringFilled(code) && !Type.isStringFilled(message)) { 2654 return ''; 2655 } 2656 if (!Type.isStringFilled(code)) { 2657 return `Error: ${message}`; 2658 } 2659 if (!Type.isStringFilled(message)) { 2660 return code; 2661 } 2662 return `${code}: ${message}`; 2663 } 2664 static isError(error) { 2665 return Type.isObject(error) && error[isError] === true; 2666 } 2667 } 2668 2669 let BaseEvent = function () { 2670 function BaseEvent(options = { 2671 data: {} 2672 }) { 2673 babelHelpers.classCallCheck(this, BaseEvent); 2674 babelHelpers.defineProperty(this, "type", ''); 2675 babelHelpers.defineProperty(this, "data", null); 2676 babelHelpers.defineProperty(this, "target", null); 2677 babelHelpers.defineProperty(this, "compatData", null); 2678 babelHelpers.defineProperty(this, "defaultPrevented", false); 2679 babelHelpers.defineProperty(this, "immediatePropagationStopped", false); 2680 babelHelpers.defineProperty(this, "errors", []); 2681 this.setData(options.data); 2682 this.setCompatData(options.compatData); 2683 } 2684 return babelHelpers.createClass(BaseEvent, [{ 2685 key: "getType", 2686 value: 2687 function getType() { 2688 return this.type; 2689 } 2690 }, { 2691 key: "setType", 2692 value: function setType(type) { 2693 if (Type.isStringFilled(type)) { 2694 this.type = type; 2695 } 2696 return this; 2697 } 2698 }, { 2699 key: "getData", 2700 value: function getData() { 2701 return this.data; 2702 } 2703 }, { 2704 key: "setData", 2705 value: function setData(data) { 2706 if (!Type.isUndefined(data)) { 2707 this.data = data; 2708 } 2709 return this; 2710 } 2711 }, { 2712 key: "getCompatData", 2713 value: function getCompatData() { 2714 return this.compatData; 2715 } 2716 }, { 2717 key: "setCompatData", 2718 value: function setCompatData(data) { 2719 if (Type.isArrayLike(data)) { 2720 this.compatData = data; 2721 } 2722 return this; 2723 } 2724 }, { 2725 key: "setTarget", 2726 value: function setTarget(target) { 2727 this.target = target; 2728 return this; 2729 } 2730 }, { 2731 key: "getTarget", 2732 value: function getTarget() { 2733 return this.target; 2734 } 2735 }, { 2736 key: "getErrors", 2737 value: function getErrors() { 2738 return this.errors; 2739 } 2740 }, { 2741 key: "setError", 2742 value: function setError(error) { 2743 if (BaseError.isError(error)) { 2744 this.errors.push(error); 2745 } 2746 } 2747 }, { 2748 key: "preventDefault", 2749 value: function preventDefault() { 2750 this.defaultPrevented = true; 2751 } 2752 }, { 2753 key: "isDefaultPrevented", 2754 value: function isDefaultPrevented() { 2755 return this.defaultPrevented; 2756 } 2757 }, { 2758 key: "stopImmediatePropagation", 2759 value: function stopImmediatePropagation() { 2760 this.immediatePropagationStopped = true; 2761 } 2762 }, { 2763 key: "isImmediatePropagationStopped", 2764 value: function isImmediatePropagationStopped() { 2765 return this.immediatePropagationStopped; 2766 } 2767 }], [{ 2768 key: "create", 2769 value: function create(options) { 2770 return new this(options); 2771 } 2772 }]); 2773 }(); 2774 2775 class EventStore { 2776 defaultMaxListeners; 2777 eventStore = new WeakMap(); 2778 constructor(options = {}) { 2779 this.defaultMaxListeners = Type.isNumber(options.defaultMaxListeners) ? options.defaultMaxListeners : 10; 2780 } 2781 add(target, options = {}) { 2782 const record = this.getRecordScheme(); 2783 if (Type.isNumber(options.maxListeners)) { 2784 record.maxListeners = options.maxListeners; 2785 } 2786 this.eventStore.set(target, record); 2787 return record; 2788 } 2789 get(target) { 2790 return this.eventStore.get(target); 2791 } 2792 getOrAdd(target, options = {}) { 2793 return this.get(target) || this.add(target, options); 2794 } 2795 delete(context) { 2796 this.eventStore.delete(context); 2797 } 2798 getRecordScheme() { 2799 return { 2800 eventsMap: new Map(), 2801 onceMap: new Map(), 2802 maxListeners: this.getDefaultMaxListeners(), 2803 eventsMaxListeners: new Map() 2804 }; 2805 } 2806 getDefaultMaxListeners() { 2807 return this.defaultMaxListeners; 2808 } 2809 } 2810 2811 class WarningStore { 2812 warnings = new Map(); 2813 printDelayed; 2814 constructor() { 2815 this.printDelayed = Runtime.debounce(this.print.bind(this), 500); 2816 } 2817 add(target, eventName, listeners) { 2818 let contextWarnings = this.warnings.get(target); 2819 if (!contextWarnings) { 2820 contextWarnings = Object.create(null); 2821 this.warnings.set(target, contextWarnings); 2822 } 2823 if (!contextWarnings[eventName]) { 2824 contextWarnings[eventName] = {}; 2825 } 2826 contextWarnings[eventName].size = listeners.size; 2827 if (!Type.isArray(contextWarnings[eventName].errors)) { 2828 contextWarnings[eventName].errors = []; 2829 } 2830 contextWarnings[eventName].errors.push(new Error('EventEmitter warning')); 2831 } 2832 print() {
2833 this.warnings.forEach(warnings => { 2834 for (const eventName of Object.keys(warnings)) { 2835 console.groupCollapsed('Possible BX.Event.EventEmitter memory leak detected. ' + `${warnings[eventName].size} "${eventName}" listeners added. ` + 'Use emitter.setMaxListeners() to increase limit.'); 2836 console.dir(warnings[eventName].errors); 2837 console.groupEnd(); 2838 } 2839 }); 2840 this.clear(); 2841 } 2842 clear() { 2843 this.warnings.clear(); 2844 } 2845 } 2846 2847 const eventStore = new EventStore({ 2848 defaultMaxListeners: 10 2849 }); 2850 const warningStore = new WarningStore(); 2851 const aliasStore = new Map(); 2852 const globalTarget = { 2853 GLOBAL_TARGET: 'GLOBAL_TARGET' 2854 }; 2855 eventStore.add(globalTarget, { 2856 maxListeners: 25 2857 }); 2858 const isEmitterProperty = Symbol.for('BX.Event.EventEmitter.isEmitter'); 2859 const namespaceProperty = Symbol('namespaceProperty'); 2860 const targetProperty = Symbol('targetProperty'); 2861 let EventEmitter = function () { 2862 function EventEmitter(...args) { 2863 babelHelpers.classCallCheck(this, EventEmitter); 2864 this[targetProperty] = null; 2865 this[namespaceProperty] = null; 2866 this[isEmitterProperty] = true; 2867 let target = this; 2868 if (Object.getPrototypeOf(this) === EventEmitter.prototype && args.length > 0) { 2869 if (!Type.isObject(args[0])) { 2870 throw new TypeError('The "target" argument must be an object.'); 2871 } 2872 target = args[0]; 2873 this.setEventNamespace(args[1]); 2874 } 2875 this[targetProperty] = target; 2876 } 2877 return babelHelpers.createClass(EventEmitter, [{ 2878 key: "setEventNamespace", 2879 value: function setEventNamespace(namespace) { 2880 if (Type.isStringFilled(namespace)) { 2881 this[namespaceProperty] = namespace; 2882 } 2883 } 2884 }, { 2885 key: "getEventNamespace", 2886 value: function getEventNamespace() { 2887 return this[namespaceProperty]; 2888 } 2889 }, { 2890 key: "subscribe", 2891 value: 2892 function subscribe(eventName, listener) { 2893 EventEmitter.subscribe(this, eventName, listener); 2894 return this; 2895 } 2896 }, { 2897 key: "subscribeFromOptions", 2898 value: function subscribeFromOptions(options, aliases, compatMode) { 2899 if (Type.isArrayFilled(options)) { 2900 options.forEach(events => { 2901 this.subscribeFromOptions(events); 2902 }); 2903 return; 2904 } 2905 if (!Type.isPlainObject(options)) { 2906 return; 2907 } 2908 const normalizedAliases = Type.isPlainObject(aliases) ? EventEmitter.normalizeAliases(aliases) : {}; 2909 const optionsRecord = options; 2910 Object.keys(optionsRecord).forEach(eventName => { 2911 const listener = EventEmitter.normalizeListener(optionsRecord[eventName]); 2912 eventName = EventEmitter.normalizeEventName(eventName); 2913 if (normalizedAliases[eventName]) { 2914 const { 2915 eventName: actualName 2916 } = normalizedAliases[eventName]; 2917 EventEmitter.subscribe(this, actualName, listener, { 2918 compatMode: compatMode !== false 2919 }); 2920 } else { 2921 EventEmitter.subscribe(this, eventName, listener, { 2922 compatMode: compatMode === true 2923 }); 2924 } 2925 }); 2926 } 2927 }, { 2928 key: "subscribeOnce", 2929 value: 2930 function subscribeOnce(eventName, listener) { 2931 EventEmitter.subscribeOnce(this, eventName, listener); 2932 return this; 2933 } 2934 }, { 2935 key: "unsubscribe", 2936 value: 2937 function unsubscribe(eventName, listener) { 2938 EventEmitter.unsubscribe(this, eventName, listener); 2939 return this; 2940 } 2941 }, { 2942 key: "unsubscribeAll", 2943 value: 2944 function unsubscribeAll(eventName) { 2945 EventEmitter.unsubscribeAll(this, eventName); 2946 } 2947 }, { 2948 key: "emit", 2949 value: 2950 function emit(eventName, event) { 2951 if (this.getEventNamespace() === null) { 2952 console.warn('The instance of BX.Event.EventEmitter is supposed to have an event namespace. ' + 'Use emitter.setEventNamespace() to make events more unique.'); 2953 } 2954 EventEmitter.emit(this, eventName, event); 2955 return this; 2956 } 2957 }, { 2958 key: "emitAsync", 2959 value: 2960 function emitAsync(eventName, event) { 2961 if (this.getEventNamespace() === null) { 2962 console.warn('The instance of BX.Event.EventEmitter is supposed to have an event namespace. ' + 'Use emitter.setEventNamespace() to make events more unique.'); 2963 } 2964 return EventEmitter.emitAsync(this, eventName, event); 2965 } 2966 }, { 2967 key: "setMaxListeners", 2968 value: 2969 function setMaxListeners(...args) { 2970 EventEmitter.setMaxListeners(this, ...args); 2971 return this; 2972 } 2973 }, { 2974 key: "getMaxListeners", 2975 value: 2976 function getMaxListeners(eventName) { 2977 return EventEmitter.getMaxListeners(this, eventName); 2978 } 2979 }, { 2980 key: "incrementMaxListeners", 2981 value: 2982 function incrementMaxListeners(...args) { 2983 return EventEmitter.incrementMaxListeners(this, ...args); 2984 } 2985 }, { 2986 key: "decrementMaxListeners", 2987 value: 2988 function decrementMaxListeners(...args) { 2989 return EventEmitter.decrementMaxListeners(this, ...args); 2990 } 2991 }, { 2992 key: "getListeners", 2993 value: 2994 function getListeners(eventName) { 2995 return EventEmitter.getListeners(this, eventName); 2996 } 2997 }, { 2998 key: "getFullEventName", 2999 value: function getFullEventName(eventName) { 3000 if (!Type.isStringFilled(eventName)) { 3001 throw new TypeError('The "eventName" argument must be a string.'); 3002 } 3003 return EventEmitter.makeFullEventName(this.getEventNamespace(), eventName); 3004 } 3005 }], [{ 3006 key: "makeObservable", 3007 value: function makeObservable(target, namespace) { 3008 if (!Type.isObject(target)) { 3009 throw new TypeError('The "target" argument must be an object.'); 3010 } 3011 if (!Type.isStringFilled(namespace)) { 3012 throw new TypeError('The "namespace" must be an non-empty string.'); 3013 } 3014 if (EventEmitter.isEventEmitter(target)) { 3015 throw new TypeError('The "target" is an event emitter already.'); 3016 } 3017 const targetProto = Object.getPrototypeOf(target); 3018 const emitter = new EventEmitter(); 3019 emitter.setEventNamespace(namespace); 3020 Object.setPrototypeOf(emitter, targetProto); 3021 Object.setPrototypeOf(target, emitter); 3022 Object.getOwnPropertyNames(EventEmitter.prototype).forEach(method => {
3023 if (['constructor'].includes(method)) { 3024 return; 3025 } 3026 emitter[method] = function (...args) { 3027 return EventEmitter.prototype[method].apply(target, args); 3028 }; 3029 }); 3030 } 3031 }, { 3032 key: "subscribe", 3033 value: function subscribe(target, eventName, listener, options) { 3034 if (Type.isString(target)) { 3035 options = listener; 3036 listener = eventName; 3037 eventName = target; 3038 target = this.GLOBAL_TARGET; 3039 } 3040 if (!Type.isObject(target)) { 3041 throw new TypeError('The "target" argument must be an object.'); 3042 } 3043 eventName = this.normalizeEventName(eventName); 3044 if (!Type.isStringFilled(eventName)) { 3045 throw new TypeError('The "eventName" argument must be a string.'); 3046 } 3047 listener = this.normalizeListener(listener); 3048 options = Type.isPlainObject(options) ? options : {}; 3049 const fullEventName = this.resolveEventName(eventName, target, options.useGlobalNaming === true); 3050 const { 3051 eventsMap, 3052 onceMap 3053 } = eventStore.getOrAdd(target); 3054 const onceListeners = onceMap.get(fullEventName); 3055 let listeners = eventsMap.get(fullEventName); 3056 if (listeners && listeners.has(listener) || onceListeners && onceListeners.has(listener)) { 3057 console.error(`You cannot subscribe the same "${fullEventName}" event listener twice.`); 3058 } else if (listeners) { 3059 listeners.set(listener, { 3060 listener, 3061 options, 3062 sort: this.getNextSequenceValue() 3063 }); 3064 } else { 3065 listeners = new Map([[listener, { 3066 listener, 3067 options, 3068 sort: this.getNextSequenceValue() 3069 }]]); 3070 eventsMap.set(fullEventName, listeners); 3071 } 3072 const maxListeners = this.getMaxListeners(target, eventName); 3073 if (listeners.size > maxListeners) { 3074 warningStore.add(target, fullEventName, listeners); 3075 warningStore.printDelayed(); 3076 } 3077 } 3078 }, { 3079 key: "subscribeOnce", 3080 value: function subscribeOnce(target, eventName, listener) { 3081 if (Type.isString(target)) { 3082 listener = eventName; 3083 eventName = target; 3084 target = this.GLOBAL_TARGET;
3085 } 3086 if (!Type.isObject(target)) { 3087 throw new TypeError('The "target" argument must be an object.'); 3088 } 3089 eventName = this.normalizeEventName(eventName); 3090 if (!Type.isStringFilled(eventName)) { 3091 throw new TypeError('The "eventName" argument must be a string.'); 3092 } 3093 listener = this.normalizeListener(listener); 3094 const fullEventName = this.resolveEventName(eventName, target); 3095 const { 3096 eventsMap, 3097 onceMap 3098 } = eventStore.getOrAdd(target); 3099 const listeners = eventsMap.get(fullEventName); 3100 let onceListeners = onceMap.get(fullEventName); 3101 if (listeners && listeners.has(listener) || onceListeners && onceListeners.has(listener)) { 3102 console.error(`You cannot subscribe the same "${fullEventName}" event listener twice.`); 3103 } else { 3104 const once = (...args) => { 3105 this.unsubscribe(target, eventName, once); 3106 onceListeners.delete(listener); 3107 listener(...args); 3108 }; 3109 if (onceListeners) { 3110 onceListeners.set(listener, once); 3111 } else { 3112 onceListeners = new Map([[listener, once]]); 3113 onceMap.set(fullEventName, onceListeners); 3114 } 3115 this.subscribe(target, eventName, once); 3116 } 3117 } 3118 }, { 3119 key: "unsubscribe", 3120 value: function unsubscribe(target, eventName, listener, options) { 3121 if (Type.isString(target)) { 3122 listener = eventName; 3123 eventName = target; 3124 target = this.GLOBAL_TARGET;
3125 } 3126 eventName = this.normalizeEventName(eventName); 3127 if (!Type.isStringFilled(eventName)) { 3128 throw new TypeError('The "eventName" argument must be a string.'); 3129 } 3130 listener = this.normalizeListener(listener); 3131 options = Type.isPlainObject(options) ? options : {}; 3132 const fullEventName = this.resolveEventName(eventName, target, options.useGlobalNaming === true); 3133 const targetInfo = eventStore.get(target); 3134 const listeners = targetInfo && targetInfo.eventsMap.get(fullEventName); 3135 const onceListeners = targetInfo && targetInfo.onceMap.get(fullEventName); 3136 if (listeners) { 3137 listeners.delete(listener); 3138 } 3139 if (onceListeners) { 3140 const once = onceListeners.get(listener); 3141 if (once) { 3142 onceListeners.delete(listener); 3143 listeners.delete(once); 3144 } 3145 } 3146 } 3147 }, { 3148 key: "unsubscribeAll", 3149 value: function unsubscribeAll(target, eventName, options) { 3150 if (Type.isString(target)) { 3151 eventName = target; 3152 target = this.GLOBAL_TARGET; 3153 } 3154 if (Type.isStringFilled(eventName)) { 3155 const targetInfo = eventStore.get(target); 3156 if (targetInfo) { 3157 options = Type.isPlainObject(options) ? options : {}; 3158 const fullEventName = this.resolveEventName(eventName, target, options.useGlobalNaming === true); 3159 targetInfo.eventsMap.delete(fullEventName); 3160 targetInfo.onceMap.delete(fullEventName); 3161 } 3162 } else if (Type.isNil(eventName)) { 3163 if (target === this.GLOBAL_TARGET) { 3164 console.error('You cannot unsubscribe all global listeners.'); 3165 } else { 3166 eventStore.delete(target); 3167 } 3168 } 3169 } 3170 }, { 3171 key: "emit", 3172 value: function emit(target, eventName, event, options) { 3173 if (Type.isString(target)) { 3174 options = event; 3175 event = eventName; 3176 eventName = target; 3177 target = this.GLOBAL_TARGET;
3178 } 3179 if (!Type.isObject(target)) { 3180 throw new TypeError('The "target" argument must be an object.'); 3181 } 3182 eventName = this.normalizeEventName(eventName); 3183 if (!Type.isStringFilled(eventName)) { 3184 throw new TypeError('The "eventName" argument must be a string.'); 3185 } 3186 options = Type.isPlainObject(options) ? options : {}; 3187 const fullEventName = this.resolveEventName(eventName, target, options.useGlobalNaming === true); 3188 const globalEvents = eventStore.get(this.GLOBAL_TARGET); 3189 const globalListeners = globalEvents && globalEvents.eventsMap.get(fullEventName) || new Map(); 3190 let targetListeners = new Set(); 3191 if (target !== this.GLOBAL_TARGET) { 3192 const targetEvents = eventStore.get(target); 3193 targetListeners = targetEvents && targetEvents.eventsMap.get(fullEventName) || new Map(); 3194 } 3195 const listeners = [...globalListeners.values(), ...targetListeners.values()]; 3196 listeners.sort((a, b) => { 3197 return a.sort - b.sort; 3198 }); 3199 const preparedEvent = this.prepareEvent(target, fullEventName, event); 3200 const result = []; 3201 for (const { 3202 listener, 3203 options: listenerOptions 3204 } of listeners) { 3205 if (preparedEvent.isImmediatePropagationStopped()) { 3206 break; 3207 } 3208 if (globalListeners.has(listener) || targetListeners.has(listener)) { 3209 let listenerResult = null; 3210 if (listenerOptions.compatMode) { 3211 const compatData = preparedEvent.getCompatData(); 3212 const params = compatData === null ? [preparedEvent] : options.cloneData === true ? Runtime.clone(compatData) : compatData; 3213 const context = Type.isUndefined(options.thisArg) ? target : options.thisArg; 3214 listenerResult = listener.apply(context, params); 3215 } else { 3216 listenerResult = Type.isUndefined(options.thisArg) ? listener(preparedEvent) : listener.call(options.thisArg, preparedEvent); 3217 } 3218 result.push(listenerResult); 3219 } 3220 } 3221 return result; 3222 } 3223 }, { 3224 key: "emitAsync", 3225 value: function emitAsync(target, eventName, event) { 3226 if (Type.isString(target)) { 3227 event = eventName; 3228 eventName = target; 3229 target = this.GLOBAL_TARGET;
3230 } 3231 return Promise.all(this.emit(target, eventName, event)); 3232 } 3233 }, { 3234 key: "prepareEvent", 3235 value: function prepareEvent(target, eventName, event) { 3236 const preparedEvent = event instanceof BaseEvent ? event : new BaseEvent(); 3237 if (!(event instanceof BaseEvent)) { 3238 preparedEvent.setData(event); 3239 } 3240 preparedEvent.setTarget(this.isEventEmitter(target) ? target[targetProperty] : target); 3241 preparedEvent.setType(eventName); 3242 return preparedEvent; 3243 } 3244 }, { 3245 key: "getNextSequenceValue", 3246 value: function getNextSequenceValue() { 3247 return this.sequenceValue++; 3248 } 3249 }, { 3250 key: "setMaxListeners", 3251 value: function setMaxListeners(...args) { 3252 let target = this.GLOBAL_TARGET; 3253 let eventName = null; 3254 let count = null; 3255 if (args.length === 1) { 3256 count = args[0]; 3257 } else if (args.length === 2) { 3258 if (Type.isString(args[0])) { 3259 [eventName, count] = args; 3260 } else { 3261 [target, count] = args; 3262 } 3263 } else if (args.length >= 3) { 3264 [target, eventName, count] = args; 3265 } 3266 if (!Type.isObject(target)) { 3267 throw new TypeError('The "target" argument must be an object.'); 3268 } 3269 if (eventName !== null && !Type.isStringFilled(eventName)) { 3270 throw new TypeError('The "eventName" argument must be a string.'); 3271 } 3272 if (!Type.isNumber(count) || count < 0) { 3273 throw new TypeError(`The value of "count" is out of range. It must be a non-negative number. Received ${count}.`); 3274 } 3275 const targetInfo = eventStore.getOrAdd(target); 3276 if (Type.isStringFilled(eventName)) { 3277 const fullEventName = this.resolveEventName(eventName, target); 3278 targetInfo.eventsMaxListeners.set(fullEventName, count); 3279 } else { 3280 targetInfo.maxListeners = count; 3281 } 3282 } 3283 }, { 3284 key: "getMaxListeners", 3285 value: function getMaxListeners(target, eventName) { 3286 if (Type.isString(target)) { 3287 eventName = target; 3288 target = this.GLOBAL_TARGET;
3289 } else if (Type.isNil(target)) { 3290 target = this.GLOBAL_TARGET; 3291 } 3292 if (!Type.isObject(target)) { 3293 throw new TypeError('The "target" argument must be an object.'); 3294 } 3295 const targetInfo = eventStore.get(target); 3296 if (targetInfo) { 3297 let maxListeners = targetInfo.maxListeners; 3298 if (Type.isStringFilled(eventName)) { 3299 const fullEventName = this.resolveEventName(eventName, target); 3300 maxListeners = targetInfo.eventsMaxListeners.get(fullEventName) || maxListeners; 3301 } 3302 return maxListeners; 3303 } 3304 return this.DEFAULT_MAX_LISTENERS; 3305 } 3306 }, { 3307 key: "addMaxListeners", 3308 value: function addMaxListeners(...args) { 3309 const [target, eventName, increment] = this.destructMaxListenersArgs(...args); 3310 const maxListeners = Math.max(this.getMaxListeners(target, eventName) + increment, 0); 3311 if (Type.isStringFilled(eventName)) { 3312 EventEmitter.setMaxListeners(target, eventName, maxListeners); 3313 } else { 3314 EventEmitter.setMaxListeners(target, maxListeners); 3315 } 3316 return maxListeners; 3317 } 3318 }, { 3319 key: "incrementMaxListeners", 3320 value: function incrementMaxListeners(...args) { 3321 const [target, eventName, increment] = this.destructMaxListenersArgs(...args); 3322 return this.addMaxListeners(target, eventName, Math.abs(increment)); 3323 } 3324 }, { 3325 key: "decrementMaxListeners", 3326 value: function decrementMaxListeners(...args) { 3327 const [target, eventName, increment] = this.destructMaxListenersArgs(...args); 3328 return this.addMaxListeners(target, eventName, -Math.abs(increment)); 3329 } 3330 }, { 3331 key: "destructMaxListenersArgs", 3332 value: function destructMaxListenersArgs(...args) { 3333 let eventName = null; 3334 let increment = 1; 3335 let target = this.GLOBAL_TARGET;
3336 if (args.length === 1) { 3337 if (Type.isNumber(args[0])) { 3338 increment = args[0]; 3339 } else if (Type.isString(args[0])) { 3340 eventName = args[0]; 3341 } else { 3342 target = args[0]; 3343 } 3344 } else if (args.length === 2) { 3345 if (Type.isString(args[0])) { 3346 [eventName, increment] = args; 3347 } else if (Type.isString(args[1])) { 3348 [target, eventName] = args; 3349 } else { 3350 [target, increment] = args; 3351 } 3352 } else if (args.length >= 3) { 3353 [target, eventName, increment] = args; 3354 } 3355 if (!Type.isObject(target)) { 3356 throw new TypeError('The "target" argument must be an object.'); 3357 } 3358 if (eventName !== null && !Type.isStringFilled(eventName)) { 3359 throw new TypeError('The "eventName" argument must be a string.'); 3360 } 3361 if (!Type.isNumber(increment)) { 3362 throw new TypeError('The value of "increment" must be a number.'); 3363 } 3364 return [target, eventName, increment]; 3365 } 3366 }, { 3367 key: "getListeners", 3368 value: function getListeners(target, eventName) { 3369 if (Type.isString(target)) { 3370 eventName = target; 3371 target = this.GLOBAL_TARGET;
3372 } 3373 if (!Type.isObject(target)) { 3374 throw new TypeError('The "target" argument must be an object.'); 3375 } 3376 eventName = this.normalizeEventName(eventName); 3377 if (!Type.isStringFilled(eventName)) { 3378 throw new TypeError('The "eventName" argument must be a string.'); 3379 } 3380 const targetInfo = eventStore.get(target); 3381 if (!targetInfo) { 3382 return new Map(); 3383 } 3384 const fullEventName = this.resolveEventName(eventName, target); 3385 return targetInfo.eventsMap.get(fullEventName) || new Map(); 3386 } 3387 }, { 3388 key: "registerAliases", 3389 value: function registerAliases(aliases) { 3390 const normalizedAliases = this.normalizeAliases(aliases); 3391 Object.keys(normalizedAliases).forEach(alias => { 3392 aliasStore.set(alias, { 3393 eventName: normalizedAliases[alias].eventName, 3394 namespace: normalizedAliases[alias].namespace 3395 }); 3396 }); 3397 EventEmitter.mergeEventAliases(normalizedAliases); 3398 } 3399 }, { 3400 key: "normalizeAliases", 3401 value: function normalizeAliases(aliases) { 3402 if (!Type.isPlainObject(aliases)) { 3403 throw new TypeError('The "aliases" argument must be an object.'); 3404 } 3405 const aliasesRecord = aliases; 3406 const result = Object.create(null); 3407 for (const key of Object.keys(aliasesRecord)) { 3408 if (!Type.isStringFilled(key)) { 3409 throw new TypeError('The alias must be an non-empty string.'); 3410 } 3411 const options = aliasesRecord[key]; 3412 if (!options || !Type.isStringFilled(options.eventName) || !Type.isStringFilled(options.namespace)) { 3413 throw new TypeError('The alias options must set the "eventName" and the "namespace".'); 3414 } 3415 const normalizedAlias = this.normalizeEventName(key); 3416 result[normalizedAlias] = { 3417 eventName: options.eventName, 3418 namespace: options.namespace 3419 }; 3420 } 3421 return result; 3422 } 3423 }, { 3424 key: "mergeEventAliases", 3425 value: function mergeEventAliases(aliases) { 3426 const globalEvents = eventStore.get(this.GLOBAL_TARGET); 3427 if (!globalEvents) { 3428 return; 3429 } 3430 Object.keys(aliases).forEach(alias => { 3431 const options = aliases[alias]; 3432 alias = this.normalizeEventName(alias); 3433 const fullEventName = this.makeFullEventName(options.namespace, options.eventName); 3434 const aliasListeners = globalEvents.eventsMap.get(alias); 3435 if (aliasListeners) { 3436 const listeners = globalEvents.eventsMap.get(fullEventName) || new Map(); 3437 globalEvents.eventsMap.set(fullEventName, new Map([...listeners, ...aliasListeners])); 3438 globalEvents.eventsMap.delete(alias); 3439 } 3440 const aliasOnceListeners = globalEvents.onceMap.get(alias); 3441 if (aliasOnceListeners) { 3442 const onceListeners = globalEvents.onceMap.get(fullEventName) || new Map(); 3443 globalEvents.onceMap.set(fullEventName, new Map([...onceListeners, ...aliasOnceListeners])); 3444 globalEvents.onceMap.delete(alias); 3445 } 3446 const aliasMaxListeners = globalEvents.eventsMaxListeners.get(alias); 3447 if (aliasMaxListeners) { 3448 const eventMaxListeners = globalEvents.eventsMaxListeners.get(fullEventName) || 0; 3449 globalEvents.eventsMaxListeners.set(fullEventName, Math.max(eventMaxListeners, aliasMaxListeners)); 3450 globalEvents.eventsMaxListeners.delete(alias); 3451 } 3452 }); 3453 } 3454 }, { 3455 key: "isEventEmitter", 3456 value: function isEventEmitter(target) { 3457 return Type.isObject(target) && target[isEmitterProperty] === true; 3458 } 3459 }, { 3460 key: "normalizeEventName", 3461 value: function normalizeEventName(eventName) { 3462 if (!Type.isStringFilled(eventName)) { 3463 return ''; 3464 } 3465 return eventName.toLowerCase(); 3466 } 3467 }, { 3468 key: "normalizeListener", 3469 value: function normalizeListener(listener) { 3470 if (Type.isString(listener)) { 3471 listener = Reflection.getClass(listener); 3472 } 3473 if (!Type.isFunction(listener)) { 3474 throw new TypeError(`The "listener" argument must be of type Function. Received type ${typeof listener}.`); 3475 } 3476 return listener; 3477 } 3478 }, { 3479 key: "resolveEventName", 3480 value: function resolveEventName(eventName, target, useGlobalNaming = false) { 3481 eventName = this.normalizeEventName(eventName); 3482 if (!Type.isStringFilled(eventName)) { 3483 return ''; 3484 } 3485 if (this.isEventEmitter(target) && useGlobalNaming !== true) { 3486 if (target.getEventNamespace() !== null && eventName.includes('.')) { 3487 console.warn(`Possible the wrong event name "${eventName}".`); 3488 } 3489 eventName = target.getFullEventName(eventName); 3490 } else if (aliasStore.has(eventName)) { 3491 const { 3492 namespace, 3493 eventName: actualEventName 3494 } = aliasStore.get(eventName); 3495 eventName = this.makeFullEventName(namespace, actualEventName); 3496 } 3497 return eventName; 3498 } 3499 }, { 3500 key: "makeFullEventName", 3501 value: function makeFullEventName(namespace, eventName) { 3502 const fullName = Type.isStringFilled(namespace) ? `${namespace}:${eventName}` : eventName; 3503 return Type.isStringFilled(fullName) ? fullName.toLowerCase() : ''; 3504 } 3505 }]); 3506 }(); 3507 babelHelpers.defineProperty(EventEmitter, "GLOBAL_TARGET", globalTarget); 3508 babelHelpers.defineProperty(EventEmitter, "DEFAULT_MAX_LISTENERS", eventStore.getDefaultMaxListeners()); 3509 babelHelpers.defineProperty(EventEmitter, "sequenceValue", 1); 3510 3511 let stack = []; 3512 exports.isReady = false;
3513 function ready$1(handler) { 3514 if (!Type.isFunction(handler)) { 3515 return; 3516 } 3517 if (exports.isReady) { 3518 handler(); 3519 } else { 3520 stack.push(handler); 3521 } 3522 } 3523 bindOnce$1(document, 'DOMContentLoaded', () => { 3524 exports.isReady = true; 3525 stack.forEach(handler => { 3526 handler(); 3527 }); 3528 stack = []; 3529 }); 3530 3531 function getEventListeners(target, eventName) { 3532 const listeners = []; 3533 if (Type.isEventTargetLike(target)) { 3534 const events = registry.get(target); 3535 if (events[eventName]) { 3536 events[eventName].forEach(listener => { 3537 listeners.push({ 3538 type: eventName, 3539 listener 3540 }); 3541 }); 3542 } 3543 } 3544 return listeners; 3545 } 3546 3547 class Event { 3548 static bind = bind$1; 3549 static bindOnce = bindOnce$1; 3550 static unbind = unbind$1; 3551 static unbindAll = unbindAll$1; 3552 static ready = ready$1; 3553 static getEventListeners = getEventListeners; 3554 static EventEmitter = EventEmitter; 3555 static BaseEvent = BaseEvent; 3556 } 3557 3558 function encodeAttributeValue(value) { 3559 if (Type.isPlainObject(value) || Type.isArray(value)) { 3560 return JSON.stringify(value); 3561 } 3562 return Text.encode(Text.decode(value)); 3563 } 3564 3565 function decodeAttributeValue(value) { 3566 if (Type.isString(value)) { 3567 const decodedValue = Text.decode(value); 3568 let result = null; 3569 try { 3570 result = JSON.parse(decodedValue); 3571 } catch { 3572 result = decodedValue; 3573 } 3574 if (result === decodedValue && /^[\d.]+[.]?\d+$/.test(result)) { 3575 return Number(result); 3576 } 3577 if (result === 'true' || result === 'false') { 3578 return Boolean(result); 3579 } 3580 return result; 3581 } 3582 return value; 3583 } 3584 3585 function getPageScroll() { 3586 const { 3587 documentElement, 3588 body 3589 } = document; 3590 const scrollTop = Math.max(window.pageYOffset || 0, documentElement ? documentElement.scrollTop : 0, body ? body.scrollTop : 0); 3591 const scrollLeft = Math.max(window.pageXOffset || 0, documentElement ? documentElement.scrollLeft : 0, body ? body.scrollLeft : 0); 3592 return { 3593 scrollTop, 3594 scrollLeft 3595 }; 3596 } 3597 3598 class Dom { 3599 static replace(oldElement, newElement) { 3600 if (Type.isDomNode(oldElement) && Type.isDomNode(newElement) && Type.isDomNode(oldElement.parentNode)) { 3601 oldElement.parentNode.replaceChild(newElement, oldElement); 3602 } 3603 } 3604 static remove(element) { 3605 if (Type.isDomNode(element) && Type.isDomNode(element.parentNode)) { 3606 element.parentNode.removeChild(element); 3607 } 3608 } 3609 static clean(element) { 3610 if (Type.isDomNode(element)) { 3611 while (element.firstChild) { 3612 element.removeChild(element.firstChild); 3613 } 3614 return; 3615 } 3616 if (Type.isString(element)) { 3617 Dom.clean(document.getElementById(element)); 3618 } 3619 } 3620 static insertBefore(current, target) { 3621 if (Type.isDomNode(current) && Type.isDomNode(target) && Type.isDomNode(target.parentNode)) { 3622 target.parentNode.insertBefore(current, target); 3623 } 3624 } 3625 static insertAfter(current, target) { 3626 if (Type.isDomNode(current) && Type.isDomNode(target) && Type.isDomNode(target.parentNode)) { 3627 const parent = target.parentNode; 3628 if (Type.isDomNode(target.nextSibling)) { 3629 parent.insertBefore(current, target.nextSibling); 3630 return; 3631 } 3632 parent.appendChild(current); 3633 } 3634 } 3635 static append(current, target) { 3636 if (Type.isDomNode(current) && Type.isDomNode(target)) { 3637 target.appendChild(current); 3638 } 3639 }
3640 static prepend(current, target) { 3641 if (Type.isDomNode(current) && Type.isDomNode(target)) { 3642 if (Type.isDomNode(target.firstChild)) { 3643 target.insertBefore(current, target.firstChild); 3644 return; 3645 } 3646 Dom.append(current, target); 3647 } 3648 } 3649 static hasClass(element, className) { 3650 if (Type.isElementNode(element)) { 3651 if (Type.isString(className)) { 3652 const preparedClassName = className.trim(); 3653 if (preparedClassName.length > 0) { 3654 if (preparedClassName.includes(' ')) { 3655 return preparedClassName.split(' ').every(name => Dom.hasClass(element, name)); 3656 } 3657 return element.classList.contains(preparedClassName); 3658 } 3659 } 3660 if (Type.isArray(className) && className.length > 0) { 3661 return className.every(name => Dom.hasClass(element, name)); 3662 } 3663 } 3664 return false; 3665 } 3666 static addClass(element, className) { 3667 if (Type.isElementNode(element)) { 3668 if (Type.isString(className)) { 3669 const preparedClassName = className.trim(); 3670 if (preparedClassName.length > 0) { 3671 if (preparedClassName.includes(' ')) { 3672 Dom.addClass(element, preparedClassName.split(' ')); 3673 return; 3674 } 3675 element.classList.add(preparedClassName); 3676 return; 3677 } 3678 } 3679 if (Type.isArray(className)) { 3680 className.forEach(name => Dom.addClass(element, name)); 3681 } 3682 } 3683 } 3684 static removeClass(element, className) { 3685 if (Type.isElementNode(element)) { 3686 if (Type.isString(className)) { 3687 const preparedClassName = className.trim(); 3688 if (preparedClassName.length > 0) { 3689 if (preparedClassName.includes(' ')) { 3690 Dom.removeClass(element, preparedClassName.split(' ')); 3691 return; 3692 } 3693 element.classList.remove(preparedClassName); 3694 return; 3695 } 3696 } 3697 if (Type.isArray(className)) { 3698 className.forEach(name => Dom.removeClass(element, name)); 3699 } 3700 } 3701 } 3702 static toggleClass(element, className, force) { 3703 if (!Type.isElementNode(element) || !Type.isStringFilled(className) && !Type.isArrayFilled(className)) { 3704 return; 3705 } 3706 [className].flat().flatMap(it =>
3706 it?.trim?.().split(' ')).forEach(token => { 3707 if (Type.isStringFilled(token)) { 3708 element.classList.toggle(token, Type.isBoolean(force) ? force : undefined); 3709 } 3710 }); 3711 } 3712 static style(element, prop, value) { 3713 if (Type.isElementNode(element)) { 3714 if (Type.isNull(prop)) { 3715 element.removeAttribute('style'); 3716 return element; 3717 } 3718 if (Type.isPlainObject(prop)) { 3719 Object.entries(prop).forEach(([currentKey, currentValue]) => { 3720 Dom.style(element, currentKey, currentValue); 3721 }); 3722 return element; 3723 } 3724 if (Type.isString(prop)) { 3725 if (Type.isUndefined(value) && element.nodeType !== Node.DOCUMENT_NODE) { 3726 const computedStyle = getComputedStyle(element); 3727 if (prop in computedStyle) { 3728 return computedStyle[prop]; 3729 } 3730 return computedStyle.getPropertyValue(prop); 3731 } 3732 if (Type.isNull(value) || value === '' || value === 'null') { 3733 if (String(prop).startsWith('--')) { 3734 element.style.removeProperty(prop); 3735 return element; 3736 } 3737 element.style[prop] = ''; 3738 return element; 3739 } 3740 if (Type.isString(value) || Type.isNumber(value)) { 3741 if (String(prop).startsWith('--')) { 3742 element.style.setProperty(prop, String(value)); 3743 return element; 3744 } 3745 element.style[prop] = value; 3746 return element; 3747 } 3748 } 3749 } 3750 return null; 3751 } 3752 static adjust(target, data = {}) { 3753 if (!target.nodeType) { 3754 return null; 3755 } 3756 let element = target; 3757 if (target.nodeType === Node.DOCUMENT_NODE) { 3758 element = target.body; 3759 } 3760 if (Type.isPlainObject(data)) { 3761 if (Type.isPlainObject(data.attrs)) { 3762 const attrs = data.attrs; 3763 Object.keys(attrs).forEach(key => { 3764 if (key === 'class' || key.toLowerCase() === 'classname') { 3765 element.className = attrs[key]; 3766 return; 3767 } 3768 if (attrs[key] == '') { 3769 element.removeAttribute(key); 3770 return; 3771 } 3772 element.setAttribute(key, attrs[key]); 3773 }); 3774 } 3775 if (Type.isPlainObject(data.style)) { 3776 Dom.style(element, data.style); 3777 } 3778 if (Type.isPlainObject(data.props)) { 3779 const props = data.props; 3780 Object.keys(props).forEach(key => { 3781 element[key] = props[key]; 3782 }); 3783 } 3784 if (Type.isPlainObject(data.events)) { 3785 const events = data.events; 3786 Object.keys(events).forEach(key => { 3787 Event.bind(element, key, events[key]); 3788 }); 3789 } 3790 if (Type.isPlainObject(data.dataset)) { 3791 const dataset = data.dataset; 3792 Object.keys(dataset).forEach(key => { 3793 element.dataset[key] = dataset[key]; 3794 }); 3795 } 3796 const children = Type.isString(data.children) ? [data.children] : data.children; 3797 if (Type.isArray(children) && children.length > 0) { 3798 children.forEach(item => { 3799 if (Type.isDomNode(item)) { 3800 Dom.append(item, element); 3801 } 3802 if (Type.isString(item)) { 3803 element.insertAdjacentHTML('beforeend', item); 3804 } 3805 }); 3806 return element; 3807 } 3808 if ('text' in data && !Type.isNil(data.text)) { 3809 element.textContent = data.text; 3810 return element; 3811 } 3812 if ('html' in data && !Type.isNil(data.html)) { 3813 element.innerHTML = data.html; 3814 } 3815 } 3816 return element; 3817 } 3818 static create(tag, data = {}, context = document) { 3819 let tagName = tag; 3820 let options = data; 3821 if (Type.isObjectLike(tag)) { 3822 const tagOptions = tag; 3823 options = tagOptions; 3824 tagName = tagOptions.tag; 3825 } 3826 return Dom.adjust(context.createElement(tagName), options); 3827 } 3828 static show(element) { 3829 if (Type.isDomNode(element)) { 3830 element.hidden = false; 3831 } 3832 } 3833 static hide(element) { 3834 if (Type.isDomNode(element)) { 3835 element.hidden = true; 3836 } 3837 } 3838 static isShown(element) { 3839 return Type.isDomNode(element) && !element.hidden && element.style.getPropertyValue('display') !== 'none'; 3840 } 3841 static isShownRecursive(element) { 3842 if (!Type.isDomNode(element)) { 3843 return false; 3844 } 3845 if (element === document.body) { 3846 return Dom.isShown(element); 3847 } 3848 return Dom.isShown(element) && Dom.isShownRecursive(element.parentElement); 3849 } 3850 static toggle(element) { 3851 if (Type.isDomNode(element)) { 3852 if (Dom.isShown(element)) { 3853 Dom.hide(element); 3854 } else { 3855 Dom.show(element); 3856 } 3857 } 3858 } 3859 static getPosition(element) { 3860 if (Type.isDomNode(element)) { 3861 const elementRect = element.getBoundingClientRect(); 3862 const { 3863 scrollLeft, 3864 scrollTop 3865 } = getPageScroll(); 3866 return new DOMRect(elementRect.left + scrollLeft, elementRect.top + scrollTop, elementRect.width, elementRect.height); 3867 } 3868 return new DOMRect(); 3869 } 3870 static getRelativePosition(element, relationElement) { 3871 if (Type.isDomNode(element) && Type.isDomNode(relationElement)) { 3872 const elementPosition = Dom.getPosition(element); 3873 const relationElementPosition = Dom.getPosition(relationElement); 3874 return new DOMRect(elementPosition.left - relationElementPosition.left, elementPosition.top - relationElementPosition.top, elementPosition.width, elementPosition.height); 3875 } 3876 return new DOMRect(); 3877 } 3878 static attr(element, attr, value) { 3879 if (Type.isElementNode(element)) { 3880 if (Type.isString(attr)) { 3881 if (!Type.isNil(value)) { 3882 if (Type.isObjectLike(value)) { 3883 element.setAttribute(attr, encodeAttributeValue(value)); 3884 } else {
3885 element.setAttribute(attr, String(value)); 3886 } 3887 } else if (Type.isNull(value)) { 3888 element.removeAttribute(attr); 3889 } else { 3890 return decodeAttributeValue(element.getAttribute(attr)); 3891 } 3892 } 3893 if (Type.isPlainObject(attr)) { 3894 Object.entries(attr).forEach(([attrKey, attrValue]) => { 3895 Dom.attr(element, attrKey, attrValue); 3896 }); 3897 } 3898 } 3899 return null; 3900 } 3901 } 3902 3903 const UA = navigator.userAgent.toLowerCase(); 3904 class Browser { 3905 static isOpera() { 3906 return UA.includes('opera'); 3907 } 3908 static isIE() { 3909 return false; 3910 } 3911 static isIE6() { 3912 return false; 3913 } 3914 static isIE7() { 3915 return false; 3916 } 3917 static isIE8() { 3918 return false; 3919 } 3920 static isIE9() { 3921 return false; 3922 } 3923 static isIE10() { 3924 return false; 3925 } 3926 static isSafari() { 3927 return UA.includes('safari') && !UA.includes('chrome'); 3928 } 3929 static isFirefox() { 3930 return UA.includes('firefox'); 3931 } 3932 static isChrome() { 3933 return UA.includes('chrome'); 3934 } 3935 static detectIEVersion() { 3936 return -1; 3937 } 3938 static isIE11() { 3939 return false; 3940 } 3941 static isMac() { 3942 return UA.includes('macintosh'); 3943 } 3944 static isWin() { 3945 return UA.includes('windows'); 3946 } 3947 static isLinux() { 3948 return UA.includes('linux') && !Browser.isAndroid(); 3949 } 3950 static isAndroid() { 3951 return UA.includes('android'); 3952 } 3953 static isIPad() { 3954 return UA.includes('ipad;') || this.isMac() && this.isTouchDevice(); 3955 } 3956 static isIPhone() { 3957 return UA.includes('iphone;'); 3958 } 3959 static isIOS() { 3960 return Browser.isIPad() || Browser.isIPhone(); 3961 } 3962 static isMobile() { 3963 return Browser.isIPhone() || Browser.isIPad() || Browser.isAndroid() || UA.includes('mobile') || UA.includes('touch'); 3964 } 3965 static isRetina() { 3966 return window.devicePixelRatio >= 2; 3967 } 3968 static isTouchDevice() { 3969 return 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; 3970 } 3971 static isDoctype(target) { 3972 const doc = target || document; 3973 if (doc.compatMode) { 3974 return doc.compatMode === 'CSS1Compat'; 3975 } 3976 return Boolean(doc.documentElement && doc.documentElement.clientHeight); 3977 } 3978 static isLocalStorageSupported() { 3979 return true; 3980 } 3981 static addGlobalClass(target) { 3982 const element = Type.isElementNode(target) ? target : document.documentElement; 3983 let globalClass = 'bx-core'; 3984 if (Dom.hasClass(element, globalClass)) { 3985 return; 3986 } 3987 if (Browser.isIOS()) { 3988 globalClass += ' bx-ios'; 3989 } else if (Browser.isWin()) { 3990 globalClass += ' bx-win'; 3991 } else if (Browser.isMac()) { 3992 globalClass += ' bx-mac'; 3993 } else if (Browser.isLinux()) { 3994 globalClass += ' bx-linux'; 3995 } else if (Browser.isAndroid()) { 3996 globalClass += ' bx-android'; 3997 } 3998 globalClass += Browser.isMobile() ? ' bx-touch' : ' bx-no-touch'; 3999 globalClass += Browser.isRetina() ? ' bx-retina' : ' bx-no-retina'; 4000 if (Browser.isSafari()) { 4001 globalClass += ' bx-safari'; 4002 } else if (/AppleWebKit/.test(navigator.userAgent)) { 4003 globalClass += ' bx-chrome'; 4004 } else if (/Opera/.test(navigator.userAgent)) { 4005 globalClass += ' bx-opera'; 4006 } else if (Browser.isFirefox()) { 4007 globalClass += ' bx-firefox'; 4008 } 4009 Dom.addClass(element, globalClass); 4010 } 4011 static detectAndroidVersion() { 4012 const re = /Android ([\d.]+)/; 4013 if (re.exec(navigator.userAgent) !== null) { 4014 const res = navigator.userAgent.match(re); 4015 if (Type.isArrayLike(res) && res.length > 0) { 4016 return parseFloat(res[1]); 4017 } 4018 } 4019 return 0; 4020 } 4021 static isPropertySupported(jsProperty, returnCSSName) { 4022 if (jsProperty === '') { 4023 return false; 4024 } 4025 function getCssName(propertyName) { 4026 return propertyName.replaceAll(/[A-Z]/g, match => `-${match.toLowerCase()}`); 4027 } 4028 function getJsName(cssName) { 4029 const reg = /(\\-([a-z]))/g; 4030 if (reg.test(cssName)) { 4031 return cssName.replaceAll(reg, (...args) => args[2].toUpperCase()); 4032 } 4033 return cssName; 4034 } 4035 const property = jsProperty.includes('-') ? getJsName(jsProperty) : jsProperty; 4036 const bReturnCSSName = Boolean(returnCSSName); 4037 const ucProperty = property.charAt(0).toUpperCase() + property.slice(1); 4038 const props = ['Webkit', 'Moz', 'O', 'ms'].join(`${ucProperty} `); 4039 const properties = `${property} ${props} ${ucProperty}`.split(' '); 4040 const obj = document.body || document.documentElement; 4041 for (const prop of properties) { 4042 if (obj && 'style' in obj && prop in obj.style) { 4043 const lowerProp = prop.slice(0, prop.length - property.length).toLowerCase(); 4044 const prefix = prop === property ? '' : `-${lowerProp}-`; 4045 return bReturnCSSName ? prefix + getCssName(property) : prop; 4046 } 4047 } 4048 return false;
4049 } 4050 static addGlobalFeatures(features) { 4051 if (!Type.isArray(features)) { 4052 return; 4053 } 4054 const classNames = []; 4055 for (const feature of features) { 4056 const support = Boolean(Browser.isPropertySupported(feature)); 4057 classNames.push(`bx-${support ? '' : 'no-'}${feature.toLowerCase()}`); 4058 } 4059 Dom.addClass(document.documentElement, classNames.join(' ')); 4060 } 4061 } 4062 4063 class Cookie { 4064 static getList() { 4065 return document.cookie.split(';').map(item => item.split('=')).map(item => item.map(subItem => subItem.trim())).reduce((acc, item) => { 4066 const [key, value] = item; 4067 acc[decodeURIComponent(key)] = decodeURIComponent(value); 4068 return acc; 4069 }, {}); 4070 } 4071 static get(name) { 4072 const cookiesList = Cookie.getList(); 4073 if (name in cookiesList) { 4074 return cookiesList[name]; 4075 } 4076 return undefined; 4077 } 4078 static set(name, value, options = {}) { 4079 const attributes = { 4080 expires: '', 4081 ...options 4082 }; 4083 if (Type.isNumber(attributes.expires)) { 4084 const now = Date.now(); 4085 const days = attributes.expires; 4086 const dayInMs = 864e5; 4087 attributes.expires = new Date(now + days * dayInMs); 4088 } 4089 if (Type.isDate(attributes.expires)) { 4090 attributes.expires = attributes.expires.toUTCString(); 4091 } 4092 const safeName = decodeURIComponent(String(name)).replaceAll(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent).replaceAll(/[()]/g, escape); 4093 const safeValue = encodeURIComponent(String(value)).replaceAll(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent); 4094 const stringifiedAttributes = Object.keys(attributes).reduce((acc, key) => { 4095 const attributeValue = attributes[key]; 4096 if (!attributeValue) { 4097 return acc; 4098 } 4099 if (attributeValue === true) { 4100 return `${acc}; ${key}`; 4101 } 4102 return `${acc}; ${key}=${attributeValue.split(';')[0]}`; 4103 }, ''); 4104 document.cookie = `${safeName}=${safeValue}${stringifiedAttributes}`; 4105 } 4106 static remove(name, options = {}) { 4107 Cookie.set(name, '', { 4108 ...options, 4109 expires: -1 4110 }); 4111 } 4112 } 4113 4114 function objectToFormData(source, formData = new FormData(), pre = null) { 4115 if (Type.isUndefined(source)) { 4116 return formData; 4117 } 4118 if (Type.isNull(source)) { 4119 formData.append(pre, ''); 4120 } else if (Type.isArray(source)) { 4121 if (source.length > 0) { 4122 source.forEach((value, index) => { 4123 const key = `${pre}[${index}]`; 4124 objectToFormData(value, formData, key); 4125 }); 4126 } else { 4127 const key = `${pre}[]`; 4128 formData.append(key, ''); 4129 } 4130 } else if (Type.isDate(source)) { 4131 formData.append(pre, source.toISOString()); 4132 } else if (Type.isObject(source) && !Type.isFile(source) && !Type.isBlob(source)) { 4133 Object.keys(source).forEach(property => { 4134 const value = source[property]; 4135 let preparedProperty = property; 4136 if (Type.isArray(value)) { 4137 while (preparedProperty.length > 2 && preparedProperty.lastIndexOf('[]') === preparedProperty.length - 2) { 4138 preparedProperty = preparedProperty.slice(0, -2); 4139 } 4140 } 4141 const key = pre ? `${pre}[${preparedProperty}]` : preparedProperty; 4142 objectToFormData(value, formData, key); 4143 }); 4144 } else { 4145 formData.append(pre, source); 4146 } 4147 return formData; 4148 } 4149 4150 class Data { 4151 static convertObjectToFormData(source) { 4152 return objectToFormData(source); 4153 } 4154 } 4155 4156 class Http { 4157 static Cookie = Cookie; 4158 static Data = Data; 4159 } 4160 4161 const message$1 = function (value) { 4162 if (Type.isString(value)) { 4163 if (Type.isNil(message$1[value])) { 4164 EventEmitter.emit('onBXMessageNotFound', new BaseEvent({ 4165 compatData: [value] 4166 })); 4167 if (Type.isNil(message$1[value])) { 4168 Runtime.debug(`message undefined: ${value}`); 4169 message$1[value] = ''; 4170 } 4171 } 4172 return message$1[value]; 4173 } 4174 if (Type.isPlainObject(value)) { 4175 Object.keys(value).forEach(key => { 4176 message$1[key] = value[key]; 4177 }); 4178 } 4179 return undefined; 4180 }; 4181 if (!Type.isNil(window.BX) && Type.isFunction(window.BX.message)) { 4182 Object.keys(window.BX.message).forEach(key => { 4183 message$1({ 4184 [key]: window.BX.message[key] 4185 }); 4186 }); 4187 } 4188 4189 class Loc { 4190 static getMessage(messageId, replacements = null) { 4191 let mess = message$1(messageId); 4192 if (Type.isString(mess) && Type.isPlainObject(replacements)) { 4193 const escape = str => String(str).replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
4194 Object.keys(replacements).forEach(replacement => { 4195 const globalRegexp = new RegExp(escape(replacement), 'gi'); 4196 mess = mess.replaceAll(globalRegexp, () => { 4197 return Type.isNil(replacements[replacement]) ? '' : String(replacements[replacement]); 4198 }); 4199 }); 4200 } 4201 return mess; 4202 } 4203 static hasMessage(messageId) { 4204 return Type.isString(messageId) && !Type.isNil(message$1[messageId]); 4205 } 4206 static setMessage(id, value) { 4207 if (Type.isString(id) && Type.isString(value)) { 4208 message$1({ 4209 [id]: value 4210 }); 4211 } 4212 if (Type.isObject(id)) { 4213 message$1(id); 4214 } 4215 } 4216 static getMessagePlural(messageId, value, replacements = null) { 4217 let result = ''; 4218 if (Type.isNumber(value)) { 4219 if (this.hasMessage(`${messageId}_PLURAL_${this.getPluralForm(value)}`)) { 4220 result = this.getMessage(`${messageId}_PLURAL_${this.getPluralForm(value)}`, replacements); 4221 } else { 4222 result = this.getMessage(`${messageId}_PLURAL_1`, replacements); 4223 } 4224 } else { 4225 result = this.getMessage(messageId, replacements); 4226 } 4227 return result; 4228 } 4229 static getPluralForm(value, languageId) { 4230 let pluralForm = 1; 4231 let lang = languageId; 4232 if (!Type.isStringFilled(lang)) { 4233 lang = message$1('LANGUAGE_ID'); 4234 } 4235 const absValue = Math.abs(value); 4236 switch (lang) { 4237 case 'ar': 4238 pluralForm = absValue === 1 ? 0 : 1; 4239 break; 4240 case 'br': 4241 case 'fr': 4242 case 'tr': 4243 pluralForm = absValue > 1 ? 1 : 0; 4244 break; 4245 case 'de': 4246 case 'en': 4247 case 'hi': 4248 case 'it': 4249 case 'la': 4250 pluralForm = absValue === 1 ? 0 : 1; 4251 break; 4252 case 'ru': 4253 case 'ua': 4254 if (absValue % 10 === 1 && absValue % 100 !== 11) { 4255 pluralForm = 0; 4256 } else if (absValue % 10 >= 2 && absValue % 10 <= 4 && (absValue % 100 < 10 || absValue % 100 >= 20)) { 4257 pluralForm = 1; 4258 } else { 4259 pluralForm = 2; 4260 } 4261 break; 4262 case 'pl': 4263 if (absValue === 1) { 4264 pluralForm = 0; 4265 } else if (absValue % 10 >= 2 && absValue % 10 <= 4 && (absValue % 100 < 10 || absValue % 100 >= 20)) { 4266 pluralForm = 1; 4267 } else { 4268 pluralForm = 2; 4269 } 4270 break; 4271 case 'id': 4272 case 'ja': 4273 case 'ms': 4274 case 'sc': 4275 case 'tc': 4276 case 'th': 4277 case 'vn': 4278 pluralForm = 0; 4279 break; 4280 default: 4281 pluralForm = 1; 4282 break; 4283 } 4284 return pluralForm; 4285 } 4286 } 4287 4288 const voidElements = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']); 4289 function isVoidElement(element) { 4290 return voidElements.has(element); 4291 } 4292 4293 const matchers = { 4294 tag: /<[\d!/A-Za-z-](?:"[^"]*"|'[^']*'|[^"'>])*>|{{uid\d+}}/g, 4295 comment: /<!--(?!<!)[^>[].*?-->/g, 4296 tagName: /<\/?(\S+?)[\s/>]/, 4297 attributes: /\s([\w.:-]+)\s?\n?=\s?\n?"([^"]+)?"|\s([\w.:-]+)\s?\n?=\s?\n?'([^']+)?'|\s([\w.:-]+)/gs, 4298 placeholder: /{{uid\d+}}/g 4299 }; 4300 4301 function parseTag(tag) { 4302 const tagResult = { 4303 type: 'tag', 4304 name: '', 4305 svg: false, 4306 attrs: {}, 4307 children: [], 4308 voidElement: false 4309 }; 4310 if (tag.startsWith('<!--')) { 4311 const endIndex = tag.indexOf('-->'); 4312 const openTagLength = '<!--'.length; 4313 return { 4314 type: 'comment', 4315 content: endIndex === -1 ? '' : tag.slice(openTagLength, endIndex) 4316 }; 4317 } 4318 const tagNameMatch = tag.match(matchers.tagName); 4319 if (Type.isArrayFilled(tagNameMatch)) { 4320 const [, tagName] = tagNameMatch; 4321 tagResult.name = tagName; 4322 tagResult.svg = tagName === 'svg'; 4323 tagResult.voidElement = isVoidElement(tagName) || tag.trim().endsWith('/>'); 4324 } 4325 const reg = new RegExp(matchers.attributes); 4326 for (;;) { 4327 const result = reg.exec(tag); 4328 if (Type.isNil(result)) { 4329 break; 4330 } 4331 const [, doubleQuoteName, doubleQuoteValue] = result; 4332 if (Type.isNil(doubleQuoteName)) { 4333 const singleQuoteName = result[3]; 4334 const singleQuoteValue = result[4]; 4335 if (Type.isNil(singleQuoteName)) { 4336 const booleanAttrName = result[5]; 4337 tagResult.attrs[booleanAttrName] = ''; 4338 } else { 4339 tagResult.attrs[singleQuoteName] = Type.isStringFilled(singleQuoteValue) ? singleQuoteValue : ''; 4340 } 4341 } else { 4342 tagResult.attrs[doubleQuoteName] = Type.isStringFilled(doubleQuoteValue) ? doubleQuoteValue : ''; 4343 } 4344 } 4345 return tagResult; 4346 } 4347 4348 function parseText(input) { 4349 const preparedText = input.replace(/[\t\n\r]$/, ''); 4350 const placeholders = preparedText.match(matchers.placeholder); 4351 return preparedText.split(matchers.placeholder).reduce((acc, item, index) => { 4352 if (Type.isStringFilled(item)) { 4353 acc.push(...item.split(/\n/).reduce((textAcc, text) => { 4354 const preparedItemText = text.replaceAll(/[\t\r]/g, ''); 4355 if (Type.isStringFilled(preparedItemText)) { 4356 textAcc.push({ 4357 type: 'text', 4358 content: preparedItemText 4359 }); 4360 } 4361 return textAcc; 4362 }, [])); 4363 } 4364 if (placeholders && placeholders[index]) { 4365 acc.push({ 4366 type: 'placeholder', 4367 uid: parseInt(placeholders[index].replace(/{{uid|}}/, ''), 10) 4368 }); 4369 } 4370 return acc; 4371 }, []); 4372 } 4373 4374 function parse(html, substitutions) { 4375 const result = []; 4376 if (html.indexOf('<') !== 0 && !html.startsWith('{{')) { 4377 const end = html.indexOf('<'); 4378 result.push(...parseText(end === -1 ? html : html.slice(0, end))); 4379 } 4380 const commentsContent = []; 4381 let commentIndex = -1; 4382 html = html.replace(matchers.comment, tag => { 4383 commentIndex += 1; 4384 commentsContent.push(tag.replaceAll(/^<!--|-->$/g, '')); 4385 return `<!--{{cUid${commentIndex}}}-->`; 4386 }); 4387 const arr = []; 4388 let level = -1; 4389 let current = null; 4390 html.replace(matchers.tag, (tag, index) => { 4391 const start = index + tag.length; 4392 const nextChar = html.charAt(start); 4393 let parent = null; 4394 if (tag.startsWith('<!--')) { 4395 const comment = parseTag(tag); 4396 comment.content = commentsContent[tag.replaceAll(/<!--{{cUid|}}-->/g, '')]; 4397 if (level < 0) { 4398 result.push(comment); 4399 return result; 4400 } 4401 parent = arr[level]; 4402 parent.children.push(comment); 4403 return result; 4404 } 4405 if (tag.startsWith('{{')) { 4406 const [placeholder] = parseText(tag); 4407 if (level < 0) { 4408 result.push(placeholder); 4409 return result; 4410 } 4411 parent = arr[level]; 4412 parent.children.push(placeholder); 4413 return result; 4414 } 4415 if (!tag.startsWith('</')) { 4416 level++; 4417 current = parseTag(tag); 4418 if (!current.voidElement && nextChar && nextChar !== '<') { 4419 current.children.push(...parseText(html.slice(start, html.indexOf('<', start)))); 4420 } 4421 if (level === 0) { 4422 result.push(current); 4423 } 4424 parent = arr[level - 1]; 4425 if (parent) { 4426 if (!current.svg) { 4427 current.svg = parent.svg; 4428 } 4429 parent.children.push(current); 4430 } 4431 arr[level] = current; 4432 } 4433 if (tag.startsWith('</') || current.voidElement) { 4434 if (level > -1 && (current.voidElement || current.name === tag.slice(2, -1))) { 4435 level--; 4436 current = level === -1 ? result : arr[level]; 4437 } 4438 if (nextChar && nextChar !== '<') { 4439 parent = level === -1 ? result : arr[level].children; 4440 const end = html.indexOf('<', start); 4441 const content = html.slice(start, end === -1 ? undefined : end); 4442 if (end >
4442 -1 && level + parent.length >= 0 || content !== ' ') { 4443 parent.push(...parseText(content)); 4444 } 4445 } 4446 } 4447 return result; 4448 }); 4449 return result; 4450 } 4451 4452 const appendElement = (current, target) => { 4453 if (Type.isDomNode(current) && Type.isDomNode(target)) { 4454 if (target.nodeName === 'TEMPLATE') { 4455 target.content.append(current); 4456 } else { 4457 Dom.append(current, target); 4458 } 4459 } 4460 }; 4461 function renderNode(options) { 4462 const { 4463 node, 4464 parentElement, 4465 substitutions, 4466 refs = [] 4467 } = options; 4468 if (node.type === 'tag') { 4469 const element = (() => { 4470 if (node.svg) { 4471 return document.createElementNS('http://www.w3.org/2000/svg', node.name); 4472 } 4473 return document.createElement(node.name); 4474 })(); 4475 if (Object.hasOwn(node.attrs, 'ref')) { 4476 refs.push([node.attrs.ref, element]); 4477 delete node.attrs.ref; 4478 } 4479 Object.entries(node.attrs).forEach(([key, value]) => { 4480 if (key.startsWith('on') && new RegExp(matchers.placeholder).test(value)) { 4481 const substitution = substitutions[parseInt(value.replace(/{{uid|}}/, ''), 10) - 1]; 4482 if (Type.isFunction(substitution)) { 4483 const bindFunctionName = key.endsWith('once') ? 'bindOnce' : 'bind'; 4484 Event[bindFunctionName](element, key.replaceAll(/^on|once$/g, ''), substitution); 4485 } else { 4486 element.setAttribute(key, substitution); 4487 } 4488 } else if (new RegExp(matchers.placeholder).test(value)) { 4489 const preparedValue = value.split(/{{|}}/).reduce((acc, item) => { 4490 if (item.startsWith('uid')) { 4491 const substitution = substitutions[parseInt(item.replace('uid', ''), 10) - 1]; 4492 return `${acc}${substitution}`; 4493 } 4494 return `${acc}${item}`; 4495 }, ''); 4496 element.setAttribute(key, preparedValue); 4497 } else { 4498 element.setAttribute(key, Text.decode(value)); 4499 } 4500 }); 4501 node.children.forEach(childNode => { 4502 const result = renderNode({ 4503 node: childNode, 4504 parentElement: element, 4505 substitutions, 4506 refs 4507 }); 4508 if (Type.isArray(result)) { 4509 result.forEach(subChildElement => { 4510 appendElement(subChildElement, element); 4511 }); 4512 } else { 4513 appendElement(result, element); 4514 } 4515 }); 4516 return element; 4517 } 4518 if (node.type === 'comment') { 4519 return document.createComment(node.content); 4520 } 4521 if (node.type === 'text') { 4522 if (parentElement) { 4523 if (parentElement.nodeName === 'TEMPLATE') { 4524 parentElement.content.append(node.content); 4525 } else { 4526 parentElement.insertAdjacentHTML('beforeend', node.content); 4527 } 4528 return undefined; 4529 } 4530 return document.createTextNode(node.content); 4531 } 4532 if (node.type === 'placeholder') { 4533 return substitutions[node.uid - 1]; 4534 } 4535 return undefined; 4536 } 4537 4538 function render(sections, ...substitutions) { 4539 const html = sections.reduce((acc, item, index) => { 4540 if (index > 0) { 4541 const substitution = substitutions[index - 1]; 4542 if (Type.isString(substitution) || Type.isNumber(substitution)) { 4543 return `${acc}${substitution}${item}`; 4544 } 4545 return `${acc}{{uid${index}}}${item}`; 4546 } 4547 return acc; 4548 }, sections[0]).replaceAll(/^\s+/gm, '').replaceAll(/>\n+/g, '>').replaceAll(/}\n+/g, '}'); 4549 const ast = parse(html); 4550 if (ast.length === 1) { 4551 const refs = []; 4552 const renderedNode = renderNode({ 4553 node: ast[0], 4554 substitutions, 4555 refs 4556 }); 4557 if (Type.isArrayFilled(refs)) { 4558 return Object.fromEntries([['root', renderedNode], ...refs]); 4559 } 4560 return renderedNode; 4561 } 4562 if (ast.length > 1) { 4563 const refs = []; 4564 const renderedNodes = ast.map(node => { 4565 return renderNode({ 4566 node, 4567 substitutions, 4568 refs 4569 }); 4570 }); 4571 if (Type.isArrayFilled(refs)) { 4572 return Object.fromEntries([['root', renderedNodes], ...refs]); 4573 } 4574 return renderedNodes; 4575 } 4576 return false; 4577 } 4578 4579 function parseProps(...args) { 4580 const [sections, ...substitutions] = args; 4581 return substitutions.reduce((acc, item, index) => { 4582 const nextSectionIndex = index + 1; 4583 if (!Type.isPlainObject(item) && !Type.isArray(item)) { 4584 return acc + item + sections[nextSectionIndex]; 4585 } 4586 return `${acc}__s${index}${sections[nextSectionIndex]}`; 4587 }, sections[0]).replaceAll(/[\t\r]/gm, '').split(';\n').map(item => item.replace(/\n/, '')).reduce((acc, item) => { 4588 if (item !== '') { 4589 const matches = item.match(/^[\w-. ]+:/); 4590 const splitted = item.split(/^[\w-. ]+:/);
4591 const key = matches[0].replace(':', '').trim(); 4592 const value = splitted[1].trim(); 4593 const substitutionPlaceholderExp = /^__s\d+/; 4594 if (substitutionPlaceholderExp.test(value)) { 4595 acc[key] = substitutions[value.replace('__s', '')]; 4596 return acc; 4597 } 4598 acc[key] = value; 4599 } 4600 return acc; 4601 }, {}); 4602 } 4603 class Tag { 4604 static safe(sections, ...substitutions) { 4605 return substitutions.reduce((acc, item, index) => acc + Text.encode(item) + sections[index + 1], sections[0]); 4606 } 4607 static unsafe(sections, ...substitutions) { 4608 return substitutions.reduce((acc, item, index) => acc + Text.decode(item) + sections[index + 1], sections[0]); 4609 } 4610 static style(element) { 4611 if (!Type.isDomNode(element)) { 4612 throw new Error('element is not HTMLElement'); 4613 } 4614 return function styleTagHandler(...args) { 4615 Dom.style(element, parseProps(...args)); 4616 }; 4617 } 4618 static message(sections, ...substitutions) { 4619 return substitutions.reduce((acc, item, index) => acc + Loc.getMessage(item) + sections[index + 1], sections[0]); 4620 } 4621 static render = render; 4622 static attrs(element) { 4623 if (!Type.isDomNode(element)) { 4624 throw new Error('element is not HTMLElement'); 4625 } 4626 return function attrsTagHandler(...args) { 4627 Dom.attr(element, parseProps(...args)); 4628 }; 4629 } 4630 static attr = Tag.attrs; 4631 } 4632 4633 function getParser(format) { 4634 switch (format) { 4635 case 'index': 4636 return (sourceKey, value, accumulator) => { 4637 const result = /\[(\w*)]$/.exec(sourceKey); 4638 const key = sourceKey.replace(/\[\w*]$/, ''); 4639 if (Type.isNil(result)) { 4640 accumulator[key] = value; 4641 return; 4642 } 4643 if (Type.isUndefined(accumulator[key])) { 4644 accumulator[key] = {}; 4645 } 4646 accumulator[key][result[1]] = value; 4647 }; 4648 case 'bracket': 4649 return (sourceKey, value, accumulator) => { 4650 const result = /(\[])$/.exec(sourceKey); 4651 const key = sourceKey.replace(/\[]$/, ''); 4652 if (Type.isNil(result)) { 4653 accumulator[key] = value; 4654 return; 4655 } 4656 if (Type.isUndefined(accumulator[key])) { 4657 accumulator[key] = Type.isNil(value) ? [] : [value]; 4658 return; 4659 } 4660 accumulator[key] = [].concat(accumulator[key], value); 4661 }; 4662 default: 4663 return (sourceKey, value, accumulator) => { 4664 const key = sourceKey.replace(/\[]$/, ''); 4665 accumulator[key] = value; 4666 }; 4667 } 4668 } 4669 function getKeyFormat(key) { 4670 if (/^\w+\[(\w+)]$/.test(key)) { 4671 return 'index'; 4672 } 4673 if (/^\w+\[]$/.test(key)) { 4674 return 'bracket'; 4675 } 4676 return 'default'; 4677 } 4678 function isAllowedKey(key) { 4679 return !String(key).startsWith('__proto__'); 4680 } 4681 function parseQuery(input) { 4682 if (!Type.isString(input)) { 4683 return {}; 4684 } 4685 const url = input.trim().replace(/^[#&?]/, ''); 4686 if (!url) { 4687 return {}; 4688 } 4689 return { 4690 ...url.split('&').reduce((acc, param) => { 4691 const [key, value] = param.replaceAll('+', ' ').split('='); 4692 if (isAllowedKey(key)) { 4693 const keyFormat = getKeyFormat(key); 4694 const formatter = getParser(keyFormat); 4695 formatter(key, value, acc); 4696 } 4697 return acc; 4698 }, Object.create(null)) 4699 }; 4700 } 4701 const urlExp = /^((\w+):)?(\/\/((\w+)?(:(\w+))?@)?([^/:?]+)(:(\d+))?)?(\/?([^#/?][^#?]*)?)?(\?([^#]+))?(#((?:[\w-?/:@.~!$&'()*+,;=]|%\w{2})*))?/; 4702 function prepareParams(params) { 4703 const paramsEntries = Object.entries(params); 4704 return paramsEntries.reduce((acc, [key, value]) => { 4705 if (Type.isNil(value)) { 4706 acc[key] = ''; 4707 } else if (Type.isPlainObject(value)) { 4708 acc[key] = prepareParams(value); 4709 } else { 4710 acc[key] = value; 4711 } 4712 return acc; 4713 }, {}); 4714 } 4715 function parseUrl(url) { 4716 const result = url.match(urlExp); 4717 if (Type.isArray(result)) { 4718 const sourceParams = parseQuery(result[14]); 4719 const preparedParams = prepareParams(sourceParams); 4720 return { 4721 useShort: /^\/\//.test(url), 4722 href: result[0] || '', 4723 schema: result[2] || '', 4724 host: result[8] || '', 4725 port: result[10] || '', 4726 path: result[11] || '', 4727 query: result[14] || '', 4728 sourceQueryParams: sourceParams, 4729 queryParams: preparedParams, 4730 hash: result[16] || '', 4731 username: result[5] || '', 4732 password: result[7] || '', 4733 origin: result[8] || '' 4734 }; 4735 } 4736 return {}; 4737 } 4738 4739 function renderParam(param, value) { 4740 if (Type.isNil(value)) { 4741 return param; 4742 } 4743 return `${param}=${value}`; 4744 } 4745 4746 function buildQueryString(params = {}) { 4747 const queryString = Object.keys(params).reduce((acc, key) => { 4748 if (Type.isArray(params[key])) {
4749 if (Type.isArrayFilled(params[key])) { 4750 params[key].forEach(paramValue => { 4751 acc.push(renderParam(`${key}[]`, paramValue)); 4752 }); 4753 } else { 4754 acc.push(renderParam(`${key}[]`, null)); 4755 } 4756 } 4757 if (Type.isPlainObject(params[key])) { 4758 Object.keys(params[key]).forEach(paramIndex => { 4759 acc.push(renderParam(`${key}[${paramIndex}]`, params[key][paramIndex])); 4760 }); 4761 } 4762 if (!Type.isObject(params[key]) && !Type.isArray(params[key])) { 4763 acc.push(renderParam(key, params[key])); 4764 } 4765 return acc; 4766 }, []).join('&'); 4767 if (queryString.length > 0) { 4768 return `?${queryString}`; 4769 } 4770 return queryString; 4771 } 4772 4773 function prepareParamValue(value) { 4774 if (Type.isArray(value)) { 4775 return value.map(item => String(item)); 4776 } 4777 if (Type.isPlainObject(value)) { 4778 return { 4779 ...value 4780 }; 4781 } 4782 return String(value); 4783 } 4784 4785 const map = new WeakMap(); 4786 class Uri { 4787 static addParam(url, params = {}) { 4788 return new Uri(url).setQueryParams(params).toString(); 4789 } 4790 static removeParam(url, params) { 4791 const removableParams = Type.isArray(params) ? params : [params]; 4792 return new Uri(url).removeQueryParam(...removableParams).toString(); 4793 } 4794 constructor(url = '') { 4795 map.set(this, parseUrl(url)); 4796 } 4797 getSchema() { 4798 return map.get(this).schema; 4799 } 4800 setSchema(schema) { 4801 map.get(this).schema = String(schema); 4802 return this; 4803 } 4804 getHost() { 4805 return map.get(this).host; 4806 } 4807 setHost(host) { 4808 map.get(this).host = String(host); 4809 return this; 4810 } 4811 getPort() { 4812 return map.get(this).port; 4813 } 4814 setPort(port) { 4815 map.get(this).port = String(port); 4816 return this; 4817 } 4818 getPath() { 4819 return map.get(this).path; 4820 } 4821 setPath(path) { 4822 if (!/^\//.test(path)) { 4823 map.get(this).path = `/${String(path)}`; 4824 return this; 4825 } 4826 map.get(this).path = String(path); 4827 return this; 4828 } 4829 getQuery() { 4830 return buildQueryString(map.get(this).queryParams); 4831 } 4832 getQueryParam(key) { 4833 const params = this.getQueryParams(); 4834 if (Object.hasOwn(params, key)) { 4835 return params[key]; 4836 } 4837 return null; 4838 } 4839 setQueryParam(key, value = '') { 4840 map.get(this).queryParams[key] = prepareParamValue(value); 4841 map.get(this).sourceQueryParams[key] = prepareParamValue(value); 4842 return this; 4843 } 4844 getQueryParams() { 4845 return { 4846 ...map.get(this).queryParams 4847 }; 4848 } 4849 setQueryParams(params = {}) { 4850 if (Type.isPlainObject(params)) { 4851 const { 4852 queryParams, 4853 sourceQueryParams 4854 } = map.get(this); 4855 Object.entries(params).forEach(([key, value]) => { 4856 const preparedValue = prepareParamValue(value); 4857 queryParams[key] = preparedValue; 4858 sourceQueryParams[key] = preparedValue; 4859 }); 4860 } 4861 return this; 4862 } 4863 removeQueryParam(...keys) { 4864 const { 4865 queryParams, 4866 sourceQueryParams 4867 } = map.get(this); 4868 keys.forEach(key => { 4869 delete queryParams[key]; 4870 delete sourceQueryParams[key]; 4871 }); 4872 return this; 4873 } 4874 getFragment() { 4875 return map.get(this).hash; 4876 } 4877 setFragment(hash) { 4878 map.get(this).hash = String(hash); 4879 return this; 4880 } 4881 serialize() { 4882 const serialized = { 4883 ...map.get(this) 4884 }; 4885 delete serialized.sourceQueryParams; 4886 serialized.href = this.toString(); 4887 return serialized; 4888 } 4889 toString() { 4890 const data = { 4891 ...map.get(this) 4892 }; 4893 let protocol = data.schema ? `${data.schema}://` : ''; 4894 if (data.useShort) { 4895 protocol = '//'; 4896 } 4897 const port = (() => { 4898 if (Type.isString(data.port) && !['', '80'].includes(data.port)) { 4899 return `:${data.port}`; 4900 } 4901 return ''; 4902 })(); 4903 const host = this.getHost(); 4904 const path = this.getPath(); 4905 const query = buildQueryString(data.sourceQueryParams); 4906 const hash = data.hash ? `#${data.hash}` : ''; 4907 return `${host ? protocol : ''}${host}${host ? port : ''}${path}${query}${hash}`; 4908 } 4909 } 4910 4911 class Validation { 4912 static MAX_EMAIL_LENGTH = 254; 4913 static MAX_LOCAL_LENGTH = 64; 4914 static LOCAL_ALLOWED_CHARS = /^[\w%+.ÐÐ-ÑÑ-]+$/; 4915 static DOMAIN_LABEL_CHARS = /^[\w.ÐÐ-ÑÑ-]+$/; 4916 static isEmail(email) { 4917 if (!Type.isStringFilled(email)) { 4918 return false; 4919 } 4920 if (email.length > Validation.MAX_EMAIL_LENGTH) { 4921 return false;
4922 } 4923 const atPos = email.indexOf('@'); 4924 if (atPos <= 0 || atPos === email.length - 1 || email.includes('@', atPos + 1)) { 4925 return false; 4926 } 4927 const local = email.slice(0, atPos); 4928 const domain = email.slice(atPos + 1); 4929 if (!Validation.LOCAL_ALLOWED_CHARS.test(local)) { 4930 return false; 4931 } 4932 if (local.startsWith('.') || local.endsWith('.') || local.startsWith('-') || local.endsWith('-') || local.includes('..') || local.length > Validation.MAX_LOCAL_LENGTH) { 4933 return false; 4934 } 4935 if (!Validation.DOMAIN_LABEL_CHARS.test(domain)) { 4936 return false; 4937 } 4938 if (domain.startsWith('.') || domain.endsWith('.') || domain.includes('..')) { 4939 return false; 4940 } 4941 const labels = domain.split('.'); 4942 if (labels.length < 2) { 4943 return false; 4944 } 4945 const tld = labels[labels.length - 1]; 4946 if (tld.length < 2 || tld.length > 24) { 4947 return false; 4948 } 4949 for (const label of labels) { 4950 if (label.startsWith('-') || label.endsWith('-')) { 4951 return false; 4952 } 4953 const startsWithLetterOrDigit = /^[\dA-Za-zÐÐ-ÑÑ]/.test(label); 4954 const endsWithLetterOrDigit = /[\dA-Za-zÐÐ-ÑÑ]$/.test(label); 4955 if (!startsWithLetterOrDigit || !endsWithLetterOrDigit) { 4956 return false; 4957 } 4958 } 4959 return true; 4960 } 4961 } 4962 4963 class BaseCache { 4964 storage = new Map(); 4965 get(key, defaultValue) { 4966 if (!this.storage.has(key)) { 4967 if (Type.isFunction(defaultValue)) { 4968 return defaultValue(); 4969 } 4970 if (!Type.isUndefined(defaultValue)) { 4971 return defaultValue; 4972 } 4973 } 4974 return this.storage.get(key); 4975 } 4976 set(key, value) { 4977 this.storage.set(key, value); 4978 } 4979 delete(key) { 4980 this.storage.delete(key); 4981 } 4982 has(key) { 4983 return this.storage.has(key); 4984 } 4985 remember(key, defaultValue) { 4986 if (!this.storage.has(key)) { 4987 if (Type.isFunction(defaultValue)) { 4988 this.storage.set(key, defaultValue()); 4989 } else if (!Type.isUndefined(defaultValue)) { 4990 this.storage.set(key, defaultValue); 4991 } 4992 } 4993 return this.storage.get(key); 4994 } 4995 size() { 4996 return this.storage.size; 4997 } 4998 keys() { 4999 return [...this.storage.keys()]; 5000 } 5001 values() { 5002 return [...this.storage.values()]; 5003 } 5004 } 5005 5006 var MemoryStorage = Map; 5007 5008 class MemoryCache extends BaseCache { 5009 storage = new MemoryStorage(); 5010 } 5011 5012 class LsStorage { 5013 stackKey = 'BX.Cache.Storage.LsStorage.stack'; 5014 stack = null; 5015 getStack() { 5016 if (Type.isPlainObject(this.stack)) { 5017 return this.stack; 5018 } 5019 const stack = localStorage.getItem(this.stackKey); 5020 if (Type.isString(stack) && stack !== '') { 5021 const parsedStack = JSON.parse(stack); 5022 if (Type.isPlainObject(parsedStack)) { 5023 this.stack = parsedStack; 5024 return this.stack; 5025 } 5026 } 5027 this.stack = {}; 5028 return this.stack; 5029 } 5030 saveStack() { 5031 if (Type.isPlainObject(this.stack)) { 5032 const preparedStack = JSON.stringify(this.stack); 5033 localStorage.setItem(this.stackKey, preparedStack); 5034 } 5035 } 5036 get(key) { 5037 const stack = this.getStack(); 5038 return stack[key]; 5039 } 5040 set(key, value) { 5041 const stack = this.getStack(); 5042 stack[key] = value; 5043 this.saveStack(); 5044 } 5045 delete(key) { 5046 const stack = this.getStack(); 5047 if (key in stack) { 5048 delete stack[key]; 5049 } 5050 } 5051 has(key) { 5052 const stack = this.getStack(); 5053 return key in stack; 5054 } 5055 get size() { 5056 const stack = this.getStack(); 5057 return Object.keys(stack).length; 5058 } 5059 keys() { 5060 const stack = this.getStack(); 5061 return Object.keys(stack); 5062 } 5063 values() { 5064 const stack = this.getStack(); 5065 return Object.values(stack); 5066 } 5067 } 5068 5069 class LocalStorageCache extends BaseCache { 5070 storage = new LsStorage(); 5071 } 5072 5073 class Cache { 5074 static BaseCache = BaseCache; 5075 static MemoryCache = MemoryCache; 5076 static LocalStorageCache = LocalStorageCache; 5077 } 5078 5079 function convertPath(path) { 5080 if (Type.isStringFilled(path)) { 5081 return path.split('.').reduce((acc, item) => { 5082 item.split(/\[["']?(.+?)["']?]/g).forEach(key => { 5083 if (Type.isStringFilled(key)) { 5084 acc.push(key); 5085 } 5086 }); 5087 return acc; 5088 }, []); 5089 } 5090 return []; 5091 } 5092 5093 class SettingsCollection { 5094 constructor(options = {}) { 5095 if (Type.isPlainObject(options)) { 5096 Object.assign(this, options); 5097 } 5098 } 5099 get(path, defaultValue = null) { 5100 const convertedPath = convertPath(path); 5101 return convertedPath.reduce((acc, key) => { 5102 if (!Type.isNil(acc) && acc !== defaultValue) { 5103 if (!Type.isUndefined(acc[key])) { 5104 return acc[key]; 5105 } 5106 return defaultValue; 5107 } 5108 return acc; 5109 }, this); 5110 } 5111 } 5112 5113 function deepFreeze(target) { 5114 if (Type.isObject(target)) { 5115 Object.values(target).forEach(value => { 5116 deepFreeze(value); 5117 }); 5118 return Object.freeze(target); 5119 } 5120 return target; 5121 } 5122 5123 const settingsStorage = new Map(); 5124 class Extension { 5125 static getSettings(extensionName) { 5126 if (Type.isStringFilled(extensionName)) { 5127 if (settingsStorage.has(extensionName)) { 5128 return settingsStorage.get(extensionName); 5129 } 5130 const settingsScriptNode = document.querySelector(`script[data-extension="${extensionName}"]`); 5131 if (Type.isDomNode(settingsScriptNode)) { 5132 const decodedSettings = (() => { 5133 try { 5134 return new SettingsCollection(JSON.parse(settingsScriptNode.innerHTML)); 5135 } catch { 5136 return new SettingsCollection(); 5137 } 5138 })(); 5139 const frozenSettings = deepFreeze(decodedSettings); 5140 settingsStorage.set(extensionName, frozenSettings); 5141 return frozenSettings; 5142 } 5143 } 5144 return deepFreeze(new SettingsCollection()); 5145 } 5146 } 5147 5148 function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); } 5149 function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); } 5150 function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); } 5151 var _OrderedArray_brand = new WeakSet(); 5152 let OrderedArray = function () { 5153 function OrderedArray(comparator = null) { 5154 babelHelpers.classCallCheck(this, OrderedArray); 5155 _classPrivateMethodInitSpec(this, _OrderedArray_brand); 5156 babelHelpers.defineProperty(this, "comparator", null); 5157 babelHelpers.defineProperty(this, "items", []); 5158 this.comparator = Type.isFunction(comparator) ? comparator : null; 5159 } 5160 return babelHelpers.createClass(OrderedArray, [{ 5161 key: "add", 5162 value: function add(item) { 5163 let index = -1; 5164 if (this.comparator) { 5165 index = _assertClassBrand(_OrderedArray_brand, this, _searchIndexToInsert).call(this, item); 5166 this.items.splice(index, 0, item); 5167 } else { 5168 this.items.push(item); 5169 } 5170 return index; 5171 } 5172 }, { 5173 key: "has", 5174 value: function has(item) { 5175 return this.items.includes(item); 5176 } 5177 }, { 5178 key: "getIndex", 5179 value: function getIndex(item) { 5180 return this.items.indexOf(item); 5181 } 5182 }, { 5183 key: "getByIndex", 5184 value: function getByIndex(index) { 5185 if (Type.isNumber(index) && index >= 0) { 5186 const item = this.items[index]; 5187 return Type.isUndefined(item) ? null : item; 5188 } 5189 return null; 5190 } 5191 }, { 5192 key: "getFirst", 5193 value: function getFirst() { 5194 const first = this.items[0]; 5195 return Type.isUndefined(first) ? null : first; 5196 } 5197 }, { 5198 key: "getLast", 5199 value: function getLast() { 5200 const last = this.items[this.count() - 1]; 5201 return Type.isUndefined(last) ? null : last; 5202 } 5203 }, { 5204 key: "count", 5205 value: function count() { 5206 return this.items.length; 5207 } 5208 }, { 5209 key: "delete", 5210 value: function _delete(item) { 5211 const index = this.getIndex(item); 5212 if (index !== -1) { 5213 this.items.splice(index, 1); 5214 return true; 5215 } 5216 return false;
5217 } 5218 }, { 5219 key: "clear", 5220 value: function clear() { 5221 this.items = []; 5222 } 5223 }, { 5224 key: Symbol.iterator, 5225 value: function () { 5226 return this.items[Symbol.iterator](); 5227 } 5228 }, { 5229 key: "forEach", 5230 value: function forEach(callbackfn, thisArg) { 5231 const callback = thisArg ? callbackfn.bind(thisArg) : callbackfn; 5232 this.items.forEach((value, index, array) => { 5233 callback(value, index, array); 5234 }); 5235 } 5236 }, { 5237 key: "getAll", 5238 value: function getAll() { 5239 return this.items; 5240 } 5241 }, { 5242 key: "getComparator", 5243 value: function getComparator() { 5244 return this.comparator; 5245 } 5246 }, { 5247 key: "sort", 5248 value: function sort() { 5249 const comparator = this.getComparator(); 5250 if (comparator === null) { 5251 return; 5252 } 5253 const length = this.items.length; 5254 const indexes = Array.from({ 5255 length 5256 }, (_, i) => i); 5257 indexes.sort((index1, index2) => { 5258 return comparator(this.items[index1], this.items[index2]) || index1 - index2; 5259 }); 5260 for (let i = 0; i < length; i++) { 5261 indexes[i] = this.items[indexes[i]]; 5262 } 5263 for (let i = 0; i < length; i++) { 5264 this.items[i] = indexes[i]; 5265 } 5266 } 5267 }]); 5268 }(); 5269 function _searchIndexToInsert(value) { 5270 let low = 0; 5271 let high = this.items.length; 5272 while (low < high) { 5273 const mid = Math.floor((low + high) / 2); 5274 if (this.comparator(this.items[mid], value) >= 0) { 5275 high = mid; 5276 } else { 5277 low = mid + 1; 5278 } 5279 } 5280 return low; 5281 } 5282 5283 class ZIndexComponent extends EventEmitter { 5284 sort = 0; 5285 alwaysOnTop = false; 5286 zIndex = 0; 5287 element = null; 5288 overlay = null; 5289 overlayGap = -5; 5290 stack = null; 5291 constructor(element, componentOptions = {}) { 5292 super(); 5293 this.setEventNamespace('BX.Main.ZIndexManager.Component'); 5294 if (!Type.isElementNode(element)) { 5295 throw new Error("ZIndexManager.Component: The argument 'element' must be a DOM element."); 5296 } 5297 this.element = element; 5298 const options = Type.isPlainObject(componentOptions) ? componentOptions : {}; 5299 this.setAlwaysOnTop(options.alwaysOnTop); 5300 this.setOverlay(options.overlay); 5301 this.setOverlayGap(options.overlayGap); 5302 this.subscribeFromOptions(options.events); 5303 } 5304 getSort() { 5305 return this.sort; 5306 } 5307 setSort(sort) { 5308 if (Type.isNumber(sort)) { 5309 this.sort = sort; 5310 } 5311 } 5312 setStack(stack) { 5313 this.stack = stack; 5314 } 5315 getStack() { 5316 return this.stack; 5317 } 5318 getZIndex() { 5319 return this.zIndex; 5320 } 5321 setZIndex(zIndex) { 5322 const changed = this.getZIndex() !== zIndex; 5323 this.getElement().style.setProperty('z-index', String(zIndex), 'important'); 5324 this.zIndex = zIndex; 5325 if (this.getOverlay() !== null) { 5326 this.getOverlay().style.setProperty('z-index', String(zIndex + this.getOverlayGap()), 'important'); 5327 } 5328 if (changed) { 5329 this.emit('onZIndexChange', { 5330 component: this 5331 }); 5332 } 5333 } 5334 getAlwaysOnTop() { 5335 return this.alwaysOnTop; 5336 } 5337 setAlwaysOnTop(value) { 5338 if (Type.isNumber(value) || Type.isBoolean(value)) { 5339 this.alwaysOnTop = value; 5340 } 5341 } 5342 getElement() { 5343 return this.element; 5344 } 5345 setOverlay(overlay, gap) { 5346 if (Type.isElementNode(overlay) || overlay === null) { 5347 this.overlay = overlay; 5348 this.setOverlayGap(gap); 5349 if (this.getStack()) { 5350 this.getStack().sort(); 5351 } 5352 } 5353 } 5354 getOverlay() { 5355 return this.overlay; 5356 } 5357 setOverlayGap(gap) { 5358 if (Type.isNumber(gap)) { 5359 this.overlayGap = gap; 5360 } 5361 } 5362 getOverlayGap() { 5363 return this.overlayGap; 5364 } 5365 } 5366 5367 class ZIndexStack { 5368 container; 5369 components; 5370 elements = new WeakMap(); 5371 baseIndex = 1000; 5372 baseStep = 50; 5373 sortCount = 0; 5374 constructor(container) { 5375 if (!Type.isDomNode(container)) { 5376 throw new Error("ZIndexManager.Stack: The 'container' argument must be a DOM element."); 5377 } 5378 this.container = container; 5379 const comparator = (componentA, componentB) => { 5380 let result = (Number(componentA.getAlwaysOnTop()) || 0) - (Number(componentB.getAlwaysOnTop()) || 0); 5381 if (!result) { 5382 result = componentA.getSort() - componentB.getSort(); 5383 } 5384 return result; 5385 }; 5386 this.components = new OrderedArray(comparator); 5387 } 5388 getBaseIndex() { 5389 return this.baseIndex; 5390 } 5391 setBaseIndex(index) { 5392 if (Type.isNumber(index) && index >= 0) { 5393 this.baseIndex = index; 5394 this.sort(); 5395 } 5396 } 5397 setBaseStep(step) { 5398 if (Type.isNumber(step) && step > 0) { 5399 this.baseStep = step; 5400 this.sort(); 5401 } 5402 } 5403 getBaseStep() { 5404 return this.baseStep; 5405 } 5406 register(element, options = {}) { 5407 if (this.getComponent(element)) { 5408 console.warn('ZIndexManager: You cannot register the element twice.', element); 5409 return this.getComponent(element); 5410 } 5411 const component = new ZIndexComponent(element, options); 5412 component.setStack(this); 5413 component.setSort(++this.sortCount); 5414 this.elements.set(element, component); 5415 this.components.add(component); 5416 this.sort(); 5417 return component; 5418 } 5419 unregister(element) { 5420 const component = this.elements.get(element); 5421 this.components.delete(component); 5422 this.elements.delete(element); 5423 this.sort(); 5424 } 5425 getComponent(element) { 5426 return this.elements.get(element) || null; 5427 } 5428 getComponents() { 5429 return this.components.getAll(); 5430 } 5431 getMaxZIndex() { 5432 const last = this.components.getLast(); 5433 return last ? last.getZIndex() : this.baseIndex; 5434 } 5435 sort() { 5436 this.components.sort(); 5437 let zIndex = this.baseIndex;
5438 this.components.forEach(component => { 5439 component.setZIndex(zIndex); 5440 zIndex += this.baseStep; 5441 }); 5442 } 5443 bringToFront(element) { 5444 const component = this.getComponent(element); 5445 if (!component) { 5446 console.error('ZIndexManager: element was not found in the stack.', element); 5447 return null; 5448 } 5449 component.setSort(++this.sortCount); 5450 this.sort(); 5451 return component; 5452 } 5453 } 5454 5455 class ZIndexManager { 5456 static stacks = new WeakMap(); 5457 static register(element, options = {}) { 5458 const parentNode = this.#getParentNode(element); 5459 if (!parentNode) { 5460 return null; 5461 } 5462 const stack = this.getOrAddStack(parentNode); 5463 return stack.register(element, options); 5464 } 5465 static unregister(element) { 5466 const parentNode = this.#getParentNode(element); 5467 const stack = this.getStack(parentNode); 5468 if (stack) { 5469 stack.unregister(element); 5470 } 5471 } 5472 static addStack(container) { 5473 const stack = new ZIndexStack(container); 5474 this.stacks.set(container, stack); 5475 return stack; 5476 } 5477 static getStack(container) { 5478 return this.stacks.get(container) || null; 5479 } 5480 static getOrAddStack(container) { 5481 return this.getStack(container) || this.addStack(container); 5482 } 5483 static getComponent(element) { 5484 const parentNode = this.#getParentNode(element, true); 5485 if (!parentNode) { 5486 return null; 5487 } 5488 const stack = this.getStack(parentNode); 5489 return stack ? stack.getComponent(element) : null; 5490 } 5491 static bringToFront(element) { 5492 const parentNode = this.#getParentNode(element); 5493 const stack = this.getStack(parentNode); 5494 if (stack) { 5495 return stack.bringToFront(element); 5496 } 5497 return null; 5498 } 5499 static #getParentNode(element, suppressWarnings = false) { 5500 if (!Type.isElementNode(element)) { 5501 if (!suppressWarnings) { 5502 console.error("ZIndexManager: The argument 'element' must be a DOM element.", element); 5503 } 5504 return null; 5505 } 5506 if (!Type.isElementNode(element.parentNode)) { 5507 if (!suppressWarnings) { 5508 console.error("ZIndexManager: The 'element' doesn't have a parent node.", element); 5509 } 5510 return null; 5511 } 5512 return element.parentNode; 5513 } 5514 } 5515 5516 const IS_WEAK_REF_SUPPORTED = typeof WeakRef !== 'undefined'; 5517 class WeakRefMap { 5518 #refs = new Map(); 5519 #registry = null; 5520 constructor() { 5521 if (IS_WEAK_REF_SUPPORTED) { 5522 this.#registry = new FinalizationRegistry(this.#cleanupCallback.bind(this)); 5523 } 5524 } 5525 clear() { 5526 if (!IS_WEAK_REF_SUPPORTED) { 5527 this.#refs.clear(); 5528 return; 5529 } 5530 this.#refs.forEach(ref => { 5531 const value = ref.deref(); 5532 if (!Type.isUndefined(value)) { 5533 this.#registry.unregister(value); 5534 } 5535 }); 5536 this.#refs.clear(); 5537 } 5538 delete(key) { 5539 if (!IS_WEAK_REF_SUPPORTED) { 5540 return this.#refs.delete(key); 5541 } 5542 const value = this.get(key); 5543 if (!Type.isUndefined(value)) { 5544 this.#registry.unregister(value); 5545 } 5546 return this.#refs.delete(key); 5547 } 5548 get(key) { 5549 if (!IS_WEAK_REF_SUPPORTED) { 5550 return this.#refs.get(key); 5551 } 5552 return this.#refs.get(key)?.deref(); 5553 } 5554 has(key) { 5555 if (!IS_WEAK_REF_SUPPORTED) { 5556 return this.#refs.has(key); 5557 } 5558 return !Type.isUndefined(this.#refs.get(key)?.deref()); 5559 } 5560 set(key, value) { 5561 if (!IS_WEAK_REF_SUPPORTED) { 5562 this.#refs.set(key, value); 5563 return this; 5564 } 5565 this.#refs.set(key, new WeakRef(value)); 5566 this.#registry.register(value, key, value); 5567 return this; 5568 } 5569 #cleanupCallback(key) { 5570 const ref = this.#refs.get(key); 5571 if (ref && !ref.deref()) { 5572 this.#refs.delete(key); 5573 } 5574 } 5575 } 5576 5577 var collections = { 5578 OrderedArray, 5579 SettingsCollection, 5580 WeakRefMap 5581 }; 5582 5583 class Transition { 5584 static linear(progress) { 5585 return progress; 5586 } 5587 static quad(progress) { 5588 return progress ** 2; 5589 } 5590 static cubic(progress) { 5591 return progress ** 3; 5592 } 5593 static quart(progress) { 5594 return progress ** 4; 5595 } 5596 static quint(progress) { 5597 return progress ** 5; 5598 } 5599 static circ(progress) { 5600 return 1 - Math.sin(Math.acos(progress)); 5601 } 5602 static back(progress) { 5603 return progress ** 2 * ((1.5 + 1) * progress - 1.5); 5604 } 5605 static elasti(progress) { 5606 return 2 ** (10 * (progress - 1)) * Math.cos(20 * Math.PI * 1.5 / 3 * progress); 5607 } 5608 static bounce(progress) { 5609 for (let a = 0, b = 1;; a += b, b /= 2) { 5610 if (progress >= (7 - 4 * a) / 11) { 5611 return -(((11 - 6 * a - 11 * progress) / 4) ** 2) + b ** 2; 5612 } 5613 } 5614 } 5615 } 5616 5617 class Easing { 5618 #duration = 1000; 5619 #transition = Transition.linear; 5620 #begin = null;
5621 #step = null; 5622 #complete = null; 5623 #start = {}; 5624 #finish = {}; 5625 #currentState = {}; 5626 #progress = null; 5627 #timer = null; 5628 #options = null; 5629 constructor(easingOptions) { 5630 this.setOptions(easingOptions); 5631 } 5632 setOptions(easingOptions) { 5633 const options = Type.isPlainObject(easingOptions) ? easingOptions : {}; 5634 this.#duration = Type.isNumber(options.duration) && options.duration > 0 ? options.duration : this.#duration; 5635 this.#begin = Type.isFunction(options.begin) || options.begin === null ? options.begin : this.#begin; 5636 this.#step = Type.isFunction(options.step) || options.step === null ? options.step : this.#step; 5637 this.#complete = Type.isFunction(options.complete) || options.complete === null ? options.complete : this.#complete; 5638 this.#progress = Type.isFunction(options.progress) || options.progress === null ? options.progress : this.#progress; 5639 this.#start = Type.isPlainObject(options.start) ? { 5640 ...options.start 5641 } : this.#start; 5642 this.#finish = Type.isPlainObject(options.finish) ? { 5643 ...options.finish 5644 } : this.#finish; 5645 } 5646 setTransition(transition) { 5647 if (Type.isFunction(transition)) { 5648 this.#transition = transition; 5649 } else if (Type.isStringFilled(transition)) { 5650 let funcName = transition; 5651 let decorator = null; 5652 if (transition.startsWith('ease-out-')) { 5653 funcName = funcName.replace('ease-out-', ''); 5654 decorator = Easing.makeEaseOut; 5655 } else if (transition.startsWith('ease-in-out-')) { 5656 funcName = funcName.replace('ease-in-out-', ''); 5657 decorator = Easing.makeEaseInOut; 5658 } 5659 if (Type.isFunction(Transition[funcName])) { 5660 this.#transition = decorator === null ? Transition[funcName] : decorator(Transition[funcName]); 5661 } 5662 } 5663 } 5664 animateProgress() { 5665 this.#animate(); 5666 } 5667 animate() { 5668 this.#progress = progress => { 5669 this.#currentState = {}; 5670 for (const propName of Object.keys(this.#start)) { 5671 this.#currentState[propName] = Math.round(this.#start[propName] + (this.#finish[propName] - this.#start[propName]) * progress); 5672 } 5673 if (this.#step !== null) { 5674 this.#step(this.#currentState); 5675 } 5676 }; 5677 this.#animate(); 5678 } 5679 #animate() { 5680 for (const propName of Object.keys(this.#start)) { 5681 if (Type.isUndefined(this.#finish[propName])) { 5682 delete this.#start[propName]; 5683 } 5684 } 5685 let start = null; 5686 const animation = time => { 5687 if (start === null) { 5688 start = time; 5689 } 5690 let progress = (time - start) / this.#duration; 5691 if (progress > 1) { 5692 progress = 1; 5693 } 5694 const delta = this.#transition(progress); 5695 this.#progress(delta); 5696 if (progress === 1) { 5697 this.stop(true); 5698 } else { 5699 this.#timer = requestAnimationFrame(animation); 5700 } 5701 }; 5702 if (this.#begin !== null) { 5703 this.#begin(this.#currentState); 5704 } 5705 this.#timer = requestAnimationFrame(animation); 5706 } 5707 get options() { 5708 if (this.#options === null) { 5709 this.#options = new Proxy(this, { 5710 get(target, property, receiver) { 5711 switch (property) { 5712 case 'transition': 5713 return target.#transition; 5714 case 'start': 5715 return target.#start; 5716 case 'finish': 5717 return target.#finish; 5718 case 'duration': 5719 return target.#duration; 5720 default: 5721 return null; 5722 } 5723 }, 5724 set(target, property, value, receiver) { 5725 target.setOptions({ 5726 [property]: value 5727 }); 5728 return true; 5729 } 5730 }); 5731 } 5732 return this.#options; 5733 } 5734 stop(completed = false) { 5735 if (this.#timer !== null) { 5736 cancelAnimationFrame(this.#timer); 5737 this.#timer = null; 5738 if (completed && this.#complete !== null) { 5739 this.#complete(this.#currentState); 5740 } 5741 } 5742 } 5743 static makeEaseInOut(delta) { 5744 return progress => { 5745 if (progress < 0.5) { 5746 return delta(2 * progress) / 2; 5747 } 5748 return (2 - delta(2 * (1 - progress))) / 2; 5749 }; 5750 } 5751 static makeEaseOut(delta) { 5752 return progress => { 5753 return 1 - delta(1 - progress); 5754 }; 5755 } 5756 static get transitions() { 5757 return Transition; 5758 } 5759 } 5760 5761 class LocalStorage { 5762 #prefix = null; 5763 constructor(storageOptions = {}) { 5764 const options = Type.isPlainObject(storageOptions) ? storageOptions : {}; 5765 this.#setPrefix(options.prefix); 5766 Event.bind(window, 'storage', this.#handleStorageChange.bind(this)); 5767 setInterval(this.#clear.bind(this), 5000); 5768 } 5769 set(key, value, ttl = 60) { 5770 if (!Type.isStringFilled(key) || Type.isNil(value)) { 5771 return false;
5772 } 5773 try { 5774 window.localStorage.setItem(this.getPrefix() + key, `${Math.round(Date.now() / 1000) + ttl}:${this.#encode(value)}`); 5775 } catch { 5776 console.error('LocalStorage error', key, ttl); 5777 return false; 5778 } 5779 return true; 5780 } 5781 get(key) { 5782 const storageValue = window.localStorage.getItem(this.getPrefix() + key); 5783 if (storageValue) { 5784 const valueParts = this.#parseValue(storageValue); 5785 if (valueParts === null) { 5786 return null; 5787 } 5788 const [ttl, value] = valueParts; 5789 if (Date.now() <= ttl) { 5790 return this.#decode(value); 5791 } 5792 this.remove(key); 5793 } 5794 return null; 5795 } 5796 remove(key) { 5797 window.localStorage.removeItem(this.getPrefix() + key); 5798 } 5799 getPrefix() { 5800 if (this.#prefix === null) { 5801 const userId = Loc.hasMessage('USER_ID') ? Loc.getMessage('USER_ID') : ''; 5802 const siteId = Loc.hasMessage('SITE_ID') ? Loc.getMessage('SITE_ID') : 'admin'; 5803 this.#prefix = `${this.getBasePrefix()}${userId}-${siteId}-`; 5804 } 5805 return this.#prefix; 5806 } 5807 getBasePrefix() { 5808 return 'bx'; 5809 } 5810 #setPrefix(prefix) { 5811 if (Type.isString(prefix)) { 5812 this.#prefix = `${this.getBasePrefix()}-${prefix}`; 5813 } 5814 } 5815 #handleStorageChange(event) { 5816 if (!Type.isStringFilled(event.key) || !event.key.startsWith(this.getPrefix())) { 5817 return; 5818 }
5819 const key = event.key.slice(this.getPrefix().length); 5820 const value = this.#getRealValue(event.newValue); 5821 const oldValue = this.#getRealValue(event.oldValue); 5822 const data = { 5823 key, 5824 value, 5825 oldValue 5826 }; 5827 if (key === 'BXGCE') { 5828 if (value) { 5829 const val = data.value; 5830 EventEmitter.emit(val.e, new BaseEvent({ 5831 data: val.p, 5832 compatData: val.p 5833 })); 5834 } 5835 } else { 5836 if (event.newValue) { 5837 EventEmitter.emit('onLocalStorageSet', new BaseEvent({ 5838 data: [data], 5839 compatData: [data] 5840 })); 5841 } 5842 if (event.oldValue && !event.newValue) { 5843 EventEmitter.emit('onLocalStorageRemove', new BaseEvent({ 5844 data: [data], 5845 compatData: [data] 5846 })); 5847 } 5848 EventEmitter.emit('onLocalStorageChange', new BaseEvent({ 5849 data: [data], 5850 compatData: [data] 5851 })); 5852 } 5853 } 5854 #clear() { 5855 const curDate = Date.now(); 5856 for (let i = 0; i < window.localStorage.length; i++) { 5857 const key = window.localStorage.key(i); 5858 if (key !== null && key.startsWith(this.getBasePrefix())) { 5859 const value = window.localStorage.getItem(key); 5860 const valueParts = this.#parseValue(value); 5861 if (valueParts === null) { 5862 continue; 5863 } 5864 const [ttl] = valueParts; 5865 if (curDate >= ttl) { 5866 window.localStorage.removeItem(key); 5867 } 5868 } 5869 } 5870 } 5871 #encode(value) { 5872 if (Type.isJsonValue(value)) { 5873 return JSON.stringify(value); 5874 } 5875 return value.toString(); 5876 } 5877 #decode(value) { 5878 let result = null; 5879 if (Type.isStringFilled(value)) { 5880 try { 5881 result = JSON.parse(value); 5882 } catch { 5883 result = value; 5884 } 5885 } 5886 return result; 5887 } 5888 #getRealValue(value) { 5889 const valueParts = this.#parseValue(value); 5890 if (valueParts === null) { 5891 return null; 5892 } 5893 return this.#decode(valueParts[1]); 5894 } 5895 #parseValue(value) { 5896 if (!this.#isValueValid(value)) { 5897 return null; 5898 } 5899 const [ttl] = value.split(':', 1); 5900 const realValue = value.slice(ttl.length + 1); 5901 return [parseInt(ttl, 10) * 1000, realValue]; 5902 } 5903 #isValueValid(value) { 5904 return Type.isStringFilled(value) && /^\d{10}:/.test(value); 5905 } 5906 } 5907 const localStorage$1 = new LocalStorage(); 5908 5909 class Page { 5910 static getRootWindow() { 5911 return this.getTopWindowOfCurrentHost(window); 5912 } 5913 static isCrossOriginObject(currentWindow) { 5914 try { 5915 void currentWindow.location.host; 5916 } catch { 5917 return true; 5918 } 5919 return false; 5920 } 5921 static getTopWindowOfCurrentHost(currentWindow) { 5922 if (!this.isCrossOriginObject(currentWindow.parent) && currentWindow.parent !== currentWindow && currentWindow.parent.location.host === currentWindow.location.host) { 5923 return this.getTopWindowOfCurrentHost(currentWindow.parent); 5924 } 5925 return currentWindow; 5926 } 5927 static getParentWindowOfCurrentHost(currentWindow) { 5928 if (this.isCrossOriginObject(currentWindow.parent)) { 5929 return currentWindow; 5930 } 5931 return currentWindow.parent; 5932 } 5933 static redirect(redirectUrl, redirectOptions = {}) { 5934 if (!Type.isStringFilled(redirectUrl)) { 5935 throw new Error('Redirect: "url" must be a non-empty string.'); 5936 } 5937 const rootWindow = this.getRootWindow(); 5938 let url = null; 5939 try { 5940 url = new URL(redirectUrl, rootWindow.location.origin); 5941 } catch { 5942 throw new Error(`Redirect: invalid URL: ${redirectUrl}`); 5943 } 5944 const options = Type.isPlainObject(redirectOptions) ? redirectOptions : {}; 5945 if (!this.#isSafeUrl(url, options.allowedOrigins)) { 5946 console.error(`Redirect: blocked potentially unsafe URL: ${url}`); 5947 return; 5948 } 5949 const wholeUrl = url.toString(); 5950 if (options.newTab === true) { 5951 const win = rootWindow.open(wholeUrl, '_blank', 'noopener,noreferrer'); 5952 if (win) { 5953 win.opener = null; 5954 } 5955 return; 5956 } 5957 if (options.replaceHistory === true) { 5958 rootWindow.location.replace(wholeUrl); 5959 } else { 5960 rootWindow.location.assign(wholeUrl); 5961 } 5962 } 5963 static reload() { 5964 const rootWindow = this.getRootWindow(); 5965 rootWindow.location.reload(); 5966 } 5967 static #isSafeUrl(url, allowedOrigins = []) { 5968 if (!(url instanceof URL)) { 5969 return false; 5970 } 5971 const allowedProtocols = ['http:', 'https:']; 5972 if (!allowedProtocols.includes(url.protocol)) { 5973 return false;
5974 } 5975 const rootWindow = this.getRootWindow(); 5976 if (url.origin === rootWindow.location.origin) { 5977 return true; 5978 } 5979 if (Type.isArray(allowedOrigins) && allowedOrigins.length > 0) { 5980 return allowedOrigins.includes(url.origin); 5981 } 5982 return false; 5983 } 5984 } 5985 5986 function getElement(element) { 5987 if (Type.isString(element)) { 5988 return document.getElementById(element); 5989 } 5990 return element; 5991 } 5992 5993 function getWindow(element) { 5994 if (Type.isElementNode(element)) { 5995 return element.ownerDocument.parentWindow || element.ownerDocument.defaultView || window; 5996 } 5997 if (Type.isDomNode(element)) { 5998 return element.parentWindow || element.defaultView || window; 5999 } 6000 return window; 6001 } 6002 6003 class FX { 6004 #easing = null; 6005 constructor(options) { 6006 const fxOptions = Type.isPlainObject(options) ? options : {}; 6007 const callback = Type.isFunction(fxOptions.callback) ? fxOptions.callback : null; 6008 const callbackStart = Type.isFunction(fxOptions.callback_start) ? fxOptions.callback_start : null; 6009 const callbackComplete = Type.isFunction(fxOptions.callback_complete) ? fxOptions.callback_complete : null; 6010 const easingOptions = { 6011 transition: 'linear', 6012 duration: Type.isNumber(fxOptions.time) && fxOptions.time > 0 ? fxOptions.time * 1000 : 1000, 6013 begin: state => { 6014 if (callbackStart !== null) { 6015 callbackStart(Type.isUndefined(state._param) ? state : state._param); 6016 } 6017 }, 6018 step: state => { 6019 if (callback !== null) { 6020 callback(Type.isUndefined(state._param) ? state : state._param); 6021 } 6022 }, 6023 complete: state => { 6024 if (callbackComplete !== null) { 6025 callbackComplete(Type.isUndefined(state._param) ? state : state._param); 6026 } 6027 } 6028 }; 6029 if (Type.isPlainObject(fxOptions.start)) { 6030 easingOptions.start = fxOptions.start; 6031 easingOptions.finish = fxOptions.finish; 6032 } else { 6033 easingOptions.start = { 6034 _param: fxOptions.start 6035 }; 6036 easingOptions.finish = { 6037 _param: fxOptions.finish 6038 }; 6039 } 6040 if (fxOptions.type === 'accelerated') { 6041 easingOptions.transition = 'quint'; 6042 } else if (fxOptions.type === 'decelerated') { 6043 fxOptions.transition = 'ease-out-quint'; 6044 } 6045 this.#easing = new Easing(easingOptions); 6046 } 6047 start() { 6048 this.#easing.animate(); 6049 return this; 6050 } 6051 stop(silent = false) { 6052 this.#easing.stop(silent); 6053 } 6054 pause() { 6055 } 6056 static hide(el, type, opts) { 6057 return this.#toggle('hide', el, type, opts); 6058 } 6059 static show(el, type, opts) { 6060 return this.#toggle('show', el, type, opts); 6061 } 6062 static #toggle(mode, el, type, opts) { 6063 let options = {}; 6064 let effect = null; 6065 const element = Type.isStringFilled(el) ? document.getElementById(el) : el; 6066 if (Type.isPlainObject(type) && Type.isNil(opts)) { 6067 options = type; 6068 effect = options.type; 6069 } else if (Type.isPlainObject(opts)) { 6070 options = opts; 6071 effect = type; 6072 } 6073 if (!Type.isStringFilled(effect)) { 6074 Dom.style(element, 'display', mode === 'show' ? 'block' : 'none'); 6075 return undefined; 6076 } 6077 const fxOptions = effect === 'scroll' ? this.#scroll(element, options, mode) : this.#fade(element, options, mode); 6078 fxOptions.callback_complete = () => { 6079 if (options.show !== false && options.hide !== false) { 6080 Dom.style(element, 'display', mode === 'show' ? 'block' : 'none'); 6081 } 6082 if (options.callback_complete) { 6083 options.callback_complete(); 6084 } 6085 }; 6086 return new FX(fxOptions).start(); 6087 } 6088 static #scroll(el, opts, mode) { 6089 const param = opts.direction === 'horizontal' ? 'width' : 'height'; 6090 let currentValue = parseInt(String(Dom.style(el, param)), 10); 6091 if (Number.isNaN(currentValue)) { 6092 currentValue = Dom.getPosition(el)[param]; 6093 } 6094 const start = currentValue; 6095 const finish = opts.min_height ? parseInt(opts.min_height, 10) : 0; 6096 return { 6097 start, 6098 finish, 6099 time: opts.time || 1, 6100 type: 'linear', 6101 callback_start: () => { 6102 if (Dom.style(el, 'position') === 'static') { 6103 Dom.style(el, 'position', 'relative'); 6104 } 6105 Dom.style(el, 'overflow', 'hidden'); 6106 Dom.style(el, param, `${start}px`); 6107 Dom.style(el, 'display', 'block'); 6108 }, 6109 callback: value => { 6110 Dom.style(el, param, `${value}px`); 6111 } 6112 }; 6113 } 6114 static #fade(element, opts, mode) { 6115 return { 6116 time: opts.time || 1, 6117 type: mode === 'show' ? 'linear' : 'decelerated', 6118 start: mode === 'show' ? 0 : 100, 6119 finish: mode === 'show' ? 100 : 0, 6120 callback_start: () => { 6121 Dom.style(element, 'display', 'block'); 6122 }, 6123 callback: val => { 6124 Dom.style(element, 'opacity', val / 100); 6125 } 6126 }; 6127 } 6128 } 6129 6130 const { 6131 getClass, 6132 namespace 6133 } = Reflection; 6134 const message = message$1;
6135 const easing = Easing; 6136 const fx = FX; 6137 const PageObject = Page; 6138 const { 6139 replace, 6140 remove, 6141 clean, 6142 insertBefore, 6143 insertAfter, 6144 append, 6145 prepend, 6146 style, 6147 adjust, 6148 create, 6149 isShown 6150 } = Dom; 6151 const addClass = function addClass() { 6152 Dom.addClass(...Runtime.merge([], Array.from(arguments), [getElement(arguments[0])])); 6153 }; 6154 const removeClass = function removeClass() { 6155 Dom.removeClass(...Runtime.merge(Array.from(arguments), [getElement(arguments[0])])); 6156 }; 6157 const hasClass = function hasClass() { 6158 return Dom.hasClass(...Runtime.merge(Array.from(arguments), [getElement(arguments[0])])); 6159 }; 6160 const toggleClass = function toggleClass() { 6161 Dom.toggleClass(...Runtime.merge(Array.from(arguments), [getElement(arguments[0])])); 6162 }; 6163 const cleanNode = (element, removeElement = false) => { 6164 const currentElement = getElement(element); 6165 if (Type.isDomNode(currentElement)) { 6166 Dom.clean(currentElement); 6167 if (removeElement) { 6168 Dom.remove(currentElement); 6169 return currentElement; 6170 } 6171 } 6172 return currentElement; 6173 }; 6174 const getCookie = Http.Cookie.get; 6175 const setCookie = (name, value, options = {}) => { 6176 const attributes = { 6177 ...options 6178 }; 6179 if (Type.isNumber(attributes.expires)) { 6180 attributes.expires /= 3600 * 24; 6181 } 6182 Http.Cookie.set(name, value, attributes); 6183 }; 6184 const { 6185 bind, 6186 unbind, 6187 unbindAll, 6188 bindOnce, 6189 ready 6190 } = Event; 6191 const { 6192 debugState: debugEnableFlag, 6193 isDebugEnabled: debugStatus, 6194 default: debug 6195 } = debugNs; 6196 const debugEnable = value => { 6197 if (value) { 6198 enableDebug(); 6199 } else { 6200 disableDebug(); 6201 } 6202 }; 6203 const { 6204 clone, 6205 loadExtension: loadExt, 6206 debounce, 6207 throttle, 6208 html 6209 } = Runtime; 6210 const type = { 6211 ...Object.getOwnPropertyNames(Type).filter(key => !['name', 'length', 'prototype', 'caller', 'arguments'].includes(key)).reduce((acc, key) => { 6212 acc[key] = Type[key]; 6213 return acc; 6214 }, {}), 6215 isNotEmptyString: value => Type.isString(value) && value !== '', 6216 isNotEmptyObject: value => Type.isObjectLike(value) && Object.keys(value).length > 0, 6217 isMapKey: Type.isObject, 6218 stringToInt: value => { 6219 const parsed = parseInt(value); 6220 return !Number.isNaN(parsed) ? parsed : 0; 6221 } 6222 }; 6223 const browser = { 6224 IsOpera: Browser.isOpera, 6225 IsIE: Browser.isIE, 6226 IsIE6: Browser.isIE6, 6227 IsIE7: Browser.isIE7, 6228 IsIE8: Browser.isIE8, 6229 IsIE9: Browser.isIE9, 6230 IsIE10: Browser.isIE10, 6231 IsIE11: Browser.isIE11, 6232 IsSafari: Browser.isSafari, 6233 IsFirefox: Browser.isFirefox, 6234 IsChrome: Browser.isChrome, 6235 DetectIeVersion: Browser.detectIEVersion, 6236 IsMac: Browser.isMac, 6237 IsAndroid: Browser.isAndroid, 6238 isIPad: Browser.isIPad, 6239 isIPhone: Browser.isIPhone, 6240 IsIOS: Browser.isIOS, 6241 IsMobile: Browser.isMobile, 6242 isRetina: Browser.isRetina, 6243 IsDoctype: Browser.isDoctype, 6244 SupportLocalStorage: Browser.isLocalStorageSupported, 6245 addGlobalClass: Browser.addGlobalClass, 6246 DetectAndroidVersion: Browser.detectAndroidVersion, 6247 isPropertySupported: Browser.isPropertySupported, 6248 addGlobalFeatures: Browser.addGlobalFeatures 6249 }; 6250 const ajax = window.BX ? window.BX.ajax : () => {}; 6251 function GetWindowScrollSize(doc = document) { 6252 return { 6253 scrollWidth: doc.documentElement.scrollWidth, 6254 scrollHeight: doc.documentElement.scrollHeight 6255 }; 6256 } 6257 function GetWindowScrollPos(doc = document) { 6258 const win = getWindow(doc); 6259 return { 6260 scrollLeft: win.pageXOffset, 6261 scrollTop: win.pageYOffset 6262 }; 6263 } 6264 function GetWindowInnerSize(doc = document) { 6265 const win = getWindow(doc); 6266 return { 6267 innerWidth: win.innerWidth, 6268 innerHeight: win.innerHeight 6269 }; 6270 } 6271 function GetWindowSize(doc = document) { 6272 return { 6273 ...GetWindowInnerSize(doc), 6274 ...GetWindowScrollPos(doc), 6275 ...GetWindowScrollSize(doc) 6276 }; 6277 } 6278 function GetContext(node) { 6279 return getWindow(node); 6280 } 6281 function pos(element, relative = false) { 6282 if (!element) { 6283 return new DOMRect().toJSON(); 6284 } 6285 if (element.ownerDocument === document && !relative) { 6286 const clientRect = element.getBoundingClientRect(); 6287 const root = document.documentElement; 6288 const { 6289 body 6290 } = document; 6291 return { 6292 top: Math.round(clientRect.top + (root.scrollTop || body.scrollTop)), 6293 left: Math.round(clientRect.left + (root.scrollLeft || body.scrollLeft)), 6294 width: Math.round(clientRect.right - clientRect.left), 6295 height: Math.round(clientRect.bottom - clientRect.top), 6296 right: Math.round(clientRect.right + (root.scrollLeft || body.scrollLeft)), 6297 bottom: Math.round(clientRect.bottom + (root.scrollTop || body.scrollTop)) 6298 }; 6299 } 6300 let x = 0; 6301 let y = 0; 6302 const w = element.offsetWidth; 6303 const h = element.offsetHeight; 6304 let first = true; 6305 for (; element != null; element = element.offsetParent) { 6306 if (!first && relative && window.BX.is_relative(element)) { 6307 break; 6308 } 6309 x += element.offsetLeft; 6310 y += element.offsetTop; 6311 if (first) { 6312 first = false;
6313 continue; 6314 } 6315 x += Text.toNumber(Dom.style(element, 'border-left-width')); 6316 y += Text.toNumber(Dom.style(element, 'border-top-width')); 6317 } 6318 return new DOMRect(x, y, w, h).toJSON(); 6319 } 6320 function addCustomEvent(eventObject, eventName, eventHandler) { 6321 if (Type.isString(eventObject)) { 6322 eventHandler = eventName; 6323 eventName = eventObject; 6324 eventObject = EventEmitter.GLOBAL_TARGET; 6325 } 6326 if (eventObject === window) { 6327 eventObject = EventEmitter.GLOBAL_TARGET; 6328 } 6329 if (!Type.isObject(eventObject)) { 6330 console.error('The "eventObject" argument must be an object. Received type ' + typeof eventObject + '.'); 6331 return; 6332 } 6333 if (!Type.isStringFilled(eventName)) { 6334 console.error('The "eventName" argument must be a string.'); 6335 return; 6336 } 6337 if (!Type.isFunction(eventHandler)) { 6338 console.error('The "eventHandler" argument must be a function. Received type ' + typeof eventHandler + '.'); 6339 return; 6340 } 6341 eventName = eventName.toLowerCase(); 6342 EventEmitter.subscribe(eventObject, eventName, eventHandler, { 6343 compatMode: true, 6344 useGlobalNaming: true 6345 }); 6346 } 6347 function onCustomEvent(eventObject, eventName, eventParams, secureParams) { 6348 if (Type.isString(eventObject)) {
6349 secureParams = eventParams; 6350 eventParams = eventName; 6351 eventName = eventObject; 6352 eventObject = EventEmitter.GLOBAL_TARGET; 6353 } 6354 if (!Type.isObject(eventObject) || eventObject === window) { 6355 eventObject = EventEmitter.GLOBAL_TARGET; 6356 } 6357 if (!eventParams) { 6358 eventParams = []; 6359 } 6360 eventName = eventName.toLowerCase(); 6361 const event = new BaseEvent(); 6362 event.setData(eventParams); 6363 event.setCompatData(eventParams); 6364 EventEmitter.emit(eventObject, eventName, event, { 6365 cloneData: secureParams === true, 6366 useGlobalNaming: true 6367 }); 6368 } 6369 function removeCustomEvent(eventObject, eventName, eventHandler) { 6370 if (Type.isString(eventObject)) { 6371 eventHandler = eventName; 6372 eventName = eventObject; 6373 eventObject = EventEmitter.GLOBAL_TARGET; 6374 } 6375 if (!Type.isFunction(eventHandler)) { 6376 console.error('The "eventHandler" argument must be a function. Received type ' + typeof eventHandler + '.'); 6377 return; 6378 } 6379 if (eventObject === window) { 6380 eventObject = EventEmitter.GLOBAL_TARGET; 6381 } 6382 eventName = eventName.toLowerCase(); 6383 EventEmitter.unsubscribe(eventObject, eventName, eventHandler, { 6384 useGlobalNaming: true 6385 }); 6386 } 6387 function removeAllCustomEvents(eventObject, eventName) { 6388 if (Type.isString(eventObject)) { 6389 eventName = eventObject; 6390 eventObject = EventEmitter.GLOBAL_TARGET;
6391 } 6392 if (eventObject === window) { 6393 eventObject = EventEmitter.GLOBAL_TARGET; 6394 } 6395 eventName = eventName.toLowerCase(); 6396 EventEmitter.unsubscribeAll(eventObject, eventName, { 6397 useGlobalNaming: true 6398 }); 6399 } 6400 function onGlobalCustomEvent(eventName, arEventParams, bSkipSelf) { 6401 localStorage$1.set('BXGCE', { 6402 e: eventName, 6403 p: arEventParams 6404 }, 1); 6405 if (!bSkipSelf) { 6406 onCustomEvent(eventName, arEventParams); 6407 } 6408 } 6409 6410 exports.BaseError = BaseError; 6411 exports.Browser = Browser; 6412 exports.Cache = Cache; 6413 exports.Collections = collections; 6414 exports.Dom = Dom; 6415 exports.Easing = Easing; 6416 exports.Event = Event; 6417 exports.Extension = Extension; 6418 exports.GetContext = GetContext; 6419 exports.GetWindowInnerSize = GetWindowInnerSize; 6420 exports.GetWindowScrollPos = GetWindowScrollPos; 6421 exports.GetWindowScrollSize = GetWindowScrollSize; 6422 exports.GetWindowSize = GetWindowSize; 6423 exports.Http = Http; 6424 exports.Loc = Loc; 6425 exports.LocalStorage = LocalStorage; 6426 exports.Page = Page; 6427 exports.PageObject = PageObject; 6428 exports.Reflection = Reflection; 6429 exports.Runtime = Runtime; 6430 exports.Tag = Tag; 6431 exports.Text = Text; 6432 exports.Type = Type; 6433 exports.Uri = Uri; 6434 exports.Validation = Validation; 6435 exports.ZIndexManager = ZIndexManager; 6436 exports.addClass = addClass; 6437 exports.addCustomEvent = addCustomEvent; 6438 exports.adjust = adjust; 6439 exports.ajax = ajax; 6440 exports.append = append; 6441 exports.bind = bind; 6442 exports.bindOnce = bindOnce; 6443 exports.browser = browser; 6444 exports.clean = clean; 6445 exports.cleanNode = cleanNode; 6446 exports.clone = clone; 6447 exports.create = create; 6448 exports.debounce = debounce; 6449 exports.debug = debug; 6450 exports.debugEnable = debugEnable; 6451 exports.debugEnableFlag = debugEnableFlag; 6452 exports.debugStatus = debugStatus; 6453 exports.easing = easing; 6454 exports.fx = fx; 6455 exports.getClass = getClass; 6456 exports.getCookie = getCookie; 6457 exports.hasClass = hasClass; 6458 exports.html = html; 6459 exports.insertAfter = insertAfter; 6460 exports.insertBefore = insertBefore; 6461 exports.isShown = isShown; 6462 exports.loadExt = loadExt; 6463 exports.localStorage = localStorage$1; 6464 exports.message = message; 6465 exports.namespace = namespace; 6466 exports.onCustomEvent = onCustomEvent; 6467 exports.onGlobalCustomEvent = onGlobalCustomEvent; 6468 exports.pos = pos; 6469 exports.prepend = prepend; 6470 exports.ready = ready; 6471 exports.remove = remove; 6472 exports.removeAllCustomEvents = removeAllCustomEvents; 6473 exports.removeClass = removeClass; 6474 exports.removeCustomEvent = removeCustomEvent; 6475 exports.replace = replace; 6476 exports.setCookie = setCookie; 6477 exports.style = style; 6478 exports.throttle = throttle; 6479 exports.toggleClass = toggleClass; 6480 exports.type = type; 6481 exports.unbind = unbind; 6482 exports.unbindAll = unbindAll; 6483 6484})(this.BX = this.BX || {}); 6485 6486 6487 6488(function(BX) { 6489 /* list of registered proxy functions */ 6490 var proxyList = new WeakMap(); 6491 var deferList = new WeakMap(); 6492 6493 /* List of denied event handlers */ 6494 var deniedEvents = []; 6495 6496 /* list of registered custom events */ 6497 var customEvents = new WeakMap(); 6498 var customEventsCnt = 0; 6499 6500 /* list of external garbage collectors */ 6501 var garbageCollectors = []; 6502 6503 /* list of loaded CSS files */ 6504 var cssList = []; 6505 var cssInit = false; 6506 6507 /* list of loaded JS files */ 6508 var jsList = []; 6509 var jsInit = false; 6510 6511 var eventTypes = { 6512 click: 'MouseEvent', 6513 dblclick: 'MouseEvent', 6514 mousedown: 'MouseEvent', 6515 mousemove: 'MouseEvent', 6516 mouseout: 'MouseEvent', 6517 mouseover: 'MouseEvent', 6518 mouseup: 'MouseEvent', 6519 focus: 'MouseEvent', 6520 blur: 'MouseEvent' 6521 }; 6522 6523 var lastWait = []; 6524 6525 var CHECK_FORM_ELEMENTS = {tagName: /^INPUT|SELECT|TEXTAREA|BUTTON$/i}; 6526 6527 BX.MSLEFT = 1; 6528 BX.MSMIDDLE = 2; 6529 BX.MSRIGHT = 4; 6530 6531 BX.AM_PM_UPPER = 1; 6532 BX.AM_PM_LOWER = 2; 6533 BX.AM_PM_NONE = false; 6534 6535 BX.ext = function(ob) 6536 { 6537 for (var i in ob) 6538 { 6539 if(ob.hasOwnProperty(i)) 6540 { 6541 this[i] = ob[i]; 6542 } 6543 } 6544 }; 6545 6546 var r = { 6547 script: /<script([^>]*)>/ig, 6548 script_end: /<\/script>/ig, 6549 script_src: /src=["\']([^"\']+)["\']/i, 6550 script_type: /type=["\']([^"\']+)["\']/i, 6551 space: /\s+/, 6552 ltrim: /^[\s\r\n]+/g, 6553 rtrim: /[\s\r\n]+$/g, 6554 style: /<link[^>]*?(rel="stylesheet"|type="text\/css")[^>]*>/i, 6555 style_href: /href=["\']([^"\']+)["\']/i 6556 }; 6557 6558 BX.processHTML = function(data, scriptsRunFirst) 6559 { 6560 var matchScript, matchStyle, matchSrc, matchHref, matchType, scripts = [], styles = []; 6561 var textIndexes = []; 6562 var lastIndex = r.script.lastIndex = r.script_end.lastIndex = 0; 6563 6564 while ((matchScript = r.script.exec(data)) !== null) 6565 { 6566 r.script_end.lastIndex = r.script.lastIndex; 6567 var matchScriptEnd = r.script_end.exec(data); 6568 if (matchScriptEnd === null) 6569 { 6570 break; 6571 } 6572 6573 // skip script tags of special types 6574 var skipTag = false;
6575 if ((matchType = matchScript[1].match(r.script_type)) !== null) 6576 { 6577 if( 6578 matchType[1] == 'text/html' 6579 || matchType[1] == 'text/template' 6580 || matchType[1] == 'extension/settings' 6581 ) 6582 { 6583 skipTag = true; 6584 } 6585 } 6586 6587 if(skipTag) 6588 { 6589 textIndexes.push([lastIndex, r.script_end.lastIndex - lastIndex]); 6590 } 6591 else 6592 { 6593 textIndexes.push([lastIndex, matchScript.index - lastIndex]); 6594 6595 var bRunFirst = scriptsRunFirst || (matchScript[1].indexOf('bxrunfirst') != '-1'); 6596 6597 if ((matchSrc = matchScript[1].match(r.script_src)) !== null) 6598 { 6599 scripts.push({"bRunFirst": bRunFirst, "isInternal": false, "JS": matchSrc[1]}); 6600 } 6601 else 6602 { 6603 var start = matchScript.index + matchScript[0].length; 6604 var js = data.substr(start, matchScriptEnd.index-start); 6605 6606 scripts.push({"bRunFirst": bRunFirst, "isInternal": true, "JS": js}); 6607 } 6608 } 6609 6610 lastIndex = matchScriptEnd.index + 9; 6611 r.script.lastIndex = lastIndex; 6612 } 6613 6614 textIndexes.push([lastIndex, lastIndex === 0 ? data.length : data.length - lastIndex]); 6615 var pureData = ""; 6616 for (var i = 0, length = textIndexes.length; i < length; i++) 6617 { 6618 if (BX.type.isString(data) && BX.type.isFunction(data.substr)) 6619 { 6620 pureData += data.substr(textIndexes[i][0], textIndexes[i][1]); 6621 } 6622 } 6623 6624 while ((matchStyle = pureData.match(r.style)) !== null) 6625 { 6626 if ((matchHref = matchStyle[0].match(r.style_href)) !== null && matchStyle[0].indexOf('media="') < 0) 6627 { 6628 styles.push(matchHref[1]); 6629 } 6630 6631 pureData = pureData.replace(matchStyle[0], ''); 6632 } 6633 6634 return {'HTML': pureData, 'SCRIPT': scripts, 'STYLE': styles}; 6635 }; 6636 6637 /* OO emulation utility */ 6638 BX.extend = function(child, parent) 6639 { 6640 var f = function() {}; 6641 f.prototype = parent.prototype; 6642 6643 child.prototype = new f(); 6644 child.prototype.constructor = child; 6645 6646 child.superclass = parent.prototype; 6647 child.prototype.superclass = parent.prototype; 6648 if(parent.prototype.constructor == Object.prototype.constructor) 6649 { 6650 parent.prototype.constructor = parent; 6651 } 6652 }; 6653 6654 BX.is_subclass_of = function(ob, parent_class) 6655 { 6656 if (ob instanceof parent_class) 6657 return true; 6658 6659 if (parent_class.superclass) 6660 return BX.is_subclass_of(ob, parent_class.superclass); 6661 6662 return false; 6663 }; 6664 6665 BX.clearNodeCache = function() 6666 { 6667 return false; 6668 }; 6669 6670 BX.bitrix_sessid = function() {return BX.message("bitrix_sessid"); }; 6671 6672 /** 6673 * Creates document fragment with child nodes. 6674 * 6675 * @param {Node[]} nodes 6676 * @return {DocumentFragment} 6677 */ 6678 BX.createFragment = function(nodes) 6679 { 6680 var fragment = document.createDocumentFragment(); 6681 6682 if(!BX.type.isArray(nodes)) 6683 { 6684 return fragment; 6685 } 6686 for(var i = 0; i < nodes.length; i++) 6687 { 6688 fragment.appendChild(nodes[i]); 6689 } 6690 6691 return fragment; 6692 }; 6693 6694 /** 6695 * @deprecated 6696 * @use BX.style 6697 * @param element 6698 * @param opacity 6699 */ 6700 BX.setOpacity = function(element, opacity) 6701 { 6702 var opacityValue = parseFloat(opacity); 6703 6704 if (!isNaN(opacityValue) && BX.type.isDomNode(element)) 6705 { 6706 opacityValue = opacityValue < 1 ? opacityValue : opacityValue / 100; 6707 BX.style(element, 'opacity', opacityValue); 6708 } 6709 }; 6710 6711 /** 6712 * @deprecated 6713 * @param el 6714 * @return {*} 6715 */ 6716 BX.hoverEvents = function(el) 6717 { 6718 if (el) 6719 return BX.adjust(el, {events: BX.hoverEvents()}); 6720 else 6721 return {mouseover: BX.hoverEventsHover, mouseout: BX.hoverEventsHout}; 6722 }; 6723 6724 /** 6725 * @deprecated 6726 */ 6727 BX.hoverEventsHover = function(){BX.addClass(this,'bx-hover');this.BXHOVER=true;}; 6728 /** 6729 * @deprecated 6730 */ 6731 BX.hoverEventsHout = function(){BX.removeClass(this,'bx-hover');this.BXHOVER=false;}; 6732 6733 /** 6734 * @deprecated 6735 */ 6736 BX.focusEvents = function(el) 6737 { 6738 if (el) 6739 return BX.adjust(el, {events: BX.focusEvents()}); 6740 else 6741 return {mouseover: BX.focusEventsFocus, mouseout: BX.focusEventsBlur}; 6742 }; 6743 6744 /** 6745 * @deprecated 6746 */ 6747 BX.focusEventsFocus = function(){BX.addClass(this,'bx-focus');this.BXFOCUS=true;}; 6748 /** 6749 * @deprecated 6750 */ 6751 BX.focusEventsBlur = function(){BX.removeClass(this,'bx-focus');this.BXFOCUS=false;}; 6752 6753 BX.setUnselectable = function(node) 6754 { 6755 BX.style(node, { 6756 'userSelect': 'none', 6757 'MozUserSelect': 'none', 6758 'WebkitUserSelect': 'none', 6759 'KhtmlUserSelect': 'none', 6760 }); 6761 node.setAttribute('unSelectable', 'on'); 6762 }; 6763 6764 BX.setSelectable = function(node) 6765 { 6766 BX.style(node, { 6767 'userSelect': null, 6768 'MozUserSelect': null, 6769 'WebkitUserSelect': null, 6770 'KhtmlUserSelect': null, 6771 }); 6772 node.removeAttribute('unSelectable'); 6773 }; 6774 6775 BX.styleIEPropertyName = function(name) 6776 { 6777 if (name == 'float') 6778 name = BX.browser.IsIE() ? 'styleFloat' : 'cssFloat'; 6779 else 6780 { 6781 var res = BX.browser.isPropertySupported(name); 6782 if (res) 6783 { 6784 name = res; 6785 } 6786 else 6787 {
6788 var reg = /(\-([a-z]){1})/g; 6789 if (reg.test(name)) 6790 { 6791 name = name.replace(reg, function () {return arguments[2].toUpperCase();}); 6792 } 6793 } 6794 } 6795 return name; 6796 }; 6797 6798 BX.focus = function(el) 6799 { 6800 try 6801 { 6802 el.focus(); 6803 return true; 6804 } 6805 catch (e) 6806 { 6807 return false; 6808 } 6809 }; 6810 6811 BX.firstChild = function(el) 6812 { 6813 return BX.type.isDomNode(el) ? el.firstElementChild : null; 6814 }; 6815 6816 BX.lastChild = function(el) 6817 { 6818 return BX.type.isDomNode(el) ? el.lastElementChild : null; 6819 }; 6820 6821 BX.previousSibling = function(el) 6822 { 6823 return BX.type.isDomNode(el) ? el.previousElementSibling : null; 6824 }; 6825 6826 BX.nextSibling = function(el) 6827 { 6828 return BX.type.isDomNode(el) ? el.nextElementSibling : null; 6829 }; 6830 6831 /* 6832 params: { 6833 obj : html node 6834 className : className value 6835 recursive : used only for older browsers to optimize the tree traversal, in new browsers the search is always recursively, default - true 6836 } 6837 6838 Search all nodes with className 6839 */ 6840 /** 6841 * @deprecated 6842 * @use .querySelectorAll 6843 * @param obj 6844 * @param className 6845 * @param recursive 6846 * @return {*} 6847 */ 6848 BX.findChildrenByClassName = function(obj, className, recursive) 6849 { 6850 if(!obj || !obj.childNodes) return null; 6851 6852 var result = []; 6853 if (typeof(obj.getElementsByClassName) == 'undefined') 6854 { 6855 recursive = recursive !== false; 6856 result = BX.findChildren(obj, {className : className}, recursive); 6857 } 6858 else 6859 { 6860 var col = obj.getElementsByClassName(className); 6861 for (i=0,l=col.length;i<l;i++) 6862 { 6863 result[i] = col[i]; 6864 } 6865 } 6866 return result; 6867 }; 6868 6869 /* 6870 params: { 6871 obj : html node 6872 className : className value 6873 recursive : used only for older browsers to optimize the tree traversal, in new browsers the search is always recursively, default - true 6874 } 6875 6876 Search first node with className 6877 */ 6878 /** 6879 * @deprecated 6880 * @use .querySelector 6881 * @param obj 6882 * @param className 6883 * @param recursive 6884 * @return {*} 6885 */ 6886 BX.findChildByClassName = function(obj, className, recursive) 6887 { 6888 if(!obj || !obj.childNodes) return null; 6889 6890 var result = null; 6891 if (typeof(obj.getElementsByClassName) == 'undefined') 6892 { 6893 recursive = recursive !== false; 6894 result = BX.findChild(obj, {className : className}, recursive); 6895 } 6896 else 6897 { 6898 var col = obj.getElementsByClassName(className); 6899 if (col && typeof(col[0]) != 'undefined') 6900 { 6901 result = col[0]; 6902 } 6903 else 6904 { 6905 result = null; 6906 } 6907 } 6908 return result; 6909 }; 6910 6911 /* 6912 params: { 6913 tagName|tag : 'tagName', 6914 className|class : 'className', 6915 attribute : {attribute : value, attribute : value} | attribute | [attribute, attribute....], 6916 property : {prop: value, prop: value} | prop | [prop, prop] 6917 } 6918 6919 all values can be RegExps or strings 6920 */ 6921 /** 6922 * @deprecated 6923 * @use .querySelectorAll 6924 * @param obj 6925 * @param params 6926 * @param recursive 6927 * @return {*|Node} 6928 */ 6929 BX.findChildren = function(obj, params, recursive) 6930 { 6931 return BX.findChild(obj, params, recursive, true); 6932 }; 6933 6934 /** 6935 * @deprecated 6936 * @use .querySelectorAll 6937 * @param obj 6938 * @param params 6939 * @param recursive 6940 * @param get_all 6941 * @return {*} 6942 */ 6943 BX.findChild = function(obj, params, recursive, get_all) 6944 { 6945 if(!obj || !obj.childNodes) return null; 6946 6947 recursive = !!recursive; get_all = !!get_all; 6948 6949 var n = obj.childNodes.length, result = []; 6950 6951 for (var j=0; j<n; j++) 6952 { 6953 var child = obj.childNodes[j]; 6954 6955 if (_checkNode(child, params)) 6956 { 6957 if (get_all) 6958 result.push(child); 6959 else 6960 return child; 6961 } 6962 6963 if(recursive == true) 6964 { 6965 var res = BX.findChild(child, params, recursive, get_all); 6966 if (res) 6967 { 6968 if (get_all) 6969 result = BX.util.array_merge(result, res); 6970 else 6971 return res; 6972 } 6973 } 6974 } 6975 6976 if (get_all || result.length > 0) 6977 return result; 6978 else 6979 return null; 6980 }; 6981 6982 /** 6983 * @deprecated 6984 * @use .closest() 6985 * @param obj 6986 * @param params 6987 * @param maxParent 6988 * @return {*} 6989 */ 6990 BX.findParent = function(obj, params, maxParent) 6991 { 6992 if(!obj) 6993 return null; 6994 6995 var o = obj; 6996 while(o.parentNode) 6997 { 6998 var parent = o.parentNode; 6999 7000 if (_checkNode(parent, params)) 7001 return parent; 7002 7003 o = parent; 7004 7005 if (!!maxParent &&
7006 (BX.type.isFunction(maxParent) 7007 || typeof maxParent == 'object')) 7008 { 7009 if (BX.type.isElementNode(maxParent)) 7010 { 7011 if (o == maxParent) 7012 break; 7013 } 7014 else 7015 { 7016 if (_checkNode(o, maxParent)) 7017 break; 7018 } 7019 } 7020 } 7021 return null; 7022 }; 7023 7024 /** 7025 * @deprecated 7026 * @use .querySelector 7027 * @param obj 7028 * @param params 7029 * @return {*} 7030 */ 7031 BX.findNextSibling = function(obj, params) 7032 { 7033 if(!obj) 7034 return null; 7035 var o = obj; 7036 while(o.nextSibling) 7037 { 7038 var sibling = o.nextSibling; 7039 if (_checkNode(sibling, params)) 7040 return sibling; 7041 o = sibling; 7042 } 7043 return null; 7044 }; 7045 7046 /** 7047 * @deprecated 7048 * @use .querySelector 7049 * @param obj 7050 * @param params 7051 * @return {*} 7052 */ 7053 BX.findPreviousSibling = function(obj, params) 7054 { 7055 if(!obj) 7056 return null; 7057 7058 var o = obj; 7059 while(o.previousSibling) 7060 { 7061 var sibling = o.previousSibling; 7062 if(_checkNode(sibling, params)) 7063 return sibling; 7064 o = sibling; 7065 } 7066 return null; 7067 }; 7068 7069 BX.checkNode = function(obj, params) 7070 { 7071 return _checkNode(obj, params); 7072 }; 7073 7074 /** 7075 * @deprecated 7076 * @use .querySelectorAll 7077 * @param form 7078 * @return {Array} 7079 */ 7080 BX.findFormElements = function(form) 7081 { 7082 if (BX.type.isString(form)) 7083 form = document.forms[form]||BX(form); 7084 7085 var res = []; 7086 7087 if (BX.type.isElementNode(form)) 7088 { 7089 if (form.tagName.toUpperCase() == 'FORM') 7090 { 7091 res = form.elements; 7092 } 7093 else 7094 { 7095 res = BX.findChildren(form, CHECK_FORM_ELEMENTS, true); 7096 } 7097 } 7098 7099 return res; 7100 }; 7101 7102 /** 7103 * @deprecated 7104 * @use .contains() 7105 * @param whichNode 7106 * @param forNode 7107 * @return {boolean} 7108 */ 7109 BX.isParentForNode = function(whichNode, forNode) 7110 { 7111 if (BX.type.isDomNode(whichNode) && BX.type.isDomNode(forNode)) 7112 { 7113 return whichNode.contains(forNode); 7114 } 7115 7116 return false; 7117 }; 7118 7119 BX.getCaretPosition = function(node) 7120 { 7121 var pos = 0; 7122 7123 if(node.selectionStart || node.selectionStart == 0) 7124 { 7125 pos = node.selectionStart; 7126 } 7127 else if(document.selection) 7128 { 7129 node.focus(); 7130 var selection = document.selection.createRange(); 7131 selection.moveStart('character', -node.value.length); 7132 pos = selection.text.length; 7133 } 7134 7135 return (pos); 7136 }; 7137 7138 BX.setCaretPosition = function(node, pos) 7139 { 7140 if(!BX.isNodeInDom(node) || BX.isNodeHidden(node) || node.disabled) 7141 { 7142 return; 7143 } 7144 7145 if(node.setSelectionRange) 7146 { 7147 node.focus(); 7148 node.setSelectionRange(pos, pos); 7149 } 7150 else if(node.createTextRange) 7151 { 7152 var range = node.createTextRange(); 7153 range.collapse(true); 7154 range.moveEnd('character', pos); 7155 range.moveStart('character', pos); 7156 range.select(); 7157 } 7158 }; 7159 7160 // access private. use BX.mergeEx instead. 7161 // todo: refactor BX.merge, make it work through BX.mergeEx 7162 BX.merge = function(){ 7163 var arg = Array.prototype.slice.call(arguments); 7164 7165 if(arg.length < 2) 7166 return {}; 7167 7168 var result = arg.shift(); 7169 7170 for(var i = 0; i < arg.length; i++) 7171 { 7172 for(var k in arg[i]){ 7173 7174 if(typeof arg[i] == 'undefined' || arg[i] == null) 7175 continue; 7176 7177 if(arg[i].hasOwnProperty(k)){ 7178 7179 if(typeof arg[i][k] == 'undefined' || arg[i][k] == null) 7180 continue; 7181 7182 if(typeof arg[i][k] == 'object' && !BX.type.isDomNode(arg[i][k]) && (typeof arg[i][k]['isUIWidget'] == 'undefined')){ 7183 7184 // go deeper 7185 7186 var isArray = 'length' in arg[i][k]; 7187 7188 if(typeof result[k] != 'object') 7189 result[k] = isArray ? [] : {}; 7190 7191 if(isArray) 7192 BX.util.array_merge(result[k], arg[i][k]); 7193 else 7194 BX.merge(result[k], arg[i][k]); 7195 7196 }else 7197 result[k] = arg[i][k]; 7198 } 7199 } 7200 } 7201 7202 return result; 7203 }; 7204 7205 BX.mergeEx = function() 7206 { 7207 var arg = Array.prototype.slice.call(arguments); 7208 if(arg.length < 2) 7209 { 7210 return {}; 7211 } 7212 7213 var result = arg.shift(); 7214 for (var i = 0; i < arg.length; i++) 7215 { 7216 for (var k in arg[i]) 7217 { 7218 if (typeof arg[i] == "undefined" || arg[i] == null || !arg[i].hasOwnProperty(k)) 7219 { 7220 continue; 7221 } 7222 7223 if (BX.type.isPlainObject(arg[i][k]) && BX.type.isPlainObject(result[k])) 7224 { 7225 BX.mergeEx(result[k], arg[i][k]); 7226 } 7227 else 7228 { 7229 result[k] = BX.type.isPlainObject(arg[i][k]) ? BX.clone(arg[i][k]) : arg[i][k]; 7230 } 7231 } 7232 } 7233 7234 return result; 7235 }; 7236 7237 BX.getEventButton = function(e) 7238 { 7239 e = e || window.event; 7240 7241 var flags = 0; 7242 7243 if (typeof e.which != 'undefined') 7244 { 7245 switch (e.which) 7246 { 7247 case 1: flags = flags|BX.MSLEFT; break; 7248 case 2: flags = flags|BX.MSMIDDLE; break; 7249 case 3: flags = flags|BX.MSRIGHT; break; 7250 } 7251 } 7252 else if (typeof e.button != 'undefined') 7253 { 7254 flags = event.button; 7255 } 7256 7257 return flags || BX.MSLEFT; 7258 }; 7259 7260 var captured_events = null, _bind = null; 7261 BX.CaptureEvents = function(el_c, evname_c) 7262 { 7263 if (_bind) 7264 return; 7265 7266 _bind = BX.bind; 7267 captured_events = []; 7268 7269 BX.bind = function(el, evname, func) 7270 { 7271 if (el === el_c && evname === evname_c) 7272 captured_events.push(func); 7273 7274 _bind.apply(this, arguments); 7275 } 7276 }; 7277 7278 BX.CaptureEventsGet = function() 7279 { 7280 if (_bind) 7281 { 7282 BX.bind = _bind; 7283 7284 var captured = captured_events; 7285 7286 _bind = null; 7287 captured_events = null; 7288 return captured; 7289 } 7290 return null; 7291 }; 7292 7293 // Don't even try to use it for submit event! 7294 BX.fireEvent = function(ob,ev) 7295 { 7296 var result = false, e = null; 7297 if (BX.type.isDomNode(ob)) 7298 { 7299 result = true; 7300 if (document.createEventObject) 7301 { 7302 // IE 7303 if (eventTypes[ev] != 'MouseEvent') 7304 { 7305 e = document.createEventObject(); 7306 e.type = ev; 7307 result = ob.fireEvent('on' + ev, e); 7308 } 7309 7310 if (ob[ev]) 7311 { 7312 ob[ev](); 7313 } 7314 } 7315 else 7316 {
7317 // non-IE 7318 e = null; 7319 7320 switch (eventTypes[ev]) 7321 { 7322 case 'MouseEvent': 7323 e = document.createEvent('MouseEvent'); 7324 try 7325 { 7326 e.initMouseEvent(ev, true, true, top, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, null); 7327 } 7328 catch (initException) 7329 { 7330 e.initMouseEvent(ev, true, true, window, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, null); 7331 } 7332 7333 break; 7334 default: 7335 e = document.createEvent('Event'); 7336 e.initEvent(ev, true, true); 7337 } 7338 7339 result = ob.dispatchEvent(e); 7340 } 7341 } 7342 7343 return result; 7344 }; 7345 7346 BX.getWheelData = function(e) 7347 { 7348 e = e || window.event; 7349 e.wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40; 7350 return e.wheelData; 7351 }; 7352 7353 BX.proxy_context = null; 7354 7355 BX.delegate = function (func, thisObject) 7356 { 7357 if (!func || !thisObject) 7358 return func; 7359 7360 return function() { 7361 var cur = BX.proxy_context; 7362 BX.proxy_context = this; 7363 var res = func.apply(thisObject, arguments); 7364 BX.proxy_context = cur; 7365 return res; 7366 } 7367 }; 7368 7369 BX.delegateLater = function (func_name, thisObject, contextObject) 7370 { 7371 return function() 7372 { 7373 if (thisObject[func_name]) 7374 { 7375 var cur = BX.proxy_context; 7376 BX.proxy_context = this; 7377 var res = thisObject[func_name].apply(contextObject||thisObject, arguments); 7378 BX.proxy_context = cur; 7379 return res; 7380 } 7381 return null; 7382 } 7383 }; 7384 7385 BX.proxy = function(func, thisObject) 7386 { 7387 return getObjectDelegate(func, thisObject, proxyList); 7388 }; 7389 7390 BX.defer = function(func, thisObject) 7391 { 7392 if (!!thisObject) 7393 return BX.defer_proxy(func, thisObject); 7394 else 7395 return function() { 7396 var arg = arguments; 7397 setTimeout(function(){func.apply(this,arg)}, 10); 7398 }; 7399 }; 7400 7401 BX.defer_proxy = function(func, thisObject) 7402 { 7403 return getObjectDelegate(func, thisObject, deferList, BX.defer); 7404 }; 7405 7406 /** 7407 * 7408 * @private 7409 */ 7410 function getObjectDelegate(func, thisObject, collection, decorator) 7411 { 7412 if (!BX.type.isFunction(func) || !BX.type.isMapKey(thisObject)) 7413 { 7414 return func; 7415 } 7416 7417 var objectDelegates = collection.get(thisObject); 7418 if (!objectDelegates) 7419 { 7420 objectDelegates = new WeakMap(); 7421 collection.set(thisObject, objectDelegates); 7422 } 7423 7424 var delegate = objectDelegates.get(func); 7425 if (!delegate) 7426 { 7427 delegate = decorator ? decorator(BX.delegate(func, thisObject)) : BX.delegate(func, thisObject); 7428 objectDelegates.set(func, delegate); 7429 } 7430 7431 return delegate; 7432 } 7433 7434 BX.once = function(el, evname, func) 7435 { 7436 var fn = function() 7437 { 7438 BX.unbind(el, evname, fn); 7439 func.apply(this, arguments); 7440 }; 7441 7442 return fn; 7443 }; 7444 7445 BX.bindDelegate = function (elem, eventName, isTarget, handler) 7446 { 7447 var h = BX.delegateEvent(isTarget, handler); 7448 BX.bind(elem, eventName, h); 7449 return h; 7450 }; 7451 7452 BX.delegateEvent = function(isTarget, handler) 7453 { 7454 return function(e) 7455 { 7456 e = e || window.event; 7457 var target = e.target || e.srcElement; 7458 7459 while (target != this) 7460 { 7461 if (_checkNode(target, isTarget)) 7462 { 7463 return handler.call(target, e); 7464 } 7465 if (target && target.parentNode) 7466 target = target.parentNode; 7467 else 7468 break; 7469 } 7470 return null; 7471 } 7472 }; 7473 7474 BX.False = function() {return false;}; 7475 BX.DoNothing = function() {}; 7476 7477 // TODO: also check event handlers set via BX.bind() 7478 BX.denyEvent = function(el, ev) 7479 { 7480 deniedEvents.push([el, ev, el['on' + ev]]); 7481 el['on' + ev] = BX.DoNothing; 7482 }; 7483 7484 BX.allowEvent = function(el, ev) 7485 { 7486 for(var i=0, len=deniedEvents.length; i<len; i++) 7487 { 7488 if (deniedEvents[i][0] == el && deniedEvents[i][1] == ev) 7489 { 7490 el['on' + ev] = deniedEvents[i][2]; 7491 BX.util.deleteFromArray(deniedEvents, i); 7492 return; 7493 } 7494 } 7495 }; 7496 7497 BX.fixEventPageXY = function(event) 7498 { 7499 BX.fixEventPageX(event); 7500 BX.fixEventPageY(event); 7501 return event; 7502 }; 7503 7504 BX.fixEventPageX = function(event) 7505 { 7506 if (event.pageX == null && event.clientX != null) 7507 { 7508 event.pageX = 7509 event.clientX + 7510 (document.documentElement && document.documentElement.scrollLeft || document.body && document.body.scrollLeft || 0) - 7511 (document.documentElement.clientLeft || 0); 7512 } 7513 7514 return event; 7515 }; 7516 7517 BX.fixEventPageY = function(event) 7518 { 7519 if (event.pageY == null && event.clientY != null) 7520 { 7521 event.pageY = 7522 event.clientY + 7523 (document.documentElement && document.documentElement.scrollTop || document.body && document.body.scrollTop || 0) - 7524 (document.documentElement.clientTop || 0); 7525 } 7526 7527 return event; 7528 }; 7529 7530 /** 7531 * @deprecated 7532 * @see e.preventDefault() 7533 */ 7534 BX.PreventDefault = function(e) 7535 { 7536 if(!e) e = window.event; 7537 if(e.stopPropagation) 7538 { 7539 e.preventDefault(); 7540 e.stopPropagation(); 7541 } 7542 else 7543 { 7544 e.cancelBubble = true; 7545 e.returnValue = false;
7546 } 7547 return false; 7548 }; 7549 7550 /** 7551 * @deprecated 7552 * @see e.preventDefault(); 7553 * 7554 * @param e 7555 * @return {boolean} 7556 */ 7557 BX.eventReturnFalse = function(e) 7558 { 7559 e=e||window.event; 7560 if (e && e.preventDefault) e.preventDefault(); 7561 else e.returnValue = false; 7562 return false; 7563 }; 7564 7565 /** 7566 * @deprecated 7567 * @see e.stopPropagation() 7568 * @param e 7569 */ 7570 BX.eventCancelBubble = function(e) 7571 { 7572 e=e||window.event; 7573 if(e && e.stopPropagation) 7574 e.stopPropagation(); 7575 else 7576 e.cancelBubble = true; 7577 }; 7578 7579 BX.bindDebouncedChange = function(node, fn, fnInstant, timeout, ctx) 7580 { 7581 ctx = ctx || window; 7582 timeout = timeout || 300; 7583 7584 var dataTag = 'bx-dc-previous-value'; 7585 BX.data(node, dataTag, node.value); 7586 7587 var act = function(fn, val){ 7588 7589 var pVal = BX.data(node, dataTag); 7590 7591 if(typeof pVal == 'undefined' || pVal != val){ 7592 if(typeof ctx != 'object') 7593 fn(val); 7594 else 7595 fn.apply(ctx, [val]); 7596 } 7597 }; 7598 7599 var actD = BX.debounce(function(){ 7600 var val = node.value; 7601 act(fn, val); 7602 BX.data(node, dataTag, val); 7603 }, timeout); 7604 7605 BX.bind(node, 'keyup', actD); 7606 BX.bind(node, 'change', actD); 7607 BX.bind(node, 'input', actD); 7608 7609 if(BX.type.isFunction(fnInstant)){ 7610 7611 var actI = function(){ 7612 act(fnInstant, node.value); 7613 }; 7614 7615 BX.bind(node, 'keyup', actI); 7616 BX.bind(node, 'change', actI); 7617 BX.bind(node, 'input', actI); 7618 } 7619 }; 7620 7621 BX.parseJSON = function(data, context) 7622 { 7623 var result = null; 7624 if (BX.type.isNotEmptyString(data)) 7625 { 7626 try { 7627 if (data.indexOf("\n") >= 0) 7628 eval('result = ' + data); 7629 else 7630 result = (new Function("return " + data))(); 7631 } catch(e) { 7632 BX.onCustomEvent(context, 'onParseJSONFailure', [data, context]) 7633 } 7634 } 7635 else if(BX.type.isPlainObject(data)) 7636 { 7637 return data; 7638 } 7639 7640 return result; 7641 }; 7642 7643 BX.submit = function(obForm, action_name, action_value, onAfterSubmit) 7644 { 7645 action_name = action_name || 'save'; 7646 if (!obForm['BXFormSubmit_' + action_name]) 7647 { 7648 obForm['BXFormSubmit_' + action_name] = obForm.appendChild(BX.create('INPUT', { 7649 'props': { 7650 'type': 'submit', 7651 'name': action_name, 7652 'value': action_value || 'Y' 7653 }, 7654 'style': { 7655 'display': 'none' 7656 } 7657 })); 7658 } 7659 7660 if (obForm.sessid) 7661 obForm.sessid.value = BX.bitrix_sessid(); 7662 7663 setTimeout(BX.delegate(function() {BX.fireEvent(this, 'click'); if (onAfterSubmit) onAfterSubmit();}, obForm['BXFormSubmit_' + action_name]), 10); 7664 }; 7665 7666 BX.show = function(ob, displayType) 7667 { 7668 if (ob.BXDISPLAY || !_checkDisplay(ob, displayType)) 7669 { 7670 ob.style.display = ob.BXDISPLAY; 7671 } 7672 }; 7673 7674 BX.hide = function(ob, displayType) 7675 { 7676 if (!ob.BXDISPLAY) 7677 _checkDisplay(ob, displayType); 7678 7679 ob.style.display = 'none'; 7680 }; 7681 7682 BX.toggle = function(ob, values) 7683 { 7684 if (!values && BX.type.isElementNode(ob)) 7685 { 7686 var bShow = true; 7687 if (ob.BXDISPLAY) 7688 bShow = !_checkDisplay(ob); 7689 else 7690 bShow = ob.style.display == 'none'; 7691 7692 if (bShow) 7693 BX.show(ob); 7694 else 7695 BX.hide(ob); 7696 } 7697 else if (BX.type.isArray(values)) 7698 { 7699 for (var i=0,len=values.length; i<len; i++) 7700 { 7701 if (ob == values[i]) 7702 { 7703 ob = values[i==len-1 ? 0 : i+1]; 7704 break; 7705 } 7706 } 7707 if (i==len) 7708 ob = values[0]; 7709 } 7710 7711 return ob; 7712 }; 7713 7714 function _checkDisplay(ob, displayType) 7715 { 7716 if (typeof displayType != 'undefined') 7717 ob.BXDISPLAY = displayType; 7718 7719 var d = ob.style.display || BX.style(ob, 'display'); 7720 if (d != 'none') 7721 { 7722 ob.BXDISPLAY = ob.BXDISPLAY || d; 7723 return true; 7724 } 7725 else 7726 { 7727 ob.BXDISPLAY = ob.BXDISPLAY || 'block'; 7728 return false; 7729 } 7730 } 7731 7732 /* some useful util functions */ 7733 7734 BX.util = { 7735 /** 7736 * @deprecated 7737 * @use [].filter(value => !BX.Type.isNil(value)) 7738 * @param ar 7739 * @return {*} 7740 */ 7741 array_values: function(ar) 7742 { 7743 if (!BX.type.isArray(ar)) 7744 return BX.util._array_values_ob(ar); 7745 var arv = []; 7746 for(var i=0,l=ar.length;i<l;i++) 7747 if (ar[i] !== null && typeof ar[i] != 'undefined') 7748 arv.push(ar[i]); 7749 return arv; 7750 }, 7751 7752 /** 7753 * @deprecated 7754 * @use Object.values([]).filter(value => !BX.Type.isNil(value)) 7755 * @param ar 7756 * @return {Array} 7757 * @private 7758 */ 7759 _array_values_ob: function(ar) 7760 { 7761 var arv = []; 7762 for(var i in ar) 7763 if (ar[i] !== null && typeof ar[i] != 'undefined') 7764 arv.push(ar[i]); 7765 return arv; 7766 }, 7767 7768 /** 7769 * @deprecated 7770 * @use 7771 * @param ar 7772 * @return {*} 7773 */ 7774 array_keys: function(ar) 7775 { 7776 if (!BX.type.isArray(ar)) 7777 return BX.util._array_keys_ob(ar); 7778 var arv = []; 7779 for(var i=0,l=ar.length;i<l;i++) 7780 if (ar[i] !== null && typeof ar[i] != 'undefined') 7781 arv.push(i); 7782 return arv; 7783 }, 7784 7785 _array_keys_ob: function(ar) 7786 { 7787 var arv = []; 7788 for(var i in ar) 7789 if (ar[i] !== null && typeof ar[i] != 'undefined') 7790 arv.push(i); 7791 return arv; 7792 }, 7793 7794 object_keys: function(obj) 7795 { 7796 var arv = []; 7797 for(var k in obj) 7798 { 7799 if(obj.hasOwnProperty(k)) 7800 { 7801 arv.push(k); 7802 } 7803 } 7804 return arv; 7805 }, 7806 7807 /** 7808 * @deprecated 7809 * @use firstArr.concat(secondArr); 7810 * @param first 7811 * @param second 7812 * @return {*[]} 7813 */ 7814 array_merge: function(first, second) 7815 { 7816 if (!BX.type.isArray(first)) first = []; 7817 if (!BX.type.isArray(second)) second = []; 7818 7819 var i = first.length, j = 0; 7820 7821 if (typeof second.length === "number") 7822 { 7823 for (var l = second.length; j < l; j++) 7824 { 7825 first[i++] = second[j]; 7826 } 7827 } 7828 else 7829 {
7830 while (second[j] !== undefined) 7831 { 7832 first[i++] = second[j++]; 7833 } 7834 } 7835 7836 first.length = i; 7837 7838 return first; 7839 }, 7840 7841 array_flip: function (object) 7842 { 7843 var newObject = {}; 7844 7845 for (var key in object) 7846 { 7847 newObject[object[key]] = key; 7848 } 7849 7850 return newObject; 7851 }, 7852 7853 array_diff: function(ar1, ar2, hash) 7854 { 7855 hash = BX.type.isFunction(hash) ? hash : null; 7856 var i, length, v, h, map = {}, result = []; 7857 for(i = 0, length = ar2.length; i < length; i++) 7858 { 7859 v = ar2[i]; 7860 h = hash ? hash(v) : v; 7861 map[h] = true; 7862 } 7863 7864 for(i = 0, length = ar1.length; i < length; i++) 7865 { 7866 v = ar1[i]; 7867 h = hash ? hash(v) : v; 7868 if(typeof(map[h]) === "undefined") 7869 { 7870 result.push(v); 7871 } 7872 } 7873 return result; 7874 }, 7875 7876 /** 7877 * @deprecated 7878 * @use Set 7879 */ 7880 array_unique: function(ar) 7881 { 7882 var i=0,j,len=ar.length; 7883 if(len<2) return ar; 7884 7885 for (; i<len-1;i++) 7886 { 7887 for (j=i+1; j<len;j++) 7888 { 7889 if (ar[i]==ar[j]) 7890 { 7891 ar.splice(j--,1); len--; 7892 } 7893 } 7894 } 7895 7896 return ar; 7897 }, 7898 7899 /** 7900 * @deprecated 7901 * @use myArr.includes(needle) 7902 */ 7903 in_array: function(needle, haystack) 7904 { 7905 for(var i=0; i<haystack.length; i++) 7906 { 7907 if(haystack[i] == needle) 7908 return true; 7909 } 7910 return false; 7911 }, 7912 7913 /** 7914 * @deprecated 7915 * @use myArr.findIndex(item => item === needle); 7916 */ 7917 array_search: function(needle, haystack) 7918 { 7919 for(var i=0; i<haystack.length; i++) 7920 { 7921 if(haystack[i] == needle) 7922 return i; 7923 } 7924 return -1; 7925 }, 7926 7927 object_search_key: function(needle, haystack) 7928 { 7929 if (typeof haystack[needle] != 'undefined') 7930 return haystack[needle]; 7931 7932 for(var i in haystack) 7933 { 7934 if (typeof haystack[i] == "object") 7935 { 7936 var result = BX.util.object_search_key(needle, haystack[i]); 7937 if (result !== false) 7938 return result; 7939 } 7940 } 7941 return false; 7942 }, 7943 7944 trim: function(s) 7945 { 7946 if (BX.type.isString(s)) 7947 { 7948 return s.trim(); 7949 } 7950 7951 return s; 7952 }, 7953 7954 urlencode: function(s){return encodeURIComponent(s);}, 7955 7956 // it may also be useful. via sVD. 7957 deleteFromArray: function(ar, ind) {return ar.slice(0, ind).concat(ar.slice(ind + 1));}, 7958 insertIntoArray: function(ar, ind, el) {return ar.slice(0, ind).concat([el]).concat(ar.slice(ind));}, 7959 7960 htmlspecialchars: function(str) 7961 { 7962 return BX.Text.encode(str); 7963 }, 7964 7965 htmlspecialcharsback: function(str) 7966 { 7967 return BX.Text.decode(str); 7968 }, 7969 7970 // Quote regular expression characters plus an optional character 7971 preg_quote: function(str, delimiter) 7972 { 7973 if(!str.replace) 7974 return str; 7975 return str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&'); 7976 }, 7977 7978 jsencode: function(str) 7979 { 7980 if (!str || !str.replace) 7981 return str; 7982 7983 var escapes = 7984 [ 7985 { c: "\\\\", r: "\\\\" }, // should be first 7986 { c: "\\t", r: "\\t" }, 7987 { c: "\\n", r: "\\n" }, 7988 { c: "\\r", r: "\\r" }, 7989 { c: "\"", r: "\\\"" }, 7990 { c: "'", r: "\\'" }, 7991 { c: "<", r: "\\x3C" }, 7992 { c: ">", r: "\\x3E" }, 7993 { c: "\\u2028", r: "\\u2028" }, 7994 { c: "\\u2029", r: "\\u2029" } 7995 ]; 7996 for (var i = 0; i < escapes.length; i++) 7997 str = str.replace(new RegExp(escapes[i].c, 'g'), escapes[i].r); 7998 return str; 7999 }, 8000 8001 getCssName: function(jsName) 8002 { 8003 if (!BX.type.isNotEmptyString(jsName)) 8004 { 8005 return ""; 8006 } 8007 8008 return jsName.replace(/[A-Z]/g, function(match) { 8009 return "-" + match.toLowerCase(); 8010 }); 8011 }, 8012 8013 getJsName: function(cssName) 8014 { 8015 var regex = /\-([a-z]){1}/g; 8016 if (regex.test(cssName)) 8017 { 8018 return cssName.replace(regex, function(match, letter) { 8019 return letter.toUpperCase(); 8020 }); 8021 } 8022 8023 return cssName; 8024 }, 8025 8026 nl2br: function(str) 8027 { 8028 if (!str || !str.replace) 8029 return str; 8030 8031 return str.replace(/([^>])\n/g, '$1<br/>'); 8032 }, 8033 8034 /** 8035 * @deprecated 8036 * @use .padStart() / .padEnd() 8037 * @param input 8038 * @param pad_length 8039 * @param pad_string 8040 * @param pad_type 8041 * @return {*} 8042 */ 8043 str_pad: function(input, pad_length, pad_string, pad_type) 8044 { 8045 pad_string = pad_string || ' '; 8046 pad_type = pad_type || 'right'; 8047 input = input.toString(); 8048 8049 if (pad_type === 'left') 8050 { 8051 return BX.util.str_pad_left(input, pad_length, pad_string); 8052 } 8053 8054 return BX.util.str_pad_right(input, pad_length, pad_string); 8055 }, 8056 8057 str_pad_left: function(input, pad_length, pad_string) 8058 { 8059 return input.toString().padStart(pad_length, pad_string); 8060 }, 8061 8062 str_pad_right: function(input, pad_length, pad_string) 8063 { 8064 return input.toString().padEnd(pad_length, pad_string); 8065 }, 8066 8067 strip_tags: function(str) 8068 { 8069 return str.split(/<[^>]+>/g).join(''); 8070 }, 8071 8072 strip_php_tags: function(str) 8073 { 8074 return str.replace(/<\?(.|[\r\n])*?\?>/g, ''); 8075 }, 8076 8077 popup: function(url, width, height) 8078 { 8079 var w, h; 8080 if(BX.browser.IsOpera()) 8081 { 8082 w = document.body.offsetWidth; 8083 h = document.body.offsetHeight; 8084 } 8085 else 8086 {
8087 w = screen.width; 8088 h = screen.height; 8089 } 8090 return window.open(url, '', 'status=no,scrollbars=yes,resizable=yes,width='+width+',height='+height+',top='+Math.floor((h - height)/2-14)+',left='+Math.floor((w - width)/2-5)); 8091 }, 8092 8093 shuffle: function(array) 8094 { 8095 var temporaryValue, randomIndex; 8096 var currentIndex = array.length; 8097 8098 while (0 !== currentIndex) 8099 { 8100 randomIndex = Math.floor(Math.random() * currentIndex); 8101 currentIndex -= 1; 8102 8103 temporaryValue = array[currentIndex]; 8104 array[currentIndex] = array[randomIndex]; 8105 array[randomIndex] = temporaryValue; 8106 } 8107 8108 return array; 8109 }, 8110 8111 // BX.util.objectSort(object, sortBy, sortDir) - Sort object by property 8112 // function params: 1 - object for sort, 2 - sort by property, 3 - sort direction (asc/desc) 8113 // return: sort array [[objectElement], [objectElement]] in sortDir direction 8114 8115 // example: BX.util.objectSort({'L1': {'name': 'Last'}, 'F1': {'name': 'First'}}, 'name', 'asc'); 8116 // return: [{'name' : 'First'}, {'name' : 'Last'}] 8117 objectSort: function(object, sortBy, sortDir) 8118 { 8119 sortDir = sortDir == 'asc'? 'asc': 'desc'; 8120 8121 var arItems = [], i; 8122 for (i in object) 8123 { 8124 if (object.hasOwnProperty(i) && object[i][sortBy]) 8125 { 8126 arItems.push([i, object[i][sortBy]]); 8127 } 8128 } 8129 8130 if (sortDir == 'asc') 8131 { 8132 arItems.sort(function(i, ii) { 8133 var s1, s2; 8134 if (BX.type.isDate(i[1])) 8135 { 8136 s1 = i[1].getTime(); 8137 } 8138 else if (!isNaN(i[1])) 8139 { 8140 s1 = parseInt(i[1]); 8141 } 8142 else 8143 { 8144 s1 = i[1].toString().toLowerCase(); 8145 } 8146 8147 if (BX.type.isDate(ii[1])) 8148 { 8149 s2 = ii[1].getTime(); 8150 } 8151 else if (!isNaN(ii[1])) 8152 { 8153 s2 = parseInt(ii[1]); 8154 } 8155 else 8156 { 8157 s2 = ii[1].toString().toLowerCase(); 8158 } 8159 8160 if (s1 > s2) 8161 return 1; 8162 else if (s1 < s2) 8163 return -1; 8164 else 8165 return 0; 8166 }); 8167 } 8168 else 8169 { 8170 arItems.sort(function(i, ii) { 8171 var s1, s2; 8172 if (BX.type.isDate(i[1])) 8173 { 8174 s1 = i[1].getTime(); 8175 } 8176 else if (!isNaN(i[1])) 8177 { 8178 s1 = parseInt(i[1]); 8179 } 8180 else 8181 { 8182 s1 = i[1].toString().toLowerCase(); 8183 } 8184 8185 if (BX.type.isDate(ii[1])) 8186 { 8187 s2 = ii[1].getTime(); 8188 } 8189 else if (!isNaN(ii[1])) 8190 { 8191 s2 = parseInt(ii[1]); 8192 } 8193 else 8194 { 8195 s2 = ii[1].toString().toLowerCase(); 8196 } 8197 8198 if (s1 < s2) 8199 return 1; 8200 else if (s1 > s2) 8201 return -1; 8202 else 8203 return 0; 8204 }); 8205 } 8206 8207 var arReturnArray = Array(); 8208 for (i = 0; i < arItems.length; i++) 8209 { 8210 arReturnArray.push(object[arItems[i][0]]); 8211 } 8212 8213 return arReturnArray; 8214 }, 8215 8216 objectMerge: function() 8217 { 8218 return BX.mergeEx.apply(window, arguments); 8219 }, 8220 8221 objectClone : function(object) 8222 { 8223 return BX.clone(object, true); 8224 }, 8225 8226 // #fdf9e5 => {r=253, g=249, b=229} 8227 hex2rgb: function(color) 8228 { 8229 var rgb = color.replace(/[# ]/g,"").replace(/^(.)(.)(.)$/,'$1$1$2$2$3$3').match(/.{2}/g); 8230 for (var i=0; i<3; i++) 8231 { 8232 rgb[i] = parseInt(rgb[i], 16); 8233 } 8234 return {'r':rgb[0],'g':rgb[1],'b':rgb[2]}; 8235 }, 8236 8237 /** 8238 * @deprecated 8239 * @use BX.Uri 8240 * @param url 8241 * @param param 8242 * @return {string} 8243 */ 8244 remove_url_param: function(url, param) 8245 { 8246 return BX.Uri.removeParam(url, param); 8247 }, 8248 8249 /* 8250 {'param1': 'value1', 'param2': 'value2'} 8251 */ 8252 /** 8253 * @deprecated 8254 * @use BX.Uri 8255 * @param url 8256 * @param params 8257 * @return {string} 8258 */ 8259 add_url_param: function(url, params) 8260 { 8261 var preparedParams = Object.entries(params).reduce(function(acc, item) { 8262 acc[item[0]] = BX.type.isArray(item[1]) ? item[1].join() : item[1]; 8263 return acc; 8264 }, {}); 8265 8266 return BX.Uri.addParam(url, preparedParams); 8267 }, 8268 8269 /* 8270 {'param1': 'value1', 'param2': 'value2'} 8271 */ 8272 buildQueryString: function(params) 8273 { 8274 var result = ''; 8275 for (var key in params) 8276 { 8277 var value = params[key]; 8278 if(BX.type.isArray(value)) 8279 { 8280 value.forEach(function(valueElement, index) 8281 { 8282 result += encodeURIComponent(key + "[" + index + "]") + "=" + encodeURIComponent(valueElement) + "&"; 8283 }); 8284 } 8285 else 8286 { 8287 result += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&"; 8288 } 8289 } 8290 8291 if(result.length > 0) 8292 { 8293 result = result.substr(0, result.length - 1); 8294 } 8295 return result; 8296 }, 8297 8298 even: function(digit) 8299 { 8300 return (parseInt(digit) % 2 == 0); 8301 }, 8302 8303 hashCode: function(str) 8304 { 8305 if(!BX.type.isNotEmptyString(str)) 8306 { 8307 return 0; 8308 } 8309 8310 var hash = 0; 8311 for (var i = 0; i < str.length; i++) 8312 { 8313 var c = str.charCodeAt(i); 8314 hash = ((hash << 5) - hash) + c; 8315 hash = hash & hash; 8316 } 8317 return hash; 8318 }, 8319 8320 getRandomString: function (length) 8321 { 8322 return BX.Text.getRandom(length); 8323 }, 8324 8325 number_format: function(number, decimals, dec_point, thousands_sep) 8326 { 8327 var i, j, kw, kd, km, sign = ''; 8328 decimals = Math.abs(decimals); 8329 if (isNaN(decimals) || decimals < 0) 8330 { 8331 decimals = 2; 8332 } 8333 dec_point = dec_point || ','; 8334 if (typeof thousands_sep === 'undefined') 8335 thousands_sep = '.'; 8336 8337 number = (+number || 0).toFixed(decimals); 8338 if (number < 0) 8339 { 8340 sign = '-'; 8341 number = -number; 8342 } 8343 8344 i = parseInt(number, 10) + ''; 8345 j = (i.length > 3 ? i.length % 3 : 0); 8346 8347 km = (j ? i.substr(0, j) + thousands_sep : ''); 8348 kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep); 8349 kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, '0').slice(2) : ''); 8350 8351 return sign + km + kw + kd; 8352 }, 8353 8354 getExtension: function (url) 8355 { 8356 url = url || ""; 8357 var items = url.split("?")[0].split("."); 8358 return items[items.length-1].toLowerCase(); 8359 }, 8360 addObjectToForm: function(object, form, prefix) 8361 { 8362 if(!BX.type.isString(prefix)) 8363 { 8364 prefix = ""; 8365 } 8366 8367 for(var key in object) 8368 { 8369 if(!object.hasOwnProperty(key)) 8370 { 8371 continue; 8372 } 8373 8374 var value = object[key]; 8375 var name = prefix !== "" ? (prefix + "[" + key + "]") : key; 8376 if(BX.type.isArray(value)) 8377 { 8378 var obj = {}; 8379 for(var i = 0; i < value.length; i++) 8380 { 8381 obj[i] = value[i]; 8382 } 8383 8384 BX.util.addObjectToForm(obj, form, name); 8385 } 8386 else if(BX.type.isPlainObject(value)) 8387 { 8388 BX.util.addObjectToForm(value, form, name); 8389 } 8390 else 8391 { 8392 value = BX.type.isFunction(value.toString) ? value.toString() : ""; 8393 if(value !== "") 8394 { 8395 form.appendChild(BX.create("INPUT", { attrs: { type: "hidden", name: name, value: value } })); 8396 } 8397 } 8398 } 8399 }, 8400 8401 observe: function(object, enable) 8402 {
8403 console.error('BX.util.observe: function is no longer supported by browser.'); 8404 return false; 8405 }, 8406 8407 escapeRegExp: function(str) 8408 { 8409 return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); 8410 } 8411 }; 8412 8413 BX.validation = { 8414 checkIfEmail: function(s) 8415 { 8416 var atom = "[=a-z0-9_+~'!$&*^`|#%/?{}-]"; 8417 return (new RegExp('^\\s*'+atom+'+(\\.'+atom+'+)*@([a-z0-9-]+\\.)+[a-z0-9-]{2,20}\\s*$', 'i')).test(s); 8418 }, 8419 checkIfPhone: function(s) 8420 { 8421 var regexp = new RegExp( 8422 typeof(BX.PhoneNumber) === "undefined" 8423 ? BX.PhoneNumber.getValidNumberPattern() 8424 : '^\\s*\\+?\s*[0-9(-)\\s]+\\s*$', 8425 'i' 8426 ); 8427 return regexp.test(s); 8428 } 8429 }; 8430 8431 BX.prop = 8432 { 8433 get: function(object, key, defaultValue) 8434 { 8435 return object && object.hasOwnProperty(key) ? object[key] : defaultValue; 8436 }, 8437 getObject: function(object, key, defaultValue) 8438 { 8439 return object && BX.type.isPlainObject(object[key]) ? object[key] : defaultValue; 8440 }, 8441 getElementNode: function(object, key, defaultValue) 8442 { 8443 return object && BX.type.isElementNode(object[key]) ? object[key] : defaultValue; 8444 }, 8445 getArray: function(object, key, defaultValue) 8446 { 8447 return object && BX.type.isArray(object[key]) ? object[key] : defaultValue; 8448 }, 8449 getFunction: function(object, key, defaultValue) 8450 { 8451 return object && BX.type.isFunction(object[key]) ? object[key] : defaultValue; 8452 }, 8453 getNumber: function(object, key, defaultValue) 8454 { 8455 if(!(object && object.hasOwnProperty(key))) 8456 { 8457 return defaultValue; 8458 } 8459 8460 var value = object[key]; 8461 if(BX.type.isNumber(value)) 8462 { 8463 return value; 8464 } 8465 8466 value = parseFloat(value); 8467 return !isNaN(value) ? value : defaultValue; 8468 }, 8469 getInteger: function(object, key, defaultValue) 8470 { 8471 if(!(object && object.hasOwnProperty(key))) 8472 { 8473 return defaultValue; 8474 } 8475 8476 var value = object[key]; 8477 if(BX.type.isNumber(value)) 8478 { 8479 return value; 8480 } 8481 8482 value = parseInt(value); 8483 return !isNaN(value) ? value : defaultValue; 8484 }, 8485 getBoolean: function(object, key, defaultValue) 8486 { 8487 if(!(object && object.hasOwnProperty(key))) 8488 { 8489 return defaultValue; 8490 } 8491 8492 var value = object[key]; 8493 return (BX.type.isBoolean(value) 8494 ? value 8495 : (BX.type.isString(value) ? (value.toLowerCase() === "true") : !!value) 8496 ); 8497 }, 8498 getString: function(object, key, defaultValue) 8499 { 8500 if(!(object && object.hasOwnProperty(key))) 8501 { 8502 return defaultValue; 8503 } 8504 8505 var value = object[key]; 8506 return BX.type.isString(value) ? value : (value ? value.toString() : ''); 8507 }, 8508 extractDate: function(datetime) 8509 { 8510 if(!BX.type.isDate(datetime)) 8511 { 8512 datetime = new Date(); 8513 } 8514 8515 datetime.setHours(0); 8516 datetime.setMinutes(0); 8517 datetime.setSeconds(0); 8518 datetime.setMilliseconds(0); 8519 8520 return datetime; 8521 } 8522 }; 8523 8524 BX.isNodeInDom = function(node, doc) 8525 { 8526 return node === (doc || document) ? true : 8527 (node.parentNode ? BX.isNodeInDom(node.parentNode) : false); 8528 }; 8529 8530 BX.isNodeHidden = function(node) 8531 { 8532 if (node === document) 8533 return false; 8534 else if (BX.style(node, 'display') == 'none') 8535 return true; 8536 else 8537 return (node.parentNode ? BX.isNodeHidden(node.parentNode) : true); 8538 }; 8539 8540 BX.evalPack = function(code) 8541 { 8542 while (code.length > 0) 8543 { 8544 var c = code.shift(); 8545 8546 if (c.TYPE == 'SCRIPT_EXT' || c.TYPE == 'SCRIPT_SRC') 8547 { 8548 BX.loadScript(c.DATA, function() {BX.evalPack(code)}); 8549 return; 8550 } 8551 else if (c.TYPE == 'SCRIPT') 8552 { 8553 BX.evalGlobal(c.DATA); 8554 } 8555 } 8556 }; 8557 8558 BX.evalGlobal = function(data) 8559 { 8560 if (data) 8561 { 8562 var head = document.getElementsByTagName("head")[0] || document.documentElement, 8563 script = document.createElement("script"); 8564 8565 script.type = "text/javascript"; 8566 8567 if (!BX.browser.IsIE()) 8568 { 8569 script.appendChild(document.createTextNode(data)); 8570 } 8571 else 8572 { 8573 script.text = data; 8574 } 8575 8576 head.insertBefore(script, head.firstChild); 8577 head.removeChild(script); 8578 } 8579 }; 8580 8581 BX.garbage = function(call, thisObject) 8582 { 8583 garbageCollectors.push({callback: call, context: thisObject}); 8584 }; 8585 8586 BX.GetDocElement = function (pDoc) 8587 { 8588 pDoc = pDoc || document; 8589 return (BX.browser.IsDoctype(pDoc) ? pDoc.documentElement : pDoc.body); 8590 }; 8591 8592 BX.scrollTop = function(node, val){ 8593 if(typeof val != 'undefined'){ 8594 8595 if(node == window){ 8596 throw new Error('scrollTop() for window is not implemented'); 8597 }else 8598 node.scrollTop = parseInt(val); 8599 8600 }else{ 8601 8602 if(node == window) 8603 return BX.GetWindowScrollPos().scrollTop; 8604 8605 return node.scrollTop; 8606 } 8607 }; 8608 8609 BX.scrollLeft = function(node, val){ 8610 if(typeof val != 'undefined'){ 8611 8612 if(node == window){ 8613 throw new Error('scrollLeft() for window is not implemented'); 8614 }else 8615 node.scrollLeft = parseInt(val); 8616 8617 }else{ 8618 8619 if(node == window) 8620 return BX.GetWindowScrollPos().scrollLeft; 8621 8622 return node.scrollLeft; 8623 } 8624 }; 8625 8626 BX.hide_object = function(ob) 8627 { 8628 ob = BX(ob); 8629 ob.style.position = 'absolute'; 8630 ob.style.top = '-1000px'; 8631 ob.style.left = '-1000px'; 8632 ob.style.height = '10px'; 8633 ob.style.width = '10px'; 8634 }; 8635 8636 BX.is_relative = function(el) 8637 { 8638 var p = BX.style(el, 'position'); 8639 return p == 'relative' || p == 'absolute'; 8640 }; 8641 8642 BX.is_float = function(el) 8643 { 8644 var p = BX.style(el, 'float'); 8645 return p == 'right' || p == 'left'; 8646 }; 8647 8648 BX.is_fixed = function(el) 8649 { 8650 var p = BX.style(el, 'position'); 8651 return p == 'fixed'; 8652 }; 8653 8654 BX.width = function(node, val){ 8655 if(typeof val != 'undefined') 8656 BX.style(node, 'width', parseInt(val)+'px'); 8657 else{ 8658 8659 if(node == window) 8660 return window.innerWidth; 8661 8662 //return parseInt(BX.style(node, 'width')); 8663 return BX.pos(node).width; 8664 } 8665 }; 8666 8667 BX.height = function(node, val){ 8668 if(typeof val != 'undefined') 8669 BX.style(node, 'height', parseInt(val)+'px'); 8670 else{ 8671 8672 if(node == window) 8673 return window.innerHeight; 8674 8675 //return parseInt(BX.style(node, 'height')); 8676 return BX.pos(node).height; 8677 } 8678 }; 8679 8680 BX.align = function(pos, w, h, type) 8681 { 8682 if (type) 8683 type = type.toLowerCase(); 8684 else 8685 type = ''; 8686 8687 var pDoc = document; 8688 if (BX.type.isElementNode(pos)) 8689 { 8690 pDoc = pos.ownerDocument; 8691 pos = BX.pos(pos); 8692 } 8693 8694 var x = pos["left"], y = pos["bottom"]; 8695 8696 var scroll = BX.GetWindowScrollPos(pDoc); 8697 var size = BX.GetWindowInnerSize(pDoc); 8698 8699 if((size.innerWidth + scroll.scrollLeft) - (pos["left"] + w) < 0) 8700 { 8701 if(pos["right"] - w >= 0 ) 8702 x = pos["right"] - w; 8703 else 8704 x = scroll.scrollLeft; 8705 } 8706
8707 if(((size.innerHeight + scroll.scrollTop) - (pos["bottom"] + h) < 0) || ~type.indexOf('top')) 8708 { 8709 if(pos["top"] - h >= 0 || ~type.indexOf('top')) 8710 y = pos["top"] - h; 8711 else 8712 y = scroll.scrollTop; 8713 } 8714 8715 return {'left':x, 'top':y}; 8716 }; 8717 8718 BX.scrollToNode = function(node) 8719 { 8720 var obNode = BX(node); 8721 8722 if (obNode.scrollIntoView) 8723 obNode.scrollIntoView(true); 8724 else 8725 { 8726 var arNodePos = BX.pos(obNode); 8727 window.scrollTo(arNodePos.left, arNodePos.top); 8728 } 8729 }; 8730 8731 /* non-xhr loadings */ 8732 BX.showWait = function(node, msg) 8733 { 8734 node = BX(node) || document.body || document.documentElement; 8735 msg = msg || BX.message('JS_CORE_LOADING'); 8736 8737 var container_id = node.id || Math.random(); 8738 8739 var obMsg = node.bxmsg = document.body.appendChild(BX.create('DIV', { 8740 props: { 8741 id: 'wait_' + container_id 8742 }, 8743 style: { 8744 background: 'url("/bitrix/js/main/core/images/wait.gif") no-repeat scroll 10px center #fcf7d1', 8745 border: '1px solid #E1B52D', 8746 color: 'black', 8747 fontFamily: 'Verdana,Arial,sans-serif', 8748 fontSize: '11px', 8749 padding: '10px 30px 10px 37px', 8750 position: 'absolute', 8751 textAlign:'center' 8752 }, 8753 text: msg 8754 })); 8755 8756 BX.ZIndexManager.register(obMsg); 8757 BX.ZIndexManager.bringToFront(obMsg); 8758 8759 setTimeout(BX.delegate(_adjustWait, node), 10); 8760 8761 lastWait[lastWait.length] = obMsg; 8762 return obMsg; 8763 }; 8764 8765 BX.closeWait = function(node, obMsg) 8766 { 8767 if(node && !obMsg) 8768 obMsg = node.bxmsg; 8769 if(node && !obMsg && BX.hasClass(node, 'bx-core-waitwindow')) 8770 obMsg = node; 8771 if(node && !obMsg) 8772 obMsg = BX('wait_' + node.id); 8773 if(!obMsg) 8774 obMsg = lastWait.pop(); 8775 8776 if (obMsg && obMsg.parentNode) 8777 { 8778 for (var i=0,len=lastWait.length;i<len;i++) 8779 { 8780 if (obMsg == lastWait[i]) 8781 { 8782 lastWait = BX.util.deleteFromArray(lastWait, i); 8783 break; 8784 } 8785 } 8786 8787 BX.ZIndexManager.unregister(obMsg); 8788 obMsg.parentNode.removeChild(obMsg); 8789 if (node) node.bxmsg = null; 8790 BX.cleanNode(obMsg, true); 8791 } 8792 }; 8793 8794 BX.setJSList = function(scripts) 8795 { 8796 if (BX.type.isArray(scripts)) 8797 { 8798 scripts = scripts.map(function(script) { 8799 return normalizeUrl(script) 8800 }); 8801 8802 jsList = jsList.concat(scripts); 8803 } 8804 }; 8805 8806 BX.getJSList = function() 8807 { 8808 initJsList(); 8809 return jsList; 8810 }; 8811 8812 BX.setCSSList = function(cssFiles) 8813 { 8814 if (BX.type.isArray(cssFiles)) 8815 { 8816 cssFiles = cssFiles.map(function(cssFile) { 8817 return normalizeUrl(cssFile); 8818 }); 8819 8820 cssList = cssList.concat(cssFiles); 8821 } 8822 }; 8823 8824 BX.getCSSList = function() 8825 { 8826 initCssList(); 8827 return cssList; 8828 }; 8829 8830 BX.getJSPath = function(js) 8831 { 8832 return js.replace(/^(http[s]*:)*\/\/[^\/]+/i, ''); 8833 }; 8834 8835 BX.getCSSPath = function(css) 8836 { 8837 return css.replace(/^(http[s]*:)*\/\/[^\/]+/i, ''); 8838 }; 8839 8840 BX.getCDNPath = function(path) 8841 { 8842 return path; 8843 }; 8844 8845 BX.loadScript = function(script, callback, doc) 8846 { 8847 if (BX.type.isString(script)) 8848 { 8849 script = [script]; 8850 } 8851 8852 return BX.load(script, callback, doc); 8853 }; 8854 8855 BX.loadCSS = function(css, doc, win) 8856 { 8857 if (BX.type.isString(css)) 8858 { 8859 css = [css]; 8860 } 8861 8862 if (BX.type.isArray(css)) 8863 { 8864 css = css.map(function(url) { 8865 return { url: url, ext: "css" } 8866 }); 8867 8868 BX.load(css, null, doc); 8869 } 8870 }; 8871 8872 const LOADING = 3; 8873 const LOADED = 4; 8874 const assets = {}; 8875 const loadingAssetCallbacks = {}; 8876 8877 BX.load = function(items, callback, doc, reject) 8878 { 8879 if (!BX.isReady) 8880 { 8881 var _args = arguments; 8882 BX.ready(function() { 8883 BX.load.apply(this, _args); 8884 }); 8885 8886 return null; 8887 } 8888 8889 doc = doc || document; 8890 8891 callback = BX.Type.isFunction(callback) ? callback : () => {}; 8892 8893 return loadAsync(items, callback, doc, reject); 8894 }; 8895 8896 function loadAsync(items, callback, doc, reject) 8897 { 8898 if (!BX.type.isArray(items)) 8899 { 8900 callback(); 8901 8902 return; 8903 } 8904 8905 function onLoad() 8906 { 8907 const nextAsset = queue.shift(); 8908 if (nextAsset) 8909 { 8910 load(nextAsset, onLoad, doc, reject); 8911 } 8912 else if (allLoaded()) 8913 { 8914 callback(); 8915 } 8916 } 8917 8918 function allLoaded() 8919 { 8920 for (const name in assetMap) 8921 { 8922 if (assetMap[name].state !== LOADED) 8923 { 8924 return false; 8925 } 8926 } 8927 8928 return true; 8929 } 8930 8931 const queue = []; 8932 const assetMap = {};
8933 items.forEach(item => { 8934 const asset = getAsset(item); 8935 if (asset && asset.state !== LOADED) 8936 { 8937 queue.push(asset); 8938 assetMap[asset.name] = asset; 8939 } 8940 }); 8941 8942 if (queue.length > 0) 8943 { 8944 const maxParallelLoads = 6; 8945 const parallelLoads = Math.min(queue.length, maxParallelLoads); 8946 const firstPackage = queue.splice(0, parallelLoads); 8947 firstPackage.forEach(asset => { 8948 load(asset, onLoad, doc, reject); 8949 }); 8950 } 8951 else 8952 { 8953 callback(); 8954 } 8955 } 8956 8957 function load(asset, callback, doc, reject) 8958 { 8959 callback = callback || BX.DoNothing; 8960 8961 if (asset.state === LOADED) 8962 { 8963 callback(); 8964 return; 8965 } 8966 8967 if (asset.state === LOADING) 8968 { 8969 if (!BX.Type.isArray(loadingAssetCallbacks[asset.name])) 8970 { 8971 loadingAssetCallbacks[asset.name] = []; 8972 } 8973 8974 loadingAssetCallbacks[asset.name].push(callback); 8975 8976 return; 8977 } 8978 8979 asset.state = LOADING; 8980 8981 const onReject = () => { 8982 delete assets[asset.name]; 8983 delete loadingAssetCallbacks[asset.name]; 8984 reject(); 8985 }; 8986 8987 loadAsset( 8988 asset, 8989 function () { 8990 asset.state = LOADED; 8991 callback(); 8992 if (BX.Type.isArrayFilled(loadingAssetCallbacks[asset.name])) 8993 { 8994 for (const cb of loadingAssetCallbacks[asset.name]) 8995 { 8996 cb(); 8997 } 8998 } 8999 9000 delete loadingAssetCallbacks[asset.name]; 9001 }, 9002 doc, 9003 BX.Type.isFunction(reject) ? onReject : null, 9004 ); 9005 } 9006 9007 function loadAsset(asset, callback, doc, reject) 9008 { 9009 callback = callback || BX.DoNothing; 9010 9011 function error(event) 9012 { 9013 window.clearTimeout(asset.errorTimeout); 9014 window.clearTimeout(asset.cssTimeout); 9015 ele.onload = ele.onreadystatechange = ele.onerror = null; 9016 if (BX.Type.isFunction(reject)) 9017 { 9018 reject(); 9019 } 9020 else 9021 { 9022 callback(); 9023 } 9024 } 9025 9026 function process(event) 9027 { 9028 if (ext === "css") 9029 { 9030 cssList.push(normalizeMinUrl(normalizeUrl(asset.url))); 9031 } 9032 else 9033 { 9034 jsList.push(normalizeMinUrl(normalizeUrl(asset.url))); 9035 } 9036 9037 event = event || window.event; 9038 if (event.type === "load" || (/loaded|complete/.test(ele.readyState) && (!doc.documentMode || doc.documentMode < 9))) 9039 { 9040 window.clearTimeout(asset.errorTimeout); 9041 window.clearTimeout(asset.cssTimeout); 9042 ele.onload = ele.onreadystatechange = ele.onerror = null; 9043 callback(); 9044 } 9045 } 9046 9047 function isCssLoaded() 9048 { 9049 if (asset.state !== LOADED && asset.cssRetries <= 20) 9050 { 9051 for (var i = 0, l = doc.styleSheets.length; i < l; i++) 9052 { 9053 if (doc.styleSheets[i].href === ele.href) 9054 { 9055 process({"type": "load"}); 9056 return; 9057 } 9058 } 9059 9060 asset.cssRetries++; 9061 asset.cssTimeout = window.setTimeout(isCssLoaded, 250); 9062 } 9063 } 9064 9065 let ele = null; 9066 const ext = BX.type.isNotEmptyString(asset.ext) ? asset.ext : BX.util.getExtension(asset.url); 9067 9068 if (ext === "css") 9069 { 9070 ele = doc.createElement("link"); 9071 ele.type = "text/" + (asset.type || "css"); 9072 ele.rel = "stylesheet"; 9073 ele.href = asset.url; 9074 9075 asset.cssRetries = 0; 9076 asset.cssTimeout = window.setTimeout(isCssLoaded, 500); 9077 } 9078 else 9079 { 9080 ele = doc.createElement("script"); 9081 ele.type = "text/" + (asset.type || "javascript"); 9082 ele.src = asset.url; 9083 } 9084 9085 ele.onload = ele.onreadystatechange = process; 9086 ele.onerror = error; 9087 9088 ele.async = asset.async === true; 9089 ele.defer = false; 9090 9091 asset.errorTimeout = window.setTimeout(function () { 9092 error({type: "timeout"}); 9093 }, 7000); 9094 9095 let templateLink = null; 9096 const head = doc.head || doc.getElementsByTagName("head")[0]; 9097 if (ext === "css" && (templateLink = getTemplateLink(head)) !== null) 9098 { 9099 templateLink.parentNode.insertBefore(ele, templateLink); 9100 } 9101 else 9102 { 9103 head.insertBefore(ele, head.lastChild); 9104 } 9105 } 9106 9107 function getAsset(item) 9108 { 9109 var asset = {}; 9110 if (typeof item === "object") 9111 { 9112 asset = item; 9113 asset.name = asset.name ? asset.name : BX.util.hashCode(item.url); 9114 } 9115 else 9116 { 9117 asset = { name: BX.util.hashCode(item), url : item }; 9118 } 9119 9120 var ext = BX.type.isNotEmptyString(asset.ext) ? asset.ext : BX.util.getExtension(asset.url); 9121 if ((ext === "css" && isCssLoaded(asset.url)) || isScriptLoaded(asset.url)) 9122 { 9123 asset.state = LOADED; 9124 } 9125 9126 var existing = assets[asset.name]; 9127 if (existing && existing.url === asset.url) 9128 { 9129 return existing; 9130 } 9131 9132 assets[asset.name] = asset; 9133 9134 return asset; 9135 } 9136 9137 function normalizeUrl(url) 9138 { 9139 if (!BX.type.isNotEmptyString(url)) 9140 { 9141 return ""; 9142 } 9143 9144 url = BX.getJSPath(url); 9145 url = url.replace(/\?[0-9]*$/, ""); 9146 9147 return url; 9148 } 9149 9150 function normalizeMinUrl(url) 9151 { 9152 if (!BX.type.isNotEmptyString(url)) 9153 { 9154 return ""; 9155 } 9156 9157 var minPos = url.indexOf(".min"); 9158 return minPos >= 0 ? url.substr(0, minPos) + url.substr(minPos + 4) : url; 9159 } 9160 9161 function isCssLoaded(fileSrc) 9162 { 9163 initCssList(); 9164 9165 fileSrc = normalizeUrl(fileSrc); 9166 var fileSrcMin = normalizeMinUrl(fileSrc); 9167 9168 return (fileSrc !== fileSrcMin && BX.util.in_array(fileSrcMin, cssList)) || BX.util.in_array(fileSrc, cssList); 9169 } 9170 9171 function initCssList() 9172 { 9173 if(!cssInit) 9174 { 9175 var linksCol = document.getElementsByTagName('link'); 9176 9177 if(!!linksCol && linksCol.length > 0) 9178 { 9179 for(var i = 0; i < linksCol.length; i++) 9180 { 9181 var href = linksCol[i].getAttribute('href'); 9182 if (BX.type.isNotEmptyString(href)) 9183 { 9184 href = normalizeMinUrl(normalizeUrl(href)); 9185 cssList.push(href); 9186 } 9187 } 9188 } 9189 cssInit = true; 9190 } 9191 } 9192 9193 function getTemplateLink(head) 9194 { 9195 var findLink = function(tag) 9196 { 9197 var links = head.getElementsByTagName(tag); 9198 for (var i = 0, length = links.length; i < length; i++) 9199 { 9200 var templateStyle = links[i].getAttribute("data-template-style"); 9201 if (BX.type.isNotEmptyString(templateStyle) && templateStyle == "true") 9202 { 9203 return links[i]; 9204 } 9205 } 9206 9207 return null; 9208 }; 9209 9210 var link = findLink("link"); 9211 if (link === null) 9212 { 9213 link = findLink("style"); 9214 } 9215 9216 return link; 9217 } 9218 9219 function isScriptLoaded(fileSrc) 9220 { 9221 initJsList(); 9222 9223 fileSrc = normalizeUrl(fileSrc); 9224 var fileSrcMin = normalizeMinUrl(fileSrc); 9225 9226 return (fileSrc !== fileSrcMin && BX.util.in_array(fileSrcMin, jsList)) || BX.util.in_array(fileSrc, jsList); 9227 } 9228 9229 function initJsList() 9230 { 9231 if(!jsInit) 9232 { 9233 var scriptCol = document.getElementsByTagName('script'); 9234 9235 if(!!scriptCol && scriptCol.length > 0) 9236 { 9237 for(var i=0; i<scriptCol.length; i++) 9238 { 9239 var src = scriptCol[i].getAttribute('src'); 9240 9241 if (BX.type.isNotEmptyString(src)) 9242 { 9243 src = normalizeMinUrl(normalizeUrl(src)); 9244 jsList.push(src); 9245 } 9246 } 9247 } 9248 jsInit = true; 9249 } 9250 } 9251 9252 function reloadInternal(back_url, bAddClearCache) 9253 { 9254 if (back_url === true) 9255 { 9256 bAddClearCache = true; 9257 back_url = null; 9258 } 9259 9260 var topWindow = (function() { 9261 if (BX.PageObject && BX.PageObject.getRootWindow) 9262 { 9263 return BX.PageObject.getRootWindow(); 9264 } 9265 9266 return window.top; 9267 })(); 9268 var new_href = back_url || topWindow.location.href; 9269 9270 var hashpos = new_href.indexOf('#'), hash = ''; 9271 9272 if (hashpos != -1) 9273 { 9274 hash = new_href.substr(hashpos); 9275 new_href = new_href.substr(0, hashpos); 9276 } 9277 9278 if (bAddClearCache && new_href.indexOf('clear_cache=Y') < 0) 9279 new_href += (new_href.indexOf('?') == -1 ? '?' : '&') + 'clear_cache=Y'; 9280 9281 if (hash) 9282 { 9283 // hack for clearing cache in ajax mode components with history emulation 9284 if (bAddClearCache && (hash.substr(0, 5) == 'view/' || hash.substr(0, 6) == '#view/') && hash.indexOf('clear_cache%3DY') < 0) 9285 hash += (hash.indexOf('%3F') == -1 ? '%3F' : '%26') + 'clear_cache%3DY'; 9286 9287 new_href = new_href.replace(/(\?|\&)_r=[\d]*/, ''); 9288 new_href += (new_href.indexOf('?') == -1 ? '?' : '&') + '_r='+Math.round(Math.random()*10000) + hash; 9289 } 9290 9291 topWindow.location.href = new_href; 9292 } 9293 9294 BX.reload = function(back_url, bAddClearCache) 9295 { 9296 reloadInternal(back_url, bAddClearCache); 9297 }; 9298 9299 BX.clearCache = function() 9300 { 9301 BX.showWait(); 9302 BX.reload(true); 9303 }; 9304 9305 BX.template = function(tpl, callback, bKillTpl) 9306 { 9307 BX.ready(function() { 9308 _processTpl(BX(tpl), callback, bKillTpl); 9309 }); 9310 }; 9311 9312 BX.isAmPmMode = function(returnConst) 9313 { 9314 if (returnConst === true) 9315 { 9316 return BX.message.AMPM_MODE; 9317 } 9318 return BX.message.AMPM_MODE !== false; 9319 }; 9320 9321 BX.formatDate = function(date, format) 9322 { 9323 date = date || new Date(); 9324 9325 var bTime = date.getHours() || date.getMinutes() || date.getSeconds(), 9326 str = !!format 9327 ? format : 9328 (bTime ? BX.message('FORMAT_DATETIME') : BX.message('FORMAT_DATE') 9329 ); 9330 9331 return str.replace(/YYYY/ig, date.getFullYear()) 9332 .replace(/MMMM/ig, BX.util.str_pad_left((date.getMonth()+1).toString(), 2, '0')) 9333 .replace(/MM/ig, BX.util.str_pad_left((date.getMonth()+1).toString(), 2, '0')) 9334 .replace(/DD/ig, BX.util.str_pad_left(date.getDate().toString(), 2, '0')) 9335 .replace(/HH/ig, BX.util.str_pad_left(date.getHours().toString(), 2, '0')) 9336 .replace(/MI/ig, BX.util.str_pad_left(date.getMinutes().toString(), 2, '0')) 9337 .replace(/SS/ig, BX.util.str_pad_left(date.getSeconds().toString(), 2, '0')); 9338 }; 9339 BX.formatName = function(user, template, login) 9340 { 9341 user = user || {}; 9342 template = (template || ''); 9343 var replacement = { 9344 TITLE : (user["TITLE"] || ''), 9345 NAME : (user["NAME"] || ''),
9346 LAST_NAME : (user["LAST_NAME"] || ''), 9347 SECOND_NAME : (user["SECOND_NAME"] || ''), 9348 LOGIN : (user["LOGIN"] || ''), 9349 NAME_SHORT : user["NAME"] ? user["NAME"].substr(0, 1) + '.' : '', 9350 LAST_NAME_SHORT : user["LAST_NAME"] ? user["LAST_NAME"].substr(0, 1) + '.' : '', 9351 SECOND_NAME_SHORT : user["SECOND_NAME"] ? user["SECOND_NAME"].substr(0, 1) + '.' : '', 9352 EMAIL : (user["EMAIL"] || ''), 9353 ID : (user["ID"] || ''), 9354 NOBR : "", 9355 '/NOBR' : "" 9356 }, result = template; 9357 for (var ii in replacement) 9358 { 9359 if (replacement.hasOwnProperty(ii)) 9360 { 9361 result = result.replace("#" + ii+ "#", replacement[ii]) 9362 } 9363 } 9364 result = result.replace(/([\s]+)/gi, " ").trim(); 9365 if (result == "") 9366 { 9367 result = (login == "Y" ? replacement["LOGIN"] : ""); 9368 result = (result == "" ? "Noname" : result); 9369 } 9370 return result; 9371 }; 9372 9373 BX.getNumMonth = function(month) 9374 { 9375 var wordMonthCut = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; 9376 var wordMonth = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']; 9377 9378 var q = month.toUpperCase(); 9379 for (i = 1; i <= 12; i++) 9380 { 9381 if (q == BX.message('MON_'+i).toUpperCase() || q == BX.message('MONTH_'+i).toUpperCase() || q == wordMonthCut[i-1].toUpperCase() || q == wordMonth[i-1].toUpperCase()) 9382 { 9383 return i; 9384 } 9385 } 9386 return month; 9387 }; 9388 9389 BX.parseDate = function(str, bUTC, formatDate, formatDatetime) 9390 { 9391 if (BX.type.isNotEmptyString(str)) 9392 { 9393 if (!formatDate) 9394 formatDate = BX.message('FORMAT_DATE'); 9395 if (!formatDatetime) 9396 formatDatetime = BX.message('FORMAT_DATETIME'); 9397 9398 var regMonths = ''; 9399 for (i = 1; i <= 12; i++) 9400 { 9401 regMonths = regMonths + '|' + BX.message('MON_'+i); 9402 } 9403
9404 var expr = new RegExp('([0-9]+|[a-z]+' + regMonths + ')', 'ig'); 9405 var aDate = str.match(expr), 9406 aFormat = formatDate.match(/(DD|MI|MMMM|MM|M|YYYY)/ig), 9407 i, cnt, 9408 aDateArgs=[], aFormatArgs=[], 9409 aResult={}; 9410 9411 if (!aDate) 9412 return null; 9413 9414 if(aDate.length > aFormat.length) 9415 { 9416 aFormat = formatDatetime.match(/(DD|MI|MMMM|MM|M|YYYY|HH|H|SS|TT|T|GG|G)/ig); 9417 } 9418 9419 for(i = 0, cnt = aDate.length; i < cnt; i++) 9420 { 9421 if(BX.util.trim(aDate[i]) != '') 9422 { 9423 aDateArgs[aDateArgs.length] = aDate[i]; 9424 } 9425 } 9426 9427 for(i = 0, cnt = aFormat.length; i < cnt; i++) 9428 { 9429 if(BX.util.trim(aFormat[i]) != '') 9430 { 9431 aFormatArgs[aFormatArgs.length] = aFormat[i]; 9432 } 9433 } 9434 9435 9436 var m = BX.util.array_search('MMMM', aFormatArgs); 9437 if (m > 0) 9438 { 9439 aDateArgs[m] = BX.getNumMonth(aDateArgs[m]); 9440 aFormatArgs[m] = "MM"; 9441 } 9442 else 9443 { 9444 m = BX.util.array_search('M', aFormatArgs); 9445 if (m > 0) 9446 { 9447 aDateArgs[m] = BX.getNumMonth(aDateArgs[m]); 9448 aFormatArgs[m] = "MM"; 9449 } 9450 } 9451 9452 for(i = 0, cnt = aFormatArgs.length; i < cnt; i++) 9453 { 9454 var k = aFormatArgs[i].toUpperCase(); 9455 aResult[k] = k == 'T' || k == 'TT' ? aDateArgs[i] : parseInt(aDateArgs[i], 10); 9456 } 9457 9458 if(aResult['DD'] > 0 && aResult['MM'] > 0 && aResult['YYYY'] > 0) 9459 { 9460 var d = new Date(); 9461 9462 if(bUTC) 9463 { 9464 d.setUTCDate(1); 9465 d.setUTCFullYear(aResult['YYYY']); 9466 d.setUTCMonth(aResult['MM'] - 1); 9467 d.setUTCDate(aResult['DD']); 9468 d.setUTCHours(0, 0, 0, 0); 9469 } 9470 else 9471 { 9472 d.setDate(1); 9473 d.setFullYear(aResult['YYYY']); 9474 d.setMonth(aResult['MM'] - 1); 9475 d.setDate(aResult['DD']); 9476 d.setHours(0, 0, 0, 0); 9477 } 9478 9479 if( 9480 (!isNaN(aResult['HH']) || !isNaN(aResult['GG']) || !isNaN(aResult['H']) || !isNaN(aResult['G'])) 9481 && !isNaN(aResult['MI']) 9482 ) 9483 { 9484 if (!isNaN(aResult['H']) || !isNaN(aResult['G'])) 9485 { 9486 var bPM = (aResult['T']||aResult['TT']||'am').toUpperCase()=='PM'; 9487 var h = parseInt(aResult['H']||aResult['G']||0, 10); 9488 if(bPM) 9489 { 9490 aResult['HH'] = h + (h == 12 ? 0 : 12); 9491 } 9492 else 9493 { 9494 aResult['HH'] = h < 12 ? h : 0; 9495 } 9496 } 9497 else 9498 { 9499 aResult['HH'] = parseInt(aResult['HH']||aResult['GG']||0, 10); 9500 } 9501 9502 if (isNaN(aResult['SS'])) 9503 aResult['SS'] = 0; 9504 9505 if(bUTC) 9506 { 9507 d.setUTCHours(aResult['HH'], aResult['MI'], aResult['SS']); 9508 } 9509 else 9510 { 9511 d.setHours(aResult['HH'], aResult['MI'], aResult['SS']); 9512 } 9513 } 9514 9515 return d; 9516 } 9517 } 9518 9519 return null; 9520 }; 9521 9522 BX.selectUtils = 9523 { 9524 addNewOption: function(oSelect, opt_value, opt_name, do_sort, check_unique) 9525 { 9526 oSelect = BX(oSelect); 9527 if(oSelect) 9528 { 9529 var n = oSelect.length; 9530 if(check_unique !== false) 9531 { 9532 for(var i=0;i<n;i++) 9533 { 9534 if(oSelect[i].value==opt_value) 9535 { 9536 return; 9537 } 9538 } 9539 } 9540 9541 oSelect.options[n] = new Option(opt_name, opt_value, false, false); 9542 } 9543 9544 if(do_sort === true) 9545 { 9546 this.sortSelect(oSelect); 9547 } 9548 }, 9549 9550 deleteOption: function(oSelect, opt_value) 9551 { 9552 oSelect = BX(oSelect); 9553 if(oSelect) 9554 { 9555 for(var i=0;i<oSelect.length;i++) 9556 { 9557 if(oSelect[i].value==opt_value) 9558 { 9559 oSelect.remove(i); 9560 break; 9561 } 9562 } 9563 } 9564 }, 9565 9566 deleteSelectedOptions: function(oSelect) 9567 { 9568 oSelect = BX(oSelect); 9569 if(oSelect) 9570 { 9571 var i=0; 9572 while(i<oSelect.length) 9573 { 9574 if(oSelect[i].selected) 9575 { 9576 oSelect[i].selected=false; 9577 oSelect.remove(i); 9578 } 9579 else 9580 { 9581 i++; 9582 } 9583 } 9584 } 9585 }, 9586 9587 deleteAllOptions: function(oSelect) 9588 { 9589 oSelect = BX(oSelect); 9590 if(oSelect) 9591 { 9592 for(var i=oSelect.length-1; i>=0; i--) 9593 { 9594 oSelect.remove(i); 9595 } 9596 } 9597 }, 9598 9599 optionCompare: function(record1, record2) 9600 { 9601 var value1 = record1.optText.toLowerCase(); 9602 var value2 = record2.optText.toLowerCase(); 9603 if (value1 > value2) return(1); 9604 if (value1 < value2) return(-1); 9605 return(0); 9606 }, 9607 9608 sortSelect: function(oSelect) 9609 { 9610 oSelect = BX(oSelect); 9611 if(oSelect) 9612 { 9613 var myOptions = []; 9614 var n = oSelect.options.length; 9615 var i; 9616 for (i=0;i<n;i++) 9617 { 9618 myOptions[i] = { 9619 optText:oSelect[i].text, 9620 optValue:oSelect[i].value 9621 }; 9622 } 9623 myOptions.sort(this.optionCompare); 9624 oSelect.length=0; 9625 n = myOptions.length; 9626 for(i=0;i<n;i++) 9627 { 9628 oSelect[i] = new Option(myOptions[i].optText, myOptions[i].optValue, false, false); 9629 } 9630 } 9631 }, 9632 9633 selectAllOptions: function(oSelect) 9634 { 9635 oSelect = BX(oSelect); 9636 if(oSelect) 9637 { 9638 var n = oSelect.length; 9639 for(var i=0;i<n;i++) 9640 { 9641 oSelect[i].selected=true; 9642 } 9643 } 9644 }, 9645 9646 selectOption: function(oSelect, opt_value) 9647 { 9648 oSelect = BX(oSelect); 9649 if(oSelect) 9650 { 9651 var n = oSelect.length; 9652 for(var i=0;i<n;i++) 9653 { 9654 oSelect[i].selected = (oSelect[i].value == opt_value); 9655 } 9656 } 9657 }, 9658 9659 addSelectedOptions: function(oSelect, to_select_id, check_unique, do_sort) 9660 { 9661 oSelect = BX(oSelect); 9662 if(!oSelect) 9663 return; 9664 var n = oSelect.length; 9665 for(var i=0; i<n; i++) 9666 if(oSelect[i].selected) 9667 this.addNewOption(to_select_id, oSelect[i].value, oSelect[i].text, do_sort, check_unique); 9668 }, 9669 9670 moveOptionsUp: function(oSelect) 9671 { 9672 oSelect = BX(oSelect); 9673 if(!oSelect) 9674 return; 9675 var n = oSelect.length; 9676 for(var i=0; i<n; i++) 9677 { 9678 if(oSelect[i].selected && i>0 && oSelect[i-1].selected == false) 9679 { 9680 var option = new Option(oSelect[i].text, oSelect[i].value); 9681 oSelect[i] = new Option(oSelect[i-1].text, oSelect[i-1].value); 9682 oSelect[i].selected = false;
9683 oSelect[i-1] = option; 9684 oSelect[i-1].selected = true; 9685 } 9686 } 9687 }, 9688 9689 moveOptionsDown: function(oSelect) 9690 { 9691 oSelect = BX(oSelect); 9692 if(!oSelect) 9693 return; 9694 var n = oSelect.length; 9695 for(var i=n-1; i>=0; i--) 9696 { 9697 if(oSelect[i].selected && i<n-1 && oSelect[i+1].selected == false) 9698 { 9699 var option = new Option(oSelect[i].text, oSelect[i].value); 9700 oSelect[i] = new Option(oSelect[i+1].text, oSelect[i+1].value); 9701 oSelect[i].selected = false; 9702 oSelect[i+1] = option; 9703 oSelect[i+1].selected = true; 9704 } 9705 } 9706 } 9707 }; 9708 9709 BX.getEventTarget = function(e) 9710 { 9711 if(e.target) 9712 { 9713 return e.target; 9714 } 9715 else if(e.srcElement) 9716 { 9717 return e.srcElement; 9718 } 9719 return null; 9720 }; 9721 9722 BX.convert = { 9723 toNumber: function(value) 9724 { 9725 if(BX.type.isNumber(value)) 9726 { 9727 return value; 9728 } 9729 9730 value = Number(value); 9731 return !isNaN(value) ? value : 0; 9732 }, 9733 nodeListToArray: function(nodes) 9734 { 9735 try 9736 { 9737 return (Array.prototype.slice.call(nodes, 0)); 9738 } 9739 catch (ex) 9740 { 9741 var ary = []; 9742 for(var i = 0, l = nodes.length; i < l; i++) 9743 { 9744 ary.push(nodes[i]); 9745 } 9746 return ary; 9747 } 9748 } 9749 }; 9750 9751 /******* HINT ***************/ 9752// if function has 2 params - the 2nd one is hint html. otherwise hint_html is third and hint_title - 2nd; 9753// '<div onmouseover="BX.hint(this, 'This is <b>Hint</b>')"'>; 9754// BX.hint(el, 'This is <b>Hint</b>') - this won't work, use constructor 9755 BX.hint = function(el, hint_title, hint_html, hint_id) 9756 { 9757 if (null == hint_html) 9758 { 9759 hint_html = hint_title; 9760 hint_title = ''; 9761 } 9762 9763 if (null == el.BXHINT) 9764 { 9765 el.BXHINT = new BX.CHint({ 9766 parent: el, hint: hint_html, title: hint_title, id: hint_id 9767 }); 9768 el.BXHINT.Show(); 9769 } 9770 }; 9771 9772 BX.hint_replace = function(el, hint_title, hint_html) 9773 { 9774 if (null == hint_html) 9775 { 9776 hint_html = hint_title; 9777 hint_title = ''; 9778 } 9779 9780 if (!el || !el.parentNode || !hint_html) 9781 return null; 9782 9783 var obHint = new BX.CHint({ 9784 hint: hint_html, 9785 title: hint_title 9786 }); 9787 9788 obHint.CreateParent(); 9789 9790 el.parentNode.insertBefore(obHint.PARENT, el); 9791 el.parentNode.removeChild(el); 9792 9793 obHint.PARENT.style.marginLeft = '5px'; 9794 9795 return el; 9796 }; 9797 9798 BX.CHint = function(params) 9799 { 9800 if (BX.CHint.cssLoaded === false) 9801 { 9802 BX.load(['/bitrix/js/main/core/css/core_hint.css']); 9803 BX.CHint.cssLoaded = true; 9804 } 9805 9806 this.PARENT = BX(params.parent); 9807 9808 this.HINT = params.hint; 9809 this.HINT_TITLE = params.title; 9810 9811 this.PARAMS = {}; 9812 for (var i in this.defaultSettings) 9813 { 9814 if (null == params[i]) 9815 this.PARAMS[i] = this.defaultSettings[i]; 9816 else 9817 this.PARAMS[i] = params[i]; 9818 } 9819 9820 if (null != params.id) 9821 this.ID = params.id; 9822 9823 this.timer = null; 9824 this.bInited = false; 9825 this.msover = true; 9826 9827 if (this.PARAMS.showOnce) 9828 { 9829 this.__show(); 9830 this.msover = false; 9831 this.timer = setTimeout(BX.proxy(this.__hide, this), this.PARAMS.hide_timeout); 9832 } 9833 else if (this.PARENT) 9834 { 9835 BX.bind(this.PARENT, 'mouseover', BX.proxy(this.Show, this)); 9836 BX.bind(this.PARENT, 'mouseout', BX.proxy(this.Hide, this)); 9837 } 9838 }; 9839 9840 BX.CHint.cssLoaded = false; 9841 9842 BX.CHint.openHints = new Set(); 9843 9844 BX.CHint.globalDisabled = false; 9845 9846 BX.CHint.handleMenuOpen = function() { 9847 BX.CHint.globalDisabled = true; 9848 9849 BX.CHint.openHints.forEach(function(hint) { 9850 hint.__hide_immediately(); 9851 }); 9852 }; 9853 9854 BX.CHint.handleMenuClose = function() { 9855 BX.CHint.globalDisabled = false; 9856 }; 9857 9858 BX.addCustomEvent('onMenuOpen', BX.CHint.handleMenuOpen); 9859 BX.addCustomEvent('onMenuClose', BX.CHint.handleMenuClose); 9860 9861 BX.CHint.prototype.defaultSettings = { 9862 show_timeout: 1000, 9863 hide_timeout: 500, 9864 dx: 2, 9865 showOnce: false, 9866 preventHide: true, 9867 min_width: 250 9868 }; 9869 9870 BX.CHint.prototype.CreateParent = function(element, params) 9871 { 9872 if (this.PARENT) 9873 { 9874 BX.unbind(this.PARENT, 'mouseover', BX.proxy(this.Show, this)); 9875 BX.unbind(this.PARENT, 'mouseout', BX.proxy(this.Hide, this)); 9876 } 9877 9878 if (!params) params = {}; 9879 var type = 'icon'; 9880 9881 if (params.type && (params.type == "link" || params.type == "icon")) 9882 type = params.type; 9883 9884 if (element) 9885 type = "element";
9886 9887 if (type == "icon") 9888 { 9889 element = BX.create('IMG', { 9890 props: { 9891 src: params.iconSrc 9892 ? params.iconSrc 9893 : "/bitrix/js/main/core/images/hint.gif" 9894 } 9895 }); 9896 } 9897 else if (type == "link") 9898 { 9899 element = BX.create("A", { 9900 props: {href: 'javascript:void(0)'}, 9901 html: '[?]' 9902 }); 9903 } 9904 9905 this.PARENT = element; 9906 9907 BX.bind(this.PARENT, 'mouseover', BX.proxy(this.Show, this)); 9908 BX.bind(this.PARENT, 'mouseout', BX.proxy(this.Hide, this)); 9909 9910 return this.PARENT; 9911 }; 9912 9913 BX.CHint.prototype.Show = function() 9914 { 9915 this.msover = true; 9916 9917 if (null != this.timer) 9918 clearTimeout(this.timer); 9919 9920 this.timer = setTimeout(BX.proxy(this.__show, this), this.PARAMS.show_timeout); 9921 }; 9922 9923 BX.CHint.prototype.Hide = function() 9924 { 9925 this.msover = false; 9926 9927 if (null != this.timer) 9928 clearTimeout(this.timer); 9929 9930 this.timer = setTimeout(BX.proxy(this.__hide, this), this.PARAMS.hide_timeout); 9931 }; 9932 9933 BX.CHint.prototype.__show = function() 9934 { 9935 if (!this.msover || this.disabled || BX.CHint.globalDisabled) return; 9936 if (!this.bInited) this.Init(); 9937 9938 if (this.prepareAdjustPos()) 9939 { 9940 this.DIV.style.display = 'block'; 9941 BX.ZIndexManager.bringToFront(this.DIV); 9942 9943 this.adjustPos(); 9944 9945 BX.CHint.openHints.add(this); 9946 9947 BX.bind(window, 'scroll', BX.proxy(this.__onscroll, this)); 9948 9949 if (this.PARAMS.showOnce) 9950 { 9951 this.timer = setTimeout(BX.proxy(this.__hide, this), this.PARAMS.hide_timeout); 9952 } 9953 } 9954 }; 9955 9956 BX.CHint.prototype.__onscroll = function() 9957 { 9958 if (!BX.admin || !BX.admin.panel || !BX.admin.panel.isFixed()) return; 9959 9960 if (this.scrollTimer) clearTimeout(this.scrollTimer); 9961 9962 this.DIV.style.display = 'none'; 9963 this.scrollTimer = setTimeout(BX.proxy(this.Reopen, this), this.PARAMS.show_timeout); 9964 }; 9965 9966 BX.CHint.prototype.Reopen = function() 9967 { 9968 if (null != this.timer) clearTimeout(this.timer); 9969 this.timer = setTimeout(BX.proxy(this.__show, this), 50); 9970 }; 9971 9972 BX.CHint.prototype.__hide = function() 9973 { 9974 if (this.msover) return; 9975 if (!this.bInited) return; 9976 9977 BX.unbind(window, 'scroll', BX.proxy(this.Reopen, this)); 9978 9979 BX.CHint.openHints.delete(this); 9980 9981 if (this.PARAMS.showOnce) 9982 { 9983 this.Destroy(); 9984 } 9985 else 9986 { 9987 this.DIV.style.display = 'none'; 9988 } 9989 }; 9990 9991 BX.CHint.prototype.__hide_immediately = function() 9992 { 9993 this.msover = false; 9994 this.__hide(); 9995 }; 9996 9997 BX.CHint.prototype.Init = function() 9998 { 9999 this.DIV = document.body.appendChild(BX.create('DIV', { 10000 props: {className: 'bx-panel-tooltip'}, 10001 style: { 10002 display: 'none', 10003 position: 'absolute', 10004 visibility: 'hidden' 10005 }, 10006 children: [ 10007 (this.CONTENT = BX.create('DIV', { 10008 props: {className: 'bx-panel-tooltip-content'}, 10009 children: [ 10010 BX.create('DIV', { 10011 props: {className: 'bx-panel-tooltip-underlay'}, 10012 children: [ 10013 BX.create('DIV', {props: {className: 'bx-panel-tooltip-underlay-bg'}}) 10014 ] 10015 }) 10016 ] 10017 })) 10018 ] 10019 })); 10020 10021 BX.ZIndexManager.register(this.DIV); 10022 10023 if (this.ID) 10024 { 10025 this.CONTENT.insertBefore(BX.create('A', { 10026 attrs: {href: 'javascript:void(0)'}, 10027 props: {className: 'bx-panel-tooltip-close'}, 10028 events: {click: BX.delegate(this.Close, this)} 10029 }), this.CONTENT.firstChild); 10030 } 10031 10032 if (this.HINT_TITLE) 10033 { 10034 this.CONTENT.appendChild( 10035 BX.create('DIV', { 10036 props: {className: 'bx-panel-tooltip-title'}, 10037 text: this.HINT_TITLE 10038 }) 10039 ); 10040 } 10041 10042 if (this.HINT) 10043 { 10044 this.CONTENT_TEXT = this.CONTENT.appendChild(BX.create('DIV', {props: {className: 'bx-panel-tooltip-text'}})).appendChild(BX.create('SPAN', {html: this.HINT})); 10045 } 10046 10047 if (this.PARAMS.preventHide) 10048 { 10049 BX.bind(this.DIV, 'mouseout', BX.proxy(this.Hide, this)); 10050 BX.bind(this.DIV, 'mouseover', BX.proxy(this.Show, this)); 10051 } 10052 10053 this.bInited = true; 10054 }; 10055 10056 BX.CHint.prototype.setContent = function(content) 10057 { 10058 this.HINT = content; 10059 10060 if (this.CONTENT_TEXT) 10061 this.CONTENT_TEXT.innerHTML = this.HINT; 10062 else 10063 this.CONTENT_TEXT = this.CONTENT.appendChild(BX.create('DIV', {props: {className: 'bx-panel-tooltip-text'}})).appendChild(BX.create('SPAN', {html: this.HINT})); 10064 }; 10065 10066 BX.CHint.prototype.prepareAdjustPos = function() 10067 { 10068 this._wnd = {scrollPos: BX.GetWindowScrollPos(),scrollSize:BX.GetWindowScrollSize()}; 10069 return BX.style(this.PARENT, 'display') != 'none'; 10070 }; 10071 10072 BX.CHint.prototype.getAdjustPos = function() 10073 { 10074 var res = {}, pos = BX.pos(this.PARENT), min_top = 0; 10075 10076 res.top = pos.bottom + this.PARAMS.dx; 10077 10078 if (BX.admin && BX.admin.panel.DIV) 10079 { 10080 min_top = BX.admin.panel.DIV.offsetHeight + this.PARAMS.dx; 10081 10082 if (BX.admin.panel.isFixed()) 10083 { 10084 min_top += this._wnd.scrollPos.scrollTop; 10085 } 10086 } 10087 10088 if (res.top < min_top) 10089 res.top = min_top; 10090 else 10091 { 10092 if (res.top + this.DIV.offsetHeight > this._wnd.scrollSize.scrollHeight) 10093 res.top = pos.top - this.PARAMS.dx - this.DIV.offsetHeight; 10094 } 10095 10096 res.left = pos.left; 10097 if (pos.left < this.PARAMS.dx) 10098 pos.left = this.PARAMS.dx; 10099 else 10100 { 10101 var floatWidth = this.DIV.offsetWidth; 10102 10103 var max_left = this._wnd.scrollSize.scrollWidth - floatWidth - this.PARAMS.dx; 10104 10105 if (res.left > max_left) 10106 res.left = max_left; 10107 } 10108 10109 return res; 10110 }; 10111 10112 BX.CHint.prototype.adjustWidth = function() 10113 { 10114 if (this.bWidthAdjusted) return; 10115 10116 var w = this.DIV.offsetWidth, h = this.DIV.offsetHeight; 10117 10118 if (w > this.PARAMS.min_width) 10119 w = Math.round(Math.sqrt(1.618*w*h)); 10120 10121 if (w < this.PARAMS.min_width) 10122 w = this.PARAMS.min_width; 10123 10124 this.DIV.style.width = w + "px"; 10125 10126 if (this._adjustWidthInt) 10127 clearInterval(this._adjustWidthInt); 10128 this._adjustWidthInt = setInterval(BX.delegate(this._adjustWidthInterval, this), 5); 10129 10130 this.bWidthAdjusted = true; 10131 }; 10132 10133 BX.CHint.prototype._adjustWidthInterval = function() 10134 { 10135 if (!this.DIV || this.DIV.style.display == 'none') 10136 clearInterval(this._adjustWidthInt); 10137 10138 var
10139 dW = 20, 10140 maxWidth = 1500, 10141 w = this.DIV.offsetWidth, 10142 w1 = this.CONTENT_TEXT.offsetWidth; 10143 10144 if (w > 0 && w1 > 0 && w - w1 < dW && w < maxWidth) 10145 { 10146 this.DIV.style.width = (w + dW) + "px"; 10147 return; 10148 } 10149 10150 clearInterval(this._adjustWidthInt); 10151 }; 10152 10153 BX.CHint.prototype.adjustPos = function() 10154 { 10155 this.adjustWidth(); 10156 10157 var pos = this.getAdjustPos(); 10158 10159 this.DIV.style.top = pos.top + 'px'; 10160 this.DIV.style.left = pos.left + 'px'; 10161 }; 10162 10163 BX.CHint.prototype.Close = function() 10164 { 10165 if (this.ID && BX.WindowManager) 10166 BX.WindowManager.saveWindowOptions(this.ID, {display: 'off'}); 10167 this.__hide_immediately(); 10168 this.Destroy(); 10169 }; 10170 10171 BX.CHint.prototype.Destroy = function() 10172 { 10173 if (this.PARENT) 10174 { 10175 BX.unbind(this.PARENT, 'mouseover', BX.proxy(this.Show, this)); 10176 BX.unbind(this.PARENT, 'mouseout', BX.proxy(this.Hide, this)); 10177 } 10178 10179 if (this.DIV) 10180 { 10181 BX.unbind(this.DIV, 'mouseover', BX.proxy(this.Show, this)); 10182 BX.unbind(this.DIV, 'mouseout', BX.proxy(this.Hide, this)); 10183 10184 BX.ZIndexManager.unregister(this.DIV); 10185 10186 BX.cleanNode(this.DIV, true); 10187 } 10188 }; 10189 10190 BX.CHint.prototype.enable = function(){this.disabled = false;}; 10191 BX.CHint.prototype.disable = function(){this.__hide_immediately(); this.disabled = true;}; 10192 10193 10194 function _adjustWait() 10195 { 10196 if (!this.bxmsg) return; 10197 10198 var arContainerPos = BX.pos(this), 10199 div_top = arContainerPos.top; 10200 10201 if (div_top < BX.GetDocElement().scrollTop) 10202 div_top = BX.GetDocElement().scrollTop + 5; 10203 10204 this.bxmsg.style.top = (div_top + 5) + 'px'; 10205 10206 if (this == BX.GetDocElement()) 10207 { 10208 this.bxmsg.style.right = '5px'; 10209 } 10210 else 10211 { 10212 this.bxmsg.style.left = (arContainerPos.right - this.bxmsg.offsetWidth - 5) + 'px'; 10213 } 10214 } 10215 10216 function _processTpl(tplNode, cb, bKillTpl) 10217 { 10218 if (tplNode) 10219 { 10220 if (bKillTpl) 10221 tplNode.parentNode.removeChild(tplNode); 10222 10223 var res = {}, nodes = BX.findChildren(tplNode, {attribute: 'data-role'}, true); 10224 10225 for (var i = 0, l = nodes.length; i < l; i++) 10226 { 10227 res[nodes[i].getAttribute('data-role')] = nodes[i]; 10228 } 10229 10230 cb.apply(tplNode, [res]); 10231 } 10232 } 10233 10234 function _checkNode(obj, params) 10235 { 10236 params = params || {}; 10237 10238 if (BX.type.isFunction(params)) 10239 return params.call(window, obj); 10240 10241 if (!params.allowTextNodes && !BX.type.isElementNode(obj)) 10242 return false; 10243 var i,j,len; 10244 for (i in params) 10245 { 10246 if(params.hasOwnProperty(i)) 10247 { 10248 switch(i) 10249 { 10250 case 'tag': 10251 case 'tagName': 10252 if (BX.type.isString(params[i])) 10253 { 10254 if (obj.tagName.toUpperCase() != params[i].toUpperCase()) 10255 return false; 10256 } 10257 else if (params[i] instanceof RegExp) 10258 { 10259 if (!params[i].test(obj.tagName)) 10260 return false; 10261 } 10262 break; 10263 10264 case 'class': 10265 case 'className': 10266 if (BX.type.isString(params[i])) 10267 { 10268 if (!BX.hasClass(obj, params[i])) 10269 return false; 10270 } 10271 else if (params[i] instanceof RegExp) 10272 { 10273 if (!BX.type.isString(obj.className) || !params[i].test(obj.className)) 10274 return false; 10275 } 10276 break; 10277 10278 case 'attr': 10279 case 'attrs': 10280 case 'attribute': 10281 if (BX.type.isString(params[i])) 10282 { 10283 if (!obj.getAttribute(params[i])) 10284 return false; 10285 } 10286 else if (BX.type.isArray(params[i])) 10287 { 10288 for (j = 0, len = params[i].length; j < len; j++) 10289 { 10290 if (params[i] && !obj.getAttribute(params[i])) 10291 return false; 10292 } 10293 } 10294 else 10295 { 10296 for (j in params[i]) 10297 { 10298 if(params[i].hasOwnProperty(j)) 10299 { 10300 var q = obj.getAttribute(j); 10301 if (params[i][j] instanceof RegExp) 10302 { 10303 if (!BX.type.isString(q) || !params[i][j].test(q)) 10304 { 10305 return false; 10306 } 10307 } 10308 else 10309 { 10310 if (q != '' + params[i][j]) 10311 { 10312 return false; 10313 } 10314 } 10315 } 10316 } 10317 } 10318 break; 10319 10320 case 'property': 10321 case 'props': 10322 if (BX.type.isString(params[i])) 10323 { 10324 if (!obj[params[i]]) 10325 return false; 10326 } 10327 else if (BX.type.isArray(params[i])) 10328 { 10329 for (j = 0, len = params[i].length; j < len; j++) 10330 { 10331 if (params[i] && !obj[params[i]]) 10332 return false;
10333 } 10334 } 10335 else 10336 { 10337 for (j in params[i]) 10338 { 10339 if (BX.type.isString(params[i][j])) 10340 { 10341 if (obj[j] != params[i][j]) 10342 return false; 10343 } 10344 else if (params[i][j] instanceof RegExp) 10345 { 10346 if (!BX.type.isString(obj[j]) || !params[i][j].test(obj[j])) 10347 return false; 10348 } 10349 } 10350 } 10351 break; 10352 10353 case 'callback': 10354 return params[i](obj); 10355 } 10356 } 10357 } 10358 10359 return true; 10360 } 10361 10362 window.addEventListener('pagehide', () => { 10363 garbageCollectors.forEach(({ callback, context = window }) => { 10364 try 10365 { 10366 callback.apply(context); 10367 } catch (err) {} 10368 }); 10369 }); 10370 10371 // set empty ready handler 10372 BX(BX.DoNothing); 10373 window.BX = BX; 10374 10375 BX.browser.addGlobalClass(); 10376 10377 /* data storage */ 10378 BX.data = function(node, key, value) 10379 { 10380 if(typeof node == 'undefined') 10381 return undefined; 10382 10383 if(typeof key == 'undefined') 10384 return undefined; 10385 10386 if(typeof value != 'undefined') 10387 { 10388 // write to manager 10389 dataStorage.set(node, key, value); 10390 } 10391 else 10392 { 10393 var data; 10394 10395 // from manager 10396 if((data = dataStorage.get(node, key)) != undefined) 10397 { 10398 return data; 10399 } 10400 else 10401 { 10402 // from attribute data-* 10403 if('getAttribute' in node) 10404 { 10405 data = node.getAttribute('data-'+key.toString()); 10406 if(data === null) 10407 { 10408 return undefined; 10409 } 10410 return data; 10411 } 10412 } 10413 10414 return undefined; 10415 } 10416 }; 10417 10418 BX.DataStorage = function() 10419 { 10420 10421 this.keyOffset = 1; 10422 this.data = {}; 10423 this.uniqueTag = 'BX-'+Math.random(); 10424 10425 this.resolve = function(owner, create){ 10426 if(typeof owner[this.uniqueTag] == 'undefined') 10427 if(create) 10428 { 10429 try 10430 { 10431 Object.defineProperty(owner, this.uniqueTag, { 10432 value: this.keyOffset++ 10433 }); 10434 } 10435 catch(e) 10436 { 10437 owner[this.uniqueTag] = this.keyOffset++; 10438 } 10439 } 10440 else 10441 return undefined; 10442 10443 return owner[this.uniqueTag]; 10444 }; 10445 this.get = function(owner, key){ 10446 if((owner != document && !BX.type.isElementNode(owner)) || typeof key == 'undefined') 10447 return undefined; 10448 10449 owner = this.resolve(owner, false); 10450 10451 if(typeof owner == 'undefined' || typeof this.data[owner] == 'undefined') 10452 return undefined; 10453 10454 return this.data[owner][key]; 10455 }; 10456 this.set = function(owner, key, value){ 10457 10458 if((owner != document && !BX.type.isElementNode(owner)) || typeof value == 'undefined') 10459 return; 10460 10461 var o = this.resolve(owner, true); 10462 10463 if(typeof this.data[o] == 'undefined') 10464 this.data[o] = {}; 10465 10466 this.data[o][key] = value; 10467 }; 10468 }; 10469 10470// some internal variables for new logic 10471 var dataStorage = new BX.DataStorage(); // manager which BX.data() uses to keep data 10472})(window.BX); 10473 10474 10475;(function(window) 10476{ 10477 /****************** ATTENTION ******************************* 10478 * Please do not use Bitrix CoreJS in this class. 10479 * This class can be called on page without Bitrix Framework 10480 *************************************************************/ 10481 10482 if (!window.BX) 10483 { 10484 window.BX = {}; 10485 } 10486 10487 var BX = window.BX; 10488 10489 BX.Promise = function(fn, ctx) // fn is future-reserved 10490 { 10491 this.state = null; 10492 this.value = null; 10493 this.reason = null; 10494 this.next = null; 10495 this.ctx = ctx || this; 10496 10497 this.onFulfilled = []; 10498 this.onRejected = []; 10499 }; 10500 BX.Promise.prototype.fulfill = function(value) 10501 { 10502 this.checkState(); 10503 10504 this.value = value; 10505 this.state = true; 10506 this.execute(); 10507 }; 10508 BX.Promise.prototype.reject = function(reason) 10509 { 10510 this.checkState(); 10511 10512 this.reason = reason; 10513 this.state = false; 10514 this.execute(); 10515 }; 10516 BX.Promise.prototype.then = function(onFulfilled, onRejected) 10517 { 10518 if(typeof (onFulfilled) == "function" || onFulfilled instanceof Function) 10519 { 10520 this.onFulfilled.push(onFulfilled); 10521 } 10522 if(typeof (onRejected) == "function" || onRejected instanceof Function) 10523 { 10524 this.onRejected.push(onRejected); 10525 } 10526 10527 if(this.next === null) 10528 { 10529 this.next = new BX.Promise(null, this.ctx); 10530 } 10531 10532 if(this.state !== null) // if promise was already resolved, execute immediately 10533 { 10534 this.execute(); 10535 } 10536 10537 return this.next; 10538 }; 10539 10540 BX.Promise.prototype.catch = function(onRejected) 10541 { 10542 if(typeof (onRejected) == "function" || onRejected instanceof Function) 10543 { 10544 this.onRejected.push(onRejected); 10545 } 10546 10547 if(this.next === null) 10548 { 10549 this.next = new BX.Promise(null, this.ctx); 10550 } 10551 10552 if(this.state !== null) // if promise was already resolved, execute immediately 10553 { 10554 this.execute(); 10555 } 10556 10557 return this.next; 10558 }; 10559 10560 BX.Promise.prototype.setAutoResolve = function(way, ms) 10561 { 10562 this.timer = setTimeout(function(){ 10563 if(this.state === null) 10564 { 10565 this[way ? 'fulfill' : 'reject'](); 10566 } 10567 }.bind(this), ms || 15); 10568 };
10569 BX.Promise.prototype.cancelAutoResolve = function() 10570 { 10571 clearTimeout(this.timer); 10572 }; 10573 /** 10574 * Resolve function. This function allows promise chaining, like ..then().then()... 10575 * Typical usage: 10576 * 10577 * var p = new Promise(); 10578 * 10579 * p.then(function(value){ 10580 * return someValue; // next promise in the chain will be fulfilled with someValue 10581 * }).then(function(value){ 10582 * 10583 * var p1 = new Promise(); 10584 * *** some async code here, that eventually resolves p1 *** 10585 * 10586 * return p1; // chain will resume when p1 resolved (fulfilled or rejected) 10587 * }).then(function(value){ 10588 * 10589 * // you can also do 10590 * var e = new Error(); 10591 * throw e; 10592 * // it will cause next promise to be rejected with e 10593 * 10594 * return someOtherValue; 10595 * }).then(function(value){ 10596 * ... 10597 * }, function(reason){ 10598 * // promise was rejected with reason 10599 * })...; 10600 * 10601 * p.fulfill('let`s start this chain'); 10602 * 10603 * @param x 10604 */ 10605 BX.Promise.prototype.resolve = function(x) 10606 { 10607 var this_ = this; 10608 10609 if(this === x) 10610 { 10611 this.reject(new TypeError('Promise cannot fulfill or reject itself')); // avoid recursion 10612 } 10613 // allow "pausing" promise chaining until promise x is fulfilled or rejected 10614 else if(x && x.toString() === "[object BX.Promise]") 10615 { 10616 x.then(function(value){ 10617 this_.fulfill(value); 10618 }, function(reason){ 10619 this_.reject(reason); 10620 }); 10621 } 10622 else // auto-fulfill this promise 10623 { 10624 this.fulfill(x); 10625 } 10626 }; 10627 10628 BX.Promise.prototype.toString = function() 10629 { 10630 return "[object BX.Promise]"; 10631 }; 10632 10633 BX.Promise.prototype.execute = function() 10634 { 10635 if(this.state === null) 10636 { 10637 //then() must not be called before BX.Promise resolve() happens 10638 return; 10639 } 10640 10641 var value = undefined; 10642 var reason = undefined; 10643 var x = undefined; 10644 var k; 10645 if(this.state === true) // promise was fulfill()-ed 10646 { 10647 if(this.onFulfilled.length) 10648 { 10649 try 10650 { 10651 for(k = 0; k < this.onFulfilled.length; k++) 10652 {
10653 x = this.onFulfilled[k].apply(this.ctx, [this.value]); 10654 if(typeof x != 'undefined') 10655 { 10656 value = x; 10657 } 10658 } 10659 } 10660 catch(e) 10661 { 10662 if('console' in window) 10663 { 10664 console.dir(e); 10665 } 10666 10667 if (typeof BX.debug !== 'undefined') 10668 { 10669 BX.debug(e); 10670 } 10671 10672 reason = e; // reject next 10673 } 10674 } 10675 else 10676 { 10677 value = this.value; // resolve next 10678 } 10679 } 10680 else if(this.state === false) // promise was reject()-ed 10681 { 10682 if(this.onRejected.length) 10683 { 10684 try 10685 { 10686 for(k = 0; k < this.onRejected.length; k++) 10687 { 10688 x = this.onRejected[k].apply(this.ctx, [this.reason]); 10689 if(typeof x != 'undefined') 10690 { 10691 value = x; 10692 } 10693 } 10694 } 10695 catch(e) 10696 { 10697 if('console' in window) 10698 { 10699 console.dir(e); 10700 } 10701 10702 if (typeof BX.debug !== 'undefined') 10703 { 10704 BX.debug(e); 10705 } 10706 10707 reason = e; // reject next 10708 } 10709 } 10710 else 10711 { 10712 reason = this.reason; // reject next 10713 } 10714 } 10715 10716 if(this.next !== null) 10717 { 10718 if(typeof reason != 'undefined') 10719 { 10720 this.next.reject(reason); 10721 } 10722 else if(typeof value != 'undefined') 10723 { 10724 this.next.resolve(value); 10725 } 10726 } 10727 }; 10728 BX.Promise.prototype.checkState = function() 10729 { 10730 if(this.state !== null) 10731 { 10732 throw new Error('You can not do fulfill() or reject() multiple times'); 10733 } 10734 }; 10735})(window); 10736 10737 10738 10739 10740;(function(window){ 10741 10742if (window.BX.ajax) 10743 return; 10744 10745var 10746 BX = window.BX, 10747 10748 tempDefaultConfig = {}, 10749 defaultConfig = { 10750 method: 'GET', // request method: GET|POST 10751 dataType: 'html', // type of data loading: html|json|script 10752 timeout: 0, // request timeout in seconds. 0 for browser-default 10753 async: true, // whether request is asynchronous or not 10754 processData: true, // any data processing is disabled if false, only callback call 10755 scriptsRunFirst: false, // whether to run _all_ found scripts before onsuccess call. script tag can have an attribute "bxrunfirst" to turn this flag on only for itself 10756 emulateOnload: true, 10757 skipAuthCheck: false, // whether to check authorization failure (SHOUD be set to true for CORS requests) 10758 start: true, // send request immediately (if false, request can be started manually via XMLHttpRequest object returned) 10759 cache: true, // whether NOT to add random addition to URL 10760 preparePost: true, // whether set Content-Type x-www-form-urlencoded in POST 10761 headers: false, // add additional headers, example: [{'name': 'If-Modified-Since', 'value': 'Wed, 15 Aug 2012 08:59:08 GMT'}, {'name': 'If-None-Match', 'value': '0'}] 10762 lsTimeout: 30, //local storage data TTL. useless without lsId. 10763 lsForce: false //wheter to force query instead of using localStorage data. useless without lsId. 10764/* 10765other parameters: 10766 url: url to get/post 10767 data: data to post 10768 onsuccess: successful request callback. BX.proxy may be used. 10769 onfailure: request failure callback. BX.proxy may be used. 10770 onprogress: request progress callback. BX.proxy may be used. 10771 10772 lsId: local storage id - for constantly updating queries which can communicate via localStorage. core_ls.js needed 10773 10774any of the default parameters can be overridden. defaults can be changed by BX.ajax.Setup() - for all further requests! 10775*/ 10776 }, 10777 loadedScripts = {}, 10778 loadedScriptsQueue = [], 10779 r = { 10780 'url_utf': /[^\034-\254]+/g, 10781 'script_self': /\/bitrix\/js\/main\/core\/core(_ajax)*.js$/i, 10782 'script_self_window': /\/bitrix\/js\/main\/core\/core_window.js$/i, 10783 'script_self_admin': /\/bitrix\/js\/main\/core\/core_admin.js$/i, 10784 'script_onload': /window.onload/g 10785 }; 10786 10787// low-level method 10788BX.ajax = function(config) 10789{ 10790 var status, data; 10791
10792 if (!config || !config.url || !BX.type.isString(config.url)) 10793 { 10794 return false; 10795 } 10796 10797 for (var i in tempDefaultConfig) 10798 if (typeof (config[i]) == "undefined") config[i] = tempDefaultConfig[i]; 10799 10800 tempDefaultConfig = {}; 10801 10802 for (i in defaultConfig) 10803 if (typeof (config[i]) == "undefined") config[i] = defaultConfig[i]; 10804 10805 config.method = config.method.toUpperCase(); 10806 10807 if (!BX.localStorage) 10808 config.lsId = null; 10809 10810 if (BX.browser.IsIE()) 10811 { 10812 var result = r.url_utf.exec(config.url); 10813 if (result) 10814 { 10815 do 10816 { 10817 config.url = config.url.replace(result, BX.util.urlencode(result)); 10818 result = r.url_utf.exec(config.url); 10819 } while (result); 10820 } 10821 } 10822 10823 if(config.dataType == 'json') 10824 config.emulateOnload = false; 10825 10826 if (!config.cache && config.method == 'GET') 10827 config.url = BX.ajax._uncache(config.url); 10828 10829 if (config.method == 'POST') 10830 { 10831 if (config.preparePost) 10832 { 10833 config.data = BX.ajax.prepareData(config.data); 10834 } 10835 else if (getLastContentTypeHeader(config.headers) === 'application/json') 10836 { 10837 const isJson = ( 10838 BX.Type.isPlainObject(config.data) 10839 || BX.Type.isString(config.data) 10840 || BX.Type.isNumber(config.data) 10841 || BX.Type.isBoolean(config.data) 10842 || BX.Type.isArray(config.data) 10843 ); 10844 10845 if (isJson) 10846 { 10847 config.data = JSON.stringify(config.data); 10848 } 10849 } 10850 } 10851 10852 var bXHR = true; 10853 if (config.lsId && !config.lsForce) 10854 { 10855 var v = BX.localStorage.get('ajax-' + config.lsId); 10856 if (v !== null) 10857 { 10858 bXHR = false; 10859 10860 var lsHandler = function(lsData) { 10861 if (lsData.key == 'ajax-' + config.lsId && lsData.value != 'BXAJAXWAIT') 10862 { 10863 var data = lsData.value, 10864 bRemove = !!lsData.oldValue && data == null; 10865 if (!bRemove) 10866 BX.ajax.__run(config, data); 10867 else if (config.onfailure) 10868 config.onfailure("timeout"); 10869 10870 BX.removeCustomEvent('onLocalStorageChange', lsHandler); 10871 } 10872 }; 10873 10874 if (v == 'BXAJAXWAIT') 10875 { 10876 BX.addCustomEvent('onLocalStorageChange', lsHandler); 10877 } 10878 else 10879 { 10880 setTimeout(function() {lsHandler({key: 'ajax-' + config.lsId, value: v})}, 10); 10881 } 10882 } 10883 } 10884 10885 if (bXHR) 10886 { 10887 config.xhr = BX.ajax.xhr(); 10888 if (!config.xhr) return; 10889 10890 if (config.lsId) 10891 { 10892 BX.localStorage.set('ajax-' + config.lsId, 'BXAJAXWAIT', config.lsTimeout); 10893 } 10894 10895 if (BX.Type.isFunction(config.onprogress)) 10896 { 10897 BX.bind(config.xhr, 'progress', config.onprogress); 10898 } 10899 10900 if (BX.Type.isFunction(config.onprogressupload) && config.xhr.upload) 10901 { 10902 BX.bind(config.xhr.upload, 'progress', config.onprogressupload); 10903 } 10904 10905 config.xhr.open(config.method, config.url, config.async); 10906 10907 if (!config.skipBxHeader && !BX.ajax.isCrossDomain(config.url)) 10908 { 10909 config.xhr.setRequestHeader('Bx-ajax', 'true'); 10910 } 10911 10912 if (config.method == 'POST' && config.preparePost) 10913 { 10914 config.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 10915 } 10916 if (typeof(config.headers) == "object") 10917 { 10918 for (i = 0; i < config.headers.length; i++) 10919 config.xhr.setRequestHeader(config.headers[i].name, config.headers[i].value); 10920 } 10921 10922 var bRequestCompleted = false; 10923 var onreadystatechange = config.xhr.onreadystatechange = function(additional) 10924 { 10925 if (bRequestCompleted) 10926 return; 10927 10928 if (additional === 'timeout') 10929 { 10930 if (config.onfailure) 10931 { 10932 config.onfailure('timeout', '', config); 10933 } 10934 10935 BX.onCustomEvent(config.xhr, 'onAjaxFailure', ['timeout', '', config]); 10936 10937 config.xhr.onreadystatechange = BX.DoNothing; 10938 config.xhr.abort(); 10939 10940 if (config.async) 10941 { 10942 config.xhr = null; 10943 } 10944 } 10945 else 10946 { 10947 if (config.xhr.readyState == 4 || additional == 'run') 10948 { 10949 status = BX.ajax.xhrSuccess(config.xhr) ? "success" : "error"; 10950 bRequestCompleted = true; 10951 config.xhr.onreadystatechange = BX.DoNothing; 10952 10953 if (status == 'success') 10954 { 10955 var authHeader = (!!config.skipAuthCheck || BX.ajax.isCrossDomain(config.url)) 10956 ? false 10957 : config.xhr.getResponseHeader('X-Bitrix-Ajax-Status'); 10958 10959 if(!!authHeader && authHeader == 'Authorize') 10960 { 10961 if (config.onfailure) 10962 { 10963 config.onfailure('auth', config.xhr.status, config); 10964 } 10965 10966 BX.onCustomEvent(config.xhr, 'onAjaxFailure', ['auth', config.xhr.status, config]); 10967 } 10968 else 10969 { 10970 var data = config.xhr.responseText; 10971 10972 if (config.lsId) 10973 { 10974 BX.localStorage.set('ajax-' + config.lsId, data, config.lsTimeout); 10975 } 10976 10977 BX.ajax.__run(config, data); 10978 } 10979 } 10980 else 10981 { 10982 if (config.onfailure) 10983 { 10984 config.onfailure('status', config.xhr.status, config); 10985 } 10986 10987 BX.onCustomEvent(config.xhr, 'onAjaxFailure', ['status', config.xhr.status, config]); 10988 } 10989 10990 if (config.async) 10991 { 10992 config.xhr = null; 10993 } 10994 } 10995 } 10996 }; 10997 10998 if (config.async && config.timeout > 0) 10999 { 11000 setTimeout(function() { 11001 if (config.xhr && !bRequestCompleted) 11002 { 11003 onreadystatechange("timeout"); 11004 } 11005 }, config.timeout * 1000); 11006 } 11007 11008 if (config.start) 11009 {
11010 config.xhr.send(config.data); 11011 11012 if (!config.async) 11013 { 11014 onreadystatechange('run'); 11015 } 11016 } 11017 11018 return config.xhr; 11019 } 11020}; 11021 11022BX.ajax.xhr = function() 11023{ 11024 if (window.XMLHttpRequest) 11025 { 11026 try {return new XMLHttpRequest();} catch(e){} 11027 } 11028 else if (window.ActiveXObject) 11029 { 11030 try { return new window.ActiveXObject("Msxml2.XMLHTTP.6.0"); } 11031 catch(e) {} 11032 try { return new window.ActiveXObject("Msxml2.XMLHTTP.3.0"); } 11033 catch(e) {} 11034 try { return new window.ActiveXObject("Msxml2.XMLHTTP"); } 11035 catch(e) {} 11036 try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } 11037 catch(e) {} 11038 throw new Error("This browser does not support XMLHttpRequest."); 11039 } 11040 11041 return null; 11042}; 11043 11044BX.ajax.isCrossDomain = function(url, location) 11045{ 11046 location = location || window.location; 11047 11048 //Relative URL gets a current protocol 11049 if (url.indexOf("//") === 0) 11050 { 11051 url = location.protocol + url; 11052 } 11053 11054 //Fast check 11055 if (url.indexOf("http") !== 0) 11056 { 11057 return false; 11058 } 11059 11060 var link = window.document.createElement("a"); 11061 link.href = url; 11062 11063 return link.protocol !== location.protocol || 11064 link.hostname !== location.hostname || 11065 BX.ajax.getHostPort(link.protocol, link.host) !== BX.ajax.getHostPort(location.protocol, location.host); 11066}; 11067 11068BX.ajax.getHostPort = function(protocol, host) 11069{ 11070 var match = /:(\d+)$/.exec(host); 11071 if (match) 11072 { 11073 return match[1]; 11074 } 11075 else 11076 { 11077 if (protocol === "http:") 11078 { 11079 return "80"; 11080 } 11081 else if (protocol === "https:") 11082 { 11083 return "443"; 11084 } 11085 } 11086 11087 return ""; 11088}; 11089 11090BX.ajax.__prepareOnload = function(scripts, ajax_session) 11091{ 11092 if (scripts.length > 0) 11093 { 11094 BX.ajax['onload_' + ajax_session] = null; 11095 11096 for (var i=0,len=scripts.length;i<len;i++) 11097 { 11098 if (scripts[i].isInternal) 11099 { 11100 scripts[i].JS = scripts[i].JS.replace(r.script_onload, 'BX.aja
11100x.onload_' + ajax_session); 11101 } 11102 } 11103 } 11104 11105 BX.CaptureEventsGet(); 11106 BX.CaptureEvents(window, 'load'); 11107}; 11108 11109BX.ajax.__runOnload = function(ajax_session) 11110{ 11111 if (null != BX.ajax['onload_' + ajax_session]) 11112 { 11113 BX.ajax['onload_' + ajax_session].apply(window); 11114 BX.ajax['onload_' + ajax_session] = null; 11115 } 11116 11117 var h = BX.CaptureEventsGet(); 11118 11119 if (h) 11120 { 11121 for (var i=0; i<h.length; i++) 11122 h[i].apply(window); 11123 } 11124}; 11125 11126BX.ajax.__run = function(config, data) 11127{ 11128 if (!config.processData) 11129 { 11130 if (config.onsuccess) 11131 { 11132 config.onsuccess(data); 11133 } 11134 11135 BX.onCustomEvent(config.xhr, 'onAjaxSuccess', [data, config]); 11136 } 11137 else 11138 { 11139 data = BX.ajax.processRequestData(data, config); 11140 } 11141}; 11142 11143 11144BX.ajax._onParseJSONFailure = function(data) 11145{ 11146 this.jsonFailure = true; 11147 this.jsonResponse = data; 11148 this.jsonProactive = /^\[WAF\]/.test(data); 11149}; 11150 11151BX.ajax.processRequestData = function(data, config) 11152{ 11153 var result, scripts = [], styles = []; 11154 switch (config.dataType.toUpperCase()) 11155 { 11156 case 'JSON': 11157 11158 var context = config.xhr || {}; 11159 BX.addCustomEvent(context, 'onParseJSONFailure', BX.proxy(BX.ajax._onParseJSONFailure, config)); 11160 result = BX.parseJSON(data, context); 11161 BX.removeCustomEvent(context, 'onParseJSONFailure', BX.proxy(BX.ajax._onParseJSONFailure, config)); 11162 11163 if(!!result && BX.type.isArray(result['bxjs'])) 11164 { 11165 for(var i = 0; i < result['bxjs'].length; i++) 11166 { 11167 if(BX.type.isNotEmptyString(result['bxjs'][i])) 11168 { 11169 scripts.push({ 11170 "isInternal": false, 11171 "JS": result['bxjs'][i], 11172 "bRunFirst": config.scriptsRunFirst 11173 }); 11174 } 11175 else 11176 { 11177 scripts.push(result['bxjs'][i]) 11178 } 11179 } 11180 } 11181 11182 if(!!result && BX.type.isArray(result['bxcss'])) 11183 { 11184 styles = result['bxcss']; 11185 } 11186 11187 break; 11188 case 'SCRIPT': 11189 scripts.push({"isInternal": true, "JS": data, "bRunFirst": config.scriptsRunFirst}); 11190 result = data; 11191 break; 11192 11193 default: // HTML 11194 var ob = BX.processHTML(data, config.scriptsRunFirst); 11195 result = ob.HTML; scripts = ob.SCRIPT; styles = ob.STYLE; 11196 break; 11197 } 11198 11199 if (styles.length > 0) 11200 { 11201 BX.loadCSS(styles); 11202 } 11203 11204 let ajax_session = null; 11205 if (config.emulateOnload) 11206 { 11207 ajax_session = parseInt(Math.random() * 1000000); 11208 BX.ajax.__prepareOnload(scripts, ajax_session); 11209 } 11210 11211 const cb = BX.defer(function() 11212 { 11213 if (config.emulateOnload) 11214 { 11215 BX.ajax.__runOnload(ajax_session); 11216 } 11217 11218 BX.onCustomEvent(config.xhr, 'onAjaxSuccessFinish', [config]); 11219 }); 11220 11221 try 11222 { 11223 if (!!config.jsonFailure) 11224 { 11225 throw {type: 'json_failure', data: config.jsonResponse, bProactive: config.jsonProactive}; 11226 } 11227 11228 config.scripts = scripts; 11229 11230 BX.ajax.processScripts(config.scripts, true); 11231 11232 if (config.onsuccess) 11233 { 11234 config.onsuccess(result); 11235 } 11236 11237 BX.onCustomEvent(config.xhr, 'onAjaxSuccess', [result, config]); 11238 11239 BX.ajax.processScripts(config.scripts, false, cb); 11240 } 11241 catch (e) 11242 { 11243 if (config.onfailure) 11244 config.onfailure("processing", e); 11245 BX.onCustomEvent(config.xhr, 'onAjaxFailure', ['processing', e, config]); 11246 } 11247}; 11248 11249BX.ajax.processScripts = function(scripts, bRunFirst, cb) 11250{ 11251 var scriptsExt = [], scriptsInt = ''; 11252 11253 cb = cb || BX.DoNothing; 11254 11255 for (var i = 0, length = scripts.length; i < length; i++) 11256 { 11257 if (typeof bRunFirst != 'undefined' && bRunFirst != !!scripts[i].bRunFirst) 11258 continue; 11259 11260 if (scripts[i].isInternal) 11261 scriptsInt += ';' + scripts[i].JS; 11262 else 11263 scriptsExt.push(scripts[i].JS); 11264 } 11265 11266 scriptsExt = BX.util.array_unique(scriptsExt); 11267 var inlineScripts = scriptsInt.length > 0 ? function() { BX.evalGlobal(scriptsInt); } : BX.DoNothing; 11268 11269 if (scriptsExt.length > 0) 11270 { 11271 BX.load(scriptsExt, function() { 11272 inlineScripts(); 11273 cb(); 11274 }); 11275 } 11276 else 11277 { 11278 inlineScripts(); 11279 cb(); 11280 } 11281}; 11282 11283// TODO: extend this function to use with any data objects or forms 11284BX.ajax.prepareData = function(arData, prefix) 11285{ 11286 var data = ''; 11287 if (BX.type.isString(arData)) 11288 data = arData; 11289 else if (null != arData) 11290 { 11291 for(var i in arData) 11292 { 11293 if (arData.hasOwnProperty(i)) 11294 { 11295 if (data.length > 0) 11296 data += '&'; 11297 var name = BX.util.urlencode(i); 11298 if(prefix) 11299 name = prefix + '[' + name + ']'; 11300 if(typeof arData[i] == 'object') 11301 data += BX.ajax.prepareData(arData[i], name); 11302 else 11303 data += name + '=' + BX.util.urlencode(arData[i]); 11304 } 11305 } 11306 } 11307 return data; 11308}; 11309 11310BX.ajax.xhrSuccess = function(xhr) 11311{ 11312 return (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; 11313}; 11314 11315BX.ajax.Setup = function(config, bTemp) 11316{ 11317 bTemp = !!bTemp; 11318 11319 for (var i in config) 11320 { 11321 if (bTemp) 11322 tempDefaultConfig[i] = config[i]; 11323 else 11324 defaultConfig[i] = config[i]; 11325 } 11326}; 11327 11328BX.ajax.replaceLocalStorageValue = function(lsId, data, ttl) 11329{ 11330 if (!!BX.localStorage) 11331 BX.localStorage.set('ajax-' + lsId, data, ttl); 11332}; 11333 11334 11335BX.ajax._uncache = function(url) 11336{ 11337 return url + ((url.indexOf('?') !== -1 ? "&" : "?") + '_=' + (new Date()).getTime()); 11338}; 11339 11340/* simple interface */ 11341BX.ajax.get = function(url, data, callback) 11342{ 11343 if (BX.type.isFunction(data)) 11344 { 11345 callback = data; 11346 data = ''; 11347 } 11348
11349 data = BX.ajax.prepareData(data); 11350 11351 if (data) 11352 { 11353 url += (url.indexOf('?') !== -1 ? "&" : "?") + data; 11354 data = ''; 11355 } 11356 11357 return BX.ajax({ 11358 'method': 'GET', 11359 'dataType': 'html', 11360 'url': url, 11361 'data': '', 11362 'onsuccess': callback 11363 }); 11364}; 11365 11366BX.ajax.getCaptcha = function(callback) 11367{ 11368 return BX.ajax.loadJSON('/bitrix/tools/ajax_captcha.php', callback); 11369}; 11370 11371BX.ajax.insertToNode = function(url, node) 11372{ 11373 node = BX(node); 11374 if (!!node) 11375 { 11376 var eventArgs = { cancel: false }; 11377 BX.onCustomEvent('onAjaxInsertToNode', [{ url: url, node: node, eventArgs: eventArgs }]); 11378 if(eventArgs.cancel === true) 11379 { 11380 return; 11381 } 11382 11383 var show = null; 11384 if (!tempDefaultConfig.denyShowWait) 11385 { 11386 show = BX.showWait(node); 11387 delete tempDefaultConfig.denyShowWait; 11388 } 11389 11390 return BX.ajax.get(url, function(data) { 11391 node.innerHTML = data; 11392 BX.closeWait(node, show); 11393 }); 11394 } 11395}; 11396 11397BX.ajax.post = function(url, data, callback) 11398{ 11399 data = BX.ajax.prepareData(data); 11400 11401 return BX.ajax({ 11402 'method': 'POST', 11403 'dataType': 'html', 11404 'url': url, 11405 'data': data, 11406 'onsuccess': callback 11407 }); 11408}; 11409 11410/** 11411 * BX.ajax with BX.Promise 11412 * 11413 * @param config 11414 * @returns {BX.Promise|false} 11415 */ 11416BX.ajax.promise = function(config) 11417{ 11418 var result = new BX.Promise(); 11419 11420 config.onsuccess = function(data) 11421 { 11422 result.fulfill(data); 11423 }; 11424 config.onfailure = function(reason, httpStatus, config) 11425 { 11426 result.reject({ 11427 reason: reason, 11428 data: httpStatus, 11429 ajaxConfig: config, 11430 xhr: config.xhr 11431 }); 11432 }; 11433 11434 var xhr = BX.ajax(config); 11435 if (xhr) 11436 { 11437 if (typeof config.onrequeststart === 'function') 11438 { 11439 config.onrequeststart(xhr); 11440 } 11441 } 11442 else 11443 { 11444 result.reject({ 11445 reason: "init", 11446 data: false 11447 }); 11448 } 11449 11450 return result; 11451}; 11452 11453/* load and execute external file script with onload emulation */ 11454BX.ajax.loadScriptAjax = function(script_src, callback, bPreload) 11455{ 11456 if (BX.type.isArray(script_src)) 11457 { 11458 for (var i=0,len=script_src.length;i<len;i++) 11459 { 11460 BX.ajax.loadScriptAjax(script_src[i], callback, bPreload); 11461 } 11462 } 11463 else 11464 { 11465 var script_src_test = script_src.replace(/\.js\?.*/, '.js'); 11466 11467 if (r.script_self.test(script_src_test)) return; 11468 if (r.script_self_window.test(script_src_test) && BX.CWindow) return; 11469 if (r.script_self_admin.test(script_src_test) && BX.admin) return; 11470 11471 if (typeof loadedScripts[script_src_test] == 'undefined') 11472 { 11473 if (!!bPreload) 11474 { 11475 loadedScripts[script_src_test] = ''; 11476 return BX.loadScript(script_src); 11477 } 11478 else 11479 { 11480 return BX.ajax({ 11481 url: script_src, 11482 method: 'GET', 11483 dataType: 'script', 11484 processData: true, 11485 emulateOnload: false, 11486 scriptsRunFirst: true, 11487 async: false, 11488 start: true, 11489 onsuccess: function(result) { 11490 loadedScripts[script_src_test] = result; 11491 if (callback) 11492 callback(result); 11493 } 11494 }); 11495 } 11496 } 11497 else if (callback) 11498 { 11499 callback(loadedScripts[script_src_test]); 11500 } 11501 } 11502}; 11503 11504/* non-xhr loadings */ 11505BX.ajax.loadJSON = function(url, data, callback, callback_failure) 11506{ 11507 if (BX.type.isFunction(data)) 11508 { 11509 callback_failure = callback; 11510 callback = data; 11511 data = ''; 11512 } 11513 11514 data = BX.ajax.prepareData(data); 11515 11516 if (data) 11517 { 11518 url += (url.indexOf('?') !== -1 ? "&" : "?") + data; 11519 data = ''; 11520 } 11521 11522 return BX.ajax({ 11523 'method': 'GET', 11524 'dataType': 'json', 11525 'url': url, 11526 'onsuccess': callback, 11527 'onfailure': callback_failure 11528 }); 11529}; 11530 11531var getLastContentTypeHeader = function (headers) { 11532 if (!BX.Type.isArray(headers)) 11533 { 11534 return null; 11535 } 11536 var lastHeader = headers 11537 .filter(function (header) { 11538 return header.name === 'Content-Type'; 11539 }) 11540 .pop(); 11541 11542 return lastHeader ? lastHeader.value : null; 11543}; 11544 11545/** 11546 * @see isValidAnalyticsData in ui.analytics 11547* */ 11548const isValidAnalyticsData = function (analytics) 11549{ 11550 if (!BX.Type.isPlainObject(analytics)) 11551 { 11552 console.error('BX.ajax: {analytics} must be an object.'); 11553 11554 return false; 11555 } 11556 11557 const requiredFields = ['event', 'tool', 'category']; 11558 for (const field of requiredFields) 11559 { 11560 if (!BX.Type.isStringFilled(analytics[field])) 11561 { 11562 console.error(`BX.ajax: The "${field}" property in the "analytics" object must be a non-empty string.`); 11563 11564 return false;
11565 } 11566 } 11567 11568 const additionalFields = ['p1', 'p2', 'p3', 'p4', 'p5']; 11569 for (const field of additionalFields) 11570 { 11571 const value = analytics[field]; 11572 if (!BX.Type.isStringFilled(value)) 11573 { 11574 continue; 11575 } 11576 11577 if (value.split('_').length > 2) 11578 { 11579 console.error(`BX.ajax: The "${field}" property (${value}) in the "analytics" object must be a string containing a single underscore.`); 11580 11581 return false; 11582 } 11583 } 11584 11585 return true; 11586}; 11587 11588const processAnalyticsDataToGetParameters = function(config) 11589{ 11590 const getParameters = {}; 11591 if (BX.Type.isStringFilled(config.analyticsLabel) || BX.Type.isPlainObject(config.analyticsLabel)) 11592 { 11593 getParameters.analyticsLabel = config.analyticsLabel; 11594 } 11595 11596 if (BX.Type.isPlainObject(config.analytics)) 11597 { 11598 if (config.analyticsLabel) 11599 { 11600 delete getParameters.analyticsLabel; 11601 console.error('BX.ajax: Only {analytics} or {analyticsLabel} should be used. If both are present, {analyticsLabel} will be ignored.'); 11602 } 11603 11604 if (isValidAnalyticsData(config.analytics)) 11605 { 11606 getParameters.st = config.analytics; 11607 } 11608 else 11609 { 11610 console.error('BX.ajax: {analytics} is invalid and is skipped.'); 11611 } 11612 } 11613 11614 return getParameters; 11615}; 11616 11617const prepareAjaxGetParameters = function(config) 11618{ 11619 let getParameters = config.getParameters || {}; 11620 getParameters = { ...getParameters, ...processAnalyticsDataToGetParameters(config) }; 11621 11622 if (typeof config.mode !== 'undefined') 11623 { 11624 getParameters.mode = config.mode; 11625 } 11626 if (config.navigation) 11627 { 11628 if (config.navigation.page) 11629 { 11630 getParameters.nav = 'page-' + config.navigation.page; 11631 } 11632 if (config.navigation.size) 11633 { 11634 if (getParameters.nav) 11635 { 11636 getParameters.nav += '-'; 11637 } 11638 else 11639 { 11640 getParameters.nav = ''; 11641 } 11642 getParameters.nav += 'size-' + config.navigation.size; 11643 } 11644 } 11645 11646 return getParameters; 11647}; 11648 11649var prepareAjaxConfig = function(config) 11650{ 11651 config = BX.type.isPlainObject(config) ? config : {}; 11652 11653 config.headers = config.headers || []; 11654 config.headers.push({name: 'X-Bitrix-Csrf-Token', value: BX.bitrix_sessid()}); 11655 if (BX.message.SITE_ID) 11656 { 11657 config.headers.push({name: 'X-Bitrix-Site-Id', value: BX.message.SITE_ID}); 11658 } 11659 11660 if (typeof config.json !== 'undefined') 11661 { 11662 if (!BX.type.isPlainObject(config.json)) 11663 { 11664 throw new Error('Wrong `config.json`, plain object expected.') 11665 } 11666 11667 config.headers.push({name: 'Content-Type', value: 'application/json'}); 11668 config.data = config.json; 11669 config.preparePost = false; 11670 } 11671 else if (config.data instanceof FormData) 11672 { 11673 config.preparePost = false; 11674 if (typeof config.signedParameters !== 'undefined') 11675 { 11676 config.data.append('signedParameters', config.signedParameters); 11677 } 11678 } 11679 else if (BX.type.isPlainObject(config.data) || BX.Type.isNil(config.data)) 11680 { 11681 config.data = BX.type.isPlainObject(config.data) ? config.data : {}; 11682 if (typeof config.signedParameters !== 'undefined') 11683 { 11684 config.data.signedParameters = config.signedParameters; 11685 } 11686 } 11687 11688 if (!config.method) 11689 { 11690 config.method = 'POST' 11691 } 11692 11693 return config; 11694}; 11695 11696var buildAjaxPromiseToRestoreCsrf = function(config, withoutRestoringCsrf) 11697{ 11698 withoutRestoringCsrf = withoutRestoringCsrf || false; 11699 var originalConfig = BX.clone(config); 11700 var request = null; 11701 11702 var onrequeststart = config.onrequeststart; 11703 config.onrequeststart = function(xhr) { 11704 request = xhr; 11705 if (BX.type.isFunction(onrequeststart)) 11706 { 11707 onrequeststart(xhr); 11708 } 11709 }; 11710 var onrequeststartOrig = originalConfig.onrequeststart; 11711 originalConfig.onrequeststart = function(xhr) { 11712 request = xhr; 11713 if (BX.type.isFunction(onrequeststartOrig)) 11714 { 11715 onrequeststartOrig(xhr); 11716 } 11717 }; 11718 11719 var promise = BX.ajax.promise(config); 11720 11721 return promise.then(function(response) { 11722 if (!withoutRestoringCsrf && BX.type.isPlainObject(response) && BX.type.isArray(response.errors)) 11723 { 11724 var csrfProblem = false; 11725 response.errors.forEach(function(error) { 11726 if (error.code === 'invalid_csrf' && error.customData.csrf) 11727 { 11728 BX.message({'bitrix_sessid': error.customData.csrf}); 11729 11730 originalConfig.headers = originalConfig.headers || []; 11731 originalConfig.headers = originalConfig.headers.filter(function(header) {
11732 return header && header.name !== 'X-Bitrix-Csrf-Token'; 11733 }); 11734 originalConfig.headers.push({name: 'X-Bitrix-Csrf-Token', value: BX.bitrix_sessid()}); 11735 11736 csrfProblem = true; 11737 } 11738 }); 11739 11740 if (csrfProblem) 11741 { 11742 return buildAjaxPromiseToRestoreCsrf(originalConfig, true); 11743 } 11744 } 11745 11746 if (!BX.type.isPlainObject(response) || response.status !== 'success') 11747 { 11748 var errorPromise = new BX.Promise(); 11749 errorPromise.reject(response); 11750 11751 return errorPromise; 11752 } 11753 11754 return response; 11755 }).catch(function(data) { 11756 var ajaxReject = new BX.Promise(); 11757 11758 var originalJsonResponse; 11759 if (BX.type.isPlainObject(data) && data.xhr && data.xhr.responseText) 11760 { 11761 try 11762 { 11763 originalJsonResponse = JSON.parse(data.xhr.responseText); 11764 data = originalJsonResponse; 11765 } 11766 catch (err) 11767 {} 11768 } 11769 11770 if (BX.type.isPlainObject(data) && data.status && data.hasOwnProperty('data')) 11771 { 11772 ajaxReject.reject(data); 11773 } 11774 else 11775 { 11776 ajaxReject.reject({ 11777 status: 'error', 11778 data: { 11779 ajaxRejectData: data 11780 }, 11781 errors: [ 11782 { 11783 code: 'NETWORK_ERROR', 11784 message: 'Network error' 11785 } 11786 ] 11787 }); 11788 } 11789 11790 return ajaxReject; 11791 }).then(function(response){ 11792 11793 var assetsLoaded = new BX.Promise(); 11794 11795 var headers = request.getAllResponseHeaders().trim().split(/[\r\n]+/); 11796 var headerMap = {}; 11797 headers.forEach(function (line) { 11798 var parts = line.split(': '); 11799 var header = parts.shift().toLowerCase(); 11800 headerMap[header] = parts.join(': '); 11801 }); 11802 11803 if (!headerMap['x-process-assets']) 11804 { 11805 assetsLoaded.fulfill(response); 11806 11807 return assetsLoaded; 11808 } 11809 11810 var assets = BX.prop.getObject(BX.prop.getObject(response, "data", {}), "assets", {}); 11811 11812 var inlineScripts = []; 11813 if (BX.Type.isArrayFilled(assets.string)) 11814 { 11815 assets.string 11816 .reduce(function(acc, item) { 11817 if (String(item).length > 0 && !acc.includes(item)) 11818 { 11819 acc.push(item); 11820 } 11821 11822 return acc; 11823 }, []) 11824 .forEach(function(item) { 11825 if (String(item).startsWith('<script type="extension/settings"')) 11826 { 11827 BX.html(document.head, item, { useAdjacentHTML: true }); 11828 } 11829 else 11830 { 11831 inlineScripts.push(item); 11832 } 11833 }); 11834 } 11835 11836 var promise = new Promise(function(resolve, reject) { 11837 var css = BX.prop.getArray(assets, "css", []); 11838 BX.load(css, function(){ 11839 BX.loadScript( 11840 BX.prop.getArray(assets, "js", []), 11841 resolve 11842 ); 11843 }); 11844 }); 11845 11846 promise.then(function(){ 11847 var stringAsset = inlineScripts.join('\n'); 11848 BX.html(document.head, stringAsset, { useAdjacentHTML: true }).then(function(){ 11849 assetsLoaded.fulfill(response); 11850 }); 11851 }); 11852 11853 return assetsLoaded; 11854 }); 11855}; 11856 11857/** 11858 * 11859 * @param {string} action 11860 * @param {Object} config 11861 * @param {?string|?Object} [config.analyticsLabel] 11862 * @param {?Object} [config.analytics] 11863 * @param {string} [config.analytics.event] 11864 * @param {string} [config.analytics.tool] 11865 * @param {string} [config.analytics.category] 11866 * @param {?string} [config.analytics.c_section] 11867 * @param {?string} [config.analytics.c_sub_section] 11868 * @param {?string} [config.analytics.c_element] 11869 * @param {?string} [config.analytics.type] 11870 * @param {?string} [config.analytics.p1] 11871 * @param {?string} [config.analytics.p2] 11872 * @param {?string} [config.analytics.p3] 11873 * @param {?string} [config.analytics.p4] 11874 * @param {?string} [config.analytics.p5] 11875 * @param {?('success' | 'error' | 'attempt' | 'cancel')} [config.analytics.status] 11876 * @param {string} [config.method='POST'] 11877 * @param {Object} [config.data] 11878 * @param {?Object} [config.getParameters] 11879 * @param {?Object} [config.headers] 11880 * @param {?Object} [config.timeout] 11881 * @param {Object} [config.navigation] 11882 * @param {number} [config.navigation.page] 11883 */ 11884BX.ajax.runAction = function(action, config) 11885{ 11886 config = prepareAjaxConfig(config); 11887 var getParameters = prepareAjaxGetParameters(config); 11888 getParameters.action = action; 11889
11890 var url = '/bitrix/services/main/ajax.php?' + BX.ajax.prepareData(getParameters); 11891 return buildAjaxPromiseToRestoreCsrf({ 11892 method: config.method, 11893 dataType: 'json', 11894 url: url, 11895 data: config.data, 11896 timeout: config.timeout, 11897 preparePost: config.preparePost, 11898 headers: config.headers, 11899 onrequeststart: config.onrequeststart, 11900 onprogress: config.onprogress, 11901 onprogressupload: config.onprogressupload 11902 }); 11903}; 11904 11905/** 11906 * 11907 * @param {string} component 11908 * @param {string} action 11909 * @param {Object} config 11910 * @param {?string|?Object} [config.analyticsLabel] 11911 * @param {?Object} [config.analytics] 11912 * @param {string} [config.analytics.event] 11913 * @param {string} [config.analytics.tool] 11914 * @param {string} [config.analytics.category] 11915 * @param {?string} [config.analytics.c_section] 11916 * @param {?string} [config.analytics.c_sub_section] 11917 * @param {?string} [config.analytics.c_element] 11918 * @param {?string} [config.analytics.type] 11919 * @param {?string} [config.analytics.p1] 11920 * @param {?string} [config.analytics.p2] 11921 * @param {?string} [config.analytics.p3] 11922 * @param {?string} [config.analytics.p4] 11923 * @param {?string} [config.analytics.p5] 11924 * @param {?string} [config.signedParameters] 11925 * @param {string} [config.method='POST'] 11926 * @param {string} [config.mode='ajax'] Ajax or class. 11927 * @param {Object} [config.data] 11928 * @param {?Object} [config.getParameters] 11929 * @param {?array} [config.headers] 11930 * @param {?number} [config.timeout] 11931 * @param {Object} [config.navigation] 11932 */ 11933BX.ajax.runComponentAction = function (component, action, config) 11934{ 11935 config = prepareAjaxConfig(config); 11936 config.mode = config.mode || 'ajax'; 11937 11938 var getParameters = prepareAjaxGetParameters(config); 11939 getParameters.c = component; 11940 getParameters.action = action; 11941
11942 var url = '/bitrix/services/main/ajax.php?' + BX.ajax.prepareData(getParameters); 11943 11944 return buildAjaxPromiseToRestoreCsrf({ 11945 method: config.method, 11946 dataType: 'json', 11947 url: url, 11948 data: config.data, 11949 timeout: config.timeout, 11950 preparePost: config.preparePost, 11951 headers: config.headers, 11952 onrequeststart: (config.onrequeststart ? config.onrequeststart : null), 11953 onprogress: config.onprogress, 11954 onprogressupload: config.onprogressupload 11955 }); 11956}; 11957 11958/* 11959arObs = [{ 11960 url: url, 11961 type: html|script|json|css, 11962 callback: function 11963}] 11964*/ 11965BX.ajax.load = function(arObs, callback) 11966{ 11967 if (!BX.type.isArray(arObs)) 11968 arObs = [arObs]; 11969 11970 var cnt = 0; 11971 11972 if (!BX.type.isFunction(callback)) 11973 callback = BX.DoNothing; 11974 11975 var handler = function(data) 11976 { 11977 if (BX.type.isFunction(this.callback)) 11978 this.callback(data); 11979 11980 if (++cnt >= len) 11981 callback(); 11982 }; 11983 11984 for (var i = 0, len = arObs.length; i<len; i++) 11985 { 11986 switch(arObs[i].type.toUpperCase()) 11987 { 11988 case 'SCRIPT': 11989 BX.loadScript([arObs[i].url], BX.proxy(handler, arObs[i])); 11990 break; 11991 case 'CSS': 11992 BX.loadCSS([arObs[i].url]); 11993 11994 if (++cnt >= len) 11995 callback(); 11996 break; 11997 case 'JSON': 11998 BX.ajax.loadJSON(arObs[i].url, BX.proxy(handler, arObs[i])); 11999 break; 12000 12001 default: 12002 BX.ajax.get(arObs[i].url, '', BX.proxy(handler, arObs[i])); 12003 break; 12004 } 12005 } 12006}; 12007 12008/* ajax form sending */ 12009BX.ajax.submit = function(obForm, callback) 12010{ 12011 if (!obForm.target) 12012 { 12013 if (null == obForm.BXFormTarget) 12014 { 12015 var frame_name = 'formTarget_' + Math.random(); 12016 obForm.BXFormTarget = document.body.appendChild(BX.create('IFRAME', { 12017 props: { 12018 name: frame_name, 12019 id: frame_name, 12020 src: 'javascript:void(0)' 12021 }, 12022 style: { 12023 display: 'none' 12024 } 12025 })); 12026 } 12027 12028 obForm.target = obForm.BXFormTarget.name; 12029 } 12030 12031 obForm.BXFormCallback = callback; 12032 BX.bind(obForm.BXFormTarget, 'load', BX.proxy(BX.ajax._submit_callback, obForm)); 12033 12034 BX.submit(obForm); 12035 12036 return false; 12037}; 12038 12039BX.ajax.submitComponentForm = function(obForm, container, bWait) 12040{ 12041 if (!obForm.target) 12042 { 12043 if (null == obForm.BXFormTarget) 12044 { 12045 var frame_name = 'formTarget_' + Math.random(); 12046 obForm.BXFormTarget = document.body.appendChild(BX.create('IFRAME', { 12047 props: { 12048 name: frame_name, 12049 id: frame_name, 12050 src: 'javascript:void(0)' 12051 }, 12052 style: { 12053 display: 'none' 12054 } 12055 })); 12056 } 12057 12058 obForm.target = obForm.BXFormTarget.name; 12059 } 12060 12061 if (!!bWait) 12062 var w = BX.showWait(container); 12063 12064 obForm.BXFormCallback = function(d) { 12065 if (!!bWait) 12066 BX.closeWait(w); 12067 12068 var callOnload = function(){ 12069 if(!!window.bxcompajaxframeonload) 12070 { 12071 setTimeout(function(){window.bxcompajaxframeonload();window.bxcompajaxframeonload=null;}, 10); 12072 } 12073 }; 12074 12075 BX(container).innerHTML = d; 12076 BX.onCustomEvent('onAjaxSuccess', [null,null,callOnload]); 12077 }; 12078 12079 BX.bind(obForm.BXFormTarget, 'load', BX.proxy(BX.ajax._submit_callback, obForm)); 12080 12081 return true; 12082}; 12083 12084// func will be executed in form context 12085BX.ajax._submit_callback = function() 12086{ 12087 //opera and IE8 triggers onload event even on empty iframe 12088 try 12089 { 12090 if(this.BXFormTarget.contentWindow.location.href.indexOf('http') != 0) 12091 return; 12092 } catch (e) { 12093 return; 12094 } 12095 12096 if (this.BXFormCallback) 12097 this.BXFormCallback.apply(this, [this.BXFormTarget.contentWindow.document.body.innerHTML]); 12098 12099 BX.unbindAll(this.BXFormTarget); 12100}; 12101 12102BX.ajax.prepareForm = function(obForm, data) 12103{ 12104 data = (!!data ? data : {}); 12105 var i, ii, el, 12106 _data = [], 12107 n = obForm.elements.length, 12108 files = 0, length = 0; 12109 if(!!obForm) 12110 { 12111 for (i = 0; i < n; i++) 12112 { 12113 el = obForm.elements[i]; 12114 if (el.disabled) 12115 continue; 12116 12117 if(!el.type) 12118 continue; 12119 12120 switch(el.type.toLowerCase()) 12121 { 12122 case 'text': 12123 case 'textarea': 12124 case 'password': 12125 case 'number': 12126 case 'hidden': 12127 case 'select-one': 12128 _data.push({name: el.name, value: el.value}); 12129 length += (el.name.length + el.value.length); 12130 break; 12131 case 'file': 12132 if (!!el.files) 12133 { 12134 for (ii = 0; ii < el.files.length; ii++) 12135 { 12136 files++; 12137 _data.push({name: el.name, value: el.files[ii], file : true}); 12138 length += el.files[ii].size; 12139 } 12140 } 12141 break; 12142 case 'radio':
12143 case 'checkbox': 12144 if(el.checked) 12145 { 12146 _data.push({name: el.name, value: el.value}); 12147 length += (el.name.length + el.value.length); 12148 } 12149 break; 12150 case 'select-multiple': 12151 for (var j = 0; j < el.options.length; j++) 12152 { 12153 if (el.options[j].selected) 12154 { 12155 _data.push({name : el.name, value : el.options[j].value}); 12156 length += (el.name.length + el.options[j].length); 12157 } 12158 } 12159 break; 12160 default: 12161 break; 12162 } 12163 } 12164 12165 i = 0; length = 0; 12166 var current = data, name, rest, pp, tmpKey; 12167 12168 while(i < _data.length) 12169 { 12170 var p = _data[i].name.indexOf('['); 12171 if (tmpKey) 12172 { 12173 current[_data[i].name] = {}; 12174 current[_data[i].name][tmpKey.replace(/\[|\]/gi, '')] = _data[i].value; 12175 current = data; 12176 tmpKey = null; 12177 i++; 12178 } 12179 else if (p == -1) 12180 { 12181 current[_data[i].name] = _data[i].value; 12182 current = data; 12183 i++; 12184 } 12185 else 12186 { 12187 name = _data[i].name.substring(0, p); 12188 rest = _data[i].name.substring(p+1); 12189 pp = rest.indexOf(']'); 12190 12191 if(pp == -1) 12192 { 12193 if (!current[name]) 12194 current[name] = []; 12195 current = data; 12196 i++; 12197 } 12198 else if(pp == 0) 12199 { 12200 if (!current[name]) 12201 current[name] = []; 12202 //No index specified - so take the next integer 12203 current = current[name]; 12204 _data[i].name = '' + current.length; 12205 if (rest.substring(pp+1).indexOf('[') === 0) 12206 tmpKey = rest.substring(0, pp) + rest.substring(pp+1); 12207 } 12208 else 12209 { 12210 if (!current[name]) 12211 current[name] = {}; 12212 //Now index name becomes and name and we go deeper into the array 12213 current = current[name]; 12214 _data[i].name = rest.substring(0, pp) + rest.substring(pp+1); 12215 } 12216 } 12217 } 12218 } 12219 return {data : data, filesCount : files, roughSize : length}; 12220}; 12221BX.ajax.submitAjax = function(obForm, config) 12222{ 12223 config = (config !== null && typeof config == "object" ? config : {}); 12224 config.url = (config["url"] || obForm.getAttribute("action")); 12225 12226 var additionalData = (config["data"] || {}); 12227 config.data = BX.ajax.prepareForm(obForm).data; 12228 for (var ii in additionalData) 12229 { 12230 if (additionalData.hasOwnProperty(ii)) 12231 { 12232 config.data[ii] = additionalData[ii]; 12233 } 12234 } 12235 12236 if (!window["FormData"]) 12237 { 12238 BX.ajax(config); 12239 } 12240 else 12241 { 12242 var isFile = function(item) 12243 { 12244 var res = Object.prototype.toString.call(item); 12245 return (res == '[object File]' || res == '[object Blob]'); 12246 }, 12247 appendToForm = function(fd, key, val) 12248 { 12249 if (!!val && typeof val == "object" && !isFile(val)) 12250 { 12251 for (var ii in val) 12252 { 12253 if (val.hasOwnProperty(ii)) 12254 { 12255 appendToForm(fd, (key == '' ? ii : key + '[' + ii + ']'), val[ii]); 12256 } 12257 } 12258 } 12259 else 12260 fd.append(key, (!!val ? val : '')); 12261 }, 12262 prepareData = function(arData) 12263 { 12264 var data = {}; 12265 if (null != arData) 12266 { 12267 if(typeof arData == 'object') 12268 { 12269 for(var i in arData) 12270 { 12271 if (arData.hasOwnProperty(i)) 12272 { 12273 var name = BX.util.urlencode(i); 12274 if(typeof arData[i] == 'object' && arData[i]["file"] !== true) 12275 data[name] = prepareData(arData[i]); 12276 else if (arData[i]["file"] === true) 12277 data[name] = arData[i]["value"]; 12278 else 12279 data[name] = BX.util.urlencode(arData[i]); 12280 } 12281 } 12282 } 12283 else 12284 data = BX.util.urlencode(arData); 12285 } 12286 return data; 12287 }, 12288 fd = new window.FormData(); 12289 12290 if (config.method !== 'POST') 12291 { 12292 config.data = BX.ajax.prepareData(config.data); 12293 if (config.data) 12294 { 12295 config.url += (config.url.indexOf('?') !== -1 ? "&" : "?") + config.data; 12296 config.data = ''; 12297 } 12298 } 12299 else 12300 { 12301 if (config.preparePost === true) 12302 config.data = prepareData(config.data); 12303 appendToForm(fd, '', config.data); 12304 config.data = fd; 12305 } 12306 12307 config.preparePost = false; 12308 config.start = false;
12309 12310 var xhr = BX.ajax(config); 12311 if (!!config["onprogress"]) 12312 xhr.upload.addEventListener( 12313 'progress', 12314 function(e){ 12315 var percent = null; 12316 if(e.lengthComputable && (e.total || e["totalSize"])) { 12317 percent = e.loaded * 100 / (e.total || e["totalSize"]); 12318 } 12319 config["onprogress"](e, percent); 12320 } 12321 ); 12322 xhr.send(fd); 12323 } 12324}; 12325 12326BX.ajax.UpdatePageData = function (arData) 12327{ 12328 if (arData.TITLE) 12329 BX.ajax.UpdatePageTitle(arData.TITLE); 12330 if (arData.WINDOW_TITLE || arData.TITLE) 12331 BX.ajax.UpdateWindowTitle(arData.WINDOW_TITLE || arData.TITLE); 12332 if (arData.NAV_CHAIN) 12333 BX.ajax.UpdatePageNavChain(arData.NAV_CHAIN); 12334 if (arData.CSS && arData.CSS.length > 0) 12335 BX.loadCSS(arData.CSS); 12336 if (arData.SCRIPTS && arData.SCRIPTS.length > 0) 12337 { 12338 var f = function(result,config,cb){ 12339 12340 if(!!config && BX.type.isArray(config.scripts)) 12341 { 12342 for(var i=0,l=arData.SCRIPTS.length;i<l;i++) 12343 { 12344 config.scripts.push({isInternal:false,JS:arData.SCRIPTS[i]}); 12345 } 12346 } 12347 else 12348 { 12349 BX.loadScript(arData.SCRIPTS,cb); 12350 } 12351 12352 BX.removeCustomEvent('onAjaxSuccess',f); 12353 }; 12354 BX.addCustomEvent('onAjaxSuccess',f); 12355 } 12356 else 12357 { 12358 var f1 = function(result,config,cb){ 12359 if(BX.type.isFunction(cb)) 12360 { 12361 cb(); 12362 } 12363 BX.removeCustomEvent('onAjaxSuccess',f1); 12364 }; 12365 BX.addCustomEvent('onAjaxSuccess', f1); 12366 } 12367}; 12368 12369BX.ajax.UpdatePageTitle = function(title) 12370{ 12371 var obTitle = BX('pagetitle'); 12372 if (obTitle) 12373 { 12374 BX.remove(obTitle.firstChild); 12375 if (!obTitle.firstChild) 12376 obTitle.appendChild(document.createTextNode(title)); 12377 else 12378 obTitle.insertBefore(document.createTextNode(title), obTitle.firstChild); 12379 } 12380}; 12381 12382BX.ajax.UpdateWindowTitle = function(title) 12383{ 12384 document.title = title; 12385}; 12386 12387BX.ajax.UpdatePageNavChain = function(nav_chain) 12388{ 12389 var obNavChain = BX('navigation'); 12390 if (obNavChain) 12391 { 12392 obNavChain.innerHTML = nav_chain; 12393 } 12394}; 12395 12396/* user options handling */ 12397BX.userOptions = { 12398 options: null, 12399 bSend: false, 12400 delay: 5000, 12401 path: '/bitrix/admin/user_options.php?' 12402}; 12403 12404BX.userOptions.setAjaxPath = function(url) 12405{ 12406 // eslint-disable-next-line no-console 12407 console.warn('BX.userOptions.setAjaxPath is deprecated. There is no way to change ajax path.'); 12408}; 12409BX.userOptions.save = function(category, name, valueName, value, common) 12410{ 12411 if (BX.userOptions.options === null) 12412 { 12413 BX.userOptions.options = {}; 12414 } 12415 12416 common = Boolean(common); 12417 BX.userOptions.options[`${category}.${name}.${valueName}`] = [category, name, valueName, value, common]; 12418 12419 const stringPackedValue = BX.userOptions.__get(); 12420 if (stringPackedValue) 12421 { 12422 document.cookie = `${BX.message('COOKIE_PREFIX')}_LAST_SETTINGS=${encodeURIComponent(stringPackedValue)}&sessid=${BX.bitrix_sessid()}; expires=Thu, 31 Dec ${(new Date()).getFullYear() + 1} 23:59:59 GMT; path=/;`; 12423 } 12424 12425 if (!BX.userOptions.bSend) 12426 { 12427 BX.userOptions.bSend = true; 12428 setTimeout(() => { 12429 BX.userOptions.send(null); 12430 }, BX.userOptions.delay); 12431 } 12432}; 12433 12434BX.userOptions.send = function(callback) 12435{ 12436 const values = BX.userOptions.__get_values({ backwardCompatibility: true}); 12437 12438 BX.userOptions.options = null; 12439 BX.userOptions.bSend = false; 12440 12441 if (values) 12442 { 12443 document.cookie = `${BX.message('COOKIE_PREFIX')}_LAST_SETTINGS=; path=/;`; 12444 12445 BX.ajax.runAction( 12446 'main.userOption.saveOptions', 12447 { 12448 json: { 12449 newValues: values, 12450 }, 12451 }, 12452 ).then((response) => { 12453 if (BX.type.isFunction(callback)) 12454 { 12455 callback(response); 12456 } 12457 }); 12458 } 12459}; 12460 12461BX.userOptions.del = function(category, name, common, callback) 12462{ 12463 BX.ajax.runAction( 12464 'main.userOption.deleteOption', 12465 { 12466 json: { 12467 category, 12468 name, 12469 common, 12470 }, 12471 }, 12472 ).then((response) => { 12473 if (BX.type.isFunction(callback)) 12474 { 12475 callback(response); 12476 } 12477 }); 12478}; 12479 12480BX.userOptions.__get_values = function({ backwardCompatibility }) 12481{ 12482 if (!BX.userOptions || !BX.Type.isPlainObject(BX.userOptions.options)) 12483 { 12484 return null; 12485 } 12486 12487 const CATEGORY = 0; 12488 const NAME = 1; 12489 const VALUE_NAME = 2; 12490 const VALUE = 3; 12491 const IS_DEFAULT = 4; 12492 12493 const packedValues = { p: [] }; 12494 let currentIndex = -1; 12495 let previousOptionIdentifier = ''; 12496 12497 Object.entries(BX.userOptions.options).forEach(([key, userOption]) => { 12498 const category = userOption[CATEGORY]; 12499 const name = userOption[NAME]; 12500 const currentOptionIdentifier = `${category}.${name}`; 12501 12502 if (previousOptionIdentifier !== currentOptionIdentifier) 12503 { 12504 currentIndex++; 12505 packedValues.p.push({ 12506 c: category, 12507 n: name, 12508 v: {}, 12509 }); 12510 if (userOption[IS_DEFAULT] === true) 12511 { 12512 packedValues.p[currentIndex].d = 'Y'; 12513 } 12514 previousOptionIdentifier = currentOptionIdentifier; 12515 } 12516 12517 if (userOption[VALUE_NAME] === null) 12518 { 12519 packedValues.p[currentIndex].v = userOption[VALUE]; 12520 } 12521 else 12522 { 12523 let data = userOption[VALUE]; 12524 if (backwardCompatibility && Array.isArray(userOption[VALUE])) 12525 { 12526 data = userOption[VALUE].join(','); 12527 } 12528 packedValues.p[currentIndex].v[userOption[VALUE_NAME]] = data; 12529 } 12530 }); 12531 12532 return packedValues.p.length > 0 ? packedValues.p : null; 12533}; 12534 12535/** 12536 * @deprecated Use instead BX.userOptions.__get_values. 12537 * */ 12538BX.userOptions.__get = function() 12539{ 12540 if (!BX.userOptions.options) return ''; 12541 12542 var sParam = '', n = -1, prevParam = '', aOpt, i; 12543 12544 for (i in BX.userOptions.options) 12545 { 12546 if(BX.userOptions.options.hasOwnProperty(i)) 12547 { 12548 aOpt = BX.userOptions.options[i]; 12549 12550 if (prevParam != aOpt[0]+'.'+aOpt[1]) 12551 { 12552 n++; 12553 sParam += '&p['+n+'][c]='+BX.util.urlencode(aOpt[0]); 12554 sParam += '&p['+n+'][n]='+BX.util.urlencode(aOpt[1]); 12555 if (aOpt[4] == true) 12556 sParam += '&p['+n+'][d]=Y'; 12557 prevParam = aOpt[0]+'.'+aOpt[1]; 12558 } 12559 12560 var valueName = aOpt[2]; 12561 var value = aOpt[3]; 12562 12563 if (valueName === null) 12564 { 12565 sParam += '&p['+n+'][v]='+BX.util.urlencode(value); 12566 } 12567 else 12568 {
12569 sParam += '&p['+n+'][v]['+BX.util.urlencode(valueName)+']='+BX.util.urlencode(value); 12570 } 12571 } 12572 } 12573 12574 return sParam.substr(1); 12575}; 12576 12577BX.ajax.history = { 12578 expected_hash: '', 12579 12580 obParams: null, 12581 12582 obFrame: null, 12583 obImage: null, 12584 12585 obTimer: null, 12586 12587 bInited: false, 12588 bHashCollision: false, 12589 bPushState: !!(history.pushState && BX.type.isFunction(history.pushState)), 12590 12591 startState: null, 12592 12593 init: function(obParams) 12594 { 12595 if (BX.ajax.history.bInited) 12596 return; 12597 12598 this.obParams = obParams; 12599 var obCurrentState = this.obParams.getState(); 12600 12601 if (BX.ajax.history.bPushState) 12602 { 12603 BX.ajax.history.expected_hash = window.location.pathname; 12604 if (window.location.search) 12605 BX.ajax.history.expected_hash += window.location.search; 12606 12607 BX.ajax.history.put(obCurrentState, BX.ajax.history.expected_hash, '', true); 12608 // due to some strange thing, chrome calls popstate event on page start. so we should delay it 12609 setTimeout(function(){BX.bind(window, 'popstate', BX.ajax.history.__hashListener);}, 500); 12610 } 12611 else 12612 { 12613 BX.ajax.history.expected_hash = window.location.hash; 12614 12615 if (!BX.ajax.history.expected_hash || BX.ajax.history.expected_hash == '#') 12616 BX.ajax.history.expected_hash = '__bx_no_hash__'; 12617 12618 jsAjaxHistoryContainer.put(BX.ajax.history.expected_hash, obCurrentState); 12619 BX.ajax.history.obTimer = setTimeout(BX.ajax.history.__hashListener, 500); 12620 12621 if (BX.browser.IsIE()) 12622 { 12623 BX.ajax.history.obFrame = document.createElement('IFRAME'); 12624 BX.hide_object(BX.ajax.history.obFrame); 12625 12626 document.body.appendChild(BX.ajax.history.obFrame); 12627 12628 BX.ajax.history.obFrame.contentWindow.document.open(); 12629 BX.ajax.history.obFrame.contentWindow.document.write(BX.ajax.history.expected_hash); 12630 BX.ajax.history.obFrame.contentWindow.document.close(); 12631 } 12632 else if (BX.browser.IsOpera()) 12633 { 12634 BX.ajax.history.obImage = document.createElement('IMG'); 12635 BX.hide_object(BX.ajax.history.obImage); 12636 12637 document.body.appendChild(BX.ajax.history.obImage); 12638 12639 BX.ajax.history.obImage.setAttribute('src', 'javascript:location.href = \'javascript:BX.ajax.history.__hashListener();\';'); 12640 } 12641 } 12642 12643 BX.ajax.history.bInited = true; 12644 }, 12645 12646 __hashListener: function(e) 12647 { 12648 e = e || window.event || {state:false}; 12649 12650 if (BX.ajax.history.bPushState) 12651 { 12652 BX.ajax.history.obParams.setState(e.state||BX.ajax.history.startState); 12653 } 12654 else 12655 { 12656 if (BX.ajax.history.obTimer) 12657 { 12658 window.clearTimeout(BX.ajax.history.obTimer); 12659 BX.ajax.history.obTimer = null; 12660 } 12661 12662 var current_hash; 12663 if (null != BX.ajax.history.obFrame) 12664 current_hash = BX.ajax.history.obFrame.contentWindow.document.body.innerText; 12665 else 12666 current_hash = window.location.hash; 12667 12668 if (!current_hash || current_hash == '#') 12669 current_hash = '__bx_no_hash__'; 12670 12671 if (current_hash.indexOf('#') == 0) 12672 current_hash = current_hash.substring(1); 12673 12674 if (current_hash != BX.ajax.history.expected_hash) 12675 { 12676 var state = jsAjaxHistoryContainer.get(current_hash); 12677 if (state) 12678 { 12679 BX.ajax.history.obParams.setState(state); 12680 12681 BX.ajax.history.expected_hash = current_hash; 12682 if (null != BX.ajax.history.obFrame) 12683 { 12684 var __hash = current_hash == '__bx_no_hash__' ? '' : current_hash; 12685 if (window.location.hash != __hash && window.location.hash != '#' + __hash) 12686 window.location.hash = __hash; 12687 } 12688 } 12689 } 12690 12691 BX.ajax.history.obTimer = setTimeout(BX.ajax.history.__hashListener, 500); 12692 } 12693 }, 12694 12695 put: function(state, new_hash, new_hash1, bStartState) 12696 { 12697 if (this.bPushState) 12698 { 12699 if(!bStartState) 12700 { 12701 history.pushState(state, '', new_hash); 12702 } 12703 else 12704 { 12705 BX.ajax.history.startState = state; 12706 } 12707 } 12708 else 12709 { 12710 if (typeof new_hash1 != 'undefined') 12711 new_hash = new_hash1; 12712 else 12713 new_hash = 'view' + new_hash; 12714 12715 jsAjaxHistoryContainer.put(new_hash, state); 12716 BX.ajax.history.expected_hash = new_hash; 12717 12718 window.location.hash = BX.util.urlencode(new_hash); 12719 12720 if (null != BX.ajax.history.obFrame) 12721 { 12722 BX.ajax.history.obFrame.contentWindow.document.open(); 12723 BX.ajax.history.obFrame.contentWindow.document.write(new_hash); 12724 BX.ajax.history.obFrame.contentWindow.document.close(); 12725 } 12726 } 12727 }, 12728 12729 checkRedirectStart: function(param_name, param_value) 12730 { 12731 var current_hash = window.location.hash; 12732 if (current_hash.substring(0, 1) == '#') current_hash = current_hash.substring(1); 12733 12734 var test = current_hash.substring(0, 5); 12735 if (test == 'view/' || test == 'view%') 12736 { 12737 BX.ajax.history.bHashCollision = true;
12738 document.write('<' + 'div id="__ajax_hash_collision_' + param_value + '" style="display: none;">'); 12739 } 12740 }, 12741 12742 checkRedirectFinish: function(param_name, param_value) 12743 { 12744 document.write('</div>'); 12745 12746 var current_hash = window.location.hash; 12747 if (current_hash.substring(0, 1) == '#') current_hash = current_hash.substring(1); 12748 12749 BX.ready(function () 12750 { 12751 var test = current_hash.substring(0, 5); 12752 if (test == 'view/' || test == 'view%') 12753 { 12754 var obColNode = BX('__ajax_hash_collision_' + param_value); 12755 var obNode = obColNode.firstChild; 12756 BX.cleanNode(obNode); 12757 obColNode.style.display = 'block'; 12758 12759 // IE, Opera and Chrome automatically modifies hash with urlencode, but FF doesn't ;-( 12760 if (test != 'view%') 12761 current_hash = BX.util.urlencode(current_hash); 12762 12763 current_hash += (current_hash.indexOf('%3F') == -1 ? '%3F' : '%26') + param_name + '=' + param_value; 12764 12765 var url = '/bitrix/tools/ajax_redirector.php?hash=' + current_hash; 12766 12767 BX.ajax.insertToNode(url, obNode); 12768 } 12769 }); 12770 } 12771}; 12772 12773BX.ajax.component = function(node) 12774{ 12775 this.node = node; 12776}; 12777 12778BX.ajax.component.prototype.getState = function() 12779{ 12780 var state = { 12781 'node': this.node, 12782 'title': window.document.title, 12783 'data': BX(this.node).innerHTML 12784 }; 12785 12786 var obNavChain = BX('navigation'); 12787 if (null != obNavChain) 12788 state.nav_chain = obNavChain.innerHTML; 12789 12790 BX.onCustomEvent(BX(state.node), "onComponentAjaxHistoryGetState", [state]); 12791 12792 return state; 12793}; 12794 12795BX.ajax.component.prototype.setState = function(state) 12796{ 12797 BX(state.node).innerHTML = state.data; 12798 BX.ajax.UpdatePageTitle(state.title); 12799 12800 if (state.nav_chain) 12801 { 12802 BX.ajax.UpdatePageNavChain(state.nav_chain); 12803 } 12804 12805 BX.onCustomEvent(BX(state.node), "onComponentAjaxHistorySetState", [state]); 12806}; 12807 12808var jsAjaxHistoryContainer = { 12809 arHistory: {}, 12810 12811 put: function(hash, state) 12812 { 12813 this.arHistory[hash] = state; 12814 }, 12815 12816 get: function(hash) 12817 { 12818 return this.arHistory[hash]; 12819 } 12820}; 12821 12822 12823BX.ajax.FormData = function() 12824{ 12825 this.elements = []; 12826 this.files = []; 12827 this.features = {}; 12828 this.isSupported(); 12829 this.log('BX FormData init'); 12830}; 12831 12832BX.ajax.FormData.isSupported = function() 12833{ 12834 var f = new BX.ajax.FormData(); 12835 var result = f.features.supported; 12836 f = null; 12837 return result; 12838}; 12839 12840BX.ajax.FormData.prototype.log = function(o) 12841{ 12842 if (false) { 12843 try { 12844 if (BX.browser.IsIE()) o = JSON.stringify(o); 12845 console.log(o); 12846 } catch(e) {} 12847 } 12848}; 12849 12850BX.ajax.FormData.prototype.isSupported = function() 12851{ 12852 var f = {}; 12853 f.fileReader = (window.FileReader && window.FileReader.prototype.readAsBinaryString); 12854 f.readFormData = f.sendFormData = !!(window.FormData); 12855 f.supported = !!(f.readFormData && f.sendFormData); 12856 this.features = f; 12857 this.log('features:'); 12858 this.log(f); 12859 12860 return f.supported; 12861}; 12862 12863BX.ajax.FormData.prototype.append = function(name, value) 12864{ 12865 if (typeof(value) === 'object') { // seems to be files element 12866 this.files.push({'name': name, 'value':value}); 12867 } else { 12868 this.elements.push({'name': name, 'value':value}); 12869 } 12870}; 12871 12872BX.ajax.FormData.prototype.send = function(url, callbackOk, callbackProgress, callbackError) 12873{ 12874 this.log('FD send'); 12875 this.xhr = BX.ajax({ 12876 'method': 'POST', 12877 'dataType': 'html', 12878 'url': url, 12879 'onsuccess': callbackOk, 12880 'onfailure': callbackError, 12881 'start': false, 12882 'preparePost':false 12883 }); 12884 12885 if (callbackProgress) 12886 { 12887 this.xhr.upload.addEventListener( 12888 'progress', 12889 function(e) { 12890 if (e.lengthComputable) 12891 callbackProgress(e.loaded / (e.total || e.totalSize)); 12892 }, 12893 false 12894 ); 12895 } 12896 12897 if (this.features.readFormData && this.features.sendFormData) 12898 { 12899 var fd = new FormData(); 12900 this.log('use browser formdata'); 12901 for (var i in this.elements) 12902 { 12903 if(this.elements.hasOwnProperty(i)) 12904 fd.append(this.elements[i].name,this.elements[i].value); 12905 } 12906 for (i in this.files) 12907 { 12908 if(this.files.hasOwnProperty(i)) 12909 fd.append(this.files[i].name, this.files[i].value); 12910 } 12911 this.xhr.send(fd); 12912 } 12913 12914 return this.xhr; 12915}; 12916 12917BX.addCustomEvent('onAjaxFailure', BX.debug); 12918})(window); 12919 12920 12921 12922(function (exports,main_core) { 12923 'use strict'; 12924 12925 var LazyLoad = { 12926 observer: null, 12927 images: {}, 12928 imageStatus: { 12929 hidden: -2, 12930 error: -1, 12931 "undefined": 0, 12932 inited: 1, 12933 loaded: 2 12934 }, 12935 imageTypes: { 12936 image: 1, 12937 background: 2 12938 }, 12939 initObserver: function initObserver() { 12940 this.observer = new IntersectionObserver(this.onIntersection.bind(this), { 12941 rootMargin: '20% 0% 20% 0%', 12942 threshold: 0.10 12943 }); 12944 }, 12945 onIntersection: function onIntersection(entries) {
12946 entries.forEach(function (entry) { 12947 if (entry.isIntersecting) { 12948 this.showImage(entry.target); 12949 } 12950 }.bind(this)); 12951 }, 12952 registerImage: function registerImage(id, isImageVisibleCallback, options) { 12953 if (this.observer === null) { 12954 this.initObserver(); 12955 } 12956 12957 options = options || {}; 12958 12959 if (!main_core.Type.isStringFilled(id)) { 12960 return; 12961 } 12962 12963 if (main_core.Type.isObject(this.images[id])) { 12964 return; 12965 } 12966 12967 var element = document.getElementById(id); 12968 12969 if (!main_core.Type.isDomNode(element)) { 12970 return; 12971 } 12972 12973 this.observer.observe(element); 12974 this.images[id] = { 12975 id: id, 12976 node: null, 12977 src: null, 12978 dataSrcName: options.dataSrcName || 'src', 12979 type: null, 12980 func: main_core.Type.isFunction(isImageVisibleCallback) ? isImageVisibleCallback : null, 12981 status: this.imageStatus.undefined 12982 }; 12983 }, 12984 registerImages: function registerImages(ids, isImageVisibleCallback, options) { 12985 if (main_core.Type.isArray(ids)) { 12986 for (var i = 0, length = ids.length; i < length; i++) { 12987 this.registerImage(ids[i], isImageVisibleCallback, options); 12988 } 12989 } 12990 }, 12991 showImage: function showImage(imageNode) { 12992 var imageNodeId = imageNode.id; 12993 12994 if (!main_core.Type.isStringFilled(imageNodeId)) { 12995 return; 12996 } 12997 12998 var image = this.images[imageNodeId]; 12999 13000 if (!main_core.Type.isPlainObject(image)) { 13001 return; 13002 } 13003 13004 if (image.status == this.imageStatus.undefined) { 13005 this.initImage(image); 13006 } 13007 13008 if (image.status !== this.imageStatus.inited) { 13009 return; 13010 } 13011 13012 if (!image.node || !image.node.parentNode) { 13013 image.node = null; 13014 image.status = this.imageStatus.error; 13015 return; 13016 } 13017 13018 if (image.type == this.imageTypes.image) { 13019 image.node.src = image.src; 13020 } else { 13021 image.node.style.backgroundImage = "url('" + image.src + "')"; 13022 } 13023 13024 image.node.dataset[image.dataSrcName] = ""; 13025 image.status = this.imageStatus.loaded; 13026 }, 13027 showImages: function showImages(checkOwnVisibility) { 13028 checkOwnVisibility = checkOwnVisibility !== false; 13029 13030 for (var id in this.images) { 13031 if (!this.images.hasOwnProperty(id)) { 13032 continue; 13033 } 13034 13035 var image = this.images[id]; 13036 13037 if (image.status == this.imageStatus.undefined) { 13038 this.initImage(image); 13039 } 13040 13041 if (image.status !== this.imageStatus.inited) { 13042 continue; 13043 } 13044 13045 if (!image.node || !image.node.parentNode) { 13046 image.node = null; 13047 image.status = this.imageStatus.error; 13048 continue; 13049 } 13050 13051 var isImageVisible = true; 13052 13053 if (checkOwnVisibility && main_core.Type.isFunction(image.func)) { 13054 isImageVisible = image.func(image); 13055 } 13056 13057 if (isImageVisible === true && this.isElementVisibleOnScreen(image.node)) { 13058 if (image.type == this.imageTypes.image) { 13059 image.node.src = image.src; 13060 } else { 13061 image.node.style.backgroundImage = "url('" + image.src + "')"; 13062 } 13063 13064 image.node.dataset[image.dataSrcName] = ""; 13065 image.status = this.imageStatus.loaded; 13066 } 13067 } 13068 }, 13069 initImage: function initImage(image) { 13070 image.status = this.imageStatus.error; 13071 var node = document.getElementById(image.id); 13072 13073 if (!main_core.Type.isDomNode(node)) { 13074 return; 13075 } 13076 13077 var src = node.dataset[image.dataSrcName]; 13078 13079 if (main_core.Type.isStringFilled(src)) { 13080 image.node = node; 13081 image.src = src; 13082 image.status = this.imageStatus.inited; 13083 image.type = image.node.tagName.toLowerCase() == "img" ? this.imageTypes.image : this.imageTypes.background; 13084 } 13085 }, 13086 isElementVisibleOnScreen: function isElementVisibleOnScreen(element) { 13087 var coords = this.getElementCoords(element); 13088 var windowTop = window.pageYOffset || document.documentElement.scrollTop; 13089 var windowBottom = windowTop + document.documentElement.clientHeight; 13090 coords.bottom = coords.top + element.offsetHeight; 13091 return coords.top > windowTop && coords.top < windowBottom || // topVisible 13092 coords.bottom < windowBottom && coords.bottom > windowTop // bottomVisible 13093 ; 13094 }, 13095 isElementVisibleOn2Screens: function isElementVisibleOn2Screens(element) { 13096 var windowHeight = document.documentElement.clientHeight; 13097 var windowTop = window.pageYOffset || document.documentElement.scrollTop; 13098 var windowBottom = windowTop + windowHeight; 13099 var coords = this.getElementCoords(element); 13100 coords.bottom = coords.top + element.offsetHeight; 13101 windowTop -= windowHeight; 13102 windowBottom += windowHeight; 13103 return coords.top > windowTop && coords.top < windowBottom || // topVisible 13104 coords.bottom < windowBottom && coords.bottom > windowTop // bottomVisible 13105 ; 13106 }, 13107 getElementCoords: function getElementCoords(element) { 13108 var box = element.getBoundingClientRect(); 13109 return { 13110 originTop: box.top, 13111 originLeft: box.left, 13112 top: box.top + window.pageYOffset, 13113 left: box.left + window.pageXOffset 13114 }; 13115 }, 13116 onScroll: function onScroll() {}, 13117 clearImages: function clearImages() { 13118 this.images = []; 13119 } 13120 }; 13121 13122 exports.LazyLoad = LazyLoad; 13123 13124}((this.BX = this.BX || {}),BX)); 13125 13126 13127 13128(function (exports) { 13129 'use strict'; 13130 13131 var ParamBag = /*#__PURE__*/function () { 13132 function ParamBag() { 13133 var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 13134 babelHelpers.classCallCheck(this, ParamBag); 13135 13136 if (!!params && babelHelpers.typeof(params) === 'object') { 13137 this.params = new Map(Object.entries(params)); 13138 } else { 13139 this.params = new Map(); 13140 } 13141 } 13142 13143 babelHelpers.createClass(ParamBag, [{ 13144 key: "getParam", 13145 value: function getParam(key) { 13146 var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; 13147 13148 if (this.params.has(key)) { 13149 return this.params.get(key); 13150 } 13151 13152 return defaultValue; 13153 } 13154 }, { 13155 key: "setParam", 13156 value: function setParam(key, value) { 13157 this.params.set(key, value); 13158 } 13159 }, { 13160 key: "clear", 13161 value: function clear() { 13162 this.params.clear(); 13163 } 13164 }], [{ 13165 key: "create", 13166 value: function create() { 13167 var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 13168 return new ParamBag(params); 13169 } 13170 }]); 13171 return ParamBag; 13172 }(); 13173 13174 exports.ParamBag = ParamBag; 13175 13176}((this.BX = this.BX || {}))); 13177 13178 13179 13180(function() { 13181 BX.FixFontSize = function(params) 13182 { 13183 var widthNode, computedStyles, width; 13184 13185 this.node = null; 13186 this.prevWindowSize = 0; 13187 this.prevWrapperSize = 0; 13188 this.mainWrapper = null; 13189 this.textWrapper = null; 13190 this.objList = params.objList; 13191 this.minFontSizeList = []; 13192 this.minFontSize = 0; 13193 13194 if (params.onresize) 13195 { 13196 this.prevWindowSize = window.innerWidth || document.documentElement.clientWidth; 13197 BX.bind(window, 'resize', BX.throttle(this.onResize, 350, this)); 13198 } 13199 13200 if (params.onAdaptiveResize) 13201 { 13202 widthNode = this.objList[0].scaleBy || this.objList[0].node; 13203 computedStyles = getComputedStyle(widthNode); 13204 this.prevWrapperSize = parseInt(computedStyles["width"]) - parseInt(computedStyles["paddingLeft"]) - parseInt(computedStyles["paddingRight"]); 13205 BX.bind(window, 'resize', BX.throttle(this.onAdaptiveResize, 350, this)); 13206 } 13207 13208 this.createTestNodes(); 13209 this.decrease(); 13210 }; 13211 13212 BX.FixFontSize.prototype = 13213 { 13214 createTestNodes: function() 13215 { 13216 this.textWrapper = BX.create('div',{ 13217 style : { 13218 display : 'inline-block', 13219 whiteSpace : 'nowrap' 13220 } 13221 }); 13222 13223 this.mainWrapper = BX.create('div',{ 13224 style : { 13225 height : 0, 13226 overflow : 'hidden' 13227 }, 13228 children : [this.textWrapper] 13229 }); 13230 13231 }, 13232 insertTestNodes: function() 13233 { 13234 document.body.appendChild(this.mainWrapper); 13235 }, 13236 removeTestNodes: function() 13237 { 13238 document.body.removeChild(this.mainWrapper); 13239 }, 13240 decrease: function() 13241 { 13242 var width, 13243 fontSize, 13244 widthNode, 13245 computedStyles; 13246 13247 this.insertTestNodes(); 13248
13249 for(var i=this.objList.length-1; i>=0; i--) 13250 { 13251 widthNode = this.objList[i].scaleBy || this.objList[i].node; 13252 computedStyles = getComputedStyle(widthNode); 13253 width = parseInt(computedStyles["width"]) - parseInt(computedStyles["paddingLeft"]) - parseInt(computedStyles["paddingRight"]); 13254 fontSize = parseInt(getComputedStyle(this.objList[i].node)["font-size"]); 13255 13256 this.textWrapperSetStyle(this.objList[i].node); 13257 13258 if(this.textWrapperInsertText(this.objList[i].node)) 13259 { 13260 while(this.textWrapper.offsetWidth > width && fontSize > 0) 13261 { 13262 this.textWrapper.style.fontSize = --fontSize + 'px'; 13263 } 13264 13265 if(this.objList[i].smallestValue) 13266 { 13267 this.minFontSize = this.minFontSize ? Math.min(this.minFontSize, fontSize) : fontSize; 13268 13269 this.minFontSizeList.push(this.objList[i].node) 13270 } 13271 else 13272 { 13273 this.objList[i].node.style.fontSize = fontSize + 'px'; 13274 } 13275 } 13276 } 13277 13278 if(this.minFontSizeList.length > 0) 13279 this.setMinFont(); 13280 13281 this.removeTestNodes(); 13282 13283 }, 13284 increase: function() 13285 { 13286 this.insertTestNodes(); 13287 var width, 13288 fontSize, 13289 widthNode, 13290 computedStyles; 13291 13292 this.insertTestNodes(); 13293 13294 for(var i=this.objList.length-1; i>=0; i--) 13295 { 13296 widthNode = this.objList[i].scaleBy || this.objList[i].node; 13297 computedStyles = getComputedStyle(widthNode); 13298 width = parseInt(computedStyles["width"]) - parseInt(computedStyles["paddingLeft"]) - parseInt(computedStyles["paddingRight"]); 13299 fontSize = parseInt(getComputedStyle(this.objList[i].node)["font-size"]); 13300 13301 this.textWrapperSetStyle(this.objList[i].node); 13302 13303 if(this.textWrapperInsertText(this.objList[i].node)) 13304 { 13305 while(this.textWrapper.offsetWidth < width && fontSize < this.objList[i].maxFontSize) 13306 { 13307 this.textWrapper.style.fontSize = ++fontSize + 'px'; 13308 } 13309 13310 fontSize--; 13311 13312 if(this.objList[i].smallestValue) 13313 { 13314 this.minFontSize = this.minFontSize ? Math.min(this.minFontSize, fontSize) : fontSize; 13315 13316 this.minFontSizeList.push(this.objList[i].node) 13317 } 13318 else 13319 { 13320 this.objList[i].node.style.fontSize = fontSize + 'px'; 13321 } 13322 } 13323 } 13324 13325 if(this.minFontSizeList.length > 0) 13326 this.setMinFont(); 13327 13328 this.removeTestNodes(); 13329 }, 13330 setMinFont : function() 13331 { 13332 for(var i = this.minFontSizeList.length-1; i>=0; i--) 13333 { 13334 this.minFontSizeList[i].style.fontSize = this.minFontSize + 'px'; 13335 } 13336 13337 this.minFontSize = 0; 13338 }, 13339 onResize : function() 13340 { 13341 var width = window.innerWidth || document.documentElement.clientWidth; 13342 13343 if(this.prevWindowSize > width) 13344 this.decrease(); 13345 13346 else if (this.prevWindowSize < width) 13347 this.increase(); 13348 13349 this.prevWindowSize = width; 13350 }, 13351 onAdaptiveResize : function() 13352 { 13353 var widthNode = this.objList[0].scaleBy || this.objList[0].node, 13354 computedStyles = getComputedStyle(widthNode), 13355 width = parseInt(computedStyles["width"]) - parseInt(computedStyles["paddingLeft"]) - parseInt(computedStyles["paddingRight"]); 13356 13357 if (this.prevWrapperSize > width) 13358 this.decrease(); 13359 else if (this.prevWrapperSize < width) 13360 this.increase(); 13361 13362 this.prevWrapperSize = width; 13363 }, 13364 textWrapperInsertText : function(node) 13365 { 13366 if(node.textContent){ 13367 this.textWrapper.textContent = node.textContent; 13368 return true; 13369 } 13370 else if(node.innerText) 13371 { 13372 this.textWrapper.innerText = node.innerText; 13373 return true; 13374 } 13375 else { 13376 return false; 13377 } 13378 }, 13379 textWrapperSetStyle : function(node) 13380 { 13381 this.textWrapper.style.fontFamily = getComputedStyle(node)["font-family"]; 13382 this.textWrapper.style.fontSize = getComputedStyle(node)["font-size"]; 13383 this.textWrapper.style.fontStyle = getComputedStyle(node)["font-style"]; 13384 this.textWrapper.style.fontWeight = getComputedStyle(node)["font-weight"]; 13385 this.textWrapper.style.lineHeight = getComputedStyle(node)["line-height"]; 13386 } 13387 }; 13388 13389 BX.FixFontSize.init = function(params) 13390 { 13391 return new BX.FixFontSize(params); 13392 }; 13393})(); 13394 13395})(); 13396//# sourceMappingURL=core.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.