@aurigma/design-atoms
Version:
Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.
442 lines • 18.5 kB
JavaScript
import { TextAlignment } from "@aurigma/design-atoms-model/Product/Items";
import { RectangleItemHandler } from "./RectangleItemHandler";
import { BaseTextHandlerData } from "./BaseTextHandlerData";
import { ImageContainer } from "./ImageContainer";
import { Graphics } from "../Graphics";
import { TextRenderer } from "../InPlace/TextRenderer";
import * as Utils from "@aurigma/design-atoms-model/Utils/Utils";
import { Path, Transform } from "@aurigma/design-atoms-model";
export class BaseTextItemHandler extends RectangleItemHandler {
constructor(item, textWhizz = null, apiClient, colorPreviewService) {
super(item, textWhizz, apiClient, colorPreviewService);
this._defaultWidth = 10;
this._currentTextImage = null;
this._onCanvasChangedDelegate = null;
this._updatedFromServer = false;
this._isLegacyTextEditor = false;
this._isUpdatingAfterResize = false;
this._height = 0;
this._updateTextsFunc = () => {
if (this.canvas != null)
this.canvas.updateTexts();
};
this._imageContainer = new ImageContainer(this._onImageLoaded.bind(this));
this._allowNegativeResize = false;
}
get item() {
return this._getItem();
}
set item(item) {
super._setItem(item);
}
get isLegacyTextEditor() {
return this._isLegacyTextEditor;
}
get currentTextImage() {
return this._currentTextImage != null
? this._currentTextImage
: (this._currentTextImage = new TextImageData());
}
set currentTextImage(value) {
var _a, _b, _c;
const oldCacheFileId = (_a = this._currentTextImage) === null || _a === void 0 ? void 0 : _a.cacheFileId;
const newCacheFileId = value === null || value === void 0 ? void 0 : value.cacheFileId;
if (oldCacheFileId && oldCacheFileId != newCacheFileId)
(_b = this.imageLoaderService) === null || _b === void 0 ? void 0 : _b.releaseImageContainerFor(oldCacheFileId, this.uniqueId);
this._currentTextImage = value;
if (newCacheFileId && oldCacheFileId != newCacheFileId)
(_c = this.imageLoaderService) === null || _c === void 0 ? void 0 : _c.lockImageContainerFor(newCacheFileId, this.uniqueId);
this._height = this.rectangle.height;
}
get textCropped() {
if (!this.item.checkTextCrop)
return null;
return this.currentTextImage != null && this.currentTextImage.textCropped;
}
get isUpdatingAfterResize() {
return this._isUpdatingAfterResize;
}
set isUpdatingAfterResize(value) {
this._isUpdatingAfterResize = value;
}
get colorSettings() {
var _a, _b, _c, _d, _e, _f, _g, _h;
return {
rgbColorProfileName: (_b = (_a = this.canvas) === null || _a === void 0 ? void 0 : _a.renderingConfigProvider.getRgbColorProfileName()) !== null && _b !== void 0 ? _b : '',
cmykColorProfileName: (_d = (_c = this.canvas) === null || _c === void 0 ? void 0 : _c.renderingConfigProvider.getCmykColorProfileName()) !== null && _d !== void 0 ? _d : '',
grayscaleColorProfileName: (_f = (_e = this.canvas) === null || _e === void 0 ? void 0 : _e.renderingConfigProvider.getGrayscaleColorProfileName()) !== null && _f !== void 0 ? _f : '',
hiResDestinationColorProfileName: (_h = (_g = this.canvas) === null || _g === void 0 ? void 0 : _g.renderingConfigProvider.getHiResDestinationColorProfileName()) !== null && _h !== void 0 ? _h : ''
};
}
isEmptyTextPlaceholder() {
return this.item.isTextPlaceholder && this.item.text === "";
}
_cropTextLimits() {
var _a, _b;
const text = this._getText();
let updatedText = text;
const maxLineCount = (_a = this.item.maxLineCount) !== null && _a !== void 0 ? _a : 0;
const maxLineLength = (_b = this.item.maxLineLength) !== null && _b !== void 0 ? _b : 0;
if (maxLineCount > 0 || maxLineLength > 0) {
if (Utils.isValidXml(updatedText))
updatedText = Utils.getTextFromXml(text, "\n");
let textLines = updatedText.split("\n");
if (maxLineCount > 0) {
if (textLines.length > maxLineCount) {
textLines = textLines.splice(0, maxLineCount);
}
}
if (maxLineLength > 0) {
for (var i = 0; i < textLines.length; i++) {
if (textLines[i].length > maxLineLength) {
textLines[i] = textLines[i].substr(0, maxLineLength);
}
}
}
const result = textLines.join("\n");
if (text != result)
this.item.text = result;
}
}
drawItemHandler(itemHandlerCtx) {
if (itemHandlerCtx == null || this.canvas == null)
return;
if (this._getText() === "")
return;
if (!this._isReadyToDraw) {
this.canvas.drawWaitClock(itemHandlerCtx, this.rectangle.center);
return;
}
if (this._hasVectorMask()) {
itemHandlerCtx.save();
this._clip(itemHandlerCtx);
}
const item = this.item;
const rectangle = this.rectangle;
const opacityMultiplier = this.isEmptyTextPlaceholder() ? 0.5 : 1;
const { fillColorPreview, borderColorPreview, altBorderColorPreview } = this._getItemColorPreviews();
Graphics.fillRectangle(itemHandlerCtx, rectangle, fillColorPreview === null || fillColorPreview === void 0 ? void 0 : fillColorPreview.toString(), item.opacity * opacityMultiplier);
if (this._updatedFromServer === true) {
try {
const combinedImageContainer = this.canvas.service.imageLoaderService.getImageContainerFor(this.currentTextImage.cacheFileId);
if (combinedImageContainer != null) {
const combinedImageRectangle = this.canvas.service.imageLoaderService.getImageContainerRectangleFor(this.currentTextImage.cacheFileId);
TextRenderer.renderTextImage(this, combinedImageContainer, combinedImageRectangle, itemHandlerCtx, opacityMultiplier, 0);
}
else {
TextRenderer.renderTextImage(this, this._imageContainer, null, itemHandlerCtx, opacityMultiplier, 0);
}
}
catch (e) {
console.error(e);
this.update();
}
}
const borderWidth = this._getActualBorderWidth();
if (borderWidth > 0) {
rectangle.width += borderWidth;
rectangle.height += borderWidth;
const path = Path.rotatedRectangle(rectangle);
Graphics.drawStroke(itemHandlerCtx, path, rectangle.center, new Transform(), borderWidth, borderColorPreview === null || borderColorPreview === void 0 ? void 0 : borderColorPreview.toString(), altBorderColorPreview === null || altBorderColorPreview === void 0 ? void 0 : altBorderColorPreview.toString(), item.opacity * opacityMultiplier, item.dash);
}
if (this._hasVectorMask())
itemHandlerCtx.restore();
}
onResized() {
if (this.canvas != null)
this.isUpdatingAfterResize = true;
return super.onResized();
}
isEmpty() {
return this.item.isEmpty();
}
isVisible() {
let p1 = this.item.parentGroupItem == null;
let fromParentVisibility = p1 || this.item.parentGroupItem.isChildVisible(this.item);
return super.isVisible() && fromParentVisibility;
}
quickUpdate() {
this._updateImageUrl();
if (this.isVisible() &&
!this._imageContainer.source &&
this.canvas &&
!this.canvas.service.imageLoaderService.hasImageContainerFor(this.currentTextImage.cacheFileId)) {
this.update();
}
}
transformChanged() {
super.transformChanged();
if (this.isUpdating && this._callbacks) {
var t = this.item.transform.clone();
const beforeUpdate = () => {
this.item.setTransform(t, true);
};
this._callbacks.push(beforeUpdate);
}
}
_endTransform(changed, resized) {
super._endTransform(changed, resized);
if (!changed)
return;
if (resized)
this.update();
}
_getColors() {
var _a;
return [this.item.color, ...(_a = this.item.colorPalette) === null || _a === void 0 ? void 0 : _a.toArray(), ...super._getColors()];
}
dispose() {
this._imageContainer.dispose();
if (this._onCanvasChangedDelegate != null) {
if (this.canvas != null)
this.canvas.remove_zoomChanged(this._onCanvasChangedDelegate);
delete this._onCanvasChangedDelegate;
}
this.currentTextImage = null;
super.dispose();
}
_isReady() {
return super._isReady() && this._imageContainer.isLoaded;
}
async _updateImpl(beforeUpdate, afterUpdate) {
if (this.isVisible()) {
const afterTextUpdate = () => { this._afterUpdate(afterUpdate); };
this._update(null, beforeUpdate, afterTextUpdate);
}
else if (typeof beforeUpdate == "function") {
beforeUpdate();
}
}
_validateBeforeCallService() {
return this._getText() !== "";
}
_onValidateBeforeCallServiceFailed() {
if (!this._getSrc())
this._updateEmptyTextControlPoints();
else
this._setDefaultTextControlPoints();
}
_updateEmptyTextControlPoints() {
let originalText = null;
const success = (data) => {
if (this.item == null)
return;
var item = null;
if (typeof data == "object") {
item = data.item;
data = data.itemHandlerData;
}
if (item != null) {
item.text = originalText;
this._applyDataItem(item, data);
}
this.setData(data);
const canvas = this.canvas;
if (canvas != null) {
canvas.updateSelection();
canvas.redraw();
}
this.onSuccessResponse();
this._setIsImageLoaded(true);
};
const failure = (error) => {
this.onErrorResponse(error);
};
const itemHandlerData = this._createDataInstance(this);
var serializedItem = JSON.parse(this._getDataItem());
originalText = serializedItem.text;
//Send some text to the server to define controlPoints.
serializedItem.text = 'a';
var data = [JSON.stringify(itemHandlerData), serializedItem, this.colorSettings];
super._callService(`Update${this.getTypeName()}`, data, success, failure, null);
}
_setDefaultTextControlPoints() {
const alignment = this.item.alignment;
if (alignment === TextAlignment.Center) {
this._controlPoints[0].x += (this._controlPoints[1].x - this._controlPoints[0].x) / 2 - (this._defaultWidth / 2);
}
else if (alignment === TextAlignment.Right) {
this._controlPoints[0].x = this._controlPoints[1].x - this._defaultWidth;
}
this._controlPoints[1].x = this._controlPoints[0].x + this._defaultWidth;
this.raiseChanged();
const canvas = this.canvas;
if (canvas != null) {
canvas.updateSelection();
canvas.redraw();
}
this.onSuccessResponse();
}
_isLoadingImage() {
return this._imageContainer.isLoading;
}
_setIsLoadingImage(value) {
this._imageContainer.isLoading = value;
}
_setIsImageLoaded(value) {
this._imageContainer.isLoaded = value;
}
_getBoundsMargin() {
return this._getActualBorderWidth() * 2;
}
_createDataInstance(itemHandler) {
return new BaseTextHandlerData(itemHandler);
}
_onItemPropertyChanged(sender, propertyName) {
switch (propertyName) {
case "text":
if (this._isLegacyTextEditor)
this._cropTextLimits();
this.update(null, this._updateTextsFunc);
break;
case "font":
this.update(null, this._updateTextsFunc);
break;
case "underline":
case "color":
case "alignment":
case "leading":
case "tracking":
case "verticalScale":
case "horizontalScale":
case "previewScale":
case "stroke":
case "shadow":
case "baselineShift":
case "overlapLinesEnabled":
case "characterLimit":
case "maxLineCount":
case "maxLineLength":
this.update();
break;
case "checkTextCrop":
if (sender.checkTextCrop)
this.update();
break;
default:
}
super._onItemPropertyChanged(sender, propertyName);
}
_setDataItem(itemData, itemHandlerData) {
super._setDataItem(itemData, itemHandlerData);
this.item.text = itemData.text;
this.item.font = itemData.font;
this.item.leading = itemData.leading;
this.item.color = itemData.color;
this.item.stroke = itemData.stroke;
this.item.shadow = itemData.shadow;
this.item.verticalScale = itemData.verticalScale;
this.item.horizontalScale = itemData.horizontalScale;
this.item.previewScale = itemData.previewScale;
this.item.mask = itemData.mask;
this.item.baselineShift = itemData.baselineShift;
this._updateVectorMaskCenter();
}
_getSrc() {
const src = this._imageContainer.source;
return !Utils.isNullOrEmptyOrWhiteSpace(src) ? src : this._createImageUrl();
}
_onAddedOnCanvas(canvas, supressUpdate) {
super._onAddedOnCanvas(canvas, supressUpdate);
if (canvas.textEditor == null) {
this._isLegacyTextEditor = true;
this._cropTextLimits();
}
if (this.canvas != null && !this._onCanvasChangedDelegate) {
this._onCanvasChangedDelegate = this._onCanvasChanged.bind(this);
this.canvas.add_zoomChanged(this._onCanvasChangedDelegate);
}
}
_onRemovedFromCanvas(canvas) {
super._onRemovedFromCanvas(canvas);
if (canvas && this._onCanvasChangedDelegate != null) {
canvas.remove_zoomChanged(this._onCanvasChangedDelegate);
delete this._onCanvasChangedDelegate;
}
}
_getText() {
const text = this.isEmptyTextPlaceholder() ? this.item.originalText : this.item.text;
return Utils.isValidXml(text) ? this._xmlToHtml(text).textContent.trim() : text.trim();
}
_createImageUrl() {
const cv = this.canvas;
if (cv == null)
return null;
if (this.canvas.service.imageLoaderService.hasImageContainerFor(this.currentTextImage.cacheFileId))
return null;
if ((this.currentTextImage.cacheFileId == null || this.currentTextImage.cacheFileId.length === 0)
&& (this.currentTextImage.base64Image == null || this.currentTextImage.base64Image.length === 0))
return null;
if (this.currentTextImage && this.currentTextImage.base64Image) {
return 'data:image/png;base64,' + this.currentTextImage.base64Image;
}
return this._apiClient.serviceEndpoint + "/txt?" + "f=" + encodeURIComponent(this.currentTextImage.cacheFileId);
}
_updateImageUrl() {
if (this._getText() === "")
return;
if (!this.isVisible())
return;
const cv = this.canvas;
if (cv == null || !cv.isInitialized)
return;
const url = this._createImageUrl();
//console.trace(`_updateImageUrl _createImageUrl ${url}`);
if (this._imageContainer.source != null && url === this._imageContainer.source) {
if (this.isUpdatingAfterResize === true) {
this.isUpdatingAfterResize = false;
cv.redraw();
}
return;
}
if (url === null) {
this._imageContainer.clear();
cv.redraw();
}
else {
this._imageContainer.updateUrl(url);
}
}
_afterUpdate(afterUpdate) {
var _a;
if (typeof afterUpdate == "function")
afterUpdate();
if (!this._updatedFromServer)
(_a = this.canvas) === null || _a === void 0 ? void 0 : _a.updateViolationContainerPosition(this);
this._updatedFromServer = true;
if (this.canvas != null) {
this.canvas.updateSelection();
this.canvas.redrawDesign();
}
}
_xmlToHtml(xml) {
var body = new DOMParser()
.parseFromString(`<body>${xml}</body>`, "text/html")
.getElementsByTagName("body")[0];
return body;
}
_onImageLoaded() {
this.isUpdatingAfterResize = false;
this._height = this.rectangle.height;
if (this.canvas != null)
this.canvas.redraw();
this._dispatchReadyEvent();
}
_onCanvasChanged(args) {
if (args.fullUpdate)
this.update();
}
get imageLoaderService() {
var _a, _b;
return (_b = (_a = this.canvas) === null || _a === void 0 ? void 0 : _a.service) === null || _b === void 0 ? void 0 : _b.imageLoaderService;
}
}
BaseTextItemHandler.typeName = "BaseTextItemHandler";
export class TextImageData {
constructor() {
this.cacheFileId = null;
this.base64Image = null;
this.textCropped = null;
}
}
//# sourceMappingURL=BaseTextItemHandler.js.map