[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/media/com_media/js/ -> edit-images-es5.js (source)

   1  (function () {
   2    'use strict';
   3  
   4    function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
   5      try {
   6        var info = gen[key](arg);
   7        var value = info.value;
   8      } catch (error) {
   9        reject(error);
  10        return;
  11      }
  12  
  13      if (info.done) {
  14        resolve(value);
  15      } else {
  16        Promise.resolve(value).then(_next, _throw);
  17      }
  18    }
  19  
  20    function _asyncToGenerator(fn) {
  21      return function () {
  22        var self = this,
  23            args = arguments;
  24        return new Promise(function (resolve, reject) {
  25          var gen = fn.apply(self, args);
  26  
  27          function _next(value) {
  28            asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  29          }
  30  
  31          function _throw(err) {
  32            asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  33          }
  34  
  35          _next(undefined);
  36        });
  37      };
  38    }
  39  
  40    /**
  41     * @copyright  (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
  42     * @license    GNU General Public License version 2 or later; see LICENSE.txt
  43     */
  44    if (!Joomla) {
  45      throw new Error('Joomla API is not properly initialized');
  46    }
  47  
  48    Joomla.MediaManager = Joomla.MediaManager || {};
  49  
  50    var Edit = /*#__PURE__*/function () {
  51      function Edit() {
  52        var _this = this;
  53  
  54        // Get the options from Joomla.optionStorage
  55        this.options = Joomla.getOptions('com_media', {});
  56  
  57        if (!this.options) {
  58          throw new Error('Initialization error "edit-images.js"');
  59        }
  60  
  61        this.extension = this.options.uploadPath.split('.').pop();
  62        this.fileType = ['jpeg', 'jpg'].includes(this.extension) ? 'jpeg' : this.extension;
  63        this.options.currentUrl = new URL(window.location.href); // Initiate the registry
  64  
  65        this.original = {
  66          filename: this.options.uploadPath.split('/').pop(),
  67          extension: this.extension,
  68          contents: "data:image/" + this.fileType + ";base64," + this.options.contents
  69        }; // eslint-disable-next-line no-promise-executor-return
  70  
  71        this.previousPluginDeactivated = new Promise(function (resolve) {
  72          return resolve;
  73        });
  74        this.history = {};
  75        this.current = this.original;
  76        this.plugins = {};
  77        this.baseContainer = document.getElementById('media-manager-edit-container');
  78  
  79        if (!this.baseContainer) {
  80          throw new Error('The image preview container is missing');
  81        }
  82  
  83        this.createImageContainer(this.original);
  84        Joomla.MediaManager.Edit = this;
  85        window.dispatchEvent(new CustomEvent('media-manager-edit-init')); // Once the DOM is ready, initialize everything
  86  
  87        customElements.whenDefined('joomla-tab').then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
  88          var tabContainer, tabsUlElement, links;
  89          return regeneratorRuntime.wrap(function _callee$(_context) {
  90            while (1) {
  91              switch (_context.prev = _context.next) {
  92                case 0:
  93                  tabContainer = document.getElementById('myTab');
  94                  tabsUlElement = tabContainer.firstElementChild;
  95                  links = [].slice.call(tabsUlElement.querySelectorAll('button[aria-controls]')); // Couple the tabs with the plugin objects
  96  
  97                  links.forEach(function (link, index) {
  98                    var tab = document.getElementById(link.getAttribute('aria-controls'));
  99  
 100                    if (index === 0) {
 101                      tab.insertAdjacentElement('beforeend', _this.baseContainer);
 102                    }
 103  
 104                    link.addEventListener('joomla.tab.hidden', function (_ref2) {
 105                      var target = _ref2.target;
 106  
 107                      if (!target) {
 108                        // eslint-disable-next-line no-promise-executor-return
 109                        _this.previousPluginDeactivated = new Promise(function (resolve) {
 110                          return resolve;
 111                        });
 112                        return;
 113                      }
 114  
 115                      _this.previousPluginDeactivated = new Promise(function (resolve, reject) {
 116                        _this.plugins[target.getAttribute('aria-controls').replace('attrib-', '')].Deactivate(_this.imagePreview).then(resolve).catch(function (e) {
 117                          // eslint-disable-next-line no-console
 118                          console.log(e);
 119                          reject();
 120                        });
 121                      });
 122                    });
 123                    link.addEventListener('joomla.tab.shown', function (_ref3) {
 124                      var target = _ref3.target;
 125                      // Move the image container to the correct tab
 126                      tab.insertAdjacentElement('beforeend', _this.baseContainer);
 127  
 128                      _this.previousPluginDeactivated.then(function () {
 129                        return _this.plugins[target.getAttribute('aria-controls').replace('attrib-', '')].Activate(_this.imagePreview);
 130                      }).catch(function (e) {
 131                        // eslint-disable-next-line no-console
 132                        console.log(e);
 133                      });
 134                    });
 135                  });
 136                  tabContainer.activateTab(0, false);
 137  
 138                case 5:
 139                case "end":
 140                  return _context.stop();
 141              }
 142            }
 143          }, _callee);
 144        })));
 145        this.addHistoryPoint = this.addHistoryPoint.bind(this);
 146        this.createImageContainer = this.createImageContainer.bind(this);
 147        this.Reset = this.Reset.bind(this);
 148        this.Undo = this.Undo.bind(this);
 149        this.Redo = this.Redo.bind(this);
 150        this.createProgressBar = this.createProgressBar.bind(this);
 151        this.updateProgressBar = this.updateProgressBar.bind(this);
 152        this.removeProgressBar = this.removeProgressBar.bind(this);
 153        this.upload = this.upload.bind(this); // Create history entry
 154  
 155        window.addEventListener('mediaManager.history.point', this.addHistoryPoint.bind(this));
 156      }
 157      /**
 158       * Creates a history snapshot
 159       * PRIVATE
 160       */
 161  
 162  
 163      var _proto = Edit.prototype;
 164  
 165      _proto.addHistoryPoint = function addHistoryPoint() {
 166        if (this.original !== this.current) {
 167          var key = Object.keys(this.history).length;
 168  
 169          if (this.history[key] && this.history[key - 1] && this.history[key] === this.history[key - 1]) {
 170            return;
 171          }
 172  
 173          this.history[key + 1] = this.current;
 174        }
 175      }
 176      /**
 177       * Creates the images for edit and preview
 178       * PRIVATE
 179       */
 180      ;
 181  
 182      _proto.createImageContainer = function createImageContainer(data) {
 183        if (!data.contents) {
 184          throw new Error('Initialization error "edit-images.js"');
 185        }
 186  
 187        this.imagePreview = document.createElement('img');
 188        this.imagePreview.src = data.contents;
 189        this.imagePreview.id = 'image-preview';
 190        this.imagePreview.style.height = 'auto';
 191        this.imagePreview.style.maxWidth = '100%';
 192        this.baseContainer.appendChild(this.imagePreview);
 193      } // Reset the image to the initial state
 194      ;
 195  
 196      _proto.Reset = function Reset() {
 197        var _this2 = this;
 198  
 199        this.current.contents = "data:image/" + this.fileType + ";base64," + this.options.contents;
 200        this.imagePreview.setAttribute('src', this.current.contents);
 201        requestAnimationFrame(function () {
 202          requestAnimationFrame(function () {
 203            _this2.imagePreview.setAttribute('width', _this2.imagePreview.naturalWidth);
 204  
 205            _this2.imagePreview.setAttribute('height', _this2.imagePreview.naturalHeight);
 206          });
 207        });
 208      } // @TODO History
 209      // eslint-disable-next-line class-methods-use-this
 210      ;
 211  
 212      _proto.Undo = function Undo() {} // @TODO History
 213      // eslint-disable-next-line class-methods-use-this
 214      ;
 215  
 216      _proto.Redo = function Redo() {} // @TODO Create the progress bar
 217      // eslint-disable-next-line class-methods-use-this
 218      ;
 219  
 220      _proto.createProgressBar = function createProgressBar() {} // @TODO Update the progress bar
 221      // eslint-disable-next-line class-methods-use-this
 222      ;
 223  
 224      _proto.updateProgressBar = function updateProgressBar() {} // @TODO Remove the progress bar
 225      // eslint-disable-next-line class-methods-use-this
 226      ;
 227  
 228      _proto.removeProgressBar = function removeProgressBar() {}
 229      /**
 230       * Uploads
 231       * Public
 232       */
 233      ;
 234  
 235      _proto.upload = function upload(url, stateChangeCallback) {
 236        var _this3 = this,
 237            _JSON$stringify;
 238  
 239        var format = Joomla.MediaManager.Edit.original.extension === 'jpg' ? 'jpeg' : Joomla.MediaManager.Edit.original.extension;
 240  
 241        if (!format) {
 242          // eslint-disable-next-line prefer-destructuring
 243          format = /data:image\/(.+);/gm.exec(Joomla.MediaManager.Edit.original.contents)[1];
 244        }
 245  
 246        if (!format) {
 247          throw new Error('Unable to determine image format');
 248        }
 249  
 250        this.xhr = new XMLHttpRequest();
 251  
 252        if (typeof stateChangeCallback === 'function') {
 253          this.xhr.onreadystatechange = stateChangeCallback;
 254        }
 255  
 256        this.xhr.upload.onprogress = function (e) {
 257          _this3.updateProgressBar(e.loaded / e.total * 100);
 258        };
 259  
 260        this.xhr.onload = function () {
 261          var resp;
 262  
 263          try {
 264            resp = JSON.parse(_this3.xhr.responseText);
 265          } catch (er) {
 266            resp = null;
 267          }
 268  
 269          if (resp) {
 270            if (_this3.xhr.status === 200) {
 271              if (resp.success === true) {
 272                _this3.removeProgressBar();
 273              }
 274  
 275              if (resp.status === '1') {
 276                Joomla.renderMessages({
 277                  success: [resp.message]
 278                }, 'true');
 279  
 280                _this3.removeProgressBar();
 281              }
 282            }
 283          } else {
 284            _this3.removeProgressBar();
 285          }
 286  
 287          _this3.xhr = null;
 288        };
 289  
 290        this.xhr.onerror = function () {
 291          _this3.removeProgressBar();
 292  
 293          _this3.xhr = null;
 294        };
 295  
 296        this.xhr.open('PUT', url, true);
 297        this.xhr.setRequestHeader('Content-Type', 'application/json');
 298        this.createProgressBar();
 299        this.xhr.send(JSON.stringify((_JSON$stringify = {
 300          name: Joomla.MediaManager.Edit.options.uploadPath.split('/').pop(),
 301          content: Joomla.MediaManager.Edit.current.contents.replace("data:image/" + format + ";base64,", '')
 302        }, _JSON$stringify[Joomla.MediaManager.Edit.options.csrfToken] = 1, _JSON$stringify)));
 303      };
 304  
 305      return Edit;
 306    }(); // Initiate the Editor API
 307    // eslint-disable-next-line no-new
 308  
 309  
 310    new Edit();
 311    /**
 312     * Compute the current URL
 313     *
 314     * @param {boolean} isModal is the URL for a modal window
 315     *
 316     * @return {{}} the URL object
 317     */
 318  
 319    var getUrl = function getUrl(isModal) {
 320      var newUrl = Joomla.MediaManager.Edit.options.currentUrl;
 321      var params = new URLSearchParams(newUrl.search);
 322      params.set('view', 'media');
 323      params.delete('path');
 324      params.delete('mediatypes');
 325      var uploadPath = Joomla.MediaManager.Edit.options.uploadPath;
 326      var fileDirectory = uploadPath.split('/');
 327      fileDirectory.pop();
 328      fileDirectory = fileDirectory.join('/'); // If we are in root add a backslash
 329  
 330      if (fileDirectory.endsWith(':')) {
 331        fileDirectory = fileDirectory + "/";
 332      }
 333  
 334      params.set('path', fileDirectory); // Respect the images_only URI param
 335  
 336      var mediaTypes = document.querySelector('input[name="mediatypes"]');
 337      params.set('mediatypes', mediaTypes && mediaTypes.value ? mediaTypes.value : '0');
 338  
 339      if (isModal) {
 340        params.set('tmpl', 'component');
 341      }
 342  
 343      newUrl.search = params;
 344      return newUrl;
 345    }; // Customize the Toolbar buttons behavior
 346  
 347  
 348    Joomla.submitbutton = function (task) {
 349      var url = new URL(Joomla.MediaManager.Edit.options.apiBaseUrl + "&task=api.files&path=" + Joomla.MediaManager.Edit.options.uploadPath);
 350  
 351      switch (task) {
 352        case 'apply':
 353          Joomla.MediaManager.Edit.upload(url, null);
 354          Joomla.MediaManager.Edit.imagePreview.src = Joomla.MediaManager.Edit.current.contents;
 355          Joomla.MediaManager.Edit.original = Joomla.MediaManager.Edit.current;
 356          Joomla.MediaManager.Edit.history = {};
 357  
 358          _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
 359            var activeTab;
 360            return regeneratorRuntime.wrap(function _callee2$(_context2) {
 361              while (1) {
 362                switch (_context2.prev = _context2.next) {
 363                  case 0:
 364                    activeTab = [].slice.call(document.querySelectorAll('joomla-tab-element')).filter(function (tab) {
 365                      return tab.hasAttribute('active');
 366                    });
 367                    _context2.prev = 1;
 368                    _context2.next = 4;
 369                    return Joomla.MediaManager.Edit.plugins[activeTab[0].id.replace('attrib-', '')].Deactivate(Joomla.MediaManager.Edit.imagePreview);
 370  
 371                  case 4:
 372                    _context2.next = 6;
 373                    return Joomla.MediaManager.Edit.plugins[activeTab[0].id.replace('attrib-', '')].Activate(Joomla.MediaManager.Edit.imagePreview);
 374  
 375                  case 6:
 376                    _context2.next = 11;
 377                    break;
 378  
 379                  case 8:
 380                    _context2.prev = 8;
 381                    _context2.t0 = _context2["catch"](1);
 382                    // eslint-disable-next-line no-console
 383                    console.log(_context2.t0);
 384  
 385                  case 11:
 386                  case "end":
 387                    return _context2.stop();
 388                }
 389              }
 390            }, _callee2, null, [[1, 8]]);
 391          }))();
 392  
 393          break;
 394  
 395        case 'save':
 396          Joomla.MediaManager.Edit.upload(url, function () {
 397            if (Joomla.MediaManager.Edit.xhr.readyState === XMLHttpRequest.DONE) {
 398              if (window.self !== window.top) {
 399                window.location = getUrl(true);
 400              } else {
 401                window.location = getUrl();
 402              }
 403            }
 404          });
 405          break;
 406  
 407        case 'cancel':
 408          if (window.self !== window.top) {
 409            window.location = getUrl(true);
 410          } else {
 411            window.location = getUrl();
 412          }
 413  
 414          break;
 415  
 416        case 'reset':
 417          Joomla.MediaManager.Edit.Reset('initial');
 418          break;
 419      }
 420    };
 421  
 422  })();


Generated: Wed Sep 7 05:41:13 2022 Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer