/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ "./assets/src/media/modal/mediaFrame.js":
/*!**********************************************!*\
  !*** ./assets/src/media/modal/mediaFrame.js ***!
  \**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _messageHandler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./messageHandler */ "./assets/src/media/modal/messageHandler.js");


/**
 * Extend the frame.
 */
const extendFrame = frame => frame.extend({
  /**
   * Initialize the messageHandler.
   */
  omDamMessageHandler: new _messageHandler__WEBPACK_IMPORTED_MODULE_0__["default"](),
  /**
   * Bind the handlers
  	 */
  bindHandlers: function () {
    frame.prototype.bindHandlers.apply(this, arguments);

    // When tab is opened, and template is created, render the content.
    this.on('content:render:optimole', this.renderContent, this);

    // When modal is opened, attach the listeners if they have been removed.
    this.on('open', this.reattach, this);

    // Append context for gallery is in add mode.
    this.on('toolbar:create:gallery-add', this.setAppend, this);

    // When tab is deactivated, modal closed, image selected, view is reset detach the listeners.
    this.on('content:deactivate:optimole', this.detach, this);
    this.on('reset', this.detach, this);
    this.on('select', this.detach, this);

    // Ensure the class is removed on closing.
    this.on('close', () => {
      this.toggleModalClass(false);
    }, this);

    // To debug the events above and others you can hook into the 'all' event.
    // this.on( 'all', ... );
  },

  /**
   * Add the Optimole tab to the router.
   * @param {wp.media.view.Router} routerView
   */
  browseRouter: function (routerView) {
    frame.prototype.browseRouter.apply(this, arguments);

    // Add the Optimole tab to the router.
    routerView.set({
      optimole: {
        text: 'Optimole',
        priority: 60
      }
    });
  },
  /**
   * Render the Optimole tab using a wp.media.View
   */
  renderContent: function () {
    const mediaFrame = this;
    const ViewWrapper = wp.media.View.extend({
      template: wp.template('optimole-dam'),
      className: 'om-dam-wrap',
      toolBar: null,
      render: function () {
        this.$el.html(this.template());

        // Attempt to remove the listeners if they are already attached.
        mediaFrame.omDamMessageHandler.detachListeners();

        // Send the frame to the message handler.
        mediaFrame.omDamMessageHandler.setFrame(this.$el.find('#om-dam')[0]);

        // Send the media frame to the message handler.
        mediaFrame.omDamMessageHandler.setMediaFrame(mediaFrame);

        // Send the multiple context to the message handler.
        mediaFrame.omDamMessageHandler.setMultiple(mediaFrame?.options?.multiple || false, mediaFrame.append || false);

        // Attach event listeners for postMessage events.
        mediaFrame.omDamMessageHandler.attachListeners();
        return this;
      }
    });
    this.damView = new ViewWrapper({
      controller: this,
      model: this.state()
    });

    // Add the class on body.
    this.toggleModalClass(true);

    // Set the content of the frame to the Optimole tab.
    this.content.set(this.damView);
  },
  /**
   * Detach the event handlers.
   */
  detach: function () {
    this.omDamMessageHandler.detachListeners();
    this.toggleModalClass(false);
  },
  /**
   * Reattach the event handlers.
   */
  reattach: function () {
    if (!this.omDamMessageHandler.frame) {
      return;
    }
    this.omDamMessageHandler.attachListeners();
    const {
      content
    } = this;
    if (content.mode && 'optimole' === content.mode()) {
      this.toggleModalClass(true);
    }
  },
  /**
   * Set append context - this is true when you add to a gallery.
  	 */
  setAppend: function () {
    this.append = true;
  },
  /**
   * Add a class to the body to scope style when modal is opened.
   *
   * @param {boolean} add - Whether to add or remove the class.
   */
  toggleModalClass: function (add = true) {
    if (add) {
      document.body.classList.add('om-dam-modal');
      return;
    }
    document.body.classList.remove('om-dam-modal');
  }
});
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (extendFrame);

/***/ }),

/***/ "./assets/src/media/modal/messageHandler.js":
/*!**************************************************!*\
  !*** ./assets/src/media/modal/messageHandler.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @wordpress/api-fetch */ "@wordpress/api-fetch");
/* harmony import */ var _wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_0__);

class MessageHandler {
  constructor() {
    this.siteUrl = window.location.origin;
    this.allowedType = 'om-dam';
    this.messageListener = this.handlePostMessage.bind(this);
    this.hasListeners = false;
  }

  /**
      * Setup frame.
      *
      * @param {HTMLIFrameElement} frame The iframe element.
      */
  setFrame(frame) {
    this.frame = frame;
  }

  /**
      * Set the context.
      *
      * @param {boolean} multiple Allow multiple selection.
      * @param {boolean} append Append to the selection.
      */
  setMultiple(multiple = false, append = false) {
    this.context = multiple ? 'multiple' : 'single';
    this.append = append;
  }

  /**
      * Set the media frame.
      * @param {wp.media.View} mediaFrame
      */
  setMediaFrame(mediaFrame) {
    this.mediaFrame = mediaFrame;
  }

  /**
      * Attach the listeners.
      */
  attachListeners() {
    if (this.hasListeners) {
      return;
    }
    const self = this;

    // We attach the listeners if the modal is loaded.
    if (this.frame.classList.contains('loaded')) {
      window.addEventListener('message', self.messageListener);
      this.hasListeners = true;
      return;
    }

    // Wait for the frame to load.
    this.frame.addEventListener('load', () => {
      let damLoader = document.querySelector('.om-dam-loader:not([style])');
      if (damLoader) {
        damLoader.style.display = 'none';
      }
      this.frame.style.display = '';
      this.frame.classList.add('loaded');
      window.addEventListener('message', self.messageListener);
      this.hasListeners = true;
    });
  }

  /**
      * Detach the listeners.
      */
  detachListeners() {
    if (!this.hasListeners) {
      return;
    }
    window.removeEventListener('message', this.messageListener);
    this.hasListeners = false;
  }

  /**
      * Handle the post message.
      */
  handlePostMessage(event) {
    if (!this.isValidEvent(event)) {
      return;
    }
    if ('getUrl' === event.data.action) {
      this.sendSiteUrl();
      return;
    }
    if ('importImages' === event.data.action) {
      if (1 > event.data.images.length) {
        return;
      }
      this.insertImages(event.data.images);
      this.detachListeners();
    }
  }

  /**
   * Insert the images.
   *
   * @param {array} images The images to insert.
   * @return {void}
   */
  async insertImages(images) {
    const route = window.optmlMediaModal.routes['insert_images'];
    this.sendMessage({
      status: 'importing'
    });
    const result = await _wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_0___default()({
      method: 'POST',
      path: route,
      data: {
        images
      }
    });
    if (!result.code || 'success' !== result.code) {
      this.sendMessage({
        error: 'import'
      });
      return;
    }
    if (!result.data || 1 > result.data.length) {
      this.sendMessage({
        error: 'importResponse'
      });
      return;
    }

    // Current selection.
    const selection = this.mediaFrame.state().get('selection');

    // Only reset if not in append mode.
    if (!this.append) {
      selection.reset();
    }
    let attachmentsQueue = [];
    Object.values(result.data).forEach((attachmentId, idx) => {
      // Fetch the attachment to add it to the selection.
      const attachment = wp.media.attachment(attachmentId);
      attachment.fetch().then(r => {
        attachmentsQueue.push(r);
        if (attachmentsQueue.length === result.data.length) {
          this.sendMessage({
            status: 'done'
          });

          // Add the attachments to the selection.
          selection.add(attachmentsQueue);

          // Simulate click on the select button.
          this.clickInsertButton();
        }
      });
    });
  }

  /**
   * Simulate click on the select button.
   *
   * A bit hacky, but there wasn't another way.
   *
   * @return {void}
   */
  clickInsertButton() {
    let buttons = document.querySelectorAll('.media-button-select, .media-button-insert, .media-button-gallery');

    // We need to do this in a hacky way.
    // Some modals render buttons multiple times, in different sidebars, but only one of them actually works.
    buttons.forEach(btn => {
      if (btn.disabled) {
        btn.disabled = false;
      }
      setTimeout(() => {
        this.sendMessage({
          status: 'done'
        });
        btn.click();
      }, 250);
    });
  }

  /**
      * Send the site url through postMessage.
      */
  sendSiteUrl() {
    this.sendMessage({
      siteUrl: this.siteUrl,
      context: this.context
    });
  }

  /**
      * Send a message to the iframe.
      *
      * @param data
      */
  sendMessage(data = {}) {
    this.frame.contentWindow.postMessage({
      type: 'om-dam',
      ...data
    }, '*');
  }

  /**
      * Check if the event is valid.
      *
      * @param {Event} event The event.
      * @return {boolean} True if the event is valid.
      */
  isValidEvent(event) {
    if (!event.data) {
      return false;
    }
    if (!event.data.type) {
      return false;
    }
    if (this.allowedType !== event.data.type) {
      return false;
    }
    if (!event.data.action) {
      return false;
    }
    return true;
  }
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MessageHandler);

/***/ }),

/***/ "./assets/src/media/scss/media-modal.scss":
/*!************************************************!*\
  !*** ./assets/src/media/scss/media-modal.scss ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
// extracted by mini-css-extract-plugin


/***/ }),

/***/ "@wordpress/api-fetch":
/*!**********************************!*\
  !*** external ["wp","apiFetch"] ***!
  \**********************************/
/***/ ((module) => {

module.exports = window["wp"]["apiFetch"];

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
/*!*****************************************!*\
  !*** ./assets/src/media/media-modal.js ***!
  \*****************************************/
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _modal_mediaFrame__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./modal/mediaFrame */ "./assets/src/media/modal/mediaFrame.js");
/* harmony import */ var _scss_media_modal_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./scss/media-modal.scss */ "./assets/src/media/scss/media-modal.scss");


window.addEventListener('DOMContentLoaded', () => {
  // Bail if the media frame is not available.
  if (!wp?.media?.view) {
    return;
  }

  // Extend the Select frame - used for single selection.
  wp.media.view.MediaFrame.Select = (0,_modal_mediaFrame__WEBPACK_IMPORTED_MODULE_0__["default"])(wp.media.view.MediaFrame.Select);

  // Extend the Post frame - used for multiple selection (mainly galleries).
  wp.media.view.MediaFrame.Post = (0,_modal_mediaFrame__WEBPACK_IMPORTED_MODULE_0__["default"])(wp.media.view.MediaFrame.Post);
});
})();

/******/ })()
;
//# sourceMappingURL=media-modal.js.map