@aurigma/design-atoms
Version:
Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.
878 lines • 46.9 kB
JavaScript
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 __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
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 * as Utils from "@aurigma/design-atoms-model/Utils/Utils";
import { PlaceholderItem } from "@aurigma/design-atoms-model/Product/Items/PlaceholderItem";
import { ImageItem } from "@aurigma/design-atoms-model/Product/Items/ImageItem";
import { BarcodeItem, BarcodeFormat, EncodingOptions, PathBoundedTextItem, TextAlignment, TextVerticalAlignment } from "@aurigma/design-atoms-model/Product/Items";
import { BaseTextItem } from "@aurigma/design-atoms-model/Product/Items/BaseTextItem";
import { ImageMetaData } from "@aurigma/design-atoms-model/Product/Items/ImageMetaData";
import { Exception } from "@aurigma/design-atoms-model/Exception";
import { Configuration } from "@aurigma/design-atoms-model/Configuration";
import { SurfaceContainer } from "@aurigma/design-atoms-model/Product/Container";
import * as _ from "underscore";
import Environment from "@aurigma/design-atoms-model/Utils/Environment";
import { BarcodeData, AutoScaledTextItem, BoundedTextItem, OverflowStrategy, PlainTextItem, GroupItem, OverlayEffect } from "@aurigma/design-atoms-model/Product/Items";
import { PlaceholderItemHandler, BaseTextItemHandler, NewBaseTextItemHandler } from "../ItemHandlers";
import { WrappingMode } from "@aurigma/design-atoms-model/Product/Items/WrappingMode";
import { ImageUtils } from "./ImageUtils";
import { RgbColors } from "@aurigma/design-atoms-model/Colors";
import { ImageEffect } from "@aurigma/design-atoms-model/Product/Items/ImageEffect";
import { ISize, fitSizeToSize, alignRectToRect } from "./Math";
import { PointF, normalizeAngle, EqualsOfFloatNumbers } from "@aurigma/design-atoms-model/Math";
import { Size } from "@aurigma/design-atoms-model/Product/Items/Size";
import { SetImageMetadataCommand } from "../Commands/ItemsCommands/SetImageMetadataCommand";
import { ItemsDataApplier } from "../Services/ItemsDataApplier";
import { pixelsToPoints } from "@aurigma/design-atoms-model";
import { ItemsCommand, OriginPointType } from "@aurigma/design-atoms-interfaces";
var ItemUtils = /** @class */ (function () {
function ItemUtils() {
}
Object.defineProperty(ItemUtils, "designAtomsApiClient", {
set: function (designAtomsApiClient) {
this._designAtomsApiClient = designAtomsApiClient;
},
enumerable: true,
configurable: true
});
ItemUtils.isBgContainerItem = function (item) {
var pc = item.parentContainer;
if (pc instanceof SurfaceContainer) {
return item.parentContainer instanceof SurfaceContainer &&
Utils.stringEquals(item.parentContainer.name, Configuration.BG_CONTAINER_NAME, true);
}
};
ItemUtils.isFgContainerItem = function (item) {
return item.parentContainer instanceof SurfaceContainer &&
Utils.stringEquals(item.parentContainer.name, Configuration.FG_CONTAINER_NAME, true);
};
ItemUtils.isImage = function (item) {
return (item instanceof ImageItem || item instanceof PlaceholderItem) && !ItemUtils.isBgContainerItem(item);
};
ItemUtils.isEmptyPlaceholder = function (item) {
return item instanceof PlaceholderItem && item.isStubOrEmpty;
};
ItemUtils.isDataMatrixBarcode = function (item) {
return item instanceof BarcodeItem && item.barcodeFormat === BarcodeFormat.DATA_MATRIX ||
item instanceof PlaceholderItem && item.barcodeFormat == BarcodeFormat.DATA_MATRIX;
};
ItemUtils.isQrCode = function (item) {
return item instanceof BarcodeItem && item.isQrCode || item instanceof PlaceholderItem && item.barcodeFormat == BarcodeFormat.QR_CODE;
};
ItemUtils.isLinearBarcode = function (item) {
return item instanceof BarcodeItem && item.isLinearBarcode ||
(item instanceof PlaceholderItem && (item.barcodeFormat == BarcodeFormat.EAN_13 || item.barcodeFormat == BarcodeFormat.EAN_8
|| item.barcodeFormat == BarcodeFormat.UPC_A || item.barcodeFormat == BarcodeFormat.UPC_E
|| item.barcodeFormat == BarcodeFormat.CODE_128));
};
ItemUtils.isVariableItem = function (item) {
return item.canSetIsVariable(); // item instanceof ContentItem || item instanceof PlaceholderItem;
};
ItemUtils.isMultiValueItem = function (item) {
return (item instanceof ImageItem || item instanceof BaseTextItem) && item.values.length !== 0;
};
ItemUtils.isTextType = function (type) {
if (type === BaseTextItem)
return true;
return BaseTextItem.prototype.isPrototypeOf(type.prototype);
};
ItemUtils.getAllowTextFormatting = function (textItem, defaultValue) {
var _a, _b, _c;
var copyfittingEnabled = textItem != null && textItem instanceof BoundedTextItem &&
textItem.overflowStrategy !== OverflowStrategy.Clip && textItem.overflowStrategy !== OverflowStrategy.ExpandBox;
if (copyfittingEnabled)
return false;
return (_c = (_b = (_a = textItem === null || textItem === void 0 ? void 0 : textItem.textPermissions) === null || _a === void 0 ? void 0 : _a.allowTextFormatting) !== null && _b !== void 0 ? _b : defaultValue) !== null && _c !== void 0 ? _c : (textItem instanceof BoundedTextItem || textItem instanceof PathBoundedTextItem);
};
ItemUtils.allowMoveHorizontal = function (item) {
return !item.locked && (!item.manipulationPermissions || item.manipulationPermissions.allowMoveHorizontal);
};
ItemUtils.allowMoveVertical = function (item) {
return !item.locked && (!item.manipulationPermissions || item.manipulationPermissions.allowMoveVertical);
};
ItemUtils.allowManipulate = function (item) {
return !item.locked && (!item.manipulationPermissions ||
item.manipulationPermissions.allowMoveVertical ||
item.manipulationPermissions.allowMoveHorizontal ||
item.manipulationPermissions.allowDelete ||
item.manipulationPermissions.allowRotate);
};
ItemUtils.clearImageContent = function (placeHolder) {
if (placeHolder == null)
return;
var content = placeHolder.content;
delete content.tags.sourceData;
delete content.tags.sourceType;
if (content instanceof ImageItem) {
content.source.setIdWithOrigin(null, null);
content.source.width = null;
content.source.height = null;
content.isUserImage = false;
content.fillColor = RgbColors.transparent;
}
};
ItemUtils.getImageItem = function (item) {
if (item == null)
return null;
if (item instanceof ImageItem) {
return item;
}
else {
var content = item.content;
if (content instanceof ImageItem) {
return content;
}
else if (content == null || content instanceof BarcodeItem) {
return null;
}
else {
throw new Exception("Wrong placeholder content!");
}
}
};
ItemUtils.getImagePermissions = function (item) {
if (item == null)
return null;
if (item instanceof ImageItem)
return item.imagePermissions;
return item.getImagePermissions();
};
ItemUtils.getImageSizeInPoints = function (source) {
var _a, _b, _c, _d, _e, _f;
var originalSize = {
width: pixelsToPoints((_c = (_b = (_a = source === null || source === void 0 ? void 0 : source.origin) === null || _a === void 0 ? void 0 : _a.originalSize) === null || _b === void 0 ? void 0 : _b.width) !== null && _c !== void 0 ? _c : source.width, source.dpiX || 72),
height: pixelsToPoints((_f = (_e = (_d = source === null || source === void 0 ? void 0 : source.origin) === null || _d === void 0 ? void 0 : _d.originalSize) === null || _e === void 0 ? void 0 : _e.height) !== null && _f !== void 0 ? _f : source.height, source.dpiY || 72)
};
return originalSize;
};
ItemUtils.getContentEffect = function (item) {
if (item.content instanceof ImageItem)
return item.content.effect;
return item.contentEffect;
};
ItemUtils.getAllowChangeContent = function (item) {
if (item instanceof BarcodeItem || item instanceof PlaceholderItem && item.isBarcodePlaceholder) {
var barcodePermissions = ItemUtils.getBarcodePermissions(item);
return barcodePermissions.allowChangeBarcodeContent;
}
else {
var contentPermissions = ItemUtils.getImagePermissions(item);
var allowChangeContent = contentPermissions != null ? contentPermissions.allowChangeImage : true;
var imageItem = ItemUtils.getImageItem(item);
return allowChangeContent && (imageItem == null || imageItem.values.length === 0);
}
};
ItemUtils.getImageMetaDataFromFile = function (appDomainUrl, filePath, userId) {
if (appDomainUrl === void 0) { appDomainUrl = undefined; }
if (userId === void 0) { userId = null; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this._designAtomsApiClient.getImageMetaDataFromFile(filePath, userId, appDomainUrl)];
});
});
};
ItemUtils.getImageMetaDataFromDesignImage = function (appDomainUrl, designImageName) {
if (appDomainUrl === void 0) { appDomainUrl = undefined; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this._designAtomsApiClient.getImageMetaDataFromDesignImage(designImageName, appDomainUrl)];
});
});
};
ItemUtils.getImageMetadataFromRemoteFile = function (appDomainUrl, url) {
if (appDomainUrl === void 0) { appDomainUrl = undefined; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this._designAtomsApiClient.getImageMetadataFromRemoteFile(url, appDomainUrl)];
});
});
};
ItemUtils.getTextFromRichTextItem = function (item) {
return Utils.getTextFromXml(item.text);
};
ItemUtils.getMaxFontSize = function (textItem) {
//TODO remove the code duplicating RichTextHtmlConvertor
//TODO add unit tests
if (textItem == null || !(textItem instanceof BaseTextItem))
return null;
if (!Utils.isValidXml(textItem.text))
return textItem.font.size;
var fontSizes = [textItem.font.size];
try {
if (textItem.text != null)
walkNodes(textItem.text, ["span", "ol", "ul"], parseSizeableNode);
}
catch (ex) {
console.error("Unexpected exception while parsing item text");
console.error(ex);
}
return Math.max.apply(Math, __spread(fontSizes));
//#region local funcs
function parseSizeableNode(node) {
var style = parseXmlStyle(node);
if (style != null && style.has("font-size"))
fontSizes.push(parseFloat(style.get("font-size")));
}
function parseXmlStyle(node) {
var e_1, _a;
var styleAttr = node.attributes.getNamedItem("style");
if (styleAttr == null || styleAttr.value == null)
return null;
var nodeStyleParts = styleAttr.value.split(";");
var styleMap = new Map();
try {
for (var nodeStyleParts_1 = __values(nodeStyleParts), nodeStyleParts_1_1 = nodeStyleParts_1.next(); !nodeStyleParts_1_1.done; nodeStyleParts_1_1 = nodeStyleParts_1.next()) {
var stylePart = nodeStyleParts_1_1.value;
stylePart = stylePart.trim();
if (stylePart == null || stylePart === "")
continue;
var content = stylePart.split(":");
var key = content[0].trim();
var value = content[1].trim();
styleMap.set(key, value);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (nodeStyleParts_1_1 && !nodeStyleParts_1_1.done && (_a = nodeStyleParts_1.return)) _a.call(nodeStyleParts_1);
}
finally { if (e_1) throw e_1.error; }
}
return styleMap;
}
function walkNodes(gmXml, nodeNames, parseNode) {
var xmlDoc = new DOMParser().parseFromString("<body>" + gmXml + "</body>", "application/xml");
var filter = {
acceptNode: function (node) {
var nodeName = node.nodeName.toLowerCase();
return nodeNames.includes(nodeName) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
}
};
if (Environment.IsIE())
filter = makeIeCompatible(filter);
var walker = document.createTreeWalker(xmlDoc.childNodes[0], NodeFilter.SHOW_ELEMENT, filter, false);
while (walker.nextNode()) {
var node = walker.currentNode;
parseNode(node);
}
function makeIeCompatible(filter) {
return filter.acceptNode;
}
}
//#endregion
};
ItemUtils.getBarcodeItem = function (item) {
if (item == null)
return null;
if (item instanceof BarcodeItem)
return item;
else {
var content = item.content;
if (content instanceof BarcodeItem)
return content;
else if (content == null)
return null;
else
throw new Exception("Wrong placeholder content!");
}
};
ItemUtils.getBarcodePermissions = function (item) {
if (item == null)
return null;
if (item instanceof BarcodeItem)
return item.barcodePermissions;
if (item.contentPermissions != null)
return item.contentPermissions.barcodePermissions;
var content = item.content;
if (content instanceof BarcodeItem)
return content.barcodePermissions;
return null;
};
ItemUtils.getImageUrlFromImageMetadata = function (imageMetadata, canvas, width, height, keepProportions) {
var w = width != null ? width : imageMetadata.size.width;
var h = height != null ? height : imageMetadata.size.height;
var kp = keepProportions != null ? keepProportions : false;
return ImageUtils.getImageUrl(canvas.renderingConfigProvider, canvas.viewer.designAtomsApiClient, imageMetadata.storageId, w, h, null, null, kp, null, imageMetadata.pageIndex);
};
ItemUtils.updateItems = function (items, productHandler, canvas, options) {
var e_2, _a;
options = Utils.normalize(options, {
addToHistory: true,
updatePhase: UpdatePhase.Final,
redraw: true
});
if (items.length === 0)
return;
try {
for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
var item = items_1_1.value;
this._updateItem(productHandler, item, options, canvas);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
}
finally { if (e_2) throw e_2.error; }
}
if (options.redraw)
productHandler.redraw();
};
ItemUtils._updateItem = function (productHandler, item, options, canvas) {
var itemHandler = productHandler.getHandler(item);
if (itemHandler == null || itemHandler.layer == null)
return;
if (item instanceof ImageItem)
this._updateImageItem(item, itemHandler, options, canvas);
else if (item instanceof PlaceholderItem)
this._updatePlaceholderItem(item, itemHandler, options, canvas);
};
ItemUtils._updateImageItem = function (imgItem, imgItemHandler, options, canvas) {
imgItemHandler.quickUpdate();
if (options.updatePhase === UpdatePhase.Final) {
imgItem.getItemChangedEvent().fire();
imgItemHandler.update();
canvas.updateTexts();
}
};
ItemUtils._updatePlaceholderItem = function (phItem, phItemHandler, options, canvas) {
if (phItem.content != null)
this._updateImageItem(phItem.content, phItemHandler.content, options, canvas);
if (!this._hidePlaceholderButtonWhileImageLoad(phItemHandler))
phItemHandler.update();
};
ItemUtils._hidePlaceholderButtonWhileImageLoad = function (placeholderItemHandler) {
if (placeholderItemHandler.isEmptyContent() ||
(!placeholderItemHandler.getPermissions().showSelectButton && !placeholderItemHandler.getPermissions().showHandleButton))
return false;
var readyHandler = function (handler) {
handler.removeReady(readyHandler);
placeholderItemHandler.getPermissions().showSelectButton = true;
placeholderItemHandler.update();
};
placeholderItemHandler.content.addReady(readyHandler);
placeholderItemHandler.getPermissions().showSelectButton = false;
placeholderItemHandler.update();
return true;
};
ItemUtils.getItemBoundsForViolationCheck = function (handler) {
if (handler instanceof PlaceholderItemHandler) {
return handler.getBoundsIncludingFrames();
}
else {
return handler.bounds;
}
};
ItemUtils.createCloneName = function (item, variableItemHelper, productHandler) {
var baseName;
if (typeof item === "string")
baseName = item;
else
baseName = variableItemHelper.getRealItemName(item);
if (typeof baseName !== "string")
baseName = "";
var allItems = productHandler.currentSurface.getAllItems({ ignoreMockups: false, excludeGroupItems: true, flatGroupItems: true }).toArray();
var isNameExist = function (checkName) { return allItems.some(function (it) { return variableItemHelper.getRealItemName(it) === checkName; }); };
if (!isNameExist(baseName))
return baseName;
var cloneNumber = 0;
var clonePostfixMatch = baseName.match(/_(\d+)$/);
if (clonePostfixMatch != null && baseName.length >= 2) {
baseName = baseName.substr(0, baseName.length - clonePostfixMatch[0].length);
var previewsCloneNumber = parseInt(clonePostfixMatch[1]);
if (previewsCloneNumber > 0)
cloneNumber = previewsCloneNumber;
}
var i = 1;
var newName;
do {
newName = baseName + "_" + (cloneNumber + i).toString();
if (!isNameExist(newName))
break;
i++;
} while (i <= 10000);
return (typeof item === "string") ?
newName
: variableItemHelper.createNewItemName(item, newName);
};
ItemUtils.createImageContentForPlaceholder = function (placeholder, metadata, productHandler, hiResOutputDpi) {
var _a;
if (placeholder.isBarcodePlaceholder !== (metadata instanceof BarcodeData))
return null;
var placeholderHandler = productHandler.getHandler(placeholder);
var rect = placeholderHandler.getTransformedRectangle(false);
rect.angle = 0;
var newContent;
var oldContent = placeholder.content;
var contentPerms = placeholder.contentPermissions;
if (placeholder.isBarcodePlaceholder && metadata instanceof BarcodeData) {
var barcodeRect = rect.clone();
var newRectSize = fitSizeToSize(ItemsDataApplier.getBarcodeRatio(metadata.barcodeFormat), new Size(rect.width, rect.height));
barcodeRect.width = newRectSize.width;
barcodeRect.height = newRectSize.height;
var newBarcodeOptions = void 0;
if (oldContent.barcodeOptions != null) {
newBarcodeOptions = oldContent.barcodeOptions;
}
else {
newBarcodeOptions = new EncodingOptions();
newBarcodeOptions.pureBarcode = false;
}
newContent = new BarcodeItem(metadata.barcodeFormat, null, newBarcodeOptions, barcodeRect.toRectangleF());
newContent.applyBarcodeData(metadata);
placeholder.barcodeFormat = metadata.barcodeFormat;
}
else if (metadata instanceof ImageMetaData) {
newContent = new ImageItem(metadata.storageId, rect.location, rect.width, rect.height, metadata.size.width / metadata.size.height);
}
if (newContent instanceof ImageItem && metadata instanceof ImageMetaData) {
SetImageMetadataCommand.setDataToImage(metadata, newContent);
newContent.effect = placeholder.contentEffect;
newContent.imagePermissions = contentPerms.imagePermissions.clone();
if (newContent.effect == ImageEffect.Colorize && placeholder.contentFillColor != null)
newContent.fillColor = placeholder.contentFillColor;
if (placeholder.contentOverlayEffect != null) {
newContent.overlayEffect = placeholder.contentOverlayEffect.clone();
}
}
newContent.transform.setAngle(placeholder.transform.angle);
var newContentHandler = productHandler.getHandler(newContent);
newContentHandler.updateRectangle(null, placeholder.contentResizeMode, placeholderHandler, hiResOutputDpi);
newContent.textWrappingMode = WrappingMode.Square;
newContent.isVariable = oldContent != null ? oldContent.isVariable : false;
if (newContent instanceof BarcodeItem) {
newContent.barcodePermissions = contentPerms.barcodePermissions.clone();
}
var keepOverlayColor = placeholder.contentPermissions.imagePermissions.allowKeepOverlayColor;
if (oldContent == null) {
if (newContent instanceof ImageItem) {
newContent.allowedSubfolder = placeholder.allowedSubfolder;
newContent.allowedTabs = placeholder.allowedTabs;
}
newContent.opacity = placeholder.opacity;
}
else {
if (oldContent instanceof ImageItem && newContent instanceof ImageItem) {
newContent.allowedSubfolder = oldContent.allowedSubfolder;
newContent.allowedTabs = oldContent.allowedTabs;
newContent.imagePermissions = oldContent.imagePermissions.clone();
if (keepOverlayColor && ((_a = oldContent.overlayEffect) === null || _a === void 0 ? void 0 : _a.color))
ItemUtils.setOverlayEffectColor(newContent, oldContent.overlayEffect.color);
}
newContent.manipulationPermissions = oldContent.manipulationPermissions.clone();
newContent.opacity = placeholder.content.opacity;
newContent.fillColor = oldContent.fillColor.clone();
if (newContent instanceof BarcodeItem && oldContent instanceof BarcodeItem) {
newContent.barcodePermissions = oldContent.barcodePermissions.clone();
}
}
return newContent;
};
ItemUtils.positionItemInArea = function (productHandler, item, boundsWidth, boundsHeight, ignoreRotate, targetRegion, oldCenterPoint, relativeToPrintArea) {
if (ignoreRotate === void 0) { ignoreRotate = true; }
if (targetRegion === void 0) { targetRegion = null; }
if (oldCenterPoint === void 0) { oldCenterPoint = null; }
if (relativeToPrintArea === void 0) { relativeToPrintArea = true; }
if (item instanceof GroupItem)
return item.getNestedItems(true).forEach(function (item) { return ItemUtils.positionItemInArea(productHandler, item, boundsWidth, boundsHeight, ignoreRotate, targetRegion, oldCenterPoint, relativeToPrintArea); });
var targetContainer = productHandler.userEditContainer;
var region = targetRegion != null ? targetRegion.toRectangleF() : targetContainer.region;
var isRegion = region != null;
var surface = (targetContainer.parentComponent);
var printAreaContainerBounds = surface.printAreas.getItem(0).bounds;
var targetAreaBounds = !isRegion ? printAreaContainerBounds : region;
var targetAreaCenter = targetAreaBounds.center;
var targetAreaVisualSize = !ignoreRotate ? productHandler.getVisualSize(ISize.from(targetAreaBounds)) : ISize.from(targetAreaBounds);
var multiplier = Math.min(targetAreaVisualSize.width / boundsWidth, targetAreaVisualSize.height / boundsHeight);
var oldCenter = oldCenterPoint != null ? oldCenterPoint : new PointF(boundsWidth / 2, boundsHeight / 2);
var transformFunc = function (i) {
var actualCenter = targetAreaCenter;
if (i instanceof BoundedTextItem || i instanceof AutoScaledTextItem) {
i.textRectangle.width *= multiplier;
i.textRectangle.height *= multiplier;
i.textRectangle.left = actualCenter.x + multiplier * (i.textRectangle.left - oldCenter.x)
- (isRegion ? 0 : 0);
i.textRectangle.top = actualCenter.y + multiplier * (i.textRectangle.top - oldCenter.y)
- (isRegion ? 0 : 0);
}
else if (i instanceof PlainTextItem) {
var newBaselineX = actualCenter.x + multiplier * (i.baselineLocation.x - oldCenter.x);
var newBaselineY = actualCenter.y + multiplier * (i.baselineLocation.y - oldCenter.y);
i.baselineLocation.x = newBaselineX;
i.baselineLocation.y = newBaselineY;
}
else {
var itemHandler = productHandler.getHandler(i);
var rect = itemHandler.getTransformedRectangle(relativeToPrintArea);
var newCenterX = actualCenter.x + multiplier * (rect.centerX - oldCenter.x);
var newCenterY = actualCenter.y + multiplier * (rect.centerY - oldCenter.y);
i.transform.setScaleX(multiplier);
i.transform.setScaleY(multiplier);
i.transform.move(newCenterX - rect.centerX, newCenterY - rect.centerY);
}
};
transformFunc(item);
if (item instanceof PlaceholderItem) {
item.updateContentAndFrames(transformFunc);
}
if (item instanceof BaseTextItem) {
item.font.size *= multiplier;
}
};
ItemUtils.rotateItems = function (productHandler, items, rotateCenter, angle) {
var rotateFunc = function (item) {
if (item instanceof GroupItem)
return item.applyToItems(rotateFunc);
var handler = productHandler.getHandler(item);
var itemRect = handler.getTransformedRectangle(false);
itemRect.rotateAt(angle, rotateCenter);
var transform = itemRect.getTransform(handler.getTransformedRectangle(false));
item.transform.move(transform.translateX, transform.translateY);
item.transform.rotate(transform.angle);
if (item instanceof PlaceholderItem)
item.updateContentAndFrames(rotateFunc);
};
items.forEach(function (item) { return rotateFunc(item); });
};
ItemUtils.changeItemsContent = function (product, productHandler, commandManager, oldItems, newItems, replaceAll) {
var e_3, _a, e_4, _b, e_5, _c;
var _this = this;
var oldItemsCopy = oldItems.map(function (i) { return i.clone( /* true */); });
var oldGroupItems = oldItemsCopy.filter(function (i) { return i instanceof GroupItem; });
var newGroupItems = newItems.filter(function (i) { return i instanceof GroupItem; });
var replaceGroupItemContent = function (newItem, oldItem) {
return _this.changeItemsContent(product, productHandler, commandManager, oldItem.items.toArray(), newItem.items.toArray(), replaceAll);
};
this._replaceContentFromOldToNewItems(oldGroupItems, newGroupItems, replaceGroupItemContent, replaceAll);
var oldTextItems = oldItemsCopy.filter(function (i) { return i instanceof BaseTextItem; });
var newTextItems = newItems.filter(function (i) { return i instanceof BaseTextItem; });
var allItems = product.getAllItems({ ignoreMockups: false, flatGroupItems: true });
var allTextItems = allItems.filter(function (i) { return i instanceof BaseTextItem; });
allTextItems = _.without.apply(_, __spread([allTextItems], newTextItems));
try {
for (var newTextItems_1 = __values(newTextItems), newTextItems_1_1 = newTextItems_1.next(); !newTextItems_1_1.done; newTextItems_1_1 = newTextItems_1.next()) {
var newTextItem = newTextItems_1_1.value;
if (newTextItem.placeholders.length === 0)
continue;
var _loop_1 = function (placeholder) {
var itemsWithCurrentPlaceholder = allTextItems
.filter(function (i) { return i.placeholders.toArray().find(function (p) { return p.name === placeholder.name; }) != null; });
if (itemsWithCurrentPlaceholder.length === 0)
return "continue";
placeholder.value = itemsWithCurrentPlaceholder[0].placeholders.toArray().find(function (p) { return p.name === placeholder.name; }).value;
};
try {
for (var _d = (e_4 = void 0, __values(newTextItem.placeholders.toArray())), _e = _d.next(); !_e.done; _e = _d.next()) {
var placeholder = _e.value;
_loop_1(placeholder);
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
}
finally { if (e_4) throw e_4.error; }
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (newTextItems_1_1 && !newTextItems_1_1.done && (_a = newTextItems_1.return)) _a.call(newTextItems_1);
}
finally { if (e_3) throw e_3.error; }
}
var replaceTextFunc = function (newItem, oldItem) {
newItem.text = oldItem.text;
if (oldItem.tags != null) {
newItem.tags = oldItem.tags;
}
};
this._replaceContentFromOldToNewItems(oldTextItems, newTextItems, replaceTextFunc, replaceAll);
var replacePlaceholderFunc = function (newItem, oldItem) {
var imageMetadata = new ImageMetaData();
imageMetadata.size = new Size(oldItem.imageContent.source.width, oldItem.imageContent.source.height);
imageMetadata.storageId = oldItem.imageContent.source.id;
imageMetadata.name = oldItem.imageContent.name;
imageMetadata.origin = oldItem.imageContent.source.origin;
imageMetadata.isVector = oldItem.imageContent.source.isVector;
imageMetadata.pageIndex = oldItem.imageContent.source.pageIndex;
commandManager.execute(ItemsCommand.setImageMetadata, { dataList: [{ item: newItem, imageData: imageMetadata, tags: oldItem.tags }] });
if (!oldItem.isEmptyContent && !newItem.isEmptyContent && oldItem.content.tags != null)
newItem.content.tags = oldItem.content.tags;
};
var isPlaceholderWithImageFilter = function (i) { return i instanceof PlaceholderItem &&
!i.isStubOrEmpty &&
i.content instanceof ImageItem; };
var oldPlaceholderItems = oldItemsCopy.filter(isPlaceholderWithImageFilter);
var newPlaceholderItems = newItems.filter(function (i) { return i instanceof PlaceholderItem; });
var allPlaceholderItems = allItems.filter(isPlaceholderWithImageFilter);
allPlaceholderItems = _.without.apply(_, __spread([allPlaceholderItems], newPlaceholderItems));
var linkedNewPlaceholders = newPlaceholderItems.filter(function (i) { return i.linkId != null; });
if (linkedNewPlaceholders.length !== 0) {
var oldPlaceholdersForRemoving_1 = new Set();
var _loop_2 = function (linkedPlaceholder) {
var oldLinkedPlaceholder = allPlaceholderItems.find(function (p) { return p.linkId === linkedPlaceholder.linkId &&
!p.isStubOrEmpty &&
p.content instanceof ImageItem; });
if (oldLinkedPlaceholder == null)
return "continue";
oldPlaceholdersForRemoving_1.add(oldLinkedPlaceholder.linkId);
replacePlaceholderFunc(linkedPlaceholder, oldLinkedPlaceholder);
newPlaceholderItems = _.without(newPlaceholderItems, linkedPlaceholder);
};
try {
for (var linkedNewPlaceholders_1 = __values(linkedNewPlaceholders), linkedNewPlaceholders_1_1 = linkedNewPlaceholders_1.next(); !linkedNewPlaceholders_1_1.done; linkedNewPlaceholders_1_1 = linkedNewPlaceholders_1.next()) {
var linkedPlaceholder = linkedNewPlaceholders_1_1.value;
_loop_2(linkedPlaceholder);
}
}
catch (e_5_1) { e_5 = { error: e_5_1 }; }
finally {
try {
if (linkedNewPlaceholders_1_1 && !linkedNewPlaceholders_1_1.done && (_c = linkedNewPlaceholders_1.return)) _c.call(linkedNewPlaceholders_1);
}
finally { if (e_5) throw e_5.error; }
}
oldPlaceholderItems = oldPlaceholderItems.filter(function (p) { return !oldPlaceholdersForRemoving_1.has(p.linkId); });
}
this._replaceContentFromOldToNewItems(oldPlaceholderItems, newPlaceholderItems, replacePlaceholderFunc, replaceAll);
};
ItemUtils._replaceContentFromOldToNewItems = function (oldItems, newItems, replaceFunc, replaceAll) {
var oldNames = oldItems.map(function (i) { return i.name; });
var equalNamesIndexes = [];
var _loop_3 = function (i) {
if (oldNames.find(function (name) { return name === newItems[i].name; })) {
oldNames.splice(oldNames.indexOf(newItems[i].name), 1);
equalNamesIndexes.push(i);
}
};
for (var i = 0; i < newItems.length; i++) {
_loop_3(i);
}
var _loop_4 = function (i) {
var currentItem = newItems[i];
var oldItem = void 0;
if (equalNamesIndexes.includes(i)) {
oldItem = oldItems.find(function (item) { return item.name === currentItem.name; });
}
else if (replaceAll && oldNames.length !== 0) {
oldName = oldNames.shift();
oldItem = oldItems.find(function (item) { return item.name === oldName; });
}
if (oldItem != null) {
replaceFunc(currentItem, oldItem.clone( /* true */));
oldItems.splice(oldItems.indexOf(oldItem), 1);
}
};
var oldName;
for (var i = 0; i < newItems.length; i++) {
_loop_4(i);
}
};
ItemUtils.getEmptyPlaceholdersFromProduct = function (product, skipLinked) {
if (skipLinked === void 0) { skipLinked = false; }
var linkIds = [];
return product.getAllItems({ flatGroupItems: true, ignoreMockups: true }).filter(function (item) {
if (!(item instanceof PlaceholderItem) ||
!item.isStubOrEmpty ||
item.parentContainer == null || item.parentContainer.name !== Configuration.MAIN_CONTAINER_NAME)
return false;
if (skipLinked)
return true;
if (item.linkId != null) {
if (linkIds.includes(item.linkId))
return false;
linkIds.push(item.linkId);
}
return true;
});
};
ItemUtils.waitForItemsUpdated = function (items, canvas) {
return __awaiter(this, void 0, void 0, function () {
var nestedInGroupItems, handlers;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
nestedInGroupItems = items.filter(function (item) { return item instanceof GroupItem; })
.map(function (item) { return item.getNestedItems(true); })
.reduce(function (arr, items) { return (__spread(arr, items)); }, []);
handlers = items.concat(nestedInGroupItems).map(function (i) { return canvas.getItemHandler(i); });
return [4 /*yield*/, canvas.waitUpdate(handlers)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
;
ItemUtils.isTextItemHandlerReady = function (item, productHandler) {
if (item instanceof BaseTextItem) {
var itemHandler = productHandler.getHandler(item);
if (itemHandler instanceof BaseTextItemHandler && itemHandler.currentTextImage.cacheFileId == null)
return false;
if (itemHandler instanceof NewBaseTextItemHandler && !itemHandler.ready)
return false;
}
return true;
};
ItemUtils.alignHandlerToRect = function (itemHandler, rectangle, item) {
var textHorizontalAlignment = item instanceof BaseTextItem ? item.alignment : TextAlignment.Left;
var textVerticalAlignment = item instanceof BoundedTextItem ? item.verticalAlignment : TextVerticalAlignment.Top;
var horizontalAlignment = OriginPointType.Center;
var verticalAlignment = OriginPointType.Center;
switch (textHorizontalAlignment) {
case TextAlignment.Left:
case TextAlignment.LastLeft:
case TextAlignment.Justify:
horizontalAlignment = OriginPointType.Left;
break;
case TextAlignment.Right:
case TextAlignment.LastRight:
horizontalAlignment = OriginPointType.Right;
break;
}
switch (textVerticalAlignment) {
case TextVerticalAlignment.Top:
verticalAlignment = OriginPointType.Top;
break;
case TextVerticalAlignment.Bottom:
verticalAlignment = OriginPointType.Bottom;
break;
}
var itemHandlerRectangle = itemHandler.rectangle;
itemHandler.angle = rectangle.angle;
var targetRect = alignRectToRect(itemHandlerRectangle, rectangle, horizontalAlignment, verticalAlignment);
itemHandler.setRectangle(targetRect);
};
ItemUtils.isRotated = function (item, contentAngle) {
return !EqualsOfFloatNumbers(normalizeAngle(Math.round(item.transform.angle + contentAngle)), 0);
};
ItemUtils.getColorPalette = function (item, colorPreviewService) {
return __awaiter(this, void 0, void 0, function () {
var promises;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
promises = item.colorPalette.select(function (color) { return __awaiter(_this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = {
color: color
};
return [4 /*yield*/, colorPreviewService.getPreviewAsync(color)];
case 1: return [2 /*return*/, (_a.preview = _b.sent(),
_a)];
}
});
}); }).toArray();
return [4 /*yield*/, Promise.all(promises)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
ItemUtils._designAtomsApiClient = null;
ItemUtils.setOverlayEffectColor = function (item, color) {
if (item == null)
return;
var overlayEffect = ItemUtils._getItemOverlayEffect(item);
overlayEffect.color = color;
};
ItemUtils.applyOverlayEffect = function (item, overlayEffect) {
if (item == null || overlayEffect == null)
return;
var itemOverlayEffect = ItemUtils._getItemOverlayEffect(item);
itemOverlayEffect.color = overlayEffect.color;
itemOverlayEffect.opacity = overlayEffect.opacity;
};
ItemUtils._getItemOverlayEffect = function (item) {
if (item instanceof ImageItem) {
item.overlayEffect = item.overlayEffect != null ? item.overlayEffect : new OverlayEffect();
return item.overlayEffect;
}
else {
item.contentOverlayEffect = item.contentOverlayEffect != null ? item.contentOverlayEffect : new OverlayEffect();
return item.contentOverlayEffect;
}
};
return ItemUtils;
}());
export { ItemUtils };
export var UpdatePhase;
(function (UpdatePhase) {
UpdatePhase[UpdatePhase["InProgress"] = 0] = "InProgress";
UpdatePhase[UpdatePhase["Final"] = 1] = "Final";
})(UpdatePhase || (UpdatePhase = {}));
//# sourceMappingURL=ItemUtils.js.map