@aurigma/design-atoms
Version:
Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.
979 lines • 49.4 kB
JavaScript
import { Canvas } from "../Canvas";
import { BaseViewer, ZoomParams } from "./BaseViewer";
import { UpdateStatus } from "../UpdateStatus";
import { ScrollBarsStyle } from "./ScrollBarsStyle";
import { Utils as AjcUtils } from "../Utils/Common";
import { ZoomMode } from "./ZoomMode";
import { ViewportAlignment } from "./ViewportAlignment";
import { Surface } from "@aurigma/design-atoms-model/Product/Surface";
import { ArgumentNullException, Exception } from "@aurigma/design-atoms-model/Exception";
import { isEmpty, urlCombine } from "@aurigma/design-atoms-model/Utils/Utils";
import { SafetyLinesHandler } from "./SafetyLinesHandler";
import { WatermarkHandler } from "./WatermarkHandler";
import { GridHandler } from "./GridHandler";
import { EventObject } from "@aurigma/design-atoms-model/EventObject";
import { PointF, EqualsOfFloatNumbers, SizeF } from "@aurigma/design-atoms-model/Math/index";
import Environment from "@aurigma/design-atoms-model/Utils/Environment";
import * as Convert from "@aurigma/design-atoms-model/Utils/Convert";
import { CurvedTextItem, BaseTextItem } from "@aurigma/design-atoms-model/Product/Items";
import { NewBaseTextItemHandler } from "../ItemHandlers";
import { ViewerConfiguration } from "./ViewerConfiguration";
import { RenderingType, PrintArea } from "@aurigma/design-atoms-model/Product";
import { LicenseHandler } from "../License";
import { Configuration } from "@aurigma/design-atoms-model/Configuration";
import { VariableItemHelper } from "../Services/VariableItemHelper";
import { EventManager } from "../Services/EventManager";
import { ProductThemeManager } from "../Services/ProductTheme/ProductThemeManager";
import { History } from "../History";
import { SnapshotHandler } from "../History/SnapshotHandler";
import { CommandManager } from "../Commands/CommandManager";
import { ProductHandler } from "../Services/ProductHandler";
import { TextEditorMode } from "./Interfaces";
import { ItemsDataApplier } from "../Services/ItemsDataApplier";
import { SurfaceHandler } from "../Services/SurfaceHandler";
import { PrintAreaBoundsType } from "@aurigma/design-atoms-model/Product/PrintAreaBoundsType";
import { CanvasViolationVisualizer } from "./../Services/ViolationService/CanvasViolationVisualizer";
import { FrontEndLogger, LogSource } from "../Services/FrontEndLogger";
import { ViolationServiceFactory } from "../Services/ViolationService/ViolationServiceFactory";
import { RotateHandler } from "../RotateHandler";
import { InputHandlerManager } from "./../Input/InputHandler/InputHandlerManager";
import { InputHandlerType } from "./../Input/InputHandler/InputHandlerType";
import { InputType } from "./../Input/InputManager/IInputManager";
import { DesignAtomsApiClient } from "../Services/DesignAtomsApiClient";
import { PathHandler } from "../ItemHandlers/PathHandler";
import { ItemUtils } from "../Utils/ItemUtils";
import { Service } from "../Services/Service";
import { ViewerInitializer } from "./ViewerInitializer";
import { ScrollbarStyleHandler } from "./ScrollbarStyleHandler";
import { ColorPreviewService } from "../Services/ColorPreviewService";
import { CmykColorParser, ColorParser, LabColorParser, NamedColorConverter, RgbColorParser, SpotColorParser } from "../Serialization/Color";
import { ProductPreviewService } from "../Services/ProductPreview";
import { InteractiveZonesHandler } from "./InteractiveZonesHandler";
import { RenderingConfigProvider } from "../RenderingConfigProvider";
export class Viewer extends BaseViewer {
constructor({ holderElement, backendUrl, surface = new Surface(null, null, null, [new PrintArea()]), canvasBackground = "chess", rulerEnabled = true, frontEndTextRenderingEnabled = false, zone = null, productViewerPartId = "ProductViewer", ignorePermissionsMode = false, keyInputElement = null, readonlyCanvasMode = false }) {
var _a;
super(zone);
this.containersFlatListChangedEvent = new EventObject();
this._containersFlatList = [];
this._textFormattingEnabled = true;
this._ignorePermissionsModeEnabled = false;
this._viewerInitializer = new ViewerInitializer();
this._twModule = { module: null };
this._updateItem = (item) => {
if (item instanceof CurvedTextItem)
item.fitToPathStep = this.configuration.text.fitToPathStep;
};
this._onHistoryChanged = (sender, propertyName) => {
this._history.addSnapshot();
};
this._surface = null;
this._onCurrentSurfaceContainerAdded = (data) => {
if (data.item.name === Configuration.MAIN_CONTAINER_NAME && data.item.renderingType === RenderingType.Normal)
this.userEditContainer = data.item;
};
this._onSurfacePropertyChanged = (s, property) => {
switch (property) {
case "mockup":
this._updateContainersFlatList();
break;
case "width":
case "height":
const bounds = this._surfaceHandler.getBounds(PrintAreaBoundsType.Total);
this._canvas.setWorkspaceSize(bounds.width, bounds.height);
break;
case "rotateAngle":
this.contentAngle = this.surface.rotateAngle;
break;
}
};
this._onPrintAreaPropertyChanged = (s, property) => {
if (property !== "bounds" && property !== "slug" && property !== "bleed")
return;
this._updateCanvasByPrintAreaBounds();
this._updateViewport();
};
this._updateCanvasByPrintAreaBounds = () => {
const totalBounds = this._surfaceHandler.getBounds(PrintAreaBoundsType.Total);
if (this._canvas.workspaceWidth !== totalBounds.width || this._canvas.workspaceHeight !== totalBounds.height) {
this._canvas.setWorkspaceSize(totalBounds.width, totalBounds.height);
}
const offset = new PointF(-Math.min(0, totalBounds.left), -Math.min(0, totalBounds.top));
this._canvas.offset = offset;
this._interactiveZonesHandler.setOffset(offset);
const paBounds = this._surfaceHandler.getPrintAreasBounds(PrintAreaBoundsType.Trim);
this._baseRulersOffset = new PointF(paBounds.left + offset.x, paBounds.top + offset.y);
};
this._restoreSelectionAfterSnapshotLoaded = async () => {
const selectedHandlers = this.canvas.getSelectedItemHandlers().toArray();
await new Promise((resolve) => {
const cb = () => {
resolve();
this.eventManager.removeSnapshotLoadedEvent(cb);
};
this.eventManager.addSnapshotLoadedEvent(cb);
});
const surfaceItems = this.surface.getAllItems({ flatGroupItems: true, ignoreMockups: false }).toArray();
const handlers = selectedHandlers.map(({ item }) => surfaceItems.find(({ id }) => item.id === id))
.filter((item) => !!item).map((item) => this._canvas.viewer.getHandler(item));
this.canvas.clearSelectedItemHandlers();
this.canvas.setSelectedItemHandlers(handlers);
};
this._updateContainersFlatList = () => {
const previewsList = this._containersFlatList;
this._containersFlatList = [
...(this.surface != null ? this.surface.mockup.underContainers : []),
//...this.surface.printAreas.select(p => p.background), //TODO next release
...(this.surface != null ? this.surface.containers : []),
//...this.surface.printAreas.select(p => p.foreground), //TODO next release
...(this.surface != null ? this.surface.mockup.overContainers : []),
...(this.previewMode ? [] : this._safetyLinesHandler.safetyLinesContainers),
...this._watermarkHandler.watermarkContainers,
...this._gridHandler.gridContainers
];
this.containersFlatListChangedEvent.notify(this._getDifference(previewsList, this._containersFlatList));
};
this._onDocumentClick = (e) => {
if (this._ignoreDocumentClickOnce === true) {
this._ignoreDocumentClickOnce = false;
return;
}
this._documentClickEvent.notify(this, e);
if (this.clearSelectionOnDocumentClick && !this._ignoreSelectionClick(e)) {
const cv = this.canvas;
if ((cv === null || cv === void 0 ? void 0 : cv.getSelectedItemHandlers().length) > 0) {
cv.clearSelectedItemHandlers();
cv.redraw();
}
}
};
this._onInput = (params) => {
if (params.type === InputType.Hover) {
this._rulersOnHover(params);
}
};
this._viewerInitializer = new ViewerInitializer();
this.frontEndTextRenderingEnabled = frontEndTextRenderingEnabled;
this._normalizeHolderElement(holderElement);
this._viewportDiv = this._createViewportDiv(holderElement);
this._viewerElement = this._createViewerElement(holderElement, productViewerPartId);
this._viewerInitializer.onSetBackendUrl(() => {
if (this._designAtomsApiClient == null) {
this._designAtomsApiClient = new DesignAtomsApiClient();
this._designAtomsApiClient.backendUrl = this.backendUrl;
this._viewerInitializer.setApiClient();
}
else {
this._designAtomsApiClient.backendUrl = this.backendUrl;
}
});
this._rgbColorParser = new RgbColorParser();
this._colorParser = new ColorParser(new NamedColorConverter(), this._rgbColorParser, new CmykColorParser(), new LabColorParser(), new SpotColorParser());
this._renderingConfigProvider = new RenderingConfigProvider(this);
this._viewerInitializer.onSetApiClient(() => {
var _a, _b;
PathHandler.designAtomsApiClient = this._designAtomsApiClient;
ItemUtils.designAtomsApiClient = this._designAtomsApiClient;
this._service = new Service(this.designAtomsApiClient);
this._licenseHandler = new LicenseHandler(this, this._designAtomsApiClient);
const viewer = this;
this._colorPreviewService = new ColorPreviewService(this.designAtomsApiClient, this._renderingConfigProvider);
this._productPreviewService = new ProductPreviewService({
get product() {
return viewer._productHandler.product;
},
get currentSurface() {
return viewer._productHandler.currentSurface;
},
get currentSurfaceChanged() {
return viewer._eventManager.surfaceChangedEvent;
}
}, this.designAtomsApiClient, this.colorPreviewService, this._service, this, this._colorParser);
this._canvas = this._createCanvas();
this._viewerInitializer.setCanvas();
this._watermarkHandler = new WatermarkHandler(null, this._service);
this._watermarkHandler.add_watermarkCollectionChanged(this._updateContainersFlatList);
this._designAtomsApiClient.setAuthorizationToken((_b = (_a = this.configuration) === null || _a === void 0 ? void 0 : _a.apiClientConfiguration) === null || _b === void 0 ? void 0 : _b.authorizationToken);
});
this._viewerInitializer.onSetCanvas(() => {
this._snapshotHandler = new SnapshotHandler(this);
this._history = this._initializeHistory();
this._eventManager.canvas = this.canvas;
});
this._eventManager = new EventManager(surface.parentProduct, this);
this._eventManager.addPrintAreaPropertyChanged(this._onPrintAreaPropertyChanged);
this._eventManager.addPrintAreaCollectionChanged(this._updateCanvasByPrintAreaBounds);
this._eventManager.addBeforeSnapshotLoad(this._restoreSelectionAfterSnapshotLoaded);
this._eventManager.addItemAdded(e => this._updateItem(e.item));
if (this.frontEndTextRenderingEnabled) {
this._eventManager.addItemPropertyChanged((item) => {
if (item instanceof BaseTextItem)
this._canvas.handlerFactory.replaceTextItemHandler(item);
});
}
this._ignorePermissionsModeEnabled = ignorePermissionsMode !== null && ignorePermissionsMode !== void 0 ? ignorePermissionsMode : false;
this._configuration = new ViewerConfiguration(null);
this._screenXDpi = this._screenYDpi = 96;
this._whitespaceDiv = null;
this._resizeCheckIntervalId = null;
this._interactiveZonesHandler = new InteractiveZonesHandler((_a = this._configuration.style) === null || _a === void 0 ? void 0 : _a.interactiveZones, this._eventManager.interactiveZonesChangedEvent);
this._safetyLinesHandler = new SafetyLinesHandler(this._configuration.printZone, this.colorParser);
this._safetyLinesHandler.addChanged(this._updateContainersFlatList);
this._safetyLinesHandler.addVisibilityChanged(() => this.canvas.redraw());
this._gridHandler = new GridHandler(this.colorParser);
this._gridHandler.addChanged(() => this.canvas.redraw());
this._scrollbarStyleHandler = new ScrollbarStyleHandler();
this._productHandler = new ProductHandler(this, this._eventManager);
this.surface = surface;
this._viewerInitializer.onInitalization(() => {
this.initialize({ ignore: false, readonlyCanvasMode });
this._setCanvasBackground(canvasBackground);
});
this._viewerInitializer.onPostInitialization(() => {
this.zoomMode = ZoomMode.bestFit;
this.viewportAlignment = ViewportAlignment.centerCenter;
this.rulerEnabled = rulerEnabled;
this._variableItemHelper = new VariableItemHelper(this._productHandler, this._canvas, this._eventManager);
this._productThemeManager = new ProductThemeManager(this._productHandler, null, this._canvas, this._eventManager);
this._itemsDataApplier = new ItemsDataApplier(this._productHandler, this._canvas, this._productThemeManager);
this._commandManager = new CommandManager(this._history, this._productHandler, this._productThemeManager, this._variableItemHelper, this._eventManager, this._canvas, this._itemsDataApplier);
this._inputHandlerManager = new InputHandlerManager(this, this._holderElement, keyInputElement);
this._inputHandlerManager.setInputHandlerType(InputHandlerType.Default);
this._inputHandlerManager.inputManager.addOnInput(this._onInput);
this._interactiveZonesHandler.setInputManager(this._inputHandlerManager.inputManager);
this._interactiveZonesHandler.setSelectionHandler(this.canvas.selection);
});
if (backendUrl != null)
this.backendUrl = backendUrl;
}
/**
* @param surfaceIndex Index of the surface to preview
* @param options Preview rendering options
* @returns Blob containing the preview image of given surface
*/
getSurfacePreview(surfaceIndex, options) {
return this._productPreviewService.getSurfacePreview(surfaceIndex, options);
}
/**
* @param options Preview rendering options
* @returns Blob containing the preview image of the current surface
*/
getCurrentSurfacePreview(options) {
return this._productPreviewService.getCurrentSurfacePreview(options);
}
ensureFocus() {
this._whitespaceDiv.focus();
}
get backendUrl() {
return this._backendUrl;
}
set backendUrl(value) {
if (this._backendUrl === value)
return;
if (value == null)
throw new ArgumentNullException("backendUrl must not be null.");
this._backendUrl = value;
this._viewerInitializer.setBackendUrl(value);
}
get designAtomsApiClient() {
return this._designAtomsApiClient;
}
get colorPreviewService() {
return this._colorPreviewService;
}
get colorParser() {
return this._colorParser;
}
get rgbColorParser() {
return this._rgbColorParser;
}
get hitTestManager() {
var _a;
return (_a = this._canvas) === null || _a === void 0 ? void 0 : _a.hitTestManager;
}
get _serviceEndpoint() {
return this._backendUrl != null ? urlCombine(this._backendUrl, "api/ccviewer") : null;
}
get containersFlatList() {
return this._containersFlatList;
}
get commandManager() { return this._commandManager; }
get configuration() {
return this._configuration;
}
// TODO: Move it to constructor please
set configuration(conf) {
var _a, _b, _c, _d;
this._configuration = new ViewerConfiguration(conf);
this.gridHandler.setConfig(this._configuration.grid, this._configuration.rulers);
this._setRulersConfig((_a = this._configuration) === null || _a === void 0 ? void 0 : _a.rulers);
this._scrollbarStyleHandler.isCustomScrollbarStyleEnabled = !this._configuration.disableCustomScrollbarStyle;
this._variableItemHelper.maskSymbol = this._configuration.variableItemsMaskSymbol;
this._productThemeManager.productThemes = this._configuration.productThemes;
if (this.surface != null && this.surface.parentProduct != null)
this.surface.parentProduct.getAllItems().forEach(this._updateItem);
this.history.historySize = this.configuration.historySize;
this.commandManager.configuration = this.configuration;
this._safetyLinesHandler.conf = this._configuration.printZone;
this.canvas.viewerConfiguration = this._configuration;
const vsConf = (_b = this._configuration) === null || _b === void 0 ? void 0 : _b.violationService;
if (!(vsConf === null || vsConf === void 0 ? void 0 : vsConf.enabled))
return;
this._violationServiceFactory = new ViolationServiceFactory(vsConf, this._configuration.messages, this._eventManager, this._productHandler, this._twModule);
this._violationService = this._violationServiceFactory.create();
if (!(vsConf === null || vsConf === void 0 ? void 0 : vsConf.qualityChangeContainersEnabled) && !(vsConf === null || vsConf === void 0 ? void 0 : vsConf.violationWarningButtonsEnabled))
return;
this._canvasViolationVisualizer = new CanvasViolationVisualizer(this.canvas, vsConf, this._violationService, this._violationServiceFactory, this._productHandler, this._configuration.messages, this._eventManager);
this._interactiveZonesHandler.setStyles(this._configuration.style.interactiveZones);
(_c = this._designAtomsApiClient) === null || _c === void 0 ? void 0 : _c.setAuthorizationToken((_d = this._configuration.apiClientConfiguration) === null || _d === void 0 ? void 0 : _d.authorizationToken);
this._scrollbarStyleHandler.scrollbarEnabled = this._configuration.scrollbarEnabled;
}
get renderingConfig() {
return this.configuration.renderingConfig;
}
get renderingConfigProvider() {
return this._renderingConfigProvider;
}
async exitEditMode() {
const escaping = this._canvas.getAllItemHandlers({ onlyType: NewBaseTextItemHandler, flatGroupItems: true })
.filter((x) => x.editing)
.map((x) => x.exitEditMode());
await Promise.all(escaping);
}
setInputHandlerType(type, args, options) {
if (this.canvas == null)
throw new Exception("Canvas is not initialized!");
this._inputHandlerManager.setInputHandlerType(type, args, options);
}
get inputHandlerManager() {
return this._inputHandlerManager;
}
queryItems(selectors, queryOptions) {
return this._productHandler.queryItems(selectors, queryOptions);
}
_initializeHistory() {
const result = new History(this._snapshotHandler);
this.eventManager.addSurfaceCollectionChanged(this._onHistoryChanged);
this.eventManager.addContainerCollectionChanged(this._onHistoryChanged);
this.eventManager.addItemCollectionChanged(this._onHistoryChanged);
this.eventManager.addUnderMockupContainerCollectionChanged(this._onHistoryChanged);
this.eventManager.addOverMockupContainerCollectionChanged(this._onHistoryChanged);
this.eventManager.addPreviewMockupContainerCollectionChanged(this._onHistoryChanged);
this.eventManager.addItemPropertyChanged(this._onHistoryChanged);
this.canvas.history = result;
return result;
}
_normalizeHolderElement(holder) {
holder.style.overflow = "hidden";
holder.style.userSelect = "none";
holder.style.webkitUserSelect = "none";
// @ts-ignore
holder.style.msUserSelect = "none";
holder.style.position = "relative";
}
_createViewerElement(holderElement, productViewerPartId) {
const viewerElement = document.createElement("div");
viewerElement.id = holderElement.id + "_" + productViewerPartId;
viewerElement.attributes["name"] = viewerElement.id;
viewerElement.style.width = "100%";
viewerElement.style.height = "100%";
viewerElement.style.display = "block";
viewerElement.style.zIndex = "1";
viewerElement.style.margin = "0";
viewerElement.style.padding = "0";
viewerElement.style.border = "0";
viewerElement.style.position = "relative";
viewerElement.style.overflow = "hidden";
viewerElement.style.transform = "translate3d(0px, 0px, 0px)";
viewerElement.style.touchAction = "none";
holderElement.appendChild(viewerElement);
return viewerElement;
}
get licenseHandler() {
return this._licenseHandler;
}
_createCanvas() {
const canvas = new Canvas(this);
canvas.service = this._service;
canvas.initialize();
canvas.multipleSelectionEnabled = true;
canvas.ignorePermissionsMode = this._ignorePermissionsModeEnabled;
canvas.floatingToolbarManager.eventManager = this._eventManager;
return canvas;
}
_setCanvasBackground(background) {
if (background === "chess") {
this.canvas.backgroundImage = urlCombine(this._serviceEndpoint, "/resource?image=background");
}
else {
this.canvas.background = background.color;
}
}
setTextWhizzModule(textWhizz) {
this._twModule.module = textWhizz;
this.canvas.setTextWhizzModule(textWhizz);
this._interactiveZonesHandler.setTextWhizz(textWhizz);
FrontEndLogger.debugLog("TextWhizz loaded", LogSource.Common);
this.eventManager.textWhizzReadyEvent.notify(textWhizz);
}
initTextEditor(fontService, useSimpleFontList, textEditor = TextEditorMode.Default, textInputIssueUserConfirmationDelegate = null) {
this._textEditorMode = textEditor;
this._fontService = fontService;
this._useSimpleFontList = useSimpleFontList;
this._textInputIssueUserConfirmationDelegate = textInputIssueUserConfirmationDelegate;
this.canvas.initTextEditor(textEditor, fontService, useSimpleFontList, textInputIssueUserConfirmationDelegate);
}
get textEditorMode() {
return this._textEditorMode;
}
setTextEditorMode(value) {
switch (value) {
case 0:
this.textEditorMode = TextEditorMode.Default;
break;
case 1:
this.textEditorMode = TextEditorMode.Html;
break;
case 2:
default:
this.textEditorMode = TextEditorMode.None;
break;
}
}
set textEditorMode(value) {
this._textEditorMode = value;
this.canvas.initTextEditor(this._textEditorMode, this._fontService, this._useSimpleFontList, this._textInputIssueUserConfirmationDelegate);
}
get canvas() {
return this._canvas;
}
get whitespaceDiv() {
return this._whitespaceDiv;
}
get viewportDiv() {
return this._viewportDiv;
}
get surface() {
return this._surface;
}
set surface(value) {
var _a;
if (value == null)
throw new ArgumentNullException("surface");
const prevSurface = this.surface;
if (value === prevSurface)
return;
(_a = this._canvas) === null || _a === void 0 ? void 0 : _a.clearSelectedItemHandlers();
this._surface = value;
this._eventManager.setProduct(value.parentProduct);
if (this._canvas != null)
this._onCurrentSurfaceChange(prevSurface);
}
get safetyLinesHandler() {
return this._safetyLinesHandler;
}
get gridHandler() {
return this._gridHandler;
}
get surfaceHandler() {
return this._surfaceHandler;
}
get violationService() {
return this._violationService;
}
get violationServiceFactory() {
return this._violationServiceFactory;
}
get interactiveZonesHandler() {
return this._interactiveZonesHandler;
}
_onCurrentSurfaceChange(prevSurface) {
this._interactiveZonesHandler.currentSurface = this.surface;
this._safetyLinesHandler.surface = this.surface;
this._watermarkHandler.surface = this.surface;
this._gridHandler.surface = this.surface;
this._surfaceHandler = new SurfaceHandler(this.surface);
const bounds = this._surfaceHandler.getBounds(PrintAreaBoundsType.Total);
this._updateCanvasByPrintAreaBounds();
this.canvas.service.beginMultiCall();
this._canvas.setWorkspaceSize(bounds.width, bounds.height);
this._updateContainersFlatList();
this.canvas.service.endMultiCall();
if (prevSurface != null) {
for (let collection of this._getContainerCollections(prevSurface, false)) {
for (let container of collection) {
for (let item of container.items) {
const itemHandler = this.getHandler(item);
this.releaseHandler(itemHandler);
}
}
}
//TODO this can be implemented more elegantly by using RxJs
for (let collection of this._getContainerCollections(prevSurface, true)) {
collection.remove_collectionChanged(this._updateContainersFlatList);
}
prevSurface.containers.remove_itemAdded(this._onCurrentSurfaceContainerAdded);
}
for (let collection of this._getContainerCollections(this._surface, true)) {
for (let container of collection) {
for (let item of container.items) {
const itemHandler = this.getHandler(item);
itemHandler.canvas = this.canvas;
}
}
collection.add_collectionChanged(this._updateContainersFlatList);
}
this.surface.addPropertyChanged(this._onSurfacePropertyChanged);
this.contentAngle = this.surface.rotateAngle;
this._updateAlignMargin();
this._eventManager.surfaceChangedEvent.notify(this._surface);
this._canvas.redraw();
this._updateViewport();
this.canvas.updateButtonGroups({ onlyVisible: false });
this.canvas.clearSelectedItemHandlers();
this.canvas.updateViolationContainers(true);
if (this.surface.containers.length > 0) {
const mainContainer = this.surface.containers.firstOrDefault(c => c.name === Configuration.MAIN_CONTAINER_NAME);
this.userEditContainer = mainContainer != null ? mainContainer : this.surface.containers.get(0);
this.surface.containers.add_itemAdded(this._onCurrentSurfaceContainerAdded);
}
}
_updateAlignMargin() {
if (!(this.surface instanceof Surface) || this._canvas == null || this.surface.printAreas.empty)
return;
const margins = { left: 0, right: 0, top: 0, bottom: 0 };
const targetSafetyLineName = this.configuration.alignToSafetyLineName;
if (!isEmpty(targetSafetyLineName)) {
const surfaceSafetyLines = this.surface.printAreas.selectMany(p => p.safetyLines);
const safetyLine = surfaceSafetyLines === null || surfaceSafetyLines === void 0 ? void 0 : surfaceSafetyLines.firstOrDefault(sl => sl.name == targetSafetyLineName);
if (safetyLine != null) {
const margin = safetyLine.getMargin();
margins.left = margin.left;
margins.right = margin.right;
margins.top = margin.top;
margins.bottom = margin.bottom;
}
else {
let alignArea = this.surface.printAreas.get(0);
switch (targetSafetyLineName) {
case "bleed":
margins.left = -alignArea.bleed.left;
margins.right = -alignArea.bleed.right;
margins.top = -alignArea.bleed.top;
margins.bottom = -alignArea.bleed.bottom;
break;
case "slug":
margins.left = -alignArea.slug.left;
margins.right = -alignArea.slug.right;
margins.top = -alignArea.slug.top;
margins.bottom = -alignArea.slug.bottom;
break;
}
}
}
this._canvas.leftMargin = margins.left;
this._canvas.rightMargin = margins.right;
this._canvas.topMargin = margins.top;
this._canvas.bottomMargin = margins.bottom;
}
_getContainerCollections(surface, includeSpecialCollections) {
let result = [
surface.mockup.underContainers,
surface.mockup.overContainers,
surface.containers,
];
if (includeSpecialCollections) {
result = [
...result,
this._safetyLinesHandler.safetyLinesContainers,
this._watermarkHandler.watermarkContainers,
this._gridHandler.gridContainers
];
}
return result;
}
get watermarkConfig() {
return this._watermarkHandler.watermarkConfig;
}
set watermarkConfig(value) {
this._watermarkHandler.watermarkConfig = value;
}
get selectedItems() {
const selectedItemHandlers = this.canvas.getSelectedItemHandlers();
return selectedItemHandlers !== null ? selectedItemHandlers.select(x => x.item).toArray() : null;
}
set selectedItems(value) {
if (value == null) {
this.canvas.clearSelectedItemHandlers();
return;
}
const itemHandlers = value.map(this.canvas.handlerFactory.get);
this.canvas.setSelectedItemHandlers(itemHandlers);
}
get currentItem() {
const currentItemHandler = this.canvas.currentItemHandler;
return currentItemHandler != null ? currentItemHandler.item : null;
}
get zoomConfig() {
if (this._configuration)
return this._configuration.zoom;
else
return null;
}
get previewMode() {
return this.canvas.previewMode;
}
set previewMode(value) {
this.canvas.previewMode = value;
this._updateContainersFlatList();
}
_getDifference(prevList, newList) {
return {
added: newList.reduce((acc, c) => {
if (!prevList.includes(c))
acc.push(c);
return acc;
}, new Array()),
removed: prevList.reduce((acc, c) => {
if (!newList.includes(c))
acc.push(c);
return acc;
}, new Array())
};
}
/** Content width in css pixels */
get contentWidth() {
return this._getContentDimension(this.workspaceWidth, Environment.screenDpi);
}
/** Content height in css pixels */
get contentHeight() {
return this._getContentDimension(this.workspaceHeight, Environment.screenDpi);
}
_getContentDimension(workspaceDimension, screenDpi) {
const value = Convert.devicePixelsToCssPixels(Convert.pointsToPixels(workspaceDimension, screenDpi) *
this.zoom);
return Math.ceil(value);
}
get workspaceWidth() {
/// <summary>Gets a value that represents the width (in points) of the <see cref="T:J:VectorObjects.Canvas" /> associated with this <see cref="T:J:CanvasViewer" />.</summary>
/// <value type="Number">The value which represents the width (in points) of the <see cref="T:J:VectorObjects.Canvas" /> associated with this <see cref="T:J:CanvasViewer" />.</value>
/// <remarks><para>This property corresponds to <see cref="P:CanvasViewer.WorkspaceWidth">CanvasViewer.WorkspaceWidth</see> server-side member.</para></remarks>
return this.canvas.workspaceWidth;
}
get workspaceHeight() {
/// <summary>Gets a value that represents the height (in points) of the <see cref="T:J:VectorObjects.Canvas" /> associated with this <see cref="T:J:CanvasViewer" />.</summary>
/// <value type="Number">The value which represents the height (in points) of the <see cref="T:J:VectorObjects.Canvas" /> associated with this <see cref="T:J:CanvasViewer" />.</value>
/// <remarks><para>This property corresponds to <see cref="P:CanvasViewer.WorkspaceHeight">CanvasViewer.WorkspaceHeight</see> server-side member.</para></remarks>
return this.canvas.workspaceHeight;
}
get actualSizeHorizontalScale() {
/// <summary>Gets value which represents the ratio of screen horizontal resolution to the canvas resolution.</summary>
/// <value type="Number">The ratio of screen horizontal resolution to the canvas resolution.</value>
/// <remarks><para>This property corresponds to <see cref="P:CanvasViewer.ActualSizeHorizontalScale">CanvasViewer.ActualSizeHorizontalScale</see> server-side member.</para></remarks>
return Environment.screenDpi / Environment.devicePixelRatio / 72;
}
get actualSizeVerticalScale() {
/// <summary>Gets value which represents the ratio of screen vertical resolution to the canvas resolution.</summary>
/// <value type="Number">The ratio of screen vertical resolution to the canvas resolution.</value>
/// <remarks><para>This property corresponds to <see cref="P:CanvasViewer.ActualSizeVerticalScale">CanvasViewer.ActualSizeVerticalScale</see> server-side member.</para></remarks>
return Environment.screenDpi / Environment.devicePixelRatio / 72;
}
/** Gets modal background class name. */
get modalBgClass() {
return this._modalBgClass;
}
set modalBgClass(value) {
this._modalBgClass = value;
}
get textFormattingEnabled() {
return this._textFormattingEnabled;
}
set textFormattingEnabled(v) {
this._textFormattingEnabled = v;
}
get clearSelectionOnDocumentClick() {
return this._clearSelectionOnDocumentClick;
}
set clearSelectionOnDocumentClick(value) {
this._clearSelectionOnDocumentClick = value;
}
get clearSelectionOnViewerClick() {
return this._clearSelectionOnViewerClick;
}
set clearSelectionOnViewerClick(value) {
this._clearSelectionOnViewerClick = value;
}
_renderContent(sb) {
const wsize = "width:" + this.contentWidth + "px;height:" + this.contentHeight + "px;";
const pos = "position:absolute;left:0px;top:0px;z-index:1";
sb += "\u003cdiv id=\"cvImage\" style=\"";
sb += wsize;
sb += pos + "\"/\u003e";
return sb;
}
_setZoomMode(v) {
super._setZoomMode(v);
if (!EqualsOfFloatNumbers(this.canvas.zoom, this.zoom)) {
this.canvas.setZoom(this.zoom);
this.canvas.redraw();
}
}
zoomToRectangle(rect) {
var _a, _b, _c, _d;
const zoom = this.calculateZoomByZoomMode(ZoomMode.bestFit, new SizeF(rect.width, rect.height));
let center = rect.center.clone();
center.x += ((_b = (_a = this._canvas) === null || _a === void 0 ? void 0 : _a.offset.x) !== null && _b !== void 0 ? _b : 0);
center.y += ((_d = (_c = this._canvas) === null || _c === void 0 ? void 0 : _c.offset.y) !== null && _d !== void 0 ? _d : 0);
center = RotateHandler.getRotatedPointFromSize(center, new SizeF(this.workspaceWidth, this.workspaceHeight), this._contentAngle);
const zoomParams = new ZoomParams();
zoomParams.skipZoomToCenter = false;
zoomParams.workspaceX = center.x;
zoomParams.workspaceY = center.y;
this.setZoom(zoom, zoomParams, true);
}
setZoom(value, params, ignoreZoomConfigRestrictions = false, withoutUpdate = false) {
var _a;
if (typeof value != "number")
return;
if (!ignoreZoomConfigRestrictions && this.zoomConfig) {
if (value > this.zoomConfig.max)
value = this.zoomConfig.max;
if (value < this.zoomConfig.min)
value = this.zoomConfig.min;
}
value = super.setZoom(value, params, ignoreZoomConfigRestrictions, withoutUpdate);
const cv = this.canvas;
if (!withoutUpdate)
cv.service.beginMultiCall();
cv.setZoom(value, (_a = params === null || params === void 0 ? void 0 : params.preventEvent) !== null && _a !== void 0 ? _a : false, { fullUpdate: !withoutUpdate, force: !withoutUpdate });
if (withoutUpdate) {
this.canvas.redrawSelection();
}
else {
cv.service.endMultiCall().finally(() => cv.redraw());
}
return value;
}
getMaxZoom() {
const baseMaxZoom = super.getMaxZoom();
return Math.min(baseMaxZoom, this.canvas.calcPlatformLimitZoom());
}
_ignoreSelectionClick(e) {
const clickInsideViewer = this.element.contains(e.target);
if (clickInsideViewer)
return true;
return AjcUtils.isEventPathContainsClass(e, Viewer.preventClickHandleClass);
}
initialize({ ignore = true, intervalCheckLoop = null, readonlyCanvasMode = false } = {}) {
if (ignore)
return;
super.initialize(intervalCheckLoop);
const el = this._contentElements;
el.push(this.element.querySelector("#cvImage"));
this.canvas.readonlyCanvasMode = readonlyCanvasMode;
this.canvas.addViewport(this._viewportDiv);
this._updateViewport();
this._whitespaceDiv = document.createElement("div");
this._whitespaceDiv.id = "cvWhitespace";
this._whitespaceDiv.tabIndex = -1;
this._whitespaceDiv.style.position = "absolute";
this._whitespaceDiv.style.zIndex = "1";
this._whitespaceDiv.style.overflow = "hidden";
this._holderElement.appendChild(this._whitespaceDiv);
this._updateWhitespace();
const cv = this.canvas;
cv.addStyles();
const canvasParent = this._contentCtx.firstChild;
if ((cv.status == UpdateStatus.ready) && (cv.isInitialized)) {
cv.setZoom(this.zoom, true);
cv.addElement(canvasParent);
cv.redraw();
}
this._resizeDelegate = this._onResize.bind(this);
cv.add_workspaceSizeChanged(this._resizeDelegate);
this._resizeCheckIntervalId = this._intervalCheckLoop.start({
checkFunction: () => this._devicePixelRatio !== Environment.devicePixelRatio,
onChange: () => {
this._devicePixelRatio = Environment.devicePixelRatio;
this._onResize(this, false);
}
});
}
_createViewportDiv(holderElement) {
const div = document.createElement("div");
div.id = "cvViewport";
div.tabIndex = -1;
div.style.position = "absolute";
div.style.overflow = "hidden";
holderElement.appendChild(div);
return div;
}
_updateWhitespace() {
if (this._whitespaceDiv == null)
return;
const swapSides = this._contentAngle === 90 || this._contentAngle === 270;
const contentWidth = swapSides ? this.contentHeight : this.contentWidth;
const contentHeight = swapSides ? this.contentWidth : this.contentHeight;
const viewportLocation = this.getViewportLocation();
const viewerWidth = this.width;
const viewerHeight = this.height;
const rulerWidth = this.actualRulerWidth;
const scrollbarWidth = this.scrollBarWidth;
const isAlways = this.scrollBarsStyle === ScrollBarsStyle.always;
const isAuto = this.scrollBarsStyle === ScrollBarsStyle.auto;
let isVerticalScrollbar = isAlways || (isAuto && (contentHeight > viewerHeight - rulerWidth));
let isHorizontalScrollbar = isAlways || (isAuto && (contentWidth > viewerWidth - rulerWidth));
isVerticalScrollbar = isVerticalScrollbar ||
(isHorizontalScrollbar && isAuto && (contentHeight > viewerHeight - rulerWidth - scrollbarWidth));
isHorizontalScrollbar = isHorizontalScrollbar ||
(isVerticalScrollbar && isAuto && (contentWidth > viewerWidth - rulerWidth - scrollbarWidth));
const verticalScrollbarWidth = isVerticalScrollbar ? scrollbarWidth : 0;
const horizontalScrollbarWidth = isHorizontalScrollbar ? scrollbarWidth : 0;
this._whitespaceDiv.style.left = `${Math.min(viewportLocation.x, rulerWidth)}px`;
this._whitespaceDiv.style.top = `${Math.min(viewportLocation.y, rulerWidth)}px`;
this._whitespaceDiv.style.width = `${Math.max(viewerWidth - rulerWidth - verticalScrollbarWidth, contentWidth)}px`;
this._whitespaceDiv.style.height = `${Math.max(viewerHeight - rulerWidth - horizontalScrollbarWidth, contentHeight)}px`;
if (isAuto) {
this._holderElement.style.overflowX = isHorizontalScrollbar ? (Environment.IsFirefox() ? "auto" : "overlay") : "hidden";
this._holderElement.style.overflowY = isVerticalScrollbar ? (Environment.IsFirefox() ? "auto" : "overlay") : "hidden";
}
this.canvas.updateButtonGroups();
}
zoomToSelection() {
super.zoomToItems(this.selectedItems);
}
_updateViewportNew() {
this._canvas.updateViewport();
}
_updateViewport(ignoreZoomConfigRestrictions = false) {
super._updateViewport(ignoreZoomConfigRestrictions);
this._updateWhitespace();
}
_getElementForCursor() {
return this._whitespaceDiv != null
? this._whitespaceDiv
: super._getElementForCursor();
}
_onResize(sender, updateButtonGroup) {
super._onResize(sender, updateButtonGroup);
this.canvas.service.beginMultiCall();
this.canvas.setZoom(this.zoom, undefined, { force: true, updateButtonGroup: updateButtonGroup });
this.canvas.service.endMultiCall().finally(() => this.canvas.redraw());
}
//show <div> over control which block control while canvas state is busy
lockViewer() {
/// <summary>Shows a semi-transparent rectangle over the <see cref="T:J:CanvasViewer" />.</summary>
/// <remarks><para>To hide this rectangle use the <see cref="M:J:CanvasViewer.unlockViewer" /> method.</para></remarks>
var el = this.element;
var mb = document.getElementById(this.id + "_modalBg");
if (!mb) {
mb = document.createElement("div");
var style = mb.style;
style.position = "absolute";
style.top = "0";
style.left = "0";
if (this._modalBgClass)
mb.className = this._modalBgClass;
else {
style.backgroundPosition = "50% 50%";
style.backgroundColor = "#000000";
style.opacity = "0.4";
style.filter = "alpha(opacity=40)";
style.zIndex = "1000";
}
mb.id = this.id + "_modalBg";
if (el.offsetParent)
el.offsetParent.appendChild(mb);
style.width = "100%";
style.height = "100%";
style.bottom = "0";
style.right = "0";
}
mb.style.display = "block";
}
//hide <div> when canvas state changed to ready
/**
* Hides the semi-transparent rectangle when it is shown over the `Viewer`
* @remarks To show this rectangle use the `Viewer.lockViewer` method.
**/
unlockViewer() {
const mb = document.getElementById(this.id + "_modalBg");
if (mb)
mb.style.display = "none";
}
get eventManager() { return this._eventManager; }
;
get history() { return this._history; }
get userEditContainer() {
return this._userEditContainer;
}
set userEditContainer(value) {
if (this._userEditContainer == value)
return;
this._userEditContainer = value;
this._productHandler.updateMaskedContainers();
this._eventManager.userEditContainerChangedEvent.notify(this._userEditContainer);
}
/** {@inheritDoc ProductHandler.interactiveContainers} */
get interactiveContainers() {
return this._productHandler.interactiveContainers;
}
set interactiveContainers(value) {
this._productHandler.interactiveContainers = value;
}
getUserEditSurface() {
return this.surface;
}
getUserEditPrintArea() {
return this.surface.printAreas.get(0);
}
get variableItemHelper() { return this._variableItemHelper; }
get productThemeManager() { return this._productThemeManager; }
get productHandler() { return this._productHandler; }
get itemsDataApplier() { return this._itemsDataApplier; }
getHandler(item) {
return this._canvas.handlerFactory.get(item);
}
releaseHandler(itemHandler) {
itemHandler.canvas = null;
this._canvas.handlerFactory.delete(itemHandler);
}
async waitUpdate() {
await this._canvas.waitUpdate();
}
/** Removes the current `Viewer` from the application. */
dispose() {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (this._resizeCheckIntervalId != null)
this._intervalCheckLoop.stop(this._resizeCheckIntervalId);
const cv = this.canvas;
if (cv) {
if (this._resizeDelegate) {
cv.remove_workspaceSizeChanged(this._resizeDelegate);
delete this._resizeDelegate;
}
cv.dispose();
}
(_a = this._eventManager) === null || _a === void 0 ? void 0 : _a.dispose();
(_b = this._safetyLinesHandler) === null || _b === void 0 ? void 0 : _b.dispose();
this._surface.containers.remove_itemAdded(this._onCurrentSurfaceContainerAdded);
(_c = this._canvasViolationVisualizer) === null || _c === void 0 ? void 0 : _c.dispose();
(_d = this._violationService) === null || _d === void 0 ? void 0 : _d.dispose();
(_e = this._productPreviewService) === null || _e === void 0 ? void 0 : _e.dispose();
(_g = (_f = this._inputHandlerManager) === null || _f === void 0 ? void 0 : _f.inputManager) === null || _g === void 0 ? void 0 : _g.removeOnInput(this._onInput);
(_h = this._inputHandlerManager) === null || _h === void 0 ? void 0 : _h.dispose();
super.dispose();
}
/** Refresh the control immediately */
_refresh() {
// Clear delayed refresh.
if (this._refreshTimer) {
window.clearTimeout(this._refreshTimer);
}
// Clear flag.
this._needToRefresh = false;
}
}
Viewer.preventKeyHandleClass = "preventCanvasKeyHandle";
Viewer.preventClickHandleClass = "preventCanvasClickHandle";
//# sourceMappingURL=Viewer.js.map