@aurigma/design-editor-iframe
Version:
Using this module you can embed Design Editor (a part of Customer's Canvas) to your page through the IFrame API.
398 lines • 20.3 kB
JavaScript
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { Client } from "./PostMessage/Client";
import * as Convert from "./ObjectModel/Convert";
import { Exception } from "@aurigma/design-atoms-model/Exception";
import { AjaxResponseException } from "@aurigma/design-atoms/Exception";
import { Editor } from "./Editor";
import { QueryString } from "./IframeApi";
import { ServerException } from "./Exception";
import { getTraceLogId } from "@aurigma/design-atoms/Utils/TraceLog";
import * as Workarounds from "./Workarounds/FirefoxWorkarounds";
import { ApiClient } from "./ApiClient";
import { RequestDataMode } from "./IConfigRequestData";
import { DE_APP_SOURCE, IFRAME_LOADED_EVENT } from "./PostMessage/Consts";
import { MessageType } from "./PostMessage";
import * as CcJson from "@aurigma/design-atoms/Utils/Json";
import { getOrigin } from "./Utils/Origin";
/** @internal */
var EditorLoader = /** @class */ (function () {
function EditorLoader(iframe, editorData, editorUrl) {
this._iframe = this._normalizeIframe(iframe);
this._editorData = this._normalizeEditorData(editorData);
this._editorUrl = this._normalizeUrl(editorUrl);
EditorLoader._apiClient = new ApiClient(editorUrl);
this._config = this._editorData instanceof QueryString ?
this._queryStringToConfigConverter(this._editorData)
: this._editorData.config;
EditorLoader._existingLoaders.push(this);
this._status = EditorLoader.Status.Initialized;
}
EditorLoader.prototype._normalizeIframe = function (iframe) {
iframe.scrolling = "no";
return iframe;
};
EditorLoader.prototype._normalizeEditorData = function (data) {
if (!(data instanceof QueryString) && data.config === null)
data.config = undefined;
return data;
};
EditorLoader.preload = function (editorUrl) {
return __awaiter(this, void 0, void 0, function () {
var iframe, head;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
iframe = document.createElement("iframe");
head = document.head || document.getElementsByTagName("head")[0];
if (head == null)
head = document.getElementsByTagName("html")[0].appendChild(document.createElement("head"));
iframe.style.position = "absolute";
iframe.style.top = "-1000px";
iframe.style.left = "-1000px";
iframe.style.width = "500px";
iframe.style.height = "500px";
iframe.style.visibility = "hidden";
head.appendChild(iframe);
return [4 /*yield*/, EditorLoader._loadIframe(iframe, EditorLoader._getIframeUrl(editorUrl), true)];
case 1:
_a.sent();
iframe.parentNode.removeChild(iframe);
return [2 /*return*/];
}
});
});
};
EditorLoader.prototype.start = function (onFirstLoad) {
var _this = this;
try {
this._status = EditorLoader.Status.Started;
var requestDataMode = this._config.enableLargeProductLoadOptimization === true
? RequestDataMode.First
: RequestDataMode.Whole;
var loadInitData = this._getInitData(onFirstLoad, requestDataMode);
var hasAdditionalSurfaces_1 = false;
loadInitData.then(function (data) {
var initDataObj = JSON.parse(data);
hasAdditionalSurfaces_1 = initDataObj.hasAdditionalSurfaces;
if (hasAdditionalSurfaces_1) {
var key = initDataObj.restRequestKey;
var loadInitDataRest = _this._getInitData(onFirstLoad, RequestDataMode.Rest, key);
loadInitDataRest.then(function (result) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, initIframeClient_1];
case 1:
_a.sent();
this._initEditorAdditionalPages(result);
return [2 /*return*/];
}
});
}); });
}
});
var initIframeClient_1 = this._cleanUpIframe()
.then(function () {
_this._checkLoadStatus();
return _this._loadIframe(_this._getIframeUrl(), true);
})
.then(function () {
_this._checkLoadStatus();
return _this._iframeClient = new Client(_this._iframe, _this._getIframeUrl());
});
var initData_1;
return Promise.all([loadInitData, initIframeClient_1, Workarounds.Firefox.waitReady(this._iframe)])
.then(function (r) { return initData_1 = r[0]; })
.then(function () {
_this._checkLoadStatus();
return _this._initEditor(initData_1);
})
.then(function () { return new Editor(_this._iframe, _this._iframeClient, _this._editorUrl, _this._config); })
.catch(function (ex) {
if (ex instanceof AjaxResponseException)
_this._handleServerException(ex, initIframeClient_1);
if (ex instanceof EditorLoader.LoadingStoppedException) {
//never fulfil return promise
return new Promise(function (resolve) { });
}
throw ex;
});
}
catch (ex) {
return Promise.reject(ex);
}
};
EditorLoader.prototype.dispose = function () {
if (this._iframeClient != null)
this._iframeClient.dispose();
this._status = EditorLoader.Status.Disposed;
};
EditorLoader.prototype._queryStringToConfigConverter = function (queryString) {
var parameters = queryString.getDeserializedObject();
var themeParameter = parameters.filter(function (p) { return p.key.toLowerCase() === "theme"; })[0];
return themeParameter != null ? { theme: themeParameter.value } : {};
};
EditorLoader.prototype._getInitData = function (onFirstTemplateLoad, requestDataMode, restRequestKey) {
if (requestDataMode === void 0) { requestDataMode = RequestDataMode.Whole; }
if (restRequestKey === void 0) { restRequestKey = null; }
var editorData = this._editorData;
if (editorData instanceof QueryString) {
return EditorLoader.getInitDataByQueryString(this._editorUrl, editorData.value, onFirstTemplateLoad);
}
else {
return EditorLoader.getInitData(this._editorUrl, editorData.productData, this._config, onFirstTemplateLoad, false, requestDataMode, restRequestKey);
}
};
EditorLoader.getInitData = function (editorUrl, productDefinition, configFromApi, onFirstTemplateLoad, hasExternalMockup, requestDataMode, restRequestKey) {
if (hasExternalMockup === void 0) { hasExternalMockup = false; }
if (requestDataMode === void 0) { requestDataMode = RequestDataMode.Whole; }
if (restRequestKey === void 0) { restRequestKey = null; }
return __awaiter(this, void 0, void 0, function () {
var requestData, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
requestData = {
userId: configFromApi.userId,
tokenId: configFromApi.tokenId,
userInfo: configFromApi.userInfo,
loadConfigFromState: configFromApi.loadConfigFromState,
configFromApi: configFromApi,
hasExternalMockup: hasExternalMockup,
requestDataMode: requestDataMode,
restRequestKey: restRequestKey
};
if (Array.isArray(productDefinition)) {
requestData.states = productDefinition;
}
else {
requestData.productDefinition = Convert.prepareForServer(productDefinition);
}
return [4 /*yield*/, this._apiClient.requestData(requestData)];
case 1:
response = _a.sent();
if (!(response.hasContent == false)) return [3 /*break*/, 3];
if (onFirstTemplateLoad != null)
onFirstTemplateLoad();
return [4 /*yield*/, this._apiClient.firstRequestData(requestData)];
case 2:
response = _a.sent();
_a.label = 3;
case 3: return [2 /*return*/, response.value];
}
});
});
};
EditorLoader.getInitDataByQueryString = function (editorUrl, queryString, onFirstTemplateLoad) {
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, EditorLoader._apiClient.requestDataByQueryString(queryString)];
case 1:
result = _a.sent();
if (!(result.hasContent == false)) return [3 /*break*/, 3];
if (onFirstTemplateLoad != null)
onFirstTemplateLoad();
return [4 /*yield*/, EditorLoader._apiClient.firstRequestDataByQueryString(queryString)];
case 2:
result = _a.sent();
_a.label = 3;
case 3: return [2 /*return*/, result.value];
}
});
});
};
EditorLoader.prototype._checkLoadStatus = function () {
if (this._status !== EditorLoader.Status.Started)
throw new EditorLoader.LoadingStoppedException("Loader disposed!");
};
EditorLoader.prototype._normalizeUrl = function (url) {
return url[url.length - 1] === "/" ?
url.substr(0, url.length - 1)
: url;
};
EditorLoader.prototype._cleanUpIframe = function () {
var _this = this;
EditorLoader._existingLoaders
.filter(function (l) { return l !== _this && l._iframe === _this._iframe; })
.forEach(function (l) { return l.dispose(); });
return this._iframe.src !== "about:blank" ?
this._loadIframe("about:blank", false)
: Promise.resolve();
};
EditorLoader.prototype._loadIframe = function (url, appendOrigin) {
return EditorLoader._loadIframe(this._iframe, url, appendOrigin);
};
EditorLoader._appendOrigin = function (url) {
var originPart = encodeURIComponent(getOrigin());
return url + "#targetOrigin=" + originPart;
};
EditorLoader._loadIframe = function (iframe, url, appendOrigin) {
if (appendOrigin)
url = this._appendOrigin(url);
iframe.setAttribute("allow", "fullscreen *; clipboard-read; clipboard-write");
return new Promise(function (resolve, reject) {
var e_1, _a;
var onIframeLoad = function () {
iframe.removeEventListener("load", onIframeLoad);
removeEventListener("message", onIframeMessage);
resolve();
};
var onIframeMessage = function (ev) {
if (ev.source !== iframe.contentWindow)
return; //alien message
var message = CcJson.Json.parse(ev.data);
if (message.source != DE_APP_SOURCE)
return; // alien message
switch (message.type) {
case MessageType.Event:
var event_1 = message;
if (event_1.event == IFRAME_LOADED_EVENT)
onIframeLoad();
break;
}
};
iframe.addEventListener("load", onIframeLoad);
addEventListener("message", onIframeMessage);
try {
for (var _b = __values(["abort", "error"]), _c = _b.next(); !_c.done; _c = _b.next()) {
var errorEvent = _c.value;
iframe.addEventListener(errorEvent, reject);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
iframe.src = url;
});
};
EditorLoader.prototype._getIframeUrl = function (config) {
if (config === void 0) { config = {}; }
return EditorLoader._getIframeUrl(this._editorUrl, this._config);
};
EditorLoader._getIframeUrl = function (editorUrl, config) {
if (config === void 0) { config = {}; }
var queryParams = {
"iframeApi": "true"
};
if (config.customStyle != null)
queryParams["customStyle"] = config.customStyle;
if (config.theme != null)
queryParams["theme"] = config.theme;
return editorUrl + "/page/iframe?" + toQueryString(queryParams);
function toQueryString(dict) {
return Object.keys(dict).map(function (key) { return key + "=" + dict[key]; }).join("&");
}
};
EditorLoader.prototype._initEditor = function (initData) {
var _this = this;
return this._iframeClient.callProcedure("setInitData", initData, getTraceLogId())
.then(function () { return _this._iframeClient.callProcedure("waitEditorReady"); });
};
EditorLoader.prototype._initEditorAdditionalPages = function (initData) {
return this._iframeClient.callProcedure("setInitDataAdditinalPages", initData, getTraceLogId());
};
EditorLoader.prototype._handleServerException = function (ex, initClient) {
var _a;
var contentType = (_a = ex.ajaxResponse.contentType) === null || _a === void 0 ? void 0 : _a.toLowerCase();
if (contentType.indexOf("application/json") !== -1 || contentType.indexOf("text/plain") !== -1) {
return initClient.then(function (c) {
c.callProcedure("notifyServerError", ex.ajaxResponse).then(function () { return c.dispose(); });
throw new ServerException(ex.ajaxResponse);
});
}
else if (ex.ajaxResponse.value != null) {
throw ex.ajaxResponse.value;
}
else {
throw JSON.stringify("ex.ajaxResponse: " + JSON.stringify(ex.ajaxResponse));
}
};
EditorLoader._existingLoaders = [];
return EditorLoader;
}());
export { EditorLoader };
/** @internal */
(function (EditorLoader) {
var Status;
(function (Status) {
Status[Status["Initialized"] = 0] = "Initialized";
Status[Status["Started"] = 1] = "Started";
Status[Status["Finished"] = 2] = "Finished";
Status[Status["Disposed"] = 3] = "Disposed";
Status[Status["Error"] = 4] = "Error";
})(Status = EditorLoader.Status || (EditorLoader.Status = {}));
;
var LoadingStoppedException = /** @class */ (function (_super) {
__extends(LoadingStoppedException, _super);
function LoadingStoppedException() {
return _super !== null && _super.apply(this, arguments) || this;
}
return LoadingStoppedException;
}(Exception));
EditorLoader.LoadingStoppedException = LoadingStoppedException;
})(EditorLoader || (EditorLoader = {}));
//# sourceMappingURL=EditorLoader.js.map