@aurigma/design-atoms
Version:
Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.
413 lines • 24 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 __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
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 };
}
};
import { BaseProductCommand } from "./BaseProductCommand";
import { maybe } from "tsmonad";
import { PlaceholderItemHandler, GroupItemHandler, BaseTextItemHandler } from "../../ItemHandlers";
import * as _ from "underscore";
import { fitRectangleToRectangle, getOriginCoordinate } from "../../Utils/Math";
import { Product, PrintArea, Surface } from "@aurigma/design-atoms-model/Product";
import { Item, ImageItem } from "@aurigma/design-atoms-model/Product/Items";
import { RectangleF, Matrix, EqualsOfFloatNumbers } from "@aurigma/design-atoms-model/Math";
import { Exception, ArgumentException, NotImplementedException } from "@aurigma/design-atoms-model/Exception";
import { ItemsCommand, OriginPointType, ResizeRectangleType } from "@aurigma/design-atoms-interfaces";
var ResizeCommand = /** @class */ (function (_super) {
__extends(ResizeCommand, _super);
function ResizeCommand(historyArgs, product, args, _productHandler, _commandManager, _canvas) {
var _this = _super.call(this, product, historyArgs, args) || this;
_this._productHandler = _productHandler;
_this._commandManager = _commandManager;
_this._canvas = _canvas;
_this._executeCommandBody = function () { return __awaiter(_this, void 0, void 0, function () {
var target, itemHandlers, canvasItemHandlers_1;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this._canvas != null)
this._canvas.pauseRedraw();
_a.label = 1;
case 1:
_a.trys.push([1, , 4, 7]);
target = this._convertedArgs.target;
itemHandlers = this._items.map(this._productHandler.getHandler);
if (!(this._canvas != null)) return [3 /*break*/, 3];
canvasItemHandlers_1 = this._canvas.getAllItemHandlers();
return [4 /*yield*/, Promise.all(itemHandlers.filter(function (handler) { return handler instanceof BaseTextItemHandler && !canvasItemHandlers_1.includes(handler); }).map(function (h) {
h.updateForExternalCanvas(_this._canvas);
return h.waitUpdate();
}))];
case 2:
_a.sent();
_a.label = 3;
case 3:
itemHandlers.forEach(function (handler) {
handler.startTransform();
handler.beginUpdate();
});
if (target instanceof Product) {
this._resizeProduct(target);
if (this._canvas != null) {
this._canvas.viewer._onResize(this, false);
}
}
else if (target instanceof PrintArea) {
this._resizePrintArea(target);
}
else if (_.isArray(target)) {
if (target[0] instanceof Surface) {
target.forEach(function (s) { return _this._resizeSurface(s); });
}
else if (target[0] instanceof Item) {
this._resizeItems(target);
}
}
this._items.map(this._productHandler.getHandler).forEach(function (handler) {
handler.endTransform(true, true);
handler.endUpdate();
});
return [3 /*break*/, 7];
case 4:
if (!(this._canvas != null)) return [3 /*break*/, 6];
return [4 /*yield*/, this._canvas.waitUpdate()];
case 5:
_a.sent();
this._canvas.updateSelection();
this._canvas.continueRedraw();
this._canvas.updateTexts();
_a.label = 6;
case 6: return [7 /*endfinally*/];
case 7: return [2 /*return*/];
}
});
}); };
_this._resizeProduct = function (product) {
product.surfaces.forEach(function (s) { return _this._resizeSurface(s); });
};
_this._resizeSurface = function (surface) {
var _a, _b;
var surfaceRect = new RectangleF(0, 0, surface.width, surface.height);
var originX = (_a = _this._getResizeOptions().originX) !== null && _a !== void 0 ? _a : OriginPointType.Left;
var originY = (_b = _this._getResizeOptions().originY) !== null && _b !== void 0 ? _b : OriginPointType.Top;
var matrix = _this._getTransformMatrix(surfaceRect, originX, originY);
surface.mockup.allContainers.forEach(function (c) { return _this._resizeMockupContainer(c, matrix, surface); });
surface.printAreas.forEach(function (p) { return _this._resizePrintAreaBounds(p, matrix); });
surface.containers.forEach(function (c) { return _this._resizeContainer(c, matrix, surface); });
matrix.updateObjectByMatrix(surface, "width", "height");
};
_this._resizeMockupContainer = function (container, matrix, surface) {
if (container.size != null)
container.size.updateByMatrix(matrix);
_this._resizeContainer(container, matrix, surface);
};
/*send printArea argument for resize items within printArea only. Other items will moved*/
_this._resizeContainer = function (container, matrix, surface, printArea) {
if (printArea === void 0) { printArea = null; }
if (container.region != null)
container.region.updateByMatrix(matrix);
var isItemInPrintArea = function (item) {
return printArea.bounds.intersectsWith(_this._productHandler.getHandler(item).bounds);
};
var items = container.items.toArray().filter(function (i) { return printArea == null || isItemInPrintArea(i); });
var resizeType = _this._getResizeOptions(container).resize;
var itemMatrix = _this._getItemsMatrix(items, resizeType, matrix, surface);
var resetPlaceholderContent = _this._getResizeOptions(container).resetPlaceholderContent;
container.items.forEach(function (i) {
var targetMatrix = printArea != null ?
_this._getTranslateMatrixRelativeToPrintArea(printArea.bounds, _this._productHandler.getHandler(i).bounds, isItemInPrintArea(i) ? itemMatrix : matrix) :
itemMatrix;
_this._resizeItem(i, targetMatrix, resetPlaceholderContent);
});
};
_this._resizeItems = function (items) {
var _a, _b;
var resize = _this._getResizeOptions().resize;
if (resize === ResizeRectangleType.Original)
throw new Exception("Original type not supported when resizing items.");
var overallBounds;
if (items.length === 1) {
var rect = _this._productHandler.getHandler(items[0]).rectangle;
rect.angle = 0;
overallBounds = rect.bounds;
}
else {
overallBounds = _this._getItemsBounds(items);
}
var originX = (_a = _this._getResizeOptions().originX) !== null && _a !== void 0 ? _a : OriginPointType.Center;
var originY = (_b = _this._getResizeOptions().originY) !== null && _b !== void 0 ? _b : OriginPointType.Center;
var originMatrix = _this._getTransformMatrix(overallBounds, originX, originY);
var matrix = _this._getItemsMatrix(items, _this._getResizeOptions().resize, originMatrix, null);
items.forEach(function (i) { var _a; return _this._resizeItem(i, matrix, (_a = _this._defaultResizeOptions.resetPlaceholderContent) !== null && _a !== void 0 ? _a : true); });
};
_this._resizeItem = function (item, matrix, resetPlaceholderContent) {
var updateHandler = function (handler) {
var _a;
handler.transformByMatrix(matrix, false);
var item = handler.item;
if (item instanceof ImageItem) {
(_a = item.values) === null || _a === void 0 ? void 0 : _a.filter(function (i) { return (i === null || i === void 0 ? void 0 : i.transformedRectangle) != null; }).forEach(function (v) {
v.transformedRectangle = v.transformedRectangle.transformByMatrix(matrix);
});
}
};
var resetPlaceholderHandler = function (handler) {
if (resetPlaceholderContent && handler.content != null)
handler.content.updateRectangle(false, handler.item.contentResizeMode, handler);
};
var itemHandler = _this._productHandler.getHandler(item);
updateHandler(itemHandler);
if (itemHandler instanceof PlaceholderItemHandler) {
itemHandler.updateContentAndFrames(updateHandler);
resetPlaceholderHandler(itemHandler);
}
if (itemHandler instanceof GroupItemHandler)
itemHandler.itemHandlers.toArray().filter(function (i) { return i instanceof PlaceholderItemHandler; }).forEach(resetPlaceholderHandler);
};
_this._resizePrintAreaBounds = function (printArea, matrix) {
printArea.bounds.updateByMatrix(matrix);
};
_this._resizePrintArea = function (printArea) {
var surface = _this._product.surfaces.toArray().find(function (s) { return s.printAreas.contains(printArea); });
var matrix = _this._getMatrixForPrintArea(printArea);
surface.containers.forEach(function (c) { return _this._resizeContainer(c, matrix, surface, printArea); });
surface.printAreas.forEach(function (p) {
if (p !== printArea)
_this._resizePrintAreaBounds(p, _this._getTranslateMatrixRelativeToPrintArea(printArea.bounds, p.bounds, matrix));
});
_this._resizePrintAreaBounds(printArea, matrix);
_this._resizeSurfaceByPrintArea(surface);
};
_this._resizeSurfaceByPrintArea = function (surface) {
var overallBounds = RectangleF.getOverallBounds(surface.printAreas.toArray().map(function (p) { return p.bounds; }));
var surfaceRect = new RectangleF(0, 0, surface.width, surface.height);
if (surfaceRect.containsRectangle(overallBounds))
return;
surface.width = Math.max(surface.width, overallBounds.right);
surface.height = Math.max(surface.height, overallBounds.bottom);
if (overallBounds.left >= 0 || overallBounds.top >= 0)
return;
_this._commandManager.execute(ItemsCommand.translateItems, {
items: surface.getAllItems().toArray(),
translateX: -Math.min(0, overallBounds.left),
translateY: -Math.min(0, overallBounds.top)
});
};
_this._getTransformMatrix = function (initialRect, originX, originY) {
var origin = getOriginCoordinate(initialRect, originX, originY);
var matrix = new Matrix();
matrix.scaleRelativeToPoint(_this._getScaleMultiplier(_this._args.width, initialRect.width), _this._getScaleMultiplier(_this._args.height, initialRect.height), origin);
return matrix;
};
_this._getScaleMultiplier = function (value, parentSize) {
if (typeof value === "string") {
if (/%$/.test(value)) {
var percent = Number(value.split(/%/)[0]);
return percent / 100;
}
else {
var parsedValue = parseFloat(value);
if (isNaN(parsedValue))
throw new ArgumentException("ResizeCommand: Wrong string format: " + value);
else
value = parsedValue;
}
}
if (value <= 0)
throw new ArgumentException("ResizeCommand: Wrong value: " + value);
if (parentSize <= 0)
throw new ArgumentException("ResizeCommand: Wrong parentSize: " + parentSize);
return value / parentSize;
};
_this._convertedArgs = _this._args.target != null ?
_this._args :
_this._convertExternalConfig(_this._args);
return _this;
}
Object.defineProperty(ResizeCommand.prototype, "_items", {
get: function () {
var target = this._convertedArgs.target;
if (target instanceof Product)
return target.getAllItems();
if (target instanceof PrintArea) {
var surface = this._product.surfaces.firstOrDefault(function (s) { return s.printAreas.contains(target); });
if (surface == null)
return [];
return surface.getAllItems().toArray();
}
if (!_.isArray(target))
return [];
if (target[0] instanceof Item)
return target;
if (target[0] instanceof Surface)
return _.flatten(target.map(function (s) { return s.getAllItems().toArray(); }));
return [];
},
enumerable: true,
configurable: true
});
ResizeCommand.prototype._getTranslateMatrixRelativeToPrintArea = function (printAreaBounds, bounds, originalMatrix) {
var result = new Matrix();
var isItemInLeftOrTopPart = bounds.bottom <= printAreaBounds.top ||
bounds.right <= printAreaBounds.left;
if (isItemInLeftOrTopPart)
return result;
if (printAreaBounds.intersectsWith(bounds))
return originalMatrix;
var newPrintAreaBounds = printAreaBounds.clone().updateByMatrix(originalMatrix);
result.translate(bounds.left > printAreaBounds.right || EqualsOfFloatNumbers(printAreaBounds.right - bounds.left, 0) ? newPrintAreaBounds.right - printAreaBounds.right : 0, bounds.top > printAreaBounds.bottom || EqualsOfFloatNumbers(printAreaBounds.bottom - bounds.top, 0) ? newPrintAreaBounds.bottom - printAreaBounds.bottom : 0);
return result;
};
ResizeCommand.prototype._getItemsMatrix = function (items, resizeType, originMatrix, originSurface) {
var _a, _b;
var itemsRectMatrix;
if (resizeType !== ResizeRectangleType.Original) {
var initialItemsRect = this._getItemsBounds(items);
var targetItemRect = initialItemsRect.clone().updateByMatrix(originMatrix);
var forceFit = resizeType === ResizeRectangleType.Arbitrary && items.some(function (i) { return i.transform.angle % 90 !== 0; });
var targetFittedRect = fitRectangleToRectangle(initialItemsRect, targetItemRect, forceFit ? ResizeRectangleType.Fit : resizeType);
itemsRectMatrix = RectangleF.getMatrix(initialItemsRect, targetFittedRect);
}
else {
var originX = (_a = this._getResizeOptions().originX) !== null && _a !== void 0 ? _a : OriginPointType.Center;
var originY = (_b = this._getResizeOptions().originY) !== null && _b !== void 0 ? _b : OriginPointType.Center;
itemsRectMatrix = this._getTranslateMatrixForOriginalMode(originMatrix, originSurface, originX, originY);
}
return itemsRectMatrix;
};
ResizeCommand.prototype._getTranslateMatrixForOriginalMode = function (originMatrix, originSurface, originX, originY) {
var initialRect = new RectangleF(0, 0, originSurface.width, originSurface.height);
var initialOrigin = getOriginCoordinate(initialRect, originX, originY);
var finalRect = initialRect.updateByMatrix(originMatrix);
var finalOrigin = getOriginCoordinate(finalRect, originX, originY);
var matrix = new Matrix();
matrix.translate(finalOrigin.x - initialOrigin.x, finalOrigin.y - initialOrigin.y);
return matrix;
};
ResizeCommand.prototype._getResizeOptions = function (container) {
var _this = this;
return maybe(this._args.containerOptions)
.bind(function (options) { return maybe(container).map(function (c) { return options[c.name]; }); })
.caseOf({
just: function (opt) { return (__assign(__assign({}, _this._defaultResizeOptions), opt)); },
nothing: function () { return _this._defaultResizeOptions; }
});
};
Object.defineProperty(ResizeCommand.prototype, "_defaultResizeOptions", {
get: function () {
return __assign({ resize: ResizeRectangleType.Fit, resetPlaceholderContent: true }, (this._args.defaultOptions || {}));
},
enumerable: true,
configurable: true
});
ResizeCommand.prototype._getItemsBounds = function (items) {
var _this = this;
if (_.isEmpty(items))
return RectangleF.empty;
return RectangleF.getOverallBounds(items.map(function (i) { return _this._productHandler.getHandler(i).bounds; }));
};
ResizeCommand.prototype._getMatrixForPrintArea = function (printArea) {
var _a, _b;
var originX = (_a = this._getResizeOptions().originX) !== null && _a !== void 0 ? _a : OriginPointType.Left;
var originY = (_b = this._getResizeOptions().originY) !== null && _b !== void 0 ? _b : OriginPointType.Top;
return this._getTransformMatrix(printArea.bounds, originX, originY);
};
ResizeCommand.prototype._convertExternalConfig = function (externalConfig) {
var target;
switch (externalConfig.targetType) {
case "surfaces":
if (_.isEmpty(externalConfig.targetIds))
throw new ArgumentException("ResizeCommand: target Ids cannot be empty");
target = this._product.surfaces.toArray().filter(function (s) { return externalConfig.targetIds.includes(s.id); });
break;
case "items":
if (_.isEmpty(externalConfig.targetIds))
throw new ArgumentException("ResizeCommand: target Ids cannot be empty");
target = this._productHandler.currentSurface
.getAllItems({ ignoreMockups: false, flatGroupItems: true })
.toArray()
.filter(function (s) { return externalConfig.targetIds.includes(s.id); });
break;
case "printArea":
if (_.isEmpty(externalConfig.targetIds))
throw new ArgumentException("ResizeCommand: target Ids cannot be empty");
target = _.flatten(this._product.surfaces.toArray().map(function (s) { return s.printAreas.toArray(); })).find(function (p) { return externalConfig.targetIds.includes(p.id); });
break;
default:
target = this._product;
break;
}
return {
target: target,
width: externalConfig.width,
height: externalConfig.height,
containerOptions: externalConfig.containerOptions,
defaultOptions: externalConfig.defaultOptions
};
};
ResizeCommand.prototype.redo = function () {
throw new NotImplementedException();
};
ResizeCommand.prototype.undo = function () {
throw new NotImplementedException();
};
return ResizeCommand;
}(BaseProductCommand));
export { ResizeCommand };
//# sourceMappingURL=ResizeCommand.js.map