UNPKG

@aurigma/design-atoms

Version:

Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.

684 lines 36 kB
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 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"; export class ItemUtils { static set designAtomsApiClient(designAtomsApiClient) { this._designAtomsApiClient = designAtomsApiClient; } static isBgContainerItem(item) { var pc = item.parentContainer; if (pc instanceof SurfaceContainer) { return item.parentContainer instanceof SurfaceContainer && Utils.stringEquals(item.parentContainer.name, Configuration.BG_CONTAINER_NAME, true); } } static isFgContainerItem(item) { return item.parentContainer instanceof SurfaceContainer && Utils.stringEquals(item.parentContainer.name, Configuration.FG_CONTAINER_NAME, true); } static isImage(item) { return (item instanceof ImageItem || item instanceof PlaceholderItem) && !ItemUtils.isBgContainerItem(item); } static isEmptyPlaceholder(item) { return item instanceof PlaceholderItem && item.isStubOrEmpty; } static isDataMatrixBarcode(item) { return item instanceof BarcodeItem && item.barcodeFormat === BarcodeFormat.DATA_MATRIX || item instanceof PlaceholderItem && item.barcodeFormat == BarcodeFormat.DATA_MATRIX; } static isQrCode(item) { return item instanceof BarcodeItem && item.isQrCode || item instanceof PlaceholderItem && item.barcodeFormat == BarcodeFormat.QR_CODE; } static isLinearBarcode(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)); } static isVariableItem(item) { return item.canSetIsVariable(); } static isMultiValueItem(item) { return (item instanceof ImageItem || item instanceof BaseTextItem) && item.values.length !== 0; } static isTextType(type) { if (type === BaseTextItem) return true; return BaseTextItem.prototype.isPrototypeOf(type.prototype); } static getAllowTextFormatting(textItem, defaultValue) { var _a, _b, _c; const 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); } static allowMoveHorizontal(item) { return !item.locked && (!item.manipulationPermissions || item.manipulationPermissions.allowMoveHorizontal); } static allowMoveVertical(item) { return !item.locked && (!item.manipulationPermissions || item.manipulationPermissions.allowMoveVertical); } static allowManipulate(item) { return !item.locked && (!item.manipulationPermissions || item.manipulationPermissions.allowMoveVertical || item.manipulationPermissions.allowMoveHorizontal || item.manipulationPermissions.allowDelete || item.manipulationPermissions.allowRotate); } static clearImageContent(placeHolder) { if (placeHolder == null) return; const 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; } } static getImageItem(item) { if (item == null) return null; if (item instanceof ImageItem) { return item; } else { const 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!"); } } } static getImagePermissions(item) { if (item == null) return null; if (item instanceof ImageItem) return item.imagePermissions; return item.getImagePermissions(); } static getImageSizeInPoints(source) { var _a, _b, _c, _d, _e, _f; const 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; } static getContentEffect(item) { if (item.content instanceof ImageItem) return item.content.effect; return item.contentEffect; } static getAllowChangeContent(item) { if (item instanceof BarcodeItem || item instanceof PlaceholderItem && item.isBarcodePlaceholder) { const barcodePermissions = ItemUtils.getBarcodePermissions(item); return barcodePermissions.allowChangeBarcodeContent; } else { const contentPermissions = ItemUtils.getImagePermissions(item); const allowChangeContent = contentPermissions != null ? contentPermissions.allowChangeImage : true; const imageItem = ItemUtils.getImageItem(item); return allowChangeContent && (imageItem == null || imageItem.values.length === 0); } } static async getImageMetaDataFromFile(appDomainUrl = undefined, filePath, userId = null) { return this._designAtomsApiClient.getImageMetaDataFromFile(filePath, userId, appDomainUrl); } static async getImageMetaDataFromDesignImage(appDomainUrl = undefined, designImageName) { return this._designAtomsApiClient.getImageMetaDataFromDesignImage(designImageName, appDomainUrl); } static async getImageMetadataFromRemoteFile(appDomainUrl = undefined, url) { return this._designAtomsApiClient.getImageMetadataFromRemoteFile(url, appDomainUrl); } static getTextFromRichTextItem(item) { return Utils.getTextFromXml(item.text); } static getMaxFontSize(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; const 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(...fontSizes); //#region local funcs function parseSizeableNode(node) { const style = parseXmlStyle(node); if (style != null && style.has("font-size")) fontSizes.push(parseFloat(style.get("font-size"))); } function parseXmlStyle(node) { const styleAttr = node.attributes.getNamedItem("style"); if (styleAttr == null || styleAttr.value == null) return null; const nodeStyleParts = styleAttr.value.split(";"); const styleMap = new Map(); for (let stylePart of nodeStyleParts) { stylePart = stylePart.trim(); if (stylePart == null || stylePart === "") continue; const content = stylePart.split(":"); const key = content[0].trim(); const value = content[1].trim(); styleMap.set(key, value); } return styleMap; } function walkNodes(gmXml, nodeNames, parseNode) { const xmlDoc = new DOMParser().parseFromString(`<body>${gmXml}</body>`, "application/xml"); let filter = { acceptNode: (node) => { const nodeName = node.nodeName.toLowerCase(); return nodeNames.includes(nodeName) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; } }; if (Environment.IsIE()) filter = makeIeCompatible(filter); // @ts-ignore const walker = document.createTreeWalker(xmlDoc.childNodes[0], NodeFilter.SHOW_ELEMENT, filter, false); while (walker.nextNode()) { const node = walker.currentNode; parseNode(node); } function makeIeCompatible(filter) { // @ts-ignore return filter.acceptNode; } } //#endregion } static getBarcodeItem(item) { if (item == null) return null; if (item instanceof BarcodeItem) return item; else { const content = item.content; if (content instanceof BarcodeItem) return content; else if (content == null) return null; else throw new Exception("Wrong placeholder content!"); } } static getBarcodePermissions(item) { if (item == null) return null; if (item instanceof BarcodeItem) return item.barcodePermissions; if (item.contentPermissions != null) return item.contentPermissions.barcodePermissions; const content = item.content; if (content instanceof BarcodeItem) return content.barcodePermissions; return null; } static getImageUrlFromImageMetadata(imageMetadata, canvas, width, height, keepProportions) { const w = width != null ? width : imageMetadata.size.width; const h = height != null ? height : imageMetadata.size.height; const kp = keepProportions != null ? keepProportions : false; return ImageUtils.getImageUrl(canvas.renderingConfigProvider, canvas.viewer.designAtomsApiClient, imageMetadata.storageId, w, h, null, null, kp, null, imageMetadata.pageIndex); } static updateItems(items, productHandler, canvas, options) { options = Utils.normalize(options, { addToHistory: true, updatePhase: UpdatePhase.Final, redraw: true }); if (items.length === 0) return; for (let item of items) this._updateItem(productHandler, item, options, canvas); if (options.redraw) productHandler.redraw(); } static _updateItem(productHandler, item, options, canvas) { const 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); } static _updateImageItem(imgItem, imgItemHandler, options, canvas) { imgItemHandler.quickUpdate(); if (options.updatePhase === UpdatePhase.Final) { imgItem.getItemChangedEvent().fire(); imgItemHandler.update(); canvas.updateTexts(); } } static _updatePlaceholderItem(phItem, phItemHandler, options, canvas) { if (phItem.content != null) this._updateImageItem(phItem.content, phItemHandler.content, options, canvas); if (!this._hidePlaceholderButtonWhileImageLoad(phItemHandler)) phItemHandler.update(); } static _hidePlaceholderButtonWhileImageLoad(placeholderItemHandler) { if (placeholderItemHandler.isEmptyContent() || (!placeholderItemHandler.getPermissions().showSelectButton && !placeholderItemHandler.getPermissions().showHandleButton)) return false; var readyHandler = (handler) => { handler.removeReady(readyHandler); placeholderItemHandler.getPermissions().showSelectButton = true; placeholderItemHandler.update(); }; placeholderItemHandler.content.addReady(readyHandler); placeholderItemHandler.getPermissions().showSelectButton = false; placeholderItemHandler.update(); return true; } static getItemBoundsForViolationCheck(handler) { if (handler instanceof PlaceholderItemHandler) { return handler.getBoundsIncludingFrames(); } else { return handler.bounds; } } static createCloneName(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 = (checkName) => allItems.some(it => 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); } static createImageContentForPlaceholder(placeholder, metadata, productHandler, hiResOutputDpi) { var _a; if (placeholder.isBarcodePlaceholder !== (metadata instanceof BarcodeData)) return null; const placeholderHandler = productHandler.getHandler(placeholder); const rect = placeholderHandler.getTransformedRectangle(false); rect.angle = 0; let newContent; const oldContent = placeholder.content; const contentPerms = placeholder.contentPermissions; if (placeholder.isBarcodePlaceholder && metadata instanceof BarcodeData) { const barcodeRect = rect.clone(); const newRectSize = fitSizeToSize(ItemsDataApplier.getBarcodeRatio(metadata.barcodeFormat), new Size(rect.width, rect.height)); barcodeRect.width = newRectSize.width; barcodeRect.height = newRectSize.height; let newBarcodeOptions; 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); const 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(); } const 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; } static positionItemInArea(productHandler, item, boundsWidth, boundsHeight, ignoreRotate = true, targetRegion = null, oldCenterPoint = null, relativeToPrintArea = true) { if (item instanceof GroupItem) return item.getNestedItems(true).forEach(item => ItemUtils.positionItemInArea(productHandler, item, boundsWidth, boundsHeight, ignoreRotate, targetRegion, oldCenterPoint, relativeToPrintArea)); const targetContainer = productHandler.userEditContainer; const region = targetRegion != null ? targetRegion.toRectangleF() : targetContainer.region; const isRegion = region != null; const surface = (targetContainer.parentComponent); const printAreaContainerBounds = surface.printAreas.getItem(0).bounds; const targetAreaBounds = !isRegion ? printAreaContainerBounds : region; const targetAreaCenter = targetAreaBounds.center; const targetAreaVisualSize = !ignoreRotate ? productHandler.getVisualSize(ISize.from(targetAreaBounds)) : ISize.from(targetAreaBounds); const multiplier = Math.min(targetAreaVisualSize.width / boundsWidth, targetAreaVisualSize.height / boundsHeight); const oldCenter = oldCenterPoint != null ? oldCenterPoint : new PointF(boundsWidth / 2, boundsHeight / 2); const transformFunc = (i) => { const 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) { const newBaselineX = actualCenter.x + multiplier * (i.baselineLocation.x - oldCenter.x); const newBaselineY = actualCenter.y + multiplier * (i.baselineLocation.y - oldCenter.y); i.baselineLocation.x = newBaselineX; i.baselineLocation.y = newBaselineY; } else { const itemHandler = productHandler.getHandler(i); const rect = itemHandler.getTransformedRectangle(relativeToPrintArea); const newCenterX = actualCenter.x + multiplier * (rect.centerX - oldCenter.x); const 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; } } static rotateItems(productHandler, items, rotateCenter, angle) { const rotateFunc = (item) => { if (item instanceof GroupItem) return item.applyToItems(rotateFunc); const handler = productHandler.getHandler(item); const itemRect = handler.getTransformedRectangle(false); itemRect.rotateAt(angle, rotateCenter); const 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(item => rotateFunc(item)); } static changeItemsContent(product, productHandler, commandManager, oldItems, newItems, replaceAll) { const oldItemsCopy = oldItems.map(i => i.clone( /* true */)); const oldGroupItems = oldItemsCopy.filter(i => i instanceof GroupItem); const newGroupItems = newItems.filter(i => i instanceof GroupItem); const replaceGroupItemContent = (newItem, oldItem) => this.changeItemsContent(product, productHandler, commandManager, oldItem.items.toArray(), newItem.items.toArray(), replaceAll); this._replaceContentFromOldToNewItems(oldGroupItems, newGroupItems, replaceGroupItemContent, replaceAll); const oldTextItems = oldItemsCopy.filter(i => i instanceof BaseTextItem); let newTextItems = newItems.filter(i => i instanceof BaseTextItem); const allItems = product.getAllItems({ ignoreMockups: false, flatGroupItems: true }); let allTextItems = allItems.filter(i => i instanceof BaseTextItem); allTextItems = allTextItems.filter((item) => !newTextItems.includes(item)); for (let newTextItem of newTextItems) { if (newTextItem.placeholders.length === 0) continue; for (let placeholder of newTextItem.placeholders.toArray()) { const itemsWithCurrentPlaceholder = allTextItems .filter(i => i.placeholders.toArray().find(p => p.name === placeholder.name) != null); if (itemsWithCurrentPlaceholder.length === 0) continue; placeholder.value = itemsWithCurrentPlaceholder[0].placeholders.toArray().find(p => p.name === placeholder.name).value; } } const replaceTextFunc = (newItem, oldItem) => { newItem.text = oldItem.text; if (oldItem.tags != null) { newItem.tags = oldItem.tags; } }; this._replaceContentFromOldToNewItems(oldTextItems, newTextItems, replaceTextFunc, replaceAll); const replacePlaceholderFunc = (newItem, oldItem) => { const 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; }; const isPlaceholderWithImageFilter = (i) => i instanceof PlaceholderItem && !i.isStubOrEmpty && i.content instanceof ImageItem; let oldPlaceholderItems = oldItemsCopy.filter(isPlaceholderWithImageFilter); let newPlaceholderItems = newItems.filter(i => i instanceof PlaceholderItem); let allPlaceholderItems = allItems.filter(isPlaceholderWithImageFilter); allPlaceholderItems = allPlaceholderItems.filter(item => !newPlaceholderItems.includes(item)); const linkedNewPlaceholders = newPlaceholderItems.filter(i => i.linkId != null); if (linkedNewPlaceholders.length !== 0) { const oldPlaceholdersForRemoving = new Set(); for (let linkedPlaceholder of linkedNewPlaceholders) { const oldLinkedPlaceholder = allPlaceholderItems.find(p => p.linkId === linkedPlaceholder.linkId && !p.isStubOrEmpty && p.content instanceof ImageItem); if (oldLinkedPlaceholder == null) continue; oldPlaceholdersForRemoving.add(oldLinkedPlaceholder.linkId); replacePlaceholderFunc(linkedPlaceholder, oldLinkedPlaceholder); newPlaceholderItems = newPlaceholderItems.filter((item) => linkedPlaceholder != linkedPlaceholder); } oldPlaceholderItems = oldPlaceholderItems.filter(p => !oldPlaceholdersForRemoving.has(p.linkId)); } this._replaceContentFromOldToNewItems(oldPlaceholderItems, newPlaceholderItems, replacePlaceholderFunc, replaceAll); } static _replaceContentFromOldToNewItems(oldItems, newItems, replaceFunc, replaceAll) { const oldNames = oldItems.map(i => i.name); const equalNamesIndexes = []; for (let i = 0; i < newItems.length; i++) { if (oldNames.find(name => name === newItems[i].name)) { oldNames.splice(oldNames.indexOf(newItems[i].name), 1); equalNamesIndexes.push(i); } } for (let i = 0; i < newItems.length; i++) { const currentItem = newItems[i]; let oldItem; if (equalNamesIndexes.includes(i)) { oldItem = oldItems.find(item => item.name === currentItem.name); } else if (replaceAll && oldNames.length !== 0) { var oldName = oldNames.shift(); oldItem = oldItems.find(item => item.name === oldName); } if (oldItem != null) { replaceFunc(currentItem, oldItem.clone( /* true */)); oldItems.splice(oldItems.indexOf(oldItem), 1); } } } static getEmptyPlaceholdersFromProduct(product, skipLinked = false) { const linkIds = []; return product.getAllItems({ flatGroupItems: true, ignoreMockups: true }).filter(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; }); } static async waitForItemsUpdated(items, canvas) { const nestedInGroupItems = items.filter(item => item instanceof GroupItem) .map((item) => item.getNestedItems(true)) .reduce((arr, items) => ([...arr, ...items]), []); const handlers = items.concat(nestedInGroupItems).map(i => canvas.getItemHandler(i)); await canvas.waitUpdate(handlers); } ; static isTextItemHandlerReady(item, productHandler) { if (item instanceof BaseTextItem) { const itemHandler = productHandler.getHandler(item); if (itemHandler instanceof BaseTextItemHandler && itemHandler.currentTextImage.cacheFileId == null) return false; if (itemHandler instanceof NewBaseTextItemHandler && !itemHandler.ready) return false; } return true; } static alignHandlerToRect(itemHandler, rectangle, item) { const textHorizontalAlignment = item instanceof BaseTextItem ? item.alignment : TextAlignment.Left; const textVerticalAlignment = item instanceof BoundedTextItem ? item.verticalAlignment : TextVerticalAlignment.Top; let horizontalAlignment = OriginPointType.Center; let 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; } const itemHandlerRectangle = itemHandler.rectangle; itemHandler.angle = rectangle.angle; const targetRect = alignRectToRect(itemHandlerRectangle, rectangle, horizontalAlignment, verticalAlignment); itemHandler.setRectangle(targetRect); } static isRotated(item, contentAngle) { return !EqualsOfFloatNumbers(normalizeAngle(Math.round(item.transform.angle + contentAngle)), 0); } static async getColorPalette(item, colorPreviewService) { const promises = item.colorPalette.select(async (color) => { return { color: color, preview: await colorPreviewService.getPreviewAsync(color) }; }).toArray(); return await Promise.all(promises); } } ItemUtils._designAtomsApiClient = null; ItemUtils.setOverlayEffectColor = (item, color) => { if (item == null) return; let overlayEffect = ItemUtils._getItemOverlayEffect(item); overlayEffect.color = color; }; ItemUtils.applyOverlayEffect = (item, overlayEffect) => { if (item == null || overlayEffect == null) return; const itemOverlayEffect = ItemUtils._getItemOverlayEffect(item); itemOverlayEffect.color = overlayEffect.color; itemOverlayEffect.opacity = overlayEffect.opacity; }; ItemUtils._getItemOverlayEffect = (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; } }; export var UpdatePhase; (function (UpdatePhase) { UpdatePhase[UpdatePhase["InProgress"] = 0] = "InProgress"; UpdatePhase[UpdatePhase["Final"] = 1] = "Final"; })(UpdatePhase || (UpdatePhase = {})); //# sourceMappingURL=ItemUtils.js.map