@mescius/dsimageviewer
Version:
Document Solutions Image Viewer
1,510 lines • 58.7 kB
TypeScript
/**
* Confirm button type.
*/
export type ConfirmButton = "Yes" | "No" | "Ok" | "Cancel" | "Confirm" | "Close" | "Dismiss";
/**
* Base type for event arguments.
*/
export type EventArgs = {
/**
* Event name.
*/
eventName?: EventName;
/**
* Event source.
*/
source?: ImageViewerAPI;
};
/**
* EventFan event handler. Invokes when the cancellation is requested.
*/
export type EventHandler = (args: EventArgs) => any;
/**
* EventFan event handler unregister function.
* @returns boolean True if handler was unregistered successfully, false otherwise.
*/
export type EventHandlerUnregisterFn = () => boolean;
/**
* Event handler attach options.
*/
export type EventBusAttachOptions = {
/**
* Listen to the event once.
*/
once?: boolean;
};
/**
* EventBus event name.
* @example
* ```javascript
* viewer.eventBus.on("zoom-changed", function(args) {
* console.log("Zoom changed", args);
* });
* ```
*/
export type EventBusEventName = "before-open" | "after-open" | "before-close" | "after-close" | "zoom-changed" | "frame-index-changed" | "animation-started" | "animation-stopped" | "keydown" | "keyup" | "object-designer-bounds-changed";
/**
* EventBus listener function
*/
export type EventBusEventListener = (...args: any[]) => void;
/**
* Viewer event name.
*/
export type EventName = "ErrorEvent" | "BeforeOpenEvent" | "AfterOpenEvent" | "ThemeChangedEvent" | "ImagePaint";
/**
* GIF options.
*/
export type GifOptions = {
/**
* Cumulative drawing mode - do not clear previous frame appearance.
*/
cumulative?: boolean;
/**
* Maximum image buffer length to load.
* The image buffer length is calculated as follows:
* `NumFrames * image.height * image.width * 4`.
* If the GIF image exceeds this value, only the first frame will be loaded.
* The default and maximum value is 2145386496.
*/
maxBufferLength?: number;
/**
* Play/stop animation on mouse over/out.
*/
playOnHover?: boolean;
/**
* Play/stop animation on mouse click.
*/
playOnClick?: boolean;
/**
* Automatically play video when a GIF image contains more than one frame.
*/
autoPlay?: boolean;
/**
* Animation speed.
* The delay between frames will be divided by the value specified in the "speed" setting.
* The lower the value, the slower the animation will run.
* The higher the value, the faster the animation runs.
* @default 1
* @example
* ```javascript
* // Slowing down the animation by two times:
* const viewer = new GcImageViewer("#root", {
* gifOptions: { speed: 0.5 }
* });
* ```
* @example
* ```javascript
* // Animation acceleration by two times::
* const viewer = new GcImageViewer("#root", {
* gifOptions: { speed: 2 }
* });
* ```
*/
speed?: number;
};
/**
* Union type representing all possible cursor styles for the application.
* Includes standard CSS cursor values and custom application-specific cursors.
*
* @typedef {string} GlobalCursorType
*
* @property {"pointer"} pointer - Standard pointer cursor (hand icon)
* @property {"default"} default - Default arrow cursor
* @property {"text"} text - Text input I-beam cursor
* @property {"move"} move - Move/pan cursor (four-way arrow)
* @property {"not-allowed"} not-allowed - Action not allowed cursor
*
* @property {"n-resize"} n-resize - North resize cursor
* @property {"e-resize"} e-resize - East resize cursor
* @property {"s-resize"} s-resize - South resize cursor
* @property {"w-resize"} w-resize - West resize cursor
* @property {"ne-resize"} ne-resize - Northeast resize cursor
* @property {"nw-resize"} nw-resize - Northwest resize cursor
* @property {"se-resize"} se-resize - Southeast resize cursor
* @property {"sw-resize"} sw-resize - Southwest resize cursor
* @property {"ew-resize"} ew-resize - East-west resize cursor
* @property {"ns-resize"} ns-resize - North-south resize cursor
* @property {"nesw-resize"} nesw-resize - Northeast-southwest resize cursor
* @property {"nwse-resize"} nwse-resize - Northwest-southeast resize cursor
*
* @property {"rotate"} rotate - Custom rotate cursor (application-specific)
* @property {"grab"} grab - Grab/open hand cursor
* @property {"grabbing"} grabbing - Grabbing/closed hand cursor
* @property {"zoom-in"} zoom-in - Zoom in/magnify cursor
* @property {"zoom-out"} zoom-out - Zoom out cursor
* @property {"wait"} wait - Wait/busy cursor
* @property {"crosshair"} crosshair - Precision selection crosshair cursor
*
* @example
* // Type-safe cursor assignment
* const resizeCursor: GlobalCursorType = 'nwse-resize';
*
* @example
* // Function parameter typing
* function setCursor(cursor: GlobalCursorType) {
* document.body.style.cursor = cursor;
* }
*/
export type GlobalCursorType = "pointer" | "default" | "text" | "move" | "not-allowed" | "n-resize" | "e-resize" | "s-resize" | "w-resize" | "ne-resize" | "nw-resize" | "se-resize" | "sw-resize" | "ew-resize" | "ns-resize" | "nesw-resize" | "nwse-resize" | "rotate" | "grab" | "grabbing" | "zoom-in" | "zoom-out" | "wait" | "crosshair";
/**
* Paint command execution options.
*/
export type PaintExecuteOptions = {
/**
* Previous command.
*/
prevCommand?: PaintCommand;
/**
* Designer paint context
*/
context: PaintDesignerContext;
};
/**
* Image format name.
*/
export type ImageFormatName = "jpg" | "png" | "tiff" | "gif" | "bmp" | "ico" | "svg" | "webp";
/**
* Image mime type.
*/
export type ImageMimeType = "image/png" | "image/x-png" | "image/jpeg" | "image/bmp" | "image/gif" | "image/webp" | "image/svg+xml" | "image/ico" | "image/tiff";
/**
* Defines the layout of the toolbar.
*/
export type ImageToolbarLayout = {
viewer: {
/** Default (desktop) view mode. Also applied when other modes are not specified. */
default?: string[];
/** The layout for the full-screen mode. */
fullscreen?: string[];
/** The toolbar layout for mobile devices. */
mobile?: string[];
};
};
/**
* Image open parameters.
*/
export type OpenParameters = {
/**
* Image format type.
* Use the imageFormat parameter when the viewer cannot automatically determine the image format.
* Available image formats are: 1 = JPEG, 2 = PNG, 3 = TIFF, 4 = GIF, 5 = BMP, 6 = ICO, 7 = SVG, 8 = WEBP
* @example
* ```javascript
* // Open TIFF image from URL.
* viewer.open("http://localhost/getimage?id=1&fmt=3", { imageFormat: 3 });
* // or:
* viewer.open("http://localhost/getimage?id=1&fmt=3", { imageFormat: "tiff" });
* ```
*/
imageFormat?: ImageFormatCode | ImageFormatName | ImageFormatCode;
/**
* Image DPI. DPI value is used to determine the quality and resolution of the image.
* @default 96
* @example
* ```javascript
* viewer.open("sample.png", { imageDPI: 72 });
* ```
*/
imageDPI?: number;
/**
* Optional. Friendly file name.
* @example
* ```javascript
* viewer.open("/getSampleImage", { fileName: "sample.png" });
* ```
*/
fileName?: string;
};
/**
* Paint command name.
*/
export type PaintCommandName = "Pencil" | "Brush" | "Eraser" | "ErasePath2D" | "CloneStamp" | "TextPaintObject" | "RectanglePaintObject" | "LinePaintObject" | "ArrowPaintObject" | "EllipsePaintObject" | "BracketsPaintObject" | "UpdateObjectPosition" | "SetObjectProperty" | "DeleteObject" | "CopySelectedRegion" | "UpdateSelectedRegion" | "ResetSelectedRegion" | "CommitSelectedRegionImage" | "UndoSequenceMarker" | "ImagePaintObject" | "SelectObject" | "UnselectObject";
/**
* Complete set of paint object properties with strict typing
*/
export type PaintObjectPropertyName = 'bounds' | 'position' | 'opacity' | 'rotation' | 'bounds' | 'position' | 'opacity' | 'rotation' | 'lineWidth' | 'lineColor' | 'fillColor' | 'text' | 'fontSize' | 'fontName' | 'fontColor' | 'fontItalic' | 'fontBold' | 'borderRadius' | 'startPosition' | 'endPosition' | 'startCapStyle' | 'endCapStyle' | 'capSize' | 'capColor' | 'bracketsShape' | 'arrowDirection' | 'showLeftBracket' | 'showRightBracket' | 'bracketWidth' | 'curveIntensity' | 'arrowIntensity';
/**
* Paint object type name.
*/
export type PaintObjectType = "image" | "rectangle" | "text" | "circle" | "triangle" | "line" | "arrow" | "polygon" | "ellipse" | "brackets";
/**
* Defines the list of officially supported plugin types for the `DsImageViewer`. These plugins extend the viewer’s functionality and are maintained internally. Custom or third-party plugin types are not supported.
*/
export type PluginType = "rotation" | "paintTools" | "pageTools" | "imageFilters";
/**
* Paint point trigger type.
*/
export type PointerTriggerType = "start" | "move" | "end";
/**
* Options for the Save As menu.
*/
export type SaveAsMenuOptions = {
/**
* Flag to hide additional options in the "Save As" menu. If true, the "Initial version" option will be hidden.
*/
hideOptions?: boolean;
/**
* List of available formats for saving. Leave undefined to detect supported formats automatically.
*/
availableFormats?: ImageMimeType[];
};
/**
* Options for customizing the behavior and appearance of the "Save" button.
*/
export type SaveButtonOptions = SaveOptions & {
/**
* Configuration for the "Save As" menu. Set to false to hide the "Save As" menu.
*/
saveAsMenu?: boolean | SaveAsMenuOptions;
};
/**
* Options for saving an image.
*/
export type SaveOptions = {
/**
* The target format code to convert the image to during saving.
*/
convertToFormat?: ImageFormatCode | ImageMimeType;
/**
* The desired file name for the saved image.
*/
fileName?: string;
/**
* Indicates whether to retrieve the original version of the image.
*/
original?: boolean;
};
/**
* Second toolbar type.
*/
export type SecondToolbarType = "page-tools" | "crop-image" | "resize-image" | "text-tools" | "paint-tools" | "effects" | "objects" | "image-filter-tools" | "image-filter-settings" | "none";
/**
* Undo storage options.
*/
export type UndoStorageOptions = {
/**
* Max undo levels.
*/
maxLevels?: number;
/**
* The names of the undo commands to skip.
* Available built-in command names are: "Open", "Close", "FrameIndex", "Zoom", "Rotation", "Flip", "StartAnimation", "StopAnimation".
* Note that the "Open"/"Close" and "StartAnimation"/"StopAnimation" commands are paired - if one command is skipped, the other command will also be skipped.
* @example
* ```javascript
* const viewer = new GcImageViewer(selector, {
* undo: { skipCommands: ["Open", "Zoom"] }
* });
* ```
*/
skipCommands?: string[];
};
/**
* Reach data structure with main (x, y, width, height) and additional (rotation angle, direction) information about the shape
*/
export interface Bounds extends PointLocation, Size {
/**
* Rotation angle
*/
rotationAngle?: number;
/**
* X-axis direction
*/
dirX?: number;
/**
* Y-axis direction
*/
dirY?: number;
}
/**
* The image viewer event bus.
* Use the event bus to listen and receive certain specific "events".
* Available events are: "before-open", "after-open", "before-close", "after-close", "zoom-changed", "frame-index-changed", "animation-started", "animation-stopped".
* @example
* ```javascript
* // Listen frame index changes:
* viewer.eventBus.on("frame-index-changed", function(args) { console.log("Image frame changed", args); });
* ```
* @example
* ```javascript
* // Listen "after-open" event once:
* viewer.eventBus.on("after-open", function(args) { console.log("Image opened", args); }, { once: true });
* ```
*/
export interface EventBus {
/**
* Use the dispatch method to raise an event.
* @param {EventBusEventName} eventName
* @param {Object} data
*/
dispatch(eventName: EventBusEventName, data: any): void;
/**
* Listen an event bus event.
* @param {EventBusEventName} eventName
* @param {EventBusEventListener} listener
* @param {EventBusAttachOptions} [options]
*/
on(eventName: EventBusEventName, listener: EventBusEventListener, options?: EventBusAttachOptions): void;
/**
* Remove all event listeners for the event specified by the eventName argument.
* @param {string} eventName
*/
offAll(eventName: EventBusEventName): void;
/**
* Remove event listener specified by the listener argument for the event specified by the eventName argument.
* @param {EventBusEventName} eventName
* @param {EventBusEventListener} listener
*/
off(eventName: EventBusEventName, listener: EventBusEventListener): void;
}
/**
* Image layer canvas.
*/
export interface ImageLayer {
/**
* Image layer name.
*/
name: string;
/**
* Image layer size.
*/
readonly size: Size;
/**
* Canvas object to paint.
*/
readonly mainCanvas: HTMLCanvasElement;
/**
* Canvas object to paint.
*/
readonly backCanvas: HTMLCanvasElement;
/**
* Main 2D rendering context.
*/
readonly mainCtx: CanvasRenderingContext2D;
/**
* Background 2D rendering context.
*/
readonly backCtx: CanvasRenderingContext2D;
/**
* The objects in this array are drawn to the canvas.
*/
readonly paintObjects: PaintObject<PaintObjectType>[];
/**
* Removes everything drawn before on image layer.
* @param {boolean} clearCache Indicates if should clear cache too.
*/
clear(clearCache: boolean): void;
/**
* Clears all resources and removes image layer.
*/
dispose(): void;
/**
* Draws an original viewer image on image layer.
* @returns {Promise<void>}
*/
ensureBackground(): Promise<void>;
/**
* Merges image layer into original viewer image.
* @returns {Promise<void>}
*/
merge(): Promise<void>;
/**
* Clears all resources and removes image layer.
* @returns {Promise<string>} Promise with string that contains dataUrl
*/
saveToDataURL(): Promise<string>;
/**
* Call this method to draw the paint objects specified in the paintObjects array onto the canvas.
*/
drawObjects(): Promise<void>;
/**
* Run a temporary paint command on a separate temporary canvas layer. This method should create and display the temporary canvas layer if it doesn't exist.
*/
executeTempPaintCommand(cmd: PaintCommand): void;
/**
* Get all temporary paint commands.
*/
getTempPaintCommands(): PaintCommand[];
/**
* Clear all temporary paint commands, clear and dispose the temporary canvas layer.
*/
clearTempPaintCommands(): void;
}
/**
* Represents a canvas paint command, optionally supporting serialization and undo operations.
*/
export interface PaintCommand {
/**
* The name or type of the paint command. Used to identify and group similar command operations.
*/
readonly name: PaintCommandName;
/**
* Optional point location (e.g. cursor or touch position) associated with the command. This can be used for positioning or context-aware execution.
*/
point?: PointLocation;
/**
* The type of pointer trigger (e.g., mouse, touch, pen) that initiated this command. Helps in distinguishing user input sources.
*/
trigger: PointerTriggerType;
/**
* Creates a deep copy of this command instance. Useful for storing history or duplicating commands without side effects.
* @returns A new instance of the same command with cloned properties.
*/
clone(): PaintCommand;
/**
* Executes the paint command using the provided rendering contexts.
* @param {CanvasRenderingContext2D} mainCtx The main canvas rendering context where new edits are applied.
* @param {CanvasRenderingContext2D} backCtx The background rendering context, typically containing the base image or previous state.
* @param {PaintExecuteOptions} options Additional configuration or context-specific options required during execution.
*/
execute(mainCtx: CanvasRenderingContext2D, backCtx: CanvasRenderingContext2D, options: PaintExecuteOptions): void;
}
/**
* Paint designer context.
*/
export interface PaintDesignerContext {
/**
* Get a reference to an array with object designers.
*/
getPaintObjectDesigners(): any[];
}
/**
* Core interface representing a paint object that can be rendered on canvas.
* @template T - The specific type of paint object (e.g., 'rectangle', 'line')
*/
export interface PaintObject<T> {
/**
* The type identifier of the paint object (e.g., 'line', 'rectangle')
*/
readonly type: T;
/**
* The display name of the paint object
*/
readonly name: string;
/**
* Gets the bounding rectangle of the object in canvas coordinates
*/
readonly bounds: Bounds;
/**
* Gets the end position (particularly relevant for line objects)
*/
readonly startPosition: PointLocation;
/**
* Gets the end position (particularly relevant for line objects)
*/
readonly endPosition: PointLocation;
/**
* Returns the additional padding (in pixels) required around the object to accommodate all visual elements like styled line caps. This is useful for properly sizing the canvas when rendering this object.
*/
readonly canvasPadding: number;
/**
* Renders the object to the specified canvas context
* @param {CanvasRenderingContext2D} destCtx Primary drawing context
* @param {CanvasRenderingContext2D} mainCtx Main canvas context (for composite operations)
* @param {CanvasRenderingContext2D} backCtx Background context (for layered rendering)
* @param {PaintObjectParameters} params Optional rendering parameters
*/
draw(destCtx: CanvasRenderingContext2D, mainCtx: CanvasRenderingContext2D, backCtx: CanvasRenderingContext2D, params?: PaintObjectParameters): Promise<void>;
/**
* Calculates the content dimensions of the object
* @param ctx - Canvas context used for measurements (e.g., text metrics)
* @returns Size object containing width and height
*/
getContentSize(ctx: CanvasRenderingContext2D): Size;
/**
* Retrieves a property value by name
* @template K - Type of the property name
* @param {K} propertyName - Name of the property to retrieve
* @returns The property value or undefined if not found
*/
getProperty<K extends PaintObjectPropertyName>(propertyName: K): any;
/**
* Updates a property value by name
* @template K - Type of the property name
* @param {K} propertyName - Name of the property to set
* @param {any} value - New value for the property
* @returns True if the property was changed, false otherwise
*/
setProperty<K extends PaintObjectPropertyName>(propertyName: K, value: any): boolean;
/**
* Resets all user-modified properties of the object
* back to their registered factory default values.
*/
resetToFactoryDefaults(): void;
}
/**
* Command based undo state storage.
*/
export interface UndoStorage {
/**
* Gets a value indicating whether the undo storage can undo changes.
*/
readonly hasUndo: boolean;
/**
* Gets a value indicating whether the undo storage can redo changes.
*/
readonly hasRedo: boolean;
/**
* Gets current undo level index.
*/
readonly undoIndex: number;
/**
* Gets total undo levels count.
*/
readonly undoCount: number;
/**
* Gets a flag indicating whether an undo/redo or execute operation is in progress.
*/
readonly undoInProgress: boolean;
/**
* Apply undo storage options.
*/
applyOptions(options: ViewerOptions): void;
/**
* Dispose undo storage.
*/
dispose(): void;
/**
* Clear undo storage.
*/
clear(): void;
/**
* Gets a value indicating whether the command specified in the command parameter is supported.
* @param {UndoCommandSupport} command Instance of a command.
*/
isCommandSupported(command: UndoCommandSupport): boolean;
/**
* Execute a new command.
* @param {UndoCommandSupport} command Instance of a command.
*/
execute(command: UndoCommandSupport): Promise<void>;
/**
* Called after command action has been executed.
* @param {UndoCommandSupport} command Instance of a command.
*/
onCommandExecuted(command: UndoCommandSupport): void;
/**
* Undo last action.
*/
undo(): Promise<void>;
/**
* Redo next action.
*/
redo(): Promise<void>;
}
/**
* Extended paint object parameters with additional rendering options
*/
export interface PaintObjectParameters {
/**
* Whether the object is being rendered in design/edit mode.
*
* In design mode (when editing objects), each object is rendered on its own canvas.
* Padding is applied around the canvas to account for effects like shadows or outlines.
* Rotation in this mode is handled at the DOM level (via CSS transform), so canvas
* rotation is skipped.
*
* In runtime (final rendering), all objects are drawn on a single shared canvas.
* In this case, padding is not applied and rotation is handled via canvas transforms.
*/
isDesignTime?: boolean;
/**
* Paint context
*/
context: ImageLayer;
}
/**
* A point representing a location in (x, y) coordinate space.
*/
export interface PointLocation {
/**
* X position.
*/
x: number;
/**
* Y position.
*/
y: number;
}
/**
* Size of the rectangle.
*/
export interface Size {
/**
* Width.
*/
width: number;
/**
* Height.
*/
height: number;
}
/**
* Interface for undo commands.
* @example
* ```javascript
* // The UndoCommandSupport interface implementation example.
* class CustomUndoCommand implements UndoCommandSupport {
* name: "CustomUndoCommand",
* execute: function(viewer) {
* return new Promise((resolve) => {
* // Put your action code here
* resolve();
* })
* },
* undo: function(viewer) {
* return new Promise((resolve) => {
* // Put your undo action here
* resolve();
* })
* }
* }
* ```
*/
export interface UndoCommandSupport {
/**
* Optional. The unique name of the command. Used by the undo.skipCommands option setting.
*/
name: string;
/**
* Action implementation.
*/
execute(viewer: ImageViewerAPI): Promise<void>;
/**
* Undo action implementation.
*/
undo(viewer: ImageViewerAPI): Promise<void>;
}
/**
* Window keyboard listener handler parameters interface.
*/
export interface WindowKeyboardListenerParams {
/**
* Indicates Alt key was pressed
*/
alt: boolean;
/**
* Indicates Ctrl key was pressed
*/
ctrl: boolean;
/**
* Indicates Shift key was pressed
*/
shift: boolean;
/**
* Indicates Space key was pressed
*/
space: boolean;
}
/**
* Window keyboard listener handler interface.
*/
export interface WindowKeyboardListener {
/**
* Called when key pressed.
*/
onKeyDown: (e: KeyboardEvent, params: WindowKeyboardListenerParams) => any;
/**
* Called when key released.
*/
onKeyUp: (e: KeyboardEvent, params: WindowKeyboardListenerParams) => any;
}
/**
* Viewer event raising interface
*/
export interface EventFan {
/**
* Registers a new event handler. The handler is invoked when the cancellation is requested.
* @param {EventHandler} eventHandler Event handler function.
* @returns {EventHandlerUnregisterFn} Event handler unregister function.
*/
register(eventHandler: EventHandler): EventHandlerUnregisterFn;
}
/**
* Defines the interface for plugins used by `GcImageViewer` and `DsImageViewer`.
*
* The plugin system is now intended for **internal use only**.
* Starting from version 9.0, only official plugins developed and distributed
* as part of the product are supported.
*
* Custom or third-party plugins are no longer supported and may not function properly.
*
* Internal plugins will continue to use this interface to extend viewer functionality.
*/
export interface ImageViewerPluginReference {
/**
* Unique plug-in identifier.
*/
id: PluginType;
/**
* The method is called when the GcImageViewer component is initialized.
* @param {ImageViewerAPI} viewer
*/
initialize(viewer: ImageViewerAPI): void;
/**
* The method is called when the DsImageViewer component is about to be disposed.
*/
dispose(): void;
}
/**
* @ignore exclude API interface from docs since it is documented by implementing classes.
*/
export interface ImageViewerPluginAPI extends ImageViewerPluginReference {
/**
* Gets the paint layer containing the HTML canvas for drawing the image.
*/
readonly paintLayer: ImageLayer;
/**
* Returns true if the image is loaded into the viewer and the image format is supported by the Image Filters plugin.
*/
readonly isReady: boolean;
/**
* Natural image size.
*/
readonly naturalSize: Size;
/**
* Gets the image viewer instance.
* The image viewer instance.
*/
readonly viewer: ImageViewerAPI;
/**
* Determines whether the specified image format is supported for modifications.
*
* @param {ImageFormatCode | string} imageFormat - The image format to check, either as an enum value or string.
* @param {boolean} [allowUnknown=false] - If true, allows unknown formats (ImageFormatCode.Default) to be considered supported.
* @returns {boolean} True if the format is supported for modifications, false otherwise.
*
* @remarks
* The following formats are explicitly not supported:
* - TIFF (ImageFormatCode.TIFF)
* - SVG (ImageFormatCode.SVG)
* - ICO (ImageFormatCode.ICO)
* - GIF (ImageFormatCode.GIF)
*
* @example
* // Check if PNG is supported
* const supported = isImageFormatSupported(ImageFormatCode.PNG);
*
* @example
* // Check if an unknown format is supported (returns false by default)
* const supported = isImageFormatSupported('custom-format');
*
* @example
* // Check if an unknown format is supported (returns true when allowUnknown is true)
* const supported = isImageFormatSupported('custom-format', true);
*/
isImageFormatSupported(imageFormat: string | ImageFormatCode, allowUnknown?: boolean): boolean;
/**
* Cleans up resources and disposes the plugin.
*/
dispose(): void;
/**
* Removes and disposes the active paint layer. If no paint layer exists, this method does nothing.
*/
removePaintLayer(): void;
}
/**
* Defines Image Viewer API.
*/
export interface ImageViewerAPI {
/**
* Indicates whether the viewer has opened the image.
* @example
*```javascript
* const hasImageFlag = viewer.hasImage;
*```
*/
readonly hasImage: boolean;
/**
* Gets the active image DPI adaptive natural size.
* This is the image size that will be used to display the image at 100%.
* The adaptiveNaturalSize property is used for the actual size calculations.
*/
readonly adaptiveNaturalSize: Size;
/**
* Gets the actual display size of the active image, including the active zoom value.
*/
readonly actualSize: Size;
/**
* language - A property that retrieves the standardized language key based on the provided language option.
* The language key is determined by the `options.language` setting.
* @returns {string} Standardized language key (e.g., 'en', 'ja').
*/
readonly language: string;
/**
* Image layers. Used for painting.
*/
readonly layers: ImageLayer[];
/**
* Gets the active image natural size.
* The natural size is the image's width/height if drawn with nothing constraining its width/height,
* this is the number of CSS pixels wide the image will be.
*/
readonly naturalSize: Size;
/**
* The Open parameters that were used to open an image.
*/
readonly openParameters: OpenParameters | undefined;
/**
* Command based undo state storage.
* @example
* ```javascript
* const isUndoInProgress = viewer.undoStorage.undoInProgress;
* ```
*/
readonly undoStorage: UndoStorage;
/**
* Gets a value indicating whether the image viewer can undo changes.
* @example
* ```javascript
* if(viewer.hasUndo) {
* viewer.undo();
* }
* ```
*/
readonly hasUndo: boolean;
/**
* Gets a value indicating whether the image viewer can redo changes.
* @example
* ```javascript
* if(viewer.hasRedo) {
* viewer.redo();
* }
* ```
*/
readonly hasRedo: boolean;
/**
* Gets current undo level index.
* @example
* ```javascript
* alert("The current Undo level index is " + viewer.undoIndex);
* ```
*/
readonly undoIndex: number;
/**
* Gets total undo levels count.
* @example
* ```javascript
* alert("Undo levels count is " + viewer.undoCount);
* ```
*/
readonly undoCount: number;
/**
* Returns the current version of the DS Image viewer.
* @example
* ```javascript
* alert("The DsImageViewer version is " + viewer.version);
* ```
*/
readonly version: string;
/**
* Gets total frames count for the active image. Applicable for TIFF, ICO images.
* @example
* ```javascript
* const viewer = new DsImageViewer('#root');
* viewer.onAfterOpen.register(function() {
* alert("The image opened. Total number of frames: " + viewer.framesCount);
* });
* viewer.open('Test.png');
* ```
*/
readonly framesCount: number;
/**
* Image viewer event bus.
* @example
* ```javascript
* viewer.eventBus.on("after-open", function(args) {
* console.log("Image opened.", args);
* });
* viewer.open('Test.png');
* ```
*/
readonly eventBus: EventBus;
/**
* The event raised when the user changes the viewer theme.
* @example
* ```javascript
* const viewer = new DsImageViewer('#root');
* viewer.onAfterOpen.register(function() {
* alert("The image opened.");
* });
* viewer.open('Test.png');
* ```
*/
readonly onAfterOpen: EventFan;
/**
* Occurs immediately before the image opens.
* @example
* ```javascript
* const viewer = new DsImageViewer('#root');
* viewer.onBeforeOpen.register(function(args) {
* alert("A new image will be opened,\n payload type(binary or URL): " + args.type +",\n payload(bytes or string): " + args.payload);
* });
* viewer.open('Test.png');
* ```
*/
readonly onBeforeOpen: EventFan;
/**
* The event indicating error.
* @example
* ```javascript
* function handleError(args) {
* console.error(args);
* }
* const viewer = new DsImageViewer('#root');
* viewer.onError.register(handleError);
* viewer.open('Test.png');
* ```
*/
readonly onError: EventFan;
/**
* The event raised when appearance image element changed.
*/
readonly onImagePaint: EventFan;
/**
* Gets a value indicating whether the image animation has started.
* @example
* ```javascript
* // Toggle image animation:
* const viewer = DsImageViewer.findControl("#root");
* if(viewer.isAnimationStarted) {
* viewer.stopAnimation();
* } else {
* viewer.startAnimation();
* }
* ```
*/
readonly isAnimationStarted: boolean;
/**
* Viewer options
*/
options: Partial<ViewerOptions>;
/**
* Defines the layout of the toolbar.
* The full list of the *viewer* specific toolbar items:
* ```javascript
* 'open', '$navigation', 'navigation-auto', '$split', 'zoom', '$fullscreen', 'save', 'about'
* ```
* @example
* ```javascript
* // Customize the toolbar layout:
* viewer.toolbarLayout.viewer.default = ["open", "$zoom", "$fullscreen", "save", "print", "about"];
* viewer.applyToolbarLayout();
* ```
*/
toolbarLayout: ImageToolbarLayout;
/**
* Gets or sets the active frame index.
* This is applicable for multi-frame images such as TIFF and ICO.
*
* When setting this value, it will also be used as the initial frame index when opening a new image.
*
* @example
* ```javascript
* const viewer = new DsImageViewer('#root');
* viewer.frameIndex = 9;
* viewer.open('Test.ico');
* ```
*/
frameIndex: number;
/**
* Gets or sets the current zoom settings
*/
zoom: ZoomSettings;
/**
* Create at least one image layer which will be used for painting.
*/
ensurePaintLayer(): ImageLayer;
/**
* Remove and dispose image layer given by argument layerOrIndex.
* @param layerOrIndex Image layer or image layer index or image layer name.
*/
removeLayer(layerOrIndex: string | number | ImageLayer): void;
/**
* Remove and dispose all image layers.
*/
removeLayers(): void;
/**
* Call this method in order to apply changed options.
* @example
*
* ```javascript
* viewer.applyOptions();
* ```
*/
applyOptions(): void;
/**
* Call this method in order to apply changes in @see:toolbarLayout.
* @example
* ```javascript
* viewer.toolbarLayout.viewer.default = ["open", "save"];
* viewer.applyToolbarLayout();
* ```
* @example
* ```javascript
* const viewer = new DsImageViewer(document.querySelector("#viewer"));
* const toolbar = viewer.toolbar;
* const toolbarLayout = viewer.toolbarLayout;
* toolbar.addItem({
* key: 'custom-action',
* icon: { type: "svg", content: '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="24" height="24" viewBox="0 0 24 24"><path style="fill: #205F78;" d="M20.25 12l-2.25 2.25 2.25 2.25-3.75 3.75-2.25-2.25-2.25 2.25-2.25-2.25-2.25 2.25-3.75-3.75 2.25-2.25-2.25-2.25 2.25-2.25-2.25-2.25 3.75-3.75 2.25 2.25 2.25-2.25 2.25 2.25 2.25-2.25 3.75 3.75-2.25 2.25 2.25 2.25z"></path></svg>' },
* title: 'Custom action',
* checked: false, enabled: false,
* action: function () {
* alert("Implement your action here.");
* },
* onUpdate: function (args) {
* return {
* enabled: true,
* checked: false,
* title: 'Custom action title'
* }
* }
* });
* toolbarLayout.viewer.default.splice(0, 0, "custom-action");
* viewer.applyToolbarLayout();
* ```
*/
applyToolbarLayout(): void;
/**
* Adds a plugin instance to the `DsImageViewer`. This method is now intended for internal and officially supported plugins only. Custom or third-party plugins are **no longer supported** starting from version 9.0. The plugin system remains available for internal use to provide optional viewer features, such as `ImageFiltersPlugin`, `PageToolsPlugin`, and `PaintToolsPlugin`. Attempting to register non-official plugins may lead to undefined behavior and is not supported by the product team.
* @param plugin The plugin instance
* @returns `true` if added successfully; otherwise `false`.
* @example
*
* ```javascript
* // ✅ Supported (built-in plugin)
* const viewer = new DsImageViewer("#root");
* viewer.addPlugin(new ImageFiltersPlugin());
*
* // ❌ Not supported (custom plugin)
* viewer.addPlugin(new CustomPlugin()); // Custom plugins are no longer supported
* ```
*/
addPlugin(plugin: ImageViewerPluginReference): boolean;
/**
* Add window keyboard listener.
* @param {string} uniqueKey Listener key.
* @param {WindowKeyboardListener} handler Keyboard event handler.
*/
addKeyboardListener(uniqueKey: string, handler: WindowKeyboardListener): void;
/**
* Remove window keyboard listener.
* @param {string} uniqueKey Listener key.
*/
removeKeyboardListener(uniqueKey: string): void;
/**
* Allows to configure the main toolbar layout.
* @param {number | boolean | undefined} pos The position where the buttons should be inserted. Use `false` or `-1` to skip insertion. Undefined means the position will be determined automatically.
* @param {string[]} buttonsToInsert An array of button keys to be inserted.
* @example
*
* ```ts
* // Apply a custom layout to insert "zoomIn" and "zoomOut" buttons at position 2 for the "PaintTools" plugin.
* viewer.configurePluginMainToolbar(2, ["zoomIn", "zoomOut"]);
* ```
*/
configurePluginMainToolbar(pos: number | boolean | undefined, buttonsToInsert: string[]): void;
/**
* Retrieves the point location from the pointer event provided by the 'event' parameter.
* The returned point is relative to the active canvas element.
* @param event DOM Pointer or Mouse event object.
*/
getEventCanvasPoint(event: MouseEvent | PointerEvent, includeDpi: boolean): PointLocation;
/**
* Sets the cursor style for the image viewer
* @param {GlobalCursorType} cursorType - The cursor style to apply
* @example
* ```ts
* // Set rotate cursor during image rotation
* viewer.setCursor('rotate');
* ```
*
* @example
* ```ts
* // Set resize cursor when hovering over edges
* viewer.setCursor('nwse-resize');
* ```
*
* @see GlobalCursorType for all available cursor options
*/
setCursor(cursorType: GlobalCursorType): void;
/**
* Resets the cursor to default style
* @example
* ```ts
* // Reset cursor when operation completes
* viewer.resetCursor();
* ```
*
* @example
* ```ts
* // Reset cursor on mouse leave
* viewerElement.addEventListener('mouseleave', () => {
* viewer.resetCursor();
* });
* ```
*/
resetCursor(): void;
/**
* Toggles between specified cursor and default style
* @param {GlobalCursorType | false} cursorType - Cursor style to apply, or false to reset
* @example
* // Toggle grab cursor during drag operations
* viewer.toggleCursor(isDragging ? 'grab' : false);
*
* @example
* // Toggle zoom cursor based on modifier key
* document.addEventListener('keydown', (e) => {
* if (e.ctrlKey) {
* viewer.toggleCursor('zoom-in');
* }
* });
*
*/
toggleCursor(cursorType: false | GlobalCursorType): void;
/**
* Load image data using given data url.
* @param {Size} destinationSize Defines needed image size
*/
dataUrlToImageData(dataUrl: string, destinationSize?: Size): Promise<ImageData>;
/**
* Display confirmation dialog.
* @param {any} confirmationText Confirmation text can be plain string or JSX.Element if you're using React.
*
* @example
* ```javascript
* const confirmResult = await viewer.confirm("Apply changes?", "info", "Confirm action", ["Yes", "No", "Cancel"]);
* if (confirmResult === "Yes") {
* // put your code here
* } else if (confirmResult === "No") {
* // put your code here
* } else {
* // put your code here
* }
* ```
*/
confirm(confirmationText?: any, level?: "error" | "info" | "warning", title?: string, buttons?: ConfirmButton[]): Promise<boolean | ConfirmButton>;
/**
* Removes a plugin instance from the `DsImageViewer`. This method remains available for internal and officially supported plugins only. Custom or third-party plugins are **no longer supported** starting from version 9.0.
* @param {PluginType} pluginId Plugin id or plugin instance.
* @example
*
* ```javascript
* // ✅ Supported
* viewer.removePlugin("ImageFiltersPlugin");
*
* // ❌ Not supported
* viewer.removePlugin("CustomPluginId");
* ```
*/
removePlugin(pluginId: ImageViewerPluginReference | PluginType): void;
/**
* Show about dialog.
*/
showAbout(): void;
/**
* Finds a viewer plugin by its id.
* @param {PluginType} pluginId Plugin id
* @example
* ```javascript
* // find imageFilters plugin:
* const imageFilters = viewer.findPlugin("imageFilters");
* // find pageTools plugin:
* const pageTools = viewer.findPlugin("pageTools");
* ```
*/
findPlugin(pluginId: PluginType): ImageViewerPluginReference | null;
/**
* Remove all plug-ins.
* @example
*
* ```javascript
* viewer.removePlugins();
* ```
*/
removePlugins(): void;
/**
* Clear undo storage.
*/
clearUndo(): void;
/**
* Execute a new command.
* @param {UndoCommandSupport} command Instance of a command.
*/
executeCommand(command: UndoCommandSupport): Promise<void>;
/**
* Create new empty image.
* @param {Partial<Size> & OpenParameters} options Optional. New image parameters.
* @example
* ```javascript
* await viewer.newImage({ width: 300, height: 300, fileName: "myImage.png" });
* ```
*/
newImage(options?: Partial<Size> & OpenParameters): Promise<any>;
/**
* Open Image document.
* @param {string | URL | Uint8Array} file Image URL or it's binary data.
* @param {ImageFormatCode | ImageFormatName | OpenParameters} openParameters Image format or image opening parameters object.
* @example
* ```javascript
* viewer.open("Images/HelloWorld.png");
* ```
*/
open(file: string | URL | Uint8Array, openParameters?: ImageFormatCode | ImageFormatName | OpenParameters): Promise<any>;
/**
* Closes the currently open image.
* @example
* ```javascript
* await viewer.close();
* ```
*/
close(): Promise<void>;
/**
* Use this method to close and release resources occupied by the DsImageViewer.
*/
dispose(): void;
/**
* Show activity spinner.
* @example
*
* ```javascript
* viewer.showActivitySpinner();
* ```
*/
showActivitySpinner(container?: HTMLElement): void;
/**
* Hide activity spinner.
* @example
*
* ```javascript
* viewer.hideActivitySpinner();
* ```
*/
hideActivitySpinner(): void;
/**
* Start GIF animation.
* @example
*
* ```javascript
* DsImageViewer.findControl("#root").startAnimation();
* ```
*/
startAnimation(): void;
/**
* Stop GIF animation. *
* @example
*
* * ```javascript
* * DsImageViewer.findControl("#root").stopAnimation();
* * ```
* *
*/
stopAnimation(): void;
/**
* Toggle GIF animation.
* @example
*
* ```javascript
* DsImageViewer.findControl("#root").toggleAnimation();
* ```
*/
toggleAnimation(): void;
/**
* Undo changes.
* @example
*
* ```javascript
* if(viewer.hasUndo) {
* viewer.undo();
* }
* ```
*/
undo(): Promise<void>;
/**
* Redo changes.
* @example
*
* ```javascript
* if(viewer.hasRedo) {
* viewer.redo();
* }
* ```
*/
redo(): Promise<void>;
/**
* Get event object.
* @param {EventName | string} eventName Embedded or custom event name.
* @example
*
* ```javascript
* viewer.getEvent("CustomEvent").register(function(args) {
* console.log(args);
* });
* ```
*/
getEvent(eventName: EventName | string): EventFan;
/**
* Trigger event.
* @param {EventName | string} eventName Embedded or custom event name.
* @param {Record<string, unknown>} args Arguments for event handler function.
* @example
*
* ```javascript
* // Listen CustomEvent:
* viewer.getEvent("CustomEvent").register(function(args) {
* console.log(args);
* });
* // Trigger CustomEvent:
* viewer.triggerEvent("CustomEvent", { arg1: 1, arg2: 2});
* ```
*/
triggerEvent(eventName: string, args?: Record<string, unknown>): void;
/**
* Get unmodified current image data url.
*/
getOriginalImageDataUrl(): string;
/**
* Get current image data url.
*/
getImageDataUrl(): string;
/**
* Modify current image data url.
*/
setImageDataUrl(dataUrl: any): Promise<void>;
/**
* Displays a second toolbar specified by the toolbarKey argument.
* @param {SecondToolbarType} toolbarKey The key identifying the specific second toolbar to show.
* @returns {Promise<void>} A Promise that resolves once the second toolbar is successfully displayed.
*
* @example
* ```javascript
* // Show the page tools toolbar
* viewer.showSecondToolbar("page-tools");
* ```
*/
showSecondToolbar(toolbarKey: SecondToolbarType): Promise<void>;
/**
* Hides the second toolbar. This method deactivates any active editor mode associated with the second toolbar and then hides the toolbar itself.
* @param {SecondToolbarType} toolbarKey Optional. The key identifying the specific second toolbar to hide. If provided, only hides the specified toolbar if it exists.
* @returns {Promise<void>} A Promise that resolves once the second toolbar is successfully hidden.
*
* @example
* ```javascript
* // Hide the second toolbar
* viewer.hideSecondToolbar();
* ```
*
* @example
* ```javascript
* // Hide a specific second toolbar by passing its key
* viewer.hideSecondToolbar("page-tools");
* ```
*/
hideSecondToolbar(toolbarKey?: SecondToolbarType): Promise<void>;
/**
* Show the file open dialog where the user can select the Image file.
*
* @example
* ```javascript
* viewer.openLocalFile();
* ```
*/
openLocalFile(): void;
/**
* Saves the Image document loaded in the Viewer to the local disk.
* @param {string | SaveOptions} options Optional Destination file name or the save options, including the destination file name and other settings.
* @param {boolean} original Optional Flag indicating whether to use the initial version of the image for save. Defaults to `false`.
*
* @example
* ```javascript
* // Example: Save the modified image without using specific options.
* const viewer = DsImageViewer.findControl("#root");
* viewer.save();
* ```
*
* @example
* ```javascript
* // Example: Save the modified image as "image.png".
* const viewer = DsImageViewer.findControl("#root");
* viewer.save({ fileName: "image.png" });
* ```
*
* @example
* ```javascript
* // Example: Download the original version of the image as "original_image.jpg".
* const viewer = DsImageViewer.findControl("#root");
* viewer.save({ fileName: "original_image.jpg", original: true });
* ```
*
* @example
* ```javascript
* // Example: Save the modified image in PNG format.
* const viewer = DsImageViewer.findControl("#root");
* viewer.save({ convertToFormat: "image/png" });
* ```
*
* @example
* ```javascript
* // Example: Save the modified image with a custom file name and in JPEG format.
* const viewer = DsImageViewer.findControl("#root");
* viewer.save({ fileName: "custom_name", convertToFormat: "image/jpeg" });
* ```
*/
save(options?: string | SaveOptions, original?: boolean): void;
/**
* Shows the message for the user.
* @param {string} message Message title text
* @param {string} details Additional details text, empty by default.
* @param {"error" | "warn" | "info" | "debug"} severity Message severity, default "info".
*/
showMessage(message: string, details: string, severity: "error" | "warn" | "info" | "debug"): void;
}
/**
* Image Viewer toolbar icons list
*/
export type MainToolbarIcon = "about" | "download" | "flip-horizontal" | "flip-vertical" | "magnify-minus-outline" | "magnify-plus-outline" | "magnify" | "open" | "print" | "rotate" | "edit-undo" | "edit-redo";
/**
* Defines custom font names viewer options object
*/
export type FontsOptions = Array<{
/**
* User displayed font name
*/
name: string;
/**
* System font name
*/
value: string;
}>;
/**
* Defines various viewer zoom modes
*/
export declare enum ZoomMode {
Value = 0,
PageWidth = 1,
WholePage = 2
}
/**
* Defines viewer instance zoom settings
*/
export type ZoomSettings = {
mode: ZoomMode.PageWidth;
} | {
mode: ZoomMode.WholePage;
} | {
mode: ZoomMode.Value;
factor: number;
};
/**
* Defines viewer zoom control options
*/
export type ZoomOptions = {
/**
* Defines min zoom factor
* @default 0.25 (25%)
*/
minZoom?: number;
/**
* Defines max zoom factor
* @