'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index$1 = require('./index-e0385008.js');
const tslib_es6 = require('./tslib.es6-8eb3c9db.js');
const index_esm2017 = require('./index.esm2017-fdce1393.js');
const hardwareBackButton = require('./overlays-83fe75fb.js');
const index$2 = require('./index-30292d33.js');
const index = require('./index-e96b6cd6.js');
const index_min = require('./index.min-0ca13044.js');
require('./index.esm2017-9b67b332.js');
require('./global-9027a413.js');
require('./ionic-global-45d4a7f7.js');
require('./helpers-905b0d22.js');
require('./_commonjsHelpers-a5111d61.js');
require('./process-es6-39ef8921.js');

/**
 * Cleans all JavaScript referneces and prototypes from Object
 * so it can be stored in Firestore.
 * @param input The JS Object to clean
 * @param keepDocumentReferenceId Should we keep reference ids for relationships
 */
async function cleanObjectOfReferences(input, keepDocumentReferenceId = false) {
  var _a, _b, _c, _d, _e;
  const data = input;
  for (const key of Object.keys(input)) {
    const value = input[key];
    if (!value)
      continue;
    try {
      if (((_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name) === "Object") {
        data[key] = await cleanObjectOfReferences(value);
      }
      else if (((_b = value === null || value === void 0 ? void 0 : value.constructor) === null || _b === void 0 ? void 0 : _b.name) === "DocumentReference") {
        keepDocumentReferenceId
          ? (data[key] = { id: value.id })
          : delete data[key];
      }
      else if (((_c = value === null || value === void 0 ? void 0 : value.constructor) === null || _c === void 0 ? void 0 : _c.name) === "Timestamp") {
        data[key] = value.toDate();
      }
      else if (((_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name) === "Array") {
        const cleanArray = [];
        for (const item of data[key]) {
          cleanArray.push(await cleanObjectOfReferences(item));
        }
        data[key] = cleanArray;
      }
      else if (typeof value === "object" &&
        ((_e = value === null || value === void 0 ? void 0 : value.constructor) === null || _e === void 0 ? void 0 : _e.name) !== "Date") {
        data[key] = await cleanObjectOfReferences(JSON.parse(JSON.stringify(value)));
      }
    }
    catch (err) {
      delete data[key];
    }
  }
  return JSON.parse(JSON.stringify(data));
}

/**
 * Editor.JS editor output to HTML
 */
async function editorToHtml(editor, { parserConfig, customParsers, embedMarkup, } = {}) {
  const parser = new index.edjsParser(parserConfig || null, customParsers || {
    button: (data) => {
      const classes = data.align === "center"
        ? "enjin-align-center"
        : data.align === "right"
          ? "enjin-align-right"
          : "enjin-align-left";
      return `<ion-button shape="${data.shape ? data.shape : "square"}" color="${data.color ? data.color : "primary"}" class="${classes}" href="${data.href ? data.href : "#"}">${data.text}</ion-button>`;
    },
    component: (data) => {
      return `<div class="editor-component">{{> ${data.templateId}}}</div>`;
    },
    tasklist: (data) => {
      const color = (data === null || data === void 0 ? void 0 : data.color) ? data.color : "success";
      const progress = (data === null || data === void 0 ? void 0 : data.progress) ? data.progress : 0;
      const html = ["<ion-list>"];
      for (const item of (data === null || data === void 0 ? void 0 : data.items) ? data.items : []) {
        html.push(`<ion-item><ion-checkbox slot="start" color="${color}" ${item.checked ? `checked="true"` : ""}></ion-checkbox><ion-label>${item.text}</ion-label></ion-item>`);
      }
      html.push(`<ion-progress-bar color="${color}" value="${progress}"></ion-progress-bar>`, "</ion-list>");
      return html.join("");
    },
    code: (data) => data.html,
    FrameHolder: () => "{{#if @partial-block}} {{> @partial-block }} {{/if}}",
  }, embedMarkup || null);
  return parser.parse(editor);
}

/**
 * render a component to HTML string
 */
async function renderComponentToHtml(html, options = {}) {
  if (!html)
    throw Error("HTML is required");
  const renderedComponent = await index.hydrate.renderToString(html, options.hydrateOptions
    ? options.hydrateOptions
    : {
      prettyHtml: true,
      removeScripts: true,
    });
  let renderedHtml = (options === null || options === void 0 ? void 0 : options.head) && (renderedComponent === null || renderedComponent === void 0 ? void 0 : renderedComponent.html)
    ? renderedComponent.html.replace(`<meta charset="utf-8">`, `<meta charset="utf-8">
    ${(options === null || options === void 0 ? void 0 : options.head) || ""}
    `)
    : (renderedComponent === null || renderedComponent === void 0 ? void 0 : renderedComponent.html) || "";
  if (options.replace) {
    for (const key of Object.keys(options.replace)) {
      renderedHtml = renderedHtml.replace(new RegExp(key, "g"), options.replace[key]);
    }
  }
  renderedHtml = renderedHtml
    .replace(new RegExp("{{&gt;", "g"), "{{>")
    .replace(new RegExp("{{#&gt;", "g"), "{{#>");
  return options.partial && renderedHtml.includes("</body>")
    ? /<body[^>]*>((.|[\n\r])*)<\/body>/im.exec(renderedHtml)[1]
    : renderedHtml;
}

const getIfDoc = async (docOrObj) => {
  var _a;
  let output = docOrObj;
  try {
    if (typeof (docOrObj === null || docOrObj === void 0 ? void 0 : docOrObj.get) === "function") {
      const doc = await docOrObj.get();
      output = { id: doc === null || doc === void 0 ? void 0 : doc.id, ...(((_a = doc === null || doc === void 0 ? void 0 : doc.data) === null || _a === void 0 ? void 0 : _a.call(doc)) || {}) };
    }
  }
  catch (_b) {
    console.log("Error getting doc");
  }
  return output;
};
/**
 * Turn a template into compiled HTML
 */
async function templateToHtml(input) {
  var _a, _b, _c;
  const template = input === null || input === void 0 ? void 0 : input.template;
  const frame = await getIfDoc((input === null || input === void 0 ? void 0 : input.frame) || (template === null || template === void 0 ? void 0 : template.frame));
  const head = ((_a = input === null || input === void 0 ? void 0 : input.hydrate) === null || _a === void 0 ? void 0 : _a.head) || (frame === null || frame === void 0 ? void 0 : frame.head) || (template === null || template === void 0 ? void 0 : template.head) || "";
  const header = await getIfDoc((frame === null || frame === void 0 ? void 0 : frame.header) || (template === null || template === void 0 ? void 0 : template.header) || "");
  const footer = await getIfDoc((frame === null || frame === void 0 ? void 0 : frame.footer) || (template === null || template === void 0 ? void 0 : template.footer) || "");
  const body = await editorToHtml(template === null || template === void 0 ? void 0 : template.editor, {
    parserConfig: input === null || input === void 0 ? void 0 : input.parserConfig,
    customParsers: input === null || input === void 0 ? void 0 : input.customParsers,
    embedMarkup: input === null || input === void 0 ? void 0 : input.embedMarkup,
  });
  let html = [
    (!(input === null || input === void 0 ? void 0 : input.excludeHeader) && (header === null || header === void 0 ? void 0 : header.html)) || "",
    (frame === null || frame === void 0 ? void 0 : frame.id) ? `{{#> ${frame === null || frame === void 0 ? void 0 : frame.id} }}${body}{{/${frame === null || frame === void 0 ? void 0 : frame.id}}}` : body,
    (!(input === null || input === void 0 ? void 0 : input.excludeFooter) && (footer === null || footer === void 0 ? void 0 : footer.html)) || "",
  ].join("");
  try {
    if ((_b = input === null || input === void 0 ? void 0 : input.handlebars) === null || _b === void 0 ? void 0 : _b.compile)
      html = input.handlebars.compile(html)((input === null || input === void 0 ? void 0 : input.data) || (template === null || template === void 0 ? void 0 : template.sampleData) || {});
  }
  catch (e) {
    console.log("Error rendering handlebars: ", e);
  }
  try {
    if (input === null || input === void 0 ? void 0 : input.mjml)
      html = (_c = index.mjml2html(html, (typeof (input === null || input === void 0 ? void 0 : input.mjml) === "object" && input.mjml) || {})) === null || _c === void 0 ? void 0 : _c.html;
  }
  catch (e) {
    console.log("Error rendering MJML", e);
  }
  try {
    if (!(input === null || input === void 0 ? void 0 : input.disableRender))
      html = await renderComponentToHtml(html, {
        ...((input === null || input === void 0 ? void 0 : input.hydrate) || {}),
        head,
      });
  }
  catch (e) {
    console.log("Error rendering components", e);
  }
  return html;
}

class FrameHolder {
  setCaretAtEnd(node) {
    const sel = document.getSelection();
    node = node.firstChild;
    if (sel.rangeCount) {
      ["Start", "End"].forEach((pos) => sel.getRangeAt(0)["set" + pos](node, node.length));
    }
  }
  renderSettings() {
    this.settingsEl = document.createElement("div");
    for (const setting of this.settings) {
      let button = document.createElement("div");
      button.classList.add("cdx-settings-button", `cdx-settings-button-${setting.name}`);
      button.innerHTML =
        typeof (setting === null || setting === void 0 ? void 0 : setting.innerHTML) === "function"
          ? setting.innerHTML()
          : setting.innerHTML;
      if (typeof (setting === null || setting === void 0 ? void 0 : setting.onClick) === "function") {
        button.addEventListener("click", setting.onClick);
      }
      this.settingsEl.appendChild(button);
    }
    return this.settingsEl;
  }
  /**
   * Notify core that read-only mode is supported
   *
   * @returns {boolean}
   */
  static get isReadOnlySupported() {
    return true;
  }
  /**
   * Should this tool be displayed at the Editor's Toolbox
   *
   * @returns {boolean}
   * @public
   */
  static get displayInToolbox() {
    return true;
  }
  /**
   * Allow to press Enter inside the RawTool textarea
   *
   * @returns {boolean}
   * @public
   */
  static get enableLineBreaks() {
    return true;
  }
  /**
   * Get Tool toolbox settings
   * icon - Tool icon's SVG
   * title - title to show in toolbox
   *
   * @returns {{icon: string, title: string}}
   */
  static get toolbox() {
    return {
      icon: '<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"><title>Scan</title><path d="M342 444h46a56 56 0 0056-56v-46M444 170v-46a56 56 0 00-56-56h-46M170 444h-46a56 56 0 01-56-56v-46M68 170v-46a56 56 0 0156-56h46" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="44"/></svg>',
      title: "Frame Holder",
    };
  }
  /**
   * @typedef {object} RawData — plugin saved data
   * @param {string} html - previously saved HTML code
   * @property
   */
  /**
   * Render plugin`s main Element and fill it with saved data
   *
   * @param {RawData} data — previously saved HTML data
   * @param {object} config - user config for Tool
   * @param {object} api - CodeX Editor API
   * @param {boolean} readOnly - read-only mode flag
   */
  constructor({ api, readOnly, block }) {
    this.settings = [];
    this.api = api;
    this.readOnly = readOnly;
    this.block = block;
    this.data = {};
    this.codeEditorEl = null;
  }
  /**
   * Return Tool's view
   *
   * @returns {HTMLDivElement} this.element - RawTool's wrapper
   * @public
   */
  render() {
    const wrapper = document.createElement("div");
    wrapper.style.padding = "15px";
    wrapper.style.borderRadius = "10px";
    wrapper.style.border = "2px dashed var(--ion-color-medium, #cccccc)";
    wrapper.style.color = "var(--ion-color-medium, #cccccc)";
    wrapper.style.fontStyle = "italic";
    wrapper.textContent = "Frame Holder";
    return wrapper;
  }
  /**
   * Extract Tool's data from the view
   *
   * @param {HTMLDivElement} rawToolsWrapper - RawTool's wrapper, containing textarea with raw HTML code
   * @returns {RawData} - raw HTML code
   * @public
   */
  save(_rawToolsWrapper) {
    return {};
  }
  /**
   * Default placeholder for RawTool's textarea
   *
   * @public
   * @returns {string}
   */
  static get DEFAULT_PLACEHOLDER() {
    return "Frame Holder";
  }
  /**
   * Automatic sanitize config
   */
  static get sanitize() {
    return {};
  }
}

const editorCss = "fireenjin-mx-editor,fireenjin-mx-editor fireenjin-editor{display:block;opacity:1;transition:all ease 0.4s;position:relative;width:100%;height:100%}fireenjin-mx-editor.is-previewing fireenjin-editor{opacity:0;pointer-events:none}fireenjin-mx-editor #preview{transition:all ease 0.4;opacity:0;position:absolute !important;top:0;left:0;right:0;display:block;width:100%;height:100%;pointer-events:none;border:1px solid #CCCCCC}fireenjin-mx-editor.is-previewing #preview{opacity:1;pointer-events:all}";

const AppTemplateForm = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
    this.fireenjinTrigger = index$1.createEvent(this, "fireenjinTrigger", 7);
    this.fireenjinFetch = index$1.createEvent(this, "fireenjinFetch", 7);
    this.fireenjinSubmit = index$1.createEvent(this, "fireenjinSubmit", 7);
    this.templateChange = index$1.createEvent(this, "templateChange", 7);
    this.app = undefined;
    this.fonts = undefined;
    this.enableClicks = false;
    this.url = undefined;
    this.name = "editor";
    this.zoom = 1;
    this.colors = undefined;
    this.parserConfig = undefined;
    this.customParsers = undefined;
    this.customEmailParsers = undefined;
    this.resize = false;
    this.allowFullscreen = false;
    this.disableFrame = false;
    this.toastPosition = "top";
    this.templateId = undefined;
    this.isPreviewing = false;
    this.template = undefined;
    this.templates = undefined;
    this.partials = undefined;
    this.frames = undefined;
    this.sizes = [50, 50];
    this.fetch = false;
    this.endpoint = undefined;
    this.controls = [];
    this.controlsHeader = undefined;
    this.templateData = undefined;
    this.mailFrom = undefined;
    this.mailReplyTo = undefined;
    this.types = undefined;
    this.tools = {};
    this.tags = [];
    this.helpers = {
      formatUSD: (amount) => {
        const formatter = new Intl.NumberFormat("en-US", {
          style: "currency",
          currency: "USD",
          minimumFractionDigits: 2,
        });
        return formatter.format(amount ? amount : 0);
      },
    };
    this.hooks = {};
    this.uploadCallback = undefined;
    this.uploadPath = "uploads/";
    this.previewTemplate = undefined;
    this.currentPartials = [];
    this.currentHelpers = [];
  }
  onKeydown(event) {
    let charCode = String.fromCharCode(event.which).toLowerCase();
    if ((event.ctrlKey || event.metaKey) && charCode === "s") {
      this.save();
    }
  }
  async onCodeChange(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    if (((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.name) === "head") {
      this.template.head = ((_b = event === null || event === void 0 ? void 0 : event.target) === null || _b === void 0 ? void 0 : _b.value) || "";
    }
    else if (((_c = event === null || event === void 0 ? void 0 : event.target) === null || _c === void 0 ? void 0 : _c.name) === "sampleData") {
      this.template.sampleData =
        (typeof ((_d = event === null || event === void 0 ? void 0 : event.target) === null || _d === void 0 ? void 0 : _d.value) === "string" &&
          JSON.stringify((_e = event === null || event === void 0 ? void 0 : event.target) === null || _e === void 0 ? void 0 : _e.value)) ||
          ((_f = event === null || event === void 0 ? void 0 : event.target) === null || _f === void 0 ? void 0 : _f.value) ||
          {};
    }
    else if (((_g = event === null || event === void 0 ? void 0 : event.target) === null || _g === void 0 ? void 0 : _g.name) === "routes") {
      this.template.routes =
        (typeof ((_h = event === null || event === void 0 ? void 0 : event.target) === null || _h === void 0 ? void 0 : _h.value) === "string" &&
          JSON.stringify((_j = event === null || event === void 0 ? void 0 : event.target) === null || _j === void 0 ? void 0 : _j.value)) ||
          ((_k = event === null || event === void 0 ? void 0 : event.target) === null || _k === void 0 ? void 0 : _k.value) ||
          {};
    }
    await this.generatePreview();
  }
  async onEditorChange() {
    const template = {
      ...(this.template || {}),
      editor: await this.editorJs.save(),
    };
    this.template = template;
    await this.generatePreview();
    this.templateChange.emit({ template });
  }
  async onChange(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    if (((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.name) === "frameId") {
      this.template = {
        ...this.template,
        frame: (this.partials || []).find((partial) => { var _a; return (partial === null || partial === void 0 ? void 0 : partial.id) === ((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.value); }) || null,
      };
    }
    else if (((_b = event === null || event === void 0 ? void 0 : event.target) === null || _b === void 0 ? void 0 : _b.name) === "headerId") {
      this.template = {
        ...this.template,
        header: (this.partials || []).find((partial) => { var _a; return (partial === null || partial === void 0 ? void 0 : partial.id) === ((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.value); }),
      };
    }
    else if (((_c = event === null || event === void 0 ? void 0 : event.target) === null || _c === void 0 ? void 0 : _c.name) === "footerId") {
      this.template = {
        ...this.template,
        footer: (this.partials || []).find((partial) => { var _a; return (partial === null || partial === void 0 ? void 0 : partial.id) === ((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.value); }),
      };
    }
    else if ([
      "type",
      "subject",
      "tags",
      "name",
      "text",
      "amp",
      "description",
    ].includes((_d = event === null || event === void 0 ? void 0 : event.target) === null || _d === void 0 ? void 0 : _d.name)) {
      this.template[(_e = event === null || event === void 0 ? void 0 : event.target) === null || _e === void 0 ? void 0 : _e.name] = (_f = event === null || event === void 0 ? void 0 : event.target) === null || _f === void 0 ? void 0 : _f.value;
    }
    else {
      this.template = {
        ...this.template,
        [(_g = event === null || event === void 0 ? void 0 : event.target) === null || _g === void 0 ? void 0 : _g.name]: (_h = event === null || event === void 0 ? void 0 : event.target) === null || _h === void 0 ? void 0 : _h.value,
      };
      const listEl = event.target.closest("ion-card ion-list");
      if (listEl) {
        this.setProgress(listEl);
      }
    }
    this.templateChange.emit({ template: this.template });
    await this.generatePreview();
  }
  async onSuccess(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
    const fetchEndpoint = (typeof this.fetch === "string" && this.fetch) ||
      this.endpoint ||
      "findTemplate";
    const addEndpoint = this.endpoint || "addTemplate";
    const editEndpoint = this.endpoint || "editTemplate";
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint) === fetchEndpoint) {
      const sampleDataInput = ((_d = (_c = (_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.template) === null || _d === void 0 ? void 0 : _d.sampleData) ||
        this.templateData ||
        ((_e = this.template) === null || _e === void 0 ? void 0 : _e.sampleData) ||
        {};
      const sampleData = typeof sampleDataInput === "string"
        ? JSON.parse(sampleDataInput)
        : sampleDataInput;
      const template = { ...(((_g = (_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.template) || {}), sampleData };
      this.template = template;
      this.templateChange.emit({ template });
      this.afterTemplateUpdate();
    }
    else if ([addEndpoint, editEndpoint].includes((_h = event === null || event === void 0 ? void 0 : event.detail) === null || _h === void 0 ? void 0 : _h.endpoint)) {
      await this.presentToast();
      if (this.fetch)
        this.fetchData();
      if ((_j = this.modalEl) === null || _j === void 0 ? void 0 : _j.dismiss)
        this.modalEl.dismiss();
    }
    else if (((_k = event === null || event === void 0 ? void 0 : event.detail) === null || _k === void 0 ? void 0 : _k.endpoint) === "generatePdf") {
      if ((window === null || window === void 0 ? void 0 : window.open) &&
        ((_o = (_m = (_l = event.detail) === null || _l === void 0 ? void 0 : _l.data) === null || _m === void 0 ? void 0 : _m.generatePdf) === null || _o === void 0 ? void 0 : _o.url)) {
        window.open((_r = (_q = (_p = event.detail) === null || _p === void 0 ? void 0 : _p.data) === null || _q === void 0 ? void 0 : _q.generatePdf) === null || _r === void 0 ? void 0 : _r.url, "_blank").focus();
      }
    }
  }
  async onTrigger(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.name) === "save") {
      this.save();
    }
    else if (((_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.name) === "export") {
      await this.exportHTML();
      await this.generatePdf();
    }
    else if (((_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.name) === "send") {
      this.openSendEmailModal((_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.payload);
    }
    else if (((_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.name) === "preview") {
      this.togglePreview(!!this.isPreviewing);
    }
    else if (((_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.name) === "more") {
      this.openTemplateInfoModal();
    }
    else if (((_g = event === null || event === void 0 ? void 0 : event.detail) === null || _g === void 0 ? void 0 : _g.name) === "closeModal" && ((_h = this.modalEl) === null || _h === void 0 ? void 0 : _h.dismiss)) {
      (_l = (_j = document === null || document === void 0 ? void 0 : document.querySelectorAll) === null || _j === void 0 ? void 0 : (_k = _j.call(document, "ion-modal")).forEach) === null || _l === void 0 ? void 0 : _l.call(_k, (modalEl) => { var _a; return (_a = modalEl === null || modalEl === void 0 ? void 0 : modalEl.dismiss) === null || _a === void 0 ? void 0 : _a.call(modalEl); });
    }
    else if (((_m = event === null || event === void 0 ? void 0 : event.detail) === null || _m === void 0 ? void 0 : _m.name) === "sampleData") {
      this.openSampleDataModal();
    }
    else if (((_o = event === null || event === void 0 ? void 0 : event.detail) === null || _o === void 0 ? void 0 : _o.name) === "code") {
      this.openCodeModal();
    }
    else if (((_p = event === null || event === void 0 ? void 0 : event.detail) === null || _p === void 0 ? void 0 : _p.name) === "layout") {
      this.openLayoutModal();
    }
    else if (((_q = event === null || event === void 0 ? void 0 : event.detail) === null || _q === void 0 ? void 0 : _q.name) === "routes") {
      this.openRoutesModal();
    }
    else if (((_r = event === null || event === void 0 ? void 0 : event.detail) === null || _r === void 0 ? void 0 : _r.name) === "head") {
      this.openHeadModal();
    }
  }
  async togglePreview(show) {
    this.generatePreview();
    this.isPreviewing = show !== null && show !== void 0 ? show : !this.isPreviewing;
  }
  async save(customInput) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
    const addEndpoint = (typeof this.endpoint === "string" && this.endpoint) || "addTemplate";
    const editEndpoint = (typeof this.endpoint === "string" && this.endpoint) || "editTemplate";
    const sampleDataInput = (customInput === null || customInput === void 0 ? void 0 : customInput.sampleData) || ((_a = this.template) === null || _a === void 0 ? void 0 : _a.sampleData) || null;
    const sampleData = typeof sampleDataInput === "string"
      ? JSON.parse(sampleDataInput)
      : sampleDataInput;
    const data = await cleanObjectOfReferences({
      editor: (await ((_c = (_b = this.editorJs) === null || _b === void 0 ? void 0 : _b.save) === null || _c === void 0 ? void 0 : _c.call(_b))) || {
        time: new Date().getTime(),
        blocks: [],
        version: "2.8.1",
      },
      amp: (customInput === null || customInput === void 0 ? void 0 : customInput.amp) || ((_d = this.template) === null || _d === void 0 ? void 0 : _d.amp) || null,
      attachments: (customInput === null || customInput === void 0 ? void 0 : customInput.attachments) || ((_e = this.template) === null || _e === void 0 ? void 0 : _e.attachments) || [],
      description: (customInput === null || customInput === void 0 ? void 0 : customInput.description) || ((_f = this.template) === null || _f === void 0 ? void 0 : _f.description) || null,
      footerId: (customInput === null || customInput === void 0 ? void 0 : customInput.footerId) || ((_h = (_g = this.template) === null || _g === void 0 ? void 0 : _g.footer) === null || _h === void 0 ? void 0 : _h.id) || null,
      headerId: (customInput === null || customInput === void 0 ? void 0 : customInput.headerId) || ((_k = (_j = this.template) === null || _j === void 0 ? void 0 : _j.header) === null || _k === void 0 ? void 0 : _k.id) || null,
      head: (customInput === null || customInput === void 0 ? void 0 : customInput.head) || ((_l = this.template) === null || _l === void 0 ? void 0 : _l.head) || null,
      frameId: (customInput === null || customInput === void 0 ? void 0 : customInput.frameId) || ((_o = (_m = this.template) === null || _m === void 0 ? void 0 : _m.frame) === null || _o === void 0 ? void 0 : _o.id) || null,
      name: (customInput === null || customInput === void 0 ? void 0 : customInput.name) || ((_p = this.template) === null || _p === void 0 ? void 0 : _p.name) || null,
      routes: (customInput === null || customInput === void 0 ? void 0 : customInput.routes) || ((_q = this.template) === null || _q === void 0 ? void 0 : _q.routes) || null,
      sampleData,
      subject: (customInput === null || customInput === void 0 ? void 0 : customInput.subject) || ((_r = this.template) === null || _r === void 0 ? void 0 : _r.subject) || null,
      tags: (customInput === null || customInput === void 0 ? void 0 : customInput.tags) || ((_s = this.template) === null || _s === void 0 ? void 0 : _s.tags) || [],
      text: (customInput === null || customInput === void 0 ? void 0 : customInput.text) || ((_t = this.template) === null || _t === void 0 ? void 0 : _t.text) || null,
      type: (customInput === null || customInput === void 0 ? void 0 : customInput.type) || ((_u = this.template) === null || _u === void 0 ? void 0 : _u.type) || null,
    });
    if ((_v = this.template) === null || _v === void 0 ? void 0 : _v.partial)
      data.partial =
        (_y = (_w = customInput === null || customInput === void 0 ? void 0 : customInput.partial) !== null && _w !== void 0 ? _w : (_x = this.template) === null || _x === void 0 ? void 0 : _x.partial) !== null && _y !== void 0 ? _y : ((_z = this.template) === null || _z === void 0 ? void 0 : _z.partial) === "on";
    if (!this.templateId) {
      this.fireenjinSubmit.emit({
        endpoint: addEndpoint,
        name: this.name,
        params: {
          data,
        },
      });
    }
    else {
      this.fireenjinSubmit.emit({
        endpoint: editEndpoint,
        name: this.name,
        id: this.templateId || ((_0 = this.template) === null || _0 === void 0 ? void 0 : _0.id),
        data,
      });
    }
    return data;
  }
  async openTemplateInfoModal() {
    var _a;
    this.modalEl = await hardwareBackButton.modalController.create({
      component: "fireenjin-mx-modal-template-settings",
      cssClass: "fireenjin-mx-modal-template-settings-wrapper",
      componentProps: {
        tags: this.tags || [],
        types: this.types,
        template: this.template,
        templateId: this.templateId || ((_a = this.template) === null || _a === void 0 ? void 0 : _a.id),
        helpers: this.helpers || null,
        partials: this.partials || null,
        frames: this.frames || null,
      },
    });
    await this.modalEl.present();
    return this.modalEl;
  }
  async openSendEmailModal(input) {
    var _a, _b, _c;
    this.modalEl = await hardwareBackButton.modalController.create({
      component: "fireenjin-mx-modal-send-email",
      cssClass: "fireenjin-mx-modal-send-email-wrapper",
      componentProps: {
        to: (input === null || input === void 0 ? void 0 : input.to) || [],
        text: input === null || input === void 0 ? void 0 : input.text,
        html: (input === null || input === void 0 ? void 0 : input.html) || (await this.exportHTML()),
        templateId: (input === null || input === void 0 ? void 0 : input.templateId) || this.templateId || ((_a = this.template) === null || _a === void 0 ? void 0 : _a.id),
        template: (input === null || input === void 0 ? void 0 : input.template) || this.template,
        hideTemplateSelect: (_b = input === null || input === void 0 ? void 0 : input.hideTemplateSelect) !== null && _b !== void 0 ? _b : true,
        subject: (input === null || input === void 0 ? void 0 : input.subject) || ((_c = this.template) === null || _c === void 0 ? void 0 : _c.subject) || null,
        from: (input === null || input === void 0 ? void 0 : input.from) || this.mailFrom || null,
        replyTo: (input === null || input === void 0 ? void 0 : input.replyTo) || this.mailReplyTo || null,
        helpers: this.helpers || null,
        partials: this.partials || null,
        frames: this.frames || null,
        templates: (input === null || input === void 0 ? void 0 : input.templates) || this.templates || null,
      },
    });
    await this.modalEl.present();
    return this.modalEl;
  }
  async openRoutesModal() {
    var _a;
    const addEndpoint = (typeof this.endpoint === "string" && this.endpoint) || "addTemplate";
    const editEndpoint = (typeof this.endpoint === "string" && this.endpoint) || "editTemplate";
    this.modalEl = await hardwareBackButton.modalController.create({
      component: "fireenjin-mx-modal-code-editor",
      cssClass: "fireenjin-mx-modal-code-editor-wrapper",
      componentProps: {
        pageTitle: "Routes",
        name: "routes",
        language: "json",
        value: JSON.stringify(((_a = this.template) === null || _a === void 0 ? void 0 : _a.routes) || {}),
        endpoint: this.templateId ? editEndpoint : addEndpoint,
        documentId: this.templateId,
      },
    });
    await this.modalEl.present();
    return this.modalEl;
  }
  async openLayoutModal() {
    var _a;
    const componentProps = {
      tags: this.tags || [],
      types: this.types,
      template: this.template,
      templates: this.templates || null,
      templateId: this.templateId || ((_a = this.template) === null || _a === void 0 ? void 0 : _a.id),
      helpers: this.helpers || null,
      partials: this.partials || null,
      frames: this.frames || null,
    };
    this.modalEl = await hardwareBackButton.modalController.create({
      component: "fireenjin-mx-modal-layout",
      cssClass: "fireenjin-mx-modal-layout-wrapper",
      componentProps,
    });
    await this.modalEl.present();
    return this.modalEl;
  }
  async openCodeModal() {
    this.modalEl = await hardwareBackButton.modalController.create({
      component: "fireenjin-mx-modal-code-editor",
      cssClass: "fireenjin-mx-modal-code-editor-wrapper",
      componentProps: {
        name: "code",
        pageTitle: "Code",
        language: "html",
        value: await this.exportHTML(),
      },
    });
    await this.modalEl.present();
    return this.modalEl;
  }
  async openHeadModal() {
    var _a;
    const addEndpoint = (typeof this.endpoint === "string" && this.endpoint) || "addTemplate";
    const editEndpoint = (typeof this.endpoint === "string" && this.endpoint) || "editTemplate";
    this.modalEl = await hardwareBackButton.modalController.create({
      component: "fireenjin-mx-modal-code-editor",
      cssClass: "fireenjin-mx-modal-code-editor-wrapper",
      componentProps: {
        pageTitle: "Edit Head",
        name: "head",
        language: "html",
        value: ((_a = this.template) === null || _a === void 0 ? void 0 : _a.head) || "",
        endpoint: this.templateId ? editEndpoint : addEndpoint,
        documentId: this.templateId,
      },
    });
    await this.modalEl.present();
    return this.modalEl;
  }
  async openSampleDataModal() {
    var _a;
    const addEndpoint = (typeof this.endpoint === "string" && this.endpoint) || "addTemplate";
    const editEndpoint = (typeof this.endpoint === "string" && this.endpoint) || "editTemplate";
    const sampleData = this.templateData || ((_a = this.template) === null || _a === void 0 ? void 0 : _a.sampleData) || {};
    this.modalEl = await hardwareBackButton.modalController.create({
      component: "fireenjin-mx-modal-code-editor",
      cssClass: "fireenjin-mx-modal-code-editor-wrapper",
      componentProps: {
        name: "sampleData",
        language: "json",
        value: typeof sampleData === "string"
          ? sampleData
          : JSON.stringify(sampleData, null, 4),
        endpoint: this.templateId ? editEndpoint : addEndpoint,
        documentId: this.templateId,
      },
    });
    await this.modalEl.present();
    return this.modalEl;
  }
  async generatePdf() {
    var _a;
    this.fireenjinSubmit.emit({
      endpoint: "generatePdf",
      params: {
        data: {
          templateId: this.templateId,
          payload: this.templateData || ((_a = this.template) === null || _a === void 0 ? void 0 : _a.sampleData) || {},
        },
      },
    });
  }
  async openControls() {
    this.actionEl = await hardwareBackButton.actionSheetController.create({
      header: this.controlsHeader,
      buttons: [
        {
          text: "Toggle Preview",
          icon: this.isPreviewing ? "eye-off" : "eye",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "preview",
              payload: {
                isPreviewing: !this.isPreviewing,
              },
            });
          },
        },
        {
          text: "Save",
          icon: "save",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "save",
            });
          },
        },
        {
          text: "Edit Info",
          icon: "create",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "more",
            });
          },
        },
        {
          text: "Edit Layout",
          icon: "layers",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "layout",
            });
          },
        },
        {
          text: "Edit Sample Data",
          icon: "document-text",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "sampleData",
            });
          },
        },
        {
          text: "Edit Head",
          icon: "search-circle",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "editHead",
            });
          },
        },
        {
          text: "Edit Routes",
          icon: "globe",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "routes",
            });
          },
        },
        {
          text: "View Code",
          icon: "code-slash",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "code",
            });
          },
        },
        {
          text: "Send as Email",
          icon: "mail",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "send",
            });
          },
        },
        {
          text: "Export",
          icon: "exit",
          handler: () => {
            this.fireenjinTrigger.emit({
              name: "export",
            });
          },
        },
        ...this.controls,
      ],
    });
    await this.actionEl.present();
    return this.actionEl;
  }
  async fetchData(input) {
    const id = (input === null || input === void 0 ? void 0 : input.templateId) || this.templateId;
    if (!id)
      return;
    this.fireenjinFetch.emit({
      endpoint: (typeof this.fetch === "string" && this.fetch) ||
        (typeof this.endpoint === "string" && this.endpoint) ||
        "findTemplate",
      name: this.name,
      params: {
        id,
      },
    });
  }
  async unsetPartials() {
    for (const partialName of this.currentPartials) {
      index$2.lib.unregisterPartial(partialName);
    }
    this.currentPartials = [];
    this.partials = [];
  }
  async setTemplates(templates) {
    var _a, _b;
    this.templates = templates || this.templates || null;
    if (!((_a = this.templates) === null || _a === void 0 ? void 0 : _a.length))
      return;
    try {
      this.partials = this.templates.filter((template) => (template === null || template === void 0 ? void 0 : template.partial) || ["frame", "component"].includes(template === null || template === void 0 ? void 0 : template.type));
      if ((_b = this.partials) === null || _b === void 0 ? void 0 : _b.length)
        this.setPartials();
      this.frames = this.templates.filter((template) => (template === null || template === void 0 ? void 0 : template.type) === "frame");
    }
    catch (_c) {
      console.log("Error setting templates.");
    }
  }
  async setPartials(partials) {
    try {
      index$2.lib.registerPartial(null, "");
    }
    catch (_a) {
      // Make sure handlebars doesn't error when null as partial name
    }
    try {
      if ((partials === null || partials === void 0 ? void 0 : partials.length) && this.partials !== partials) {
        this.partials = partials;
      }
      for (const partial of this.partials) {
        try {
          if (this.currentPartials.includes(partial === null || partial === void 0 ? void 0 : partial.id))
            index$2.lib.unregisterPartial(partial === null || partial === void 0 ? void 0 : partial.id);
          index$2.lib.registerPartial(partial === null || partial === void 0 ? void 0 : partial.id, (partial === null || partial === void 0 ? void 0 : partial.html) || "");
          if (!this.currentPartials.includes(partial === null || partial === void 0 ? void 0 : partial.id))
            this.currentPartials = [...this.currentPartials, partial === null || partial === void 0 ? void 0 : partial.id];
        }
        catch (_b) {
          console.log(`Error setting partial ${partial === null || partial === void 0 ? void 0 : partial.id}.`);
        }
      }
    }
    catch (_c) {
      console.log("Error setting partials.");
    }
  }
  async setHelpers(helpers) {
    try {
      if ((helpers === null || helpers === void 0 ? void 0 : helpers.length) && this.helpers !== helpers) {
        this.helpers = helpers;
      }
      for (const [helperName, helperFn] of Object.entries(this.helpers)) {
        try {
          if (this.currentHelpers.includes(helperName))
            index$2.lib.unregisterHelper(helperName);
          index$2.lib.registerHelper(helperName, helperFn);
          if (!this.currentHelpers.includes(helperName))
            this.currentHelpers = [...this.currentHelpers, helperName];
        }
        catch (_a) {
          console.log(`Error setting helper ${helperName}.`);
        }
      }
    }
    catch (_b) {
      console.log("Error setting helpers.");
    }
  }
  sanitizeHtml(html) {
    let markup = html;
    markup = markup.replace(/&/g, "&amp;");
    markup = markup.replace(/</g, "&lt;");
    markup = markup.replace(/>/g, "&gt;");
    return markup;
  }
  async getIfDoc(docOrObj) {
    var _a;
    let output = docOrObj;
    try {
      if (docOrObj === null || docOrObj === void 0 ? void 0 : docOrObj.get) {
        const doc = await docOrObj.get();
        output = { id: doc === null || doc === void 0 ? void 0 : doc.id, ...(((_a = doc === null || doc === void 0 ? void 0 : doc.data) === null || _a === void 0 ? void 0 : _a.call(doc)) || {}) };
      }
    }
    catch (_b) {
      console.log("Error getting doc");
    }
    return output;
  }
  async exportHTML({ data, excludeFrame, mjml, disableRender, disableHandlebarsCompile, excludeFooter, excludeHeader, url, } = {}) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    let html = "";
    try {
      if (excludeFrame) {
        html = await this.editorEl.exportHTML();
      }
      else {
        this.template.editor = await this.editorEl.exportJSON();
        html = await templateToHtml({
          mjml: mjml ||
            (((_a = this.template) === null || _a === void 0 ? void 0 : _a.type) === "email" && {
              fonts: this.fonts,
            }),
          excludeFooter: excludeFooter !== null && excludeFooter !== void 0 ? excludeFooter : (((_b = this.template) === null || _b === void 0 ? void 0 : _b.partial) || ((_c = this.template) === null || _c === void 0 ? void 0 : _c.type) === "component"),
          excludeHeader: excludeHeader !== null && excludeHeader !== void 0 ? excludeHeader : (((_d = this.template) === null || _d === void 0 ? void 0 : _d.partial) || ((_e = this.template) === null || _e === void 0 ? void 0 : _e.type) === "component"),
          data: data || this.templateData || ((_f = this.template) === null || _f === void 0 ? void 0 : _f.sampleData),
          handlebars: !(disableHandlebarsCompile !== null && disableHandlebarsCompile !== void 0 ? disableHandlebarsCompile : (((_g = this.template) === null || _g === void 0 ? void 0 : _g.partial) ||
            ["component", "frame"].includes((_h = this.template) === null || _h === void 0 ? void 0 : _h.type))) &&
            (index$2.lib === null || index$2.lib === void 0 ? void 0 : index$2.lib.compile) &&
            index$2.lib,
          parserConfig: this.parserConfig,
          customParsers: this.customParsers ||
            (((_j = this.template) === null || _j === void 0 ? void 0 : _j.type) === "email" && {
              header: (data) => `<mj-text><h${data.level}>${data.text}</h${data.level}></mj-text>`,
              list: (data) => {
                const type = data.style === "ordered" ? "ol" : "ul";
                const items = data.items.reduce((acc, item) => acc + `<li>${item}</li>`, "");
                return `<mj-text><${type}>${items}</${type}></mj-text>`;
              },
              raw: (data) => `<mj-raw>${data.html}</mj-raw>`,
              quote: (data) => `<mj-text align="${(data === null || data === void 0 ? void 0 : data.alignment) || "left"}"><blockquote style="text-align: ${(data === null || data === void 0 ? void 0 : data.alignment) || "left"}"><p>${data.text}</p><cite>${data.caption}</cite></blockquote></mj-text>`,
              image: (data, config) => {
                var _a;
                const imageConditions = `${data.stretched ? "img-fullwidth" : ""} ${data.withBorder ? "img-border" : ""} ${data.withBackground ? "img-bg" : ""}`;
                const imgClass = config.image.imgClass || "";
                let imageSrc;
                if (data.url) {
                  // simple-image was used and the image probably is not uploaded to this server
                  // therefore, we use the absolute path provided in data.url
                  // so, config.image.path property is useless in this case!
                  imageSrc = data.url;
                }
                else if (config.image.path === "absolute") {
                  imageSrc = data.file.url;
                }
                else {
                  imageSrc = config.image.path.replace(/<(.+)>/, (_match, p1) => data.file[p1]);
                }
                if ((data === null || data === void 0 ? void 0 : data.stretched) && config.image.use === "figure") {
                  const figCapClass = config.image.figCapClass || "";
                  return `<mj-hero mode="fluid-height"  padding="100px 0px" background-url="${imageSrc}"><mj-text padding="20px" color="${((_a = config === null || config === void 0 ? void 0 : config.img) === null || _a === void 0 ? void 0 : _a.figColor) || "#ffffff"}" font-family="Helvetica" align="center" font-size="45px" line-height="45px" font-weight="900" css-class="${figCapClass}">${(data === null || data === void 0 ? void 0 : data.caption) || ""}</mj-text></mj-hero>`;
                }
                else {
                  return `<mj-image css-class="${imageConditions} ${imgClass}" src="${imageSrc}" alt="${(data === null || data === void 0 ? void 0 : data.caption) || ""}" fluid-on-mobile="${(data === null || data === void 0 ? void 0 : data.stretched) ? "true" : "false"}" />`;
                }
              },
              paragraph: (data) => {
                var _a;
                return `<mj-text color="${((data === null || data === void 0 ? void 0 : data.color) && ((_a = this.colors) === null || _a === void 0 ? void 0 : _a[data === null || data === void 0 ? void 0 : data.color])) || "#000000"}" align="${(data === null || data === void 0 ? void 0 : data.alignment) || "left"}">${(data === null || data === void 0 ? void 0 : data.text) || ""}</mj-text>`;
              },
              table: (data) => {
                const rows = data.content.map((row) => {
                  return `<tr>${row.reduce((acc, cell) => acc + `<td>${cell}</td>`, "")}</tr>`;
                });
                return `<mj-table>${rows.join("")}</mj-table>`;
              },
              button: (data) => {
                var _a, _b;
                const color = (_a = this.colors) === null || _a === void 0 ? void 0 : _a[data === null || data === void 0 ? void 0 : data.color];
                const textColorKey = (data === null || data === void 0 ? void 0 : data.fill) === "solid"
                  ? `${data === null || data === void 0 ? void 0 : data.color}-contrast`
                  : data.color;
                const textColor = (_b = this.colors) === null || _b === void 0 ? void 0 : _b[textColorKey];
                return `<mj-button ${(data === null || data === void 0 ? void 0 : data.expand) ? `width="100%"` : ""} align="${(data === null || data === void 0 ? void 0 : data.align) || "left"}" background-color="${((data === null || data === void 0 ? void 0 : data.fill) === "solid" && (data === null || data === void 0 ? void 0 : data.color) && color) ||
                  "transparent"}" ${((data === null || data === void 0 ? void 0 : data.color) && textColor && `color="${textColor}"`) || ""} href="${(data === null || data === void 0 ? void 0 : data.href) || "#"}" ${(data === null || data === void 0 ? void 0 : data.shape) === "round" ? `border-radius="64px"` : ""} ${data.fill === "outline" ? `border="2px solid ${color}"` : ""}>${(data === null || data === void 0 ? void 0 : data.text) || ""}</mj-button>`;
              },
              component: (data) => {
                return `<mj-text><div class="editor-component">{{> ${data.templateId}}}</div></mj-text>`;
              },
              code: (data) => data === null || data === void 0 ? void 0 : data.html,
              ...(this.customEmailParsers || {}),
            }),
          template: this.template,
          disableRender: disableRender !== null && disableRender !== void 0 ? disableRender : true,
          url: url || this.url,
        });
      }
    }
    catch (e) {
      console.log("Error exoprting HTML", e);
    }
    return html;
  }
  async generatePreview({ templateData, mjml, disableRender, excludeFrame, excludeHeader, excludeFooter, disableHandlebarsCompile, } = {}) {
    var _a;
    if (!((_a = this.editorEl) === null || _a === void 0 ? void 0 : _a.exportHTML))
      return;
    if (templateData)
      this.templateData = templateData;
    const html = await this.exportHTML({
      excludeFrame,
      mjml,
      disableRender,
      excludeFooter,
      excludeHeader,
      disableHandlebarsCompile,
    });
    this.template.html = html;
    this.previewTemplate = {
      html,
      id: "preview",
    };
    return html;
  }
  setProgress(listEl) {
    var _a;
    let completed = 0;
    const items = Array.from(listEl.querySelectorAll("ion-item"));
    const progressBarEl = listEl.querySelector("ion-progress-bar");
    for (const item of items) {
      completed =
        completed + (((_a = item === null || item === void 0 ? void 0 : item.querySelector("ion-checkbox")) === null || _a === void 0 ? void 0 : _a.checked) ? 1 : 0);
    }
    const progressMath = completed / items.length;
    const progress = isFinite(progressMath) && progressMath > 0 ? progressMath : 0;
    progressBarEl.value = progress;
  }
  async presentToast() {
    const toast = await hardwareBackButton.toastController.create({
      message: "The template has been saved successfully!",
      duration: 2000,
      position: this.toastPosition || "top",
    });
    toast.present();
  }
  getExtension(path) {
    var basename = path.split(/[\\/]/).pop(), // extract file name from full path ...
    // (supports `\\` and `/` separators)
    pos = basename.lastIndexOf("."); // get last position of `.`
    if (basename === "" || pos < 1)
      // if file name is empty or ...
      return ""; //  `.` not found (-1) or comes first (0)
    return basename.slice(pos + 1); // extract extension ignoring `.`
  }
  async afterTemplateUpdate() {
    var _a, _b, _c, _d;
    if (typeof ((_a = this.hooks) === null || _a === void 0 ? void 0 : _a.afterTemplateUpdate) === "function")
      return this.hooks.afterTemplateUpdate(this.template);
    this.templateId = ((_b = this.template) === null || _b === void 0 ? void 0 : _b.id) || this.templateId;
    if (!((_c = this.template) === null || _c === void 0 ? void 0 : _c.editor))
      return;
    try {
      this.editorJs.blocks.render(((_d = this.template) === null || _d === void 0 ? void 0 : _d.editor) || {});
      this.generatePreview();
    }
    catch (error) {
      setTimeout(async () => {
        var _a;
        this.editorJs.blocks.render(((_a = this.template) === null || _a === void 0 ? void 0 : _a.editor) || {});
        this.generatePreview();
      }, 1000);
    }
  }
  async onPhotoUpload(event) {
    var _a, _b;
    const storageRef = index_esm2017.ref(this.storage, `${this.uploadPath || ""}${new Date().toISOString()}.${this.getExtension((_a = event === null || event === void 0 ? void 0 : event.file) === null || _a === void 0 ? void 0 : _a.name)}`);
    const upload = await index_esm2017.uploadBytes(storageRef, event.file);
    const url = await index_esm2017.getDownloadURL(upload.ref);
    if (typeof ((_b = this.hooks) === null || _b === void 0 ? void 0 : _b.onPhotoUpload) === "function")
      this.hooks.onPhotoUpload(url, this.template);
    return {
      success: true,
      file: {
        url,
      },
    };
  }
  async componentDidLoad() {
    var _a, _b, _c, _d, _e;
    if (!(index$1.Build === null || index$1.Build === void 0 ? void 0 : index$1.Build.isBrowser))
      return;
    this.storage = index_esm2017.getStorage(this.app);
    if (this.fetch)
      this.fetchData();
    if ((_a = this.templates) === null || _a === void 0 ? void 0 : _a.length) {
      this.setTemplates();
    }
    else {
      if (this.helpers && ((_b = Object.keys(this.helpers)) === null || _b === void 0 ? void 0 : _b.length))
        this.setHelpers();
      if ((_c = this.partials) === null || _c === void 0 ? void 0 : _c.length)
        this.setPartials();
    }
    if ((_d = this.editorEl) === null || _d === void 0 ? void 0 : _d.getInstance) {
      this.editorJs = await this.editorEl.getInstance();
    }
    else {
      setTimeout(async () => {
        this.editorJs = await this.editorEl.getInstance();
      }, 2000);
    }
    if ((_e = this.template) === null || _e === void 0 ? void 0 : _e.id)
      this.afterTemplateUpdate();
  }
  render() {
    var _a, _b, _c;
    if (typeof ((_a = this.hooks) === null || _a === void 0 ? void 0 : _a.onRender) === "function")
      this.hooks.onRender(this.template);
    const partials = this.partials ||
      ((_c = (_b = this.templates) === null || _b === void 0 ? void 0 : _b.filter) === null || _c === void 0 ? void 0 : _c.call(_b, (template) => template === null || template === void 0 ? void 0 : template.partial)) ||
      [];
    return (index$1.h(index$1.Host, { class: { "is-previewing": !!this.isPreviewing } }, (index$1.Build === null || index$1.Build === void 0 ? void 0 : index$1.Build.isBrowser) && (index$1.h("fireenjin-editor", { partials: partials, ref: (el) => (this.editorEl = el), uploadCallback: (event) => (typeof this.uploadCallback === "function" &&
        this.uploadCallback(event)) ||
        this.onPhotoUpload(event), tools: {
        FrameHolder,
        ...(this.tools || {}),
      } })), index$1.h("fireenjin-render-template", { ref: (el) => (this.previewEl = el), id: "preview", name: this.name, enableClicks: this.enableClicks, disableFrame: this.disableFrame, allowFullscreen: this.allowFullscreen, resize: this.resize, zoom: this.zoom, partials: partials, template: this.previewTemplate })));
  }
  get appTemplateEl() { return index$1.getElement(this); }
  static get watchers() { return {
    "templates": ["setTemplates"],
    "partials": ["setPartials"],
    "helpers": ["setHelpers"]
  }; }
};
tslib_es6.__decorate([
  index_min.index_min.debounce(1000)
], AppTemplateForm.prototype, "generatePreview", null);
AppTemplateForm.style = editorCss;

exports.fireenjin_mx_editor = AppTemplateForm;
