@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.
263 lines • 11.6 kB
JavaScript
import { Editor } from "./Editor";
import { EditorLoader } from "./EditorLoader";
import { Exception } from "@aurigma/design-atoms-model/Exception";
import { Client } from "./PostMessage/Client";
import * as Types from "@aurigma/design-atoms/Utils/Type";
import * as LoadMask from "./LoadMask/LoadMask";
import { traceLog, enableTraceLog } from '@aurigma/design-atoms/Utils/TraceLog';
import { RgbColorParser } from "@aurigma/design-atoms/Serialization/Color";
import { RgbColor } from "@aurigma/design-atoms-model/Colors";
/**
* URL to your Customer's Canvas instance.
* @remarks Typically, you do not have to specify this URL explicitly. If you add `id="CcIframeApiScript"` to the script tag which links the `IframeApi.js`, Design Editor automatically detects this URL from the script source. However, if for any reasons you do not want to use the id in the script tag, you can use this property to specify the URL to the Design Editor instance explicitly.
* @example
* ``` js
* <script>
* CustomersCanvas = {
* IframeApi: {
* editorUrl: "http://example.com/"
* }
* };
* </script>
*
* <script type="text/javascript" src="http://example.com/Resources/Generated/IframeApi.js">
* </script>
*
* <script>
* //....
* const editor = await CustomersCanvas.IframeApi.loadEditor(iframe, productDefinition);
* </script>
* ```
* @public
*/
export var editorUrl;
if (window.CustomersCanvas && window.CustomersCanvas.IframeApi)
editorUrl = window.CustomersCanvas.IframeApi.editorUrl;
if (typeof editorUrl !== "string")
editorUrl = findEditorUrl();
/** @internal */
export function setEditorUrl(url) {
editorUrl = url;
}
/**
* Loads the web-to-print editor.
* @param editorFrame - The iframe element to place the editor to.
* @param product - The product to load into the editor.
* @param config - Editor configuration.
* @param onFirstLoad - <em>Outdated.</em> A function that handles the first product launch. For details, see {@link https://customerscanvas.com/dev/editors/iframe-api/customization/preloader.html|Preloader} topic.
* @returns An instance of the web-to-print editor.
* @example
* ``` html
* <!DOCTYPE html>
*
* <html lang="en">
*
* <head>
* <meta charset="utf-8" />
* <title>Customer's Canvas Quick Start Sample Page</title>
* <!-- The IFrame API script. IMPORTANT! Do not remove or change the ID. -->
* <script id="CcIframeApiScript" type="text/javascript" src="/cc/Resources/Generated/IframeApi.js">
* </script>
* <!-- Preloading resources of the editor. -->
* <script>CustomersCanvas.IframeApi.preload();</script>
* </head>
*
* <body>
* <!-- The iframe to display the editor in. -->
* <iframe id="editorFrame" width="100%" height="800px"></iframe>
* </body>
*
* <script>
* // Initializing a product with only one template - "BusinessCard.psd".
* const productDefinition = { surfaces: ["BusinessCard"] };
* // Providing the tokenId, which is required in the Secure Mode.
* const config = { tokenId: "95c16577-75fe-4145-87ff-c0ba49d1a554" };
* // Getting the iframe element to display the editor in.
* const iframe = document.getElementById("editorFrame");
* // Loading the editor.
* const editor = await CustomersCanvas.IframeApi.loadEditor(iframe, productDefinition, config)
* // If an error occurred while loading the editor.
* .catch(error => console.error("The editor failed to load with an exception: ", error));
* </script>
*
* </html>
* ```
* @public
*/
export function loadEditor(editorFrame, product, config, onFirstLoad) {
var _a;
var startLoadTime = performance.now();
checkEditorUrl();
config = normalizeConfig(config);
if (config.enableTrace) {
enableTraceLog(true, editorUrl, "iframeapi");
}
LoadMask.setLogo((_a = config === null || config === void 0 ? void 0 : config.themeConfiguration) === null || _a === void 0 ? void 0 : _a.logo);
if (config.preloader.enabled) {
LoadMask.maskElement(editorFrame.parentElement);
}
applyThemeConfiguration(config.themeConfiguration);
var productData;
if (typeof product === "string")
productData = [product];
else if (Types.isStringArray(product))
productData = product;
else if (typeof product === "object" && product !== null)
productData = product;
else
throw new Exception("Parameter product has unexpected type");
var loader = new EditorLoader(editorFrame, { productData: productData, config: config }, editorUrl);
traceLog({ method: "loadEditor", product: product, config: config });
return loader.start(function () {
if (config.preloader.enabled) {
LoadMask.maskMessage(editorFrame.parentElement, config.preloader.firstTimeMessage);
}
if (onFirstLoad != null)
onFirstLoad();
}).then(function (e) {
if (config.preloader.enabled) {
LoadMask.unmaskElement(editorFrame.parentElement);
}
logInitDuration(startLoadTime);
return e;
}).catch(function (error) {
if (config.preloader.enabled)
LoadMask.maskMessage(editorFrame.parentElement, config.preloader.errorMessage, true);
throw error;
});
}
/**
* Preloads resources of the web-to-print editor.
* @example
* ``` html
* <head>
* <meta charset="utf-8" />
* <title>Customer's Canvas Quick Start Sample Page</title>
* <!-- The IFrame API script. IMPORTANT! Do not remove or change the ID. -->
* <script id="CcIframeApiScript" type="text/javascript" src="/cc/Resources/Generated/IframeApi.js">
* </script>
* <!-- Preloading resources of the editor. -->
* <script>CustomersCanvas.IframeApi.preload();</script>
* </head>
* ```
* @public
*/
export function preload() {
EditorLoader.preload(editorUrl);
}
/** @internal */
export function loadEditorByQueryString(editorFrame, queryString, onFirstLoad) {
checkEditorUrl();
var loader = new EditorLoader(editorFrame, new QueryString(queryString), editorUrl);
return loader.start(onFirstLoad);
}
// ReSharper disable InconsistentNaming
/** @internal */
export function _createPreConfiguredEditor(editorFrame) {
return new Editor(editorFrame, new Client(editorFrame, editorUrl), "hostpage_api_unknown");
}
// ReSharper restore InconsistentNaming
function checkEditorUrl() {
if (editorUrl == null)
throw new Error("IFrame Api is unable to find location of Customer's Canvas application. Please make sure you have added id=\"CcIframeApiScript\" to the <script> tag loading IFrame Api:\n<head>\n \u2026\n <script id=\"CcIframeApiScript\" type=\"text/javascript\" src=\"http://example.com/CustomersCanvas/Resources/SPEditor/Scripts/IFrame/IframeApi.js\"></script>\n \u2026\n</head>\nFor more information please visit https://customerscanvas.com/docs/cc/IframeApi-introduction.htm");
}
function findEditorUrl() {
var apiScript = document.querySelector("script#CcIframeApiScript");
var ccSdkIframeApiSrcPath = "/Resources/Generated/IframeApi.js".toLowerCase();
if (apiScript == null)
return null;
var scriptSrc = apiScript.src.toLowerCase();
var signPosition = scriptSrc.indexOf("?");
if (signPosition !== -1)
scriptSrc = scriptSrc.substring(0, signPosition);
return scriptSrc.replace(ccSdkIframeApiSrcPath, "");
}
function normalizeConfig(config) {
if (config == null)
config = {};
if (config.preloader == null)
config.preloader = {};
if (config.preloader.enabled == null)
config.preloader.enabled = true;
if (config.preloader.enabled) {
if (config.preloader.errorMessage == null)
config.preloader
.errorMessage = "Initialization error.";
if (config.preloader.firstTimeMessage == null)
config.preloader
.firstTimeMessage = "The product is being configured. It may take a while.";
}
return config;
}
/** @internal */
var QueryString = /** @class */ (function () {
function QueryString(value) {
this.value = value;
}
QueryString.prototype.getDeserializedObject = function () {
return this.value.split("&")
.map(function (pair) { return pair.split("="); })
.map(function (pairArr) { return ({ key: pairArr[0], value: pairArr[1] }); });
};
return QueryString;
}());
export { QueryString };
/** @public */
var StateId = /** @class */ (function () {
function StateId(value) {
this.value = value;
}
return StateId;
}());
export { StateId };
function applyThemeConfiguration(themeConfiguration) {
if ((themeConfiguration === null || themeConfiguration === void 0 ? void 0 : themeConfiguration.primaryColor) != null) {
var primaryColorString = themeConfiguration.primaryColor;
document.documentElement.style.setProperty("--de-brand-primary", primaryColorString);
var primaryFadeColorString = null;
try {
var color = new RgbColorParser().parse(primaryColorString);
color = new RgbColor(color.r, color.g, color.b, color.alpha * 0.2);
primaryFadeColorString = color.toString();
}
catch (_a) {
console.error("EditorLoader: Cannot parse color: " + primaryColorString);
}
if (primaryFadeColorString != null)
document.documentElement.style.setProperty("--de-brand-primary-fade-80", primaryFadeColorString);
}
if ((themeConfiguration === null || themeConfiguration === void 0 ? void 0 : themeConfiguration.preloaderColor) != null) {
var preloaderColorString = themeConfiguration.preloaderColor;
document.documentElement.style.setProperty("--de-preloader-color", preloaderColorString);
var primaryFadeColorString = null;
try {
var color = new RgbColorParser().parse(preloaderColorString);
color = new RgbColor(color.r, color.g, color.b, color.alpha * 0.2);
primaryFadeColorString = color.toString();
}
catch (_b) {
console.error("EditorLoader: Cannot parse color: " + preloaderColorString);
}
if (primaryFadeColorString != null)
document.documentElement.style.setProperty("--de-preloader-color-fade-80", primaryFadeColorString);
}
else {
var primary = window.getComputedStyle(document.body).getPropertyValue("--de-brand-primary");
document.documentElement.style.setProperty("--de-preloader-color", primary);
try {
var color = new RgbColorParser().parse(primary);
color = new RgbColor(color.r, color.g, color.b, color.alpha * 0.2);
var primaryFadeColorString = color.toString();
document.documentElement.style.setProperty("--de-preloader-color-fade-80", primaryFadeColorString);
}
catch (_c) {
console.error("EditorLoader: Cannot parse color: " + primary);
}
}
}
function logInitDuration(startLoadTime) {
var initTime = performance.now() - startLoadTime;
var timeInSeconds = (initTime / 1000).toFixed(2);
console.log("[DE] The editor initialized in " + timeInSeconds + " seconds.");
}
//# sourceMappingURL=IframeApi.js.map