[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

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

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


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