From f44ecb69b86c6320288d4cb9a32fe48e8095008c Mon Sep 17 00:00:00 2001 From: Yuan Date: Tue, 12 Dec 2023 17:31:07 +0800 Subject: [PATCH] =?UTF-8?q?=E7=9B=AE=E5=BD=95=E7=BB=93=E6=9E=84=E5=8F=8A?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/app/BasicOperation.d.ts | 42 + lib/app/JlDrawApp.d.ts | 150 + lib/app/JlGraphicApp.d.ts | 601 ++ lib/app/index.d.ts | 17 + lib/core/GraphicRelation.d.ts | 82 + lib/core/GraphicStore.d.ts | 90 + lib/core/IdGenerator.d.ts | 12 + lib/core/JlGraphic.d.ts | 284 + .../core/index.ts => lib/core/index.d.ts | 0 lib/graphic/AbsorbablePosition.d.ts | 91 + lib/graphic/DashedLine.d.ts | 39 + lib/graphic/DraggablePoint.d.ts | 23 + lib/graphic/VectorGraphic.d.ts | 8 + lib/graphic/VectorText.d.ts | 16 + .../index.ts => lib/graphic/index.d.ts | 0 src/jlgraphic/index.ts => lib/index.d.ts | 0 lib/index.js | 6927 +++++++---------- lib/math/Constants.d.ts | 17 + lib/math/Vector2.d.ts | 91 + lib/math/index.d.ts | 2 + lib/message/BasicMessageClient.d.ts | 52 + lib/message/MessageBroker.d.ts | 146 + lib/message/MqttBroker.d.ts | 13 + lib/message/WsMsgBroker.d.ts | 11 + .../index.ts => lib/message/index.d.ts | 0 lib/operation/JlOperation.d.ts | 42 + .../index.ts => lib/operation/index.d.ts | 0 lib/plugins/AnimationManager.d.ts | 48 + lib/plugins/CommonMousePlugin.d.ts | 82 + lib/plugins/CopyPlugin.d.ts | 23 + lib/plugins/GraphicEditPlugin.d.ts | 82 + lib/plugins/GraphicTransformPlugin.d.ts | 207 + lib/plugins/InteractionPlugin.d.ts | 173 + lib/plugins/KeyboardPlugin.d.ts | 81 + .../index.ts => lib/plugins/index.d.ts | 0 lib/ui/ContextMenu.d.ts | 164 + lib/ui/Menu.d.ts | 146 + lib/utils/GraphicUtils.d.ts | 232 + lib/utils/IntersectUtils.d.ts | 119 + lib/utils/debounce.d.ts | 5 + lib/utils/index.d.ts | 26 + package.json | 2 +- rollup.config.ts | 15 +- src/{jlgraphic => }/app/BasicOperation.ts | 0 src/{jlgraphic => }/app/JlDrawApp.ts | 0 src/{jlgraphic => }/app/JlGraphicApp.ts | 14 - src/{jlgraphic => }/app/index.ts | 0 src/{jlgraphic => }/core/GraphicRelation.ts | 0 src/{jlgraphic => }/core/GraphicStore.ts | 0 src/{jlgraphic => }/core/IdGenerator.ts | 1 - src/{jlgraphic => }/core/JlGraphic.ts | 0 src/core/index.ts | 4 + src/{jlgraphic => }/global.d.ts | 0 .../graphic/AbsorbablePosition.ts | 0 src/{jlgraphic => }/graphic/DashedLine.ts | 0 src/{jlgraphic => }/graphic/DraggablePoint.ts | 0 src/{jlgraphic => }/graphic/VectorGraphic.ts | 0 src/{jlgraphic => }/graphic/VectorText.ts | 0 src/graphic/index.ts | 5 + src/graphics/CommonGraphics.ts | 51 - src/graphics/iscs-fan/IscsFan.ts | 139 - src/graphics/iscs-fan/IscsFanDrawAssistant.ts | 109 - src/graphics/iscs-fan/iscs-fan-data.json | 66 - .../iscs-fan/iscs-fan-spritesheet.png | Bin 15944 -> 0 bytes src/graphics/link/Link.ts | 104 - src/graphics/link/LinkDrawAssistant.ts | 451 -- src/graphics/platform/Platform.ts | 203 - .../platform/PlatformDrawAssistant.ts | 123 - src/graphics/rect/Rect.ts | 86 - src/graphics/rect/RectDrawAssistant.ts | 261 - src/graphics/signal/Lamp.ts | 52 - src/graphics/signal/LampMainBody.ts | 51 - src/graphics/signal/Signal.ts | 102 - src/graphics/signal/SignalDrawAssistant.ts | 133 - src/graphics/station/Station.ts | 101 - src/graphics/station/StationDrawAssistant.ts | 93 - src/graphics/train/Train.ts | 185 - src/graphics/train/TrainDrawAssistant.ts | 138 - src/graphics/turnout/Turnout.ts | 9 - src/graphics/turnout/TurnoutDrawAssistant.ts | 0 src/index.ts | 7 + src/{jlgraphic => }/math/Constants.ts | 0 src/{jlgraphic => }/math/Vector2.ts | 0 src/{jlgraphic => }/math/index.ts | 0 .../message/BasicMessageClient.ts | 0 .../message/CentrifugeBroker.ts | 0 src/{jlgraphic => }/message/MessageBroker.ts | 0 src/{jlgraphic => }/message/MqttBroker.ts | 0 src/{jlgraphic => }/message/WsMsgBroker.ts | 0 src/message/index.ts | 1 + src/{jlgraphic => }/operation/JlOperation.ts | 3 - src/operation/index.ts | 1 + .../plugins/AnimationManager.ts | 0 .../plugins/CommonMousePlugin.ts | 13 - src/{jlgraphic => }/plugins/CopyPlugin.ts | 0 .../plugins/GraphicEditPlugin.ts | 1 - .../plugins/GraphicTransformPlugin.ts | 5 - .../plugins/InteractionPlugin.ts | 2 - src/{jlgraphic => }/plugins/KeyboardPlugin.ts | 6 - src/plugins/index.ts | 6 + src/{jlgraphic => }/ui/ContextMenu.ts | 0 src/{jlgraphic => }/ui/Menu.ts | 0 src/{jlgraphic => }/utils/GraphicUtils.ts | 0 src/{jlgraphic => }/utils/IntersectUtils.ts | 0 src/{jlgraphic => }/utils/debounce.ts | 0 src/{jlgraphic => }/utils/index.ts | 0 tsconfig.json | 3 +- 107 files changed, 5994 insertions(+), 6696 deletions(-) create mode 100644 lib/app/BasicOperation.d.ts create mode 100644 lib/app/JlDrawApp.d.ts create mode 100644 lib/app/JlGraphicApp.d.ts create mode 100644 lib/app/index.d.ts create mode 100644 lib/core/GraphicRelation.d.ts create mode 100644 lib/core/GraphicStore.d.ts create mode 100644 lib/core/IdGenerator.d.ts create mode 100644 lib/core/JlGraphic.d.ts rename src/jlgraphic/core/index.ts => lib/core/index.d.ts (100%) create mode 100644 lib/graphic/AbsorbablePosition.d.ts create mode 100644 lib/graphic/DashedLine.d.ts create mode 100644 lib/graphic/DraggablePoint.d.ts create mode 100644 lib/graphic/VectorGraphic.d.ts create mode 100644 lib/graphic/VectorText.d.ts rename src/jlgraphic/graphic/index.ts => lib/graphic/index.d.ts (100%) rename src/jlgraphic/index.ts => lib/index.d.ts (100%) create mode 100644 lib/math/Constants.d.ts create mode 100644 lib/math/Vector2.d.ts create mode 100644 lib/math/index.d.ts create mode 100644 lib/message/BasicMessageClient.d.ts create mode 100644 lib/message/MessageBroker.d.ts create mode 100644 lib/message/MqttBroker.d.ts create mode 100644 lib/message/WsMsgBroker.d.ts rename src/jlgraphic/message/index.ts => lib/message/index.d.ts (100%) create mode 100644 lib/operation/JlOperation.d.ts rename src/jlgraphic/operation/index.ts => lib/operation/index.d.ts (100%) create mode 100644 lib/plugins/AnimationManager.d.ts create mode 100644 lib/plugins/CommonMousePlugin.d.ts create mode 100644 lib/plugins/CopyPlugin.d.ts create mode 100644 lib/plugins/GraphicEditPlugin.d.ts create mode 100644 lib/plugins/GraphicTransformPlugin.d.ts create mode 100644 lib/plugins/InteractionPlugin.d.ts create mode 100644 lib/plugins/KeyboardPlugin.d.ts rename src/jlgraphic/plugins/index.ts => lib/plugins/index.d.ts (100%) create mode 100644 lib/ui/ContextMenu.d.ts create mode 100644 lib/ui/Menu.d.ts create mode 100644 lib/utils/GraphicUtils.d.ts create mode 100644 lib/utils/IntersectUtils.d.ts create mode 100644 lib/utils/debounce.d.ts create mode 100644 lib/utils/index.d.ts rename src/{jlgraphic => }/app/BasicOperation.ts (100%) rename src/{jlgraphic => }/app/JlDrawApp.ts (100%) rename src/{jlgraphic => }/app/JlGraphicApp.ts (98%) rename src/{jlgraphic => }/app/index.ts (100%) rename src/{jlgraphic => }/core/GraphicRelation.ts (100%) rename src/{jlgraphic => }/core/GraphicStore.ts (100%) rename src/{jlgraphic => }/core/IdGenerator.ts (94%) rename src/{jlgraphic => }/core/JlGraphic.ts (100%) create mode 100644 src/core/index.ts rename src/{jlgraphic => }/global.d.ts (100%) rename src/{jlgraphic => }/graphic/AbsorbablePosition.ts (100%) rename src/{jlgraphic => }/graphic/DashedLine.ts (100%) rename src/{jlgraphic => }/graphic/DraggablePoint.ts (100%) rename src/{jlgraphic => }/graphic/VectorGraphic.ts (100%) rename src/{jlgraphic => }/graphic/VectorText.ts (100%) create mode 100644 src/graphic/index.ts delete mode 100644 src/graphics/CommonGraphics.ts delete mode 100644 src/graphics/iscs-fan/IscsFan.ts delete mode 100644 src/graphics/iscs-fan/IscsFanDrawAssistant.ts delete mode 100644 src/graphics/iscs-fan/iscs-fan-data.json delete mode 100644 src/graphics/iscs-fan/iscs-fan-spritesheet.png delete mode 100644 src/graphics/link/Link.ts delete mode 100644 src/graphics/link/LinkDrawAssistant.ts delete mode 100644 src/graphics/platform/Platform.ts delete mode 100644 src/graphics/platform/PlatformDrawAssistant.ts delete mode 100644 src/graphics/rect/Rect.ts delete mode 100644 src/graphics/rect/RectDrawAssistant.ts delete mode 100644 src/graphics/signal/Lamp.ts delete mode 100644 src/graphics/signal/LampMainBody.ts delete mode 100644 src/graphics/signal/Signal.ts delete mode 100644 src/graphics/signal/SignalDrawAssistant.ts delete mode 100644 src/graphics/station/Station.ts delete mode 100644 src/graphics/station/StationDrawAssistant.ts delete mode 100644 src/graphics/train/Train.ts delete mode 100644 src/graphics/train/TrainDrawAssistant.ts delete mode 100644 src/graphics/turnout/Turnout.ts delete mode 100644 src/graphics/turnout/TurnoutDrawAssistant.ts create mode 100644 src/index.ts rename src/{jlgraphic => }/math/Constants.ts (100%) rename src/{jlgraphic => }/math/Vector2.ts (100%) rename src/{jlgraphic => }/math/index.ts (100%) rename src/{jlgraphic => }/message/BasicMessageClient.ts (100%) rename src/{jlgraphic => }/message/CentrifugeBroker.ts (100%) rename src/{jlgraphic => }/message/MessageBroker.ts (100%) rename src/{jlgraphic => }/message/MqttBroker.ts (100%) rename src/{jlgraphic => }/message/WsMsgBroker.ts (100%) create mode 100644 src/message/index.ts rename src/{jlgraphic => }/operation/JlOperation.ts (94%) create mode 100644 src/operation/index.ts rename src/{jlgraphic => }/plugins/AnimationManager.ts (100%) rename src/{jlgraphic => }/plugins/CommonMousePlugin.ts (93%) rename src/{jlgraphic => }/plugins/CopyPlugin.ts (100%) rename src/{jlgraphic => }/plugins/GraphicEditPlugin.ts (99%) rename src/{jlgraphic => }/plugins/GraphicTransformPlugin.ts (99%) rename src/{jlgraphic => }/plugins/InteractionPlugin.ts (99%) rename src/{jlgraphic => }/plugins/KeyboardPlugin.ts (97%) create mode 100644 src/plugins/index.ts rename src/{jlgraphic => }/ui/ContextMenu.ts (100%) rename src/{jlgraphic => }/ui/Menu.ts (100%) rename src/{jlgraphic => }/utils/GraphicUtils.ts (100%) rename src/{jlgraphic => }/utils/IntersectUtils.ts (100%) rename src/{jlgraphic => }/utils/debounce.ts (100%) rename src/{jlgraphic => }/utils/index.ts (100%) diff --git a/lib/app/BasicOperation.d.ts b/lib/app/BasicOperation.d.ts new file mode 100644 index 0000000..3dc5480 --- /dev/null +++ b/lib/app/BasicOperation.d.ts @@ -0,0 +1,42 @@ +import { GraphicData, JlGraphic } from '../core'; +import { JlOperation } from '../operation'; +import { ICanvasProperties, IGraphicApp, IJlCanvas } from './JlGraphicApp'; +/** + * 更新画布操作 + */ +export declare class UpdateCanvasOperation extends JlOperation { + obj: IJlCanvas; + old: ICanvasProperties; + data: ICanvasProperties; + description: string; + constructor(app: IGraphicApp, obj: IJlCanvas, old: ICanvasProperties, data: ICanvasProperties); + undo(): JlGraphic[]; + redo(): JlGraphic[]; +} +/** + * 创建图形操作 + */ +export declare class GraphicCreateOperation extends JlOperation { + obj: JlGraphic[]; + description: string; + constructor(app: IGraphicApp, obj: JlGraphic[]); + undo(): JlGraphic[] | void; + redo(): JlGraphic[]; +} +/** + * 删除图形操作 + */ +export declare class GraphicDeleteOperation extends JlOperation { + obj: JlGraphic[]; + constructor(app: IGraphicApp, obj: JlGraphic[]); + undo(): JlGraphic[]; + redo(): void; +} +export declare class GraphicDataUpdateOperation extends JlOperation { + obj: JlGraphic[]; + oldData: GraphicData[]; + newData: GraphicData[]; + constructor(app: IGraphicApp, obj: JlGraphic[], oldData: GraphicData[], newData: GraphicData[]); + undo(): void | JlGraphic[]; + redo(): void | JlGraphic[]; +} diff --git a/lib/app/JlDrawApp.d.ts b/lib/app/JlDrawApp.d.ts new file mode 100644 index 0000000..88c281e --- /dev/null +++ b/lib/app/JlDrawApp.d.ts @@ -0,0 +1,150 @@ +import { BitmapFont, BitmapText, Container, FederatedMouseEvent, Point } from 'pixi.js'; +import { GraphicData, GraphicTemplate, JlGraphic } from '../core/JlGraphic'; +import { AppInteractionPlugin, InteractionPlugin, KeyListener } from '../plugins'; +import { GraphicApp, GraphicAppOptions, ICanvasProperties, IGraphicApp, IJlCanvas } from './JlGraphicApp'; +/** + * 图形绘制助手 + */ +export declare abstract class GraphicDrawAssistant extends AppInteractionPlugin { + readonly __GraphicDrawAssistant = true; + app: IDrawApp; + type: string; + description: string; + icon: string; + container: Container; + graphicTemplate: GT; + escListener: KeyListener; + onEsc(): void; + constructor(graphicApp: IDrawApp, graphicTemplate: GT, icon: string, description: string); + get canvas(): IJlCanvas; + bind(): void; + unbind(): void; + onLeftDown(e: FederatedMouseEvent): void; + onMouseMove(e: FederatedMouseEvent): void; + onLeftUp(e: FederatedMouseEvent): void; + onRightDown(e: FederatedMouseEvent): void; + onRightUp(e: FederatedMouseEvent): void; + onRightClick(e: FederatedMouseEvent): void; + /** + * 获取下一个id + */ + nextId(): string; + clearCache(): void; + /** + * 重绘 + * @param cp 鼠标所在画布坐标 + */ + abstract redraw(cp: Point): void; + abstract prepareData(data: GD): boolean; + toCanvasCoordinates(p: Point): Point; + /** + * 保存创建的图形对象 + */ + storeGraphic(...graphics: JlGraphic[]): void; + /** + * 创建并添加到图形App + */ + createAndStore(finish: boolean): JlGraphic | null; + /** + * 绘制完成 + */ + finish(...graphics: JlGraphic[]): void; +} +/** + * 绘制助手类型 + */ +export type DrawAssistant = GraphicDrawAssistant; +/** + * 绘制配置选项 + */ +export type DrawAppOptions = GraphicAppOptions; +/** + * 绘制应用接口 + */ +export interface IDrawApp extends IGraphicApp { + /** + * 是否正在绘制图形 + */ + get drawing(): boolean; + /** + * 更新绘制中状态 + */ + set drawing(value: boolean); + /** + * 设置配置选项 + * @param options + */ + setOptions(options: DrawAppOptions): void; + /** + * 获取绘制助手 + */ + getDrawAssistant(graphicType: string): DA; + /** + * 更新画布并记录 + * @param data + */ + updateCanvasAndRecord(data: ICanvasProperties): void; + /** + * 更新图形并记录 + * @param g + * @param data + */ + updateGraphicAndRecord(g: JlGraphic, data: GraphicData): void; + /** + * 绑定form表单对象 + * @param form + */ + bindFormData(form: GraphicData): void; + /** + * 解绑form表单对象 + * @param form + */ + unbindFormData(form: GraphicData): void; +} +/** + * 绘制应用 + */ +export declare class JlDrawApp extends GraphicApp implements IDrawApp { + font: BitmapFont; + coordinates: BitmapText; + scaleText: BitmapText; + drawAssistants: DrawAssistant[]; + _drawing: boolean; + private debouncedFormDataUpdator; + get drawing(): boolean; + set drawing(value: boolean); + constructor(options: DrawAppOptions); + setOptions(options: DrawAppOptions): void; + registerInteractionPlugin(...plugins: InteractionPlugin[]): void; + getDrawAssistant(graphicType: string): DA; + private appOperationRecord; + /** + * 绘制状态信息显示 + */ + private appendDrawStatesDisplay; + bindKeyboardOperation(): void; + /** + * 图形对象存储处理,默认添加图形交互 + * @param graphic + */ + beforeGraphicStore(graphic: JlGraphic): void; + formData: GraphicData | undefined; + /** + * 绑定form表单对象 + * @param form + */ + bindFormData(form: GraphicData): void; + /** + * 移除form绑定 + * @param form + */ + unbindFormData(form: GraphicData): void; + private formDataSyncListen; + /** + * 处理表单数据更新(使用debounce限流) + */ + private handleFormDataUpdate; + private doFormDataUpdate; + updateCanvasAndRecord(data: ICanvasProperties): void; + updateGraphicAndRecord(g: JlGraphic, data: GraphicData): void; +} diff --git a/lib/app/JlGraphicApp.d.ts b/lib/app/JlGraphicApp.d.ts new file mode 100644 index 0000000..b97e91c --- /dev/null +++ b/lib/app/JlGraphicApp.d.ts @@ -0,0 +1,601 @@ +/// +import EventEmitter from 'eventemitter3'; +import { Viewport } from 'pixi-viewport'; +import { Application, Container, DisplayObject, Graphics, Point } from 'pixi.js'; +import { GraphicQueryStore } from '../core/GraphicStore'; +import { GraphicData, GraphicState, GraphicTemplate, GraphicTransform, JlGraphic } from '../core/JlGraphic'; +import { AbsorbablePosition } from '../graphic'; +import { AppWsMsgBroker, GraphicQuery, ICreateOnNotFound, type AppStateSubscription, type MessageCliOption } from '../message'; +import { OperationRecord } from '../operation/JlOperation'; +import { AnimationManager, IMouseToolOptions } from '../plugins'; +import { GraphicCopyPlugin } from '../plugins/CopyPlugin'; +import { AppDragEvent, InteractionPlugin } from '../plugins/InteractionPlugin'; +import { JlGraphicAppKeyboardPlugin, KeyListener } from '../plugins/KeyboardPlugin'; +import { ContextMenu, ContextMenuPlugin } from '../ui/ContextMenu'; +import { MenuItemOptions } from '../ui/Menu'; +export declare const AppConsts: { + viewportname: string; + canvasname: string; + AssistantAppendsName: string; + assistantElementColor: string; +}; +/** + * 画布属性 + */ +export interface ICanvasProperties { + width: number; + height: number; + backgroundColor: string; + viewportTransform: GraphicTransform; +} +export declare class CanvasData implements ICanvasProperties { + width: number; + height: number; + backgroundColor: string; + viewportTransform: GraphicTransform; + constructor(properties?: ICanvasProperties); + copyFrom(properties: ICanvasProperties): boolean; + clone(): CanvasData; +} +export interface IJlCanvas extends Container { + /** + * 获取画布属性 + */ + get properties(): ICanvasProperties; + /** + * 获取所属场景 + */ + get scene(): IGraphicScene; + /** + * 更新画布属性 + * @param properties + */ + update(properties: ICanvasProperties): void; + /** + * 添加辅助附加元素 + * @param appends + */ + addAssistantAppends(...appends: DisplayObject[]): void; + /** + * 移除辅助附加元素 + * @param appends + */ + removeAssistantAppends(...appends: DisplayObject[]): void; + /** + * 保存画布及视口缩放数据 + */ + saveData(): ICanvasProperties; +} +export declare class JlCanvas extends Container implements IJlCanvas { + __JlCanvas: boolean; + type: string; + scene: IGraphicScene; + _properties: CanvasData; + bg: Graphics; + nonInteractiveContainer: Container; + assistantAppendContainer: Container; + constructor(scene: IGraphicScene, properties?: CanvasData); + /** + * 图形重绘(数据/状态变化时触发) + */ + repaint(): void; + get width(): number; + get height(): number; + get backgroundColor(): string; + doRepaint(): void; + get properties(): CanvasData; + saveData(): CanvasData; + update(properties: ICanvasProperties): void; + addChild(...children: U): U[0]; + removeChild(...children: U): U[0]; + /** + * 添加无交互Child + */ + addNonInteractiveChild(...obj: DisplayObject[]): void; + removeGraphic(...obj: DisplayObject[]): void; + /** + * 移除无交互Child + */ + removeNonInteractiveChild(...obj: DisplayObject[]): void; + addAssistantAppends(...appends: DisplayObject[]): void; + removeAssistantAppends(...appends: DisplayObject[]): void; + /** + * 暂停所有可交互对象 + */ + pauseInteractiveChildren(): void; + /** + * 恢复所有可交互对象 + */ + resumeInteractiveChildren(): void; +} +/** + * 选中改变事件 + */ +export declare class SelectedChangeEvent { + graphic: JlGraphic; + select: boolean; + constructor(graphic: JlGraphic, select: boolean); +} +/** + * 应用事件 + */ +export interface GraphicAppEvents extends GlobalMixins.GraphicAppEvents { + graphicstored: [graphic: JlGraphic]; + graphicdeleted: [graphic: JlGraphic]; + postdataloaded: []; + loadfinish: []; + 'interaction-plugin-resume': [plugin: InteractionPlugin]; + 'interaction-plugin-pause': [plugin: InteractionPlugin]; + 'options-update': [options: GraphicAppOptions]; + graphicselectedchange: [graphic: JlGraphic, selected: boolean]; + graphicchildselectedchange: [child: DisplayObject, selected: boolean]; + graphicselected: [graphics: JlGraphic[]]; + 'viewport-scaled': [vp: Viewport]; + drag_op_start: [event: AppDragEvent]; + drag_op_move: [event: AppDragEvent]; + drag_op_end: [event: AppDragEvent]; + 'pre-menu-handle': [menu: MenuItemOptions]; + 'post-menu-handle': [menu: MenuItemOptions]; + 'websocket-connect-state-change': [connected: boolean]; + 'websocket-error': [err: Error]; + destroy: [app: IGraphicApp]; +} +/** + * 图形数据存储 + */ +export interface IGraphicStorage { + /** + * 画布属性 + */ + canvasProperty?: ICanvasProperties; + /** + * 图形数据 + */ + datas: GraphicData[]; +} +/** + * 图形App构造参数 + */ +export interface IGraphicAppConfig { + /** + * 数据加载 + * @returns + */ + dataLoader?: () => Promise; + /** + * 最大保存的操作记录数,默认100,越大越占用内存资源 + */ + maxOperationRecords?: number; + /** + * 拖拽触发移动门槛 + */ + threshold?: number; + /** + * 通用鼠标工具选项 + */ + mouseToolOptions?: IMouseToolOptions; + /** + * 可吸附位置列表 + */ + absorbablePositions?: AbsorbablePosition[]; + /** + * 超出屏幕显示范围是否剪裁,默认true + */ + cullable?: boolean; + /** + * 是否支持删除操作 + */ + isSupportDeletion?: (g: JlGraphic) => boolean; + /** + * 辅助元素颜色,默认蓝色 + */ + assistantElementColor?: string; +} +/** + * 图形添加到容器选项 + */ +export interface IInteractiveGraphicOptions { + /** + * 包含添加到可交互容器的图形类型,和Excludes同时只能存在一个 + */ + interactiveGraphicTypeIncludes?: string[]; + /** + * 不包含添加到可交互容器的图形类型,和Includes同时只能存在一个 + */ + interactiveGraphicTypeExcludes?: string[]; +} +export type GraphicAppOptions = IGraphicAppConfig & IInteractiveGraphicOptions; +/** + * 图形场景接口 + */ +export interface IGraphicScene extends EventEmitter { + /** + * 获取图形应用对象 + */ + get app(): GraphicApp; + /** + * 获取pixijs应用对象 + */ + get pixi(): Application; + /** + * 获取视口对象 + */ + get viewport(): Viewport; + /** + * 获取画布对象 + */ + get canvas(): IJlCanvas; + /** + * 获取dom + */ + get dom(): HTMLElement | undefined; + /** + * 获取图形查询仓库 + */ + get queryStore(): GraphicQueryStore; + /** + * 获取选中的图形对象 + */ + get selectedGraphics(): JlGraphic[]; + /** + * 获取动画管理器 + */ + get animationManager(): AnimationManager; + /** + * 获取配置选项 + */ + get appOptions(): GraphicAppOptions; + /** + * 设置配置选项 + * @param options + */ + setOptions(options: GraphicAppOptions): void; + /** + * 注册菜单 + * @param menu + */ + registerMenu(menu: ContextMenu): void; + /** + * 将屏幕点转换为画布坐标 + * @param p 屏幕坐标 + */ + toCanvasCoordinates(p: Point): Point; + /** + * 加载/重新加载数据(若已经加载过,则不会重新加载) + */ + reload(): Promise; + /** + * 强制重新加载,无论是否已经加载过 + */ + forceReload(): Promise; + /** + * 绑定到dom + * @param dom + */ + bindDom(dom: HTMLElement): void; + /** + * 从dom节点移除 + */ + unbindDom(): void; + /** + * 注册图形模板 + * @param graphicTemplates + */ + registerGraphicTemplates(...graphicTemplates: GraphicTemplate[]): void; + /** + * 处理图形状态 + * @param graphicStates + */ + handleGraphicStates(graphicStates: GraphicState[], queryer?: GraphicQuery, createOnNotFound?: ICreateOnNotFound): void; + /** + * 根据类型获取图形模板 + * @param type + */ + getGraphicTemplatesByType(type: string): GT; + /** + * 添加图形 + * @param graphics + */ + addGraphics(...graphics: JlGraphic[]): void; + /** + * 删除图形 + * @param graphics + */ + deleteGraphics(...graphics: JlGraphic[]): JlGraphic[]; + /** + * 检测并构建关系 + */ + detectRelations(): void; + /** + * 注册交互插件 + * @param plugins + */ + registerInteractionPlugin(...plugins: InteractionPlugin[]): void; + /** + * 暂停交互插件 + */ + pauseAppInteractionPlugins(): void; + /** + * 根据name获取交互插件 + * @param name + */ + interactionPlugin

(name: string): P; + /** + * 更新选中图形对象 + * @param graphics + */ + updateSelected(...graphics: JlGraphic[]): void; + /** + * 选中所有图形 + */ + selectAllGraphics(): void; + /** + * 使所选图形居中 + * @param group + */ + makeGraphicCenterShow(...group: JlGraphic[]): void; + /** + * 销毁 + */ + destroy(): void; + /** + * 订阅websocket消息 + */ + subscribe(sub: AppStateSubscription): void; + /** + * 取消websocket订阅 + */ + unsubscribe(destination: string): void; +} +declare abstract class GraphicSceneBase extends EventEmitter implements IGraphicScene { + private graphicStore; + _options: GraphicAppOptions; + pixi: Application; + viewport: Viewport; + canvas: JlCanvas; + _loaded: boolean; + _dom?: HTMLElement; + _viewportResizer?: NodeJS.Timeout; + graphicTemplateMap: Map; + interactionPluginMap: Map; + graphicCopyPlugin: GraphicCopyPlugin; + animationManager: AnimationManager; + menuPlugin: ContextMenuPlugin; + private debounceEmitFunc; + wsMsgBroker: AppWsMsgBroker; + constructor(options: GraphicAppOptions); + get appOptions(): GraphicAppOptions; + abstract get app(): GraphicApp; + get dom(): HTMLElement | undefined; + get queryStore(): GraphicQueryStore; + get selectedGraphics(): JlGraphic[]; + private load; + /** + * 重新加载数据 + */ + reload(): Promise; + forceReload(): Promise; + /** + * 更新选项 + * @param options + */ + setOptions(options: GraphicAppOptions): void; + toCanvasCoordinates(p: Point): Point; + /** + * 注册菜单 + * @param menu + */ + registerMenu(menu: ContextMenu): void; + /** + * 注册图形对象模板 + * @param graphicTemplates + */ + registerGraphicTemplates(...graphicTemplates: GraphicTemplate[]): void; + getGraphicTemplatesByType(type: string): GT; + private updateViewport; + /** + * 暂停 + */ + private pause; + /** + * 恢复 + */ + private resume; + bindDom(dom: HTMLElement): void; + unbindDom(): void; + /** + * 加载图形,GraphicApp默认添加到无交互容器,DrawApp默认添加到交互容器,如需定制,提供选项配置 + * @param protos + * @param options 添加到可交互/不可交互容器选项配置 + */ + loadGraphic(protos: GraphicData[]): Promise; + /** + * 添加图形前处理 + * @param graphic + */ + beforeGraphicStore(graphic: JlGraphic): void; + /** + * 执行添加图形对象 + * @param graphic + */ + private doAddGraphics; + private doDeleteGraphics; + /** + * 存储图形 + * @param graphics 图形对象 + */ + addGraphics(...graphics: JlGraphic[]): void; + /** + * 删除图形 + * @param graphics 图形对象 + */ + deleteGraphics(...graphics: JlGraphic[]): JlGraphic[]; + /** + * 检测并构建关系 + */ + detectRelations(): void; + /** + * 全选 + */ + selectAllGraphics(filter?: (g: JlGraphic) => boolean): void; + /** + * 更新选中 + */ + updateSelected(...graphics: JlGraphic[]): void; + private doEmitAppGraphicSelected; + /** + * 更新画布 + * @param param + */ + updateCanvas(param: ICanvasProperties): void; + /** + * 使图形居中显示(所有图形的外包围盒) + */ + makeGraphicCenterShow(...group: JlGraphic[]): void; + /** + * 注册交互插件,会替换旧的 + */ + registerInteractionPlugin(...plugins: InteractionPlugin[]): void; + /** + * 根据名称获取交互插件 + * @param name + * @returns + */ + interactionPlugin

(name: string): P; + /** + * 停止应用交互插件 + */ + pauseAppInteractionPlugins(): void; + private doPauseInteractionPlugin; + /** + * 移除交互插件 + */ + removeInteractionPlugin(plugin: InteractionPlugin): void; + private checkWsMsgCli; + /** + * 订阅websocket消息 + */ + subscribe(sub: AppStateSubscription): void; + /** + * 取消websocket订阅 + */ + unsubscribe(destination: string): void; + /** + * 处理图形状态 + * @param graphicStates + */ + handleGraphicStates(graphicStates: GraphicState[], queryer?: GraphicQuery, createOnNotFound?: ICreateOnNotFound): void; + /** + * 销毁 + */ + destroy(): void; +} +/** + * 图形应用接口 + */ +export interface IGraphicApp extends IGraphicScene { + get opRecord(): OperationRecord; + /** + * 实例化一个场景 + * @param code 场景标识 + * @returns + */ + initScene(code: string, options: GraphicAppOptions): IGraphicScene; + /** + * 获取场景 + * @param code + * @returns + */ + getScene(code: string): IGraphicScene; + /** + * 切换场景 + * @param dom + */ + switchScene(code: string, dom: HTMLElement): void; + /** + * 移除指定code场景 + * @param code + */ + removeScene(code: string): void; + /** + * 添加图形并记录 + * @param graphics + */ + addGraphicAndRecord(...graphics: JlGraphic[]): void; + /** + * 删除图形并记录 + * @param graphics + */ + deleteGraphicAndRecord(...graphics: JlGraphic[]): void; + /** + * 启动websocket消息客户端 + */ + enableWsMassaging(options: MessageCliOption): void; + /** + * 添加键盘监听器,如果是相同的按键,新注册的会覆盖旧的,当移除新的时,旧的自动生效 + * @param keyListeners + */ + addKeyboardListener(...keyListeners: KeyListener[]): void; + /** + * 移除键盘监听器 + * @param keyListeners + */ + removeKeyboardListener(...keyListeners: KeyListener[]): void; +} +/** + * 图形app基类 + */ +export declare class GraphicApp extends GraphicSceneBase implements IGraphicApp { + /** + * 场景列表 + */ + scenes: Map; + opRecord: OperationRecord; + keyboardPlugin: JlGraphicAppKeyboardPlugin; + constructor(options: GraphicAppOptions); + get app(): GraphicApp; + setOptions(options: GraphicAppOptions): void; + addGraphicAndRecord(...graphics: JlGraphic[]): void; + deleteGraphicAndRecord(...graphics: JlGraphic[]): void; + /** + * 实例化一个场景 + * @param code 场景标识 + * @returns + */ + initScene(code: string, options: GraphicAppOptions): IGraphicScene; + /** + * 获取场景 + * @param code + * @returns + */ + getScene(code: string): IGraphicScene; + switchScene(code: string, dom: HTMLElement): void; + removeScene(code: string): void; + /** + * 启动websocket消息客户端 + */ + enableWsMassaging(options: MessageCliOption): void; + /** + * 添加键盘监听器,如果是相同的按键,新注册的会覆盖旧的,当移除新的时,旧的自动生效 + * @param keyListeners + */ + addKeyboardListener(...keyListeners: KeyListener[]): void; + /** + * 移除键盘监听器 + * @param keyListeners + */ + removeKeyboardListener(...keyListeners: KeyListener[]): void; + /** + * 销毁 + */ + destroy(): void; +} +/** + * 场景 + */ +export default class JlScene extends GraphicSceneBase { + code: string; + app: GraphicApp; + constructor(app: GraphicApp, code: string, options: GraphicAppOptions); +} +export {}; diff --git a/lib/app/index.d.ts b/lib/app/index.d.ts new file mode 100644 index 0000000..1d31ec9 --- /dev/null +++ b/lib/app/index.d.ts @@ -0,0 +1,17 @@ +import { DrawAppOptions, DrawAssistant, GraphicDrawAssistant, IDrawApp } from './JlDrawApp'; +import { AppConsts, GraphicAppOptions, ICanvasProperties, IGraphicApp, IGraphicScene, IGraphicStorage, IJlCanvas } from './JlGraphicApp'; +import { GraphicDataUpdateOperation } from './BasicOperation'; +/** + * 实例化图形app + * @param options + * @returns + */ +export declare function newGraphicApp(options: GraphicAppOptions): IGraphicApp; +/** + * 实例化绘图app + * @param options + * @returns + */ +export declare function newDrawApp(options: DrawAppOptions): IDrawApp; +export { AppConsts, GraphicDrawAssistant, GraphicDataUpdateOperation }; +export type { DrawAssistant, ICanvasProperties, IDrawApp, IGraphicApp, IGraphicScene, IGraphicStorage, IJlCanvas, }; diff --git a/lib/core/GraphicRelation.d.ts b/lib/core/GraphicRelation.d.ts new file mode 100644 index 0000000..bd99160 --- /dev/null +++ b/lib/core/GraphicRelation.d.ts @@ -0,0 +1,82 @@ +import { JlGraphic } from './JlGraphic'; +/** + * 图形关系数据 + */ +export declare class GraphicRelationParam { + g: JlGraphic; + param: any; + constructor(g: JlGraphic, param?: any); + isTheGraphic(g: JlGraphic): boolean; + getGraphic(): G; + getParam

(): P; + equals(other: GraphicRelationParam): boolean; +} +/** + * 图形关系 + */ +export declare class GraphicRelation { + rp1: GraphicRelationParam; + rp2: GraphicRelationParam; + constructor(rp1: GraphicRelationParam, rp2: GraphicRelationParam); + contains(g: JlGraphic): boolean; + /** + * 获取给定图形的关系参数 + * @param g + * @returns + */ + getRelationParam(g: JlGraphic): GraphicRelationParam; + /** + * 获取关联的另一个图形的关系参数 + * @param g + * @returns + */ + getOtherRelationParam(g: JlGraphic): GraphicRelationParam; + /** + * 获取关联的另一个图形对象 + * @param g + * @returns graphic + */ + getOtherGraphic(g: JlGraphic): G; + equals(orp1: GraphicRelationParam, orp2: GraphicRelationParam): boolean; + isEqualOther(other: GraphicRelation): boolean; +} +/** + * 图形关系管理 + */ +export declare class RelationManage { + relations: GraphicRelation[]; + isContainsRelation(rp1: GraphicRelationParam, rp2: GraphicRelationParam): boolean; + addRelation(rp1: GraphicRelationParam | JlGraphic, rp2: GraphicRelationParam | JlGraphic): void; + /** + * 获取图形的所有关系 + * @param g + * @returns + */ + getRelationsOfGraphic(g: JlGraphic): GraphicRelation[]; + /** + * 获取指定图形的指定关系图形类型的所有关系 + * @param g 指定图形 + * @param type 关联图形的类型 + * @returns + */ + getRelationsOfGraphicAndOtherType(g: JlGraphic, type: string): GraphicRelation[]; + /** + * 删除关系 + * @param relation + */ + private deleteRelation; + /** + * 删除指定图形的所有关系 + * @param g + */ + deleteRelationOfGraphic(g: JlGraphic): void; + /** + * 删除指定图形的所有关系 + * @param g + */ + deleteRelationOfGraphicAndOtherType(g: JlGraphic, type: string): void; + /** + * 清空 + */ + clear(): void; +} diff --git a/lib/core/GraphicStore.d.ts b/lib/core/GraphicStore.d.ts new file mode 100644 index 0000000..b0710fc --- /dev/null +++ b/lib/core/GraphicStore.d.ts @@ -0,0 +1,90 @@ +import { RelationManage } from './GraphicRelation'; +import { JlGraphic } from './JlGraphic'; +export interface GraphicQueryStore { + /** + * 获取所有图形对象 + */ + getAllGraphics(): JlGraphic[]; + /** + * 根据id获取图形 + */ + queryById(id: string): T; + /** + * 根据id模糊查询图形 + * @param id + */ + queryByIdAmbiguous(id: string): JlGraphic[]; + /** + * 根据类型获取图形列表 + */ + queryByType(type: string): T[]; + /** + * 根据code查询 + * @param code + */ + queryByCode(code: string): JlGraphic[] | undefined; + /** + * 根据code模糊查询图形 + * @param code + * @param type + */ + queryByCodeAmbiguous(code: string): JlGraphic[]; + /** + * 根据id或code查询图形 + * @param v + */ + queryByIdOrCode(v: string): JlGraphic[]; + /** + * 根据id或code及类型查询图形 + * @param v + * @param type + */ + queryByIdOrCodeAndType(v: string, type: string): JlGraphic[]; + /** + * 根据code和类型获取图形 + * @param code + * @param type + */ + queryByCodeAndType(code: string, type: string): T | undefined; + /** + * 根据code和类型模糊查询图形 + * @param code + * @param type + */ + queryByCodeAndTypeAmbiguous(code: string, type: string): T[]; +} +/** + * 图形存储 + */ +export declare class GraphicStore implements GraphicQueryStore { + store: Map; + relationManage: RelationManage; + constructor(); + /** + * 获取所有图形对象 + */ + getAllGraphics(): JlGraphic[]; + queryById(id: string): T; + queryByIdAmbiguous(id: string): JlGraphic[]; + queryByType(type: string): T[]; + queryByCode(code: string): JlGraphic[] | undefined; + queryByCodeAmbiguous(code: string): JlGraphic[]; + queryByIdOrCode(s: string): JlGraphic[]; + queryByIdOrCodeAndType(s: string, type: string): JlGraphic[]; + queryByCodeAndType(code: string, type: string): T | undefined; + queryByCodeAndTypeAmbiguous(code: string, type: string): T[]; + /** + * 存储图形对象 + * @param graphics 要存储的图形 + */ + storeGraphics(graphic: JlGraphic): boolean; + /** + * 删除图形 + * @param graph 要删除的图形 + */ + deleteGraphics(graphic: JlGraphic): JlGraphic | undefined; + /** + * 清空 + */ + clear(): void; +} diff --git a/lib/core/IdGenerator.d.ts b/lib/core/IdGenerator.d.ts new file mode 100644 index 0000000..c27cada --- /dev/null +++ b/lib/core/IdGenerator.d.ts @@ -0,0 +1,12 @@ +/** + * ID生成器 + */ +export declare class IdGenerator { + serial: number; + type: string; + constructor(type: string); + next(): string; + getType(): string; + initSerial(serial: number): void; +} +export declare const GraphicIdGenerator: IdGenerator; diff --git a/lib/core/JlGraphic.d.ts b/lib/core/JlGraphic.d.ts new file mode 100644 index 0000000..caa8068 --- /dev/null +++ b/lib/core/JlGraphic.d.ts @@ -0,0 +1,284 @@ +import { Container, DisplayObject, IPointData, Rectangle } from 'pixi.js'; +import { GraphicRelation, RelationManage } from './GraphicRelation'; +import { GraphicQueryStore } from './GraphicStore'; +export interface IGraphicTransform { + position: IPointData; + scale: IPointData; + rotation: number; + skew: IPointData; +} +/** + * 图形变换数据 + */ +export declare class GraphicTransform { + position: IPointData; + scale: IPointData; + rotation: number; + skew: IPointData; + constructor(position: IPointData, scale: IPointData, rotation: number, skew: IPointData); + static default(): GraphicTransform; + static fromObject(obj: DisplayObject): GraphicTransform; + static from(transform: IGraphicTransform | undefined): GraphicTransform; +} +export interface IChildTransform { + name: string; + transform: IGraphicTransform; +} +/** + * 图形子元素变换 + */ +export declare class ChildTransform { + name: string; + transform: GraphicTransform; + constructor(name: string, transform: GraphicTransform); + static fromChild(child: DisplayObject): ChildTransform; + static from(ct: IChildTransform): ChildTransform; +} +/** + * 图形数据 + */ +export interface GraphicData { + get id(): string; + set id(v: string); + get graphicType(): string; + set graphicType(v: string); + get transform(): GraphicTransform; + set transform(v: GraphicTransform); + get childTransforms(): ChildTransform[] | undefined; + set childTransforms(v: ChildTransform[] | undefined); + /** + * 克隆消息 + */ + clone(): GraphicData; + /** + * 从给定数据拷贝 + * @param data + */ + copyFrom(data: GraphicData): void; + /** + * 是否相等 + * @param other + */ + eq(other: GraphicData): boolean; +} +/** + * 图形状态 + */ +export interface GraphicState { + get code(): string; + get graphicType(): string; + remove?: boolean; + /** + * 克隆消息 + */ + clone(): GraphicState; + /** + * 从给定数据拷贝 + * @param data + */ + copyFrom(data: GraphicState): void; + /** + * 是否相等 + * @param data + */ + eq(data: GraphicState): boolean; +} +export interface GraphicAnimationOptions { + name: string; + run?: (dt: number) => void; +} +export declare class GraphicAnimation { + options: GraphicAnimationOptions; + _running: boolean; + /** + * 倍速 + */ + _xSpeed: number; + constructor(options: GraphicAnimationOptions); + static init(options: GraphicAnimationOptions): GraphicAnimation; + pause(): GraphicAnimation; + resume(): GraphicAnimation; + get name(): string; + get running(): boolean; + get xSpeed(): number; + set xSpeed(v: number); + run(dt: number): GraphicAnimation; +} +/** + * 图形对象基类 + */ +export declare abstract class JlGraphic extends Container { + readonly __JlGraphic: true; + readonly type: string; + private _id; + private _code; + _datas?: GraphicData; + _states?: GraphicState; + private _relationManage?; + private _queryStore?; + constructor(type: string); + /** + * 添加图形动画,只有在画布上才能添加 + * @param animation + */ + addAnimation(animation: GraphicAnimation): void; + removeAnimation(name: string): void; + animation(name: string): GraphicAnimation | undefined; + removeAllAnimation(): void; + /** + * 更新选中状态 + * @param selected + * @returns 是否更新 + */ + updateSelected(selected: boolean): boolean; + invertSelected(): void; + fireSelected(): void; + hasSelectedChilds(): boolean; + setChildSelected(child: DisplayObject): boolean; + invertChildSelected(child: DisplayObject): boolean; + removeAllChildSelected(): void; + fireChildSelected(child: DisplayObject): void; + exitChildEdit(): void; + /** + * 是否此对象id/code + */ + isIdOrCode(s: string): boolean; + /** + * 获取图形id,如果图形数据对象存在,则返回图形数据对象id + */ + get id(): string; + /** + * 设置图形id,如果图形数据存在,则同时设置图形数据id + */ + set id(v: string); + /** + * 获取图形业务code,如果业务code在图形数据或图形状态中,则需要重写此方法 + */ + get code(): string; + /** + * 设置图形业务code,如果业务code在图形数据或图形状态中,则需要重写此方法 + */ + set code(v: string); + getDatas(): D; + getStates(): S; + get queryStore(): GraphicQueryStore; + set queryStore(v: GraphicQueryStore); + get relationManage(): RelationManage; + set relationManage(v: RelationManage); + /** + * 构建图形关系 + * @param g + */ + buildRelation(): void; + /** + * 从数据加载恢复图形关系 + */ + loadRelations(): void; + /** + * 获取当前图形的所有图形关系 + * @returns + */ + getAllRelations(): GraphicRelation[]; + /** + * 获取当前图形的所有指定类型图形关系 + * @param type + * @returns + */ + queryRelationByType(type: string): GraphicRelation[]; + /** + * 删除当前图形关联的指定类型的关系 + * @param type + */ + deleteRelationByType(type: string): void; + /** + * 构建并保存关系数据到datas中 + */ + saveRelations(): void; + /** + * 保存数据,复制,非原始数据 + * @returns + */ + saveData(): D; + /** + * 构建子元素变换列表 + * @returns + */ + private buildChildTransforms; + /** + * 加载数据 + * @param data + */ + loadData(data: GraphicData): void; + private loadTransformFrom; + /** + * 更新图形数据 + * @param data + * @returns + */ + updateData(data: GraphicData): boolean; + /** + * 图形数据更新 + */ + onDataChange(newVal: GraphicData, old?: GraphicData): void; + /** + * 加载状态 + * @param state + */ + loadState(state: GraphicState): void; + /** + * 更新状态 + * @param state + * @returns + */ + updateStates(state: GraphicState): boolean; + /** + * 图形状态更新处理 + */ + onStateChange(newVal: GraphicState, old?: GraphicState): void; + repaint(): void; + /** + * 处理重绘逻辑 + */ + abstract doRepaint(): void; + /** + * 处理删除逻辑 + */ + onDelete(): void; + /** + * 框选检测,默认取图形包围盒判定,若需要精细判定-子类重写此方法 + * @param box + * @returns + */ + boxIntersectCheck(box: Rectangle): boolean; +} +export type CreateData = () => GraphicData; +export type CreateState = () => GraphicState; +export interface IGraphicTemplateOptions { + dataTemplate?: GraphicData; + stateTemplate?: GraphicState; +} +/** + * 图形对象模板 + */ +export declare abstract class JlGraphicTemplate { + readonly type: string; + options: IGraphicTemplateOptions; + constructor(type: string, options: IGraphicTemplateOptions); + get datas(): GraphicData; + get states(): GraphicState; + /** + * 初始化一个新的图形对象 + */ + abstract new(): G; + /** + * 加载图形对象需要用到的资源 + */ + loadAssets(): Promise; + /** + * 克隆图形对象 + * @param graphic + * @returns + */ + clone(graphic: G): G; +} +export type GraphicTemplate = JlGraphicTemplate; diff --git a/src/jlgraphic/core/index.ts b/lib/core/index.d.ts similarity index 100% rename from src/jlgraphic/core/index.ts rename to lib/core/index.d.ts diff --git a/lib/graphic/AbsorbablePosition.d.ts b/lib/graphic/AbsorbablePosition.d.ts new file mode 100644 index 0000000..b4d8baf --- /dev/null +++ b/lib/graphic/AbsorbablePosition.d.ts @@ -0,0 +1,91 @@ +import { Container, DisplayObject, Graphics, IPointData, Point } from 'pixi.js'; +import { VectorGraphic } from './VectorGraphic'; +/** + * 抽象可吸附位置 + */ +export interface AbsorbablePosition extends Container { + /** + * 是否与另一个可吸附位置重叠(相似,但可能范围不同) + * @param other + */ + isOverlapping(other: AbsorbablePosition): boolean; + /** + * 与另一个相似的吸附位置比较范围大小 + * @param other + * @returns >0此吸附范围大,<0另一个吸附范围大,=0两个吸附范围一样大 + */ + compareTo(other: AbsorbablePosition): number; + /** + * 尝试吸附图形对象 + * @param objs 图形对象列表 + * @returns 如果吸附成功,返回true,否则false + */ + tryAbsorb(...objs: DisplayObject[]): void; +} +/** + * 可吸附点图形参数 + */ +export declare const AbsorbablePointParam: { + lineWidth: number; + lineColor: string; + fillColor: string; + radius: number; +}; +/** + * 可吸附点 + */ +export default class AbsorbablePoint extends Graphics implements AbsorbablePosition, VectorGraphic { + _point: Point; + absorbRange: number; + scaledListenerOn: boolean; + /** + * + * @param point 画布坐标 + * @param absorbRange + */ + constructor(point: IPointData, absorbRange?: number); + compareTo(other: AbsorbablePosition): number; + isOverlapping(other: AbsorbablePosition): boolean; + tryAbsorb(...objs: DisplayObject[]): void; + updateOnScaled(): void; +} +/** + * 可吸附线 + */ +export declare class AbsorbableLine extends Graphics implements AbsorbablePosition { + p1: Point; + p2: Point; + absorbRange: number; + _color: string; + /** + * + * @param p1 画布坐标 + * @param p2 画布坐标 + * @param absorbRange + */ + constructor(p1: IPointData, p2: IPointData, absorbRange?: number); + isOverlapping(other: AbsorbablePosition): boolean; + compareTo(other: AbsorbablePosition): number; + redraw(): void; + tryAbsorb(...objs: DisplayObject[]): void; +} +/** + * 可吸附圆 + */ +export declare class AbsorbableCircle extends Graphics implements AbsorbablePosition { + absorbRange: number; + p0: Point; + radius: number; + _color: string; + /** + * + * @param p 画布坐标 + * @param radius + * @param absorbRange + */ + constructor(p: IPointData, radius: number, absorbRange?: number); + isOverlapping(other: AbsorbablePosition): boolean; + compareTo(other: AbsorbablePosition): number; + redraw(): void; + tryAbsorb(...objs: DisplayObject[]): void; +} diff --git a/lib/graphic/DashedLine.d.ts b/lib/graphic/DashedLine.d.ts new file mode 100644 index 0000000..c0fbb49 --- /dev/null +++ b/lib/graphic/DashedLine.d.ts @@ -0,0 +1,39 @@ +import { Container, IPointData, Point } from 'pixi.js'; +export interface IDashedLineOptions { + /** + * 每小段长度,默认4 + */ + length?: number; + /** + * 起始间隔,默认0 + */ + startSpace?: number; + /** + * 间隔长度,默认4 + */ + space?: number; + /** + * 线宽,默认1 + */ + lineWidth?: number; + /** + * 线色,默认黑 + */ + color?: string; +} +interface ICompleteDashedLineOptions extends IDashedLineOptions { + length: number; + startSpace: number; + space: number; + lineWidth: number; + color: string; +} +export declare class DashedLine extends Container { + p1: Point; + p2: Point; + _options: ICompleteDashedLineOptions; + constructor(p1: IPointData, p2: IPointData, options?: IDashedLineOptions); + setOptions(options: IDashedLineOptions): void; + redraw(): void; +} +export {}; diff --git a/lib/graphic/DraggablePoint.d.ts b/lib/graphic/DraggablePoint.d.ts new file mode 100644 index 0000000..3eed5f8 --- /dev/null +++ b/lib/graphic/DraggablePoint.d.ts @@ -0,0 +1,23 @@ +import { Graphics, IPointData } from 'pixi.js'; +import { VectorGraphic } from './VectorGraphic'; +/** + * 拖拽点参数 + */ +export declare const DraggablePointParam: { + lineWidth: number; + lineColor: number; + fillColor: number; + radius: number; +}; +/** + * 拖拽点,用于更新图形属性 + */ +export declare class DraggablePoint extends Graphics implements VectorGraphic { + scaledListenerOn: boolean; + /** + * + * @param point 画布坐标点 + */ + constructor(point: IPointData); + updateOnScaled(): void; +} diff --git a/lib/graphic/VectorGraphic.d.ts b/lib/graphic/VectorGraphic.d.ts new file mode 100644 index 0000000..bdc8449 --- /dev/null +++ b/lib/graphic/VectorGraphic.d.ts @@ -0,0 +1,8 @@ +import { DisplayObject } from 'pixi.js'; +export interface VectorGraphic extends DisplayObject { + scaledListenerOn: boolean; + updateOnScaled(): void; +} +export declare class VectorGraphicUtil { + static handle(obj: VectorGraphic): void; +} diff --git a/lib/graphic/VectorText.d.ts b/lib/graphic/VectorText.d.ts new file mode 100644 index 0000000..2be1dcf --- /dev/null +++ b/lib/graphic/VectorText.d.ts @@ -0,0 +1,16 @@ +import { ICanvas, ITextStyle, Text, TextStyle } from 'pixi.js'; +import { VectorGraphic } from '.'; +/** + * 矢量文字.实现原理:在缩放发生变化时,更新fontSize + */ +export declare class VectorText extends Text implements VectorGraphic { + vectorFontSize: number; + scaled: number; + scaledListenerOn: boolean; + constructor(text?: string | number, style?: Partial | TextStyle, canvas?: ICanvas); + updateOnScaled(): void; + /** + * 设置矢量文字的字体大小 + */ + setVectorFontSize(fontSize: number): void; +} diff --git a/src/jlgraphic/graphic/index.ts b/lib/graphic/index.d.ts similarity index 100% rename from src/jlgraphic/graphic/index.ts rename to lib/graphic/index.d.ts diff --git a/src/jlgraphic/index.ts b/lib/index.d.ts similarity index 100% rename from src/jlgraphic/index.ts rename to lib/index.d.ts diff --git a/lib/index.js b/lib/index.js index 96a33c2..af43ef5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,127 +1,43 @@ -'use strict'; - -var pixi_js = require('pixi.js'); -var EventEmitter = require('eventemitter3'); -var pixiViewport = require('pixi-viewport'); -var stompjs = require('@stomp/stompjs'); -var mqtt = require('mqtt'); - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise, SuppressedError, Symbol */ - -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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -function __awaiter(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()); - }); -} - -function __generator(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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; - } -} - -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - -typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; +import { Graphics, Container, Text, Point, Matrix, Color, Polygon, Rectangle, Application, BitmapFont, BitmapText, DisplayObject } from 'pixi.js'; +import EventEmitter from 'eventemitter3'; +import { Viewport } from 'pixi-viewport'; +import { Client } from '@stomp/stompjs'; +import mqtt from 'mqtt'; /** * ID生成器 */ -var IdGenerator = /** @class */ (function () { - function IdGenerator(type) { - this.serial = 0; +class IdGenerator { + serial = 0; + type; + constructor(type) { this.type = type; } - IdGenerator.prototype.next = function () { + next() { ++this.serial; - // console.log(this.getType() + this.serial) return this.getType() + this.serial; - }; - IdGenerator.prototype.getType = function () { + } + getType() { return this.type; - }; - IdGenerator.prototype.initSerial = function (serial) { - // console.log(serial) + } + initSerial(serial) { this.serial = serial; - }; - return IdGenerator; -}()); -var GraphicIdGenerator = new IdGenerator(''); + } +} +const GraphicIdGenerator = new IdGenerator(''); -exports.InteractionPluginType = void 0; +var InteractionPluginType; (function (InteractionPluginType) { InteractionPluginType["App"] = "app"; InteractionPluginType["Graphic"] = "graphic"; InteractionPluginType["Other"] = "other"; -})(exports.InteractionPluginType || (exports.InteractionPluginType = {})); -var InteractionPluginBase = /** @class */ (function () { - function InteractionPluginBase(app, name, type) { +})(InteractionPluginType || (InteractionPluginType = {})); +class InteractionPluginBase { + _type; + name; // 唯一标识 + app; + _pause; + constructor(app, name, type) { this._type = type; this.app = app; this.name = name; @@ -131,188 +47,148 @@ var InteractionPluginBase = /** @class */ (function () { /** * 恢复 */ - InteractionPluginBase.prototype.resume = function () { + resume() { this.bind(); this._pause = false; this.app.emit('interaction-plugin-resume', this); - }; + } /** * 停止 */ - InteractionPluginBase.prototype.pause = function () { + pause() { this.unbind(); this._pause = true; this.app.emit('interaction-plugin-pause', this); - }; + } /** * 是否生效 */ - InteractionPluginBase.prototype.isActive = function () { + isActive() { return !this._pause; - }; - InteractionPluginBase.prototype.isGraphicPlugin = function () { - return this._type === exports.InteractionPluginType.Graphic; - }; - InteractionPluginBase.prototype.isAppPlugin = function () { - return this._type === exports.InteractionPluginType.App; - }; - InteractionPluginBase.prototype.isOtherPlugin = function () { - return this._type === exports.InteractionPluginType.Other; - }; - return InteractionPluginBase; -}()); -var OtherInteractionPlugin = /** @class */ (function (_super) { - __extends(OtherInteractionPlugin, _super); - function OtherInteractionPlugin(app, name) { - return _super.call(this, app, name, exports.InteractionPluginType.Other) || this; } - return OtherInteractionPlugin; -}(InteractionPluginBase)); -var AppDragEvent = /** @class */ (function () { - function AppDragEvent(app, type, target, original, start) { + isGraphicPlugin() { + return this._type === InteractionPluginType.Graphic; + } + isAppPlugin() { + return this._type === InteractionPluginType.App; + } + isOtherPlugin() { + return this._type === InteractionPluginType.Other; + } +} +class OtherInteractionPlugin extends InteractionPluginBase { + constructor(app, name) { + super(app, name, InteractionPluginType.Other); + } +} +class AppDragEvent { + app; + type; + target; + original; + start; // 画布坐标 + constructor(app, type, target, original, start) { this.app = app; this.type = type; this.target = target; this.original = original; this.start = start; } - Object.defineProperty(AppDragEvent.prototype, "isMouse", { - get: function () { - return this.original.pointerType === 'mouse'; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "isLeftButton", { - get: function () { - return (this.isMouse && - ((this.original.button === -1 && this.original.buttons === 1) || - (this.original.button === 0 && this.original.buttons === 0))); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "isRightButton", { - get: function () { - return (this.isMouse && - ((this.original.button === -1 && this.original.buttons === 2) || - (this.original.button === 2 && this.original.buttons === 0))); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "isMiddleButton", { - get: function () { - return (this.isMouse && - ((this.original.button === -1 && this.original.buttons === 4) || - (this.original.button === 1 && this.original.buttons === 0))); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "isTouch", { - get: function () { - return this.original.pointerType === 'touch'; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "end", { - /** - * 终点坐标(画布坐标) - */ - get: function () { - return this.app.toCanvasCoordinates(this.original.global); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "dx", { - get: function () { - var move = this.original.movement; - return move.x / this.app.viewport.scaled; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "dy", { - get: function () { - var move = this.original.movement; - return move.y / this.app.viewport.scaled; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "dsx", { - get: function () { - return this.end.x - this.start.x; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AppDragEvent.prototype, "dsy", { - get: function () { - return this.end.y - this.start.y; - }, - enumerable: false, - configurable: true - }); + get isMouse() { + return this.original.pointerType === 'mouse'; + } + get isLeftButton() { + return (this.isMouse && + ((this.original.button === -1 && this.original.buttons === 1) || + (this.original.button === 0 && this.original.buttons === 0))); + } + get isRightButton() { + return (this.isMouse && + ((this.original.button === -1 && this.original.buttons === 2) || + (this.original.button === 2 && this.original.buttons === 0))); + } + get isMiddleButton() { + return (this.isMouse && + ((this.original.button === -1 && this.original.buttons === 4) || + (this.original.button === 1 && this.original.buttons === 0))); + } + get isTouch() { + return this.original.pointerType === 'touch'; + } + /** + * 终点坐标(画布坐标) + */ + get end() { + return this.app.toCanvasCoordinates(this.original.global); + } + get dx() { + const move = this.original.movement; + return move.x / this.app.viewport.scaled; + } + get dy() { + const move = this.original.movement; + return move.y / this.app.viewport.scaled; + } + get dsx() { + return this.end.x - this.start.x; + } + get dsy() { + return this.end.y - this.start.y; + } /** * 转换为目标对象的位移距离 */ - AppDragEvent.prototype.toTargetShiftLen = function (target) { - var sl = target.canvasToLocalPoint(this.start); - var el = target.canvasToLocalPoint(this.end); + toTargetShiftLen(target) { + const sl = target.canvasToLocalPoint(this.start); + const el = target.canvasToLocalPoint(this.end); return { dx: el.x - sl.x, dy: el.y - sl.y }; - }; - return AppDragEvent; -}()); + } +} /** * 拖拽操作插件 */ -var DragPlugin = /** @class */ (function (_super) { - __extends(DragPlugin, _super); - function DragPlugin(app) { - var _this = _super.call(this, app, DragPlugin.Name) || this; - _this.threshold = 3; - _this.target = null; - _this.start = null; - _this.startClientPoint = null; - _this.drag = false; - app.on('options-update', function (options) { +class DragPlugin extends OtherInteractionPlugin { + static Name = '__drag_operation_plugin'; + threshold = 3; + target = null; + start = null; + startClientPoint = null; + drag = false; + constructor(app) { + super(app, DragPlugin.Name); + app.on('options-update', (options) => { if (options.threshold !== undefined) { - _this.threshold = options.threshold; + this.threshold = options.threshold; } }); - return _this; } - DragPlugin.new = function (app) { + static new(app) { return new DragPlugin(app); - }; - DragPlugin.prototype.bind = function () { - var canvas = this.app.canvas; + } + bind() { + const canvas = this.app.canvas; canvas.on('pointerdown', this.onPointerDown, this); - }; - DragPlugin.prototype.unbind = function () { - var canvas = this.app.canvas; + } + unbind() { + const canvas = this.app.canvas; canvas.off('pointerdown', this.onPointerDown, this); canvas.off('pointerup', this.onPointerUp, this); canvas.off('pointerupoutside', this.onPointerUp, this); - }; - DragPlugin.prototype.onPointerDown = function (e) { + } + onPointerDown(e) { this.target = e.target; this.start = this.app.toCanvasCoordinates(e.global); this.startClientPoint = e.global.clone(); - var canvas = this.app.canvas; + const canvas = this.app.canvas; canvas.on('pointermove', this.onPointerMove, this); canvas.on('pointerup', this.onPointerUp, this); canvas.on('pointerupoutside', this.onPointerUp, this); - }; - DragPlugin.prototype.onPointerMove = function (e) { + } + onPointerMove(e) { if (this.start && this.startClientPoint) { - var current = e.global; - var sgp = this.startClientPoint; - var dragStart = Math.abs(current.x - sgp.x) > this.threshold || + const current = e.global; + const sgp = this.startClientPoint; + const dragStart = Math.abs(current.x - sgp.x) > this.threshold || Math.abs(current.y - sgp.y) > this.threshold; if (this.target && this.start && !this.drag && dragStart) { this.app.emit('drag_op_start', new AppDragEvent(this.app, 'start', this.target, e, this.start)); @@ -320,20 +196,18 @@ var DragPlugin = /** @class */ (function (_super) { } // drag移动处理 if (this.target && this.drag && this.start) { - // console.log('drag move', e.movement); this.app.emit('drag_op_move', new AppDragEvent(this.app, 'move', this.target, e, this.start)); } } - }; - DragPlugin.prototype.onPointerUp = function (e) { + } + onPointerUp(e) { if (this.target && this.drag && this.start) { - // console.log('drag end'); this.app.emit('drag_op_end', new AppDragEvent(this.app, 'end', this.target, e, this.start)); } else if (this.target && this.start && !this.drag) { // this.target.emit('click', this.target); - var ade = new AppDragEvent(this.app, 'end', this.target, e, this.start); - var graphic = this.target.getGraphic(); + const ade = new AppDragEvent(this.app, 'end', this.target, e, this.start); + const graphic = this.target.getGraphic(); if (ade.isRightButton) { this.target.emit('_rightclick', e); if (graphic != null) { @@ -347,72 +221,71 @@ var DragPlugin = /** @class */ (function (_super) { } } } - var canvas = this.app.canvas; + const canvas = this.app.canvas; canvas.off('mousemove', this.onPointerMove, this); canvas.off('mouseup', this.onPointerUp, this); canvas.off('mouseupoutside', this.onPointerUp, this); this.clearCache(); - }; + } /** * 清理缓存 */ - DragPlugin.prototype.clearCache = function () { + clearCache() { this.drag = false; this.start = null; this.startClientPoint = null; this.target = null; - }; - DragPlugin.Name = '__drag_operation_plugin'; - return DragPlugin; -}(OtherInteractionPlugin)); + } +} /** * 视口移动插件 */ -var ViewportMovePlugin = /** @class */ (function (_super) { - __extends(ViewportMovePlugin, _super); - function ViewportMovePlugin(app) { - var _this = _super.call(this, app, ViewportMovePlugin.Name) || this; - _this.moveHandler = null; - _this.moveSpeedx = 0; - _this.moveSpeedy = 0; - return _this; +class ViewportMovePlugin extends OtherInteractionPlugin { + static Name = '__viewport_move_plugin'; + static MoveInterval = 20; // 移动间隔,单位ms + static TriggerRange = 100; // 边界触发范围,单位px + static DefaultMoveSpeed = 200 / ViewportMovePlugin.MoveInterval; // 默认移动速度 + moveHandler = null; + moveSpeedx = 0; + moveSpeedy = 0; + constructor(app) { + super(app, ViewportMovePlugin.Name); } - ViewportMovePlugin.new = function (app) { + static new(app) { return new ViewportMovePlugin(app); - }; - ViewportMovePlugin.prototype.pause = function () { - _super.prototype.pause.call(this); + } + pause() { + super.pause(); this.stopMove(); - }; - ViewportMovePlugin.prototype.bind = function () { + } + bind() { this.app.canvas.on('pointermove', this.viewportMove, this); - }; - ViewportMovePlugin.prototype.unbind = function () { + } + unbind() { this.app.canvas.off('pointermove', this.viewportMove, this); - }; - ViewportMovePlugin.prototype.startMove = function (moveSpeedx, moveSpeedy) { - var _this = this; + } + startMove(moveSpeedx, moveSpeedy) { this.moveSpeedx = moveSpeedx; this.moveSpeedy = moveSpeedy; if (this.moveHandler == null) { - var viewport_1 = this.app.viewport; - this.moveHandler = setInterval(function () { - viewport_1.moveCorner(viewport_1.corner.x + _this.moveSpeedx, viewport_1.corner.y + _this.moveSpeedy); + const viewport = this.app.viewport; + this.moveHandler = setInterval(() => { + viewport.moveCorner(viewport.corner.x + this.moveSpeedx, viewport.corner.y + this.moveSpeedy); }, ViewportMovePlugin.MoveInterval); } - }; - ViewportMovePlugin.prototype.stopMove = function () { + } + stopMove() { if (this.moveHandler != null) { clearInterval(this.moveHandler); this.moveHandler = null; this.app.canvas.cursor = 'auto'; } - }; - ViewportMovePlugin.prototype.calculateBoundaryMoveSpeed = function (sp) { - var moveSpeedx = 0; - var moveSpeedy = 0; - var range = ViewportMovePlugin.TriggerRange; - var viewport = this.app.viewport; + } + calculateBoundaryMoveSpeed(sp) { + let moveSpeedx = 0; + let moveSpeedy = 0; + const range = ViewportMovePlugin.TriggerRange; + const viewport = this.app.viewport; if (sp.x < range) { moveSpeedx = this.calculateMoveSpeed(sp.x - range); } @@ -431,15 +304,15 @@ var ViewportMovePlugin = /** @class */ (function (_super) { else { moveSpeedy = 0; } - return { moveSpeedx: moveSpeedx, moveSpeedy: moveSpeedy }; - }; - ViewportMovePlugin.prototype.calculateMoveSpeed = function (dd) { + return { moveSpeedx, moveSpeedy }; + } + calculateMoveSpeed(dd) { return ((dd / ViewportMovePlugin.TriggerRange) * ViewportMovePlugin.DefaultMoveSpeed); - }; - ViewportMovePlugin.prototype.viewportMove = function (e) { - var sp = e.global; - var _a = this.calculateBoundaryMoveSpeed(sp), moveSpeedx = _a.moveSpeedx, moveSpeedy = _a.moveSpeedy; + } + viewportMove(e) { + const sp = e.global; + const { moveSpeedx, moveSpeedy } = this.calculateBoundaryMoveSpeed(sp); if (moveSpeedx == 0 && moveSpeedy == 0) { this.app.canvas.cursor = 'auto'; this.stopMove(); @@ -448,101 +321,98 @@ var ViewportMovePlugin = /** @class */ (function (_super) { this.app.canvas.cursor = 'grab'; this.startMove(moveSpeedx, moveSpeedy); } - }; - ViewportMovePlugin.Name = '__viewport_move_plugin'; - ViewportMovePlugin.MoveInterval = 20; // 移动间隔,单位ms - ViewportMovePlugin.TriggerRange = 100; // 边界触发范围,单位px - ViewportMovePlugin.DefaultMoveSpeed = 200 / ViewportMovePlugin.MoveInterval; // 默认移动速度 - return ViewportMovePlugin; -}(OtherInteractionPlugin)); + } +} /** * 应用交互插件,同时只能生效一个 */ -var AppInteractionPlugin = /** @class */ (function (_super) { - __extends(AppInteractionPlugin, _super); - function AppInteractionPlugin(name, app) { - return _super.call(this, app, name, exports.InteractionPluginType.App) || this; +class AppInteractionPlugin extends InteractionPluginBase { + constructor(name, app) { + super(app, name, InteractionPluginType.App); } /** * 恢复,app交互插件同时只能生效一个 */ - AppInteractionPlugin.prototype.resume = function () { + resume() { this.app.pauseAppInteractionPlugins(); - _super.prototype.resume.call(this); - }; - return AppInteractionPlugin; -}(InteractionPluginBase)); + super.resume(); + } +} /** * 图形交互插件,可同时生效 */ -var GraphicInteractionPlugin = /** @class */ (function () { - function GraphicInteractionPlugin(name, app) { - var _this = this; - this._type = exports.InteractionPluginType.Graphic; +class GraphicInteractionPlugin { + _type = InteractionPluginType.Graphic; + app; + name; // 唯一标识 + _pause; + constructor(name, app) { this.app = app; this.name = name; this._pause = true; app.registerInteractionPlugin(this); this.resume(); // 新增的图形对象绑定 - this.app.on('graphicstored', function (g) { - if (_this.isActive()) { - _this.binds(_this.filter(g)); + this.app.on('graphicstored', (g) => { + if (this.isActive()) { + this.binds(this.filter(g)); } }); - this.app.on('graphicdeleted', function (g) { - if (_this.isActive()) { - _this.unbinds(_this.filter(g)); + this.app.on('graphicdeleted', (g) => { + if (this.isActive()) { + this.unbinds(this.filter(g)); } }); } - GraphicInteractionPlugin.prototype.isActive = function () { + isActive() { return !this._pause; - }; - GraphicInteractionPlugin.prototype.isAppPlugin = function () { + } + isAppPlugin() { return false; - }; - GraphicInteractionPlugin.prototype.isOtherPlugin = function () { + } + isOtherPlugin() { return false; - }; - GraphicInteractionPlugin.prototype.isGraphicPlugin = function () { + } + isGraphicPlugin() { return true; - }; - GraphicInteractionPlugin.prototype.resume = function () { - var list = this.filter.apply(this, this.app.queryStore.getAllGraphics()); + } + resume() { + const list = this.filter(...this.app.queryStore.getAllGraphics()); this.binds(list); this._pause = false; this.app.emit('interaction-plugin-resume', this); - }; - GraphicInteractionPlugin.prototype.pause = function () { - var list = this.filter.apply(this, this.app.queryStore.getAllGraphics()); + } + pause() { + const list = this.filter(...this.app.queryStore.getAllGraphics()); this.unbinds(list); this._pause = true; this.app.emit('interaction-plugin-pause', this); - }; - GraphicInteractionPlugin.prototype.binds = function (list) { - var _this = this; + } + binds(list) { if (list) { - list.forEach(function (g) { return _this.bind(g); }); + list.forEach((g) => this.bind(g)); } - }; - GraphicInteractionPlugin.prototype.unbinds = function (list) { - var _this = this; + } + unbinds(list) { if (list) { - list.forEach(function (g) { return _this.unbind(g); }); + list.forEach((g) => this.unbind(g)); } - }; - return GraphicInteractionPlugin; -}()); + } +} -var CompleteMouseToolOptions = /** @class */ (function () { - function CompleteMouseToolOptions() { +class CompleteMouseToolOptions { + boxSelect; + viewportDrag; + viewportDragLeft; + wheelZoom; + selectFilter; + constructor() { this.boxSelect = true; this.viewportDrag = true; this.wheelZoom = true; this.viewportDragLeft = false; } - CompleteMouseToolOptions.prototype.update = function (options) { + update(options) { if (options.boxSelect != undefined) { this.boxSelect = options.boxSelect; } @@ -556,41 +426,42 @@ var CompleteMouseToolOptions = /** @class */ (function () { this.wheelZoom = options.wheelZoom; } this.selectFilter = options.selectFilter; - }; - return CompleteMouseToolOptions; -}()); + } +} /** * 通用交互工具 */ -var CommonMouseTool = /** @class */ (function (_super) { - __extends(CommonMouseTool, _super); - function CommonMouseTool(scene) { - var _this = _super.call(this, CommonMouseTool.Name, scene) || this; - _this.leftDownTarget = null; - _this.drag = false; - _this.graphicSelect = false; - _this.rightTarget = null; - _this.options = new CompleteMouseToolOptions(); - _this.box = new pixi_js.Graphics(); - _this.box.name = CommonMouseTool.SelectBox; - _this.box.visible = false; - _this.app.canvas.addAssistantAppends(_this.box); - scene.on('options-update', function (options) { +class CommonMouseTool extends AppInteractionPlugin { + static Name = 'mouse-tool'; + static SelectBox = '__select_box'; + options; + box; + leftDownTarget = null; + drag = false; + graphicSelect = false; + rightTarget = null; + constructor(scene) { + super(CommonMouseTool.Name, scene); + this.options = new CompleteMouseToolOptions(); + this.box = new Graphics(); + this.box.name = CommonMouseTool.SelectBox; + this.box.visible = false; + this.app.canvas.addAssistantAppends(this.box); + scene.on('options-update', (options) => { if (options.mouseToolOptions) { - _this.options.update(options.mouseToolOptions); - if (_this.isActive()) { - _this.pause(); - _this.resume(); + this.options.update(options.mouseToolOptions); + if (this.isActive()) { + this.pause(); + this.resume(); } } }); - return _this; } - CommonMouseTool.new = function (app) { + static new(app) { return new CommonMouseTool(app); - }; - CommonMouseTool.prototype.bind = function () { - var canvas = this.app.canvas; + } + bind() { + const canvas = this.app.canvas; canvas.on('mousedown', this.onMouseDown, this); canvas.on('mouseup', this.onMouseUp, this); this.app.on('drag_op_start', this.onDragStart, this); @@ -619,9 +490,9 @@ var CommonMouseTool = /** @class */ (function (_super) { percent: 0.01, }); } - }; - CommonMouseTool.prototype.unbind = function () { - var canvas = this.app.canvas; + } + unbind() { + const canvas = this.app.canvas; // 确保所有事件取消监听 canvas.off('mousedown', this.onMouseDown, this); canvas.off('mouseup', this.onMouseUp, this); @@ -637,32 +508,20 @@ var CommonMouseTool = /** @class */ (function (_super) { canvas.off('rightupoutside', this.resumeCursor, this); this.app.viewport.plugins.remove('wheel'); this.clearCache(); - }; - CommonMouseTool.prototype.onDragStart = function (event) { - // console.log( - // 'start', - // `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}` - // ); + } + onDragStart(event) { if (this.boxSelect && event.target.isCanvas() && event.isLeftButton) { this.box.visible = true; this.app.interactionPlugin(ViewportMovePlugin.Name).resume(); } this.drag = true; - }; - CommonMouseTool.prototype.onDragMove = function (event) { - // console.log( - // 'moving', - // `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}` - // ); + } + onDragMove(event) { if (this.boxSelect && event.target.isCanvas()) { this.boxSelectDraw(event.start, event.end); } - }; - CommonMouseTool.prototype.onDragEnd = function (event) { - // console.log( - // 'end', - // `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}` - // ); + } + onDragEnd(event) { if (this.boxSelect && event.target.isCanvas() && event.isLeftButton) { this.boxSelectDraw(event.start, event.end); this.boxSelectGraphicCheck(); @@ -670,45 +529,44 @@ var CommonMouseTool = /** @class */ (function (_super) { this.box.clear(); this.box.visible = false; } - }; - CommonMouseTool.prototype.setLeftCursor = function (e) { - var target = e.target; + } + setLeftCursor(e) { + const target = e.target; this.leftDownTarget = target; if (target.isCanvas() && this.app.pixi.view.style) { this.app.pixi.view.style.cursor = 'grab'; } - }; - CommonMouseTool.prototype.resumeLeftCursor = function () { + } + resumeLeftCursor() { if (this.leftDownTarget && this.leftDownTarget.isCanvas() && this.app.pixi.view.style) { this.app.pixi.view.style.cursor = 'inherit'; } this.leftDownTarget = null; - }; - CommonMouseTool.prototype.setCursor = function (e) { - var target = e.target; + } + setCursor(e) { + const target = e.target; this.rightTarget = target; if (target.isCanvas() && this.app.pixi.view.style) { this.app.pixi.view.style.cursor = 'grab'; } - }; - CommonMouseTool.prototype.resumeCursor = function () { + } + resumeCursor() { if (this.rightTarget && this.rightTarget.isCanvas() && this.app.pixi.view.style) { this.app.pixi.view.style.cursor = 'inherit'; } this.rightTarget = null; - }; - CommonMouseTool.prototype.onMouseDown = function (e) { + } + onMouseDown(e) { this.leftDownTarget = e.target; this.graphicSelect = false; // 图形 - var graphic = this.leftDownTarget.getGraphic(); + const graphic = this.leftDownTarget.getGraphic(); if (graphic) { - var app = this.app; - // console.log(this.leftDownTarget.isGraphic()); + const app = this.app; // 图形选中 if (!e.ctrlKey && !graphic.selected && graphic.selectable) { app.updateSelected(graphic); @@ -725,16 +583,16 @@ var CommonMouseTool = /** @class */ (function (_super) { } } } - }; + } /** * 选中处理 * @param e */ - CommonMouseTool.prototype.onMouseUp = function (e) { - var app = this.app; + onMouseUp(e) { + const app = this.app; if (!this.drag) { - var target = e.target; - var graphic = e.target.getGraphic(); + const target = e.target; + const graphic = e.target.getGraphic(); if (graphic && graphic.selected && !this.graphicSelect && @@ -770,38 +628,30 @@ var CommonMouseTool = /** @class */ (function (_super) { } } // 多个图形选中,退出子元素编辑模式 - var selecteds = this.app.selectedGraphics; + const selecteds = this.app.selectedGraphics; if (selecteds.length > 1) { - selecteds.forEach(function (g) { return g.exitChildEdit(); }); + selecteds.forEach((g) => g.exitChildEdit()); } } this.clearCache(); - }; + } /** * 清理缓存 */ - CommonMouseTool.prototype.clearCache = function () { + clearCache() { this.drag = false; this.leftDownTarget = null; - }; - Object.defineProperty(CommonMouseTool.prototype, "boxSelect", { - get: function () { - return this.options.boxSelect; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CommonMouseTool.prototype, "selectFilter", { - get: function () { - return this.options.selectFilter; - }, - enumerable: false, - configurable: true - }); + } + get boxSelect() { + return this.options.boxSelect; + } + get selectFilter() { + return this.options.selectFilter; + } /** * 框选图形绘制并检查 */ - CommonMouseTool.prototype.boxSelectDraw = function (start, end) { + boxSelectDraw(start, end) { if (!this.drag) return; // 绘制框选矩形框 @@ -811,56 +661,51 @@ var CommonMouseTool = /** @class */ (function (_super) { color: this.app.appOptions.assistantElementColor || AppConsts.assistantElementColor, }); - var dsx = end.x - start.x; - var dsy = end.y - start.y; - var x = start.x, y = start.y; + const dsx = end.x - start.x; + const dsy = end.y - start.y; + let { x, y } = start; if (dsx < 0) { x += dsx; } if (dsy < 0) { y += dsy; } - var width = Math.abs(dsx); - var height = Math.abs(dsy); + const width = Math.abs(dsx); + const height = Math.abs(dsy); this.box.drawRect(x, y, width, height); - }; + } /** * 框选图形判断 * @returns */ - CommonMouseTool.prototype.boxSelectGraphicCheck = function () { - var _this = this; + boxSelectGraphicCheck() { if (!this.drag) return; // 遍历筛选 - var boxRect = this.box.getLocalBounds(); - var app = this.app; - var selects = []; - app.queryStore.getAllGraphics().forEach(function (g) { - if ((_this.selectFilter == undefined && g.visible) || - (!!_this.selectFilter && _this.selectFilter(g))) { + const boxRect = this.box.getLocalBounds(); + const app = this.app; + const selects = []; + app.queryStore.getAllGraphics().forEach((g) => { + if ((this.selectFilter == undefined && g.visible) || + (!!this.selectFilter && this.selectFilter(g))) { // 选择过滤器 if (g.boxIntersectCheck(boxRect)) { selects.push(g); } } }); - app.updateSelected.apply(app, selects); - }; - CommonMouseTool.Name = 'mouse-tool'; - CommonMouseTool.SelectBox = '__select_box'; - return CommonMouseTool; -}(AppInteractionPlugin)); + app.updateSelected(...selects); + } +} -var target; -var GlobalKeyboardHelper = /** @class */ (function () { - function GlobalKeyboardHelper() { - var _this = this; - this.appKeyboardPluginMap = []; - window.onkeydown = function (e) { - _this.appKeyboardPluginMap.forEach(function (plugin) { - var listenerMap = plugin.getKeyListener(e); - listenerMap === null || listenerMap === void 0 ? void 0 : listenerMap.forEach(function (listener) { +let target; +class GlobalKeyboardHelper { + appKeyboardPluginMap = []; + constructor() { + window.onkeydown = (e) => { + this.appKeyboardPluginMap.forEach((plugin) => { + const listenerMap = plugin.getKeyListener(e); + listenerMap?.forEach((listener) => { if (listener.global) { listener.press(e, plugin.app); } @@ -869,7 +714,6 @@ var GlobalKeyboardHelper = /** @class */ (function () { if (e.ctrlKey) { if (e.code == 'KeyS') { // 屏蔽全局Ctrl+S保存操作 - // console.log('屏蔽全局Ctrl+S') return false; } } @@ -884,10 +728,10 @@ var GlobalKeyboardHelper = /** @class */ (function () { } return true; }; - window.onkeyup = function (e) { - _this.appKeyboardPluginMap.forEach(function (plugin) { - var listenerMap = plugin.getKeyListener(e); - listenerMap === null || listenerMap === void 0 ? void 0 : listenerMap.forEach(function (listener) { + window.onkeyup = (e) => { + this.appKeyboardPluginMap.forEach((plugin) => { + const listenerMap = plugin.getKeyListener(e); + listenerMap?.forEach((listener) => { if (listener.global) { listener.release(e, plugin.app); } @@ -895,54 +739,50 @@ var GlobalKeyboardHelper = /** @class */ (function () { }); }; } - GlobalKeyboardHelper.prototype.registerGAKPlugin = function (plugin) { - if (!this.appKeyboardPluginMap.find(function (pg) { return pg == plugin; })) { + registerGAKPlugin(plugin) { + if (!this.appKeyboardPluginMap.find((pg) => pg == plugin)) { this.appKeyboardPluginMap.push(plugin); } - }; - GlobalKeyboardHelper.prototype.removeGAKPlugin = function (plugin) { - var index = this.appKeyboardPluginMap.findIndex(function (pg) { return pg == plugin; }); + } + removeGAKPlugin(plugin) { + const index = this.appKeyboardPluginMap.findIndex((pg) => pg == plugin); if (index >= 0) { this.appKeyboardPluginMap.splice(index, 1); } - }; - return GlobalKeyboardHelper; -}()); -var GlobalKeyboardPlugin = new GlobalKeyboardHelper(); -var JlGraphicAppKeyboardPlugin = /** @class */ (function () { - function JlGraphicAppKeyboardPlugin(app) { - var _this = this; - /** - * 结构为Map> - */ - this.keyListenerMap = new Map(); // 键值监听map - this.keyListenerStackMap = new Map(); // 键值监听栈(多次注册相同的监听会把之前注册的监听器入栈,移除最新的监听会从栈中弹出一个作为指定事件监听处理器) + } +} +const GlobalKeyboardPlugin = new GlobalKeyboardHelper(); +class JlGraphicAppKeyboardPlugin { + app; + /** + * 结构为Map> + */ + keyListenerMap = new Map(); // 键值监听map + keyListenerStackMap = new Map(); // 键值监听栈(多次注册相同的监听会把之前注册的监听器入栈,移除最新的监听会从栈中弹出一个作为指定事件监听处理器) + constructor(app) { this.app = app; GlobalKeyboardPlugin.registerGAKPlugin(this); - var onMouseUpdateTarget = function (e) { - var node = e.target; + const onMouseUpdateTarget = (e) => { + const node = e.target; target = node; - // console.log('Mousedown Event', node.nodeName, node.nodeType, node.nodeValue) }; - var keydownHandle = function (e) { - var _a; + const keydownHandle = (e) => { // console.debug(e.key, e.code, e.keyCode); - if (target && target == ((_a = _this.app.dom) === null || _a === void 0 ? void 0 : _a.getElementsByTagName('canvas')[0])) { - var listenerMap = _this.getKeyListener(e); - listenerMap === null || listenerMap === void 0 ? void 0 : listenerMap.forEach(function (listener) { + if (target && target == this.app.dom?.getElementsByTagName('canvas')[0]) { + const listenerMap = this.getKeyListener(e); + listenerMap?.forEach((listener) => { if (!listener.global) { - listener.press(e, _this.app); + listener.press(e, this.app); } }); } }; - var keyupHandle = function (e) { - var _a; - if (target && target == ((_a = _this.app.dom) === null || _a === void 0 ? void 0 : _a.getElementsByTagName('canvas')[0])) { - var listenerMap = _this.getKeyListener(e); - listenerMap === null || listenerMap === void 0 ? void 0 : listenerMap.forEach(function (listener) { + const keyupHandle = (e) => { + if (target && target == this.app.dom?.getElementsByTagName('canvas')[0]) { + const listenerMap = this.getKeyListener(e); + listenerMap?.forEach((listener) => { if (!listener.global) { - listener.release(e, _this.app); + listener.release(e, this.app); } }); } @@ -950,100 +790,95 @@ var JlGraphicAppKeyboardPlugin = /** @class */ (function () { document.addEventListener('mousedown', onMouseUpdateTarget, false); document.addEventListener('keydown', keydownHandle, false); document.addEventListener('keyup', keyupHandle, false); - this.app.on('destroy', function () { + this.app.on('destroy', () => { document.removeEventListener('mousedown', onMouseUpdateTarget, false); document.removeEventListener('keydown', keydownHandle, false); document.removeEventListener('keyup', keyupHandle, false); - GlobalKeyboardPlugin.removeGAKPlugin(_this); + GlobalKeyboardPlugin.removeGAKPlugin(this); }); } - JlGraphicAppKeyboardPlugin.prototype.getOrInit = function (key) { - var map = this.keyListenerMap.get(key); + getOrInit(key) { + let map = this.keyListenerMap.get(key); if (map === undefined) { map = new Map(); this.keyListenerMap.set(key, map); } return map; - }; - JlGraphicAppKeyboardPlugin.prototype.getOrInitStack = function (key) { - var stack = this.keyListenerStackMap.get(key); + } + getOrInitStack(key) { + let stack = this.keyListenerStackMap.get(key); if (stack === undefined) { stack = []; this.keyListenerStackMap.set(key, stack); } return stack; - }; + } /** * 注册按键监听,若有旧的,旧的入栈 * @param keyListener */ - JlGraphicAppKeyboardPlugin.prototype.addKeyListener = function (keyListener) { - var map = this.getOrInit(keyListener.value); + addKeyListener(keyListener) { + const map = this.getOrInit(keyListener.value); // 查询是否有旧的监听,若有入栈 - var old = map.get(keyListener.identifier); + const old = map.get(keyListener.identifier); if (old) { - var stack = this.getOrInitStack(keyListener.identifier); + const stack = this.getOrInitStack(keyListener.identifier); stack.push(old); } map.set(keyListener.identifier, keyListener); - // console.log(this.getAllListenedKeys()); - }; + } /** * 移除按键监听,若是当前注册的监听,尝试从栈中取出作为按键监听器,若是旧的,则同时移除栈中的监听 * @param keyListener */ - JlGraphicAppKeyboardPlugin.prototype.removeKeyListener = function (keyListener) { + removeKeyListener(keyListener) { keyListener.onRemove(); - var map = this.getOrInit(keyListener.value); - var old = map.get(keyListener.identifier); + const map = this.getOrInit(keyListener.value); + const old = map.get(keyListener.identifier); map.delete(keyListener.identifier); - var stack = this.getOrInitStack(keyListener.identifier); + const stack = this.getOrInitStack(keyListener.identifier); if (old && old === keyListener) { // 是旧的监听 - var listener = stack.pop(); + const listener = stack.pop(); if (listener) { map.set(keyListener.identifier, listener); } } else { // 移除栈中的 - var index = stack.findIndex(function (ls) { return ls === keyListener; }); + const index = stack.findIndex((ls) => ls === keyListener); if (index >= 0) { stack.splice(index, 1); } } - // console.log(this); - }; - JlGraphicAppKeyboardPlugin.prototype.getKeyListenerBy = function (key) { + } + getKeyListenerBy(key) { return this.keyListenerMap.get(key); - }; - JlGraphicAppKeyboardPlugin.prototype.getKeyListener = function (e) { + } + getKeyListener(e) { return (this.getKeyListenerBy(e.key) || this.getKeyListenerBy(e.code) || this.getKeyListenerBy(e.keyCode)); - }; - JlGraphicAppKeyboardPlugin.prototype.isKeyListened = function (key) { + } + isKeyListened(key) { return this.getOrInit(key).size > 0; - }; + } /** * 获取所有注册监听的键值(组合键) */ - JlGraphicAppKeyboardPlugin.prototype.getAllListenedKeys = function () { - var keys = []; - this.keyListenerMap.forEach(function (v) { - return v.forEach(function (_listener, ck) { return keys.push(ck); }); - }); + getAllListenedKeys() { + const keys = []; + this.keyListenerMap.forEach((v) => v.forEach((_listener, ck) => keys.push(ck))); return keys; - }; - return JlGraphicAppKeyboardPlugin; -}()); -exports.CombinationKey = void 0; + } +} +var CombinationKey; (function (CombinationKey) { CombinationKey["Ctrl"] = "Ctrl"; CombinationKey["Alt"] = "Alt"; CombinationKey["Shift"] = "Shift"; -})(exports.CombinationKey || (exports.CombinationKey = {})); -var DefaultKeyListenerOptions = { +})(CombinationKey || (CombinationKey = {})); +const DefaultKeyListenerOptions = { value: '', combinations: [], global: false, @@ -1051,97 +886,70 @@ var DefaultKeyListenerOptions = { pressTriggerAsOriginalEvent: false, onRelease: undefined, }; -var KeyListener = /** @class */ (function () { - function KeyListener(options) { - this.isPress = false; +class KeyListener { + // value 支持keyCode,key,code三种值 + options; + isPress = false; + constructor(options) { this.options = Object.assign({}, DefaultKeyListenerOptions, options); } - KeyListener.create = function (options) { + static create(options) { return new KeyListener(options); - }; - Object.defineProperty(KeyListener.prototype, "value", { - get: function () { - return this.options.value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(KeyListener.prototype, "combinations", { - get: function () { - return this.options.combinations; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(KeyListener.prototype, "identifier", { - get: function () { - return this.options.combinations.join('+') + '+' + this.options.value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(KeyListener.prototype, "global", { - get: function () { - return this.options.global; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(KeyListener.prototype, "onPress", { - get: function () { - return this.options.onPress; - }, - set: function (v) { - this.options.onPress = v; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(KeyListener.prototype, "onRelease", { - get: function () { - return this.options.onRelease; - }, - set: function (v) { - this.options.onRelease = v; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(KeyListener.prototype, "pressTriggerEveryTime", { - get: function () { - return this.options.pressTriggerAsOriginalEvent; - }, - set: function (v) { - this.options.pressTriggerAsOriginalEvent = v; - }, - enumerable: false, - configurable: true - }); - KeyListener.prototype.press = function (e, app) { + } + get value() { + return this.options.value; + } + get combinations() { + return this.options.combinations; + } + get identifier() { + return this.options.combinations.join('+') + '+' + this.options.value; + } + get global() { + return this.options.global; + } + get onPress() { + return this.options.onPress; + } + set onPress(v) { + this.options.onPress = v; + } + get onRelease() { + return this.options.onRelease; + } + set onRelease(v) { + this.options.onRelease = v; + } + get pressTriggerEveryTime() { + return this.options.pressTriggerAsOriginalEvent; + } + set pressTriggerEveryTime(v) { + this.options.pressTriggerAsOriginalEvent = v; + } + press(e, app) { if (!this.checkCombinations(e)) { console.debug('组合键不匹配, 不执行press', e, this); return; } if (this.pressTriggerEveryTime || !this.isPress) { - // console.log('Keydown: ', e, this.onPress); this.isPress = true; if (this.onPress) { this.onPress(e, app); } } - }; + } /** * 检查组合键是否匹配 */ - KeyListener.prototype.checkCombinations = function (e) { - var cbs = this.combinations; + checkCombinations(e) { + const cbs = this.combinations; if (cbs.length > 0) { - if (((e.altKey && cbs.includes(exports.CombinationKey.Alt)) || - (!e.altKey && !cbs.includes(exports.CombinationKey.Alt))) && - ((e.ctrlKey && cbs.includes(exports.CombinationKey.Ctrl)) || - (!e.ctrlKey && !cbs.includes(exports.CombinationKey.Ctrl))) && - ((e.shiftKey && cbs.includes(exports.CombinationKey.Shift)) || - (!e.shiftKey && !cbs.includes(exports.CombinationKey.Shift)))) { + if (((e.altKey && cbs.includes(CombinationKey.Alt)) || + (!e.altKey && !cbs.includes(CombinationKey.Alt))) && + ((e.ctrlKey && cbs.includes(CombinationKey.Ctrl)) || + (!e.ctrlKey && !cbs.includes(CombinationKey.Ctrl))) && + ((e.shiftKey && cbs.includes(CombinationKey.Shift)) || + (!e.shiftKey && !cbs.includes(CombinationKey.Shift)))) { return true; } } @@ -1149,32 +957,35 @@ var KeyListener = /** @class */ (function () { return !e.altKey && !e.ctrlKey && !e.shiftKey; } return false; - }; - KeyListener.prototype.release = function (e, app) { + } + release(e, app) { if (this.isPress) { - // console.log('Keyup : ', e.key, e); this.isPress = false; if (this.onRelease) { this.onRelease(e, app); } } - }; - KeyListener.prototype.onRemove = function () { + } + onRemove() { // 重置按下状态 this.isPress = false; - }; - return KeyListener; -}()); + } +} /** * 图形复制插件 */ -var GraphicCopyPlugin = /** @class */ (function () { - function GraphicCopyPlugin(scene) { - var _this = this; - this.running = false; +class GraphicCopyPlugin { + container; + scene; + keyListeners; + copys; + start; + running = false; + moveLimit; + constructor(scene) { this.scene = scene; - this.container = new pixi_js.Container(); + this.container = new Container(); this.copys = []; this.keyListeners = []; this.keyListeners.push(new KeyListener({ @@ -1182,37 +993,36 @@ var GraphicCopyPlugin = /** @class */ (function () { value: 'Escape', global: true, // combinations: [CombinationKey.Ctrl], - onPress: function () { - _this.cancle(); + onPress: () => { + this.cancle(); }, }), new KeyListener({ // X 限制只能在x轴移动 value: 'KeyX', global: true, // combinations: [CombinationKey.Ctrl], - onPress: function () { - _this.updateMoveLimit('x'); + onPress: () => { + this.updateMoveLimit('x'); }, }), new KeyListener({ // Y 限制只能在y轴移动 value: 'KeyY', global: true, // combinations: [CombinationKey.Ctrl], - onPress: function () { - _this.updateMoveLimit('y'); + onPress: () => { + this.updateMoveLimit('y'); }, })); } - GraphicCopyPlugin.prototype.updateMoveLimit = function (limit) { + updateMoveLimit(limit) { if (this.moveLimit === limit) { this.moveLimit = undefined; } else { this.moveLimit = limit; } - }; - GraphicCopyPlugin.prototype.init = function () { - var _this = this; + } + init() { if (this.running) return; if (this.scene.selectedGraphics.length === 0) { @@ -1222,24 +1032,23 @@ var GraphicCopyPlugin = /** @class */ (function () { this.copys = []; this.container.alpha = 0.5; this.scene.canvas.addChild(this.container); - var app = this.scene; - this.scene.selectedGraphics.forEach(function (g) { - var template = app.getGraphicTemplatesByType(g.type); - var clone = template.clone(g); - _this.copys.push(clone); - _this.container.position.set(0, 0); - _this.container.addChild(clone); + const app = this.scene; + this.scene.selectedGraphics.forEach((g) => { + const template = app.getGraphicTemplatesByType(g.type); + const clone = template.clone(g); + this.copys.push(clone); + this.container.position.set(0, 0); + this.container.addChild(clone); clone.repaint(); }); this.scene.canvas.on('mousemove', this.onPointerMove, this); this.scene.canvas.on('mouseup', this.onFinish, this); this.scene.canvas.on('rightup', this.cancle, this); - this.keyListeners.forEach(function (kl) { - _this.scene.app.addKeyboardListener(kl); + this.keyListeners.forEach((kl) => { + this.scene.app.addKeyboardListener(kl); }); - }; - GraphicCopyPlugin.prototype.clear = function () { - var _this = this; + } + clear() { this.running = false; this.start = undefined; this.moveLimit = undefined; @@ -1249,73 +1058,68 @@ var GraphicCopyPlugin = /** @class */ (function () { this.scene.canvas.off('mousemove', this.onPointerMove, this); this.scene.canvas.off('mouseup', this.onFinish, this); this.scene.canvas.off('rightup', this.cancle, this); - this.keyListeners.forEach(function (kl) { - _this.scene.app.removeKeyboardListener(kl); + this.keyListeners.forEach((kl) => { + this.scene.app.removeKeyboardListener(kl); }); - }; - GraphicCopyPlugin.prototype.onPointerMove = function (e) { - var cp = this.scene.toCanvasCoordinates(e.global); + } + onPointerMove(e) { + const cp = this.scene.toCanvasCoordinates(e.global); if (!this.start) { this.start = cp; } else { if (this.moveLimit === 'x') { - var dx = cp.x - this.start.x; + const dx = cp.x - this.start.x; this.container.position.x = dx; this.container.position.y = 0; } else if (this.moveLimit === 'y') { - var dy = cp.y - this.start.y; + const dy = cp.y - this.start.y; this.container.position.x = 0; this.container.position.y = dy; } else { - var dx = cp.x - this.start.x; - var dy = cp.y - this.start.y; + const dx = cp.x - this.start.x; + const dy = cp.y - this.start.y; this.container.position.x = dx; this.container.position.y = dy; } } - }; - GraphicCopyPlugin.prototype.onFinish = function () { - var _a, _b; - var _this = this; + } + onFinish() { console.log('复制确认'); // 将图形添加到app - this.copys.forEach(function (g) { - g.position.x += _this.container.position.x; - g.position.y += _this.container.position.y; + this.copys.forEach((g) => { + g.position.x += this.container.position.x; + g.position.y += this.container.position.y; }); - (_a = this.scene.app).addGraphicAndRecord.apply(_a, this.copys); + this.scene.app.addGraphicAndRecord(...this.copys); this.scene.detectRelations(); - (_b = this.scene).updateSelected.apply(_b, this.copys); + this.scene.updateSelected(...this.copys); this.clear(); - }; - GraphicCopyPlugin.prototype.cancle = function () { + } + cancle() { console.log('复制操作取消'); this.scene.canvas.removeChild(this.container); this.clear(); - }; - return GraphicCopyPlugin; -}()); - -var VectorGraphicUtil = /** @class */ (function () { - function VectorGraphicUtil() { } - VectorGraphicUtil.handle = function (obj) { - var vg = obj; - var onScaleChange = function (obj) { +} + +class VectorGraphicUtil { + static handle(obj) { + const vg = obj; + const onScaleChange = function (obj) { if (vg.isParent(obj)) { vg.updateOnScaled(); } }; - var registerScaleChange = function registerScaleChange(obj) { + const registerScaleChange = function registerScaleChange(obj) { if (!obj.scaledListenerOn) { obj.scaledListenerOn = true; obj.getGraphicApp().on('viewport-scaled', onScaleChange); } }; - var unregisterScaleChange = function unregisterScaleChange(obj) { + const unregisterScaleChange = function unregisterScaleChange(obj) { obj.scaledListenerOn = false; obj.getGraphicApp().off('viewport-scaled', onScaleChange); }; @@ -1327,56 +1131,52 @@ var VectorGraphicUtil = /** @class */ (function () { // console.debug('矢量图像onRemoveFromCanvas'); unregisterScaleChange(obj); }; - obj.on('added', function (container) { + obj.on('added', (container) => { if (container.isInCanvas()) { obj.onAddToCanvas(container.getCanvas()); } }); - }; - return VectorGraphicUtil; -}()); + } +} /** * 矢量文字.实现原理:在缩放发生变化时,更新fontSize */ -var VectorText = /** @class */ (function (_super) { - __extends(VectorText, _super); - function VectorText(text, style, canvas) { - var _this = _super.call(this, text, style, canvas) || this; - _this.vectorFontSize = 8; - _this.scaled = 1; - _this.scaledListenerOn = false; - VectorGraphicUtil.handle(_this); - return _this; +class VectorText extends Text { + vectorFontSize = 8; + scaled = 1; + scaledListenerOn = false; + constructor(text, style, canvas) { + super(text, style, canvas); + VectorGraphicUtil.handle(this); } - VectorText.prototype.updateOnScaled = function () { - var scaled = this.getAllParentScaled(); - var scale = Math.max(scaled.x, scaled.y); + updateOnScaled() { + const scaled = this.getAllParentScaled(); + const scale = Math.max(scaled.x, scaled.y); this.style.fontSize = this.vectorFontSize * scale; this.scale.set(1 / scale, 1 / scale); - }; + } /** * 设置矢量文字的字体大小 */ - VectorText.prototype.setVectorFontSize = function (fontSize) { + setVectorFontSize(fontSize) { if (this.vectorFontSize !== fontSize) { this.vectorFontSize = fontSize; this.updateOnScaled(); } - }; - return VectorText; -}(pixi_js.Text)); + } +} /** * 拖拽点参数 */ -var DraggablePointParam = { +const DraggablePointParam = { lineWidth: 1, lineColor: 0x000000, fillColor: 0xffffff, radius: 5, // 半径 }; -var DraggablePointGraphic = new pixi_js.Graphics(); +const DraggablePointGraphic = new Graphics(); DraggablePointGraphic.lineStyle(DraggablePointParam.lineWidth, DraggablePointParam.lineColor); DraggablePointGraphic.beginFill(DraggablePointParam.fillColor); DraggablePointGraphic.drawCircle(0, 0, DraggablePointParam.radius); @@ -1384,34 +1184,31 @@ DraggablePointGraphic.endFill(); /** * 拖拽点,用于更新图形属性 */ -var DraggablePoint = /** @class */ (function (_super) { - __extends(DraggablePoint, _super); +class DraggablePoint extends Graphics { + scaledListenerOn = false; /** * * @param point 画布坐标点 */ - function DraggablePoint(point) { - var _this = _super.call(this, DraggablePointGraphic.geometry) || this; - _this.scaledListenerOn = false; - _this.position.copyFrom(point); - _this.eventMode = 'static'; - _this.draggable = true; - _this.cursor = 'crosshair'; - VectorGraphicUtil.handle(_this); - return _this; + constructor(point) { + super(DraggablePointGraphic.geometry); + this.position.copyFrom(point); + this.eventMode = 'static'; + this.draggable = true; + this.cursor = 'crosshair'; + VectorGraphicUtil.handle(this); } - DraggablePoint.prototype.updateOnScaled = function () { - var scaled = this.getAllParentScaled(); - var scale = Math.max(scaled.x, scaled.y); + updateOnScaled() { + const scaled = this.getAllParentScaled(); + const scale = Math.max(scaled.x, scaled.y); this.scale.set(1 / scale, 1 / scale); - }; - return DraggablePoint; -}(pixi_js.Graphics)); + } +} /** * 浮点数相等判断误差值 */ -var epsilon = 0.00001; +const epsilon = 0.00001; /** * 判断浮点数是不是0 * @param v @@ -1434,72 +1231,61 @@ function floatEquals(f1, f2) { } /* eslint-disable @typescript-eslint/no-this-alias */ -var Vector2 = /** @class */ (function () { - function Vector2(values) { - this.values = new Float32Array(2); +class Vector2 { + constructor(values) { if (values !== undefined) { this.xy = values; } } - Vector2.from = function (p) { + static from(p) { return new Vector2([p.x, p.y]); - }; - Object.defineProperty(Vector2.prototype, "x", { - get: function () { - return this.values[0]; - }, - set: function (value) { - this.values[0] = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Vector2.prototype, "y", { - get: function () { - return this.values[1]; - }, - set: function (value) { - this.values[1] = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Vector2.prototype, "xy", { - get: function () { - return [this.values[0], this.values[1]]; - }, - set: function (values) { - this.values[0] = values[0]; - this.values[1] = values[1]; - }, - enumerable: false, - configurable: true - }); - Vector2.prototype.at = function (index) { + } + values = new Float32Array(2); + static zero = new Vector2([0, 0]); + static one = new Vector2([1, 1]); + get x() { + return this.values[0]; + } + set x(value) { + this.values[0] = value; + } + get y() { + return this.values[1]; + } + set y(value) { + this.values[1] = value; + } + get xy() { + return [this.values[0], this.values[1]]; + } + set xy(values) { + this.values[0] = values[0]; + this.values[1] = values[1]; + } + at(index) { return this.values[index]; - }; - Vector2.prototype.reset = function () { + } + reset() { this.x = 0; this.y = 0; - }; - Vector2.prototype.copy = function (dest) { + } + copy(dest) { if (!dest) { dest = new Vector2(); } dest.x = this.x; dest.y = this.y; return dest; - }; - Vector2.prototype.negate = function (dest) { + } + negate(dest) { if (!dest) { dest = this; } dest.x = -this.x; dest.y = -this.y; return dest; - }; - Vector2.prototype.equals = function (vector, threshold) { - if (threshold === void 0) { threshold = epsilon; } + } + equals(vector, threshold = epsilon) { if (Math.abs(this.x - vector.x) > threshold) { return false; } @@ -1507,48 +1293,48 @@ var Vector2 = /** @class */ (function () { return false; } return true; - }; - Vector2.prototype.length = function () { + } + length() { return Math.sqrt(this.squaredLength()); - }; - Vector2.prototype.squaredLength = function () { - var x = this.x; - var y = this.y; + } + squaredLength() { + const x = this.x; + const y = this.y; return x * x + y * y; - }; - Vector2.prototype.add = function (vector) { + } + add(vector) { this.x += vector.x; this.y += vector.y; return this; - }; - Vector2.prototype.subtract = function (vector) { + } + subtract(vector) { this.x -= vector.x; this.y -= vector.y; return this; - }; - Vector2.prototype.multiply = function (vector) { + } + multiply(vector) { this.x *= vector.x; this.y *= vector.y; return this; - }; - Vector2.prototype.divide = function (vector) { + } + divide(vector) { this.x /= vector.x; this.y /= vector.y; return this; - }; - Vector2.prototype.scale = function (value, dest) { + } + scale(value, dest) { if (!dest) { dest = this; } dest.x *= value; dest.y *= value; return dest; - }; - Vector2.prototype.normalize = function (dest) { + } + normalize(dest) { if (!dest) { dest = this; } - var length = this.length(); + let length = this.length(); if (length === 1) { return this; } @@ -1561,7 +1347,7 @@ var Vector2 = /** @class */ (function () { dest.x *= length; dest.y *= length; return dest; - }; + } // multiplyMat2(matrix: mat2, dest?: Vector2): Vector2 { // if (!dest) { // dest = this; @@ -1594,29 +1380,29 @@ var Vector2 = /** @class */ (function () { * @param vector2 * @returns */ - Vector2.dot = function (vector, vector2) { + static dot(vector, vector2) { return vector.x * vector2.x + vector.y * vector2.y; - }; + } /** * 向量长度 * @param vector * @param vector2 * @returns */ - Vector2.distance = function (vector, vector2) { + static distance(vector, vector2) { return Math.sqrt(this.squaredDistance(vector, vector2)); - }; + } /** * 向量长度平方 * @param vector * @param vector2 * @returns */ - Vector2.squaredDistance = function (vector, vector2) { - var x = vector2.x - vector.x; - var y = vector2.y - vector.y; + static squaredDistance(vector, vector2) { + const x = vector2.x - vector.x; + const y = vector2.y - vector.y; return x * x + y * y; - }; + } /** * v2->v1的方向的单位向量 * @param v1 @@ -1624,13 +1410,13 @@ var Vector2 = /** @class */ (function () { * @param dest * @returns */ - Vector2.direction = function (v1, v2, dest) { + static direction(v1, v2, dest) { if (!dest) { dest = new Vector2(); } - var x = v1.x - v2.x; - var y = v1.y - v2.y; - var length = Math.sqrt(x * x + y * y); + const x = v1.x - v2.x; + const y = v1.y - v2.y; + let length = Math.sqrt(x * x + y * y); if (length === 0) { dest.x = 0; dest.y = 0; @@ -1640,19 +1426,19 @@ var Vector2 = /** @class */ (function () { dest.x = x * length; dest.y = y * length; return dest; - }; - Vector2.mix = function (vector, vector2, time, dest) { + } + static mix(vector, vector2, time, dest) { if (!dest) { dest = new Vector2(); } - var x = vector.x; - var y = vector.y; - var x2 = vector2.x; - var y2 = vector2.y; + const x = vector.x; + const y = vector.y; + const x2 = vector2.x; + const y2 = vector2.y; dest.x = x + time * (x2 - x); dest.y = y + time * (y2 - y); return dest; - }; + } /** * 向量加法 * @param vector @@ -1660,14 +1446,14 @@ var Vector2 = /** @class */ (function () { * @param dest * @returns */ - Vector2.sum = function (vector, vector2, dest) { + static sum(vector, vector2, dest) { if (!dest) { dest = new Vector2(); } dest.x = vector.x + vector2.x; dest.y = vector.y + vector2.y; return dest; - }; + } /** * 向量减法 * @param vector @@ -1675,14 +1461,14 @@ var Vector2 = /** @class */ (function () { * @param dest * @returns */ - Vector2.difference = function (vector, vector2, dest) { + static difference(vector, vector2, dest) { if (!dest) { dest = new Vector2(); } dest.x = vector.x - vector2.x; dest.y = vector.y - vector2.y; return dest; - }; + } /** * 向量乘法 * @param vector @@ -1690,14 +1476,14 @@ var Vector2 = /** @class */ (function () { * @param dest * @returns */ - Vector2.product = function (vector, vector2, dest) { + static product(vector, vector2, dest) { if (!dest) { dest = new Vector2(); } dest.x = vector.x * vector2.x; dest.y = vector.y * vector2.y; return dest; - }; + } /** * 向量除法 * @param vector @@ -1705,18 +1491,15 @@ var Vector2 = /** @class */ (function () { * @param dest * @returns */ - Vector2.quotient = function (vector, vector2, dest) { + static quotient(vector, vector2, dest) { if (!dest) { dest = new Vector2(); } dest.x = vector.x / vector2.x; dest.y = vector.y / vector2.y; return dest; - }; - Vector2.zero = new Vector2([0, 0]); - Vector2.one = new Vector2([1, 1]); - return Vector2; -}()); + } +} /** * 递归父节点执行逻辑 @@ -1752,7 +1535,7 @@ function recursiveFindParent(obj, finder) { * @param handler */ function recursiveChildren(container, handler) { - container.children.forEach(function (child) { + container.children.forEach((child) => { handler(child); if (child.children) { recursiveChildren(child, handler); @@ -1763,9 +1546,9 @@ function recursiveChildren(container, handler) { * 递归子节点查询子节点对象 */ function recursiveFindChild(container, finder) { - var result = null; - for (var i = 0; i < container.children.length; i++) { - var child = container.children[i]; + let result = null; + for (let i = 0; i < container.children.length; i++) { + const child = container.children[i]; if (finder(child)) { return child; } @@ -1781,7 +1564,7 @@ function recursiveFindChild(container, finder) { */ function assertBezierPoints(points) { if (points.length < 4 || points.length % 3 !== 1) { - throw new Error("bezierCurve \u6570\u636E\u9519\u8BEF: ".concat(points)); + throw new Error(`bezierCurve 数据错误: ${points}`); } } /** @@ -1791,17 +1574,17 @@ function assertBezierPoints(points) { */ function convertToBezierParams(points) { assertBezierPoints(points); - var bps = []; - for (var i = 0; i < points.length - 3; i += 3) { - var p1 = new pixi_js.Point(points[i].x, points[i].y); - var p2 = new pixi_js.Point(points[i + 3].x, points[i + 3].y); - var cp1 = new pixi_js.Point(points[i + 1].x, points[i + 1].y); - var cp2 = new pixi_js.Point(points[i + 2].x, points[i + 2].y); + const bps = []; + for (let i = 0; i < points.length - 3; i += 3) { + const p1 = new Point(points[i].x, points[i].y); + const p2 = new Point(points[i + 3].x, points[i + 3].y); + const cp1 = new Point(points[i + 1].x, points[i + 1].y); + const cp2 = new Point(points[i + 2].x, points[i + 2].y); bps.push({ - p1: p1, - p2: p2, - cp1: cp1, - cp2: cp2, + p1, + p2, + cp1, + cp2, }); } return bps; @@ -1813,10 +1596,10 @@ function convertToBezierParams(points) { * @returns */ function calculateBezierPoints(basePoints, segmentsCount) { - var bps = convertToBezierParams(basePoints); - var points = []; - bps.forEach(function (bp) { - points.push.apply(points, calculateOneBezierPoints(bp.p1, bp.p2, bp.cp1, bp.cp2, segmentsCount)); + const bps = convertToBezierParams(basePoints); + const points = []; + bps.forEach((bp) => { + points.push(...calculateOneBezierPoints(bp.p1, bp.p2, bp.cp1, bp.cp2, segmentsCount)); }); return points; } @@ -1827,32 +1610,32 @@ function calculateBezierPoints(basePoints, segmentsCount) { * @returns */ function calculateOneBezierPoints(p1, p2, cp1, cp2, segmentsCount) { - var points = []; - var fromX = p1.x; - var fromY = p1.y; - var n = segmentsCount; - var dt = 0; - var dt2 = 0; - var dt3 = 0; - var t2 = 0; - var t3 = 0; - var cpX = cp1.x; - var cpY = cp1.y; - var cpX2 = cp2.x; - var cpY2 = cp2.y; - var toX = p2.x; - var toY = p2.y; - points.push(new pixi_js.Point(p1.x, p1.y)); - for (var i = 1, j = 0; i <= n; ++i) { + const points = []; + const fromX = p1.x; + const fromY = p1.y; + const n = segmentsCount; + let dt = 0; + let dt2 = 0; + let dt3 = 0; + let t2 = 0; + let t3 = 0; + const cpX = cp1.x; + const cpY = cp1.y; + const cpX2 = cp2.x; + const cpY2 = cp2.y; + const toX = p2.x; + const toY = p2.y; + points.push(new Point(p1.x, p1.y)); + for (let i = 1, j = 0; i <= n; ++i) { j = i / n; dt = 1 - j; dt2 = dt * dt; dt3 = dt2 * dt; t2 = j * j; t3 = t2 * j; - var px = dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX; - var py = dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY; - points.push(new pixi_js.Point(px, py)); + const px = dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX; + const py = dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY; + points.push(new Point(px, py)); } return points; } @@ -1860,7 +1643,7 @@ function calculateOneBezierPoints(p1, p2, cp1, cp2, segmentsCount) { * 计算矩形中点 */ function getRectangleCenter(rectangle) { - return new pixi_js.Point(rectangle.x + rectangle.width / 2, rectangle.y + rectangle.height / 2); + return new Point(rectangle.x + rectangle.width / 2, rectangle.y + rectangle.height / 2); } /** * 计算两个矩形中心对齐的坐标, PS: 计算的是较大包围框的中心 @@ -1869,9 +1652,9 @@ function getRectangleCenter(rectangle) { * @returns */ function getCenterOfTwoRectangle(rect1, rect2) { - var x = Math.abs(rect1.width - rect2.width) / 2; - var y = Math.abs(rect1.height - rect2.height) / 2; - return new pixi_js.Point(x, y); + const x = Math.abs(rect1.width - rect2.width) / 2; + const y = Math.abs(rect1.height - rect2.height) / 2; + return new Point(x, y); } /** * 序列化图形变换 @@ -1879,10 +1662,10 @@ function getCenterOfTwoRectangle(rect1, rect2) { * @returns */ function serializeTransform(obj) { - var position = obj.position; - var scale = obj.scale; - var angle = obj.angle; - var skew = obj.skew; + const position = obj.position; + const scale = obj.scale; + const angle = obj.angle; + const skew = obj.skew; return [position.x, position.y, scale.x, scale.y, angle, skew.x, skew.y]; } /** @@ -1909,15 +1692,15 @@ function deserializeTransformInto(obj, transform) { * @returns */ function convertLineToPolygonPoints(p1, p2, thick) { - var angle = Math.atan2(p2.y - p1.y, p2.x - p1.x) - Math.PI / 2; - var half = thick / 2; - var cos = Math.cos(angle) * half; - var sin = Math.sin(angle) * half; + const angle = Math.atan2(p2.y - p1.y, p2.x - p1.x) - Math.PI / 2; + const half = thick / 2; + const cos = Math.cos(angle) * half; + const sin = Math.sin(angle) * half; return [ - new pixi_js.Point(p1.x - cos, p1.y - sin), - new pixi_js.Point(p2.x - cos, p2.y - sin), - new pixi_js.Point(p2.x + cos, p2.y + sin), - new pixi_js.Point(p1.x + cos, p1.y + sin), + new Point(p1.x - cos, p1.y - sin), + new Point(p2.x - cos, p2.y - sin), + new Point(p2.x + cos, p2.y + sin), + new Point(p1.x + cos, p1.y + sin), ]; } /** @@ -1927,10 +1710,10 @@ function convertLineToPolygonPoints(p1, p2, thick) { */ function convertRectangleToPolygonPoints(rect) { return [ - new pixi_js.Point(rect.x, rect.y), - new pixi_js.Point(rect.x + rect.width, rect.y), - new pixi_js.Point(rect.x + rect.width, rect.y + rect.height), - new pixi_js.Point(rect.x, rect.y + rect.height), + new Point(rect.x, rect.y), + new Point(rect.x + rect.width, rect.y), + new Point(rect.x + rect.width, rect.y + rect.height), + new Point(rect.x, rect.y + rect.height), ]; } /** @@ -1940,9 +1723,9 @@ function convertRectangleToPolygonPoints(rect) { * @returns */ function calculateLineMidpoint(p1, p2) { - var x = (p1.x + p2.x) / 2; - var y = (p1.y + p2.y) / 2; - return new pixi_js.Point(x, y); + const x = (p1.x + p2.x) / 2; + const y = (p1.y + p2.y) / 2; + return new Point(x, y); } /** * 计算线段细分坐标--线段分成几份 @@ -1952,15 +1735,15 @@ function calculateLineMidpoint(p1, p2) { * @returns */ function calculateLineSegmentingPoint(p1, p2, knife) { - var segmentingPoints = []; - var x = p1.x < p2.x ? p1.x : p2.x; - var y = p1.y < p2.y ? p1.y : p2.y; - var w = Math.abs(p1.x - p2.x); - var h = Math.abs(p1.y - p2.y); - for (var i = 0; i < knife - 1; i++) { - var pointX = x + (w * (i + 1)) / knife; - var pointy = y + (h * (i + 1)) / knife; - segmentingPoints.push(new pixi_js.Point(pointX, pointy)); + const segmentingPoints = []; + const x = p1.x < p2.x ? p1.x : p2.x; + const y = p1.y < p2.y ? p1.y : p2.y; + const w = Math.abs(p1.x - p2.x); + const h = Math.abs(p1.y - p2.y); + for (let i = 0; i < knife - 1; i++) { + const pointX = x + (w * (i + 1)) / knife; + const pointy = y + (h * (i + 1)) / knife; + segmentingPoints.push(new Point(pointX, pointy)); } return segmentingPoints; } @@ -1972,11 +1755,11 @@ function calculateLineSegmentingPoint(p1, p2, knife) { */ function calculateDistanceFromPointToLine(p1, p2, p) { // 求直线的一般方程参数ABC,直线的一般式方程AX+BY+C=0 - var A = p1.y - p2.y; - var B = p2.x - p1.x; - var C = p1.x * p2.y - p1.y * p2.x; + const A = p1.y - p2.y; + const B = p2.x - p1.x; + const C = p1.x * p2.y - p1.y * p2.x; // 计算点到直线垂直距离: d = |Ax+By+C|/sqrt(A*A+B*B),其中x,y为点坐标 - var dl = Math.abs(A * p.x + B * p.y + C) / Math.sqrt(A * A + B * B); + const dl = Math.abs(A * p.x + B * p.y + C) / Math.sqrt(A * A + B * B); return dl; } /** @@ -1987,16 +1770,16 @@ function calculateDistanceFromPointToLine(p1, p2, p) { */ function calculateFootPointFromPointToLine(p1, p2, p) { if (p1.x == p2.x && p1.y == p2.y) { - throw new Error("\u76F4\u7EBF\u4E24\u5750\u6807\u70B9\u76F8\u7B49:".concat(p1)); + throw new Error(`直线两坐标点相等:${p1}`); } - var k = -(((p1.x - p.x) * (p2.x - p1.x) + (p1.y - p.y) * (p2.y - p1.y)) / + const k = -(((p1.x - p.x) * (p2.x - p1.x) + (p1.y - p.y) * (p2.y - p1.y)) / (Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2))); if (isZero(k)) { - return new pixi_js.Point(p.x, p.y); + return new Point(p.x, p.y); } - var xf = k * (p2.x - p1.x) + p1.x; - var yf = k * (p2.y - p1.y) + p1.y; - return new pixi_js.Point(xf, yf); + const xf = k * (p2.x - p1.x) + p1.x; + const yf = k * (p2.y - p1.y) + p1.y; + return new Point(xf, yf); } /** * 计算直线与圆的交点 @@ -2013,26 +1796,26 @@ function calculateFootPointFromPointToLine(p1, p2, p) { * @returns 交点坐标,可能2/1/0个 */ function calculateIntersectionPointOfCircleAndLine(p0, radius, p1, p2) { - var distance = calculateDistanceFromPointToLine(p1, p2, p0); + const distance = calculateDistanceFromPointToLine(p1, p2, p0); if (distance <= radius) { // 有交点 // 计算垂点 - var pr = calculateFootPointFromPointToLine(p1, p2, p0); + const pr = calculateFootPointFromPointToLine(p1, p2, p0); if (floatEquals(distance, radius)) { // 切线 return [pr]; } - var vpr = new Vector2([pr.x, pr.y]); - var vc = new Vector2([p0.x, p0.y]); + const vpr = new Vector2([pr.x, pr.y]); + const vc = new Vector2([p0.x, p0.y]); // 计算直线单位向量 - var v1 = new Vector2([p1.x, p1.y]); - var v2 = new Vector2([p2.x, p2.y]); - var ve = Vector2.direction(v2, v1); - var base = Math.sqrt(Math.abs(radius * radius - Vector2.difference(vpr, vc).squaredLength())); - var vl = ve.scale(base); - var ip1 = Vector2.sum(vpr, vl); - var ip2 = Vector2.difference(vpr, vl); - return [new pixi_js.Point(ip1.x, ip1.y), new pixi_js.Point(ip2.x, ip2.y)]; + const v1 = new Vector2([p1.x, p1.y]); + const v2 = new Vector2([p2.x, p2.y]); + const ve = Vector2.direction(v2, v1); + const base = Math.sqrt(Math.abs(radius * radius - Vector2.difference(vpr, vc).squaredLength())); + const vl = ve.scale(base); + const ip1 = Vector2.sum(vpr, vl); + const ip2 = Vector2.difference(vpr, vl); + return [new Point(ip1.x, ip1.y), new Point(ip2.x, ip2.y)]; } else { // 无交点 @@ -2047,13 +1830,13 @@ function calculateIntersectionPointOfCircleAndLine(p0, radius, p1, p2) { * @returns */ function calculateIntersectionPointOfCircleAndPoint(p0, radius, p) { - var points = calculateIntersectionPointOfCircleAndLine(p0, radius, p0, p); - var vc = new Vector2([p0.x, p0.y]); - var vp = new Vector2([p.x, p.y]); - var vecp = Vector2.direction(vp, vc); - for (var i = 0; i < points.length; i++) { - var ip = points[i]; - var ve = Vector2.direction(new Vector2([ip.x, ip.y]), vc); + const points = calculateIntersectionPointOfCircleAndLine(p0, radius, p0, p); + const vc = new Vector2([p0.x, p0.y]); + const vp = new Vector2([p.x, p.y]); + const vecp = Vector2.direction(vp, vc); + for (let i = 0; i < points.length; i++) { + const ip = points[i]; + const ve = Vector2.direction(new Vector2([ip.x, ip.y]), vc); if (ve.equals(vecp)) { return ip; } @@ -2068,14 +1851,14 @@ function calculateIntersectionPointOfCircleAndPoint(p0, radius, p) { * @returns */ function calculateMirrorPoint(bp, p, distance) { - var vbp = Vector2.from(bp); - var vp = Vector2.from(p); - var direction = Vector2.direction(vbp, vp); + const vbp = Vector2.from(bp); + const vp = Vector2.from(p); + const direction = Vector2.direction(vbp, vp); if (distance == undefined) { distance = Vector2.distance(vbp, vp); } - var vmp = Vector2.sum(vbp, direction.scale(distance)); - return new pixi_js.Point(vmp.x, vmp.y); + const vmp = Vector2.sum(vbp, direction.scale(distance)); + return new Point(vmp.x, vmp.y); } /** * 计算基于给定轴的给定点的镜像点坐标 @@ -2086,7 +1869,7 @@ function calculateMirrorPoint(bp, p, distance) { * @returns */ function calculateMirrorPointBasedOnAxis(pa, pb, p, distance) { - var fp = calculateFootPointFromPointToLine(pa, pb, p); + const fp = calculateFootPointFromPointToLine(pa, pb, p); if (fp.equals(p)) { return fp; } @@ -2104,8 +1887,8 @@ function angleToAxisx(p1, p2) { if (p1.x == p2.x && p1.y == p2.y) { throw new Error('一个点无法计算角度'); } - var dx = Math.abs(p1.x - p2.x); - var dy = Math.abs(p1.y - p2.y); + const dx = Math.abs(p1.x - p2.x); + const dy = Math.abs(p1.y - p2.y); if (p2.x == p1.x) { if (p2.y > p1.y) { return 90; @@ -2122,7 +1905,7 @@ function angleToAxisx(p1, p2) { return 180; } } - var angle = (Math.atan2(dy, dx) * 180) / Math.PI; + const angle = (Math.atan2(dy, dx) * 180) / Math.PI; if (p2.x > p1.x) { if (p2.y > p1.y) { return angle; @@ -2149,9 +1932,9 @@ function angleToAxisx(p1, p2) { * @returns 夹角, [-180, 180] */ function angleOfIncludedAngle(pa, pb, pc) { - var abAngle = angleToAxisx(pa, pb); - var acAngle = angleToAxisx(pa, pc); - var angle = acAngle - abAngle; + const abAngle = angleToAxisx(pa, pb); + const acAngle = angleToAxisx(pa, pc); + let angle = acAngle - abAngle; if (angle < -180) { angle = 360 + angle; } @@ -2167,9 +1950,9 @@ function angleOfIncludedAngle(pa, pb, pc) { * @returns 单位法向量 */ function getNormalVector(point1, point2) { - var x1 = point1.x, y1 = point1.y; - var x2 = point2.x, y2 = point2.y; - var length = Math.sqrt(Math.pow((y2 - y1), 2) + Math.pow((x2 - x1), 2)); + const x1 = point1.x, y1 = point1.y; + const x2 = point2.x, y2 = point2.y; + const length = Math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2); return [(y2 - y1) / length, (x1 - x2) / length]; } /** @@ -2180,7 +1963,7 @@ function getNormalVector(point1, point2) { * @returns 移动后的点 */ function movePointAlongNormal(point, normal, length) { - var newPoint = new pixi_js.Point(point.x + length * normal[0], point.y + length * normal[1]); + const newPoint = new Point(point.x + length * normal[0], point.y + length * normal[1]); return newPoint; } /** @@ -2190,19 +1973,19 @@ function movePointAlongNormal(point, normal, length) { * @returns 相交点 */ function getIntersectionPoint(line1, line2) { - var a1 = line1[0], b1 = line1[1]; - var a2 = line1[2], b2 = line1[3]; - var a3 = line2[0], b3 = line2[1]; - var a4 = line2[2], b4 = line2[3]; - var denominator = (a3 - a4) * (b1 - b2) - (a1 - a2) * (b3 - b4); + const a1 = line1[0], b1 = line1[1]; + const a2 = line1[2], b2 = line1[3]; + const a3 = line2[0], b3 = line2[1]; + const a4 = line2[2], b4 = line2[3]; + const denominator = (a3 - a4) * (b1 - b2) - (a1 - a2) * (b3 - b4); if (denominator === 0) { - return new pixi_js.Point(a1, b1); + return new Point(a1, b1); } - var x = ((a3 - a4) * (a2 * b1 - a1 * b2) - (a1 - a2) * (a4 * b3 - a3 * b4)) / + const x = ((a3 - a4) * (a2 * b1 - a1 * b2) - (a1 - a2) * (a4 * b3 - a3 * b4)) / denominator; - var y = ((b3 - b4) * (b2 * a1 - b1 * a2) - (b1 - b2) * (b4 * a3 - b3 * a4)) / + const y = ((b3 - b4) * (b2 * a1 - b1 * a2) - (b1 - b2) * (b4 * a3 - b3 * a4)) / -denominator; - return new pixi_js.Point(x, y); + return new Point(x, y); } /** * 是否平行线 @@ -2213,8 +1996,8 @@ function getIntersectionPoint(line1, line2) { * @returns */ function isParallelLines(p1, p2, pa, pb) { - var vle1 = Vector2.direction(Vector2.from(p1), Vector2.from(p2)); - var vle2 = Vector2.direction(Vector2.from(pa), Vector2.from(pb)); + const vle1 = Vector2.direction(Vector2.from(p1), Vector2.from(p2)); + const vle2 = Vector2.direction(Vector2.from(pa), Vector2.from(pb)); if (vle2.equals(vle1)) { return true; } @@ -2228,14 +2011,14 @@ function isParallelLines(p1, p2, pa, pb) { * @returns */ function isPointOnLine(p1, p2, p) { - var vp1 = Vector2.from(p1); - var vp2 = Vector2.from(p2); - var vp = Vector2.from(p); + const vp1 = Vector2.from(p1); + const vp2 = Vector2.from(p2); + const vp = Vector2.from(p); if (vp1.equals(vp) || vp2.equals(vp)) { return true; } - var vle = Vector2.direction(vp1, Vector2.from(p2)); - var vpe = Vector2.direction(vp1, vp); + const vle = Vector2.direction(vp1, Vector2.from(p2)); + const vpe = Vector2.direction(vp1, vp); if (vle.equals(vpe)) { return (Vector2.difference(vp1, vp2).squaredLength() >= Vector2.difference(vp1, vp).squaredLength()); @@ -2256,10 +2039,10 @@ function isLineContainOther(line1, line2) { } /** 均分线段, 返回各线段端点 */ function splitLineEvenly(p1, p2, count) { - var _a = [(p2.x - p1.x) / count, (p2.y - p1.y) / count], stepX = _a[0], stepY = _a[1]; + const [stepX, stepY] = [(p2.x - p1.x) / count, (p2.y - p1.y) / count]; return Array(count) .fill(1) - .map(function (_, i) { + .map((_, i) => { return [ { x: p1.x + stepX * i, y: p1.y + stepY * i }, { x: p1.x + stepX * (i + 1), y: p1.y + stepY * (i + 1) }, @@ -2268,30 +2051,28 @@ function splitLineEvenly(p1, p2, count) { } function splitPolyline(points, count) { if (points.length !== 2) { - var totalLen_1 = 0; - var lengths = []; - for (var i = 1; i < points.length; i++) { - var _a = points[i - 1], x1 = _a.x, y1 = _a.y, _b = points[i], x2 = _b.x, y2 = _b.y; - var len = new Vector2([x2 - x1, y2 - y1]).length(); - totalLen_1 += len; + let totalLen = 0; + const lengths = []; + for (let i = 1; i < points.length; i++) { + const { x: x1, y: y1 } = points[i - 1], { x: x2, y: y2 } = points[i]; + const len = new Vector2([x2 - x1, y2 - y1]).length(); + totalLen += len; lengths.push(len); } - var counts = lengths.map(function (length) { - return Math.round((count * length) / totalLen_1); - }); - if (counts.reduce(function (p, c) { return p + c; }, 0) !== count) { - var intersection = counts.reduce(function (p, c) { return p + c; }, 0) - count; - var maxCountIndex_1 = 0, maxCount_1 = 0; - counts.forEach(function (c, i) { - if (c > maxCount_1) { - maxCount_1 = c; - maxCountIndex_1 = i; + const counts = lengths.map((length) => Math.round((count * length) / totalLen)); + if (counts.reduce((p, c) => p + c, 0) !== count) { + const intersection = counts.reduce((p, c) => p + c, 0) - count; + let maxCountIndex = 0, maxCount = 0; + counts.forEach((c, i) => { + if (c > maxCount) { + maxCount = c; + maxCountIndex = i; } }); - counts[maxCountIndex_1] + intersection; + counts[maxCountIndex] + intersection; } return counts - .map(function (count, i) { + .map((count, i) => { return splitLineEvenly(points[i], points[i + 1], count); }) .flat(); @@ -2301,12 +2082,12 @@ function splitPolyline(points, count) { } } function getParallelOfPolyline(points, offset, side) { - var PI = Math.PI, cos = Math.cos, acos = Math.acos; - var angleBase = side === 'L' ? -PI / 2 : PI / 2; - return points.map(function (p, i) { - var baseUnitVec; //上一段的基准单位向量 - var angle; //偏转角度 - var len; //结合偏转角度的实际偏移量 + const { PI, cos, acos } = Math; + const angleBase = side === 'L' ? -PI / 2 : PI / 2; + return points.map((p, i) => { + let baseUnitVec; //上一段的基准单位向量 + let angle; //偏转角度 + let len; //结合偏转角度的实际偏移量 if (!points[i - 1] || !points[i + 1]) { angle = angleBase; len = offset; @@ -2321,16 +2102,16 @@ function getParallelOfPolyline(points, offset, side) { ]).normalize(); } else { - var vp = new Vector2([p.x - points[i - 1].x, p.y - points[i - 1].y]); - var vn = new Vector2([points[i + 1].x - p.x, points[i + 1].y - p.y]); - var cosTheta = Vector2.dot(vn, vp) / (vp.length() * vn.length()); - var direction = vp.x * vn.y - vp.y * vn.x > 0; //det(vp|vn)>0? - var theta = direction ? acos(cosTheta) : -acos(cosTheta); + const vp = new Vector2([p.x - points[i - 1].x, p.y - points[i - 1].y]); + const vn = new Vector2([points[i + 1].x - p.x, points[i + 1].y - p.y]); + const cosTheta = Vector2.dot(vn, vp) / (vp.length() * vn.length()); + const direction = vp.x * vn.y - vp.y * vn.x > 0; //det(vp|vn)>0? + const theta = direction ? acos(cosTheta) : -acos(cosTheta); angle = angleBase + theta / 2; len = offset / cos(theta / 2); baseUnitVec = Vector2.from(vp).normalize(); } - return new pixi_js.Matrix() + return new Matrix() .scale(len, len) .rotate(angle) .translate(p.x, p.y) @@ -2358,23 +2139,22 @@ function getParallelOfPolyline(points, offset, side) { * @param exact 是否精确(使用给定线宽,否则线宽会设置为8) * @returns */ -function linePoint(pa, pb, p, lineWidth, exact) { - if (exact === void 0) { exact = false; } +function linePoint(pa, pb, p, lineWidth, exact = false) { if (!exact && lineWidth < 6) { lineWidth = 6; } // 求直线的一般方程参数ABC,直线的一般式方程AX+BY+C=0 - var A = pa.y - pb.y; - var B = pb.x - pa.x; - var C = pa.x * pb.y - pa.y * pb.x; + const A = pa.y - pb.y; + const B = pb.x - pa.x; + const C = pa.x * pb.y - pa.y * pb.x; // 计算点到直线垂直距离: d = |Ax+By+C|/sqrt(A*A+B*B),其中x,y为点坐标 - var dl = Math.abs(A * p.x + B * p.y + C) / Math.sqrt(A * A + B * B); - var intersect = dl <= lineWidth / 2; + const dl = Math.abs(A * p.x + B * p.y + C) / Math.sqrt(A * A + B * B); + const intersect = dl <= lineWidth / 2; if (intersect) { // 距离在线宽范围内,再判断点是否超过线段两端点范围外(两端点外会有一点误差,两端点线宽一半半径的圆范围内) - var da = distance(pa.x, pa.y, p.x, p.y); - var db = distance(pb.x, pb.y, p.x, p.y); - var dab = distance(pa.x, pa.y, pb.x, pb.y); + const da = distance(pa.x, pa.y, p.x, p.y); + const db = distance(pb.x, pb.y, p.x, p.y); + const dab = distance(pa.x, pa.y, pb.x, pb.y); return da <= dl + dab && db <= dl + dab; } return false; @@ -2386,8 +2166,8 @@ function linePoint(pa, pb, p, lineWidth, exact) { * @param lineWidth 线宽 */ function polylinePoint(points, p, lineWidth) { - var len = points.length; - for (var i = 0; i < len - 1; i++) { + const len = points.length; + for (let i = 0; i < len - 1; i++) { if (linePoint(points[i], points[i + 1], p, lineWidth)) { return true; } @@ -2403,20 +2183,20 @@ function polylinePoint(points, p, lineWidth) { * @returns */ function lineLine(pa, pb, p1, p2) { - var x1 = pa.x; - var y1 = pa.y; - var x2 = pb.x; - var y2 = pb.y; - var x3 = p1.x; - var y3 = p1.y; - var x4 = p2.x; - var y4 = p2.y; - var s1_x = x2 - x1; - var s1_y = y2 - y1; - var s2_x = x4 - x3; - var s2_y = y4 - y3; - var s = (-s1_y * (x1 - x3) + s1_x * (y1 - y3)) / (-s2_x * s1_y + s1_x * s2_y); - var t = (s2_x * (y1 - y3) - s2_y * (x1 - x3)) / (-s2_x * s1_y + s1_x * s2_y); + const x1 = pa.x; + const y1 = pa.y; + const x2 = pb.x; + const y2 = pb.y; + const x3 = p1.x; + const y3 = p1.y; + const x4 = p2.x; + const y4 = p2.y; + const s1_x = x2 - x1; + const s1_y = y2 - y1; + const s2_x = x4 - x3; + const s2_y = y4 - y3; + const s = (-s1_y * (x1 - x3) + s1_x * (y1 - y3)) / (-s2_x * s1_y + s1_x * s2_y); + const t = (s2_x * (y1 - y3) - s2_y * (x1 - x3)) / (-s2_x * s1_y + s1_x * s2_y); return s >= 0 && s <= 1 && t >= 0 && t <= 1; } /** @@ -2426,9 +2206,9 @@ function lineLine(pa, pb, p1, p2) { * @returns */ function pointBox(p, rect) { - var x = rect.x, y = rect.y, width = rect.width, height = rect.height; - var x2 = p.x; - var y2 = p.y; + const { x, y, width, height } = rect; + const x2 = p.x; + const y2 = p.y; return x2 >= x && x2 <= x + width && y2 >= y && y2 <= y + height; } /** @@ -2442,11 +2222,11 @@ function lineBox(pa, pb, rect) { if (pointBox(pa, rect) || pointBox(pb, rect)) { return true; } - var x = rect.x, y = rect.y, width = rect.width, height = rect.height; - var rp1 = new pixi_js.Point(x, y); - var rp2 = new pixi_js.Point(x + width, y); - var rp3 = new pixi_js.Point(x + width, y + height); - var rp4 = new pixi_js.Point(x, y + height); + const { x, y, width, height } = rect; + const rp1 = new Point(x, y); + const rp2 = new Point(x + width, y); + const rp3 = new Point(x + width, y + height); + const rp4 = new Point(x, y + height); return (lineLine(pa, pb, rp1, rp2) || lineLine(pa, pb, rp2, rp3) || lineLine(pa, pb, rp3, rp4) || @@ -2462,9 +2242,9 @@ function polylineBox(points, rect) { if (points.length < 2) { return false; } - for (var i = 0; i < points.length - 1; i++) { - var p1 = points[i]; - var p2 = points[i + 1]; + for (let i = 0; i < points.length - 1; i++) { + const p1 = points[i]; + const p2 = points[i + 1]; if (lineBox(p1, p2, rect)) { return true; } @@ -2523,16 +2303,16 @@ function distance2(p1, p2) { * @returns */ function circlePoint(x1, y1, r1, x2, y2) { - var x = x2 - x1; - var y = y2 - y1; + const x = x2 - x1; + const y = y2 - y1; return x * x + y * y <= r1 * r1; } /** * 圆和点的碰撞检测--不包括圆内部 */ function circlePoint2(x1, y1, r1, x2, y2, tolerance) { - var x = x2 - x1; - var y = y2 - y1; + const x = x2 - x1; + const y = y2 - y1; return (x * x + y * y <= (r1 + tolerance) * (r1 + tolerance) && x * x + y * y >= (r1 - tolerance) * (r1 - tolerance)); } @@ -2540,10 +2320,10 @@ function circlePoint2(x1, y1, r1, x2, y2, tolerance) { * 点和多边形碰撞检测 */ function pointPolygon(p, points, lineWidth) { - var x = p.x, y = p.y; - var length = points.length; - var c = false; - var i, j; + const { x, y } = p; + const length = points.length; + let c = false; + let i, j; for (i = 0, j = length - 1; i < length; i++) { if (points[i].y > y !== points[j].y > y && x < @@ -2558,7 +2338,7 @@ function pointPolygon(p, points, lineWidth) { return true; } for (i = 0; i < length - 1; i++) { - var p1 = void 0, p2 = void 0; + let p1, p2; if (i === length - 1) { p1 = points[i]; p2 = points[0]; @@ -2585,9 +2365,9 @@ function linePolygon(p1, p2, points, lineWidth, polygonWidth) { if (pointPolygon(p1, points, polygonWidth)) { return true; } - var length = points.length; - for (var i = 0; i < length; i++) { - var pa = void 0, pb = void 0; + const length = points.length; + for (let i = 0; i < length; i++) { + let pa, pb; if (i === length - 1) { pa = points[i]; pb = points[0]; @@ -2612,10 +2392,10 @@ function linePolygon(p1, p2, points, lineWidth, polygonWidth) { * @returns */ function polylinePolygon(polylinePoints, polygonPoints, polylineWidth, polygonWidth) { - var length = polylinePoints.length; - for (var i = 0; i < length - 1; i++) { - var p1 = polylinePoints[i]; - var p2 = polylinePoints[i + 1]; + const length = polylinePoints.length; + for (let i = 0; i < length - 1; i++) { + const p1 = polylinePoints[i]; + const p2 = polylinePoints[i + 1]; if (linePolygon(p1, p2, polygonPoints, polylineWidth, polygonWidth)) { return true; } @@ -2623,15 +2403,10 @@ function polylinePolygon(polylinePoints, polygonPoints, polylineWidth, polygonWi return false; } -function debounce(fn, waitMs) { - if (waitMs === void 0) { waitMs = 250; } - var timeoutId; - var debouncedFunction = function (context) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var invokeFunction = function () { +function debounce(fn, waitMs = 250) { + let timeoutId; + const debouncedFunction = function (context, ...args) { + const invokeFunction = function () { timeoutId = undefined; fn.apply(context, args); }; @@ -2649,61 +2424,65 @@ function debounce(fn, waitMs) { return debouncedFunction; } -var UP = new pixi_js.Point(0, -1); -var DOWN = new pixi_js.Point(0, 1); -var LEFT = new pixi_js.Point(-1, 0); -var RIGHT = new pixi_js.Point(1, 0); +const UP = new Point(0, -1); +const DOWN = new Point(0, 1); +const LEFT = new Point(-1, 0); +const RIGHT = new Point(1, 0); /** * 越界结果 */ -var OutOfBound = /** @class */ (function () { - function OutOfBound(left, top, right, bottom) { +class OutOfBound { + left; + top; + right; + bottom; + constructor(left, top, right, bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } - OutOfBound.check = function (rect, bound) { - var left = rect.left < bound.left; - var top = rect.top < bound.top; - var right = rect.right > bound.right; - var bottom = rect.bottom > bound.bottom; + static check(rect, bound) { + const left = rect.left < bound.left; + const top = rect.top < bound.top; + const right = rect.right > bound.right; + const bottom = rect.bottom > bound.bottom; return new OutOfBound(left, top, right, bottom); - }; - OutOfBound.none = function () { + } + static none() { return new OutOfBound(false, false, false, false); - }; - OutOfBound.leftOut = function () { + } + static leftOut() { return new OutOfBound(true, false, false, false); - }; - OutOfBound.topOut = function () { + } + static topOut() { return new OutOfBound(false, true, false, false); - }; - OutOfBound.rightOut = function () { + } + static rightOut() { return new OutOfBound(false, false, true, false); - }; - OutOfBound.bottomOut = function () { + } + static bottomOut() { return new OutOfBound(false, false, false, true); - }; - OutOfBound.leftTopOut = function () { + } + static leftTopOut() { return new OutOfBound(true, true, false, false); - }; - OutOfBound.rightBottomOut = function () { + } + static rightBottomOut() { return new OutOfBound(false, false, true, true); - }; - return OutOfBound; -}()); + } +} +/* eslint-disable @typescript-eslint/no-unused-vars */ /** * 可吸附点图形参数 */ -var AbsorbablePointParam = { +const AbsorbablePointParam = { lineWidth: 1, lineColor: '#000000', fillColor: '#E77E0E', radius: 5, // 半径 }; -var AbsorbablePointGraphic = new pixi_js.Graphics(); +const AbsorbablePointGraphic = new Graphics(); // AbsorbablePointGraphic.lineStyle( // AbsorbablePointParam.lineWidth, // AbsorbablePointParam.lineColor @@ -2711,193 +2490,130 @@ var AbsorbablePointGraphic = new pixi_js.Graphics(); AbsorbablePointGraphic.beginFill(AbsorbablePointParam.fillColor); AbsorbablePointGraphic.drawCircle(0, 0, AbsorbablePointParam.radius); AbsorbablePointGraphic.endFill(); -/** - * 可吸附点 - */ -/** @class */ ((function (_super) { - __extends(AbsorbablePoint, _super); - /** - * - * @param point 画布坐标 - * @param absorbRange - */ - function AbsorbablePoint(point, absorbRange) { - if (absorbRange === void 0) { absorbRange = 10; } - var _this = _super.call(this, AbsorbablePointGraphic.geometry) || this; - _this.scaledListenerOn = false; - _this._point = new pixi_js.Point(point.x, point.y); - _this.absorbRange = absorbRange; - _this.position.copyFrom(_this._point); - _this.interactive; - VectorGraphicUtil.handle(_this); - return _this; - } - AbsorbablePoint.prototype.compareTo = function (other) { - if (other instanceof AbsorbablePoint) { - return this.absorbRange - other.absorbRange; - } - throw new Error('非可吸附点'); - }; - AbsorbablePoint.prototype.isOverlapping = function (other) { - if (other instanceof AbsorbablePoint) { - return (this._point.equals(other._point) && - this.absorbRange === other.absorbRange); - } - return false; - }; - AbsorbablePoint.prototype.tryAbsorb = function () { - var objs = []; - for (var _i = 0; _i < arguments.length; _i++) { - objs[_i] = arguments[_i]; - } - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; - var canvasPosition = obj.getPositionOnCanvas(); - if (distance(this._point.x, this._point.y, canvasPosition.x, canvasPosition.y) < this.absorbRange) { - obj.updatePositionByCanvasPosition(this._point); - } - } - }; - AbsorbablePoint.prototype.updateOnScaled = function () { - var scaled = this.getAllParentScaled(); - var scale = Math.max(scaled.x, scaled.y); - this.scale.set(1 / scale, 1 / scale); - }; - return AbsorbablePoint; -})(pixi_js.Graphics)); /** * 可吸附线 */ -var AbsorbableLine = /** @class */ (function (_super) { - __extends(AbsorbableLine, _super); +class AbsorbableLine extends Graphics { + p1; + p2; + absorbRange; + _color = '#E77E0E'; /** * * @param p1 画布坐标 * @param p2 画布坐标 * @param absorbRange */ - function AbsorbableLine(p1, p2, absorbRange) { - if (absorbRange === void 0) { absorbRange = 20; } - var _this = _super.call(this) || this; - _this._color = '#E77E0E'; - _this.p1 = new pixi_js.Point(p1.x, p1.y); - _this.p2 = new pixi_js.Point(p2.x, p2.y); - _this.absorbRange = absorbRange; - _this.redraw(); - return _this; + constructor(p1, p2, absorbRange = 20) { + super(); + this.p1 = new Point(p1.x, p1.y); + this.p2 = new Point(p2.x, p2.y); + this.absorbRange = absorbRange; + this.redraw(); } - AbsorbableLine.prototype.isOverlapping = function (other) { + isOverlapping(other) { if (other instanceof AbsorbableLine) { - var contain = isLineContainOther({ p1: this.p1, p2: this.p2 }, { p1: other.p1, p2: other.p2 }); + const contain = isLineContainOther({ p1: this.p1, p2: this.p2 }, { p1: other.p1, p2: other.p2 }); return contain; } return false; - }; - AbsorbableLine.prototype.compareTo = function (other) { + } + compareTo(other) { if (other instanceof AbsorbableLine) { return distance2(this.p1, this.p2) - distance2(other.p1, other.p2); } throw new Error('非可吸附线'); - }; - AbsorbableLine.prototype.redraw = function () { + } + redraw() { this.clear(); - this.lineStyle(1, new pixi_js.Color(this._color)); + this.lineStyle(1, new Color(this._color)); this.moveTo(this.p1.x, this.p1.y); this.lineTo(this.p2.x, this.p2.y); - }; - AbsorbableLine.prototype.tryAbsorb = function () { - var objs = []; - for (var _i = 0; _i < arguments.length; _i++) { - objs[_i] = arguments[_i]; - } - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; - var canvasPosition = obj.getPositionOnCanvas(); + } + tryAbsorb(...objs) { + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; + const canvasPosition = obj.getPositionOnCanvas(); if (linePoint(this.p1, this.p2, canvasPosition, this.absorbRange, true)) { - var fp = calculateFootPointFromPointToLine(this.p1, this.p2, canvasPosition); + const fp = calculateFootPointFromPointToLine(this.p1, this.p2, canvasPosition); obj.updatePositionByCanvasPosition(fp); } } - }; - return AbsorbableLine; -}(pixi_js.Graphics)); + } +} /** * 可吸附圆 */ -var AbsorbableCircle = /** @class */ (function (_super) { - __extends(AbsorbableCircle, _super); +class AbsorbableCircle extends Graphics { + absorbRange; + p0; + radius; + _color = '#E77E0E'; /** * * @param p 画布坐标 * @param radius * @param absorbRange */ - function AbsorbableCircle(p, radius, absorbRange) { - if (absorbRange === void 0) { absorbRange = 10; } - var _this = _super.call(this) || this; - _this._color = '#E77E0E'; - _this.p0 = new pixi_js.Point(p.x, p.y); - _this.radius = radius; - _this.absorbRange = absorbRange; - _this.redraw(); - return _this; + constructor(p, radius, absorbRange = 10) { + super(); + this.p0 = new Point(p.x, p.y); + this.radius = radius; + this.absorbRange = absorbRange; + this.redraw(); } - AbsorbableCircle.prototype.isOverlapping = function (other) { + isOverlapping(other) { if (other instanceof AbsorbableCircle) { return this.p0.equals(other.p0) && this.radius === other.radius; } return false; - }; - AbsorbableCircle.prototype.compareTo = function (other) { + } + compareTo(other) { if (other instanceof AbsorbableCircle) { return this.absorbRange - other.absorbRange; } throw new Error('非可吸附圆'); - }; - AbsorbableCircle.prototype.redraw = function () { + } + redraw() { this.clear(); - this.lineStyle(1, new pixi_js.Color(this._color)); + this.lineStyle(1, new Color(this._color)); this.drawCircle(this.p0.x, this.p0.y, this.radius); - }; - AbsorbableCircle.prototype.tryAbsorb = function () { - var objs = []; - for (var _i = 0; _i < arguments.length; _i++) { - objs[_i] = arguments[_i]; - } - for (var i = 0; i < objs.length; i++) { - var obj = objs[i]; - var canvasPosition = obj.getPositionOnCanvas(); - var len = distance(this.p0.x, this.p0.y, canvasPosition.x, canvasPosition.y); + } + tryAbsorb(...objs) { + for (let i = 0; i < objs.length; i++) { + const obj = objs[i]; + const canvasPosition = obj.getPositionOnCanvas(); + const len = distance(this.p0.x, this.p0.y, canvasPosition.x, canvasPosition.y); if (len > this.radius - this.absorbRange && len < this.radius + this.absorbRange) { // 吸附,计算直线与圆交点,更新对象坐标 - var p = calculateIntersectionPointOfCircleAndPoint(this.p0, this.radius, canvasPosition); + const p = calculateIntersectionPointOfCircleAndPoint(this.p0, this.radius, canvasPosition); obj.updatePositionByCanvasPosition(p); } } - }; - return AbsorbableCircle; -}(pixi_js.Graphics)); + } +} -var DefaultDashedLineOptions = { +const DefaultDashedLineOptions = { length: 4, startSpace: 0, space: 4, lineWidth: 1, color: '#0000ff', }; -var DashedLine = /** @class */ (function (_super) { - __extends(DashedLine, _super); - function DashedLine(p1, p2, options) { - var _this = _super.call(this) || this; - var config = Object.assign({}, DefaultDashedLineOptions, options); - _this._options = config; - _this.p1 = new pixi_js.Point(p1.x, p1.y); - _this.p2 = new pixi_js.Point(p2.x, p2.y); - _this.redraw(); - return _this; +class DashedLine extends Container { + p1; + p2; + _options; + constructor(p1, p2, options) { + super(); + const config = Object.assign({}, DefaultDashedLineOptions, options); + this._options = config; + this.p1 = new Point(p1.x, p1.y); + this.p2 = new Point(p2.x, p2.y); + this.redraw(); } - DashedLine.prototype.setOptions = function (options) { + setOptions(options) { if (options.startSpace != undefined) { this._options.startSpace = options.startSpace; } @@ -2914,20 +2630,20 @@ var DashedLine = /** @class */ (function (_super) { this._options.color = options.color; } this.redraw(); - }; - DashedLine.prototype.redraw = function () { + } + redraw() { this.removeChildren(); - var p1 = this.p1; - var p2 = this.p2; - var option = this._options; - var total = Math.pow(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2), 0.5); - var len = option.startSpace; + const p1 = this.p1; + const p2 = this.p2; + const option = this._options; + const total = Math.pow(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2), 0.5); + let len = option.startSpace; while (len < total) { - var dashedLen = option.length; + let dashedLen = option.length; if (len + option.length > total) { dashedLen = total - len; } - var line = new pixi_js.Graphics(); + const line = new Graphics(); line.lineStyle(option.lineWidth, option.color); line.moveTo(len, 0); line.lineTo(len + dashedLen, 0); @@ -2937,136 +2653,143 @@ var DashedLine = /** @class */ (function (_super) { this.pivot.set(0, option.lineWidth / 2); this.position.set(p1.x, p1.y); this.angle = angleToAxisx(p1, p2); - }; - return DashedLine; -}(pixi_js.Container)); + } +} -var ShiftData = /** @class */ (function () { - function ShiftData(startPosition, currentPosition, lastPosition) { +/* eslint-disable @typescript-eslint/no-explicit-any */ +class ShiftData { + /** + * 起始位置 + */ + startPosition; + /** + * 上一次终点位置 + */ + lastPosition; + /** + * 当前位置 + */ + currentPosition; + constructor(startPosition, currentPosition, lastPosition) { this.startPosition = startPosition; this.lastPosition = lastPosition; this.currentPosition = currentPosition; } - ShiftData.new = function (startPosition, currentPosition, lastPosition) { + static new(startPosition, currentPosition, lastPosition) { return new ShiftData(startPosition, currentPosition, lastPosition); - }; - Object.defineProperty(ShiftData.prototype, "dx", { - get: function () { - if (!this.lastPosition || !this.currentPosition) { - throw new Error('错误的位移数据或阶段'); - } - return this.currentPosition.x - this.lastPosition.x; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ShiftData.prototype, "dy", { - get: function () { - if (!this.lastPosition || !this.currentPosition) { - throw new Error('错误的位移数据或阶段'); - } - return this.currentPosition.y - this.lastPosition.y; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ShiftData.prototype, "dsx", { - get: function () { - if (!this.currentPosition) { - throw new Error('错误的位移数据或阶段'); - } - return this.currentPosition.x - this.startPosition.x; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ShiftData.prototype, "dsy", { - get: function () { - if (!this.currentPosition) { - throw new Error('错误的位移数据或阶段'); - } - return this.currentPosition.y - this.startPosition.y; - }, - enumerable: false, - configurable: true - }); - return ShiftData; -}()); -var ScaleData = /** @class */ (function () { - function ScaleData(start, current, last) { + } + get dx() { + if (!this.lastPosition || !this.currentPosition) { + throw new Error('错误的位移数据或阶段'); + } + return this.currentPosition.x - this.lastPosition.x; + } + get dy() { + if (!this.lastPosition || !this.currentPosition) { + throw new Error('错误的位移数据或阶段'); + } + return this.currentPosition.y - this.lastPosition.y; + } + get dsx() { + if (!this.currentPosition) { + throw new Error('错误的位移数据或阶段'); + } + return this.currentPosition.x - this.startPosition.x; + } + get dsy() { + if (!this.currentPosition) { + throw new Error('错误的位移数据或阶段'); + } + return this.currentPosition.y - this.startPosition.y; + } +} +class ScaleData { + start; + current; + last; + constructor(start, current, last) { this.start = start; this.current = current; this.last = last; } - ScaleData.new = function (start, current, last) { + static new(start, current, last) { return new ScaleData(start, current, last); - }; - return ScaleData; -}()); + } +} /** * 图形平移事件 */ -var GraphicTransformEvent = /** @class */ (function () { - function GraphicTransformEvent(target, type, data) { +class GraphicTransformEvent { + /** + * 图形对象 + */ + target; + type; + data; + constructor(target, type, data) { this.target = target; this.type = type; this.data = data; } - GraphicTransformEvent.prototype.getData = function () { + getData() { return this.data; - }; - GraphicTransformEvent.shift = function (target, data) { + } + static shift(target, data) { return new GraphicTransformEvent(target, 'shift', data); - }; - GraphicTransformEvent.scale = function (target) { + } + static scale(target) { return new GraphicTransformEvent(target, 'scale', null); - }; - GraphicTransformEvent.rotate = function (target) { + } + static rotate(target) { return new GraphicTransformEvent(target, 'rotate', null); - }; - GraphicTransformEvent.skew = function (target) { + } + static skew(target) { return new GraphicTransformEvent(target, 'skew', null); - }; - GraphicTransformEvent.prototype.isShift = function () { + } + isShift() { return this.type === 'shift'; - }; - GraphicTransformEvent.prototype.isRotate = function () { + } + isRotate() { return this.type === 'rotate'; - }; - GraphicTransformEvent.prototype.isScale = function () { + } + isScale() { return this.type === 'scale'; - }; - GraphicTransformEvent.prototype.isSkew = function () { + } + isSkew() { return this.type === 'skew'; - }; - return GraphicTransformEvent; -}()); -var GraphicTransformPlugin = /** @class */ (function (_super) { - __extends(GraphicTransformPlugin, _super); - function GraphicTransformPlugin(app) { - var _this = _super.call(this, app, GraphicTransformPlugin.Name, exports.InteractionPluginType.Other) || this; - _this.apContainer = new pixi_js.Container(); - _this.apContainer.name = GraphicTransformPlugin.AbsorbablePosisiontsName; - _this.app.canvas.addAssistantAppend(_this.apContainer); - app.on('options-update', function (options) { + } +} +class GraphicTransformPlugin extends InteractionPluginBase { + static Name = '__graphic_transform_plugin'; + /** + * 可吸附位置列表 + */ + absorbablePositions; + apContainer; + static AbsorbablePosisiontsName = '__AbsorbablePosisionts'; + constructor(app) { + super(app, GraphicTransformPlugin.Name, InteractionPluginType.Other); + this.apContainer = new Container(); + this.apContainer.name = GraphicTransformPlugin.AbsorbablePosisiontsName; + this.app.canvas.addAssistantAppend(this.apContainer); + app.on('options-update', (options) => { if (options.absorbablePositions) { - _this.absorbablePositions = _this.filterAbsorbablePositions(options.absorbablePositions); + this.absorbablePositions = this.filterAbsorbablePositions(options.absorbablePositions); } }); - return _this; } /** * 过滤重复的吸附位置 * @param positions * @returns */ - GraphicTransformPlugin.prototype.filterAbsorbablePositions = function (positions) { - var aps = []; - for (var i = 0; i < positions.length; i++) { - var ap1 = positions[i]; - var ap = ap1; - for (var j = positions.length - 1; j > i; j--) { - var ap2 = positions[j]; + filterAbsorbablePositions(positions) { + const aps = []; + for (let i = 0; i < positions.length; i++) { + const ap1 = positions[i]; + let ap = ap1; + for (let j = positions.length - 1; j > i; j--) { + const ap2 = positions[j]; if (ap.isOverlapping(ap2) && ap.compareTo(ap2) <= 0) { ap = null; break; @@ -3076,100 +2799,95 @@ var GraphicTransformPlugin = /** @class */ (function (_super) { aps.push(ap); } } - // console.log(positions, aps); return aps; - }; - GraphicTransformPlugin.new = function (app) { + } + static new(app) { return new GraphicTransformPlugin(app); - }; - GraphicTransformPlugin.prototype.bind = function () { + } + bind() { this.app.on('drag_op_start', this.onDragStart, this); this.app.on('drag_op_move', this.onDragMove, this); this.app.on('drag_op_end', this.onDragEnd, this); this.app.on('graphicselectedchange', this.onGraphicSelectedChange, this); this.app.on('graphicchildselectedchange', this.onGraphicSelectedChange, this); - }; - GraphicTransformPlugin.prototype.unbind = function () { + } + unbind() { this.app.off('drag_op_start', this.onDragStart, this); this.app.off('drag_op_move', this.onDragMove, this); this.app.off('drag_op_end', this.onDragEnd, this); this.app.off('graphicselectedchange', this.onGraphicSelectedChange, this); this.app.off('graphicchildselectedchange', this.onGraphicSelectedChange, this); - }; - GraphicTransformPlugin.prototype.getDraggedTargets = function (e) { - var _a; - var targets = []; + } + getDraggedTargets(e) { + const targets = []; if (e.target.isGraphicChild() && e.target.selected && e.target.draggable) { - var graphic = e.target.getGraphic(); + const graphic = e.target.getGraphic(); // 图形子元素 - recursiveChildren(graphic, function (child) { + recursiveChildren(graphic, (child) => { if (child.selected && child.draggable) { targets.push(child); } }); } else if ((e.target.isGraphic() || e.target.isGraphicChild()) && - ((_a = e.target.getGraphic()) === null || _a === void 0 ? void 0 : _a.draggable)) { + e.target.getGraphic()?.draggable) { // 图形对象 - targets.push.apply(targets, this.app.selectedGraphics); + targets.push(...this.app.selectedGraphics); } else if (e.target.draggable) { targets.push(e.target); } return targets; - }; - GraphicTransformPlugin.prototype.onDragStart = function (e) { - var _a; + } + onDragStart(e) { if (!e.target.isCanvas() && e.isLeftButton) { - var targets = this.getDraggedTargets(e); + const targets = this.getDraggedTargets(e); if (targets.length > 0) { - targets.forEach(function (target) { + targets.forEach((target) => { target.shiftStartPoint = target.position.clone(); target.emit('transformstart', GraphicTransformEvent.shift(target, ShiftData.new(target.shiftStartPoint))); }); // 显示吸附图形 if (this.absorbablePositions && this.absorbablePositions.length > 0) { this.apContainer.removeChildren(); - (_a = this.apContainer).addChild.apply(_a, this.absorbablePositions); + this.apContainer.addChild(...this.absorbablePositions); } } } - }; - GraphicTransformPlugin.prototype.onDragMove = function (e) { + } + onDragMove(e) { if (!e.target.isCanvas() && e.isLeftButton) { - var targets = this.getDraggedTargets(e); + const targets = this.getDraggedTargets(e); if (targets.length > 0) { // 处理位移 - targets.forEach(function (target) { + targets.forEach((target) => { if (target.shiftStartPoint) { target.shiftLastPoint = target.position.clone(); - var _a = e.toTargetShiftLen(target.parent), dx = _a.dx, dy = _a.dy; + const { dx, dy } = e.toTargetShiftLen(target.parent); target.position.set(target.shiftStartPoint.x + dx, target.shiftStartPoint.y + dy); } }); // 处理吸附 if (this.absorbablePositions) { - for (var i = 0; i < this.absorbablePositions.length; i++) { - var ap = this.absorbablePositions[i]; - ap.tryAbsorb.apply(ap, targets); + for (let i = 0; i < this.absorbablePositions.length; i++) { + const ap = this.absorbablePositions[i]; + ap.tryAbsorb(...targets); } } // const start = new Date().getTime(); // 事件发布 - targets.forEach(function (target) { + targets.forEach((target) => { if (target.shiftStartPoint && target.shiftLastPoint) { target.emit('transforming', GraphicTransformEvent.shift(target, ShiftData.new(target.shiftStartPoint, target.position.clone(), target.shiftLastPoint))); } }); - // const dt = new Date().getTime() - start; - // console.log('拖拽耗时', `${dt}ms`, targets); } } - }; - GraphicTransformPlugin.prototype.onDragEnd = function (e) { + } + onDragEnd(e) { if (!e.target.isCanvas() && e.isLeftButton) { - var targets = this.getDraggedTargets(e); - targets.forEach(function (target) { + const targets = this.getDraggedTargets(e); + targets.forEach((target) => { if (target.shiftStartPoint) { target.emit('transformend', GraphicTransformEvent.shift(target, ShiftData.new(target.shiftStartPoint, target.position.clone()))); } @@ -3177,17 +2895,17 @@ var GraphicTransformPlugin = /** @class */ (function (_super) { }); } this.clearCache(); - }; + } /** * 清理缓存 */ - GraphicTransformPlugin.prototype.clearCache = function () { + clearCache() { // 移除吸附图形 this.absorbablePositions = []; this.apContainer.removeChildren(); - }; - GraphicTransformPlugin.prototype.onGraphicSelectedChange = function (g, selected) { - var br = g.getAssistantAppend(BoundsGraphic.Name); + } + onGraphicSelectedChange(g, selected) { + let br = g.getAssistantAppend(BoundsGraphic.Name); if (!br) { // 绘制辅助包围框 br = new BoundsGraphic(g); @@ -3205,7 +2923,7 @@ var GraphicTransformPlugin = /** @class */ (function (_super) { } if (g.scalable || g.rotatable) { // 缩放点 - var sp = g.getAssistantAppend(TransformPoints.Name); + let sp = g.getAssistantAppend(TransformPoints.Name); if (!sp) { sp = new TransformPoints(g); } @@ -3217,169 +2935,192 @@ var GraphicTransformPlugin = /** @class */ (function (_super) { sp.visible = false; } } - }; - GraphicTransformPlugin.Name = '__graphic_transform_plugin'; - GraphicTransformPlugin.AbsorbablePosisiontsName = '__AbsorbablePosisionts'; - return GraphicTransformPlugin; -}(InteractionPluginBase)); + } +} /** * 缩放、旋转辅助 */ -var TransformPoints = /** @class */ (function (_super) { - __extends(TransformPoints, _super); - function TransformPoints(obj) { - var _this = _super.call(this) || this; - _this.ltLocal = new pixi_js.Point(); - _this.tLocal = new pixi_js.Point(); - _this.tCanvas = new pixi_js.Point(); - _this.rtLocal = new pixi_js.Point(); - _this.rLocal = new pixi_js.Point(); - _this.rbLocal = new pixi_js.Point(); - _this.bLocal = new pixi_js.Point(); - _this.lbLocal = new pixi_js.Point(); - _this.lLocal = new pixi_js.Point(); - _this.originScale = new pixi_js.Point(); - _this.scalePivot = new pixi_js.Point(); - /** - * 起始图形角度 - */ - _this.startAngle = 0; - /** - * 旋转角度步长 - */ - _this.angleStep = 1; - /** - * 修改旋转步长键盘监听 - */ - _this.rotateAngleStepKeyListeners = []; - _this.obj = obj; - _this.name = TransformPoints.Name; - _this.angleAssistantText = new VectorText('', { +class TransformPoints extends Container { + static Name = 'transformPoints'; + static MinLength = 40; + static LeftTopName = 'lt-scale-point'; + static TopName = 't-scale-point'; + static RightTopName = 'rt-scale-point'; + static RightName = 'r-scale-point'; + static RightBottomName = 'rb-scale-point'; + static BottomName = 'b-scale-point'; + static LeftBottomName = 'lb-scale-point'; + static LeftName = 'l-scale-point'; + static RotateName = 'rotate-point'; + obj; + ltScalePoint; + ltLocal = new Point(); + tScalePoint; + tLocal = new Point(); + tCanvas = new Point(); + rtScalePoint; + rtLocal = new Point(); + rScalePoint; + rLocal = new Point(); + rbScalePoint; + rbLocal = new Point(); + bScalePoint; + bLocal = new Point(); + lbScalePoint; + lbLocal = new Point(); + lScalePoint; + lLocal = new Point(); + originScale = new Point(); + scalePivot = new Point(); + /** + * 旋转拖拽点 + */ + rotatePoint; + /** + * 旋转中心坐标 + */ + rotatePivot; + /** + * 起始旋转坐标 + */ + rotateLastPoint; + /** + * 起始图形角度 + */ + startAngle = 0; + /** + * 当前角度信息文本辅助 + */ + angleAssistantText; + /** + * 旋转角度步长 + */ + angleStep = 1; + /** + * 修改旋转步长键盘监听 + */ + rotateAngleStepKeyListeners = []; + constructor(obj) { + super(); + this.obj = obj; + this.name = TransformPoints.Name; + this.angleAssistantText = new VectorText('', { fill: AppConsts.assistantElementColor, }); - _this.angleAssistantText.setVectorFontSize(16); - _this.angleAssistantText.anchor.set(0.5); + this.angleAssistantText.setVectorFontSize(16); + this.angleAssistantText.anchor.set(0.5); // 创建缩放拖拽点 - _this.ltScalePoint = new DraggablePoint(new pixi_js.Point()); - _this.ltScalePoint.name = TransformPoints.LeftTopName; - _this.addChild(_this.ltScalePoint); - _this.tScalePoint = new DraggablePoint(new pixi_js.Point()); - _this.tScalePoint.name = TransformPoints.TopName; - _this.addChild(_this.tScalePoint); - _this.rtScalePoint = new DraggablePoint(new pixi_js.Point()); - _this.rtScalePoint.name = TransformPoints.RightTopName; - _this.addChild(_this.rtScalePoint); - _this.rScalePoint = new DraggablePoint(new pixi_js.Point()); - _this.rScalePoint.name = TransformPoints.RightName; - _this.addChild(_this.rScalePoint); - _this.rbScalePoint = new DraggablePoint(new pixi_js.Point()); - _this.rbScalePoint.name = TransformPoints.RightBottomName; - _this.addChild(_this.rbScalePoint); - _this.bScalePoint = new DraggablePoint(new pixi_js.Point()); - _this.bScalePoint.name = TransformPoints.BottomName; - _this.addChild(_this.bScalePoint); - _this.lbScalePoint = new DraggablePoint(new pixi_js.Point()); - _this.lbScalePoint.name = TransformPoints.LeftBottomName; - _this.addChild(_this.lbScalePoint); - _this.lScalePoint = new DraggablePoint(new pixi_js.Point()); - _this.lScalePoint.name = TransformPoints.LeftName; - _this.addChild(_this.lScalePoint); - _this.obj.on('transformstart', _this.onObjTransformStart, _this); - _this.obj.on('transformend', _this.onObjTransformEnd, _this); - if (_this.obj.children && _this.obj.children.length > 0) { - recursiveChildren(_this.obj, function (child) { - child.on('transformstart', _this.onObjTransformStart, _this); - child.on('transformend', _this.onObjTransformEnd, _this); + this.ltScalePoint = new DraggablePoint(new Point()); + this.ltScalePoint.name = TransformPoints.LeftTopName; + this.addChild(this.ltScalePoint); + this.tScalePoint = new DraggablePoint(new Point()); + this.tScalePoint.name = TransformPoints.TopName; + this.addChild(this.tScalePoint); + this.rtScalePoint = new DraggablePoint(new Point()); + this.rtScalePoint.name = TransformPoints.RightTopName; + this.addChild(this.rtScalePoint); + this.rScalePoint = new DraggablePoint(new Point()); + this.rScalePoint.name = TransformPoints.RightName; + this.addChild(this.rScalePoint); + this.rbScalePoint = new DraggablePoint(new Point()); + this.rbScalePoint.name = TransformPoints.RightBottomName; + this.addChild(this.rbScalePoint); + this.bScalePoint = new DraggablePoint(new Point()); + this.bScalePoint.name = TransformPoints.BottomName; + this.addChild(this.bScalePoint); + this.lbScalePoint = new DraggablePoint(new Point()); + this.lbScalePoint.name = TransformPoints.LeftBottomName; + this.addChild(this.lbScalePoint); + this.lScalePoint = new DraggablePoint(new Point()); + this.lScalePoint.name = TransformPoints.LeftName; + this.addChild(this.lScalePoint); + this.obj.on('transformstart', this.onObjTransformStart, this); + this.obj.on('transformend', this.onObjTransformEnd, this); + if (this.obj.children && this.obj.children.length > 0) { + recursiveChildren(this.obj, (child) => { + child.on('transformstart', this.onObjTransformStart, this); + child.on('transformend', this.onObjTransformEnd, this); }); } - var pg = _this.obj.getGraphic(); + const pg = this.obj.getGraphic(); if (pg != null) { - pg.on('transformstart', _this.onObjTransformStart, _this); - pg.on('transformend', _this.onObjTransformEnd, _this); + pg.on('transformstart', this.onObjTransformStart, this); + pg.on('transformend', this.onObjTransformEnd, this); } - _this.obj.on('repaint', _this.onGraphicRepaint, _this); - _this.children.forEach(function (dp) { - dp.on('transformstart', _this.onScaleDragStart, _this); - dp.on('transforming', _this.onScaleDragMove, _this); - dp.on('transformend', _this.onScaleDragEnd, _this); + this.obj.on('repaint', this.onGraphicRepaint, this); + this.children.forEach((dp) => { + dp.on('transformstart', this.onScaleDragStart, this); + dp.on('transforming', this.onScaleDragMove, this); + dp.on('transformend', this.onScaleDragEnd, this); }); // 创建旋转拖拽点 - _this.rotatePoint = new DraggablePoint(new pixi_js.Point()); - _this.addChild(_this.rotatePoint); - _this.rotatePoint.on('transformstart', _this.onRotateStart, _this); - _this.rotatePoint.on('transforming', _this.onRotateMove, _this); - _this.rotatePoint.on('transformend', _this.onRotateEnd, _this); - _this.rotatePivot = new pixi_js.Point(); - _this.rotateLastPoint = new pixi_js.Point(); - var _loop_1 = function (i) { - this_1.rotateAngleStepKeyListeners.push(KeyListener.create({ + this.rotatePoint = new DraggablePoint(new Point()); + this.addChild(this.rotatePoint); + this.rotatePoint.on('transformstart', this.onRotateStart, this); + this.rotatePoint.on('transforming', this.onRotateMove, this); + this.rotatePoint.on('transformend', this.onRotateEnd, this); + this.rotatePivot = new Point(); + this.rotateLastPoint = new Point(); + // 初始化旋转角度修改键盘监听器 + for (let i = 1; i < 10; i++) { + this.rotateAngleStepKeyListeners.push(KeyListener.create({ value: '' + i, - onPress: function () { - // console.log('修改角度step'); - _this.angleStep = i; + onPress: () => { + this.angleStep = i; }, })); - }; - var this_1 = this; - // 初始化旋转角度修改键盘监听器 - for (var i = 1; i < 10; i++) { - _loop_1(i); } - _this.obj.addAssistantAppend(_this); - return _this; + this.obj.addAssistantAppend(this); } - TransformPoints.prototype.onObjTransformStart = function () { + onObjTransformStart() { this.visible = false; - }; - TransformPoints.prototype.onObjTransformEnd = function () { + } + onObjTransformEnd() { this.update(); this.visible = true; - }; - TransformPoints.prototype.onGraphicRepaint = function () { + } + onGraphicRepaint() { if (this.visible) { this.update(); } - }; + } /** * 旋转开始 * @param de */ - TransformPoints.prototype.onRotateStart = function (de) { + onRotateStart(de) { this.hideAll(); - var assistantPoint = this.obj.localToCanvasPoint(this.obj.pivot); + const assistantPoint = this.obj.localToCanvasPoint(this.obj.pivot); this.rotatePivot.copyFrom(assistantPoint); this.rotateLastPoint.copyFrom(de.target.position); this.startAngle = this.obj.angle; - var app = this.obj.getGraphicApp(); - this.rotateAngleStepKeyListeners.forEach(function (listener) { - return app.addKeyboardListener(listener); - }); + const app = this.obj.getGraphicApp(); + this.rotateAngleStepKeyListeners.forEach((listener) => app.addKeyboardListener(listener)); this.obj.emit('transformstart', GraphicTransformEvent.rotate(this.obj)); // app.emit('transformstart', app.selectedGraphics); this.obj.getCanvas().addAssistantAppends(this.angleAssistantText); this.updateAngleAssistantText(de); - }; - TransformPoints.prototype.updateAngleAssistantText = function (de) { - var _a, _b, _c; + } + updateAngleAssistantText(de) { this.angleAssistantText.text = this.obj.angle + '°'; - var cursorPoint = (_a = de.data) === null || _a === void 0 ? void 0 : _a.startPosition; - if ((_b = de.data) === null || _b === void 0 ? void 0 : _b.currentPosition) { - cursorPoint = (_c = de.data) === null || _c === void 0 ? void 0 : _c.currentPosition; + let cursorPoint = de.data?.startPosition; + if (de.data?.currentPosition) { + cursorPoint = de.data?.currentPosition; } if (cursorPoint) { this.angleAssistantText.position.x = cursorPoint.x; this.angleAssistantText.position.y = cursorPoint.y - 10; } - }; + } /** * 旋转移动 * @param de */ - TransformPoints.prototype.onRotateMove = function (de) { + onRotateMove(de) { // 旋转角度计算逻辑:取锚点y负方向一点作为旋转点,求旋转点和锚点所形成的直线与x轴角度,此角度+90°即为最终旋转角度,再将旋转角度限制到(-180,180]之间 - var angle = angleToAxisx(this.rotatePivot, de.target.position); + let angle = angleToAxisx(this.rotatePivot, de.target.position); angle = Math.floor(angle / this.angleStep) * this.angleStep; - var parentAngle = this.obj.parent.worldAngle; + const parentAngle = this.obj.parent.worldAngle; angle = (angle + 90 - parentAngle) % 360; if (angle > 180) { angle = angle - 360; @@ -3387,30 +3128,27 @@ var TransformPoints = /** @class */ (function (_super) { this.obj.angle = angle; this.updateAngleAssistantText(de); // this.obj.emit('rotatemove', this.obj); - }; + } /** * 旋转结束 * @param de */ - TransformPoints.prototype.onRotateEnd = function () { - var _this = this; + onRotateEnd() { this.showAll(); this.obj.getCanvas().removeAssistantAppends(this.angleAssistantText); - this.rotateAngleStepKeyListeners.forEach(function (listener) { - return _this.obj.getGraphicApp().removeKeyboardListener(listener); - }); + this.rotateAngleStepKeyListeners.forEach((listener) => this.obj.getGraphicApp().removeKeyboardListener(listener)); this.obj.emit('transformend', GraphicTransformEvent.rotate(this.obj)); - }; + } /** * 缩放开始 */ - TransformPoints.prototype.onScaleDragStart = function () { + onScaleDragStart() { this.hideAll(); - var points = convertRectangleToPolygonPoints(this.obj.getLocalBounds()); - var p0 = points[0]; - var p1 = points[1]; - var p2 = points[2]; - var p3 = points[3]; + const points = convertRectangleToPolygonPoints(this.obj.getLocalBounds()); + const p0 = points[0]; + const p1 = points[1]; + const p2 = points[2]; + const p3 = points[3]; this.scalePivot = this.obj.pivot.clone(); this.ltLocal.copyFrom(p0); this.tCanvas.copyFrom(this.obj.localToCanvasPoint(calculateLineMidpoint(p0, p1))); @@ -3423,20 +3161,20 @@ var TransformPoints = /** @class */ (function (_super) { this.lLocal.copyFrom(calculateLineMidpoint(p0, p3)); this.originScale = this.obj.scale.clone(); this.obj.emit('transformstart', GraphicTransformEvent.scale(this.obj)); - }; - TransformPoints.prototype.onScaleDragMove = function (e) { + } + onScaleDragMove(e) { // 缩放计算逻辑:共8个方向缩放点,根据所拖拽的方向: // 1,计算缩放为1时的此点在拖拽开始时的位置到锚点x、y距离, // 2,计算拖拽点的当前位置到锚点的x、y方向距离, // PS:以上两个计算都是在local(也就是图形对象本地)坐标系, // 用当前距离除以原始距离即为缩放比例 - var defaultScale = new pixi_js.Point(1, 1); - var originWidth = 0; - var originHeight = 0; - var width = 0; - var height = 0; + const defaultScale = new Point(1, 1); + let originWidth = 0; + let originHeight = 0; + let width = 0; + let height = 0; this.obj.scale.copyFrom(defaultScale); - var point = this.obj.toLocal(e.target.parent.localToScreenPoint(e.target.position)); + const point = this.obj.toLocal(e.target.parent.localToScreenPoint(e.target.position)); if (e.target === this.ltScalePoint) { // 左上角 originWidth = Math.abs(this.ltLocal.x - this.scalePivot.x); @@ -3486,11 +3224,10 @@ var TransformPoints = /** @class */ (function (_super) { width = Math.abs(point.x - this.scalePivot.x); } // 计算缩放比例,并根据是否保持纵横比两种情况进行缩放处理 - var sx = originWidth == 0 ? this.originScale.x : width / originWidth; - var sy = originHeight == 0 ? this.originScale.y : height / originHeight; - // console.log(originWidth, originHeight, width, height, sx, sy); + const sx = originWidth == 0 ? this.originScale.x : width / originWidth; + const sy = originHeight == 0 ? this.originScale.y : height / originHeight; if (this.obj.keepAspectRatio) { - var max = Math.max(sx, sy); + let max = Math.max(sx, sy); if (originWidth == 0) { max = sy; } @@ -3503,56 +3240,56 @@ var TransformPoints = /** @class */ (function (_super) { this.obj.scale.x = sx; this.obj.scale.y = sy; } - }; - TransformPoints.prototype.onScaleDragEnd = function () { + } + onScaleDragEnd() { this.showAll(); this.obj.emit('transformend', GraphicTransformEvent.scale(this.obj)); - }; - TransformPoints.prototype.hideOthers = function (dg) { - this.children.forEach(function (child) { + } + hideOthers(dg) { + this.children.forEach((child) => { if (child.name !== dg.name) { child.visible = false; } }); - }; - TransformPoints.prototype.hideAll = function () { - this.children.forEach(function (child) { return (child.visible = false); }); - }; - TransformPoints.prototype.showAll = function () { + } + hideAll() { + this.children.forEach((child) => (child.visible = false)); + } + showAll() { this.update(); - this.children.forEach(function (child) { return (child.visible = true); }); - }; - TransformPoints.prototype.getObjBounds = function () { - var points = this.obj.localBoundsToCanvasPoints(); - var p0 = points[0]; - var p1 = points[1]; - var p3 = points[3]; - var width = distance(p0.x, p0.y, p1.x, p1.y); - var height = distance(p0.x, p0.y, p3.x, p3.y); - return { width: width, height: height }; - }; + this.children.forEach((child) => (child.visible = true)); + } + getObjBounds() { + const points = this.obj.localBoundsToCanvasPoints(); + const p0 = points[0]; + const p1 = points[1]; + const p3 = points[3]; + const width = distance(p0.x, p0.y, p1.x, p1.y); + const height = distance(p0.x, p0.y, p3.x, p3.y); + return { width, height }; + } /** * 更新位置和cursor * @returns */ - TransformPoints.prototype.update = function () { + update() { if (this.obj.scalable) { this.updateScalePoints(); } if (this.obj.rotatable) { this.updateRotatePoint(); } - }; - TransformPoints.prototype.updateRotatePoint = function () { - var rect = this.obj.getLocalBounds(); - var lp = this.obj.pivot.clone(); - var dy = 10 / this.obj.scale.y; + } + updateRotatePoint() { + const rect = this.obj.getLocalBounds(); + const lp = this.obj.pivot.clone(); + const dy = 10 / this.obj.scale.y; lp.y = rect.y - dy; - var p = this.obj.localToCanvasPoint(lp); + const p = this.obj.localToCanvasPoint(lp); this.rotatePoint.position.copyFrom(p); - }; - TransformPoints.prototype.updateScalePoints = function () { - var points = this.obj.localBoundsToCanvasPoints(); + } + updateScalePoints() { + const points = this.obj.localBoundsToCanvasPoints(); this.ltScalePoint.position.copyFrom(points[0]); this.tScalePoint.position.copyFrom(calculateLineMidpoint(points[0], points[1])); this.rtScalePoint.position.copyFrom(points[1]); @@ -3561,8 +3298,8 @@ var TransformPoints = /** @class */ (function (_super) { this.bScalePoint.position.copyFrom(calculateLineMidpoint(points[2], points[3])); this.lbScalePoint.position.copyFrom(points[3]); this.lScalePoint.position.copyFrom(calculateLineMidpoint(points[3], points[0])); - var angle = this.obj.worldAngle; - var angle360 = (360 + angle) % 360; + const angle = this.obj.worldAngle; + const angle360 = (360 + angle) % 360; if ((angle >= -22.5 && angle <= 22.5) || (angle360 >= 180 - 22.5 && angle360 <= 180 + 22.5)) { this.ltScalePoint.cursor = 'nw-resize'; @@ -3606,399 +3343,374 @@ var TransformPoints = /** @class */ (function (_super) { this.lbScalePoint.cursor = 'n-resize'; this.lScalePoint.cursor = 'ne-resize'; } - }; - TransformPoints.Name = 'transformPoints'; - TransformPoints.MinLength = 40; - TransformPoints.LeftTopName = 'lt-scale-point'; - TransformPoints.TopName = 't-scale-point'; - TransformPoints.RightTopName = 'rt-scale-point'; - TransformPoints.RightName = 'r-scale-point'; - TransformPoints.RightBottomName = 'rb-scale-point'; - TransformPoints.BottomName = 'b-scale-point'; - TransformPoints.LeftBottomName = 'lb-scale-point'; - TransformPoints.LeftName = 'l-scale-point'; - TransformPoints.RotateName = 'rotate-point'; - return TransformPoints; -}(pixi_js.Container)); + } +} /** * 包围盒矩形图形,现使用外边框转画布多边形实现 */ -var BoundsGraphic = /** @class */ (function (_super) { - __extends(BoundsGraphic, _super); - function BoundsGraphic(graphic) { - var _this = _super.call(this) || this; - _this.obj = graphic; - _this.name = BoundsGraphic.Name; - _this.visible = false; - _this.debouncedRedraw = debounce(_this.doRedraw, 50); - _this.obj.on('transformstart', _this.onObjTransformStart, _this); - _this.obj.on('transformend', _this.onObjTransformEnd, _this); - if (_this.obj.children && _this.obj.children.length > 0) { - recursiveChildren(_this.obj, function (child) { - child.on('transformstart', _this.onObjTransformStart, _this); - child.on('transformend', _this.onObjTransformEnd, _this); - }); - } - var pg = _this.obj.getGraphic(); - if (pg != null) { - pg.on('transformstart', _this.onObjTransformStart, _this); - pg.on('transformend', _this.onObjTransformEnd, _this); - } - _this.obj.on('repaint', _this.onGraphicRepaint, _this); - graphic.addAssistantAppend(_this); - return _this; - } - BoundsGraphic.prototype.onObjTransformStart = function () { - this.visible = false; - }; - BoundsGraphic.prototype.onObjTransformEnd = function () { - this.redraw(); - this.visible = true; - }; - BoundsGraphic.prototype.onGraphicRepaint = function () { - if (this.visible) { - this.redraw(); - } - }; - BoundsGraphic.prototype.destroy = function (options) { - if (this.obj.isGraphic()) { - this.obj.off('repaint', this.onGraphicRepaint, this); - } - _super.prototype.destroy.call(this, options); - }; - BoundsGraphic.prototype.redraw = function () { - this.debouncedRedraw(this); - }; - BoundsGraphic.prototype.doRedraw = function () { - var visible = this.visible; - this.visible = false; // 屏蔽包围框本身 - var bounds = new pixi_js.Polygon(this.obj.localBoundsToCanvasPoints()); - this.clear().lineStyle(BoundsGraphic.BoundsLineStyle).drawShape(bounds); - this.visible = visible; - }; - BoundsGraphic.Name = '_BoundsRect'; - BoundsGraphic.BoundsLineStyle = { +class BoundsGraphic extends Graphics { + static Name = '_BoundsRect'; + static BoundsLineStyle = { width: 1, color: '#1976d2', alpha: 1, }; - return BoundsGraphic; -}(pixi_js.Graphics)); + obj; + debouncedRedraw; + constructor(graphic) { + super(); + this.obj = graphic; + this.name = BoundsGraphic.Name; + this.visible = false; + this.debouncedRedraw = debounce(this.doRedraw, 50); + this.obj.on('transformstart', this.onObjTransformStart, this); + this.obj.on('transformend', this.onObjTransformEnd, this); + if (this.obj.children && this.obj.children.length > 0) { + recursiveChildren(this.obj, (child) => { + child.on('transformstart', this.onObjTransformStart, this); + child.on('transformend', this.onObjTransformEnd, this); + }); + } + const pg = this.obj.getGraphic(); + if (pg != null) { + pg.on('transformstart', this.onObjTransformStart, this); + pg.on('transformend', this.onObjTransformEnd, this); + } + this.obj.on('repaint', this.onGraphicRepaint, this); + graphic.addAssistantAppend(this); + } + onObjTransformStart() { + this.visible = false; + } + onObjTransformEnd() { + this.redraw(); + this.visible = true; + } + onGraphicRepaint() { + if (this.visible) { + this.redraw(); + } + } + destroy(options) { + if (this.obj.isGraphic()) { + this.obj.off('repaint', this.onGraphicRepaint, this); + } + super.destroy(options); + } + redraw() { + this.debouncedRedraw(this); + } + doRedraw() { + const visible = this.visible; + this.visible = false; // 屏蔽包围框本身 + const bounds = new Polygon(this.obj.localBoundsToCanvasPoints()); + this.clear().lineStyle(BoundsGraphic.BoundsLineStyle).drawShape(bounds); + this.visible = visible; + } +} /** * 图形动画管理 */ -var AnimationManager = /** @class */ (function () { - function AnimationManager(app) { +class AnimationManager { + app; + _pause; + /** + * key - graphic.id + */ + graphicAnimationMap; + constructor(app) { this.app = app; this._pause = false; this.graphicAnimationMap = new Map(); // 动画控制 app.pixi.ticker.add(this.run, this); } - AnimationManager.prototype.run = function (dt) { + run(dt) { if (this._pause) { // 暂停 return; } - this.graphicAnimationMap.forEach(function (map) { - map.forEach(function (animation) { + this.graphicAnimationMap.forEach((map) => { + map.forEach((animation) => { if (animation.running) { animation.run(dt); } }); }); - }; - AnimationManager.prototype.pause = function () { + } + pause() { this._pause = true; - }; - AnimationManager.prototype.resume = function () { + } + resume() { this._pause = false; - }; - AnimationManager.prototype.destroy = function () { + } + destroy() { this.app.pixi.ticker.remove(this.run, this); - }; + } /** * 图形对象的所有动画map * @param graphic * @returns */ - AnimationManager.prototype.animationMap = function (graphic) { - var map = this.graphicAnimationMap.get(graphic.id); + animationMap(graphic) { + let map = this.graphicAnimationMap.get(graphic.id); if (!map) { map = new Map(); this.graphicAnimationMap.set(graphic.id, map); } return map; - }; + } /** * 注册图形动画 * @param graphic * @param animation */ - AnimationManager.prototype.registerAnimation = function (graphic, animation) { + registerAnimation(graphic, animation) { this.animationMap(graphic).set(animation.name, animation); - }; + } /** * 删除图形动画 * @param graphic * @param name */ - AnimationManager.prototype.unregisterAnimation = function (graphic, name) { + unregisterAnimation(graphic, name) { this.animationMap(graphic).delete(name); - }; + } /** * 删除所有图形动画 * @param graphic */ - AnimationManager.prototype.unregisterGraphicAnimations = function (graphic) { + unregisterGraphicAnimations(graphic) { this.animationMap(graphic).clear(); - }; + } /** * 获取图形指定名称动画 * @param graphic * @param name * @returns */ - AnimationManager.prototype.animation = function (graphic, name) { + animation(graphic, name) { return this.animationMap(graphic).get(name); - }; - return AnimationManager; -}()); + } +} /** * 操作 */ -var JlOperation = /** @class */ (function () { - function JlOperation(app, type) { - this.description = ''; // 操作描述 +class JlOperation { + type; // 操作类型/名称 + app; + obj; // 操作对象 + data; // 操作数据 + description = ''; // 操作描述 + constructor(app, type) { this.app = app; this.type = type; } - JlOperation.prototype.undo1 = function () { - var _a; - var updates = this.undo(); + undo1() { + const updates = this.undo(); if (updates) { - (_a = this.app).updateSelected.apply(_a, updates); + this.app.updateSelected(...updates); } - }; - JlOperation.prototype.redo1 = function () { - var _a; - var updates = this.redo(); + } + redo1() { + const updates = this.redo(); if (updates) { - (_a = this.app).updateSelected.apply(_a, updates); + this.app.updateSelected(...updates); } - }; - return JlOperation; -}()); + } +} /** * 操作记录 */ -var OperationRecord = /** @class */ (function () { - function OperationRecord(maxLen) { - if (maxLen === void 0) { maxLen = 100; } - this.undoStack = []; - this.redoStack = []; +class OperationRecord { + undoStack = []; + redoStack = []; + maxLen; + constructor(maxLen = 100) { this.maxLen = maxLen; } - Object.defineProperty(OperationRecord.prototype, "hasUndo", { - get: function () { - return this.undoStack.length > 0; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(OperationRecord.prototype, "hasRedo", { - get: function () { - return this.redoStack.length > 0; - }, - enumerable: false, - configurable: true - }); - OperationRecord.prototype.setMaxLen = function (v) { + get hasUndo() { + return this.undoStack.length > 0; + } + get hasRedo() { + return this.redoStack.length > 0; + } + setMaxLen(v) { this.maxLen = v; - var len = this.undoStack.length; + const len = this.undoStack.length; if (len > v) { - var removeCount = len - v; + const removeCount = len - v; this.undoStack.splice(0, removeCount); } - }; + } /** * 记录 * @param op */ - OperationRecord.prototype.record = function (op) { + record(op) { if (this.undoStack.length >= this.maxLen) { this.undoStack.shift(); } - // console.log('operation record', op) this.undoStack.push(op); this.redoStack.splice(0, this.redoStack.length); - }; + } /** * 撤销 */ - OperationRecord.prototype.undo = function () { - var op = this.undoStack.pop(); - // console.log('撤销', op); + undo() { + const op = this.undoStack.pop(); if (op) { op.undo1(); this.redoStack.push(op); } - }; + } /** * 重做 */ - OperationRecord.prototype.redo = function () { - var op = this.redoStack.pop(); - // console.log('重做', op); + redo() { + const op = this.redoStack.pop(); if (op) { op.redo1(); this.undoStack.push(op); } - }; - return OperationRecord; -}()); + } +} /** * 更新画布操作 */ -var UpdateCanvasOperation = /** @class */ (function (_super) { - __extends(UpdateCanvasOperation, _super); - function UpdateCanvasOperation(app, obj, old, data) { - var _this = _super.call(this, app, 'update-canvas') || this; - _this.description = ''; - _this.app = app; - _this.obj = obj; - _this.old = old; - _this.data = data; - return _this; +class UpdateCanvasOperation extends JlOperation { + obj; + old; + data; + description = ''; + constructor(app, obj, old, data) { + super(app, 'update-canvas'); + this.app = app; + this.obj = obj; + this.old = old; + this.data = data; } - UpdateCanvasOperation.prototype.undo = function () { + undo() { this.obj.update(this.old); return []; - }; - UpdateCanvasOperation.prototype.redo = function () { + } + redo() { this.obj.update(this.data); return []; - }; - return UpdateCanvasOperation; -}(JlOperation)); + } +} /** * 创建图形操作 */ -var GraphicCreateOperation = /** @class */ (function (_super) { - __extends(GraphicCreateOperation, _super); - function GraphicCreateOperation(app, obj) { - var _this = _super.call(this, app, 'graphic-create') || this; - _this.description = ''; - _this.app = app; - _this.obj = obj; - return _this; +class GraphicCreateOperation extends JlOperation { + obj; + description = ''; + constructor(app, obj) { + super(app, 'graphic-create'); + this.app = app; + this.obj = obj; } - GraphicCreateOperation.prototype.undo = function () { - var _a; - (_a = this.app).deleteGraphics.apply(_a, this.obj); - }; - GraphicCreateOperation.prototype.redo = function () { - var _a; - (_a = this.app).addGraphics.apply(_a, this.obj); + undo() { + this.app.deleteGraphics(...this.obj); + } + redo() { + this.app.addGraphics(...this.obj); return this.obj; - }; - return GraphicCreateOperation; -}(JlOperation)); + } +} /** * 删除图形操作 */ -var GraphicDeleteOperation = /** @class */ (function (_super) { - __extends(GraphicDeleteOperation, _super); - function GraphicDeleteOperation(app, obj) { - var _this = _super.call(this, app, 'graphic-delete') || this; - _this.app = app; - _this.obj = obj; - return _this; +class GraphicDeleteOperation extends JlOperation { + obj; + constructor(app, obj) { + super(app, 'graphic-delete'); + this.app = app; + this.obj = obj; } - GraphicDeleteOperation.prototype.undo = function () { - var _a; - (_a = this.app).addGraphics.apply(_a, this.obj); + undo() { + this.app.addGraphics(...this.obj); return this.obj; - }; - GraphicDeleteOperation.prototype.redo = function () { - var _a; - (_a = this.app).deleteGraphics.apply(_a, this.obj); - }; - return GraphicDeleteOperation; -}(JlOperation)); -var GraphicDataUpdateOperation = /** @class */ (function (_super) { - __extends(GraphicDataUpdateOperation, _super); - function GraphicDataUpdateOperation(app, obj, oldData, newData) { - var _this = _super.call(this, app, 'graphic-drag') || this; - _this.obj = __spreadArray([], obj, true); - _this.oldData = oldData; - _this.newData = newData; - return _this; } - GraphicDataUpdateOperation.prototype.undo = function () { - for (var i = 0; i < this.obj.length; i++) { - var g = this.obj[i]; + redo() { + this.app.deleteGraphics(...this.obj); + } +} +class GraphicDataUpdateOperation extends JlOperation { + obj; + oldData; + newData; + constructor(app, obj, oldData, newData) { + super(app, 'graphic-drag'); + this.obj = [...obj]; + this.oldData = oldData; + this.newData = newData; + } + undo() { + for (let i = 0; i < this.obj.length; i++) { + const g = this.obj[i]; // g.exitChildEdit(); g.updateData(this.oldData[i]); } return this.obj; - }; - GraphicDataUpdateOperation.prototype.redo = function () { - for (var i = 0; i < this.obj.length; i++) { - var g = this.obj[i]; + } + redo() { + for (let i = 0; i < this.obj.length; i++) { + const g = this.obj[i]; // g.exitChildEdit(); g.updateData(this.newData[i]); } return this.obj; - }; - return GraphicDataUpdateOperation; -}(JlOperation)); + } +} /** * 图形关系数据 */ -var GraphicRelationParam = /** @class */ (function () { - function GraphicRelationParam(g, param) { - if (param === void 0) { param = null; } +class GraphicRelationParam { + g; + param; + constructor(g, param = null) { this.g = g; this.param = param; } - GraphicRelationParam.prototype.isTheGraphic = function (g) { + isTheGraphic(g) { return this.g.id === g.id; - }; - GraphicRelationParam.prototype.getGraphic = function () { + } + getGraphic() { return this.g; - }; - GraphicRelationParam.prototype.getParam = function () { + } + getParam() { return this.param; - }; - GraphicRelationParam.prototype.equals = function (other) { + } + equals(other) { return this.isTheGraphic(other.g) && this.param === other.param; - }; - return GraphicRelationParam; -}()); + } +} /** * 图形关系 */ -var GraphicRelation = /** @class */ (function () { - function GraphicRelation(rp1, rp2) { +class GraphicRelation { + rp1; + rp2; + constructor(rp1, rp2) { this.rp1 = rp1; this.rp2 = rp2; } - GraphicRelation.prototype.contains = function (g) { + contains(g) { return this.rp1.isTheGraphic(g) || this.rp2.isTheGraphic(g); - }; + } /** * 获取给定图形的关系参数 * @param g * @returns */ - GraphicRelation.prototype.getRelationParam = function (g) { + getRelationParam(g) { if (!this.contains(g)) { - throw new Error("\u56FE\u5F62\u5173\u7CFB".concat(this.rp1.g.id, "-").concat(this.rp2.g.id, "\u4E2D\u4E0D\u5305\u542B\u7ED9\u5B9A\u56FE\u5F62").concat(g.id)); + throw new Error(`图形关系${this.rp1.g.id}-${this.rp2.g.id}中不包含给定图形${g.id}`); } if (this.rp1.isTheGraphic(g)) { return this.rp1; @@ -4006,15 +3718,15 @@ var GraphicRelation = /** @class */ (function () { else { return this.rp2; } - }; + } /** * 获取关联的另一个图形的关系参数 * @param g * @returns */ - GraphicRelation.prototype.getOtherRelationParam = function (g) { + getOtherRelationParam(g) { if (!this.contains(g)) { - throw new Error("\u56FE\u5F62\u5173\u7CFB".concat(this.rp1.g.id, "-").concat(this.rp2.g.id, "\u4E2D\u4E0D\u5305\u542B\u7ED9\u5B9A\u56FE\u5F62").concat(g.id)); + throw new Error(`图形关系${this.rp1.g.id}-${this.rp2.g.id}中不包含给定图形${g.id}`); } if (this.rp1.isTheGraphic(g)) { return this.rp2; @@ -4022,16 +3734,16 @@ var GraphicRelation = /** @class */ (function () { else { return this.rp1; } - }; + } /** * 获取关联的另一个图形对象 * @param g * @returns graphic */ - GraphicRelation.prototype.getOtherGraphic = function (g) { + getOtherGraphic(g) { return this.getOtherRelationParam(g).g; - }; - GraphicRelation.prototype.equals = function (orp1, orp2) { + } + equals(orp1, orp2) { if (this.rp1.isTheGraphic(orp1.g)) { return this.rp1.equals(orp1) && this.rp2.equals(orp2); } @@ -4039,26 +3751,21 @@ var GraphicRelation = /** @class */ (function () { return this.rp1.equals(orp2) && this.rp2.equals(orp1); } return false; - }; - GraphicRelation.prototype.isEqualOther = function (other) { + } + isEqualOther(other) { return this.equals(other.rp1, other.rp2); - }; - return GraphicRelation; -}()); + } +} /** * 图形关系管理 */ -var RelationManage = /** @class */ (function () { - function RelationManage() { - this.relations = []; - } - RelationManage.prototype.isContainsRelation = function (rp1, rp2) { - var relation = this.relations.find(function (relation) { - return relation.equals(rp1, rp2); - }); +class RelationManage { + relations = []; + isContainsRelation(rp1, rp2) { + const relation = this.relations.find((relation) => relation.equals(rp1, rp2)); return !!relation; - }; - RelationManage.prototype.addRelation = function (rp1, rp2) { + } + addRelation(rp1, rp2) { if (!(rp1 instanceof GraphicRelationParam)) { rp1 = new GraphicRelationParam(rp1); } @@ -4066,167 +3773,165 @@ var RelationManage = /** @class */ (function () { rp2 = new GraphicRelationParam(rp2); } if (!this.isContainsRelation(rp1, rp2)) { - var relation = new GraphicRelation(rp1, rp2); + const relation = new GraphicRelation(rp1, rp2); this.relations.push(relation); } - }; + } /** * 获取图形的所有关系 * @param g * @returns */ - RelationManage.prototype.getRelationsOfGraphic = function (g) { - return this.relations.filter(function (rl) { return rl.contains(g); }); - }; + getRelationsOfGraphic(g) { + return this.relations.filter((rl) => rl.contains(g)); + } /** * 获取指定图形的指定关系图形类型的所有关系 * @param g 指定图形 * @param type 关联图形的类型 * @returns */ - RelationManage.prototype.getRelationsOfGraphicAndOtherType = function (g, type) { - return this.relations.filter(function (rl) { return rl.contains(g) && rl.getOtherGraphic(g).type === type; }); - }; + getRelationsOfGraphicAndOtherType(g, type) { + return this.relations.filter((rl) => rl.contains(g) && rl.getOtherGraphic(g).type === type); + } /** * 删除关系 * @param relation */ - RelationManage.prototype.deleteRelation = function (relation) { - var index = this.relations.findIndex(function (rl) { return rl.isEqualOther(relation); }); + deleteRelation(relation) { + const index = this.relations.findIndex((rl) => rl.isEqualOther(relation)); if (index >= 0) { this.relations.splice(index, 1); } - }; + } /** * 删除指定图形的所有关系 * @param g */ - RelationManage.prototype.deleteRelationOfGraphic = function (g) { - var _this = this; - var relations = this.getRelationsOfGraphic(g); - relations.forEach(function (rl) { return _this.deleteRelation(rl); }); - }; + deleteRelationOfGraphic(g) { + const relations = this.getRelationsOfGraphic(g); + relations.forEach((rl) => this.deleteRelation(rl)); + } /** * 删除指定图形的所有关系 * @param g */ - RelationManage.prototype.deleteRelationOfGraphicAndOtherType = function (g, type) { - var _this = this; - var relations = this.getRelationsOfGraphicAndOtherType(g, type); - relations.forEach(function (rl) { return _this.deleteRelation(rl); }); - }; + deleteRelationOfGraphicAndOtherType(g, type) { + const relations = this.getRelationsOfGraphicAndOtherType(g, type); + relations.forEach((rl) => this.deleteRelation(rl)); + } /** * 清空 */ - RelationManage.prototype.clear = function () { + clear() { this.relations.splice(0, this.relations.length); - }; - return RelationManage; -}()); + } +} /** * 图形存储 */ -var GraphicStore = /** @class */ (function () { - function GraphicStore() { +class GraphicStore { + store; + relationManage; + constructor() { this.store = new Map(); this.relationManage = new RelationManage(); } /** * 获取所有图形对象 */ - GraphicStore.prototype.getAllGraphics = function () { - return __spreadArray([], this.store.values(), true); - }; - GraphicStore.prototype.queryById = function (id) { - var graphic = this.store.get(id); + getAllGraphics() { + return [...this.store.values()]; + } + queryById(id) { + const graphic = this.store.get(id); if (!graphic) - throw Error("\u672A\u627E\u5230id\u4E3A [".concat(id, "] \u7684\u56FE\u5F62.")); + throw Error(`未找到id为 [${id}] 的图形.`); return this.store.get(id); - }; - GraphicStore.prototype.queryByIdAmbiguous = function (id) { - var list = []; - this.store.forEach(function (g) { + } + queryByIdAmbiguous(id) { + const list = []; + this.store.forEach((g) => { if (g.id.search(id) >= 0) { list.push(g); } }); return list; - }; - GraphicStore.prototype.queryByType = function (type) { - var list = []; - this.store.forEach(function (g) { + } + queryByType(type) { + const list = []; + this.store.forEach((g) => { if (g.type === type) { list.push(g); } }); return list; - }; - GraphicStore.prototype.queryByCode = function (code) { - var list = []; - this.store.forEach(function (g) { + } + queryByCode(code) { + const list = []; + this.store.forEach((g) => { if (g.code === code) { list.push(g); } }); return list; - }; - GraphicStore.prototype.queryByCodeAmbiguous = function (code) { - var list = []; - this.store.forEach(function (g) { + } + queryByCodeAmbiguous(code) { + const list = []; + this.store.forEach((g) => { if (g.code.search(code) >= 0) { list.push(g); } }); return list; - }; - GraphicStore.prototype.queryByIdOrCode = function (s) { - var list = []; - this.store.forEach(function (g) { + } + queryByIdOrCode(s) { + const list = []; + this.store.forEach((g) => { if (g.isIdOrCode(s)) { list.push(g); } }); return list; - }; - GraphicStore.prototype.queryByIdOrCodeAndType = function (s, type) { - var list = []; - this.store.forEach(function (g) { + } + queryByIdOrCodeAndType(s, type) { + const list = []; + this.store.forEach((g) => { if (g.isIdOrCode(s) && g.type === type) { list.push(g); } }); return list; - }; - GraphicStore.prototype.queryByCodeAndType = function (code, type) { - for (var _i = 0, _a = this.store.values(); _i < _a.length; _i++) { - var item = _a[_i]; + } + queryByCodeAndType(code, type) { + for (const item of this.store.values()) { if (item.code === code && item.type === type) { return item; } } - }; - GraphicStore.prototype.queryByCodeAndTypeAmbiguous = function (code, type) { - var list = []; - this.store.forEach(function (g) { + } + queryByCodeAndTypeAmbiguous(code, type) { + const list = []; + this.store.forEach((g) => { if (g.type === type && g.code.search(code) >= 0) { list.push(g); } }); return list; - }; + } /** * 存储图形对象 * @param graphics 要存储的图形 */ - GraphicStore.prototype.storeGraphics = function (graphic) { + storeGraphics(graphic) { if (!graphic.id || graphic.id.trim() === '') { - throw new Error("\u5B58\u50A8\u56FE\u5F62\u5BF9\u8C61\u5F02\u5E38: id\u4E3A\u7A7A, ".concat(graphic)); + throw new Error(`存储图形对象异常: id为空, ${graphic}`); } if (this.store.has(graphic.id)) { // 已经存在 - var exist = this.store.get(graphic.id); - console.error("\u5DF2\u7ECF\u5B58\u5728id=".concat(graphic.id, "\u7684\u8BBE\u5907").concat(exist)); + const exist = this.store.get(graphic.id); + console.error(`已经存在id=${graphic.id}的设备${exist}`); return false; } else { @@ -4235,108 +3940,108 @@ var GraphicStore = /** @class */ (function () { graphic.relationManage = this.relationManage; return true; } - }; + } /** * 删除图形 * @param graph 要删除的图形 */ - GraphicStore.prototype.deleteGraphics = function (graphic) { - var id = graphic.id; - var remove = this.store.get(id); + deleteGraphics(graphic) { + const id = graphic.id; + const remove = this.store.get(id); if (remove) { this.store.delete(id); // 删除图形关系 this.relationManage.deleteRelationOfGraphic(remove); } return remove; - }; + } /** * 清空 */ - GraphicStore.prototype.clear = function () { + clear() { this.relationManage.clear(); this.store.clear(); - }; - return GraphicStore; -}()); - -var MessageClient = /** @class */ (function (_super) { - __extends(MessageClient, _super); - function MessageClient(options) { - var _this = _super.call(this) || this; - _this.subClients = []; // 订阅客户端 - _this.options = options; - return _this; } - MessageClient.prototype.unsubscribe = function (destination) { +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +class MessageClient extends EventEmitter { + options; + subClients = []; // 订阅客户端 + constructor(options) { + super(); + this.options = options; + } + unsubscribe(destination) { this.unsubscribe0(destination); - var idx = this.subClients.findIndex(function (cli) { return cli.destination === destination; }); + const idx = this.subClients.findIndex((cli) => cli.destination === destination); if (idx >= 0) { this.subClients.splice(idx, 1); } - }; - MessageClient.prototype.getOrNewSubClient = function (destination) { - var cli = this.subClients.find(function (cli) { return cli.destination === destination; }); + } + getOrNewSubClient(destination) { + let cli = this.subClients.find((cli) => cli.destination === destination); if (!cli) { // 不存在,新建 cli = new SubscriptionClient(this, destination, this.options.protocol); this.subClients.push(cli); } return cli; - }; - MessageClient.prototype.addSubscription = function (destination, handler) { - var cli = this.getOrNewSubClient(destination); + } + addSubscription(destination, handler) { + const cli = this.getOrNewSubClient(destination); cli.addHandler(handler); - }; - MessageClient.prototype.removeSubscription = function (destination, handle) { + } + removeSubscription(destination, handle) { this.getOrNewSubClient(destination).removeHandler(handle); - }; - return MessageClient; -}(EventEmitter)); -var SubscriptionClient = /** @class */ (function () { - function SubscriptionClient(mc, destination, protocal) { - this.handlers = []; - this.subscripted = false; + } +} +class SubscriptionClient { + mc; + destination; + protocol; + handlers = []; + subscripted = false; + constructor(mc, destination, protocal) { this.mc = mc; this.destination = destination; this.protocol = protocal; this.mc.on('disconnected', this.onDisconnect, this); this.mc.on('connected', this.trySubscribe, this); } - SubscriptionClient.prototype.addHandler = function (handler) { - if (this.handlers.filter(function (h) { return h.App === handler.App; }).length == 0) { + addHandler(handler) { + if (this.handlers.filter((h) => h.App === handler.App).length == 0) { this.handlers.push(handler); } if (!this.subscripted) { this.trySubscribe(); } - }; - SubscriptionClient.prototype.removeHandler = function (handler) { - var idx = this.handlers.findIndex(function (h) { return h.App === handler.App; }); + } + removeHandler(handler) { + const idx = this.handlers.findIndex((h) => h.App === handler.App); if (idx >= 0) { this.handlers.splice(idx, 1); } if (this.handlers.length == 0) { - console.log("\u8BA2\u9605".concat(this.destination, "\u6CA1\u6709\u6D88\u606F\u76D1\u542C\u5904\u7406,\u79FB\u9664\u8BA2\u9605")); + console.log(`订阅${this.destination}没有消息监听处理,移除订阅`); this.unsubscribe(); } - }; - SubscriptionClient.prototype.trySubscribe = function () { - var _this = this; + } + trySubscribe() { if (this.mc.connected) { - this.subscripted = this.mc.subscribe(this.destination, function (data) { - _this.handleMessage(data); + this.subscripted = this.mc.subscribe(this.destination, (data) => { + this.handleMessage(data); }); } - }; - SubscriptionClient.prototype.unsubscribe = function () { + } + unsubscribe() { this.mc.unsubscribe(this.destination); - }; - SubscriptionClient.prototype.handleMessage = function (data) { + } + handleMessage(data) { if (this.protocol === 'json') { console.debug('收到消息:', data); } - this.handlers.forEach(function (handler) { + this.handlers.forEach((handler) => { try { handler.handle(data); } @@ -4344,22 +4049,21 @@ var SubscriptionClient = /** @class */ (function () { console.error('图形应用状态消息处理异常', error); } }); - }; - SubscriptionClient.prototype.onDisconnect = function () { + } + onDisconnect() { this.subscripted = false; - }; - return SubscriptionClient; -}()); + } +} -var ReconnectDelay = 3000; -var HeartbeatIncoming = 30000; -var HeartbeatOutgoing = 30000; -var StompMessagingClient = /** @class */ (function (_super) { - __extends(StompMessagingClient, _super); - function StompMessagingClient(options) { - var _this = _super.call(this, options) || this; - _this.options = options; - _this.cli = new stompjs.Client({ +const ReconnectDelay = 3000; +const HeartbeatIncoming = 30000; +const HeartbeatOutgoing = 30000; +class StompMessagingClient extends MessageClient { + cli; + constructor(options) { + super(options); + this.options = options; + this.cli = new Client({ brokerURL: options.wsUrl, connectHeaders: { Authorization: options.token ? options.token : '', @@ -4368,45 +4072,39 @@ var StompMessagingClient = /** @class */ (function (_super) { heartbeatIncoming: HeartbeatIncoming, heartbeatOutgoing: HeartbeatOutgoing, }); - _this.cli.onConnect = function () { + this.cli.onConnect = () => { // this.subClients.forEach((cli) => { // this.subscribe(cli.destination, cli.handleMessage); // }); - _this.emit('connected', ''); + this.emit('connected', ''); }; - _this.cli.onStompError = function (frame) { - var errMsg = frame.headers['message']; + this.cli.onStompError = (frame) => { + const errMsg = frame.headers['message']; if (errMsg === '401') { console.warn('认证失败,断开WebSocket连接'); - _this.cli.deactivate(); + this.cli.deactivate(); } else { console.error('收到Stomp错误消息', frame); } }; - _this.cli.onDisconnect = function (frame) { + this.cli.onDisconnect = (frame) => { console.log('Stomp 断开连接', frame); - _this.emit('disconnected', frame); + this.emit('disconnected', frame); }; // websocket错误处理 - _this.cli.onWebSocketError = function (err) { + this.cli.onWebSocketError = (err) => { console.error('websocket错误', err); }; - _this.cli.activate(); - return _this; + this.cli.activate(); } - Object.defineProperty(StompMessagingClient.prototype, "connected", { - get: function () { - return this.cli.connected; - }, - enumerable: false, - configurable: true - }); - StompMessagingClient.prototype.subscribe = function (destination, handle) { - var _this = this; - this.cli.subscribe(destination, function (frame) { - if (_this.options.protocol === 'json') { - var data = JSON.parse(frame.body); + get connected() { + return this.cli.connected; + } + subscribe(destination, handle) { + this.cli.subscribe(destination, (frame) => { + if (this.options.protocol === 'json') { + const data = JSON.parse(frame.body); handle(data); } else { @@ -4416,25 +4114,24 @@ var StompMessagingClient = /** @class */ (function (_super) { id: destination, }); return true; - }; - StompMessagingClient.prototype.unsubscribe0 = function (destination) { + } + unsubscribe0(destination) { this.cli.unsubscribe(destination); - }; - StompMessagingClient.prototype.close = function () { + } + close() { this.cli.deactivate(); - }; - return StompMessagingClient; -}(MessageClient)); + } +} -var MqttMsgClient = /** @class */ (function (_super) { - __extends(MqttMsgClient, _super); - function MqttMsgClient(options) { - var _this = _super.call(this, options) || this; - _this.retryTimes = 0; - _this.subMsgHandler = new Map(); - _this.options = options; +class MqttMsgClient extends MessageClient { + cli; + retryTimes = 0; + subMsgHandler = new Map(); + constructor(options) { + super(options); + this.options = options; try { - _this.cli = mqtt.connect(options.wsUrl, { + this.cli = mqtt.connect(options.wsUrl, { protocolVersion: 5, clean: true, resubscribe: false, @@ -4444,25 +4141,25 @@ var MqttMsgClient = /** @class */ (function (_super) { username: options.clientName || '', password: options.token, }); - _this.cli.on('connect', function (packet) { + this.cli.on('connect', (packet) => { console.log('MQTT 连接成功!'); - _this.retryTimes = 0; // 连接成功,重置 - _this.emit('connected', packet); + this.retryTimes = 0; // 连接成功,重置 + this.emit('connected', packet); }); - _this.cli.on('disconnect', function (packet) { + this.cli.on('disconnect', (packet) => { console.log('MQTT 连接断开!'); - _this.emit('disconnected', packet); + this.emit('disconnected', packet); }); - _this.cli.on('close', function () { + this.cli.on('close', () => { console.log('MQTT 关闭!'); - _this.emit('disconnected', 'close'); + this.emit('disconnected', 'close'); }); - _this.cli.on('reconnect', function () { - _this.retryTimes += 1; - console.log("MQTT\u7B2C ".concat(_this.retryTimes, " \u6B21\u5C1D\u8BD5\u91CD\u8FDE")); - if (_this.retryTimes > options.retryTimes) { + this.cli.on('reconnect', () => { + this.retryTimes += 1; + console.log(`MQTT第 ${this.retryTimes} 次尝试重连`); + if (this.retryTimes > options.retryTimes) { try { - _this.cli.end(); + this.cli.end(); console.error('MQTT 达到重连最大尝试次数,停止重试'); } catch (error) { @@ -4470,16 +4167,16 @@ var MqttMsgClient = /** @class */ (function (_super) { } } }); - _this.cli.on('error', function (error) { + this.cli.on('error', (error) => { console.log('MQTT 出现错误', error); console.warn(error); - _this.emit('error', error); + this.emit('error', error); }); - _this.cli.on('message', function (topic, message) { - var handle = _this.subMsgHandler.get(topic); + this.cli.on('message', (topic, message) => { + const handle = this.subMsgHandler.get(topic); if (handle) { - if (_this.options.protocol === 'json') { - var data = JSON.parse(message.toString()); + if (this.options.protocol === 'json') { + const data = JSON.parse(message.toString()); handle(data); } else { @@ -4491,14 +4188,13 @@ var MqttMsgClient = /** @class */ (function (_super) { } catch (err) { console.error('MQTT connect error', err); - _this.emit('error', err); + this.emit('error', err); throw err; } - return _this; } - MqttMsgClient.prototype.subscribe = function (destination, handle) { + subscribe(destination, handle) { console.debug('MQTT订阅执行', destination); - this.cli.subscribe(destination, { qos: 0 }, function (error, res) { + this.cli.subscribe(destination, { qos: 0 }, (error, res) => { if (error) { console.warn('MQTT 订阅失败', error); return; @@ -4508,51 +4204,44 @@ var MqttMsgClient = /** @class */ (function (_super) { }); this.subMsgHandler.set(destination, handle); return true; - }; - MqttMsgClient.prototype.unsubscribe0 = function (destination) { - var _this = this; + } + unsubscribe0(destination) { console.debug('MQTT取消订阅执行', destination); - this.cli.unsubscribe(destination, function (error, packet) { + this.cli.unsubscribe(destination, (error, packet) => { if (error) { console.warn('MQTT 取消订阅失败', error); } else { console.debug('MQTT 取消订阅成功', packet); - _this.subMsgHandler.delete(destination); + this.subMsgHandler.delete(destination); } }); - }; - Object.defineProperty(MqttMsgClient.prototype, "connected", { - get: function () { - return this.cli.connected; - }, - enumerable: false, - configurable: true - }); - MqttMsgClient.prototype.close = function () { - var _this = this; + } + get connected() { + return this.cli.connected; + } + close() { try { console.debug('MQTT关闭执行'); - this.cli.end(true, function () { + this.cli.end(true, () => { console.debug('MQTT 消息客户端关闭成功'); - _this.subMsgHandler.clear(); + this.subMsgHandler.clear(); }); } catch (error) { console.warn('MQTT 消息客户端关闭失败', error); } - }; - return MqttMsgClient; -}(MessageClient)); + } +} -exports.ClientEngine = void 0; +var ClientEngine; (function (ClientEngine) { ClientEngine[ClientEngine["Stomp"] = 0] = "Stomp"; // Centrifugo, ClientEngine[ClientEngine["MQTT"] = 1] = "MQTT"; -})(exports.ClientEngine || (exports.ClientEngine = {})); -var DefaultStompOption = { - engine: exports.ClientEngine.Stomp, +})(ClientEngine || (ClientEngine = {})); +const DefaultStompOption = { + engine: ClientEngine.Stomp, protocol: 'protobuf', wsUrl: '', token: '', @@ -4561,10 +4250,11 @@ var DefaultStompOption = { retryPeriod: 2 * 1000, retryTimes: 100, }; -var WsMsgCli = /** @class */ (function () { - function WsMsgCli() { - } - WsMsgCli.new = function (options) { +class WsMsgCli { + static client; + static options; + static appMsgBroker = []; + static new(options) { if (WsMsgCli.client) { // 已经创建 return; @@ -4575,11 +4265,11 @@ var WsMsgCli = /** @class */ (function () { // WsMsgCli.client = new CentrifugeMessagingClient(WsMsgCli.options); // break; // } - case exports.ClientEngine.MQTT: { + case ClientEngine.MQTT: { WsMsgCli.client = new MqttMsgClient(WsMsgCli.options); break; } - case exports.ClientEngine.Stomp: { + case ClientEngine.Stomp: { WsMsgCli.client = new StompMessagingClient(WsMsgCli.options); break; } @@ -4587,218 +4277,170 @@ var WsMsgCli = /** @class */ (function () { throw new Error('未知的消息客户端引擎类型', WsMsgCli.options.engine); } } - var cli = WsMsgCli.client; - cli.on('connected', function () { + const cli = WsMsgCli.client; + cli.on('connected', () => { WsMsgCli.emitConnectStateChangeEvent(true); }); - cli.on('disconnected', function () { + cli.on('disconnected', () => { WsMsgCli.emitConnectStateChangeEvent(false); }); - cli.on('error', function (err) { + cli.on('error', (err) => { console.warn('websocket 客户端错误消息发布', err); - WsMsgCli.appMsgBroker.forEach(function (broker) { + WsMsgCli.appMsgBroker.forEach((broker) => { broker.app.emit('websocket-error', err); }); }); - }; - WsMsgCli.isInitiated = function () { + } + static isInitiated() { return !!WsMsgCli.client; - }; - WsMsgCli.emitConnectStateChangeEvent = function (connected) { - WsMsgCli.appMsgBroker.forEach(function (broker) { + } + static emitConnectStateChangeEvent(connected) { + WsMsgCli.appMsgBroker.forEach((broker) => { broker.app.emit('websocket-connect-state-change', connected); }); - }; - WsMsgCli.isConnected = function () { + } + static isConnected() { return WsMsgCli.client && WsMsgCli.client.connected; - }; - WsMsgCli.registerSubscription = function (destination, handler) { + } + static registerSubscription(destination, handler) { WsMsgCli.client.addSubscription(destination, handler); - }; - WsMsgCli.unregisterSubscription = function (destination, handler) { + } + static unregisterSubscription(destination, handler) { WsMsgCli.client.removeSubscription(destination, handler); - }; - WsMsgCli.registerAppMsgBroker = function (broker) { + } + static registerAppMsgBroker(broker) { WsMsgCli.appMsgBroker.push(broker); - }; - WsMsgCli.removeAppMsgBroker = function (broker) { - var index = WsMsgCli.appMsgBroker.findIndex(function (mb) { return mb == broker; }); + } + static removeAppMsgBroker(broker) { + const index = WsMsgCli.appMsgBroker.findIndex((mb) => mb == broker); if (index >= 0) { WsMsgCli.appMsgBroker.splice(index, 1); } - }; - WsMsgCli.hasAppMsgBroker = function () { + } + static hasAppMsgBroker() { return WsMsgCli.appMsgBroker.length > 0; - }; + } /** * 关闭websocket连接 */ - WsMsgCli.close = function () { + static close() { if (WsMsgCli.client) { WsMsgCli.client.close(); } - }; - WsMsgCli.appMsgBroker = []; - return WsMsgCli; -}()); -var AppMessageHandler = /** @class */ (function () { - function AppMessageHandler(app, subOptions) { + } +} +class AppMessageHandler { + app; + sub; + constructor(app, subOptions) { this.app = app; if (!subOptions.messageConverter && !subOptions.messageHandle) { - throw new Error("\u6CA1\u6709\u6D88\u606F\u5904\u7406\u5668\u6216\u56FE\u5F62\u72B6\u6001\u6D88\u606F\u8F6C\u6362\u5668: ".concat(subOptions)); + throw new Error(`没有消息处理器或图形状态消息转换器: ${subOptions}`); } this.sub = subOptions; } - Object.defineProperty(AppMessageHandler.prototype, "App", { - get: function () { - return this.app; - }, - enumerable: false, - configurable: true - }); - AppMessageHandler.prototype.handle = function (data) { - var sub = this.sub; + get App() { + return this.app; + } + handle(data) { + const sub = this.sub; if (sub.messageConverter) { - var graphicStates = sub.messageConverter(data); + const graphicStates = sub.messageConverter(data); this.app.handleGraphicStates(graphicStates, sub.graphicQueryer, sub.createOnNotFound); } else if (sub.messageHandle) { sub.messageHandle(data); } - }; - return AppMessageHandler; -}()); + } +} /** * 图形APP的websocket消息代理 */ -var AppWsMsgBroker = /** @class */ (function () { - function AppWsMsgBroker(app) { - this.subscriptions = new Map(); +class AppWsMsgBroker { + app; + subscriptions = new Map(); + constructor(app) { this.app = app; WsMsgCli.registerAppMsgBroker(this); } - AppWsMsgBroker.prototype.subscribe = function (sub) { - var handler = new AppMessageHandler(this.app, sub); + subscribe(sub) { + const handler = new AppMessageHandler(this.app, sub); WsMsgCli.registerSubscription(sub.destination, handler); this.subscriptions.set(sub.destination, handler); - }; - AppWsMsgBroker.prototype.unsbuscribe = function (destination) { - var oldSub = this.subscriptions.get(destination); + } + unsbuscribe(destination) { + const oldSub = this.subscriptions.get(destination); if (oldSub) { WsMsgCli.unregisterSubscription(destination, oldSub); } - }; - AppWsMsgBroker.prototype.unsubscribeAll = function () { - var _this = this; - this.subscriptions.forEach(function (record, destination) { - _this.unsbuscribe(destination); + } + unsubscribeAll() { + this.subscriptions.forEach((record, destination) => { + this.unsbuscribe(destination); }); - }; - AppWsMsgBroker.prototype.resubscribeAll = function () { - this.subscriptions.forEach(function (handler, destination) { + } + resubscribeAll() { + this.subscriptions.forEach((handler, destination) => { WsMsgCli.registerSubscription(destination, handler); }); - }; + } /** * 取消所有订阅,从通用Stomp客户端移除此消息代理 */ - AppWsMsgBroker.prototype.close = function () { + close() { WsMsgCli.removeAppMsgBroker(this); this.unsubscribeAll(); - }; - return AppWsMsgBroker; -}()); + } +} -/** - * 默认的白色样式 - */ -var DefaultWhiteStyleOptions = { - titleStyle: { - fontSize: 16, - fontColor: '#000000', - padding: [5, 15], - }, - backgroundColor: '#ffffff', - border: true, - borderWidth: 1, - borderColor: '#4C4C4C', - /** - * 默认圆角 - */ - borderRoundRadius: 5, - itemStyle: { - fontSize: 16, - fontColor: '#000000', - padding: [5, 25], - hoverColor: '#1E78DB', - disabledFontColor: '#9D9D9D', - }, -}; -/** - * 默认的白色菜单配置 - */ -var DefaultWhiteMenuOptions = { - name: '', - style: DefaultWhiteStyleOptions, - groups: [], -}; - -var ContextMenuPlugin = /** @class */ (function () { - function ContextMenuPlugin(app) { - var _this = this; - this.contextMenuMap = new Map(); +class ContextMenuPlugin { + app; + contextMenuMap = new Map(); + constructor(app) { this.app = app; - var canvas = this.app.canvas; - canvas.on('pointerdown', function () { - _this.contextMenuMap.forEach(function (menu) { + const canvas = this.app.canvas; + canvas.on('pointerdown', () => { + this.contextMenuMap.forEach((menu) => { menu.close(); }); }); } - ContextMenuPlugin.prototype.registerMenu = function (menu) { + registerMenu(menu) { this.contextMenuMap.set(menu.menuName, menu); menu.plugin = this; - }; - Object.defineProperty(ContextMenuPlugin.prototype, "screenWidth", { - /** - * 获取视口屏幕宽度 - */ - get: function () { - return this.app.viewport.screenWidth; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuPlugin.prototype, "screenHeight", { - /** - * 获取视口屏幕高度 - */ - get: function () { - return this.app.viewport.screenHeight; - }, - enumerable: false, - configurable: true - }); + } + /** + * 获取视口屏幕宽度 + */ + get screenWidth() { + return this.app.viewport.screenWidth; + } + /** + * 获取视口屏幕高度 + */ + get screenHeight() { + return this.app.viewport.screenHeight; + } /** * 打开菜单 * @param menu * @param global */ - ContextMenuPlugin.prototype.open = function (menu, global) { + open(menu, global) { if (!menu.opened) { menu.opened = true; this.app.pixi.stage.addChild(menu); } // 处理超出显示范围 - var screenHeight = this.screenHeight; - var bottomY = global.y + menu.height; - var oob = this.oob(menu, global); - var pos = global.clone(); + const screenHeight = this.screenHeight; + const bottomY = global.y + menu.height; + let oob = this.oob(menu, global); + const pos = global.clone(); if (oob.right) { pos.x = global.x - menu.width; } if (oob.bottom) { - var py = global.y - menu.height; + const py = global.y - menu.height; if (py > 0) { pos.y = py; } @@ -4815,768 +4457,71 @@ var ContextMenuPlugin = /** @class */ (function () { pos.y = 0; } menu.position.copyFrom(pos); - }; + } /** * 关闭菜单 * @param menu */ - ContextMenuPlugin.prototype.close = function (menu) { + close(menu) { if (menu.opened) { menu.opened = false; this.app.pixi.stage.removeChild(menu); } - }; + } /** * 关闭所有菜单 */ - ContextMenuPlugin.prototype.closeAll = function () { - var _this = this; - this.contextMenuMap.forEach(function (cm) { - _this.close(cm); + closeAll() { + this.contextMenuMap.forEach((cm) => { + this.close(cm); }); - }; + } /** * 越界检查 * @param menu * @param global * @returns */ - ContextMenuPlugin.prototype.oob = function (menu, global) { - var screenWidth = this.screenWidth; - var screenHeight = this.screenHeight; - var bound = new pixi_js.Rectangle(0, 0, screenWidth, screenHeight); - var menuRect = new pixi_js.Rectangle(global.x, global.y, menu.width, menu.height); + oob(menu, global) { + const screenWidth = this.screenWidth; + const screenHeight = this.screenHeight; + const bound = new Rectangle(0, 0, screenWidth, screenHeight); + const menuRect = new Rectangle(global.x, global.y, menu.width, menu.height); return OutOfBound.check(menuRect, bound); - }; - return ContextMenuPlugin; -}()); -/** - * 上下文菜单,多级嵌套 - */ -var ContextMenu = /** @class */ (function (_super) { - __extends(ContextMenu, _super); - function ContextMenu(menuOptions, parentMenuItem) { - var _this = _super.call(this) || this; - _this.opened = false; - _this.padding = 5; - _this._active = false; // 激活状态 - _this.menuOptions = Object.assign({}, DefaultWhiteMenuOptions, menuOptions); - _this.name = _this.menuOptions.name; - _this.bg = new pixi_js.Graphics(); - _this.addChild(_this.bg); - _this.groups = []; - _this.init(); - _this.parentMenuItem = parentMenuItem; - return _this; } - ContextMenu.init = function (options) { - return new ContextMenu(options); - }; - Object.defineProperty(ContextMenu.prototype, "style", { - get: function () { - return this.menuOptions.style; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenu.prototype, "parentMenu", { - /** - * 父级菜单 - */ - get: function () { - var _a; - return (_a = this.parentMenuItem) === null || _a === void 0 ? void 0 : _a.menu; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenu.prototype, "rootMenu", { - /** - * 最顶级菜单 - */ - get: function () { - if (this.parentMenu) { - return this.parentMenu.rootMenu; - } - return this; - }, - enumerable: false, - configurable: true - }); - /** - * 是否存在激活的菜单项 - * @returns - */ - ContextMenu.prototype.hasActiveItem = function () { - for (var i = 0; i < this.groups.length; i++) { - var group = this.groups[i]; - if (group.hasActiveItem()) { - return true; - } - } - return false; - }; - Object.defineProperty(ContextMenu.prototype, "active", { - get: function () { - return (this._active || - this.hasActiveItem() || - (this.parentMenuItem != undefined && this.parentMenuItem._active)); - }, - set: function (v) { - this._active = v; - this.onActiveChanged(); - }, - enumerable: false, - configurable: true - }); - ContextMenu.prototype.onActiveChanged = function () { - var _this = this; - if (this.parentMenuItem) { - this.parentMenuItem.onActiveChanged(); - if (!this.active) { - this.timeoutCloseHandle = setTimeout(function () { - _this.close(); - }, 500); - } - else { - if (this.timeoutCloseHandle) { - clearTimeout(this.timeoutCloseHandle); - } - } - } - }; - ContextMenu.prototype.setOptions = function (menuOptions) { - this.menuOptions = Object.assign({}, DefaultWhiteMenuOptions, menuOptions); - this.init(); - }; - /** - * 初始化 - */ - ContextMenu.prototype.init = function () { - var _this = this; - // this.initTitle(); - this.groups = []; - var options = this.menuOptions; - options.groups.forEach(function (group) { - var menuGroup = new MenuGroup(_this, group); - _this.groups.push(menuGroup); - }); - var _a = this.calculateBorderInfo(), borderHeight = _a.borderHeight, maxItemWidth = _a.maxItemWidth; - var splitLineWidth = 1; - var bgWidth = maxItemWidth + this.padding * 2; - var bgHeight = borderHeight + - this.groups.length * this.padding * 2 + - (this.groups.length - 1) * splitLineWidth; - if (options.style.border) { - this.bg.lineStyle(options.style.borderWidth, new pixi_js.Color(options.style.borderColor)); - } - this.bg.beginFill(new pixi_js.Color(options.style.backgroundColor)); - if (options.style.borderRoundRadius > 0) { - this.bg.drawRoundedRect(0, 0, bgWidth, bgHeight, options.style.borderRoundRadius); - } - else { - this.bg.drawRect(0, 0, bgWidth, bgHeight); - } - this.bg.endFill(); - var groupHeight = 0; - this.bg.lineStyle(splitLineWidth, new pixi_js.Color(options.style.borderColor)); - for (var i = 0; i < this.groups.length; i++) { - var group = this.groups[i]; - group.updateItemBox(maxItemWidth); - group.position.set(this.padding, groupHeight + this.padding); - if (i === this.groups.length - 1) { - // 最后一个 - break; - } - var splitLineY = groupHeight + group.height + this.padding * 2; - this.bg.moveTo(0, splitLineY); - this.bg.lineTo(bgWidth, splitLineY); - groupHeight = splitLineY + splitLineWidth; - } - this.addChild.apply(this, this.groups); - this.eventMode = 'static'; - this.on('pointerover', function () { - _this.active = true; - }); - this.on('pointerout', function () { - _this.active = false; - }); - }; - ContextMenu.prototype.initGroups = function () { - var _this = this; - this.groups = []; - var options = this.menuOptions; - options.groups.forEach(function (group) { - var menuGroup = new MenuGroup(_this, group); - _this.groups.push(menuGroup); - }); - this.addChild.apply(this, this.groups); - }; - ContextMenu.prototype.initTitle = function () { - if (this.menuOptions.title) { - this.title = new pixi_js.Text(this.menuOptions.title, { align: 'left' }); - } - }; - ContextMenu.prototype.calculateBorderInfo = function () { - var maxItemNameWidth = 0; - var maxShortcutWidth = 0; - var maxGutter = 0; - var borderHeight = 0; - this.groups.forEach(function (menuGroup) { - borderHeight += menuGroup.totalHeight; - var maxInw = menuGroup.maxItemNameWidth; - if (maxInw > maxItemNameWidth) { - maxItemNameWidth = maxInw; - } - var maxSw = menuGroup.maxShortcutWidth; - if (maxSw > maxShortcutWidth) { - maxShortcutWidth = maxSw; - } - var gutter = menuGroup.totalGutter; - if (gutter > maxGutter) { - maxGutter = gutter; - } - }); - var maxItemWidth = maxItemNameWidth + maxShortcutWidth + maxGutter; - return { borderHeight: borderHeight, maxItemWidth: maxItemWidth }; - }; - ContextMenu.prototype.updateBg = function () { - this.bg.clear(); - var options = this.menuOptions; - var _a = this.calculateBorderInfo(), borderHeight = _a.borderHeight, maxItemWidth = _a.maxItemWidth; - var splitLineWidth = 1; - var bgWidth = maxItemWidth + this.padding * 2; - var bgHeight = borderHeight + - this.groups.length * this.padding * 2 + - (this.groups.length - 1) * splitLineWidth; - if (options.style.border) { - this.bg.lineStyle(options.style.borderWidth, new pixi_js.Color(options.style.borderColor)); - } - this.bg.beginFill(new pixi_js.Color(options.style.backgroundColor)); - if (options.style.borderRoundRadius > 0) { - this.bg.drawRoundedRect(0, 0, bgWidth, bgHeight, options.style.borderRoundRadius); - } - else { - this.bg.drawRect(0, 0, bgWidth, bgHeight); - } - this.bg.endFill(); - var groupHeight = 0; - this.bg.lineStyle(splitLineWidth, new pixi_js.Color(options.style.borderColor)); - for (var i = 0; i < this.groups.length; i++) { - var group = this.groups[i]; - group.updateItemBox(maxItemWidth); - group.position.set(this.padding, groupHeight + this.padding); - if (i === this.groups.length - 1) { - // 最后一个 - break; - } - var splitLineY = groupHeight + group.height + this.padding * 2; - this.bg.moveTo(0, splitLineY); - this.bg.lineTo(bgWidth, splitLineY); - groupHeight = splitLineY + splitLineWidth; - } - }; - ContextMenu.prototype.update = function () { - if (this.menuOptions.groups.length !== this.groups.length) { - this.init(); - } - else { - this.groups.forEach(function (group) { return group.update(); }); - this.updateBg(); - } - }; - Object.defineProperty(ContextMenu.prototype, "menuName", { - get: function () { - return this.menuOptions.name; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenu.prototype, "plugin", { - get: function () { - if (this.parentMenu) { - return this.parentMenu.plugin; - } - if (this._plugin) { - return this._plugin; - } - throw new Error("\u4E0A\u4E0B\u6587\u83DC\u5355name=".concat(this.menuOptions.name, "\u6CA1\u6709\u6DFB\u52A0\u5230\u63D2\u4EF6\u4E2D")); - }, - set: function (v) { - this._plugin = v; - }, - enumerable: false, - configurable: true - }); - /** - * 显示菜单 - */ - ContextMenu.prototype.open = function (global) { - if (this.parentMenu) { - this.parentMenu.openSub(this, global); - } - else { - this.update(); - this.plugin.open(this, global); - } - }; - /** - * 关闭菜单 - */ - ContextMenu.prototype.close = function () { - if (this.openedSubMenu) { - this.openedSubMenu.close(); - this.openedSubMenu = undefined; - } - this.plugin.close(this); - }; - /** - * 打开子菜单 - * @param subMenu - * @param global - */ - ContextMenu.prototype.openSub = function (subMenu, global) { - if (this.openedSubMenu) { - this.openedSubMenu.close(); - } - var pos = global.clone(); - var oob = this.plugin.oob(subMenu, global); - if (oob.right) { - pos.x = this.position.x - subMenu.width + this.padding; - } - if (oob.bottom) { - pos.y = this.plugin.screenHeight - subMenu.height - this.padding; - } - this.plugin.open(subMenu, pos); - this.openedSubMenu = subMenu; - }; - return ContextMenu; -}(pixi_js.Container)); -var MenuGroup = /** @class */ (function (_super) { - __extends(MenuGroup, _super); - function MenuGroup(menu, config) { - var _this = _super.call(this) || this; - _this.gutter = 3; // 名称、快捷键、箭头文本间隙 - _this.items = []; - _this.config = config; - _this.menu = menu; - _this.init(); - return _this; - } - MenuGroup.prototype.init = function () { - var _this = this; - this.items = []; // 清空 - this.config.items.forEach(function (item) { - _this.items.push(new ContextMenuItem(_this.menu, item)); - }); - if (this.items.length === 0) { - console.error('菜单group为空', this.config, this.menu); - throw new Error("{name=".concat(this.menu.name, "}\u7684\u83DC\u5355\u7684group\u4E3A{name=").concat(this.config.name, "}\u7684\u6761\u76EE\u4E3A\u7A7A!")); - } - this.addChild.apply(this, this.items); - }; - MenuGroup.prototype.hasActiveItem = function () { - for (var i = 0; i < this.items.length; i++) { - var item = this.items[i]; - if (item.active) { - return true; - } - } - return false; - }; - Object.defineProperty(MenuGroup.prototype, "maxItemNameWidth", { - get: function () { - var maxNameWidth = this.items - .map(function (item) { return item.nameBounds.width; }) - .sort(function (a, b) { return a - b; }) - .reverse()[0]; - return maxNameWidth; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MenuGroup.prototype, "maxShortcutWidth", { - get: function () { - var maxShortcutWidth = this.items - .map(function (item) { return item.shortcutKeyBounds.width; }) - .sort(function (a, b) { return a - b; }) - .reverse()[0]; - return maxShortcutWidth; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MenuGroup.prototype, "totalGutter", { - get: function () { - return this.gutter + this.items[0].paddingLeft + this.items[0].paddingRight; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MenuGroup.prototype, "totalHeight", { - get: function () { - var total = 0; - this.items.forEach(function (item) { return (total += item.totalHeight); }); - return total; - }, - enumerable: false, - configurable: true - }); - MenuGroup.prototype.update = function () { - if (this.items.length !== this.config.items.length) { - this.init(); - } - else { - var i_1 = 0; - this.items.forEach(function (item) { - item.update(); - if (item.visible) { - item.position.y = i_1 * item.totalHeight; - i_1++; - } - }); - } - }; - MenuGroup.prototype.updateItemBox = function (maxItemWidth) { - this.items.forEach(function (item) { - return item.updateBox(maxItemWidth, item.totalHeight); - }); - }; - return MenuGroup; -}(pixi_js.Container)); -/** - * 菜单项 - */ -var ContextMenuItem = /** @class */ (function (_super) { - __extends(ContextMenuItem, _super); - function ContextMenuItem(menu, config) { - var _this = _super.call(this) || this; - _this.gutter = 3; // 名称、快捷键、箭头文本间隙 - _this._active = false; // 激活状态 - _this.menu = menu; - _this.config = config; - _this.box = new pixi_js.Graphics(); - _this.addChild(_this.box); - _this.nameText = new pixi_js.Text(_this.config.name, { - fontSize: _this.fontSize, - fill: _this.fontColor, - }); - _this.addChild(_this.nameText); - _this.initShortcutKeyText(); - _this.initSubMenu(); - return _this; - } - ContextMenuItem.prototype.registerEventHandler = function () { - var _this = this; - this.eventMode = 'static'; - this.cursor = 'pointer'; - this.on('pointerover', function () { - _this.active = true; - if (_this.config.disabled) { - _this.cursor = 'not-allowed'; - } - else { - _this.cursor = 'pointer'; - } - if (_this.subMenu) { - var p = _this.toGlobal(new pixi_js.Point(_this.width)); - _this.subMenu.open(p); - } - }); - this.on('pointerout', function () { - _this.active = false; - }); - this.on('pointertap', function () { - if (_this.config.disabled) { - // 禁用,不处理 - return; - } - if (_this.config.handler) { - _this.menu.plugin.app.emit('pre-menu-handle', _this.config); - _this.config.handler(); - _this.menu.plugin.app.emit('post-menu-handle', _this.config); - } - if (!_this.config.subMenu || _this.config.subMenu.groups.length === 0) { - _this.active = false; - _this.menu.active = false; - _this.menu.rootMenu.close(); - } - }); - }; - Object.defineProperty(ContextMenuItem.prototype, "active", { - get: function () { - return this._active || (this.subMenu != undefined && this.subMenu.active); - }, - set: function (v) { - this._active = v; - if (this.subMenu) { - this.subMenu.onActiveChanged(); - } - this.onActiveChanged(); - }, - enumerable: false, - configurable: true - }); - ContextMenuItem.prototype.onActiveChanged = function () { - if (this.active) { - this.box.alpha = 1; - } - else { - this.box.alpha = 0; - } - }; - Object.defineProperty(ContextMenuItem.prototype, "textWidth", { - get: function () { - return this.nameBounds.width + this.shortcutKeyBounds.width + this.gutter; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "nameGraphic", { - get: function () { - if (this.nameText) { - return this.nameText; - } - throw new Error("\u83DC\u5355\u9879name=".concat(this.config.name, "\u6CA1\u6709\u521D\u59CB\u5316\u540D\u79F0\u56FE\u5F62\u5BF9\u8C61")); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "totalHeight", { - get: function () { - if (this.config.visible === false) { - return 0; - } - else { - return this.paddingTop + this.paddingBottom + this.nameGraphic.height; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "nameBounds", { - get: function () { - return this.nameGraphic.getLocalBounds(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "shortcutKeyBounds", { - get: function () { - if (this.shortcutKeyText) { - return this.shortcutKeyText.getLocalBounds(); - } - else { - return new pixi_js.Rectangle(0, 0, 0, 0); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "style", { - get: function () { - return this.menu.style.itemStyle; - }, - enumerable: false, - configurable: true - }); - ContextMenuItem.prototype.checkPadding = function (padding) { - if (Array.isArray(padding)) { - if (padding.length !== 2 && padding.length !== 4) { - throw new Error('错误的padding数据'); - } - } - }; - ContextMenuItem.prototype.toWholePadding = function (padding) { - this.checkPadding(padding); - if (Array.isArray(padding)) { - if (padding.length == 2) { - return [padding[0], padding[1], padding[0], padding[1]]; - } - else { - return padding; - } - } - else { - return [padding, padding, padding, padding]; - } - }; - Object.defineProperty(ContextMenuItem.prototype, "paddingTop", { - get: function () { - return this.toWholePadding(this.menu.style.itemStyle.padding)[0]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "paddingBottom", { - get: function () { - return this.toWholePadding(this.menu.style.itemStyle.padding)[2]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "paddingLeft", { - get: function () { - return this.toWholePadding(this.menu.style.itemStyle.padding)[3]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "paddingRight", { - get: function () { - return this.toWholePadding(this.menu.style.itemStyle.padding)[1]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "hoverColor", { - get: function () { - return this.style.hoverColor; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "fontSize", { - get: function () { - return this.style.fontSize; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ContextMenuItem.prototype, "fontColor", { - get: function () { - if (this.config.disabled) { - return this.style.disabledFontColor; - } - else if (this.config.fontColor) { - return this.config.fontColor; - } - return this.style.fontColor; - }, - enumerable: false, - configurable: true - }); - ContextMenuItem.prototype.initShortcutKeyText = function () { - if (this.config.shortcutKeys && this.config.shortcutKeys.length > 0) { - this.shortcutKeyText = new pixi_js.Text(this.config.shortcutKeys.join('+'), { - fontSize: this.fontSize, - fill: this.fontColor, - }); - this.addChild(this.shortcutKeyText); - return this.shortcutKeyText; - } - return undefined; - }; - ContextMenuItem.prototype.initSubMenu = function () { - if (this.config.subMenu && this.config.subMenu.groups.length > 0) { - this.arrowText = new pixi_js.Text('>', { - fontSize: this.fontSize, - fill: this.fontColor, - }); - this.addChild(this.arrowText); - this.subMenu = new ContextMenu(this.config.subMenu, this); - } - }; - ContextMenuItem.prototype.updateBackground = function (width, height) { - this.box.clear(); - var box = this.box; - var style = this.menu.style; - if (!style.itemStyle.hoverColor) { - throw new Error('未设置菜单项的hoverColor'); - } - var hoverColor = style.itemStyle.hoverColor; - if (this.style && this.style.hoverColor) { - hoverColor = this.style.hoverColor; - } - box.beginFill(new pixi_js.Color(hoverColor)); - if (style.borderRoundRadius > 0) { - box.drawRoundedRect(0, 0, width, height, style.borderRoundRadius); - } - else { - box.drawRect(0, 0, width, height); - } - box.endFill(); - box.alpha = 0; - }; - ContextMenuItem.prototype.updateBox = function (width, height) { - var _a; - this.removeAllListeners(); - this.updateBackground(width, height); - (_a = this.nameText) === null || _a === void 0 ? void 0 : _a.position.set(this.paddingLeft, this.paddingTop); - if (this.shortcutKeyText) { - var skTextWidth = this.shortcutKeyBounds.width; - this.shortcutKeyText.position.set(width - skTextWidth - this.paddingRight, this.paddingTop); - } - if (this.arrowText) { - this.arrowText.position.set(width - this.paddingRight - this.gutter, this.paddingTop); - } - // 事件监听 - this.hitArea = new pixi_js.Rectangle(0, 0, width, height); - this.registerEventHandler(); - }; - ContextMenuItem.prototype.update = function () { - if (this.config.visible === false) { - this.visible = false; - return; - } - this.visible = true; - this.nameText.text = this.config.name; - this.nameText.style.fontSize = this.fontSize; - this.nameText.style.fill = this.fontColor; - if (this.shortcutKeyText) { - if (this.config.shortcutKeys && this.config.shortcutKeys.length > 0) { - this.shortcutKeyText.text = this.config.shortcutKeys.join('+'); - this.shortcutKeyText.style.fontSize = this.fontSize; - this.shortcutKeyText.style.fill = this.fontColor; - } - else { - this.shortcutKeyText.visible = false; - } - } - else { - this.initShortcutKeyText(); - } - if (this.config.subMenu == undefined && this.subMenu) { - this.subMenu = undefined; - } - else if (this.config.subMenu && this.subMenu == undefined) { - this.initSubMenu(); - } - if (this.subMenu) { - this.subMenu.update(); - } - }; - return ContextMenuItem; -}(pixi_js.Container)); +} -var AppConsts = { +const AppConsts = { viewportname: '__viewport', canvasname: '__jlcanvas', AssistantAppendsName: '__assistantAppends', // 辅助元素默认颜色 assistantElementColor: '#1976d2', }; -var CanvasData = /** @class */ (function () { - function CanvasData(properties) { - if (properties === void 0) { properties = { - width: 1920, - height: 1080, - backgroundColor: '#ffffff', - viewportTransform: GraphicTransform.default(), - }; } +class CanvasData { + width; + height; + backgroundColor; + viewportTransform; + constructor(properties = { + width: 1920, + height: 1080, + backgroundColor: '#ffffff', + viewportTransform: GraphicTransform.default(), + }) { this.width = properties.width; this.height = properties.height; this.backgroundColor = properties.backgroundColor; this.viewportTransform = properties.viewportTransform; } - CanvasData.prototype.copyFrom = function (properties) { - var sizeChange = false; + copyFrom(properties) { + let sizeChange = false; if (properties.width <= 0 || properties.height <= 0) { console.error('画布宽度/高度不能小于等于0'); } else { - var width = Math.floor(properties.width); - var height = Math.floor(properties.height); + const width = Math.floor(properties.width); + const height = Math.floor(properties.height); if (this.width != width) { this.width = width; sizeChange = true; @@ -5589,239 +4534,187 @@ var CanvasData = /** @class */ (function () { this.backgroundColor = properties.backgroundColor; this.viewportTransform = properties.viewportTransform; return sizeChange; - }; - CanvasData.prototype.clone = function () { - var cp = new CanvasData(this); + } + clone() { + const cp = new CanvasData(this); return cp; - }; - return CanvasData; -}()); -var JlCanvas = /** @class */ (function (_super) { - __extends(JlCanvas, _super); - function JlCanvas(scene, properties) { - if (properties === void 0) { properties = new CanvasData(); } - var _this = _super.call(this) || this; - _this.__JlCanvas = true; - _this.type = 'Canvas'; - _this.bg = new pixi_js.Graphics(); // 背景 - _this.scene = scene; - _this._properties = properties; - _this.eventMode = 'static'; - _this.nonInteractiveContainer = new pixi_js.Container(); - _this.nonInteractiveContainer.name = 'non-interactives'; - _this.nonInteractiveContainer.eventMode = 'none'; - _this.addChild(_this.bg); - _this.addChild(_this.nonInteractiveContainer); - _this.sortableChildren = true; - _this.assistantAppendContainer = new pixi_js.Container(); - _this.assistantAppendContainer.eventMode = 'static'; - _this.assistantAppendContainer.name = AppConsts.AssistantAppendsName; - _this.assistantAppendContainer.zIndex = 999; - _this.assistantAppendContainer.sortableChildren = true; - _this.addChild(_this.assistantAppendContainer); - _this.repaint(); - return _this; + } +} +class JlCanvas extends Container { + __JlCanvas = true; + type = 'Canvas'; + scene; + _properties; + bg = new Graphics(); // 背景 + nonInteractiveContainer; // 无交互对象容器 + assistantAppendContainer; // 辅助附加容器 + constructor(scene, properties = new CanvasData()) { + super(); + this.scene = scene; + this._properties = properties; + this.eventMode = 'static'; + this.nonInteractiveContainer = new Container(); + this.nonInteractiveContainer.name = 'non-interactives'; + this.nonInteractiveContainer.eventMode = 'none'; + this.addChild(this.bg); + this.addChild(this.nonInteractiveContainer); + this.sortableChildren = true; + this.assistantAppendContainer = new Container(); + this.assistantAppendContainer.eventMode = 'static'; + this.assistantAppendContainer.name = AppConsts.AssistantAppendsName; + this.assistantAppendContainer.zIndex = 999; + this.assistantAppendContainer.sortableChildren = true; + this.addChild(this.assistantAppendContainer); + this.repaint(); } /** * 图形重绘(数据/状态变化时触发) */ - JlCanvas.prototype.repaint = function () { + repaint() { this.doRepaint(); - }; - Object.defineProperty(JlCanvas.prototype, "width", { - get: function () { - return this._properties.width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(JlCanvas.prototype, "height", { - get: function () { - return this._properties.height; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(JlCanvas.prototype, "backgroundColor", { - get: function () { - return this._properties.backgroundColor; - }, - enumerable: false, - configurable: true - }); - JlCanvas.prototype.doRepaint = function () { + } + get width() { + return this._properties.width; + } + get height() { + return this._properties.height; + } + get backgroundColor() { + return this._properties.backgroundColor; + } + doRepaint() { this.bg.clear(); this.bg - .beginFill(new pixi_js.Color(this.backgroundColor)) + .beginFill(new Color(this.backgroundColor)) .drawRect(0, 0, this._properties.width, this._properties.height) .endFill(); - }; - Object.defineProperty(JlCanvas.prototype, "properties", { - get: function () { - return this._properties; - }, - enumerable: false, - configurable: true - }); - JlCanvas.prototype.saveData = function () { - var vp = this.getViewport(); + } + get properties() { + return this._properties; + } + saveData() { + const vp = this.getViewport(); this.properties.viewportTransform = vp.saveTransform(); return this.properties.clone(); - }; - JlCanvas.prototype.update = function (properties) { + } + update(properties) { // 更新画布 - var old = this.properties.clone(); + const old = this.properties.clone(); this._properties.copyFrom(properties); this.repaint(); - var vp = this.getViewport(); + const vp = this.getViewport(); vp.loadTransform(properties.viewportTransform); this.emit('dataupdate', this.properties, old); - }; - JlCanvas.prototype.addChild = function () { - var _this = this; - var children = []; - for (var _i = 0; _i < arguments.length; _i++) { - children[_i] = arguments[_i]; - } - var rt = _super.prototype.addChild.apply(this, children); - children.forEach(function (g) { - g.onAddToCanvas(_this); - recursiveChildren(g, function (child) { return child.onAddToCanvas(_this); }); + } + addChild(...children) { + const rt = super.addChild(...children); + children.forEach((g) => { + g.onAddToCanvas(this); + recursiveChildren(g, (child) => child.onAddToCanvas(this)); }); return rt; - }; - JlCanvas.prototype.removeChild = function () { - var _this = this; - var children = []; - for (var _i = 0; _i < arguments.length; _i++) { - children[_i] = arguments[_i]; - } - children.forEach(function (g) { - g.onRemoveFromCanvas(_this); - recursiveChildren(g, function (child) { - return child.onRemoveFromCanvas(_this); - }); + } + removeChild(...children) { + children.forEach((g) => { + g.onRemoveFromCanvas(this); + recursiveChildren(g, (child) => child.onRemoveFromCanvas(this)); }); - return _super.prototype.removeChild.apply(this, children); - }; + return super.removeChild(...children); + } /** * 添加无交互Child */ - JlCanvas.prototype.addNonInteractiveChild = function () { - var _a; - var _this = this; - var obj = []; - for (var _i = 0; _i < arguments.length; _i++) { - obj[_i] = arguments[_i]; - } - (_a = this.nonInteractiveContainer).addChild.apply(_a, obj); - obj.forEach(function (g) { - g.onAddToCanvas(_this); - recursiveChildren(g, function (child) { return child.onAddToCanvas(_this); }); + addNonInteractiveChild(...obj) { + this.nonInteractiveContainer.addChild(...obj); + obj.forEach((g) => { + g.onAddToCanvas(this); + recursiveChildren(g, (child) => child.onAddToCanvas(this)); }); - }; - JlCanvas.prototype.removeGraphic = function () { - var _a; - var _this = this; - var obj = []; - for (var _i = 0; _i < arguments.length; _i++) { - obj[_i] = arguments[_i]; - } - obj.forEach(function (g) { - g.onRemoveFromCanvas(_this); - recursiveChildren(g, function (child) { - return child.onRemoveFromCanvas(_this); - }); + } + removeGraphic(...obj) { + obj.forEach((g) => { + g.onRemoveFromCanvas(this); + recursiveChildren(g, (child) => child.onRemoveFromCanvas(this)); }); - this.removeChild.apply(this, obj); - (_a = this.nonInteractiveContainer).removeChild.apply(_a, obj); - }; + this.removeChild(...obj); + this.nonInteractiveContainer.removeChild(...obj); + } /** * 移除无交互Child */ - JlCanvas.prototype.removeNonInteractiveChild = function () { - var _a; - var _this = this; - var obj = []; - for (var _i = 0; _i < arguments.length; _i++) { - obj[_i] = arguments[_i]; - } - obj.forEach(function (g) { - g.onRemoveFromCanvas(_this); - recursiveChildren(g, function (child) { - return child.onRemoveFromCanvas(_this); - }); + removeNonInteractiveChild(...obj) { + obj.forEach((g) => { + g.onRemoveFromCanvas(this); + recursiveChildren(g, (child) => child.onRemoveFromCanvas(this)); }); - (_a = this.nonInteractiveContainer).removeChild.apply(_a, obj); - }; - JlCanvas.prototype.addAssistantAppends = function () { - var _a; - var _this = this; - var appends = []; - for (var _i = 0; _i < arguments.length; _i++) { - appends[_i] = arguments[_i]; - } - (_a = this.assistantAppendContainer).addChild.apply(_a, appends); - appends.forEach(function (g) { - g.onAddToCanvas(_this); - recursiveChildren(g, function (child) { return child.onAddToCanvas(_this); }); + this.nonInteractiveContainer.removeChild(...obj); + } + addAssistantAppends(...appends) { + this.assistantAppendContainer.addChild(...appends); + appends.forEach((g) => { + g.onAddToCanvas(this); + recursiveChildren(g, (child) => child.onAddToCanvas(this)); }); - }; - JlCanvas.prototype.removeAssistantAppends = function () { - var _a; - var _this = this; - var appends = []; - for (var _i = 0; _i < arguments.length; _i++) { - appends[_i] = arguments[_i]; - } - appends.forEach(function (g) { - g.onRemoveFromCanvas(_this); - recursiveChildren(g, function (child) { return child.onAddToCanvas(_this); }); + } + removeAssistantAppends(...appends) { + appends.forEach((g) => { + g.onRemoveFromCanvas(this); + recursiveChildren(g, (child) => child.onAddToCanvas(this)); }); - (_a = this.assistantAppendContainer).removeChild.apply(_a, appends); - }; + this.assistantAppendContainer.removeChild(...appends); + } /** * 暂停所有可交互对象 */ - JlCanvas.prototype.pauseInteractiveChildren = function () { + pauseInteractiveChildren() { this.interactiveChildren = false; - }; + } /** * 恢复所有可交互对象 */ - JlCanvas.prototype.resumeInteractiveChildren = function () { + resumeInteractiveChildren() { this.interactiveChildren = true; - }; - return JlCanvas; -}(pixi_js.Container)); -var GraphicSceneBase = /** @class */ (function (_super) { - __extends(GraphicSceneBase, _super); - function GraphicSceneBase(options) { - var _this = _super.call(this) || this; - _this._loaded = false; // 是否已经加载 - _this.graphicTemplateMap = new Map(); // 图形对象模板 - _this.interactionPluginMap = new Map(); // 交互插件 - _this.graphicStore = new GraphicStore(); - _this._options = options; + } +} +class GraphicSceneBase extends EventEmitter { + graphicStore; + _options; + pixi; // Pixi 渲染器 + viewport; // 视口 + canvas; // 画布 + _loaded = false; // 是否已经加载 + _dom; // 场景绑定到的dom节点 + _viewportResizer; // 自动根据dom大小变化调整视口尺寸 + graphicTemplateMap = new Map(); // 图形对象模板 + interactionPluginMap = new Map(); // 交互插件 + graphicCopyPlugin; // 图形复制操作插件 + animationManager; // 动画管理组件 + menuPlugin; // 菜单插件 + debounceEmitFunc; + wsMsgBroker; // websocket消息代理 + constructor(options) { + super(); + this.graphicStore = new GraphicStore(); + this._options = options; // 创建pixi渲染app - _this.pixi = new pixi_js.Application({ + this.pixi = new Application({ antialias: true, }); // 创建画布 - _this.canvas = new JlCanvas(_this); - _this.canvas.name = AppConsts.canvasname; + this.canvas = new JlCanvas(this); + this.canvas.name = AppConsts.canvasname; // 创建相机 - _this.viewport = new pixiViewport.Viewport({ + this.viewport = new Viewport({ screenWidth: window.innerWidth, screenHeight: window.innerHeight, - worldWidth: _this.canvas._properties.width, - worldHeight: _this.canvas._properties.height, + worldWidth: this.canvas._properties.width, + worldHeight: this.canvas._properties.height, passiveWheel: true, - events: _this.pixi.renderer.events, + events: this.pixi.renderer.events, disableOnContextMenu: true, }); // 设置视口操作方式 - _this.viewport + this.viewport .wheel({ percent: 1, }) @@ -5833,133 +4726,82 @@ var GraphicSceneBase = /** @class */ (function (_super) { .clamp({ direction: 'all', }); - _this.viewport.name = AppConsts.viewportname; - _this.viewport.interactiveChildren = true; + this.viewport.name = AppConsts.viewportname; + this.viewport.interactiveChildren = true; // 添加视口到渲染器舞台 - _this.pixi.stage.addChild(_this.viewport); + this.pixi.stage.addChild(this.viewport); // 将画布置于视口 - _this.viewport.addChild(_this.canvas); + this.viewport.addChild(this.canvas); // 监听并通知缩放变化事件 - _this.viewport.on('zoomed-end', function () { - _this.emit('viewport-scaled', _this.viewport); + this.viewport.on('zoomed-end', () => { + this.emit('viewport-scaled', this.viewport); }); - _this.graphicCopyPlugin = new GraphicCopyPlugin(_this); + this.graphicCopyPlugin = new GraphicCopyPlugin(this); // 添加通用交互插件 - CommonMouseTool.new(_this).resume(); + CommonMouseTool.new(this).resume(); // drag插件 - DragPlugin.new(_this).resume(); + DragPlugin.new(this).resume(); // 视口移动插件 - ViewportMovePlugin.new(_this); + ViewportMovePlugin.new(this); // 图形变换插件 - GraphicTransformPlugin.new(_this).resume(); + GraphicTransformPlugin.new(this).resume(); // 动画管理 - _this.animationManager = new AnimationManager(_this); - _this.menuPlugin = new ContextMenuPlugin(_this); - _this.wsMsgBroker = new AppWsMsgBroker(_this); - _this.debounceEmitFunc = debounce(_this.doEmitAppGraphicSelected, 50); - _this.on('graphicselectedchange', function () { - _this.debounceEmitFunc(_this); + this.animationManager = new AnimationManager(this); + this.menuPlugin = new ContextMenuPlugin(this); + this.wsMsgBroker = new AppWsMsgBroker(this); + this.debounceEmitFunc = debounce(this.doEmitAppGraphicSelected, 50); + this.on('graphicselectedchange', () => { + this.debounceEmitFunc(this); }); // 发布选项更新事件 - _this.emit('options-update', _this._options); - return _this; + this.emit('options-update', this._options); + } + get appOptions() { + return this._options; + } + get dom() { + return this._dom; + } + get queryStore() { + return this.graphicStore; + } + get selectedGraphics() { + return this.queryStore.getAllGraphics().filter((g) => g.selected); + } + async load() { + if (this._options.dataLoader) { + const storage = await this._options.dataLoader(); + if (storage.canvasProperty) { + this.canvas.update(storage.canvasProperty); + } + if (storage.datas) { + await this.loadGraphic(storage.datas); + } + } + this._loaded = true; } - Object.defineProperty(GraphicSceneBase.prototype, "appOptions", { - get: function () { - return this._options; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(GraphicSceneBase.prototype, "dom", { - get: function () { - return this._dom; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(GraphicSceneBase.prototype, "queryStore", { - get: function () { - return this.graphicStore; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(GraphicSceneBase.prototype, "selectedGraphics", { - get: function () { - return this.queryStore.getAllGraphics().filter(function (g) { return g.selected; }); - }, - enumerable: false, - configurable: true - }); - GraphicSceneBase.prototype.load = function () { - return __awaiter(this, void 0, void 0, function () { - var storage; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this._options.dataLoader) return [3 /*break*/, 3]; - return [4 /*yield*/, this._options.dataLoader()]; - case 1: - storage = _a.sent(); - if (storage.canvasProperty) { - this.canvas.update(storage.canvasProperty); - } - if (!storage.datas) return [3 /*break*/, 3]; - return [4 /*yield*/, this.loadGraphic(storage.datas)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: - this._loaded = true; - return [2 /*return*/]; - } - }); - }); - }; /** * 重新加载数据 */ - GraphicSceneBase.prototype.reload = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!this._loaded) return [3 /*break*/, 2]; - this.graphicStore.clear(); - return [4 /*yield*/, this.load()]; - case 1: - _a.sent(); - return [3 /*break*/, 3]; - case 2: - console.debug('场景已经加载过数据,不重新加载', this); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - GraphicSceneBase.prototype.forceReload = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - console.debug('场景强制重新加载数据', this); - this.graphicStore.clear(); - return [4 /*yield*/, this.load()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; + async reload() { + if (!this._loaded) { + this.graphicStore.clear(); + await this.load(); + } + else { + console.debug('场景已经加载过数据,不重新加载', this); + } + } + async forceReload() { + console.debug('场景强制重新加载数据', this); + this.graphicStore.clear(); + await this.load(); + } /** * 更新选项 * @param options */ - GraphicSceneBase.prototype.setOptions = function (options) { - // console.log('更新选项', options); + setOptions(options) { if (this._options) { this._options = Object.assign(this._options, options); } @@ -5967,49 +4809,44 @@ var GraphicSceneBase = /** @class */ (function (_super) { this._options = options; } this.emit('options-update', options); - }; - GraphicSceneBase.prototype.toCanvasCoordinates = function (p) { + } + toCanvasCoordinates(p) { return this.viewport.toWorld(p); - }; + } /** * 注册菜单 * @param menu */ - GraphicSceneBase.prototype.registerMenu = function (menu) { + registerMenu(menu) { this.menuPlugin.registerMenu(menu); - }; + } /** * 注册图形对象模板 * @param graphicTemplates */ - GraphicSceneBase.prototype.registerGraphicTemplates = function () { - var _this = this; - var graphicTemplates = []; - for (var _i = 0; _i < arguments.length; _i++) { - graphicTemplates[_i] = arguments[_i]; - } - graphicTemplates.forEach(function (graphicTemplate) { - _this.graphicTemplateMap.set(graphicTemplate.type, graphicTemplate); + registerGraphicTemplates(...graphicTemplates) { + graphicTemplates.forEach((graphicTemplate) => { + this.graphicTemplateMap.set(graphicTemplate.type, graphicTemplate); }); - }; - GraphicSceneBase.prototype.getGraphicTemplatesByType = function (type) { - var template = this.graphicTemplateMap.get(type); + } + getGraphicTemplatesByType(type) { + const template = this.graphicTemplateMap.get(type); if (!template) { - throw new Error("\u4E0D\u5B58\u5728type=".concat(type, "\u7684\u56FE\u5F62\u5BF9\u8C61\u6A21\u677F")); + throw new Error(`不存在type=${type}的图形对象模板`); } return template; - }; - GraphicSceneBase.prototype.updateViewport = function (domWidth, domHeight) { - var screenWidth = this.viewport.screenWidth; - var screenHeight = this.viewport.screenHeight; + } + updateViewport(domWidth, domHeight) { + let screenWidth = this.viewport.screenWidth; + let screenHeight = this.viewport.screenHeight; if (domWidth) { screenWidth = domWidth; } if (domHeight) { screenHeight = domHeight; } - var worldWidth = this.canvas._properties.width; - var worldHeight = this.canvas._properties.height; + const worldWidth = this.canvas._properties.width; + const worldHeight = this.canvas._properties.height; this.pixi.resize(); this.viewport.resize(screenWidth, screenHeight, worldWidth, worldHeight); if (this.viewport.OOB().right) { @@ -6024,46 +4861,38 @@ var GraphicSceneBase = /** @class */ (function (_super) { else if (this.viewport.OOB().bottom) { this.viewport.bottom = this.viewport.bottom + 1; } - }; + } /** * 暂停 */ - GraphicSceneBase.prototype.pause = function () { + pause() { // 暂停动画 this.animationManager.pause(); // 取消消息订阅 this.wsMsgBroker.unsubscribeAll(); // 关闭所有上下文菜单 this.menuPlugin.closeAll(); - }; + } /** * 恢复 */ - GraphicSceneBase.prototype.resume = function () { + resume() { // 恢复动画 this.animationManager.resume(); // 重新订阅 this.wsMsgBroker.resubscribeAll(); - }; - GraphicSceneBase.prototype.bindDom = function (dom) { - var _this = this; + } + bindDom(dom) { this._dom = dom; this.pixi.resizeTo = dom; dom.appendChild(this.pixi.view); - this._viewportResizer = setInterval(function () { - // console.log( - // 'dom resize ', - // dom.style.width, - // dom.style.height, - // dom.clientWidth, - // dom.clientHeight - // ); - _this.updateViewport(dom.clientWidth, dom.clientHeight); + this._viewportResizer = setInterval(() => { + this.updateViewport(dom.clientWidth, dom.clientHeight); }, 1000); // 恢复 this.resume(); - }; - GraphicSceneBase.prototype.unbindDom = function () { + } + unbindDom() { if (this._dom) { clearInterval(this._viewportResizer); this._dom.removeChild(this.pixi.view); @@ -6071,82 +4900,59 @@ var GraphicSceneBase = /** @class */ (function (_super) { // 暂停 this.pause(); } - }; + } /** * 加载图形,GraphicApp默认添加到无交互容器,DrawApp默认添加到交互容器,如需定制,提供选项配置 * @param protos * @param options 添加到可交互/不可交互容器选项配置 */ - GraphicSceneBase.prototype.loadGraphic = function (protos) { - var _a; - return __awaiter(this, void 0, void 0, function () { - var _i, _b, item, max; - var _this = this; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - _i = 0, _b = this.graphicTemplateMap; - _c.label = 1; - case 1: - if (!(_i < _b.length)) return [3 /*break*/, 4]; - item = _b[_i]; - return [4 /*yield*/, item[1].loadAssets()]; - case 2: - _c.sent(); - _c.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: - // console.log('开始加载proto数据', protos); - // 加载数据到图形存储 - protos.forEach(function (proto) { - var template = _this.getGraphicTemplatesByType(proto.graphicType); - var g = template.new(); - g.loadData(proto); - _this.addGraphics(g); - }); - // 加载数据关系 - this.queryStore.getAllGraphics().forEach(function (g) { return g.loadRelations(); }); - max = (_a = this.queryStore - .getAllGraphics() - .filter(function (g) { return !isNaN(parseInt(g.id)); }) - .map(function (g) { return parseInt(g.id); }) - .sort(function (a, b) { return a - b; }) - .pop()) !== null && _a !== void 0 ? _a : 0; - // console.log('最大值', max) - GraphicIdGenerator.initSerial(max); - // 数据加载完成后 - this.emit('postdataloaded'); - // 加载完成通知 - this.emit('loadfinish'); - return [2 /*return*/]; - } - }); + async loadGraphic(protos) { + for (const item of this.graphicTemplateMap) { + await item[1].loadAssets(); + } + // 加载数据到图形存储 + protos.forEach((proto) => { + const template = this.getGraphicTemplatesByType(proto.graphicType); + const g = template.new(); + g.loadData(proto); + this.addGraphics(g); }); - }; + // 加载数据关系 + this.queryStore.getAllGraphics().forEach((g) => g.loadRelations()); + // 更新id生成器 + const max = this.queryStore + .getAllGraphics() + .filter((g) => !isNaN(parseInt(g.id))) + .map((g) => parseInt(g.id)) + .sort((a, b) => a - b) + .pop() ?? 0; + GraphicIdGenerator.initSerial(max); + // 数据加载完成后 + this.emit('postdataloaded'); + // 加载完成通知 + this.emit('loadfinish'); + } /** * 添加图形前处理 * @param graphic */ - GraphicSceneBase.prototype.beforeGraphicStore = function (graphic) { - var interactiveGraphicTypeIncludes = this._options.interactiveGraphicTypeIncludes || []; - var interactiveGraphicTypeExcludes = this._options.interactiveGraphicTypeExcludes || []; + beforeGraphicStore(graphic) { + const interactiveGraphicTypeIncludes = this._options.interactiveGraphicTypeIncludes || []; + const interactiveGraphicTypeExcludes = this._options.interactiveGraphicTypeExcludes || []; // 默认无交互 graphic.eventMode = 'auto'; - if (interactiveGraphicTypeIncludes.findIndex(function (type) { return type === graphic.type; }) >= 0) { + if (interactiveGraphicTypeIncludes.findIndex((type) => type === graphic.type) >= 0) { graphic.eventMode = 'static'; } - else if (interactiveGraphicTypeExcludes.findIndex(function (type) { return type === graphic.type; }) < 0) { + else if (interactiveGraphicTypeExcludes.findIndex((type) => type === graphic.type) < 0) { graphic.eventMode = 'static'; } - }; + } /** * 执行添加图形对象 * @param graphic */ - GraphicSceneBase.prototype.doAddGraphics = function (graphic) { - var _this = this; + doAddGraphics(graphic) { this.beforeGraphicStore(graphic); if (this.graphicStore.storeGraphics(graphic)) { // cullable,默认设置剪裁,如果图形包围框不在屏幕内,则不渲染,增加效率用 @@ -6155,27 +4961,25 @@ var GraphicSceneBase = /** @class */ (function (_super) { } if (graphic.eventMode == 'static' || graphic.eventMode == 'dynamic') { // 添加为可交互 - // console.log(`type=${graphic.type}的图形添加到交互容器`); this.canvas.addChild(graphic); } else { // 添加到不可交互容器 - // console.log(`type=${graphic.type}的图形添加到无交互容器`); this.canvas.addNonInteractiveChild(graphic); } graphic.repaint(); this.emit('graphicstored', graphic); - graphic.on('childselected', function (child) { - _this.emit('graphicchildselectedchange', child, true); + graphic.on('childselected', (child) => { + this.emit('graphicchildselectedchange', child, true); }); - graphic.on('childunselected', function (child) { - _this.emit('graphicchildselectedchange', child, false); + graphic.on('childunselected', (child) => { + this.emit('graphicchildselectedchange', child, false); }); } - }; - GraphicSceneBase.prototype.doDeleteGraphics = function (graphic) { + } + doDeleteGraphics(graphic) { // 从store中删除 - var g = this.graphicStore.deleteGraphics(graphic); + const g = this.graphicStore.deleteGraphics(graphic); if (g) { // 清除选中 g.updateSelected(false); @@ -6185,212 +4989,186 @@ var GraphicSceneBase = /** @class */ (function (_super) { g.onDelete(); this.emit('graphicdeleted', g); } - }; + } /** * 存储图形 * @param graphics 图形对象 */ - GraphicSceneBase.prototype.addGraphics = function () { - var _this = this; - var graphics = []; - for (var _i = 0; _i < arguments.length; _i++) { - graphics[_i] = arguments[_i]; - } - graphics.forEach(function (g) { return _this.doAddGraphics(g); }); - }; + addGraphics(...graphics) { + graphics.forEach((g) => this.doAddGraphics(g)); + } /** * 删除图形 * @param graphics 图形对象 */ - GraphicSceneBase.prototype.deleteGraphics = function () { - var _this = this; - var graphics = []; - for (var _i = 0; _i < arguments.length; _i++) { - graphics[_i] = arguments[_i]; - } - var dels = graphics.filter(function (g) { - var _a; - if (((_a = _this._options) === null || _a === void 0 ? void 0 : _a.isSupportDeletion) == undefined || - _this._options.isSupportDeletion(g)) { - _this.doDeleteGraphics(g); + deleteGraphics(...graphics) { + const dels = graphics.filter((g) => { + if (this._options?.isSupportDeletion == undefined || + this._options.isSupportDeletion(g)) { + this.doDeleteGraphics(g); return true; } - console.debug("type=".concat(g.type, ",id=").concat(g.id, "\u7684\u56FE\u5F62\u4E0D\u652F\u6301\u5220\u9664")); + console.debug(`type=${g.type},id=${g.id}的图形不支持删除`); return false; }); return dels; - }; + } /** * 检测并构建关系 */ - GraphicSceneBase.prototype.detectRelations = function () { - this.queryStore.getAllGraphics().forEach(function (g) { return g.buildRelation(); }); - }; + detectRelations() { + this.queryStore.getAllGraphics().forEach((g) => g.buildRelation()); + } /** * 全选 */ - GraphicSceneBase.prototype.selectAllGraphics = function (filter) { + selectAllGraphics(filter) { if (filter == undefined) { - filter = function (g) { return g.visible; }; + filter = (g) => g.visible; } - this.updateSelected.apply(this, this.queryStore.getAllGraphics().filter(filter)); - }; + this.updateSelected(...this.queryStore.getAllGraphics().filter(filter)); + } /** * 更新选中 */ - GraphicSceneBase.prototype.updateSelected = function () { - var graphics = []; - for (var _i = 0; _i < arguments.length; _i++) { - graphics[_i] = arguments[_i]; - } - this.selectedGraphics.forEach(function (graphic) { - if (graphics.findIndex(function (g) { return g.id === graphic.id; }) >= 0) { + updateSelected(...graphics) { + this.selectedGraphics.forEach((graphic) => { + if (graphics.findIndex((g) => g.id === graphic.id) >= 0) { return; } if (graphic.selected) { graphic.updateSelected(false); } }); - graphics.forEach(function (graphic) { + graphics.forEach((graphic) => { graphic.updateSelected(true); }); - }; - GraphicSceneBase.prototype.doEmitAppGraphicSelected = function () { + } + doEmitAppGraphicSelected() { // 场景发布图形选中 this.emit('graphicselected', this.selectedGraphics); // this.app.emit('graphicselected', this.selectedGraphics); - }; + } /** * 更新画布 * @param param */ - GraphicSceneBase.prototype.updateCanvas = function (param) { + updateCanvas(param) { this.canvas.update(param); - }; + } /** * 使图形居中显示(所有图形的外包围盒) */ - GraphicSceneBase.prototype.makeGraphicCenterShow = function () { - var group = []; - for (var _i = 0; _i < arguments.length; _i++) { - group[_i] = arguments[_i]; - } + makeGraphicCenterShow(...group) { if (group.length > 0) { - var bounds0 = group[0].getBounds(); - var lx = bounds0.x; - var ly = bounds0.y; - var rx = bounds0.x + bounds0.width; - var ry = bounds0.y + bounds0.height; + const bounds0 = group[0].getBounds(); + let lx = bounds0.x; + let ly = bounds0.y; + let rx = bounds0.x + bounds0.width; + let ry = bounds0.y + bounds0.height; if (group.length > 1) { - for (var i = 1; i < group.length; i++) { - var g = group[i]; - var bound = g.getBounds(); + for (let i = 1; i < group.length; i++) { + const g = group[i]; + const bound = g.getBounds(); if (bound.x < lx) { lx = bound.x; } if (bound.y < ly) { ly = bound.y; } - var brx = bound.x + bound.width; + const brx = bound.x + bound.width; if (brx > rx) { rx = brx; } - var bry = bound.y + bound.height; + const bry = bound.y + bound.height; if (bry > ry) { ry = bry; } } } - var _a = getRectangleCenter(new pixi_js.Rectangle(lx, ly, rx - lx, ry - ly)), x = _a.x, y = _a.y; - var p = this.viewport.toWorld(x, y); + const { x, y } = getRectangleCenter(new Rectangle(lx, ly, rx - lx, ry - ly)); + const p = this.viewport.toWorld(x, y); this.viewport.moveCenter(p.x, p.y); } - }; + } /** * 注册交互插件,会替换旧的 */ - GraphicSceneBase.prototype.registerInteractionPlugin = function () { - var _this = this; - var plugins = []; - for (var _i = 0; _i < arguments.length; _i++) { - plugins[_i] = arguments[_i]; - } - plugins.forEach(function (plugin) { - var old = _this.interactionPluginMap.get(plugin.name); + registerInteractionPlugin(...plugins) { + plugins.forEach((plugin) => { + const old = this.interactionPluginMap.get(plugin.name); if (old) { - console.warn("\u5DF2\u7ECF\u5B58\u5728name=".concat(plugin.name, "\u7684\u4EA4\u4E92\u63D2\u4EF6,\u5FFD\u7565\u6B64\u63D2\u4EF6\u6CE8\u518C!")); + console.warn(`已经存在name=${plugin.name}的交互插件,忽略此插件注册!`); return; } - _this.interactionPluginMap.set(plugin.name, plugin); + this.interactionPluginMap.set(plugin.name, plugin); }); - }; + } /** * 根据名称获取交互插件 * @param name * @returns */ - GraphicSceneBase.prototype.interactionPlugin = function (name) { - var plugin = this.interactionPluginMap.get(name); + interactionPlugin(name) { + const plugin = this.interactionPluginMap.get(name); if (!plugin) { - throw new Error("\u672A\u627E\u5230name=".concat(name, "\u7684\u4EA4\u4E92\u63D2\u4EF6")); + throw new Error(`未找到name=${name}的交互插件`); } return plugin; - }; + } /** * 停止应用交互插件 */ - GraphicSceneBase.prototype.pauseAppInteractionPlugins = function () { - var _this = this; - this.interactionPluginMap.forEach(function (plugin) { - if (plugin.isActive() && plugin._type === exports.InteractionPluginType.App) { - _this.doPauseInteractionPlugin(plugin); + pauseAppInteractionPlugins() { + this.interactionPluginMap.forEach((plugin) => { + if (plugin.isActive() && plugin._type === InteractionPluginType.App) { + this.doPauseInteractionPlugin(plugin); } }); - }; - GraphicSceneBase.prototype.doPauseInteractionPlugin = function (plugin) { + } + doPauseInteractionPlugin(plugin) { if (plugin && plugin.isActive()) { plugin.pause(); this.emit('interaction-plugin-pause', plugin); } - }; + } /** * 移除交互插件 */ - GraphicSceneBase.prototype.removeInteractionPlugin = function (plugin) { + removeInteractionPlugin(plugin) { this.interactionPluginMap.delete(plugin.name); - }; - GraphicSceneBase.prototype.checkWsMsgCli = function () { + } + checkWsMsgCli() { if (!WsMsgCli.isInitiated()) { throw new Error('订阅消息需先启动消息代理, 执行app.enableWebsocket()'); } - }; + } /** * 订阅websocket消息 */ - GraphicSceneBase.prototype.subscribe = function (sub) { + subscribe(sub) { this.checkWsMsgCli(); this.wsMsgBroker.subscribe(sub); - }; + } /** * 取消websocket订阅 */ - GraphicSceneBase.prototype.unsubscribe = function (destination) { + unsubscribe(destination) { this.checkWsMsgCli(); this.wsMsgBroker.unsbuscribe(destination); - }; + } /** * 处理图形状态 * @param graphicStates */ - GraphicSceneBase.prototype.handleGraphicStates = function (graphicStates, queryer, createOnNotFound) { - var _this = this; - graphicStates.forEach(function (state) { - var g; + handleGraphicStates(graphicStates, queryer, createOnNotFound) { + graphicStates.forEach((state) => { + let g; if (queryer) { - g = queryer(state, _this.queryStore); + g = queryer(state, this.queryStore); } else { - g = _this.queryStore.queryByCodeAndType(state.code, state.graphicType); + g = this.queryStore.queryByCodeAndType(state.code, state.graphicType); } try { if (!g) { @@ -6398,17 +5176,17 @@ var GraphicSceneBase = /** @class */ (function (_super) { if (!state.remove && createOnNotFound && createOnNotFound.graphicTypes && - createOnNotFound.graphicTypes.findIndex(function (v) { return v === state.graphicType; }) >= 0) { - var template = _this.getGraphicTemplatesByType(state.graphicType); - var g_1 = template.new(); - g_1.loadState(state); - _this.addGraphics(g_1); + createOnNotFound.graphicTypes.findIndex((v) => v === state.graphicType) >= 0) { + const template = this.getGraphicTemplatesByType(state.graphicType); + const g = template.new(); + g.loadState(state); + this.addGraphics(g); } } else { // 找到 if (state.remove) { - _this.deleteGraphics(g); + this.deleteGraphics(g); g.destroy({ children: true }); } else if (g.updateStates(state)) { @@ -6421,213 +5199,182 @@ var GraphicSceneBase = /** @class */ (function (_super) { // throw err; } }); - }; + } /** * 销毁 */ - GraphicSceneBase.prototype.destroy = function () { + destroy() { console.debug('场景销毁', this); this.unbindDom(); if (this.wsMsgBroker) { this.wsMsgBroker.close(); } - this.interactionPluginMap.forEach(function (plugin) { + this.interactionPluginMap.forEach((plugin) => { plugin.pause(); }); this.animationManager.destroy(); this.canvas.destroy(true); this.viewport.destroy(); this.pixi.destroy(true, true); - }; - return GraphicSceneBase; -}(EventEmitter)); + } +} /** * 图形app基类 */ -var GraphicApp = /** @class */ (function (_super) { - __extends(GraphicApp, _super); - function GraphicApp(options) { - var _this = _super.call(this, options) || this; - /** - * 场景列表 - */ - _this.scenes = new Map(); - // console.log('创建图形App') - _this.opRecord = new OperationRecord(); +class GraphicApp extends GraphicSceneBase { + /** + * 场景列表 + */ + scenes = new Map(); + opRecord; // 操作记录 + keyboardPlugin; // 键盘操作处理插件 + constructor(options) { + super(options); + this.opRecord = new OperationRecord(); // 绑定键盘监听 - _this.keyboardPlugin = new JlGraphicAppKeyboardPlugin(_this); - return _this; + this.keyboardPlugin = new JlGraphicAppKeyboardPlugin(this); } - Object.defineProperty(GraphicApp.prototype, "app", { - get: function () { - return this; - }, - enumerable: false, - configurable: true - }); - GraphicApp.prototype.setOptions = function (options) { - // console.log('更新选项', options); + get app() { + return this; + } + setOptions(options) { if (options.maxOperationRecords && options.maxOperationRecords > 0) { this.opRecord.setMaxLen(options.maxOperationRecords); } - _super.prototype.setOptions.call(this, options); - }; - GraphicApp.prototype.addGraphicAndRecord = function () { - var graphics = []; - for (var _i = 0; _i < arguments.length; _i++) { - graphics[_i] = arguments[_i]; - } - this.addGraphics.apply(this, graphics); + super.setOptions(options); + } + addGraphicAndRecord(...graphics) { + this.addGraphics(...graphics); this.opRecord.record(new GraphicCreateOperation(this, graphics)); - }; - GraphicApp.prototype.deleteGraphicAndRecord = function () { - var graphics = []; - for (var _i = 0; _i < arguments.length; _i++) { - graphics[_i] = arguments[_i]; - } - this.deleteGraphics.apply(this, graphics); + } + deleteGraphicAndRecord(...graphics) { + this.deleteGraphics(...graphics); this.opRecord.record(new GraphicDeleteOperation(this, graphics)); - }; + } /** * 实例化一个场景 * @param code 场景标识 * @returns */ - GraphicApp.prototype.initScene = function (code, options) { - var scene = this.scenes.get(code); + initScene(code, options) { + let scene = this.scenes.get(code); if (!scene) { scene = new JlScene(this, code, options); this.scenes.set(code, scene); } return scene; - }; + } /** * 获取场景 * @param code * @returns */ - GraphicApp.prototype.getScene = function (code) { - var scene = this.scenes.get(code); + getScene(code) { + const scene = this.scenes.get(code); if (!scene) { - throw new Error("\u4E0D\u5B58\u5728code=".concat(code, "\u7684\u573A\u666F")); + throw new Error(`不存在code=${code}的场景`); } return scene; - }; - GraphicApp.prototype.switchScene = function (code, dom) { - var scene = this.getScene(code); + } + switchScene(code, dom) { + const scene = this.getScene(code); // eslint-disable-next-line @typescript-eslint/no-unused-vars - for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) { - var _b = _a[_i]; _b[0]; var pre = _b[1]; + for (const [_code, pre] of this.scenes) { if (pre.dom === dom) { pre.unbindDom(); break; } } scene.bindDom(dom); - }; - GraphicApp.prototype.removeScene = function (code) { - var scene = this.scenes.get(code); + } + removeScene(code) { + const scene = this.scenes.get(code); if (scene) { this.scenes.delete(code); scene.destroy(); } - }; + } /** * 启动websocket消息客户端 */ - GraphicApp.prototype.enableWsMassaging = function (options) { + enableWsMassaging(options) { WsMsgCli.new(options); this.wsMsgBroker = new AppWsMsgBroker(this); - }; + } /** * 添加键盘监听器,如果是相同的按键,新注册的会覆盖旧的,当移除新的时,旧的自动生效 * @param keyListeners */ - GraphicApp.prototype.addKeyboardListener = function () { - var _this = this; - var keyListeners = []; - for (var _i = 0; _i < arguments.length; _i++) { - keyListeners[_i] = arguments[_i]; - } - keyListeners.forEach(function (keyListener) { - return _this.keyboardPlugin.addKeyListener(keyListener); - }); - }; + addKeyboardListener(...keyListeners) { + keyListeners.forEach((keyListener) => this.keyboardPlugin.addKeyListener(keyListener)); + } /** * 移除键盘监听器 * @param keyListeners */ - GraphicApp.prototype.removeKeyboardListener = function () { - var _this = this; - var keyListeners = []; - for (var _i = 0; _i < arguments.length; _i++) { - keyListeners[_i] = arguments[_i]; - } - keyListeners.forEach(function (keyListener) { - return _this.keyboardPlugin.removeKeyListener(keyListener); - }); - }; + removeKeyboardListener(...keyListeners) { + keyListeners.forEach((keyListener) => this.keyboardPlugin.removeKeyListener(keyListener)); + } /** * 销毁 */ - GraphicApp.prototype.destroy = function () { + destroy() { console.debug('图形应用销毁', this); this.emit('destroy', this); - _super.prototype.destroy.call(this); - this.scenes.forEach(function (scene) { return scene.destroy(); }); - }; - return GraphicApp; -}(GraphicSceneBase)); + super.destroy(); + this.scenes.forEach((scene) => scene.destroy()); + } +} /** * 场景 */ -var JlScene = /** @class */ (function (_super) { - __extends(JlScene, _super); - function JlScene(app, code, options) { - var _this = _super.call(this, options) || this; - _this.code = code; - _this.app = app; - return _this; +class JlScene extends GraphicSceneBase { + code; + app; + constructor(app, code, options) { + super(options); + this.code = code; + this.app = app; } - return JlScene; -}(GraphicSceneBase)); +} +/* eslint-disable @typescript-eslint/no-unused-vars */ +/* eslint-disable @typescript-eslint/no-empty-function */ /** * 图形绘制助手 */ -var GraphicDrawAssistant = /** @class */ (function (_super) { - __extends(GraphicDrawAssistant, _super); - function GraphicDrawAssistant(graphicApp, graphicTemplate, icon, description) { - var _this = _super.call(this, graphicTemplate.type, graphicApp) || this; - _this.__GraphicDrawAssistant = true; - _this.container = new pixi_js.Container(); - _this.escListener = new KeyListener({ - value: 'Escape', - onRelease: function () { - _this.onEsc(); - }, - }); - _this.app = graphicApp; - _this.type = graphicTemplate.type; - _this.graphicTemplate = graphicTemplate; - _this.icon = icon; - _this.description = description; - _this.app.registerGraphicTemplates(_this.graphicTemplate); - return _this; - } - GraphicDrawAssistant.prototype.onEsc = function () { - this.createAndStore(true); - }; - Object.defineProperty(GraphicDrawAssistant.prototype, "canvas", { - get: function () { - return this.app.canvas; +class GraphicDrawAssistant extends AppInteractionPlugin { + __GraphicDrawAssistant = true; + app; + type; // 图形对象类型 + description; // 描述 + icon; // 界面显示的图标 + container = new Container(); + graphicTemplate; + escListener = new KeyListener({ + value: 'Escape', + onRelease: () => { + this.onEsc(); }, - enumerable: false, - configurable: true }); - GraphicDrawAssistant.prototype.bind = function () { + onEsc() { + this.createAndStore(true); + } + constructor(graphicApp, graphicTemplate, icon, description) { + super(graphicTemplate.type, graphicApp); + this.app = graphicApp; + this.type = graphicTemplate.type; + this.graphicTemplate = graphicTemplate; + this.icon = icon; + this.description = description; + this.app.registerGraphicTemplates(this.graphicTemplate); + } + get canvas() { + return this.app.canvas; + } + bind() { this.app.drawing = true; - var canvas = this.canvas; + const canvas = this.canvas; canvas.addChild(this.container); canvas.on('mousedown', this.onLeftDown, this); canvas.on('mousemove', this.onMouseMove, this); @@ -6642,12 +5389,11 @@ var GraphicDrawAssistant = /** @class */ (function (_super) { this.app.viewport.drag({ mouseButtons: 'right', }); - }; - GraphicDrawAssistant.prototype.unbind = function () { - var _a; + } + unbind() { this.clearCache(); - var canvas = this.canvas; - if ((_a = this.container) === null || _a === void 0 ? void 0 : _a.parent) { + const canvas = this.canvas; + if (this.container?.parent) { canvas.removeChild(this.container); } canvas.off('mousedown', this.onLeftDown, this); @@ -6659,43 +5405,38 @@ var GraphicDrawAssistant = /** @class */ (function (_super) { this.app.removeKeyboardListener(this.escListener); this.app.viewport.plugins.remove('drag'); this.app.drawing = false; - }; - GraphicDrawAssistant.prototype.onLeftDown = function (e) { }; - GraphicDrawAssistant.prototype.onMouseMove = function (e) { + } + onLeftDown(e) { } + onMouseMove(e) { this.redraw(this.toCanvasCoordinates(e.global)); - }; - GraphicDrawAssistant.prototype.onLeftUp = function (e) { }; - GraphicDrawAssistant.prototype.onRightDown = function (e) { }; - GraphicDrawAssistant.prototype.onRightUp = function (e) { }; - GraphicDrawAssistant.prototype.onRightClick = function (e) { + } + onLeftUp(e) { } + onRightDown(e) { } + onRightUp(e) { } + onRightClick(e) { this.finish(); - }; + } /** * 获取下一个id */ - GraphicDrawAssistant.prototype.nextId = function () { + nextId() { return GraphicIdGenerator.next(); - }; - GraphicDrawAssistant.prototype.clearCache = function () { }; - GraphicDrawAssistant.prototype.toCanvasCoordinates = function (p) { + } + clearCache() { } + toCanvasCoordinates(p) { return this.app.toCanvasCoordinates(p); - }; + } /** * 保存创建的图形对象 */ - GraphicDrawAssistant.prototype.storeGraphic = function () { - var _a; - var graphics = []; - for (var _i = 0; _i < arguments.length; _i++) { - graphics[_i] = arguments[_i]; - } - (_a = this.app).addGraphicAndRecord.apply(_a, graphics); - }; + storeGraphic(...graphics) { + this.app.addGraphicAndRecord(...graphics); + } /** * 创建并添加到图形App */ - GraphicDrawAssistant.prototype.createAndStore = function (finish) { - var data = this.graphicTemplate.datas; + createAndStore(finish) { + const data = this.graphicTemplate.datas; data.id = this.nextId(); data.graphicType = this.graphicTemplate.type; if (!this.prepareData(data)) { @@ -6704,161 +5445,141 @@ var GraphicDrawAssistant = /** @class */ (function (_super) { } return null; } - var template = this.graphicTemplate; - var g = template.new(); + const template = this.graphicTemplate; + const g = template.new(); g.loadData(data); this.storeGraphic(g); if (finish) { this.finish(g); } return g; - }; + } /** * 绘制完成 */ - GraphicDrawAssistant.prototype.finish = function () { - var _a; - var graphics = []; - for (var _i = 0; _i < arguments.length; _i++) { - graphics[_i] = arguments[_i]; - } + finish(...graphics) { this.clearCache(); this.app.interactionPlugin(CommonMouseTool.Name).resume(); - (_a = this.app).updateSelected.apply(_a, graphics); - }; - return GraphicDrawAssistant; -}(AppInteractionPlugin)); + this.app.updateSelected(...graphics); + } +} /** * 绘制应用 */ -var JlDrawApp = /** @class */ (function (_super) { - __extends(JlDrawApp, _super); - function JlDrawApp(options) { - var _this = _super.call(this, options) || this; - _this.font = pixi_js.BitmapFont.from('coordinates', { - fontFamily: 'Roboto', - fontSize: 16, - fill: '#ff2700', - }, { chars: ['画布坐标:() 屏幕坐标:() 缩放:.,', ['0', '9']] }); - _this.coordinates = new pixi_js.BitmapText('画布坐标: (0, 0) 屏幕坐标:(0, 0)', { - fontName: 'coordinates', - }); - _this.scaleText = new pixi_js.BitmapText('缩放: 1', { - fontName: 'coordinates', - }); - _this.drawAssistants = []; - _this._drawing = false; - _this.formData = undefined; - _this.appendDrawStatesDisplay(); - // 拖拽操作记录 - _this.appOperationRecord(); - // 绑定通用键盘操作 - _this.bindKeyboardOperation(); - _this.formDataSyncListen(); - _this.debouncedFormDataUpdator = debounce(_this.doFormDataUpdate, 60); - return _this; - } - Object.defineProperty(JlDrawApp.prototype, "drawing", { - get: function () { - return this._drawing; - }, - set: function (value) { - this._drawing = value; - }, - enumerable: false, - configurable: true +class JlDrawApp extends GraphicApp { + font = BitmapFont.from('coordinates', { + fontFamily: 'Roboto', + fontSize: 16, + fill: '#ff2700', + }, { chars: ['画布坐标:() 屏幕坐标:() 缩放:.,', ['0', '9']] }); + coordinates = new BitmapText('画布坐标: (0, 0) 屏幕坐标:(0, 0)', { + fontName: 'coordinates', }); - JlDrawApp.prototype.setOptions = function (options) { - _super.prototype.setOptions.call(this, options); - }; - JlDrawApp.prototype.registerInteractionPlugin = function () { - var _this = this; - var plugins = []; - for (var _i = 0; _i < arguments.length; _i++) { - plugins[_i] = arguments[_i]; - } - plugins.forEach(function (plugin) { + scaleText = new BitmapText('缩放: 1', { + fontName: 'coordinates', + }); + drawAssistants = []; + _drawing = false; + debouncedFormDataUpdator; + get drawing() { + return this._drawing; + } + set drawing(value) { + this._drawing = value; + } + constructor(options) { + super(options); + this.appendDrawStatesDisplay(); + // 拖拽操作记录 + this.appOperationRecord(); + // 绑定通用键盘操作 + this.bindKeyboardOperation(); + this.formDataSyncListen(); + this.debouncedFormDataUpdator = debounce(this.doFormDataUpdate, 60); + } + setOptions(options) { + super.setOptions(options); + } + registerInteractionPlugin(...plugins) { + plugins.forEach((plugin) => { if (plugin instanceof GraphicDrawAssistant) { - _this.drawAssistants.push(plugin); + this.drawAssistants.push(plugin); } - _super.prototype.registerInteractionPlugin.call(_this, plugin); + super.registerInteractionPlugin(plugin); }); - }; - JlDrawApp.prototype.getDrawAssistant = function (graphicType) { - var sda = this.drawAssistants - .filter(function (da) { return da.type === graphicType; }) + } + getDrawAssistant(graphicType) { + const sda = this.drawAssistants + .filter((da) => da.type === graphicType) .pop(); if (!sda) { - throw new Error("\u672A\u627E\u5230\u56FE\u5F62\u7ED8\u5236\u52A9\u624B: ".concat(graphicType)); + throw new Error(`未找到图形绘制助手: ${graphicType}`); } return sda; - }; - JlDrawApp.prototype.appOperationRecord = function () { - var _this = this; - var dragStartDatas = []; - this.on('drag_op_start', function (e) { + } + appOperationRecord() { + let dragStartDatas = []; + this.on('drag_op_start', (e) => { // 图形拖拽,记录初始数据 if (!e.target.isCanvas()) { - dragStartDatas = _this.selectedGraphics.map(function (g) { return g.saveData(); }); + dragStartDatas = this.selectedGraphics.map((g) => g.saveData()); } }); // 图形拖拽操作监听 - this.on('drag_op_end', function () { + this.on('drag_op_end', () => { // 图形拖拽,记录操作 if (dragStartDatas.length > 0) { - var newData = _this.selectedGraphics.map(function (g) { return g.saveData(); }); - _this.opRecord.record(new GraphicDataUpdateOperation(_this, _this.selectedGraphics, dragStartDatas, newData)); + const newData = this.selectedGraphics.map((g) => g.saveData()); + this.opRecord.record(new GraphicDataUpdateOperation(this, this.selectedGraphics, dragStartDatas, newData)); dragStartDatas = []; } }); // 菜单操作 - var preMenuHandleDatas = []; - this.on('pre-menu-handle', function (menu) { + let preMenuHandleDatas = []; + this.on('pre-menu-handle', (menu) => { if (menu.name === '撤销' || menu.name === '重做') { return; } - preMenuHandleDatas = _this.selectedGraphics.map(function (g) { return g.saveData(); }); + preMenuHandleDatas = this.selectedGraphics.map((g) => g.saveData()); }); - this.on('post-menu-handle', function () { + this.on('post-menu-handle', () => { if (preMenuHandleDatas.length > 0) { - var newData = _this.selectedGraphics.map(function (g) { return g.saveData(); }); - _this.opRecord.record(new GraphicDataUpdateOperation(_this, _this.selectedGraphics, preMenuHandleDatas, newData)); + const newData = this.selectedGraphics.map((g) => g.saveData()); + this.opRecord.record(new GraphicDataUpdateOperation(this, this.selectedGraphics, preMenuHandleDatas, newData)); preMenuHandleDatas = []; } }); - }; + } /** * 绘制状态信息显示 */ - JlDrawApp.prototype.appendDrawStatesDisplay = function () { - var _this = this; + appendDrawStatesDisplay() { this.pixi.stage.addChild(this.coordinates); this.pixi.stage.addChild(this.scaleText); - var bound = this.coordinates.getLocalBounds(); + const bound = this.coordinates.getLocalBounds(); this.scaleText.position.set(bound.width + 10, 0); - this.canvas.on('mousemove', function (e) { + this.canvas.on('mousemove', (e) => { if (e.target) { - var _a = _this.toCanvasCoordinates(e.global), x = _a.x, y = _a.y; - var cpTxt = "(".concat(x, ", ").concat(y, ")"); - var tp = e.global; - var tpTxt = "(".concat(tp.x, ", ").concat(tp.y, ")"); - _this.coordinates.text = "\u753B\u5E03\u5750\u6807:".concat(cpTxt, " \u5C4F\u5E55\u5750\u6807:").concat(tpTxt); - var bound_1 = _this.coordinates.getLocalBounds(); - _this.scaleText.position.set(bound_1.width + 10, 0); + const { x, y } = this.toCanvasCoordinates(e.global); + const cpTxt = `(${x}, ${y})`; + const tp = e.global; + const tpTxt = `(${tp.x}, ${tp.y})`; + this.coordinates.text = `画布坐标:${cpTxt} 屏幕坐标:${tpTxt}`; + const bound = this.coordinates.getLocalBounds(); + this.scaleText.position.set(bound.width + 10, 0); } }); - this.viewport.on('zoomed-end', function () { - _this.scaleText.text = "\u7F29\u653E: ".concat(_this.viewport.scaled); + this.viewport.on('zoomed-end', () => { + this.scaleText.text = `缩放: ${this.viewport.scaled}`; }); - }; - JlDrawApp.prototype.bindKeyboardOperation = function () { - var _this = this; + } + bindKeyboardOperation() { this.addKeyboardListener( // Ctrl + A new KeyListener({ value: 'KeyA', - combinations: [exports.CombinationKey.Ctrl], - onPress: function (e, app) { + combinations: [CombinationKey.Ctrl], + onPress: (e, app) => { if (e.ctrlKey) { app.selectAllGraphics(); } @@ -6867,17 +5588,17 @@ var JlDrawApp = /** @class */ (function (_super) { // 复制功能 this.addKeyboardListener(new KeyListener({ value: 'KeyD', - combinations: [exports.CombinationKey.Shift], - onPress: function (e, app) { - _this.graphicCopyPlugin.init(); + combinations: [CombinationKey.Shift], + onPress: (e, app) => { + this.graphicCopyPlugin.init(); }, })); this.addKeyboardListener(new KeyListener({ // Ctrl + Z value: 'KeyZ', global: true, - combinations: [exports.CombinationKey.Ctrl], - onPress: function (e, app) { + combinations: [CombinationKey.Ctrl], + onPress: (e, app) => { app.opRecord.undo(); }, })); @@ -6885,79 +5606,79 @@ var JlDrawApp = /** @class */ (function (_super) { // Ctrl + Shift + Z value: 'KeyZ', global: true, - combinations: [exports.CombinationKey.Ctrl, exports.CombinationKey.Shift], - onPress: function (e, app) { + combinations: [CombinationKey.Ctrl, CombinationKey.Shift], + onPress: (e, app) => { app.opRecord.redo(); }, })); this.addKeyboardListener(new KeyListener({ value: 'Delete', - onPress: function (e, app) { - app.deleteGraphicAndRecord.apply(app, app.selectedGraphics); + onPress: (e, app) => { + app.deleteGraphicAndRecord(...app.selectedGraphics); }, })); this.addKeyboardListener(new KeyListener({ value: 'ArrowUp', pressTriggerAsOriginalEvent: true, - onPress: function (e, app) { + onPress: (e, app) => { updateGraphicPositionOnKeyboardEvent(app, UP); }, - onRelease: function (e, app) { + onRelease: (e, app) => { recordGraphicMoveOperation(app); }, })); this.addKeyboardListener(new KeyListener({ value: 'ArrowDown', pressTriggerAsOriginalEvent: true, - onPress: function (e, app) { + onPress: (e, app) => { updateGraphicPositionOnKeyboardEvent(app, DOWN); }, - onRelease: function (e, app) { + onRelease: (e, app) => { recordGraphicMoveOperation(app); }, })); this.addKeyboardListener(new KeyListener({ value: 'ArrowLeft', pressTriggerAsOriginalEvent: true, - onPress: function (e, app) { + onPress: (e, app) => { updateGraphicPositionOnKeyboardEvent(app, LEFT); }, - onRelease: function (e, app) { + onRelease: (e, app) => { recordGraphicMoveOperation(app); }, })); this.addKeyboardListener(new KeyListener({ value: 'ArrowRight', pressTriggerAsOriginalEvent: true, - onPress: function (e, app) { + onPress: (e, app) => { updateGraphicPositionOnKeyboardEvent(app, RIGHT); }, - onRelease: function (e, app) { + onRelease: (e, app) => { recordGraphicMoveOperation(app); }, })); - }; + } /** * 图形对象存储处理,默认添加图形交互 * @param graphic */ - JlDrawApp.prototype.beforeGraphicStore = function (graphic) { - var _this = this; + beforeGraphicStore(graphic) { graphic.eventMode = 'static'; graphic.selectable = true; graphic.draggable = true; - graphic.on('repaint', function () { - _this.handleFormDataUpdate(graphic); + graphic.on('repaint', () => { + this.handleFormDataUpdate(graphic); }); - graphic.on('transformend', function () { - _this.handleFormDataUpdate(graphic); + graphic.on('transformend', () => { + this.handleFormDataUpdate(graphic); }); - }; + } + formData = undefined; /** * 绑定form表单对象 * @param form */ - JlDrawApp.prototype.bindFormData = function (form) { + bindFormData(form) { this.formData = form; if (this.formData && this.selectedGraphics.length == 1) { if (this.formData.graphicType == this.selectedGraphics[0].type) { @@ -6967,74 +5688,72 @@ var JlDrawApp = /** @class */ (function (_super) { this.formData = undefined; } } - }; + } /** * 移除form绑定 * @param form */ - JlDrawApp.prototype.unbindFormData = function (form) { + unbindFormData(form) { if (this.formData == form) { this.formData = undefined; } - }; - JlDrawApp.prototype.formDataSyncListen = function () { - var _this = this; - this.on('graphicselected', function () { - if (_this.selectedGraphics.length == 1) { - _this.handleFormDataUpdate(_this.selectedGraphics[0]); + } + formDataSyncListen() { + this.on('graphicselected', () => { + if (this.selectedGraphics.length == 1) { + this.handleFormDataUpdate(this.selectedGraphics[0]); } }); - }; + } /** * 处理表单数据更新(使用debounce限流) */ - JlDrawApp.prototype.handleFormDataUpdate = function (g) { + handleFormDataUpdate(g) { this.debouncedFormDataUpdator(this, g); - }; - JlDrawApp.prototype.doFormDataUpdate = function (g) { + } + doFormDataUpdate(g) { if (this.selectedGraphics.length > 1) return; if (this.formData && g.type === this.formData.graphicType) { this.formData.copyFrom(g.saveData()); } - }; - JlDrawApp.prototype.updateCanvasAndRecord = function (data) { - var old = this.canvas.properties.clone(); + } + updateCanvasAndRecord(data) { + const old = this.canvas.properties.clone(); this.canvas.update(data); - var newVal = this.canvas.properties.clone(); + const newVal = this.canvas.properties.clone(); this.opRecord.record(new UpdateCanvasOperation(this, this.canvas, old, newVal)); - }; - JlDrawApp.prototype.updateGraphicAndRecord = function (g, data) { - var old = g.saveData(); + } + updateGraphicAndRecord(g, data) { + const old = g.saveData(); g.updateData(data); - var newVal = g.saveData(); + const newVal = g.saveData(); this.opRecord.record(new GraphicDataUpdateOperation(this, [g], [old], [newVal])); - }; - return JlDrawApp; -}(GraphicApp)); -var dragStartDatas = []; + } +} +let dragStartDatas = []; function handleArrowKeyMoveGraphics(app, handler) { if (app.selectedGraphics.length === 1 && app.selectedGraphics[0].hasSelectedChilds()) { - recursiveChildren(app.selectedGraphics[0], function (child) { + recursiveChildren(app.selectedGraphics[0], (child) => { if (child.selected && child.draggable) { handler(child); } }); } else { - app.selectedGraphics.forEach(function (g) { + app.selectedGraphics.forEach((g) => { handler(g); }); } } function updateGraphicPositionOnKeyboardEvent(app, dp) { - var dragStart = false; + let dragStart = false; if (dragStartDatas.length === 0) { - dragStartDatas = app.selectedGraphics.map(function (g) { return g.saveData(); }); + dragStartDatas = app.selectedGraphics.map((g) => g.saveData()); dragStart = true; } - handleArrowKeyMoveGraphics(app, function (g) { + handleArrowKeyMoveGraphics(app, (g) => { if (dragStart) { g.shiftStartPoint = g.position.clone(); g.emit('transformstart', GraphicTransformEvent.shift(g, ShiftData.new(g.shiftStartPoint))); @@ -7054,9 +5773,9 @@ function updateGraphicPositionOnKeyboardEvent(app, dp) { function recordGraphicMoveOperation(app) { if (dragStartDatas.length > 0 && dragStartDatas.length === app.selectedGraphics.length) { - var newData = app.selectedGraphics.map(function (g) { return g.saveData(); }); + const newData = app.selectedGraphics.map((g) => g.saveData()); app.opRecord.record(new GraphicDataUpdateOperation(app, app.selectedGraphics, dragStartDatas, newData)); - handleArrowKeyMoveGraphics(app, function (g) { + handleArrowKeyMoveGraphics(app, (g) => { if (g.shiftStartPoint) { g.emit('transformend', GraphicTransformEvent.shift(g, ShiftData.new(g.shiftStartPoint, g.position.clone()))); } @@ -7083,20 +5802,20 @@ function newDrawApp(options) { } //基础图形对象扩展 -pixi_js.DisplayObject.prototype._selectable = false; //是否可选中 -pixi_js.DisplayObject.prototype._selected = false; -pixi_js.DisplayObject.prototype._childEdit = false; -pixi_js.DisplayObject.prototype._transformSave = false; -pixi_js.DisplayObject.prototype._assistantAppendMap = null; -pixi_js.DisplayObject.prototype._draggable = false; -pixi_js.DisplayObject.prototype._shiftStartPoint = null; -pixi_js.DisplayObject.prototype._shiftLastPoint = null; -pixi_js.DisplayObject.prototype._scalable = false; -pixi_js.DisplayObject.prototype._keepAspectRatio = true; -pixi_js.DisplayObject.prototype._rotatable = false; -Object.defineProperties(pixi_js.DisplayObject.prototype, { +DisplayObject.prototype._selectable = false; //是否可选中 +DisplayObject.prototype._selected = false; +DisplayObject.prototype._childEdit = false; +DisplayObject.prototype._transformSave = false; +DisplayObject.prototype._assistantAppendMap = null; +DisplayObject.prototype._draggable = false; +DisplayObject.prototype._shiftStartPoint = null; +DisplayObject.prototype._shiftLastPoint = null; +DisplayObject.prototype._scalable = false; +DisplayObject.prototype._keepAspectRatio = true; +DisplayObject.prototype._rotatable = false; +Object.defineProperties(DisplayObject.prototype, { assistantAppendMap: { - get: function () { + get() { if (this._assistantAppendMap == null) { this._assistantAppendMap = new Map(); } @@ -7104,89 +5823,89 @@ Object.defineProperties(pixi_js.DisplayObject.prototype, { }, }, selectable: { - get: function () { + get() { return this._selectable; }, - set: function (value) { + set(value) { this._selectable = value; }, }, selected: { - get: function () { + get() { return this._selected; }, - set: function (v) { + set(v) { this._selected = v; }, }, childEdit: { - get: function () { + get() { return this._childEdit; }, - set: function (v) { + set(v) { this._childEdit = v; }, }, transformSave: { - get: function () { + get() { return this._transformSave; }, - set: function (v) { + set(v) { this._transformSave = v; }, }, draggable: { - get: function () { + get() { return this._draggable; }, - set: function (v) { + set(v) { this._draggable = v; }, }, shiftStartPoint: { - get: function () { + get() { return this._shiftStartPoint; }, - set: function (v) { + set(v) { this._shiftStartPoint = v; }, }, shiftLastPoint: { - get: function () { + get() { return this._shiftLastPoint; }, - set: function (v) { + set(v) { this._shiftLastPoint = v; }, }, scalable: { - get: function () { + get() { return this._scalable; }, - set: function (v) { + set(v) { this._scalable = v; }, }, keepAspectRatio: { - get: function () { + get() { return this._keepAspectRatio; }, - set: function (v) { + set(v) { this._keepAspectRatio = v; }, }, rotatable: { - get: function () { + get() { return this._rotatable; }, - set: function (v) { + set(v) { this._rotatable = v; }, }, worldAngle: { - get: function () { - var angle = this.angle; - var parent = this.parent; + get() { + let angle = this.angle; + let parent = this.parent; while (parent != undefined && parent != null) { angle += parent.angle; parent = parent.parent; @@ -7199,16 +5918,16 @@ Object.defineProperties(pixi_js.DisplayObject.prototype, { }, }, }); -pixi_js.DisplayObject.prototype.getAllParentScaled = +DisplayObject.prototype.getAllParentScaled = function getAllParentScaled() { - var scaled = new pixi_js.Point(1, 1); - recursiveParents(this, function (parent) { + const scaled = new Point(1, 1); + recursiveParents(this, (parent) => { scaled.x *= parent.scale.x; scaled.y *= parent.scale.y; }); return scaled; }; -pixi_js.DisplayObject.prototype.getPositionOnCanvas = +DisplayObject.prototype.getPositionOnCanvas = function getPositionOnCanvas() { if (this.parent.isCanvas()) { return this.position; @@ -7217,96 +5936,81 @@ pixi_js.DisplayObject.prototype.getPositionOnCanvas = return this.parent.localToCanvasPoint(this.position); } }; -pixi_js.DisplayObject.prototype.updatePositionByCanvasPosition = +DisplayObject.prototype.updatePositionByCanvasPosition = function updatePositionByCanvasPosition(p) { if (this.parent.isCanvas()) { this.position.copyFrom(p); } else { - var localPosition = this.parent.canvasToLocalPoint(p); + const localPosition = this.parent.canvasToLocalPoint(p); this.position.copyFrom(localPosition); } }; -pixi_js.DisplayObject.prototype.saveTransform = function saveTransform() { +DisplayObject.prototype.saveTransform = function saveTransform() { return GraphicTransform.fromObject(this); }; -pixi_js.DisplayObject.prototype.loadTransform = function loadTransform(transfrom) { +DisplayObject.prototype.loadTransform = function loadTransform(transfrom) { this.position.copyFrom(transfrom.position); this.scale.copyFrom(transfrom.scale); this.rotation = transfrom.rotation; this.skew.copyFrom(transfrom.skew); }; -pixi_js.DisplayObject.prototype.isChild = function isChild(obj) { - return recursiveFindChild(this, function (child) { return child == obj; }) != null; +DisplayObject.prototype.isChild = function isChild(obj) { + return recursiveFindChild(this, (child) => child == obj) != null; }; -pixi_js.DisplayObject.prototype.isParent = function isParent(obj) { - return recursiveFindParent(this, function (parent) { return parent == obj; }) != null; +DisplayObject.prototype.isParent = function isParent(obj) { + return recursiveFindParent(this, (parent) => parent == obj) != null; }; -pixi_js.DisplayObject.prototype.isAssistantAppend = +DisplayObject.prototype.isAssistantAppend = function isAssistantAppend() { - return (recursiveFindParent(this, function (parent) { + return (recursiveFindParent(this, (parent) => { return parent.name === AppConsts.AssistantAppendsName; }) != null); }; -pixi_js.DisplayObject.prototype.addAssistantAppend = function addAssistantAppend() { - var _this = this; - var appends = []; - for (var _i = 0; _i < arguments.length; _i++) { - appends[_i] = arguments[_i]; - } - appends.forEach(function (append) { +DisplayObject.prototype.addAssistantAppend = function addAssistantAppend(...appends) { + appends.forEach((append) => { if (append.name == null || append.name.trim() == '') { throw new Error('辅助附加name不能为空'); } - _this.assistantAppendMap.set(append.name, append); - _this.getCanvas().addAssistantAppends(append); + this.assistantAppendMap.set(append.name, append); + this.getCanvas().addAssistantAppends(append); }); }; -pixi_js.DisplayObject.prototype.getAssistantAppend = function getAssistantAppend(name) { +DisplayObject.prototype.getAssistantAppend = function getAssistantAppend(name) { return this.assistantAppendMap.get(name); }; -pixi_js.DisplayObject.prototype.removeAssistantAppend = function removeAssistantAppend() { - var _this = this; - var appends = []; - for (var _i = 0; _i < arguments.length; _i++) { - appends[_i] = arguments[_i]; - } - appends.forEach(function (append) { +DisplayObject.prototype.removeAssistantAppend = function removeAssistantAppend(...appends) { + appends.forEach((append) => { if (append.name) { - _this.removeAssistantAppendByName(append.name); + this.removeAssistantAppendByName(append.name); } }); }; -pixi_js.DisplayObject.prototype.removeAssistantAppendByName = - function removeAssistantAppendByName() { - var _this = this; - var names = []; - for (var _i = 0; _i < arguments.length; _i++) { - names[_i] = arguments[_i]; - } - names.forEach(function (name) { - var append = _this.getAssistantAppend(name); +DisplayObject.prototype.removeAssistantAppendByName = + function removeAssistantAppendByName(...names) { + names.forEach((name) => { + const append = this.getAssistantAppend(name); if (append) { - _this.getCanvas().removeAssistantAppends(append); - _this.assistantAppendMap.delete(name); + this.getCanvas().removeAssistantAppends(append); + this.assistantAppendMap.delete(name); append.destroy(); } }); }; -pixi_js.DisplayObject.prototype.removeAllAssistantAppend = +DisplayObject.prototype.removeAllAssistantAppend = function removeAllAssistantAppend() { if (this._assistantAppendMap != null) { - this.assistantAppendMap.forEach(function (append) { + this.assistantAppendMap.forEach((append) => { append.getCanvas().removeAssistantAppends(append); }); this.assistantAppendMap.clear(); } }; -pixi_js.DisplayObject.prototype.isGraphic = function isGraphic() { +DisplayObject.prototype.isGraphic = function isGraphic() { return Object.hasOwn(this, '__JlGraphic'); }; -pixi_js.DisplayObject.prototype.getGraphic = function getGraphic() { - var graphic = this; +DisplayObject.prototype.getGraphic = function getGraphic() { + let graphic = this; while (graphic && !Object.hasOwn(graphic, '__JlGraphic')) { graphic = graphic.parent; } @@ -7315,14 +6019,14 @@ pixi_js.DisplayObject.prototype.getGraphic = function getGraphic() { } return null; }; -pixi_js.DisplayObject.prototype.isGraphicChild = function isGraphicChild() { - var g = this.getGraphic(); +DisplayObject.prototype.isGraphicChild = function isGraphicChild() { + const g = this.getGraphic(); return g != null && !this.isAssistantAppend() && g.isChild(this); }; -pixi_js.DisplayObject.prototype.onAddToCanvas = function onAddToCanvas(_canvas) { }; -pixi_js.DisplayObject.prototype.onRemoveFromCanvas = function onRemoveFromCanvas(_canvas) { }; -pixi_js.DisplayObject.prototype.isInCanvas = function isInCanvas() { - var graphic = this; +DisplayObject.prototype.onAddToCanvas = function onAddToCanvas(_canvas) { }; +DisplayObject.prototype.onRemoveFromCanvas = function onRemoveFromCanvas(_canvas) { }; +DisplayObject.prototype.isInCanvas = function isInCanvas() { + let graphic = this; while (graphic && !Object.hasOwn(graphic, '__JlCanvas')) { graphic = graphic.parent; } @@ -7331,103 +6035,83 @@ pixi_js.DisplayObject.prototype.isInCanvas = function isInCanvas() { } return false; }; -pixi_js.DisplayObject.prototype.getCanvas = function getCanvas() { - var graphic = this; +DisplayObject.prototype.getCanvas = function getCanvas() { + let graphic = this; while (graphic && !Object.hasOwn(graphic, '__JlCanvas')) { graphic = graphic.parent; } if (graphic) { return graphic; } - throw new Error("\u56FE\u5F62".concat(this.name, "\u4E0D\u5728\u753B\u5E03\u4E2D")); + throw new Error(`图形${this.name}不在画布中`); }; -pixi_js.DisplayObject.prototype.isCanvas = function isCanvas() { +DisplayObject.prototype.isCanvas = function isCanvas() { return Object.hasOwn(this, '__JlCanvas'); }; -pixi_js.DisplayObject.prototype.getViewport = function getViewport() { - var canvas = this.getCanvas(); +DisplayObject.prototype.getViewport = function getViewport() { + const canvas = this.getCanvas(); return canvas.parent; }; -pixi_js.DisplayObject.prototype.getGraphicApp = function getGraphicApp() { - var canvas = this.getCanvas(); +DisplayObject.prototype.getGraphicApp = function getGraphicApp() { + const canvas = this.getCanvas(); return canvas.scene.app; }; -pixi_js.DisplayObject.prototype.localToCanvasPoint = function localToCanvasPoint(p) { +DisplayObject.prototype.localToCanvasPoint = function localToCanvasPoint(p) { return this.getViewport().toWorld(this.toGlobal(p)); }; -pixi_js.DisplayObject.prototype.localToCanvasPoints = function localToCanvasPoints() { - var _this = this; - var points = []; - for (var _i = 0; _i < arguments.length; _i++) { - points[_i] = arguments[_i]; - } - return points.map(function (p) { return _this.localToCanvasPoint(p); }); +DisplayObject.prototype.localToCanvasPoints = function localToCanvasPoints(...points) { + return points.map((p) => this.localToCanvasPoint(p)); }; -pixi_js.DisplayObject.prototype.canvasToLocalPoint = function canvasToLocalPoint(p) { +DisplayObject.prototype.canvasToLocalPoint = function canvasToLocalPoint(p) { return this.toLocal(this.getViewport().toScreen(p)); }; -pixi_js.DisplayObject.prototype.canvasToLocalPoints = function canvasToLocalPoints() { - var _this = this; - var points = []; - for (var _i = 0; _i < arguments.length; _i++) { - points[_i] = arguments[_i]; - } - return points.map(function (p) { return _this.canvasToLocalPoint(p); }); +DisplayObject.prototype.canvasToLocalPoints = function canvasToLocalPoints(...points) { + return points.map((p) => this.canvasToLocalPoint(p)); }; -pixi_js.DisplayObject.prototype.localToScreenPoint = function localToScreenPoint(p) { +DisplayObject.prototype.localToScreenPoint = function localToScreenPoint(p) { return this.toGlobal(p); }; -pixi_js.DisplayObject.prototype.localToScreenPoints = function localToScreenPoints() { - var _this = this; - var points = []; - for (var _i = 0; _i < arguments.length; _i++) { - points[_i] = arguments[_i]; - } - return points.map(function (p) { return _this.toGlobal(p); }); +DisplayObject.prototype.localToScreenPoints = function localToScreenPoints(...points) { + return points.map((p) => this.toGlobal(p)); }; -pixi_js.DisplayObject.prototype.screenToLocalPoint = function screenToLocalPoint(p) { +DisplayObject.prototype.screenToLocalPoint = function screenToLocalPoint(p) { return this.toLocal(p); }; -pixi_js.DisplayObject.prototype.screenToLocalPoints = function screenToLocalPoints() { - var _this = this; - var points = []; - for (var _i = 0; _i < arguments.length; _i++) { - points[_i] = arguments[_i]; - } - return points.map(function (p) { return _this.toLocal(p); }); +DisplayObject.prototype.screenToLocalPoints = function screenToLocalPoints(...points) { + return points.map((p) => this.toLocal(p)); }; -pixi_js.DisplayObject.prototype.localBoundsToCanvasPoints = +DisplayObject.prototype.localBoundsToCanvasPoints = function localBoundsToCanvasPoints() { - var rect = this.getLocalBounds(); - var pps = convertRectangleToPolygonPoints(rect); - return this.localToCanvasPoints.apply(this, pps); + const rect = this.getLocalBounds(); + const pps = convertRectangleToPolygonPoints(rect); + return this.localToCanvasPoints(...pps); }; // 扩展pixijs图形对象,添加自定义绘制贝塞尔曲线,可自定义分段数 -pixi_js.Graphics.prototype.drawBezierCurve = function drawBezierCurve(p1, p2, cp1, cp2, segmentsCount) { - var fromX = p1.x; - var fromY = p1.y; - var n = segmentsCount; - var dt = 0; - var dt2 = 0; - var dt3 = 0; - var t2 = 0; - var t3 = 0; - var cpX = cp1.x; - var cpY = cp1.y; - var cpX2 = cp2.x; - var cpY2 = cp2.y; - var toX = p2.x; - var toY = p2.y; +Graphics.prototype.drawBezierCurve = function drawBezierCurve(p1, p2, cp1, cp2, segmentsCount) { + const fromX = p1.x; + const fromY = p1.y; + const n = segmentsCount; + let dt = 0; + let dt2 = 0; + let dt3 = 0; + let t2 = 0; + let t3 = 0; + const cpX = cp1.x; + const cpY = cp1.y; + const cpX2 = cp2.x; + const cpY2 = cp2.y; + const toX = p2.x; + const toY = p2.y; this.moveTo(p1.x, p1.y); - for (var i = 1, j = 0; i <= n; ++i) { + for (let i = 1, j = 0; i <= n; ++i) { j = i / n; dt = 1 - j; dt2 = dt * dt; dt3 = dt2 * dt; t2 = j * j; t3 = t2 * j; - var px = dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX; - var py = dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY; + const px = dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX; + const py = dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY; this.lineTo(px, py); } return this; @@ -7435,151 +6119,150 @@ pixi_js.Graphics.prototype.drawBezierCurve = function drawBezierCurve(p1, p2, cp /** * 图形变换数据 */ -var GraphicTransform = /** @class */ (function () { - function GraphicTransform(position, scale, rotation, skew) { +class GraphicTransform { + position; + scale; + rotation; + skew; + constructor(position, scale, rotation, skew) { this.position = position; this.scale = scale; this.rotation = rotation; this.skew = skew; } - GraphicTransform.default = function () { - return new GraphicTransform(new pixi_js.Point(0, 0), new pixi_js.Point(1, 1), 0, new pixi_js.Point(0, 0)); - }; - GraphicTransform.fromObject = function (obj) { + static default() { + return new GraphicTransform(new Point(0, 0), new Point(1, 1), 0, new Point(0, 0)); + } + static fromObject(obj) { return new GraphicTransform(obj.position.clone(), obj.scale.clone(), obj.rotation, obj.skew.clone()); - }; - GraphicTransform.from = function (transform) { + } + static from(transform) { if (transform) { - return new GraphicTransform(new pixi_js.Point(transform.position.x, transform.position.y), new pixi_js.Point(transform.scale.x, transform.scale.y), transform.rotation, new pixi_js.Point(transform.skew.x, transform.skew.y)); + return new GraphicTransform(new Point(transform.position.x, transform.position.y), new Point(transform.scale.x, transform.scale.y), transform.rotation, new Point(transform.skew.x, transform.skew.y)); } return GraphicTransform.default(); - }; - return GraphicTransform; -}()); + } +} /** * 图形子元素变换 */ -var ChildTransform = /** @class */ (function () { - function ChildTransform(name, transform) { +class ChildTransform { + name; + transform; + constructor(name, transform) { this.name = name; this.transform = transform; } - ChildTransform.fromChild = function (child) { - var _a; + static fromChild(child) { if (child.name == null || child.name == undefined || child.name.trim() == '') { - throw new Error("\u56FE\u5F62type=".concat((_a = child.getGraphic()) === null || _a === void 0 ? void 0 : _a.type, "\u7684\u5B50\u5143\u7D20").concat(child, "name\u4E3A\u7A7A\uFF0C\u4F46\u8BBE\u7F6E\u4E3A\u9700\u8981\u4FDD\u5B58\u53D8\u6362\u6570\u636E")); + throw new Error(`图形type=${child.getGraphic()?.type}的子元素${child}name为空,但设置为需要保存变换数据`); } return new ChildTransform(child.name, GraphicTransform.fromObject(child)); - }; - ChildTransform.from = function (ct) { + } + static from(ct) { return new ChildTransform(ct.name, GraphicTransform.from(ct.transform)); - }; - return ChildTransform; -}()); -var GraphicAnimation = /** @class */ (function () { - function GraphicAnimation(options) { + } +} +class GraphicAnimation { + options; + _running; + /** + * 倍速 + */ + _xSpeed; + constructor(options) { this.options = options; this._running = false; this._xSpeed = 1; } - GraphicAnimation.init = function (options) { + static init(options) { return new GraphicAnimation(options); - }; - GraphicAnimation.prototype.pause = function () { + } + pause() { this._running = false; return this; - }; - GraphicAnimation.prototype.resume = function () { + } + resume() { this._running = true; return this; - }; - Object.defineProperty(GraphicAnimation.prototype, "name", { - get: function () { - return this.options.name; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(GraphicAnimation.prototype, "running", { - get: function () { - return this._running; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(GraphicAnimation.prototype, "xSpeed", { - get: function () { - return this._xSpeed; - }, - set: function (v) { - this._xSpeed = v; - }, - enumerable: false, - configurable: true - }); - GraphicAnimation.prototype.run = function (dt) { + } + get name() { + return this.options.name; + } + get running() { + return this._running; + } + get xSpeed() { + return this._xSpeed; + } + set xSpeed(v) { + this._xSpeed = v; + } + run(dt) { if (this.options.run) { this.options.run(dt * this.xSpeed); } return this; - }; - return GraphicAnimation; -}()); + } +} /** * 图形对象基类 */ -var JlGraphic = /** @class */ (function (_super) { - __extends(JlGraphic, _super); - function JlGraphic(type) { - var _this = _super.call(this) || this; - _this.__JlGraphic = true; - _this._id = ''; // 图形的唯一标识,不具有业务意义,唯一,不可重复,可用做图形数据关联。 - _this._code = ''; // 业务编号/名称,用于标识图形对象,具有业务意义 - _this.type = type; - _this.draggable = false; - _this.filters; - return _this; +class JlGraphic extends Container { + __JlGraphic = true; + type; // 图形类型 + _id = ''; // 图形的唯一标识,不具有业务意义,唯一,不可重复,可用做图形数据关联。 + _code = ''; // 业务编号/名称,用于标识图形对象,具有业务意义 + _datas; // 图形数据 + _states; // 图形状态数据 + _relationManage; // 图形关系管理 + _queryStore; // 图形对象查询仓库 + constructor(type) { + super(); + this.type = type; + this.draggable = false; + this.filters; } /** * 添加图形动画,只有在画布上才能添加 * @param animation */ - JlGraphic.prototype.addAnimation = function (animation) { - var app = this.getGraphicApp(); + addAnimation(animation) { + const app = this.getGraphicApp(); app.animationManager.registerAnimation(this, animation); - }; - JlGraphic.prototype.removeAnimation = function (name) { - var app = this.getGraphicApp(); + } + removeAnimation(name) { + const app = this.getGraphicApp(); app.animationManager.unregisterAnimation(this, name); - }; - JlGraphic.prototype.animation = function (name) { - var app = this.getGraphicApp(); + } + animation(name) { + const app = this.getGraphicApp(); return app.animationManager.animation(this, name); - }; - JlGraphic.prototype.removeAllAnimation = function () { - var app = this.getGraphicApp(); + } + removeAllAnimation() { + const app = this.getGraphicApp(); app.animationManager.unregisterGraphicAnimations(this); - }; + } /** * 更新选中状态 * @param selected * @returns 是否更新 */ - JlGraphic.prototype.updateSelected = function (selected) { + updateSelected(selected) { if (this.selected !== selected) { this.selected = selected; this.fireSelected(); return true; } return false; - }; - JlGraphic.prototype.invertSelected = function () { + } + invertSelected() { this.selected = !this.selected; this.fireSelected(); - }; - JlGraphic.prototype.fireSelected = function () { + } + fireSelected() { if (this.selected) { this.emit('selected', this); } @@ -7588,236 +6271,218 @@ var JlGraphic = /** @class */ (function (_super) { this.removeAllChildSelected(); this.emit('unselected', this); } - var app = this.getGraphicApp(); + const app = this.getGraphicApp(); if (app) { app.emit('graphicselectedchange', this, this.selected); } - }; - JlGraphic.prototype.hasSelectedChilds = function () { - return (recursiveFindChild(this, function (child) { + } + hasSelectedChilds() { + return (recursiveFindChild(this, (child) => { if (child.selected) { return true; } return false; }) != null); - }; - JlGraphic.prototype.setChildSelected = function (child) { + } + setChildSelected(child) { if (child.isGraphicChild() && child.selectable) { this.removeAllChildSelected(); child.selected = true; this.fireChildSelected(child); } return false; - }; - JlGraphic.prototype.invertChildSelected = function (child) { + } + invertChildSelected(child) { if (child.isGraphicChild() && child.selectable) { child.selected = !child.selected; this.fireChildSelected(child); } return false; - }; - JlGraphic.prototype.removeAllChildSelected = function () { - var _this = this; - recursiveChildren(this, function (child) { + } + removeAllChildSelected() { + recursiveChildren(this, (child) => { if (child.selected) { child.selected = false; - _this.fireChildSelected(child); + this.fireChildSelected(child); } }); - }; - JlGraphic.prototype.fireChildSelected = function (child) { - var selected = child.selected; + } + fireChildSelected(child) { + const selected = child.selected; if (selected) { this.emit('childselected', child); } else { this.emit('childunselected', child); } - var app = this.getGraphicApp(); + const app = this.getGraphicApp(); if (app) { app.emit('graphicchildselectedchange', child, selected); } - }; - JlGraphic.prototype.exitChildEdit = function () { + } + exitChildEdit() { this.childEdit = false; this.removeAllChildSelected(); - }; + } /** * 是否此对象id/code */ - JlGraphic.prototype.isIdOrCode = function (s) { + isIdOrCode(s) { return this.id === s || this.code === s; - }; - Object.defineProperty(JlGraphic.prototype, "id", { - /** - * 获取图形id,如果图形数据对象存在,则返回图形数据对象id - */ - get: function () { - if (this._datas) { - return this._datas.id; - } - return this._id; - }, - /** - * 设置图形id,如果图形数据存在,则同时设置图形数据id - */ - set: function (v) { - this._id = v; - if (this._datas) { - this._datas.id = v; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(JlGraphic.prototype, "code", { - /** - * 获取图形业务code,如果业务code在图形数据或图形状态中,则需要重写此方法 - */ - get: function () { - return this._code; - }, - /** - * 设置图形业务code,如果业务code在图形数据或图形状态中,则需要重写此方法 - */ - set: function (v) { - this._code = v; - }, - enumerable: false, - configurable: true - }); - JlGraphic.prototype.getDatas = function () { + } + /** + * 获取图形id,如果图形数据对象存在,则返回图形数据对象id + */ + get id() { + if (this._datas) { + return this._datas.id; + } + return this._id; + } + /** + * 设置图形id,如果图形数据存在,则同时设置图形数据id + */ + set id(v) { + this._id = v; + if (this._datas) { + this._datas.id = v; + } + } + /** + * 获取图形业务code,如果业务code在图形数据或图形状态中,则需要重写此方法 + */ + get code() { + return this._code; + } + /** + * 设置图形业务code,如果业务code在图形数据或图形状态中,则需要重写此方法 + */ + set code(v) { + this._code = v; + } + getDatas() { if (this._datas) { return this._datas; } - throw new Error("id=".concat(this.id, ",type=").concat(this.type, "\u7684\u56FE\u5F62\u6CA1\u6709\u6570\u636E")); - }; - JlGraphic.prototype.getStates = function () { + throw new Error(`id=${this.id},type=${this.type}的图形没有数据`); + } + getStates() { if (this._states) { return this._states; } - throw new Error("id=".concat(this.id, ",type=").concat(this.type, "\u7684\u7684\u56FE\u5F62\u6CA1\u6709\u72B6\u6001")); - }; - Object.defineProperty(JlGraphic.prototype, "queryStore", { - get: function () { - if (this._queryStore) { - return this._queryStore; - } - throw new Error("type=".concat(this.type, "\u7684\u56FE\u5F62\u6CA1\u6709QueryStore")); - }, - set: function (v) { - this._queryStore = v; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(JlGraphic.prototype, "relationManage", { - get: function () { - if (this._relationManage) { - return this._relationManage; - } - throw new Error("type=".concat(this.type, "\u7684\u56FE\u5F62\u6CA1\u6709\u5173\u7CFB\u7BA1\u7406")); - }, - set: function (v) { - this._relationManage = v; - }, - enumerable: false, - configurable: true - }); + throw new Error(`id=${this.id},type=${this.type}的的图形没有状态`); + } + get queryStore() { + if (this._queryStore) { + return this._queryStore; + } + throw new Error(`type=${this.type}的图形没有QueryStore`); + } + set queryStore(v) { + this._queryStore = v; + } + get relationManage() { + if (this._relationManage) { + return this._relationManage; + } + throw new Error(`type=${this.type}的图形没有关系管理`); + } + set relationManage(v) { + this._relationManage = v; + } /** * 构建图形关系 * @param g */ - JlGraphic.prototype.buildRelation = function () { }; + buildRelation() { } /** * 从数据加载恢复图形关系 */ - JlGraphic.prototype.loadRelations = function () { }; + loadRelations() { } /** * 获取当前图形的所有图形关系 * @returns */ - JlGraphic.prototype.getAllRelations = function () { + getAllRelations() { return this.relationManage.getRelationsOfGraphic(this); - }; + } /** * 获取当前图形的所有指定类型图形关系 * @param type * @returns */ - JlGraphic.prototype.queryRelationByType = function (type) { + queryRelationByType(type) { return this.relationManage.getRelationsOfGraphicAndOtherType(this, type); - }; + } /** * 删除当前图形关联的指定类型的关系 * @param type */ - JlGraphic.prototype.deleteRelationByType = function (type) { + deleteRelationByType(type) { this.relationManage.deleteRelationOfGraphicAndOtherType(this, type); - }; + } /** * 构建并保存关系数据到datas中 */ - JlGraphic.prototype.saveRelations = function () { }; + saveRelations() { } /** * 保存数据,复制,非原始数据 * @returns */ - JlGraphic.prototype.saveData = function () { + saveData() { this.getDatas().graphicType = this.type; this.getDatas().transform = GraphicTransform.fromObject(this); this.getDatas().childTransforms = this.buildChildTransforms(); this.saveRelations(); return this.getDatas().clone(); - }; + } /** * 构建子元素变换列表 * @returns */ - JlGraphic.prototype.buildChildTransforms = function () { - var childTransforms = []; - recursiveChildren(this, function (child) { + buildChildTransforms() { + const childTransforms = []; + recursiveChildren(this, (child) => { if (child.transformSave) { childTransforms.push(ChildTransform.fromChild(child)); } }); return childTransforms; - }; + } /** * 加载数据 * @param data */ - JlGraphic.prototype.loadData = function (data) { + loadData(data) { if (data.graphicType !== this.type) { - throw new Error("\u4E0D\u540C\u7684\u56FE\u5F62\u7C7B\u578B,\u8BF7\u68C0\u67E5\u6570\u636E\u662F\u5426\u6B63\u5E38: data.graphicType=\"".concat(data.graphicType, ", type=\"").concat(this.type)); + throw new Error(`不同的图形类型,请检查数据是否正常: data.graphicType="${data.graphicType}, type="${this.type}`); } this._datas = data; this.loadTransformFrom(data); - }; - JlGraphic.prototype.loadTransformFrom = function (data) { - var _this = this; + } + loadTransformFrom(data) { if (data.transform) { this.loadTransform(data.transform); } if (data.childTransforms) { - data.childTransforms.forEach(function (ct) { - var child = _this.getChildByName(ct.name, true); + data.childTransforms.forEach((ct) => { + const child = this.getChildByName(ct.name, true); if (child) { child.loadTransform(ct.transform); } }); } - }; + } /** * 更新图形数据 * @param data * @returns */ - JlGraphic.prototype.updateData = function (data) { - var update = false; + updateData(data) { + let update = false; if (!this.getDatas().eq(data)) { update = true; - var old = this.getDatas().clone(); + const old = this.getDatas().clone(); this.getDatas().copyFrom(data); this.onDataChange(data, old); this.loadTransformFrom(data); @@ -7825,31 +6490,31 @@ var JlGraphic = /** @class */ (function (_super) { this.repaint(); } return update; - }; + } /** * 图形数据更新 */ - JlGraphic.prototype.onDataChange = function (newVal, old) { }; + onDataChange(newVal, old) { } /** * 加载状态 * @param state */ - JlGraphic.prototype.loadState = function (state) { + loadState(state) { if (state.graphicType !== this.type) { - throw new Error("\u4E0D\u540C\u7684\u56FE\u5F62\u7C7B\u578B,\u8BF7\u68C0\u67E5\u6570\u636E\u662F\u5426\u6B63\u5E38: state.graphicType=\"".concat(state.graphicType, ", type=\"").concat(this.type)); + throw new Error(`不同的图形类型,请检查数据是否正常: state.graphicType="${state.graphicType}, type="${this.type}`); } this._states = state; - }; + } /** * 更新状态 * @param state * @returns */ - JlGraphic.prototype.updateStates = function (state) { - var stateChange = false; + updateStates(state) { + let stateChange = false; if (!this.getStates().eq(state)) { // 判断并更新状态,默认状态 - var old = this.getStates().clone(); + const old = this.getStates().clone(); this.getStates().copyFrom(state); this.onStateChange(state, old); stateChange = true; @@ -7857,195 +6522,83 @@ var JlGraphic = /** @class */ (function (_super) { // this.repaint(); } return stateChange; - }; + } /** * 图形状态更新处理 */ - JlGraphic.prototype.onStateChange = function (newVal, old) { }; - JlGraphic.prototype.repaint = function () { + onStateChange(newVal, old) { } + repaint() { try { this.doRepaint(); this.emit('repaint', this); } catch (e) { - console.error("\u8BBE\u5907id=".concat(this.id, ",type=").concat(this.type, "\u91CD\u7ED8\u903B\u8F91\u5F02\u5E38"), e); + console.error(`设备id=${this.id},type=${this.type}重绘逻辑异常`, e); } - }; + } /** * 处理删除逻辑 */ - JlGraphic.prototype.onDelete = function () { + onDelete() { this.removeAllAssistantAppend(); this.removeAllListeners(); - recursiveChildren(this, function (child) { return child.removeAllAssistantAppend(); }); - }; + recursiveChildren(this, (child) => child.removeAllAssistantAppend()); + } /** * 框选检测,默认取图形包围盒判定,若需要精细判定-子类重写此方法 * @param box * @returns */ - JlGraphic.prototype.boxIntersectCheck = function (box) { + boxIntersectCheck(box) { return box.intersects(this.getLocalBounds(), this.localTransform); - }; - return JlGraphic; -}(pixi_js.Container)); + } +} /** * 图形对象模板 */ -var JlGraphicTemplate = /** @class */ (function () { - function JlGraphicTemplate(type, options) { +class JlGraphicTemplate { + type; + options; + constructor(type, options) { this.type = type; this.options = options; } - Object.defineProperty(JlGraphicTemplate.prototype, "datas", { - get: function () { - if (this.options.dataTemplate) { - return this.options.dataTemplate.clone(); - } - throw new Error("type=".concat(this.type, "\u7684\u56FE\u5F62\u6A21\u677F\u6CA1\u6709\u6570\u636E\u6A21\u677F")); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(JlGraphicTemplate.prototype, "states", { - get: function () { - if (this.options.stateTemplate) { - return this.options.stateTemplate.clone(); - } - throw new Error("type=".concat(this.type, "\u7684\u56FE\u5F62\u6A21\u677F\u6CA1\u6709\u72B6\u6001\u6A21\u677F")); - }, - enumerable: false, - configurable: true - }); + get datas() { + if (this.options.dataTemplate) { + return this.options.dataTemplate.clone(); + } + throw new Error(`type=${this.type}的图形模板没有数据模板`); + } + get states() { + if (this.options.stateTemplate) { + return this.options.stateTemplate.clone(); + } + throw new Error(`type=${this.type}的图形模板没有状态模板`); + } /** * 加载图形对象需要用到的资源 */ - JlGraphicTemplate.prototype.loadAssets = function () { - return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { - return [2 /*return*/]; - }); }); - }; + async loadAssets() { } /** * 克隆图形对象 * @param graphic * @returns */ - JlGraphicTemplate.prototype.clone = function (graphic) { - var g = this.new(); + clone(graphic) { + const g = this.new(); if (graphic._datas) { // 数据克隆 - var datas = graphic.saveData(); + const datas = graphic.saveData(); g.loadData(datas); } if (graphic._states) { // 状态克隆 - var state = graphic.getStates().clone(); + const state = graphic.getStates().clone(); g.loadState(state); } g.id = GraphicIdGenerator.next(); return g; - }; - return JlGraphicTemplate; -}()); + } +} -exports.AbsorbableCircle = AbsorbableCircle; -exports.AbsorbableLine = AbsorbableLine; -exports.AbsorbablePointParam = AbsorbablePointParam; -exports.AnimationManager = AnimationManager; -exports.AppConsts = AppConsts; -exports.AppDragEvent = AppDragEvent; -exports.AppInteractionPlugin = AppInteractionPlugin; -exports.AppWsMsgBroker = AppWsMsgBroker; -exports.BoundsGraphic = BoundsGraphic; -exports.ChildTransform = ChildTransform; -exports.CommonMouseTool = CommonMouseTool; -exports.DOWN = DOWN; -exports.DashedLine = DashedLine; -exports.DragPlugin = DragPlugin; -exports.DraggablePoint = DraggablePoint; -exports.DraggablePointParam = DraggablePointParam; -exports.GlobalKeyboardHelper = GlobalKeyboardHelper; -exports.GraphicAnimation = GraphicAnimation; -exports.GraphicCopyPlugin = GraphicCopyPlugin; -exports.GraphicDataUpdateOperation = GraphicDataUpdateOperation; -exports.GraphicDrawAssistant = GraphicDrawAssistant; -exports.GraphicIdGenerator = GraphicIdGenerator; -exports.GraphicInteractionPlugin = GraphicInteractionPlugin; -exports.GraphicRelation = GraphicRelation; -exports.GraphicRelationParam = GraphicRelationParam; -exports.GraphicStore = GraphicStore; -exports.GraphicTransform = GraphicTransform; -exports.GraphicTransformEvent = GraphicTransformEvent; -exports.GraphicTransformPlugin = GraphicTransformPlugin; -exports.IdGenerator = IdGenerator; -exports.InteractionPluginBase = InteractionPluginBase; -exports.JlGraphic = JlGraphic; -exports.JlGraphicAppKeyboardPlugin = JlGraphicAppKeyboardPlugin; -exports.JlGraphicTemplate = JlGraphicTemplate; -exports.JlOperation = JlOperation; -exports.KeyListener = KeyListener; -exports.LEFT = LEFT; -exports.OperationRecord = OperationRecord; -exports.OtherInteractionPlugin = OtherInteractionPlugin; -exports.OutOfBound = OutOfBound; -exports.RIGHT = RIGHT; -exports.RelationManage = RelationManage; -exports.ScaleData = ScaleData; -exports.ShiftData = ShiftData; -exports.TransformPoints = TransformPoints; -exports.UP = UP; -exports.VectorGraphicUtil = VectorGraphicUtil; -exports.VectorText = VectorText; -exports.ViewportMovePlugin = ViewportMovePlugin; -exports.WsMsgCli = WsMsgCli; -exports.angleOfIncludedAngle = angleOfIncludedAngle; -exports.angleToAxisx = angleToAxisx; -exports.assertBezierPoints = assertBezierPoints; -exports.calculateBezierPoints = calculateBezierPoints; -exports.calculateDistanceFromPointToLine = calculateDistanceFromPointToLine; -exports.calculateFootPointFromPointToLine = calculateFootPointFromPointToLine; -exports.calculateIntersectionPointOfCircleAndLine = calculateIntersectionPointOfCircleAndLine; -exports.calculateIntersectionPointOfCircleAndPoint = calculateIntersectionPointOfCircleAndPoint; -exports.calculateLineMidpoint = calculateLineMidpoint; -exports.calculateLineSegmentingPoint = calculateLineSegmentingPoint; -exports.calculateMirrorPoint = calculateMirrorPoint; -exports.calculateMirrorPointBasedOnAxis = calculateMirrorPointBasedOnAxis; -exports.calculateOneBezierPoints = calculateOneBezierPoints; -exports.circlePoint = circlePoint; -exports.circlePoint2 = circlePoint2; -exports.convertLineToPolygonPoints = convertLineToPolygonPoints; -exports.convertRectangleToPolygonPoints = convertRectangleToPolygonPoints; -exports.convertToBezierParams = convertToBezierParams; -exports.debounce = debounce; -exports.deserializeTransformInto = deserializeTransformInto; -exports.distance = distance; -exports.distance2 = distance2; -exports.getCenterOfTwoRectangle = getCenterOfTwoRectangle; -exports.getIntersectionPoint = getIntersectionPoint; -exports.getNormalVector = getNormalVector; -exports.getParallelOfPolyline = getParallelOfPolyline; -exports.getRectangleCenter = getRectangleCenter; -exports.isLineContainOther = isLineContainOther; -exports.isParallelLines = isParallelLines; -exports.isPointOnLine = isPointOnLine; -exports.lineBox = lineBox; -exports.lineLine = lineLine; -exports.linePoint = linePoint; -exports.linePolygon = linePolygon; -exports.movePointAlongNormal = movePointAlongNormal; -exports.newDrawApp = newDrawApp; -exports.newGraphicApp = newGraphicApp; -exports.pointBox = pointBox; -exports.pointPoint = pointPoint; -exports.pointPoint2 = pointPoint2; -exports.pointPolygon = pointPolygon; -exports.polylineBox = polylineBox; -exports.polylinePoint = polylinePoint; -exports.polylinePolygon = polylinePolygon; -exports.recursiveChildren = recursiveChildren; -exports.recursiveFindChild = recursiveFindChild; -exports.recursiveFindParent = recursiveFindParent; -exports.recursiveParents = recursiveParents; -exports.serializeTransform = serializeTransform; -exports.splitLineEvenly = splitLineEvenly; -exports.splitPolyline = splitPolyline; +export { AbsorbableCircle, AbsorbableLine, AbsorbablePointParam, AnimationManager, AppConsts, AppDragEvent, AppInteractionPlugin, AppWsMsgBroker, BoundsGraphic, ChildTransform, ClientEngine, CombinationKey, CommonMouseTool, DOWN, DashedLine, DragPlugin, DraggablePoint, DraggablePointParam, GlobalKeyboardHelper, GraphicAnimation, GraphicCopyPlugin, GraphicDataUpdateOperation, GraphicDrawAssistant, GraphicIdGenerator, GraphicInteractionPlugin, GraphicRelation, GraphicRelationParam, GraphicStore, GraphicTransform, GraphicTransformEvent, GraphicTransformPlugin, IdGenerator, InteractionPluginBase, InteractionPluginType, JlGraphic, JlGraphicAppKeyboardPlugin, JlGraphicTemplate, JlOperation, KeyListener, LEFT, OperationRecord, OtherInteractionPlugin, OutOfBound, RIGHT, RelationManage, ScaleData, ShiftData, TransformPoints, UP, VectorGraphicUtil, VectorText, ViewportMovePlugin, WsMsgCli, angleOfIncludedAngle, angleToAxisx, assertBezierPoints, calculateBezierPoints, calculateDistanceFromPointToLine, calculateFootPointFromPointToLine, calculateIntersectionPointOfCircleAndLine, calculateIntersectionPointOfCircleAndPoint, calculateLineMidpoint, calculateLineSegmentingPoint, calculateMirrorPoint, calculateMirrorPointBasedOnAxis, calculateOneBezierPoints, circlePoint, circlePoint2, convertLineToPolygonPoints, convertRectangleToPolygonPoints, convertToBezierParams, debounce, deserializeTransformInto, distance, distance2, getCenterOfTwoRectangle, getIntersectionPoint, getNormalVector, getParallelOfPolyline, getRectangleCenter, isLineContainOther, isParallelLines, isPointOnLine, lineBox, lineLine, linePoint, linePolygon, movePointAlongNormal, newDrawApp, newGraphicApp, pointBox, pointPoint, pointPoint2, pointPolygon, polylineBox, polylinePoint, polylinePolygon, recursiveChildren, recursiveFindChild, recursiveFindParent, recursiveParents, serializeTransform, splitLineEvenly, splitPolyline }; diff --git a/lib/math/Constants.d.ts b/lib/math/Constants.d.ts new file mode 100644 index 0000000..404e7fc --- /dev/null +++ b/lib/math/Constants.d.ts @@ -0,0 +1,17 @@ +/** + * 浮点数相等判断误差值 + */ +export declare const epsilon = 0.00001; +/** + * 判断浮点数是不是0 + * @param v + * @returns + */ +export declare function isZero(v: number): boolean; +/** + * 两浮点数是否相等 + * @param f1 + * @param f2 + * @returns + */ +export declare function floatEquals(f1: number, f2: number): boolean; diff --git a/lib/math/Vector2.d.ts b/lib/math/Vector2.d.ts new file mode 100644 index 0000000..acfaedd --- /dev/null +++ b/lib/math/Vector2.d.ts @@ -0,0 +1,91 @@ +export default class Vector2 { + constructor(values?: [number, number]); + static from(p: { + x: number; + y: number; + }): Vector2; + private values; + static readonly zero: Vector2; + static readonly one: Vector2; + get x(): number; + set x(value: number); + get y(): number; + set y(value: number); + get xy(): [number, number]; + set xy(values: [number, number]); + at(index: number): number; + reset(): void; + copy(dest?: Vector2): Vector2; + negate(dest?: Vector2): Vector2; + equals(vector: Vector2, threshold?: number): boolean; + length(): number; + squaredLength(): number; + add(vector: Vector2): Vector2; + subtract(vector: Vector2): Vector2; + multiply(vector: Vector2): Vector2; + divide(vector: Vector2): Vector2; + scale(value: number, dest?: Vector2): Vector2; + normalize(dest?: Vector2): Vector2; + /** + * 向量点乘 + * @param vector + * @param vector2 + * @returns + */ + static dot(vector: Vector2, vector2: Vector2): number; + /** + * 向量长度 + * @param vector + * @param vector2 + * @returns + */ + static distance(vector: Vector2, vector2: Vector2): number; + /** + * 向量长度平方 + * @param vector + * @param vector2 + * @returns + */ + static squaredDistance(vector: Vector2, vector2: Vector2): number; + /** + * v2->v1的方向的单位向量 + * @param v1 + * @param v2 + * @param dest + * @returns + */ + static direction(v1: Vector2, v2: Vector2, dest?: Vector2): Vector2; + static mix(vector: Vector2, vector2: Vector2, time: number, dest?: Vector2): Vector2; + /** + * 向量加法 + * @param vector + * @param vector2 + * @param dest + * @returns + */ + static sum(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2; + /** + * 向量减法 + * @param vector + * @param vector2 + * @param dest + * @returns + */ + static difference(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2; + /** + * 向量乘法 + * @param vector + * @param vector2 + * @param dest + * @returns + */ + static product(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2; + /** + * 向量除法 + * @param vector + * @param vector2 + * @param dest + * @returns + */ + static quotient(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2; +} diff --git a/lib/math/index.d.ts b/lib/math/index.d.ts new file mode 100644 index 0000000..0997ec2 --- /dev/null +++ b/lib/math/index.d.ts @@ -0,0 +1,2 @@ +export * from './Constants'; +export * from './Vector2'; diff --git a/lib/message/BasicMessageClient.d.ts b/lib/message/BasicMessageClient.d.ts new file mode 100644 index 0000000..d311b1e --- /dev/null +++ b/lib/message/BasicMessageClient.d.ts @@ -0,0 +1,52 @@ +import EventEmitter from 'eventemitter3'; +import { IGraphicScene } from '../app'; +import { CompleteMessageCliOption, IMessageClient } from './MessageBroker'; +export interface MessageClientEvents { + connected: [ctx: any]; + disconnected: [ctx: any]; + error: [err: any]; +} +export type HandleMessage = (data: any) => void; +export interface IMessageHandler { + /** + * id + */ + get App(): IGraphicScene; + /** + * 处理消息数据 + * @param data + */ + handle(data: any): void; +} +export declare abstract class MessageClient extends EventEmitter implements IMessageClient { + options: CompleteMessageCliOption; + subClients: SubscriptionClient[]; + constructor(options: CompleteMessageCliOption); + /** + * 订阅消息 + * @param destination + * @param handle + */ + abstract subscribe(destination: string, handle: HandleMessage): boolean; + unsubscribe(destination: string): void; + abstract unsubscribe0(destination: string): void; + getOrNewSubClient(destination: string): SubscriptionClient; + addSubscription(destination: string, handler: IMessageHandler): void; + removeSubscription(destination: string, handle: IMessageHandler): void; + abstract get connected(): boolean; + abstract close(): void; +} +export declare class SubscriptionClient { + mc: MessageClient; + destination: string; + protocol: 'json' | 'protobuf'; + handlers: IMessageHandler[]; + subscripted: boolean; + constructor(mc: MessageClient, destination: string, protocal: 'json' | 'protobuf'); + addHandler(handler: IMessageHandler): void; + removeHandler(handler: IMessageHandler): void; + trySubscribe(): void; + unsubscribe(): void; + handleMessage(data: any): void; + onDisconnect(): void; +} diff --git a/lib/message/MessageBroker.d.ts b/lib/message/MessageBroker.d.ts new file mode 100644 index 0000000..90f410a --- /dev/null +++ b/lib/message/MessageBroker.d.ts @@ -0,0 +1,146 @@ +import EventEmitter from 'eventemitter3'; +import { IGraphicScene } from '../app'; +import { GraphicQueryStore, GraphicState, JlGraphic } from '../core'; +import { IMessageHandler, MessageClientEvents } from './BasicMessageClient'; +export declare enum ClientEngine { + Stomp = 0, + MQTT = 1 +} +export interface MessageCliOption { + /** + * 客户端引擎 + */ + engine?: ClientEngine; + /** + * 消息协议,默认protobuf + */ + protocol?: 'json' | 'protobuf'; + /** + * websocket url地址 + */ + wsUrl: string; + /** + * 认证token + */ + token?: string; + /** + * 项目名称(可用于订阅客户端识别) + */ + clientName?: string; + /** + * 连接超时,默认30秒,ms + */ + connectTimeout?: number; + /** + * 心跳发送间隔,默认60秒,s + */ + heartbeat?: number; + /** + * 重试间隔,默认2秒,ms + */ + retryPeriod?: number; + /** + * 重试次数,默认100次 + */ + retryTimes?: number; +} +export interface CompleteMessageCliOption extends MessageCliOption { + protocol: 'json' | 'protobuf'; + connectTimeout: number; + heartbeat: number; + retryPeriod: number; + retryTimes: number; +} +export interface IMessageClient extends EventEmitter { + /** + * 添加订阅 + * @param destination + * @param handler + */ + addSubscription(destination: string, handler: IMessageHandler): void; + /** + * 移除订阅 + * @param destination + * @param handler + */ + removeSubscription(destination: string, handler: IMessageHandler): void; + /** + * 是否已经连接 + */ + get connected(): boolean; + /** + * 关闭连接 + */ + close(): void; +} +export declare class WsMsgCli { + private static client; + private static options; + private static appMsgBroker; + static new(options: MessageCliOption): void; + static isInitiated(): boolean; + static emitConnectStateChangeEvent(connected: boolean): void; + static isConnected(): boolean; + static registerSubscription(destination: string, handler: IMessageHandler): void; + static unregisterSubscription(destination: string, handler: IMessageHandler): void; + static registerAppMsgBroker(broker: AppWsMsgBroker): void; + static removeAppMsgBroker(broker: AppWsMsgBroker): void; + static hasAppMsgBroker(): boolean; + /** + * 关闭websocket连接 + */ + static close(): void; +} +export type GraphicStateMessageConvert = (message: Uint8Array) => GraphicState[]; +export type GraphicQuery = (state: GraphicState, store: GraphicQueryStore) => JlGraphic | undefined; +export type SubscriptionMessageHandle = (message: Uint8Array) => void; +export interface ICreateOnNotFound { + graphicTypes?: string[]; +} +export interface AppStateSubscription { + /** + * 订阅路径 + */ + destination: string; + /** + * 图形状态消息转换 + */ + messageConverter?: GraphicStateMessageConvert; + /** + * 根据状态查询图形对象,默认为根据code和type查询图形对象 + */ + graphicQueryer?: GraphicQuery; + /** + * 当未根据状态找到图形对象时是否创建新对象 + * 值为设备类型列表 + */ + createOnNotFound?: ICreateOnNotFound; + /** + * 订阅消息处理 + */ + messageHandle?: SubscriptionMessageHandle; +} +declare class AppMessageHandler implements IMessageHandler { + app: IGraphicScene; + sub: AppStateSubscription; + constructor(app: IGraphicScene, subOptions: AppStateSubscription); + get App(): IGraphicScene; + handle(data: any): void; +} +/** + * 图形APP的websocket消息代理 + */ +export declare class AppWsMsgBroker { + app: IGraphicScene; + subscriptions: Map; + constructor(app: IGraphicScene); + subscribe(sub: AppStateSubscription): void; + unsbuscribe(destination: string): void; + unsubscribeAll(): void; + resubscribeAll(): void; + /** + * 取消所有订阅,从通用Stomp客户端移除此消息代理 + */ + close(): void; +} +export {}; diff --git a/lib/message/MqttBroker.d.ts b/lib/message/MqttBroker.d.ts new file mode 100644 index 0000000..1a3f7b5 --- /dev/null +++ b/lib/message/MqttBroker.d.ts @@ -0,0 +1,13 @@ +import mqtt from 'mqtt'; +import { HandleMessage, MessageClient } from './BasicMessageClient'; +import { CompleteMessageCliOption } from './MessageBroker'; +export declare class MqttMsgClient extends MessageClient { + cli: mqtt.MqttClient; + retryTimes: number; + subMsgHandler: Map; + constructor(options: CompleteMessageCliOption); + subscribe(destination: string, handle: HandleMessage): boolean; + unsubscribe0(destination: string): void; + get connected(): boolean; + close(): void; +} diff --git a/lib/message/WsMsgBroker.d.ts b/lib/message/WsMsgBroker.d.ts new file mode 100644 index 0000000..3d34677 --- /dev/null +++ b/lib/message/WsMsgBroker.d.ts @@ -0,0 +1,11 @@ +import { Client as StompClient } from '@stomp/stompjs'; +import { HandleMessage, MessageClient } from './BasicMessageClient'; +import { CompleteMessageCliOption } from './MessageBroker'; +export declare class StompMessagingClient extends MessageClient { + cli: StompClient; + constructor(options: CompleteMessageCliOption); + get connected(): boolean; + subscribe(destination: string, handle: HandleMessage): boolean; + unsubscribe0(destination: string): void; + close(): void; +} diff --git a/src/jlgraphic/message/index.ts b/lib/message/index.d.ts similarity index 100% rename from src/jlgraphic/message/index.ts rename to lib/message/index.d.ts diff --git a/lib/operation/JlOperation.d.ts b/lib/operation/JlOperation.d.ts new file mode 100644 index 0000000..dd06aa5 --- /dev/null +++ b/lib/operation/JlOperation.d.ts @@ -0,0 +1,42 @@ +import { IGraphicApp } from '../app/JlGraphicApp'; +import { JlGraphic } from '../core/JlGraphic'; +/** + * 操作 + */ +export declare abstract class JlOperation { + type: string; + app: IGraphicApp; + obj?: any; + data?: any; + description?: string; + constructor(app: IGraphicApp, type: string); + undo1(): void; + redo1(): void; + abstract undo(): JlGraphic[] | void; + abstract redo(): JlGraphic[] | void; +} +/** + * 操作记录 + */ +export declare class OperationRecord { + undoStack: JlOperation[]; + redoStack: JlOperation[]; + private maxLen; + constructor(maxLen?: number); + get hasUndo(): boolean; + get hasRedo(): boolean; + setMaxLen(v: number): void; + /** + * 记录 + * @param op + */ + record(op: JlOperation): void; + /** + * 撤销 + */ + undo(): void; + /** + * 重做 + */ + redo(): void; +} diff --git a/src/jlgraphic/operation/index.ts b/lib/operation/index.d.ts similarity index 100% rename from src/jlgraphic/operation/index.ts rename to lib/operation/index.d.ts diff --git a/lib/plugins/AnimationManager.d.ts b/lib/plugins/AnimationManager.d.ts new file mode 100644 index 0000000..77b6207 --- /dev/null +++ b/lib/plugins/AnimationManager.d.ts @@ -0,0 +1,48 @@ +import { IGraphicScene } from '../app'; +import { GraphicAnimation, JlGraphic } from '../core'; +/** + * 图形动画管理 + */ +export declare class AnimationManager { + app: IGraphicScene; + _pause: boolean; + /** + * key - graphic.id + */ + graphicAnimationMap: Map>; + constructor(app: IGraphicScene); + private run; + pause(): void; + resume(): void; + destroy(): void; + /** + * 图形对象的所有动画map + * @param graphic + * @returns + */ + animationMap(graphic: JlGraphic): Map; + /** + * 注册图形动画 + * @param graphic + * @param animation + */ + registerAnimation(graphic: JlGraphic, animation: GraphicAnimation): void; + /** + * 删除图形动画 + * @param graphic + * @param name + */ + unregisterAnimation(graphic: JlGraphic, name: string): void; + /** + * 删除所有图形动画 + * @param graphic + */ + unregisterGraphicAnimations(graphic: JlGraphic): void; + /** + * 获取图形指定名称动画 + * @param graphic + * @param name + * @returns + */ + animation(graphic: JlGraphic, name: string): GraphicAnimation | undefined; +} diff --git a/lib/plugins/CommonMousePlugin.d.ts b/lib/plugins/CommonMousePlugin.d.ts new file mode 100644 index 0000000..aea3d42 --- /dev/null +++ b/lib/plugins/CommonMousePlugin.d.ts @@ -0,0 +1,82 @@ +import { DisplayObject, FederatedMouseEvent, Graphics, Point } from 'pixi.js'; +import { IGraphicScene } from '../app'; +import { JlGraphic } from '../core'; +import { AppDragEvent, AppInteractionPlugin } from './InteractionPlugin'; +type GraphicSelectFilter = (graphic: JlGraphic) => boolean; +export interface IMouseToolOptions { + /** + * 是否启用框选,默认启用 + */ + boxSelect?: boolean; + /** + * 是否启用视口拖拽(默认右键),默认启用 + */ + viewportDrag?: boolean; + /** + * 是否启用左键视口拖拽 + */ + viewportDragLeft?: boolean; + /** + * 是否启用鼠标滚轮缩放,默认启用 + */ + wheelZoom?: boolean; + /** + * 可选择图形过滤器 + */ + selectFilter?: GraphicSelectFilter; +} +declare class CompleteMouseToolOptions implements IMouseToolOptions { + boxSelect: boolean; + viewportDrag: boolean; + viewportDragLeft: boolean; + wheelZoom: boolean; + selectFilter?: GraphicSelectFilter | undefined; + constructor(); + update(options: IMouseToolOptions): void; +} +/** + * 通用交互工具 + */ +export declare class CommonMouseTool extends AppInteractionPlugin { + static Name: string; + static SelectBox: string; + options: CompleteMouseToolOptions; + box: Graphics; + leftDownTarget: DisplayObject | null; + drag: boolean; + graphicSelect: boolean; + rightTarget: DisplayObject | null; + constructor(scene: IGraphicScene); + static new(app: IGraphicScene): CommonMouseTool; + bind(): void; + unbind(): void; + onDragStart(event: AppDragEvent): void; + onDragMove(event: AppDragEvent): void; + onDragEnd(event: AppDragEvent): void; + setLeftCursor(e: FederatedMouseEvent): void; + resumeLeftCursor(): void; + setCursor(e: FederatedMouseEvent): void; + resumeCursor(): void; + onMouseDown(e: FederatedMouseEvent): void; + /** + * 选中处理 + * @param e + */ + onMouseUp(e: FederatedMouseEvent): void; + /** + * 清理缓存 + */ + clearCache(): void; + get boxSelect(): boolean | undefined; + get selectFilter(): GraphicSelectFilter | undefined; + /** + * 框选图形绘制并检查 + */ + boxSelectDraw(start: Point, end: Point): void; + /** + * 框选图形判断 + * @returns + */ + boxSelectGraphicCheck(): void; +} +export {}; diff --git a/lib/plugins/CopyPlugin.d.ts b/lib/plugins/CopyPlugin.d.ts new file mode 100644 index 0000000..dfa51b6 --- /dev/null +++ b/lib/plugins/CopyPlugin.d.ts @@ -0,0 +1,23 @@ +import { Container, FederatedPointerEvent, Point } from 'pixi.js'; +import { IGraphicScene } from '../app'; +import { JlGraphic } from '../core'; +import { KeyListener } from './KeyboardPlugin'; +/** + * 图形复制插件 + */ +export declare class GraphicCopyPlugin { + container: Container; + scene: IGraphicScene; + keyListeners: KeyListener[]; + copys: JlGraphic[]; + start?: Point; + running: boolean; + moveLimit?: 'x' | 'y'; + constructor(scene: IGraphicScene); + updateMoveLimit(limit?: 'x' | 'y'): void; + init(): void; + clear(): void; + onPointerMove(e: FederatedPointerEvent): void; + onFinish(): void; + cancle(): void; +} diff --git a/lib/plugins/GraphicEditPlugin.d.ts b/lib/plugins/GraphicEditPlugin.d.ts new file mode 100644 index 0000000..23330e7 --- /dev/null +++ b/lib/plugins/GraphicEditPlugin.d.ts @@ -0,0 +1,82 @@ +import { Container, DisplayObject, Graphics, IDestroyOptions, IPointData } from 'pixi.js'; +import { JlGraphic } from '../core'; +import { DraggablePoint } from '../graphic'; +export declare abstract class GraphicEditPlugin extends Container { + graphic: DO; + constructor(g: DO); + destroy(options?: boolean | IDestroyOptions | undefined): void; + abstract updateEditedPointsPosition(): void; + hideAll(): void; + showAll(): void; +} +export interface ILineGraphic extends JlGraphic { + get linePoints(): IPointData[]; + set linePoints(points: IPointData[]); +} +export declare abstract class LineEditPlugin extends GraphicEditPlugin { + linePoints: IPointData[]; + editedPoints: DraggablePoint[]; + constructor(g: ILineGraphic); + destroy(options?: boolean | IDestroyOptions | undefined): void; + reset(): void; + abstract initEditPoints(): void; +} +export declare function getWayLineIndex(points: IPointData[], p: IPointData): { + start: number; + end: number; +}; +export declare function getWaypointRangeIndex(points: IPointData[], curve: boolean, p: IPointData, lineWidth: number): { + start: number; + end: number; +}; +export type onEditPointCreate = (g: ILineGraphic, dp: DraggablePoint, index: number) => void; +export interface IEditPointOptions { + /** + * 编辑点创建处理 + */ + onEditPointCreate?: onEditPointCreate; +} +/** + * 折线编辑(兼容线段) + */ +export declare class PolylineEditPlugin extends LineEditPlugin { + static Name: string; + options: IEditPointOptions; + constructor(g: ILineGraphic, options?: IEditPointOptions); + initEditPoints(): void; + updateEditedPointsPosition(): void; +} +export interface BezierCurveEditPointOptions extends IEditPointOptions { + auxiliaryLineColor?: string; + smooth?: boolean; + symmetry?: boolean; +} +export interface ICompleteBezierCurveEditPointOptions extends BezierCurveEditPointOptions { + smooth: boolean; +} +export declare function addWayPoint(graphic: ILineGraphic, curve: boolean, start: number, end: number, p: IPointData): void; +export declare function addLineWayPoint(graphic: ILineGraphic, start: number, end: number, p: IPointData): void; +export declare function addPolygonSegmentingPoint(graphic: ILineGraphic, start: number, end: number, knife?: number): void; +export declare function addBezierWayPoint(graphic: ILineGraphic, start: number, end: number, p: IPointData): void; +export declare function removeWayPoint(graphic: ILineGraphic, curve: boolean, i: number): void; +export declare function removeLineWayPoint(graphic: ILineGraphic, i: number): void; +export declare function removeBezierWayPoint(graphic: ILineGraphic, i: number): void; +/** + * 清除路径点(只留端点),适用于直线和贝塞尔曲线 + * @param graphic + * @param curve + */ +export declare function clearWayPoint(graphic: ILineGraphic, curve: boolean): void; +/** + * 贝塞尔曲线编辑 + */ +export declare class BezierCurveEditPlugin extends LineEditPlugin { + static Name: string; + options: ICompleteBezierCurveEditPointOptions; + auxiliaryLines: Graphics[]; + constructor(g: ILineGraphic, options?: BezierCurveEditPointOptions); + reset(): void; + initEditPoints(): void; + drawAuxiliaryLine(line: Graphics, p1: IPointData, p2: IPointData): void; + updateEditedPointsPosition(): void; +} diff --git a/lib/plugins/GraphicTransformPlugin.d.ts b/lib/plugins/GraphicTransformPlugin.d.ts new file mode 100644 index 0000000..244f071 --- /dev/null +++ b/lib/plugins/GraphicTransformPlugin.d.ts @@ -0,0 +1,207 @@ +import { Container, DisplayObject, Graphics, IDestroyOptions, Point } from 'pixi.js'; +import { AppDragEvent, InteractionPluginBase, KeyListener } from '.'; +import { IGraphicScene } from '../app'; +import { AbsorbablePosition, VectorText } from '../graphic'; +import { DraggablePoint } from '../graphic/DraggablePoint'; +import { DebouncedFunction } from '../utils'; +export declare class ShiftData { + /** + * 起始位置 + */ + startPosition: Point; + /** + * 上一次终点位置 + */ + lastPosition?: Point; + /** + * 当前位置 + */ + currentPosition?: Point; + constructor(startPosition: Point, currentPosition?: Point, lastPosition?: Point); + static new(startPosition: Point, currentPosition?: Point, lastPosition?: Point): ShiftData; + get dx(): number; + get dy(): number; + get dsx(): number; + get dsy(): number; +} +export declare class ScaleData { + start: Point; + current?: Point; + last?: Point; + constructor(start: Point, current?: Point, last?: Point); + static new(start: Point, current?: Point, last?: Point): ScaleData; +} +export type TransformData = ShiftData | null; +/** + * 图形平移事件 + */ +export declare class GraphicTransformEvent { + /** + * 图形对象 + */ + target: DisplayObject; + type: 'shift' | 'rotate' | 'scale' | 'skew'; + data: TransformData; + constructor(target: DisplayObject, type: 'shift' | 'rotate' | 'scale' | 'skew', data: TransformData); + getData(): D; + static shift(target: DisplayObject, data: ShiftData): GraphicTransformEvent; + static scale(target: DisplayObject): GraphicTransformEvent; + static rotate(target: DisplayObject): GraphicTransformEvent; + static skew(target: DisplayObject): GraphicTransformEvent; + isShift(): boolean; + isRotate(): boolean; + isScale(): boolean; + isSkew(): boolean; +} +export declare class GraphicTransformPlugin extends InteractionPluginBase { + static Name: string; + /** + * 可吸附位置列表 + */ + absorbablePositions?: AbsorbablePosition[]; + apContainer: Container; + static AbsorbablePosisiontsName: string; + constructor(app: IGraphicScene); + /** + * 过滤重复的吸附位置 + * @param positions + * @returns + */ + filterAbsorbablePositions(positions: AbsorbablePosition[]): AbsorbablePosition[]; + static new(app: IGraphicScene): GraphicTransformPlugin; + bind(): void; + unbind(): void; + getDraggedTargets(e: AppDragEvent): DisplayObject[]; + onDragStart(e: AppDragEvent): void; + onDragMove(e: AppDragEvent): void; + onDragEnd(e: AppDragEvent): void; + /** + * 清理缓存 + */ + clearCache(): void; + onGraphicSelectedChange(g: DisplayObject, selected: boolean): void; +} +/** + * 缩放、旋转辅助 + */ +export declare class TransformPoints extends Container { + static Name: string; + static MinLength: number; + static LeftTopName: string; + static TopName: string; + static RightTopName: string; + static RightName: string; + static RightBottomName: string; + static BottomName: string; + static LeftBottomName: string; + static LeftName: string; + static RotateName: string; + obj: DisplayObject; + ltScalePoint: DraggablePoint; + ltLocal: Point; + tScalePoint: DraggablePoint; + tLocal: Point; + tCanvas: Point; + rtScalePoint: DraggablePoint; + rtLocal: Point; + rScalePoint: DraggablePoint; + rLocal: Point; + rbScalePoint: DraggablePoint; + rbLocal: Point; + bScalePoint: DraggablePoint; + bLocal: Point; + lbScalePoint: DraggablePoint; + lbLocal: Point; + lScalePoint: DraggablePoint; + lLocal: Point; + originScale: Point; + scalePivot: Point; + /** + * 旋转拖拽点 + */ + rotatePoint: DraggablePoint; + /** + * 旋转中心坐标 + */ + rotatePivot: Point; + /** + * 起始旋转坐标 + */ + rotateLastPoint: Point; + /** + * 起始图形角度 + */ + startAngle: number; + /** + * 当前角度信息文本辅助 + */ + angleAssistantText: VectorText; + /** + * 旋转角度步长 + */ + angleStep: number; + /** + * 修改旋转步长键盘监听 + */ + rotateAngleStepKeyListeners: KeyListener[]; + constructor(obj: DisplayObject); + onObjTransformStart(): void; + onObjTransformEnd(): void; + onGraphicRepaint(): void; + /** + * 旋转开始 + * @param de + */ + onRotateStart(de: GraphicTransformEvent): void; + updateAngleAssistantText(de: GraphicTransformEvent): void; + /** + * 旋转移动 + * @param de + */ + onRotateMove(de: GraphicTransformEvent): void; + /** + * 旋转结束 + * @param de + */ + onRotateEnd(): void; + /** + * 缩放开始 + */ + onScaleDragStart(): void; + onScaleDragMove(e: GraphicTransformEvent): void; + onScaleDragEnd(): void; + hideOthers(dg: DisplayObject): void; + hideAll(): void; + showAll(): void; + getObjBounds(): { + width: number; + height: number; + }; + /** + * 更新位置和cursor + * @returns + */ + update(): void; + updateRotatePoint(): void; + updateScalePoints(): void; +} +/** + * 包围盒矩形图形,现使用外边框转画布多边形实现 + */ +export declare class BoundsGraphic extends Graphics { + static Name: string; + static BoundsLineStyle: { + width: number; + color: string; + alpha: number; + }; + obj: DisplayObject; + debouncedRedraw: DebouncedFunction<() => void>; + constructor(graphic: DisplayObject); + onObjTransformStart(): void; + onObjTransformEnd(): void; + onGraphicRepaint(): void; + destroy(options?: boolean | IDestroyOptions | undefined): void; + redraw(): void; + doRedraw(): void; +} diff --git a/lib/plugins/InteractionPlugin.d.ts b/lib/plugins/InteractionPlugin.d.ts new file mode 100644 index 0000000..832a138 --- /dev/null +++ b/lib/plugins/InteractionPlugin.d.ts @@ -0,0 +1,173 @@ +/// +import { DisplayObject, FederatedMouseEvent, FederatedPointerEvent, Point } from 'pixi.js'; +import { IGraphicScene } from '../app/JlGraphicApp'; +import { JlGraphic } from '../core/JlGraphic'; +export declare enum InteractionPluginType { + App = "app", + Graphic = "graphic", + Other = "other" +} +/** + * 交互插件 + */ +export interface InteractionPlugin { + readonly _type: string; + name: string; + app: IGraphicScene; + /** + * 恢复 + */ + resume(): void; + /** + * 停止 + */ + pause(): void; + /** + * 是否生效 + */ + isActive(): boolean; + isAppPlugin(): boolean; + isOtherPlugin(): boolean; + isGraphicPlugin(): boolean; +} +export declare abstract class InteractionPluginBase implements InteractionPlugin { + readonly _type: string; + name: string; + app: IGraphicScene; + _pause: boolean; + constructor(app: IGraphicScene, name: string, type: string); + /** + * 恢复 + */ + resume(): void; + /** + * 停止 + */ + pause(): void; + abstract bind(): void; + abstract unbind(): void; + /** + * 是否生效 + */ + isActive(): boolean; + isGraphicPlugin(): boolean; + isAppPlugin(): boolean; + isOtherPlugin(): boolean; +} +export declare abstract class OtherInteractionPlugin extends InteractionPluginBase { + constructor(app: IGraphicScene, name: string); +} +export declare class AppDragEvent { + app: IGraphicScene; + type: 'start' | 'move' | 'end'; + target: DisplayObject; + original: FederatedPointerEvent; + start: Point; + constructor(app: IGraphicScene, type: 'start' | 'move' | 'end', target: DisplayObject, original: FederatedPointerEvent, start: Point); + get isMouse(): boolean; + get isLeftButton(): boolean; + get isRightButton(): boolean; + get isMiddleButton(): boolean; + get isTouch(): boolean; + /** + * 终点坐标(画布坐标) + */ + get end(): Point; + get dx(): number; + get dy(): number; + get dsx(): number; + get dsy(): number; + /** + * 转换为目标对象的位移距离 + */ + toTargetShiftLen(target: DisplayObject): { + dx: number; + dy: number; + }; +} +/** + * 拖拽操作插件 + */ +export declare class DragPlugin extends OtherInteractionPlugin { + static Name: string; + private threshold; + target: DisplayObject | null; + start: Point | null; + startClientPoint: Point | null; + drag: boolean; + constructor(app: IGraphicScene); + static new(app: IGraphicScene): DragPlugin; + bind(): void; + unbind(): void; + onPointerDown(e: FederatedPointerEvent): void; + onPointerMove(e: FederatedPointerEvent): void; + onPointerUp(e: FederatedPointerEvent): void; + /** + * 清理缓存 + */ + clearCache(): void; +} +/** + * 视口移动插件 + */ +export declare class ViewportMovePlugin extends OtherInteractionPlugin { + static Name: string; + static MoveInterval: number; + static TriggerRange: number; + static DefaultMoveSpeed: number; + moveHandler: NodeJS.Timeout | null; + moveSpeedx: number; + moveSpeedy: number; + constructor(app: IGraphicScene); + static new(app: IGraphicScene): ViewportMovePlugin; + pause(): void; + bind(): void; + unbind(): void; + startMove(moveSpeedx: number, moveSpeedy: number): void; + stopMove(): void; + private calculateBoundaryMoveSpeed; + calculateMoveSpeed(dd: number): number; + viewportMove(e: FederatedMouseEvent): void; +} +/** + * 应用交互插件,同时只能生效一个 + */ +export declare abstract class AppInteractionPlugin extends InteractionPluginBase { + constructor(name: string, app: IGraphicScene); + /** + * 恢复,app交互插件同时只能生效一个 + */ + resume(): void; +} +/** + * 图形交互插件,可同时生效 + */ +export declare abstract class GraphicInteractionPlugin implements InteractionPlugin { + readonly _type = InteractionPluginType.Graphic; + app: IGraphicScene; + name: string; + _pause: boolean; + constructor(name: string, app: IGraphicScene); + isActive(): boolean; + isAppPlugin(): boolean; + isOtherPlugin(): boolean; + isGraphicPlugin(): boolean; + resume(): void; + pause(): void; + /** + * 过滤需要的图形对象 + */ + abstract filter(...grahpics: JlGraphic[]): G[] | undefined; + binds(list?: G[]): void; + unbinds(list?: G[]): void; + /** + * 绑定图形对象的交互处理 + * @param g 图形对象 + */ + abstract bind(g: G): void; + /** + * 取消图形对象的交互处理 + * @param g 图形对象 + */ + abstract unbind(g: G): void; +} diff --git a/lib/plugins/KeyboardPlugin.d.ts b/lib/plugins/KeyboardPlugin.d.ts new file mode 100644 index 0000000..ac69e2c --- /dev/null +++ b/lib/plugins/KeyboardPlugin.d.ts @@ -0,0 +1,81 @@ +import { IGraphicApp } from '../app/JlGraphicApp'; +export declare class GlobalKeyboardHelper { + appKeyboardPluginMap: JlGraphicAppKeyboardPlugin[]; + constructor(); + registerGAKPlugin(plugin: JlGraphicAppKeyboardPlugin): void; + removeGAKPlugin(plugin: JlGraphicAppKeyboardPlugin): void; +} +export declare class JlGraphicAppKeyboardPlugin { + app: IGraphicApp; + /** + * 结构为Map> + */ + keyListenerMap: Map>; + keyListenerStackMap: Map; + constructor(app: IGraphicApp); + private getOrInit; + private getOrInitStack; + /** + * 注册按键监听,若有旧的,旧的入栈 + * @param keyListener + */ + addKeyListener(keyListener: KeyListener): void; + /** + * 移除按键监听,若是当前注册的监听,尝试从栈中取出作为按键监听器,若是旧的,则同时移除栈中的监听 + * @param keyListener + */ + removeKeyListener(keyListener: KeyListener): void; + getKeyListenerBy(key: string | number): Map | undefined; + getKeyListener(e: KeyboardEvent): Map | undefined; + isKeyListened(key: string | number): boolean; + /** + * 获取所有注册监听的键值(组合键) + */ + getAllListenedKeys(): string[]; +} +type KeyboardKeyHandler = (e: KeyboardEvent, app: IGraphicApp) => void; +export declare enum CombinationKey { + Ctrl = "Ctrl", + Alt = "Alt", + Shift = "Shift" +} +export interface KeyListenerOptions { + value: string | number; + combinations?: CombinationKey[]; + global?: boolean; + onPress?: KeyboardKeyHandler; + pressTriggerAsOriginalEvent?: boolean; + onRelease?: KeyboardKeyHandler; +} +export interface ICompleteKeyListenerOptions { + value: string | number; + combinations: CombinationKey[]; + global: boolean; + onPress?: KeyboardKeyHandler; + pressTriggerAsOriginalEvent: boolean; + onRelease?: KeyboardKeyHandler; +} +export declare class KeyListener { + readonly options: ICompleteKeyListenerOptions; + private isPress; + constructor(options: KeyListenerOptions); + static create(options: KeyListenerOptions): KeyListener; + get value(): string | number; + get combinations(): string[]; + get identifier(): string; + get global(): boolean | undefined; + get onPress(): KeyboardKeyHandler | undefined; + set onPress(v: KeyboardKeyHandler | undefined); + get onRelease(): KeyboardKeyHandler | undefined; + set onRelease(v: KeyboardKeyHandler | undefined); + get pressTriggerEveryTime(): boolean; + set pressTriggerEveryTime(v: boolean); + press(e: KeyboardEvent, app: IGraphicApp): void; + /** + * 检查组合键是否匹配 + */ + checkCombinations(e: KeyboardEvent): boolean; + release(e: KeyboardEvent, app: IGraphicApp): void; + onRemove(): void; +} +export {}; diff --git a/src/jlgraphic/plugins/index.ts b/lib/plugins/index.d.ts similarity index 100% rename from src/jlgraphic/plugins/index.ts rename to lib/plugins/index.d.ts diff --git a/lib/ui/ContextMenu.d.ts b/lib/ui/ContextMenu.d.ts new file mode 100644 index 0000000..2f38923 --- /dev/null +++ b/lib/ui/ContextMenu.d.ts @@ -0,0 +1,164 @@ +/// +import { Container, Graphics, Point, Rectangle, Text } from 'pixi.js'; +import { IGraphicScene } from '../app'; +import { OutOfBound } from '../utils'; +import { MenuCompletionItemStyle, MenuCompletionOptions, MenuCompletionStyleOptions, MenuGroupOptions, MenuItemOptions, MenuOptions } from './Menu'; +export declare class ContextMenuPlugin { + app: IGraphicScene; + contextMenuMap: Map; + constructor(app: IGraphicScene); + registerMenu(menu: ContextMenu): void; + /** + * 获取视口屏幕宽度 + */ + get screenWidth(): number; + /** + * 获取视口屏幕高度 + */ + get screenHeight(): number; + /** + * 打开菜单 + * @param menu + * @param global + */ + open(menu: ContextMenu, global: Point): void; + /** + * 关闭菜单 + * @param menu + */ + close(menu: ContextMenu): void; + /** + * 关闭所有菜单 + */ + closeAll(): void; + /** + * 越界检查 + * @param menu + * @param global + * @returns + */ + oob(menu: ContextMenu, global: Point): OutOfBound; +} +/** + * 上下文菜单,多级嵌套 + */ +export declare class ContextMenu extends Container { + _plugin?: ContextMenuPlugin; + parentMenuItem?: ContextMenuItem; + openedSubMenu?: ContextMenu; + menuOptions: MenuCompletionOptions; + opened: boolean; + bg: Graphics; + title?: Text; + groups: MenuGroup[]; + private padding; + _active: boolean; + timeoutCloseHandle?: NodeJS.Timeout; + constructor(menuOptions: MenuOptions, parentMenuItem?: ContextMenuItem); + static init(options: MenuOptions): ContextMenu; + get style(): MenuCompletionStyleOptions; + /** + * 父级菜单 + */ + get parentMenu(): ContextMenu | undefined; + /** + * 最顶级菜单 + */ + get rootMenu(): ContextMenu; + /** + * 是否存在激活的菜单项 + * @returns + */ + hasActiveItem(): boolean; + get active(): boolean; + set active(v: boolean); + onActiveChanged(): void; + setOptions(menuOptions: MenuOptions): void; + /** + * 初始化 + */ + init(): void; + initGroups(): void; + initTitle(): void; + private calculateBorderInfo; + updateBg(): void; + update(): void; + get menuName(): string; + get plugin(): ContextMenuPlugin; + set plugin(v: ContextMenuPlugin); + /** + * 显示菜单 + */ + open(global: Point): void; + /** + * 关闭菜单 + */ + close(): void; + /** + * 打开子菜单 + * @param subMenu + * @param global + */ + private openSub; +} +declare class MenuGroup extends Container { + private gutter; + config: MenuGroupOptions; + menu: ContextMenu; + items: ContextMenuItem[]; + constructor(menu: ContextMenu, config: MenuGroupOptions); + private init; + hasActiveItem(): boolean; + get maxItemNameWidth(): number; + get maxShortcutWidth(): number; + get totalGutter(): number; + get totalHeight(): number; + update(): void; + updateItemBox(maxItemWidth: number): void; +} +/** + * 菜单项 + */ +declare class ContextMenuItem extends Container { + menu: ContextMenu; + config: MenuItemOptions; + /** + * 名称文本 + */ + nameText: Text; + /** + * 快捷键文本 + */ + shortcutKeyText?: Text; + private gutter; + arrowText?: Text; + box: Graphics; + subMenu?: ContextMenu; + _active: boolean; + constructor(menu: ContextMenu, config: MenuItemOptions); + registerEventHandler(): void; + get active(): boolean; + set active(v: boolean); + onActiveChanged(): void; + get textWidth(): number; + get nameGraphic(): Text; + get totalHeight(): number; + get nameBounds(): Rectangle; + get shortcutKeyBounds(): Rectangle; + get style(): MenuCompletionItemStyle; + private checkPadding; + private toWholePadding; + get paddingTop(): number; + get paddingBottom(): number; + get paddingLeft(): number; + get paddingRight(): number; + get hoverColor(): string; + get fontSize(): number; + get fontColor(): string; + initShortcutKeyText(): Text | undefined; + initSubMenu(): void; + updateBackground(width: number, height: number): void; + updateBox(width: number, height: number): void; + update(): void; +} +export {}; diff --git a/lib/ui/Menu.d.ts b/lib/ui/Menu.d.ts new file mode 100644 index 0000000..339f05a --- /dev/null +++ b/lib/ui/Menu.d.ts @@ -0,0 +1,146 @@ +/** + * 菜单配置项 + */ +export interface MenuOptions { + /** + * 菜单名称,需唯一 + */ + name: string; + /** + * 菜单标题 + */ + title?: string; + /** + * 菜单分组 + */ + groups: MenuGroupOptions[]; + /** + * 菜单样式 + */ + style?: MenuStyleOptions; +} +/** + * 菜单分组 + */ +export interface MenuGroupOptions { + /** + * 分组命名 + */ + name?: string; + /** + * 菜单项 + */ + items: MenuItemOptions[]; +} +export interface MenuCompletionOptions extends MenuOptions { + style: MenuCompletionStyleOptions; +} +/** + * 菜单样式配置项 + */ +export interface MenuStyleOptions { + /** + * 菜单标题样式 + */ + titleStyle?: MenuItemStyle; + /** + * 菜单背景色 + */ + backgroundColor?: string; + /** + * 菜单边框线宽度,默认1,0为无线框 + */ + borderWidth?: number; + /** + * 菜单边框颜色 + */ + borderColor?: string; + /** + * 包围框是否圆角,圆角的半径,0为直角 + */ + borderRoundRadius?: number; + /** + * 菜单项样式 + */ + itemStyle?: MenuItemStyle; +} +export interface MenuCompletionStyleOptions extends MenuStyleOptions { + titleStyle: MenuItemStyle; + backgroundColor: string; + border: boolean; + borderWidth: number; + borderColor: string; + borderRoundRadius: number; + itemStyle: MenuCompletionItemStyle; +} +export interface MenuItemOptions { + /** + * 名称 + */ + name: string; + /** + * 是否禁用,默认不禁用 + */ + disabled?: boolean; + /** + * 是否显示,默认显示 + */ + visible?: boolean; + /** + * 快捷键 + */ + shortcutKeys?: string[]; + /** + * 菜单逻辑处理 + */ + handler?: () => void; + fontColor?: string; + /** + * 子菜单 + */ + subMenu?: MenuOptions; +} +export interface MenuItemStyle { + /** + * 字体大小 + */ + fontSize: number; + /** + * 字体颜色 + */ + fontColor?: string; + /** + * hover颜色 + */ + hoverColor?: string; + /** + * 禁用下字体颜色 + */ + disabledFontColor?: string; + /** + * 内边距 + */ + padding: number[] | number; +} +export interface MenuCompletionItemStyle extends MenuItemStyle { + /** + * 文字颜色 + */ + fontColor: string; + /** + * 激活颜色 + */ + hoverColor: string; + /** + * 禁用下字体颜色 + */ + disabledFontColor: string; +} +/** + * 默认的白色样式 + */ +export declare const DefaultWhiteStyleOptions: MenuCompletionStyleOptions; +/** + * 默认的白色菜单配置 + */ +export declare const DefaultWhiteMenuOptions: MenuCompletionOptions; diff --git a/lib/utils/GraphicUtils.d.ts b/lib/utils/GraphicUtils.d.ts new file mode 100644 index 0000000..d55d320 --- /dev/null +++ b/lib/utils/GraphicUtils.d.ts @@ -0,0 +1,232 @@ +import { Container, DisplayObject, IPointData, Point, Rectangle } from 'pixi.js'; +/** + * 递归父节点执行逻辑 + * @param obj + * @param handler + */ +export declare function recursiveParents(obj: DisplayObject, handler: (parent: Container) => void): void; +/** + * 递归父节点查询父节点对象 + * @param obj + * @param finder + * @returns + */ +export declare function recursiveFindParent(obj: DisplayObject, finder: (parent: Container) => boolean): Container | null; +/** + * 递归子节点执行逻辑 + * @param container + * @param handler + */ +export declare function recursiveChildren(container: Container, handler: (child: DisplayObject) => void): void; +/** + * 递归子节点查询子节点对象 + */ +export declare function recursiveFindChild(container: Container, finder: (child: DisplayObject) => boolean): DisplayObject | null; +export interface BezierParam { + p1: IPointData; + p2: IPointData; + cp1: IPointData; + cp2: IPointData; +} +/** + * 判断贝塞尔曲线数据是否正确 + * @param points + */ +export declare function assertBezierPoints(points: IPointData[]): void; +/** + * 转换为贝塞尔曲线参数 + * @param points + * @returns + */ +export declare function convertToBezierParams(points: IPointData[]): BezierParam[]; +/** + * 根据分段数计算贝塞尔曲线所有点坐标 + * @param basePoints + * @param segmentsCount + * @returns + */ +export declare function calculateBezierPoints(basePoints: IPointData[], segmentsCount: number): Point[]; +/** + * 根据分段数计算贝塞尔曲线所有点坐标 + * @param basePoints + * @param segmentsCount + * @returns + */ +export declare function calculateOneBezierPoints(p1: IPointData, p2: IPointData, cp1: IPointData, cp2: IPointData, segmentsCount: number): Point[]; +/** + * 计算矩形中点 + */ +export declare function getRectangleCenter(rectangle: Rectangle): Point; +/** + * 计算两个矩形中心对齐的坐标, PS: 计算的是较大包围框的中心 + * @param rect1 + * @param rect2 + * @returns + */ +export declare function getCenterOfTwoRectangle(rect1: Rectangle, rect2: Rectangle): Point; +/** + * 序列化图形变换 + * @param obj + * @returns + */ +export declare function serializeTransform(obj: DisplayObject): number[]; +/** + * 反序列化变换数据到图形对象 + * @param obj + * @param transform + */ +export declare function deserializeTransformInto(obj: DisplayObject, transform: number[]): void; +/** + * 将直线转换为多边形 + * @param p1 + * @param p2 + * @param thick + * @returns + */ +export declare function convertLineToPolygonPoints(p1: IPointData, p2: IPointData, thick: number): IPointData[]; +/** + * 转换矩形为多边形点坐标 + * @param rect 矩形 + * @returns + */ +export declare function convertRectangleToPolygonPoints(rect: Rectangle): IPointData[]; +/** + * 计算线段中点坐标 + * @param p1 + * @param p2 + * @returns + */ +export declare function calculateLineMidpoint(p1: IPointData, p2: IPointData): Point; +/** + * 计算线段细分坐标--线段分成几份 + * @param p1 + * @param p2 + * @param knife + * @returns + */ +export declare function calculateLineSegmentingPoint(p1: IPointData, p2: IPointData, knife: number): IPointData[]; +/** + * 计算点到直线距离 + * @param p1 + * @param p2 + * @param p + */ +export declare function calculateDistanceFromPointToLine(p1: IPointData, p2: IPointData, p: IPointData): number; +/** + * 计算点到直线的垂足坐标 + * @param p + * @param p1 + * @param p2 + */ +export declare function calculateFootPointFromPointToLine(p1: IPointData, p2: IPointData, p: IPointData): Point; +/** + * 计算直线与圆的交点 + * 1用直线到圆心的距离和半径相比,判断是否和圆有交点; + * 2求出圆心在直线上面的垂点; + * 3算出直线的单位向量e; + * 4求出一侧交点(Intersection)到projectPoint的长度(sideLength); + * 5求出sideLength和这侧端点到projectPoint距离的比例(ratio); + * 6projectPoint +/- ratio * e = 两侧交点; + * @param p0 圆心坐标 + * @param radius 圆半径 + * @param p1 直线坐标1 + * @param p2 直线坐标2 + * @returns 交点坐标,可能2/1/0个 + */ +export declare function calculateIntersectionPointOfCircleAndLine(p0: IPointData, radius: number, p1: IPointData, p2: IPointData): Point[]; +/** + * 计算圆心与圆心外一点与圆的交点(取圆心到点的向量与圆的交点) + * @param p0 圆心坐标 + * @param radius 圆半径 + * @param p 点坐标 + * @returns + */ +export declare function calculateIntersectionPointOfCircleAndPoint(p0: IPointData, radius: number, p: IPointData): Point; +/** + * 计算点基于点的镜像点坐标 + * @param bp 基准点 + * @param p 待镜像的点坐标 + * @param distance 镜像点到基准点的距离,默认为p到基准点的距离,即对称 + * @returns + */ +export declare function calculateMirrorPoint(bp: IPointData, p: IPointData, distance?: number): Point; +/** + * 计算基于给定轴的给定点的镜像点坐标 + * @param pa 给定轴线的坐标 + * @param pb 给定轴线的坐标 + * @param p 待镜像点坐标 + * @param distance + * @returns + */ +export declare function calculateMirrorPointBasedOnAxis(pa: IPointData, pb: IPointData, p: IPointData, distance?: number): Point; +/** + * 计算直线与水平夹角,角度按顺时针,从0开始 + * @param p1 + * @param p2 + * @returns 角度,范围[0, 360) + */ +export declare function angleToAxisx(p1: IPointData, p2: IPointData): number; +/** + * 计算两线夹角,pc与pa,pb的夹角,顺时针为正,逆时针为负 + * @param pa 交点 + * @param pb 锚定 + * @param pc + * @returns 夹角, [-180, 180] + */ +export declare function angleOfIncludedAngle(pa: IPointData, pb: IPointData, pc: IPointData): number; +/** + * 计算两点连线的法向量 + * @param point1 + * @param point2 + * @returns 单位法向量 + */ +export declare function getNormalVector(point1: IPointData, point2: IPointData): number[]; +/** + * 点延向量方向移动 + * @param point + * @param normal 单位向量 + * @param length 平移长度 + * @returns 移动后的点 + */ +export declare function movePointAlongNormal(point: IPointData, normal: number[], length: number): Point; +/** + * 计算两组点各自组成直线的相交点(若两线平行 返回第一组坐标第一个点) + * @param line1 两点坐标列表 + * @param line2 两点坐标列表 + * @returns 相交点 + */ +export declare function getIntersectionPoint(line1: number[], line2: number[]): Point; +/** + * 是否平行线 + * @param p1 + * @param p2 + * @param pa + * @param pb + * @returns + */ +export declare function isParallelLines(p1: IPointData, p2: IPointData, pa: IPointData, pb: IPointData): boolean; +/** + * 点是否在线段上 + * @param p1 + * @param p2 + * @param p + * @returns + */ +export declare function isPointOnLine(p1: IPointData, p2: IPointData, p: IPointData): boolean; +/** + * 两条线段是否存在包含关系 + * @param line1 + * @param line2 + * @returns + */ +export declare function isLineContainOther(line1: { + p1: IPointData; + p2: IPointData; +}, line2: { + p1: IPointData; + p2: IPointData; +}): boolean; +/** 均分线段, 返回各线段端点 */ +export declare function splitLineEvenly(p1: IPointData, p2: IPointData, count: number): IPointData[][]; +export declare function splitPolyline(points: IPointData[], count: number): IPointData[][]; +export declare function getParallelOfPolyline(points: IPointData[], offset: number, side: 'L' | 'R'): IPointData[]; diff --git a/lib/utils/IntersectUtils.d.ts b/lib/utils/IntersectUtils.d.ts new file mode 100644 index 0000000..8628060 --- /dev/null +++ b/lib/utils/IntersectUtils.d.ts @@ -0,0 +1,119 @@ +import { IPointData, Rectangle } from 'pixi.js'; +/** + * 根据点到直线的垂直距离计算碰撞 + * @param pa 线段a端坐标 + * @param pb 线段b端坐标 + * @param p 点坐标 + * @param lineWidth 线宽 + * @param exact 是否精确(使用给定线宽,否则线宽会设置为8) + * @returns + */ +export declare function linePoint(pa: IPointData, pb: IPointData, p: IPointData, lineWidth: number, exact?: boolean): boolean; +/** + * 折线与点碰撞 + * @param points 折线端点列表 + * @param p 点座标 + * @param lineWidth 线宽 + */ +export declare function polylinePoint(points: IPointData[], p: IPointData, lineWidth: number): boolean; +/** + * 线线碰撞检测 + * @param pa 线段1a端坐标 + * @param pb 线段1b端坐标 + * @param p1 线段2a端坐标 + * @param p2 线段2b端坐标 + * @returns + */ +export declare function lineLine(pa: IPointData, pb: IPointData, p1: IPointData, p2: IPointData): boolean; +/** + * 点和矩形碰撞检测 + * @param p 点作弊 + * @param rect 矩形 + * @returns + */ +export declare function pointBox(p: IPointData, rect: Rectangle): boolean; +/** + * 线和矩形碰撞检测 + * @param pa 线段a端坐标 + * @param pb 线段b端坐标 + * @param rect 矩形 + * @returns + */ +export declare function lineBox(pa: IPointData, pb: IPointData, rect: Rectangle): boolean; +/** + * 多线段和矩形碰撞检测 + * @param points + * @param rect + * @returns false / 碰撞的线段序号 + */ +export declare function polylineBox(points: IPointData[], rect: Rectangle): boolean; +/** + * 两点碰撞检测 + * @param p1 + * @param p2 + * @param tolerance + * @returns + */ +export declare function pointPoint2(p1: IPointData, p2: IPointData, tolerance: number): boolean; +/** + * 两点碰撞检测 + * @param x1 + * @param y1 + * @param x2 + * @param y2 + * @param tolerance 容忍度/两点半径和 + * @returns + */ +export declare function pointPoint(x1: number, y1: number, x2: number, y2: number, tolerance: number): boolean; +/** + * 两点距离 + * @param x1 + * @param y1 + * @param x2 + * @param y2 + * @returns + */ +export declare function distance(x1: number, y1: number, x2: number, y2: number): number; +/** + * 两点距离 + * @param p1 + * @param p2 + * @returns + */ +export declare function distance2(p1: IPointData, p2: IPointData): number; +/** + * 圆和点的碰撞检测 + * @param x1 圆心x + * @param y1 圆心y + * @param r1 圆半径 + * @param x2 点x + * @param y2 点y + * @returns + */ +export declare function circlePoint(x1: number, y1: number, r1: number, x2: number, y2: number): boolean; +/** + * 圆和点的碰撞检测--不包括圆内部 + */ +export declare function circlePoint2(x1: number, y1: number, r1: number, x2: number, y2: number, tolerance: number): boolean; +/** + * 点和多边形碰撞检测 + */ +export declare function pointPolygon(p: IPointData, points: IPointData[], lineWidth: number): boolean; +/** + * 线和多边形碰撞检测 + * @param p1 + * @param p2 + * @param points + * @param tolerance 多边形包围线宽 + * @returns + */ +export declare function linePolygon(p1: IPointData, p2: IPointData, points: IPointData[], lineWidth: number, polygonWidth: number): boolean; +/** + * 多边线与多边形碰撞检测 + * @param polylinePoints 多边线所有点坐标 + * @param polygonPoints 多边形所有点坐标 + * @param polylineWidth 多边线的线宽 + * @param polygonWidth 多边形线宽 + * @returns + */ +export declare function polylinePolygon(polylinePoints: IPointData[], polygonPoints: IPointData[], polylineWidth: number, polygonWidth: number): boolean; diff --git a/lib/utils/debounce.d.ts b/lib/utils/debounce.d.ts new file mode 100644 index 0000000..9798024 --- /dev/null +++ b/lib/utils/debounce.d.ts @@ -0,0 +1,5 @@ +export interface DebouncedFunction any> { + (context: ThisParameterType, ...args: Parameters): void; + cancel: () => void; +} +export declare function debounce) => any>(fn: F, waitMs?: number): DebouncedFunction; diff --git a/lib/utils/index.d.ts b/lib/utils/index.d.ts new file mode 100644 index 0000000..45eb8ea --- /dev/null +++ b/lib/utils/index.d.ts @@ -0,0 +1,26 @@ +import { Point, Rectangle } from 'pixi.js'; +export * from './GraphicUtils'; +export * from './IntersectUtils'; +export * from './debounce'; +export declare const UP: Point; +export declare const DOWN: Point; +export declare const LEFT: Point; +export declare const RIGHT: Point; +/** + * 越界结果 + */ +export declare class OutOfBound { + left: boolean; + top: boolean; + right: boolean; + bottom: boolean; + constructor(left: boolean, top: boolean, right: boolean, bottom: boolean); + static check(rect: Rectangle, bound: Rectangle): OutOfBound; + static none(): OutOfBound; + static leftOut(): OutOfBound; + static topOut(): OutOfBound; + static rightOut(): OutOfBound; + static bottomOut(): OutOfBound; + static leftTopOut(): OutOfBound; + static rightBottomOut(): OutOfBound; +} diff --git a/package.json b/package.json index 8f2d430..97549f2 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "author": "walker ", "private": true, "type": "module", - "main": "src/jlgraphic", + "main": "lib", "scripts": { "build": "rollup -c rollup.config.ts --configPlugin typescript" }, diff --git a/rollup.config.ts b/rollup.config.ts index 79bb121..683ce58 100644 --- a/rollup.config.ts +++ b/rollup.config.ts @@ -3,14 +3,21 @@ import typescript from '@rollup/plugin-typescript' const config: RollupOptions = { - input: 'src/jlgraphic/index.ts', + input: 'src/index.ts', output: { - file: 'lib/index.js', - format: 'cjs', + dir: 'lib', + format: 'esm', }, + external: [ + 'pixi.js', 'pixi-viewport', '@stomp/stompjs', 'mqtt', 'eventemitter3' + ], + logLevel: 'debug', plugins: [ typescript({ - + declaration: true, + declarationDir: 'lib', + include: ['src/**/*'], + tsconfig: './tsconfig.json', }) ], } diff --git a/src/jlgraphic/app/BasicOperation.ts b/src/app/BasicOperation.ts similarity index 100% rename from src/jlgraphic/app/BasicOperation.ts rename to src/app/BasicOperation.ts diff --git a/src/jlgraphic/app/JlDrawApp.ts b/src/app/JlDrawApp.ts similarity index 100% rename from src/jlgraphic/app/JlDrawApp.ts rename to src/app/JlDrawApp.ts diff --git a/src/jlgraphic/app/JlGraphicApp.ts b/src/app/JlGraphicApp.ts similarity index 98% rename from src/jlgraphic/app/JlGraphicApp.ts rename to src/app/JlGraphicApp.ts index 8e4d852..c699951 100644 --- a/src/jlgraphic/app/JlGraphicApp.ts +++ b/src/app/JlGraphicApp.ts @@ -719,7 +719,6 @@ abstract class GraphicSceneBase * @param options */ setOptions(options: GraphicAppOptions) { - // console.log('更新选项', options); if (this._options) { this._options = Object.assign(this._options, options); } else { @@ -807,13 +806,6 @@ abstract class GraphicSceneBase this.pixi.resizeTo = dom; dom.appendChild(this.pixi.view as unknown as Node); this._viewportResizer = setInterval(() => { - // console.log( - // 'dom resize ', - // dom.style.width, - // dom.style.height, - // dom.clientWidth, - // dom.clientHeight - // ); this.updateViewport(dom.clientWidth, dom.clientHeight); }, 1000); // 恢复 @@ -838,7 +830,6 @@ abstract class GraphicSceneBase for (const item of this.graphicTemplateMap) { await item[1].loadAssets(); } - // console.log('开始加载proto数据', protos); // 加载数据到图形存储 protos.forEach((proto) => { const template = this.getGraphicTemplatesByType(proto.graphicType); @@ -855,7 +846,6 @@ abstract class GraphicSceneBase .map((g) => g.id) .sort((a, b) => a - b) .pop() ?? 0; - // console.log('最大值', max) GraphicIdGenerator.initSerial(max); // 数据加载完成后 this.emit('postdataloaded'); @@ -900,11 +890,9 @@ abstract class GraphicSceneBase } if (graphic.eventMode == 'static' || graphic.eventMode == 'dynamic') { // 添加为可交互 - // console.log(`type=${graphic.type}的图形添加到交互容器`); this.canvas.addChild(graphic); } else { // 添加到不可交互容器 - // console.log(`type=${graphic.type}的图形添加到无交互容器`); this.canvas.addNonInteractiveChild(graphic); } graphic.repaint(); @@ -1253,7 +1241,6 @@ export class GraphicApp extends GraphicSceneBase implements IGraphicApp { constructor(options: GraphicAppOptions) { super(options); - // console.log('创建图形App') this.opRecord = new OperationRecord(); // 绑定键盘监听 this.keyboardPlugin = new JlGraphicAppKeyboardPlugin(this); @@ -1264,7 +1251,6 @@ export class GraphicApp extends GraphicSceneBase implements IGraphicApp { } setOptions(options: GraphicAppOptions) { - // console.log('更新选项', options); if (options.maxOperationRecords && options.maxOperationRecords > 0) { this.opRecord.setMaxLen(options.maxOperationRecords); } diff --git a/src/jlgraphic/app/index.ts b/src/app/index.ts similarity index 100% rename from src/jlgraphic/app/index.ts rename to src/app/index.ts diff --git a/src/jlgraphic/core/GraphicRelation.ts b/src/core/GraphicRelation.ts similarity index 100% rename from src/jlgraphic/core/GraphicRelation.ts rename to src/core/GraphicRelation.ts diff --git a/src/jlgraphic/core/GraphicStore.ts b/src/core/GraphicStore.ts similarity index 100% rename from src/jlgraphic/core/GraphicStore.ts rename to src/core/GraphicStore.ts diff --git a/src/jlgraphic/core/IdGenerator.ts b/src/core/IdGenerator.ts similarity index 94% rename from src/jlgraphic/core/IdGenerator.ts rename to src/core/IdGenerator.ts index 57b2a09..4655eac 100644 --- a/src/jlgraphic/core/IdGenerator.ts +++ b/src/core/IdGenerator.ts @@ -20,7 +20,6 @@ export class IdGenerator { } initSerial(serial: number): void { - // console.log(serial) this.serial = serial; } } diff --git a/src/jlgraphic/core/JlGraphic.ts b/src/core/JlGraphic.ts similarity index 100% rename from src/jlgraphic/core/JlGraphic.ts rename to src/core/JlGraphic.ts diff --git a/src/core/index.ts b/src/core/index.ts new file mode 100644 index 0000000..742c1e9 --- /dev/null +++ b/src/core/index.ts @@ -0,0 +1,4 @@ +export * from './JlGraphic'; +export * from './IdGenerator'; +export * from './GraphicRelation'; +export * from './GraphicStore'; diff --git a/src/jlgraphic/global.d.ts b/src/global.d.ts similarity index 100% rename from src/jlgraphic/global.d.ts rename to src/global.d.ts diff --git a/src/jlgraphic/graphic/AbsorbablePosition.ts b/src/graphic/AbsorbablePosition.ts similarity index 100% rename from src/jlgraphic/graphic/AbsorbablePosition.ts rename to src/graphic/AbsorbablePosition.ts diff --git a/src/jlgraphic/graphic/DashedLine.ts b/src/graphic/DashedLine.ts similarity index 100% rename from src/jlgraphic/graphic/DashedLine.ts rename to src/graphic/DashedLine.ts diff --git a/src/jlgraphic/graphic/DraggablePoint.ts b/src/graphic/DraggablePoint.ts similarity index 100% rename from src/jlgraphic/graphic/DraggablePoint.ts rename to src/graphic/DraggablePoint.ts diff --git a/src/jlgraphic/graphic/VectorGraphic.ts b/src/graphic/VectorGraphic.ts similarity index 100% rename from src/jlgraphic/graphic/VectorGraphic.ts rename to src/graphic/VectorGraphic.ts diff --git a/src/jlgraphic/graphic/VectorText.ts b/src/graphic/VectorText.ts similarity index 100% rename from src/jlgraphic/graphic/VectorText.ts rename to src/graphic/VectorText.ts diff --git a/src/graphic/index.ts b/src/graphic/index.ts new file mode 100644 index 0000000..eecc0b6 --- /dev/null +++ b/src/graphic/index.ts @@ -0,0 +1,5 @@ +export * from './VectorGraphic'; +export * from './VectorText'; +export * from './DraggablePoint'; +export * from './AbsorbablePosition'; +export * from './DashedLine'; diff --git a/src/graphics/CommonGraphics.ts b/src/graphics/CommonGraphics.ts deleted file mode 100644 index 60e935f..0000000 --- a/src/graphics/CommonGraphics.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Graphics } from 'pixi.js'; -export function drawArrow( - polygon: Graphics, - x: number, - y: number, - length: number, - radius: number, - lineWidth: number -) { - const trianglAcme = { x, y }; - const triangleP1 = { - x: x - radius - Math.sin(Math.PI / 6), - y: y + Math.cos(Math.PI / 6) * radius, - }; - const triangleP2 = { - x: x - radius - Math.sin(Math.PI / 6), - y: y - Math.cos(Math.PI / 6) * radius, - }; - const lineP1 = { - x: x - radius - Math.sin(Math.PI / 6), - y: y + lineWidth / 2, - }; - const lineP2 = { - x: x - length, - y: y + lineWidth / 2, - }; - const lineP3 = { - x: x - length, - y: y - lineWidth / 2, - }; - const lineP4 = { - x: x - radius - Math.sin(Math.PI / 6), - y: y - lineWidth / 2, - }; - polygon.drawPolygon( - trianglAcme.x, - trianglAcme.y, - triangleP1.x, - triangleP1.y, - lineP1.x, - lineP1.y, - lineP2.x, - lineP2.y, - lineP3.x, - lineP3.y, - lineP4.x, - lineP4.y, - triangleP2.x, - triangleP2.y - ); -} diff --git a/src/graphics/iscs-fan/IscsFan.ts b/src/graphics/iscs-fan/IscsFan.ts deleted file mode 100644 index 184f3b3..0000000 --- a/src/graphics/iscs-fan/IscsFan.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { - GraphicAnimation, - GraphicData, - GraphicState, - JlGraphic, - JlGraphicTemplate, -} from 'src/jlgraphic'; -import ISCS_FAN_Assets from './iscs-fan-spritesheet.png'; -import ISCS_FAN_JSON from './iscs-fan-data.json'; - -import { Assets, Sprite, Spritesheet, Texture } from 'pixi.js'; - -interface FanTextures { - border: Texture; - blue: Texture; - gray: Texture; - green: Texture; - red: Texture; - yellow: Texture; -} - -export interface IIscsFanData extends GraphicData { - get code(): string; - set code(v: string); -} - -export interface IIscsFanState extends GraphicState { - get state(): number; - set state(v: number); -} - -export class IscsFan extends JlGraphic { - static Type = 'IscsFan'; - _border: Sprite; - _fan: Sprite; - fanTextures: FanTextures; - - constructor(fanTextures: FanTextures) { - super(IscsFan.Type); - this.fanTextures = fanTextures; - this._border = new Sprite(); - this._border.texture = this.fanTextures.border; - this._border.anchor.set(0.5); - this._fan = new Sprite(); - this._fan.texture = this.fanTextures.gray; - this._fan.anchor.set(0.5); - this.addChild(this._border); - this.addChild(this._fan); - } - get states(): IIscsFanState { - return this.getStates(); - } - doRepaint(): void { - if (this.states.state === 0) { - // 停止 - this.stopFanRun(); - this._fan.rotation = 0; - this._fan.texture = this.fanTextures.gray; - } else if (this.states.state === 1) { - // 正常运行 - this._fan.texture = this.fanTextures.green; - // 动画 - this.initFanRun(); - } else if (this.states.state === 2) { - // 报警运行 - this._fan.texture = this.fanTextures.yellow; - // 动画 - this.initFanRun(); - } else if (this.states.state === 3) { - // 故障 - this.stopFanRun(); - this._fan.rotation = 0; - this._fan.texture = this.fanTextures.red; - } else if (this.states.state === 4) { - // 通信故障 - // 停止 - this.stopFanRun(); - this._fan.rotation = 0; - this._fan.texture = this.fanTextures.blue; - } - } - initFanRun() { - // 动画 - const name = 'fan_run'; - let fanRun = this.animation(name); - if (!fanRun) { - fanRun = GraphicAnimation.init({ - name: 'fan_run', - run: (dt: number) => { - this._fan.angle = (this._fan.angle + dt) % 360; - }, - }); - this.addAnimation(fanRun); - } - const speed = Math.round(Math.random() * 10) + 1; - fanRun.xSpeed = speed; - fanRun.resume(); - } - stopFanRun() { - const name = 'fan_run'; - const fanRun = this.animation(name); - if (fanRun) { - fanRun.pause(); - } - } -} - -export class IscsFanTemplate extends JlGraphicTemplate { - fanTextures?: FanTextures; - constructor(dataTemplate: IIscsFanData, stateTemplate: IIscsFanState) { - super(IscsFan.Type, { - dataTemplate, - stateTemplate, - }); - } - new(): IscsFan { - if (this.fanTextures) { - const g = new IscsFan(this.fanTextures); - g.loadData(this.datas); - g.loadState(this.states); - return g; - } - throw new Error('资源未加载/加载失败'); - } - async loadAssets(): Promise { - const texture = await Assets.load(ISCS_FAN_Assets); - const iscsFanSheet = new Spritesheet(texture, ISCS_FAN_JSON); - const result = await iscsFanSheet.parse(); - this.fanTextures = { - border: result['fan-border.png'], - blue: result['fan-blue.png'], - gray: result['fan-gray.png'], - green: result['fan-green.png'], - red: result['fan-red.png'], - yellow: result['fan-yellow.png'], - }; - return this.fanTextures as FanTextures; - } -} diff --git a/src/graphics/iscs-fan/IscsFanDrawAssistant.ts b/src/graphics/iscs-fan/IscsFanDrawAssistant.ts deleted file mode 100644 index 4c7bc1e..0000000 --- a/src/graphics/iscs-fan/IscsFanDrawAssistant.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { FederatedMouseEvent, Point } from 'pixi.js'; -import { - AbsorbableLine, - AbsorbablePosition, - GraphicDrawAssistant, - GraphicInteractionPlugin, - GraphicTransformEvent, - JlDrawApp, - JlGraphic, -} from 'src/jlgraphic'; -import { IIscsFanData, IscsFan, IscsFanTemplate } from './IscsFan'; - -export class IscsFanDraw extends GraphicDrawAssistant< - IscsFanTemplate, - IIscsFanData -> { - _iscsFan: IscsFan | null = null; - - constructor(app: JlDrawApp, template: IscsFanTemplate) { - super(app, template, IscsFan.Type, '风机'); - IscsFanInteraction.init(app); - } - - bind(): void { - super.bind(); - if (!this._iscsFan) { - this._iscsFan = this.graphicTemplate.new(); - this.container.addChild(this._iscsFan); - } - } - - public get iscsFan(): IscsFan { - if (!this._iscsFan) { - throw new Error('风机绘制逻辑异常'); - } - return this._iscsFan; - } - - redraw(cp: Point): void { - this.iscsFan.position.copyFrom(cp); - } - onLeftUp(e: FederatedMouseEvent): void { - this.iscsFan.position.copyFrom(this.toCanvasCoordinates(e.global)); - this.createAndStore(false); - } - prepareData(data: IIscsFanData): boolean { - data.transform = this.iscsFan.saveTransform(); - return true; - } - onEsc(): void { - this.finish(); - } -} - -export class IscsFanInteraction extends GraphicInteractionPlugin { - static Name = 'iscs_fan_transform'; - constructor(app: JlDrawApp) { - super(IscsFanInteraction.Name, app); - } - static init(app: JlDrawApp) { - return new IscsFanInteraction(app); - } - filter(...grahpics: JlGraphic[]): IscsFan[] | undefined { - return grahpics - .filter((g) => g.type === IscsFan.Type) - .map((g) => g as IscsFan); - } - bind(g: IscsFan): void { - g.eventMode = 'static'; - g.cursor = 'pointer'; - // g.scalable = true; - g.rotatable = true; - g.on('drag-start', () => { - console.log('风机拖拽'); - }); - g.on('transformstart', (e: GraphicTransformEvent) => { - if (e.isShift()) { - g.getGraphicApp().setOptions({ - absorbablePositions: buildAbsorbablePositions(g), - }); - } - }); - } - unbind(g: IscsFan): void { - g.eventMode = 'none'; - // g.scalable = false; - g.rotatable = false; - } -} - -function buildAbsorbablePositions( - g: IscsFan -): AbsorbablePosition[] | undefined { - const app = g.getGraphicApp(); - const canvas = app.canvas; - const store = app.queryStore; - const aps: AbsorbablePosition[] = []; - store.queryByType(IscsFan.Type).forEach((fan) => { - if (fan.id === g.id) return; - const p = fan.position; - aps.push( - new AbsorbableLine(new Point(0, p.y), new Point(canvas.width, p.y)) - ); - aps.push( - new AbsorbableLine(new Point(p.x, 0), new Point(p.x, canvas.height)) - ); - }); - return aps; -} diff --git a/src/graphics/iscs-fan/iscs-fan-data.json b/src/graphics/iscs-fan/iscs-fan-data.json deleted file mode 100644 index 5d2c674..0000000 --- a/src/graphics/iscs-fan/iscs-fan-data.json +++ /dev/null @@ -1,66 +0,0 @@ -{"frames": { - -"fan-blue.png": -{ - "frame": {"x":0,"y":0,"w":41,"h":41}, - "rotated": false, - "trimmed": false, - "spriteSourceSize": {"x":0,"y":0,"w":41,"h":41}, - "sourceSize": {"w":41,"h":41}, - "anchor": {"x":0.5,"y":0.5} -}, -"fan-border.png": -{ - "frame": {"x":41,"y":0,"w":41,"h":41}, - "rotated": false, - "trimmed": false, - "spriteSourceSize": {"x":0,"y":0,"w":41,"h":41}, - "sourceSize": {"w":41,"h":41}, - "anchor": {"x":0.5,"y":0.5} -}, -"fan-gray.png": -{ - "frame": {"x":82,"y":0,"w":41,"h":41}, - "rotated": false, - "trimmed": false, - "spriteSourceSize": {"x":0,"y":0,"w":41,"h":41}, - "sourceSize": {"w":41,"h":41}, - "anchor": {"x":0.5,"y":0.5} -}, -"fan-green.png": -{ - "frame": {"x":123,"y":0,"w":41,"h":41}, - "rotated": false, - "trimmed": false, - "spriteSourceSize": {"x":0,"y":0,"w":41,"h":41}, - "sourceSize": {"w":41,"h":41}, - "anchor": {"x":0.5,"y":0.5} -}, -"fan-red.png": -{ - "frame": {"x":164,"y":0,"w":41,"h":41}, - "rotated": false, - "trimmed": false, - "spriteSourceSize": {"x":0,"y":0,"w":41,"h":41}, - "sourceSize": {"w":41,"h":41}, - "anchor": {"x":0.5,"y":0.5} -}, -"fan-yellow.png": -{ - "frame": {"x":205,"y":0,"w":41,"h":41}, - "rotated": false, - "trimmed": false, - "spriteSourceSize": {"x":0,"y":0,"w":41,"h":41}, - "sourceSize": {"w":41,"h":41}, - "anchor": {"x":0.5,"y":0.5} -}}, -"meta": { - "app": "https://www.codeandweb.com/texturepacker", - "version": "1.1", - "image": "test-iscs-fan.png", - "format": "RGBA8888", - "size": {"w":246,"h":41}, - "scale": "1", - "smartupdate": "$TexturePacker:SmartUpdate:e7620bd2d73cc0b3e2deea9704e7eefc:f129a1d9e4b9ba57720b3861c22b155b:eb2d421f7759984b7713aa4aa5354134$" -} -} diff --git a/src/graphics/iscs-fan/iscs-fan-spritesheet.png b/src/graphics/iscs-fan/iscs-fan-spritesheet.png deleted file mode 100644 index adec75a7eeb1947842bad720e4c05c218c9584cd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 15944 zcmW-o1yCH%(}oW}T!Xv2ySuvu_n^Vu4|liVmcWnTPH+kC?(WV(aQp86UCrLsRqamQ z?9TLbzx{NKx~d#15+M=*06$?L0$k_iopa3~} z_y7PoKtWnU+h^^f%iCi?=i~D;AnQ~ljq~)UBoHxq#-9#K8e_19KCUCStvs&e7Y=pPF7jt$)AuumgqDw%GziOuS^!-OJB`-!SAC2eZ z^TTTS-Bo7ipLrKKmUk=f?f~VWh6>VlNFE4E!9V3SKpI6WL@KNNI zl%(9;IK3`j`d?bJKAihPMAmzrP5E9-p9|}1rR^uwX;(vf6yW7GOdFn=RM#P#M`UGz4_g@a^j;-O5Xy z1w8yIu02ZG8SaEQe70vJ=RGfeVt$Vk40u#R>W=+PB3=aOzQp;c#~@E0RR4!n8~+R7 z4#Fi+JmBTDe9*Kc?d`5GH^zCL4Wk5jBaCjcgIFO=2uBA9B_E_w3VM%Y@4jC$%=#y{ zV<@D#@ar8sC3O8JgKrx2{0$lwF}gq4PL`ZL7DplV!u)OXI>=ike)*#Q^ZN5c?F(X* zTeiA*ABTB1FojY+Hf`jfO1rG;`TZTet)@AV$hoKTd3XD>rEt?JYWo^NMkDK8SRoZM zev|?7ercD3zYOdsFuYh$)9x73nA8%XC3f<^G)Ju5;+aYPKDIdlAaY<epKgvQ0fD1;0ssiIsMPNr|TX>&h8jL?60? zqls9VuILcty&c%YzrUYUt6i~B|EKzL5~!$8J9qG%299l!|sc~*{WmT%Jo+ndG{g=OS?d2jlmBiHAsL@8%hX~Ejidl1kl*CX|7Z{@pqZAS^VX+j7|Rd}%gG_!ju+?ltm` zFt(R(GK`GLi8EfAZ@?=*ZWc)%{vSvJ>ycy#UGxdmeVAz&q&pP&I=1)jb&QNuOQ(DN z=%6o=39sEX&|X$G5oT}4KU;aVy}c5tjtj-U+3KpThl zJVx0z4}e^B(s9)u_c|Kh<$GscF>V*zm(at8NnE^H zpc^^ywSPxrH`@MA5ltBo0)Vui+!0q!Y!((4><&X7|7kPc2!DoY1xA`ca^6`Gis_!0cJ zPnI-1G?a7Q^=Ps?d==o_365M?b4u`aTTBy)Ka{KdaX~kM&1LPal|M;&kpLP*;a{UJ zX;^hd+;?pK{9RPvQvWIT`RCck!XorflgCoh)YFoov%)3o*NFip-GA()f*MnA3^cBL z!iWkCYdM%mQLd^OGgEhaUSVLYp+TjrFHJ42kHN2(tx37cw0H3YTtOZ~Stfo8gh&yV zq=ElZNQW8%ZL;w`7I?r%LILTF)X8eN{`STu0JoJPn1As+fjxpJS zTsS^WR<=6-rS-JY7$Ix9#)fdfa*eUJ=~)>)7H2jJV+NAquUnxk+0u~h>*3*b zF)4Q?hlWnIy)UvOm3uPA+H7zWi3{^vRs+R39c0g4TjAiMGEDpNqwVx0Wq-V~ z(jn8s!vkfz4XkrEd=U>BWbDO43K#MN>4$ybSo8&{tN?@eTxa^vbV~XHfWm{e(tn*} zq(l7_QalN+LVTAZZ;Q87QHd;ePIe@aMUzOD0d8J4Ny}JXVp+KZx7;shr~2d5XjX7Z z&i|BTMW9EbmI*1Nmq!e(J4F?VmkEosjUQI~zSd*8d^>-Ss$^hb5P7}T^(yzxsKYD& zVq{kfx%=ZS;a+Q~EZ9K~?i5!1_X4F$x9lGjbw+XS^#zgmclQP!*E2QVz=zY}aW!H# z)42@`(hrEOxR0qX^QYdD$K)-Jx_aa4Fp`) zH(8aYv}uy8SyHT7rkp&qKxiD9;_7NtvcPuKqX)FQwd z0RrM-V@^wQ1*}kVan|$o+m{qM(iAcgzW~gEy13e0q4FPP73pT|?DY-5LtBNacFW3W z#Q+K9K!~}AmFPe8cupjKrUe3qe)#MSi^L(i~t&m@{`y|i zeSLPE& z-I2dIg<^JlV6ObmK?9(3c9K!9sKOw77-gOlHxz-RPtOS!*t zUwLVK+rwyk#QuAG>=9$_*o}mHiT{|v*KUF`D2_+ z;8Sj?Qfg`{sowj9mL(E0vQ>S3y=7x#qu+(?X_H4x$qF`85j_@eT=Q@uK{mlSneRby zLE4XYF=mKpI^RjN0Ygu4!7*VCUjyilcO}lgCywx;qfNMs91ix z_3`@NIyygqf067JbMcGgtG@i!06htYNx?1CdA~RpYD@vm&sLpp0sGrrkN;M=ybCI; zNIn<8ni^y8$FX%$f4+=>X-*4+UV4WfS~v#eC9SEW>z|#zqL-$9YwrzQzh=-7&sAI; z_@SaPe$91)Thf9X)=6q%>7WHK`ti6CR?Y-@N|i*xJG~(e76Ac=jL)-a8A|Z@-F`ds z$IO*|OhOd0+dZj+B)84%2c8n>tv0QZ%EJOY&dVC)|CKpdwL@)ju#N@g(_V$*N1_0eO z31V8a#?&)OvE&2Te}49Y`%ckoniaT#-hdlGvi&TNN3)&WFSnyVW3j#v`#H1~Pm`fo ztWNJI+-guAxqRN2iQZb$H84l#YOG@J3w4=~+xgnp191_GbSwSwaggACYTDI4>iu#1 z^>c4xRVWgLz-^nUwmYvdGZQUA7A9XcYR_DTsj<iRa8kyM?KkPxwcDQjs-)t|!d^vAO}#_~D)*xvq_hnpL}wk4m4_j_`lsQ(d~`wQOV zA?x*6QVbp@ww!n^!p5jE6LJ(vJ}e+!>Iw%22gqpeT!BI!I;RT2PZ#(eaCB|B3=Nv> zAFzb$bm|qE`Oer#oTKkv<7DFLIjO_tw9%&F_P@Vwmuga&Hdm;L=oO{<;U472iLwCtHCg(RFb}@Zb`ecGg<#Qjp z04RVtDbN=x2IpY~>uQIue3`|#eIe1rs70DGM6wtJX_^&~ebUEa9HGv`Gvv_sEuE&n zp-!*b=kXn#B1OJPo6%p78cV@L(N#c*w>8Kb#--N zrli<#ZyzgxG^us`)Z+nYh#?&wDp9G5ou+3XcsD@g^h53SJ!s`SFQn;J>#{4u!ra}p zjWsTw7x-TZye_uX|K20kpEu%gpP{|U+VqFX>AkU=aN!b6`GVNMjTN0AM-{^n%vU+mG`4DkEO8| z*Q(pa--)O@x4W4hG4eEuOmYl0jgfsl`>M%ynhu|zvuq_yBXuJExPT|S7@lTZ={;tK z_gxQK<akT6>6?AVsXd2G)a3~UL36*O)Ph@KrFUv>yuOzV<(=6O$0Qg~ZOvt1XjnXJTQg!AeAD-enKgcY68QMOwY2z6Mp+pJ3kwSa z4-cWsB#D5ljON#`az|Hw;-K6~v}|Q~4V*q#;`YFxe2%5IdvrCC>=DS%_V$^@MY!5! z>_p zGiDxE@Qh68PpASK@&@WQKyg}GRBPEsJJswl)^2m$jX$vMf>M}NT-VWlgztE=ir+X$ zB|g}+m3M9soFr=ByuJZO6z>Tlw<83@hUgiD`l`xlwhVXuiX(r|7e=@d?q$dDA>E{| zP{J6jMxT?WG%x^(14uQ(6OPS~eFLzt*KcY!I_R`OEiuDjTlj+(K> zi2rdlyLfEpiEA!~-rTKRE3utvCs&u@FQ1$a8XXz^CPfqV9jL zUtmOA2aaA!E_(Y?!TZC6nwpwZNejfbIkHt8w66;lw;{eTckrcDNx*$rRq zVV%GxiJ^ku@ME8Stz*N)aszMp{Uep5z8;|5lo~ld-PHxBT-6_0-9e;iZ^=L}Mlv!A7ZK2p~J(mZ|1q!wUlXvA^7( z%0ee~WwzX%??LIXE_;tD90lIgl6G~P#1Ke%7 z8+qzwi59L32qLxRpsFdv6Tp6vDAo!sqE1#P<~IdSE>dvoAYyoc0cw(SUeXg)L2e0= zbycFSEwcE6W&ny!c=s3J>-x!uw$93A(MjJJS)sHa6+Sb>* zr54)j=jH|u7Lm*MWz%5CmziRznXRqFmKNTH#YGBUUR*dhxMX>1i0h6c6Jn0<;qARI z8Jf6$*`LkzWv}D9vvugut@f(vM?~9-bSQZ;5gwk6dPRD}tfj11dU`r{R%WJ&SAyHo z1i@$~3t2j`sGr`cr;k|ee~ga>rc6XM1QV~m!M_Vt|Ax;j0{PbwSGp+O+&u6_|HDAc z`Qcpp$C~K3YEzhwASA%uL63If8I##BzTiRX`F@|hmeyZ1VGav2iizRCZ*py@C@uG3 z?z}uY%FDYL=hXfBRjDQTL4WkP@KUqgsAih!H&Z7d*--EM1o_QJoc-WGBL_OO%TQAc z7hYoc{QQKxw}Af++-9f|L&`7@_+fK%De^>+NrwBT?)Vio_r~8FmR1&X7LQd)G2M{k zfSNe&`+zW73KQO695vVT6%g?!BmzSFfC3E36J zkDv9UoFcW!5w`F^1odTTpM9&5F%m$&>Z*I8nR@v2CeoO-L@0_GRd2V}&!>a)GM-E0 zoJCxR>SWt9HNc39!VQ6~Z^QS$BOD}3R|a#!J~w6`4eQ3%jrx}@o)f>(tyx`drjO?r z$efZ8^Mi7KK5gErTiU&K^aK{4>!K8tJUgOTizgG2)BfJ;?W%|B~EIw{q%LZ*qEe7_oK=s;{UxWdm$% z>vJU^494HQzCY2#F7HcdX=x?Zu^qLyc^C*T8XLFh`*j74rZc2HK|~WrXGceWLyYiE zM;6ClJ?(+BceULww*%O8D%4X2B5|Fa!jL%(aS33<`tH_^Vbc|9lxeZ?BPG6lqY)Gm z0w0NOZ@JXeyqtzV9Vp1i3^%6E zR}6@TVJBXxUiu$3qK-`yFhUA4-^_*6yNa)@4(G#O@ze+fn{T`>lWXQyz?-9y93~5& zG&~F6SOOrAr2eaH<7(BFOPlo|&jQ<@(aVF!G8?B_zQ3K5S_@aS67=s0Voz^zf&&9m z_>nFit23s>;>z@}#DcI-0U&Y^CD7JG&=w1OSC>&^-=#>Oa_}X-3N>n4MN{%mjs4CYE2cm9n-im=5@InN6F}zFF?q0<(%w8f*8W$eDGEiZOT~s#MOWcKL%I+- zlgrj!Wu5u?n6i(wAvCp)zylX=J3Bk?+Z{^y;GjfgnKoCpmZqkFD6mk!7yreYS0l|j ziO|9rI&@rO(}2@2QK+j!RxVc*+t?n}n1SuNxCv59$);<`nX&(o#||tb#z7ARP3P?ru`qQcQh)eV^k?Z;G^WBvK== z`r(3|)}34;F=8p$@LIt4R{EK#wll}Nb={-OQ$BaG*c0wzwcDpwJF~Z!)V^o6aIaHf ziqM%R@AlC=gY0)8bGc^QyHQAkDZarUP@*57d@KNtQm_>Vs&G2Vy<5;$6TlfFz6?d9 z&DmgfmR6DRvWxoM9s-r@heoL+ZiVO~p!(e3!PUTcn>NHut<9xKDW;pCklV{pEp6cVCtCwz&X(3%WjR0w2Jb^-N6*130MmK(?cI8>S+8iip>e@!(PftF!+y)Tag7XEH z=g;QV7u+~c8L2>+3ois}tWk7QCkh}mx5~giSiC}e?`xdX@Dq5yysW(Z5x9NmMu8Or z09fo>AWGn*8MC(5w6;98!!VNVD@8LsfU=N_`o*J9BIyR5u?XDYNRn&Cb4dy9fCMps zeL8W?Z4o|?U1xK2a;<3j?0wl1R(73yOsH`vCpM@hNsx_99WjOmETZY(w2PLK2twjU4A>BH@)>uvNb_D-;s8-H z`c%%yfvi?40Bk^z{*QlWmhjQZn1Ep*5CPGp6Iig{>lOr?_C9k8m2$l7(&%6BMoH6h>6C? z{txDkACX@B>kvJ*jL!h9AWeLY}W zYKT4Am3Sd^WSSJlag0y!VbA21;Zc+{HQejd86A zc{~HJq3_RsPC(q`JW~$%eDR44z%3{oZtZgR00$E=E!#TCj|P+jnZYKHQ~8C7nygjU z!AVg6LQn;h_Ww+3xxm8Ofmdk_cuki!5qa0WQD-7>IqT=F;-0aF@KF3fe`aBR(L8h(Q62{UJ9;0G&9lR&a{8z zh@E)9=98E9wIO1ZOdH`LBmlfT3ghnA_7H!-gfiK;eiBWz3NKO*=di~?h%Ckg0{YDU zAw_`X@de9~C%(`!AY#liM*o*7zneOHqsi?9o$M;i%?uNPailM?^V)EvMXwDj6W%`) z+M%a~H|^@73POZZJX^2ua3-2n#H{ngvUQ~0`KRgfEFVsQ#9>eBmJKLPJRUG7s9j1v z(OKba7NvB*Mz#HHNv5LD!Lovv1i(p@A)q6bgh#Ibj;i!I{eqGN(8H=%xu)QG10%`P ztV_%RfYGps66xe9zy8xmDUlZ4Ylxbl!9uihJ7i=0Za{f?Z;ozI&Fl7*OBIsMW$ntX zqCr@l3DI{66X0=VBv{kJzO_=M5di=sSN~%H2;zx(O0KP`Az9|6+McbXfo)=ai2Br` zM4eh-Mx-*ItVlyCGhd=vd~#pctyvrkSDPwiu-fd5cIOKn$<3;OG9%Z7Yt~Zv%AeRP(0}U|9lcc2;OEELB z6l&u`ii9*5({X-?WE@zz34AF9V*`q~WPh=wLDl~xQ*uIlP+7pc7=d=aiW%$?Tdpml zNxkHrl%kA5oFMo@v79Gvx zLVpyDRE{dIc(Lh#eT?wRN))h#p+@y zHD_Dppkn|AaG2v(n(?X0!JqMXnTsxOgo)%^6+-T}SVL07Xpeqk&5BEaovB;L=i95Q;*3}7+=&x%n@RY9EDHh$3a`fB#ev;1kSY@+=UZ&5mMRiv= zxDVm_N<`wYM+sacoP$SWDVcuiS8m>)P}4*-2dl$5qm7C}gz}e>RSZc3kcU~+Nrq+M(F*0y{aM?e^-wL>6sc&k61%tsieqBC?&7T8TwGZzW{iHfZ z;dG?_Kk1U29hQ%`71Wgec~%4U|xOSWC05cQ8m)Y1quFY8Uc$T*p+|6f@1 z9i-B-DL1lEo`)fr5fpnqEQ1El5hk5d%2g2U5$vTn z;AVGaDd7&NXGjpV7oi7`06bs5v_6?i!6TCQ!tf-33}9Svq`7v!Y5*UJU@mt!=KrbQ zt-j3{ij5QdTt~db26o8~LV`@q)HI4Tc?|Q_LgNKZ#Du@n*bDZag`$NS8A8lFG~YbG zSGj818~kSE;)02ZiBYf6j)tTxlxYVlw95So3Wx6AXgI==32ar%u_q^0beaQtF~x;K_|?Bnhw+l1-UiLScc5(lc;PJkdLc(9o>CV}LPy@!Zp4kj{r) zRrTHXwU9QO%B{tonSlR3V)3JFtZK)P+9D7gS?scl0dD=6Kck`l;Y9evz-lH+$xuVH zC`fu|i|0HBc;$qY^))b4^Age5;_YMYaj*)|bn~!2WKR#I&~5D_o077dZ=}`sJlGeu znz?ad9ifd5kW{!9mzcljzM?80M+ebjBI$E~70$<2_l*=!kqqYqzZv9yveC&yNg%76 zO7#}O>;QIPe#)Bl|6`|BZdK;uQ@3e#o)>*x5<0_6EIfTP5elk>IGby}N z;XBpo-&7oLC$7v$F2rUJ2SU_OcEe5n<`0Nt65K3fZHEQu@jmaFDd`Wad#5sRXnGQ{*mx2nb`^!;_U^f$JA zRQBGt5NiwC@@%x3$g3d~4Zxq9pU1?*i#j;4`uX#x*;JkY%c>PFsbmG3?xnAPjeEUiUCveZow*Wmb$f{*Vjc*QbF)Kr_h>7t+`i`IFw zy;<#5tG4GBzK^l(G9NL2yuDHA?q@csEf)XZT;Pw?kTxrF=TM+QdhtCzqO+8TSPuED zJGcty3=^_sN&S|u_|$HzCj`ii0F|Pi*u%D;0TdbOIfE>NMSX#WUXR9)w1xbx4b$lJ z%1BX}EWE8hC%xA=c!_1v6v$;LC9q^96g5uB$k0W3amnQHx$Br$J`I*!N}}O22ZJdw z18Nrgq*B@4nTbn)tXNPJm*O&TbB2a4Ny?N&W!l2&nQ8ChzP`SN_`&bz-^MObZnxDw z*ILY;6E+F7BI~5RVu8(qjP`$_|NH_)l-CD#z&d^b;V1eXBj;cah#SJ)96Aw_T`iL1 zL+d&JBL@mX&7$TZ)~_76DxeGrC#jum*j0)v1WGs+jFv-;&b8Opvo z=qD7zmxvkYRQz5SH#}#~+Sn!x_w-G=43I98E%z)%4lP+)->r}jE@43!o(_T?7lwDdXbk$ zOifE0#I_uqrIO2Q_W^z(`jF?Rw6?a!!b|)<^!G10MEZoVDG+`~^mFeei%KdEo+&pc zcV=b=5FrWGWdfNQJ060?+Kd{SnxPpT^5WHa zeQv}n?x6NkF##)Ua}CXs3blCCYqt3+e{0m;dVP-ck|HVvd>}MdC?H*toC4}IMgI9% zTyCf_PxJ78hk06xC6*l!olO0`1SpBY&fXV3S(d&jH&8r}EHsI(hVsO~CetUMIs*?) z4xygDJIS5@$MM#dchM3Td_JBrTNk=oB|uOkUA6<d?;Qx_<7Q$BwbrwclIUw6{ z=&bDpCU`D5Ji<@ z6Pbjc$Wc0M)*p^Y&&>R{JMeXOWhELi7bo(C@aD@@21Fj;mNdSa-aW~EzWDU@v<6`{ z=`o*NT!gQFmo+pbG6_2UV(6v1WTIsu`TREq`?V>U*ZoL&JASrtyNqQmvMmU94_oFh zHI}?Qow+=W;75wV_RDclm@nHs3e&E*Eu1_yT(~V^A}&n;FLb!BxJ3ad#1fHuW8>^U zA^m5cjg)w}{+ORdwQ;gp*`Q_^msLbPG4542Y=kQkBR#!>^t=tap;2tQC)p`h;~@D` z_ai_wor3&NO>zN(3lNkZ-Pa{Cdd)C`#6W8!>iAhrhDdcB6a&;PzM);90tI3(b2f?; zHTM;T&v1%+Mw0W`nDI>}2kXj|yDctk6Ed`3WFKv)8)}~L=^;+qY0;?F8TS6B_x9y^ zmVnuK3(Rl7Zx;Vhc(DM~&{eQc`)M5aaarHcto3iRS4-dNNk)r5#i4Gsq0d`?*MFwt zoW?*8sp7DIj|3qES-R#`*!u-6ip}E*_s9@6{QcRcF;9<9 zVZBm+2mIhYZ-?3cxA-aXI_gA;IP-v@-1#NOd8IljoQ-N7tqYb-q-2g16d5b>g<(W*$QcwT1K zu)cn*tmuVHQnYP4ZMdCJwyOPL_tllNS#Oa-Kv&ypx#Y^7v<`zLb6OnNrBG2-Op^$C z+}0giH-luZafn3BpF%MA4vcRB?Fj-P2E1eq>fePE8?*O8{Xl?mOVC5c?GyU~BedOf z@5w5xMUs^xIE(J`7@r)gWT!cXUG-thM3^pk36iK;$0Ed{o#&y=otNyJmni{*n9~XI z-|o}1v0D>JgdSq?Yjb%I8#8AuThg^W_$(|y5@BYe6a6B^BZwi+5N41l#R!Cm5GnLYP;;MID+a>gSCCfR03WZ2MsYkli(R=XT{!cijgl0J z>KpqruRa!XaNIjD7FXw7ZiDCgWO~|nFGsb?NIEXMsfbkeJIS4L%2F~i!sbTzgK#y} zhqwS`bT<1ii zYmZf7w?6@k|7lR&;}!V*)~s;3GGZ}eU0ypXJEHOGAPE7HktQM7HxrIub=g=NRVi%R z@sJ4_2U$;a2Y&PPZ1%jcS@$N+gKUYH9oOBjD;X`0|4wEzg^ssxHO$U?1Kr?$$Tw=z z_jvEvn`ZC6jFn-NYEV>3=E$*SK)L+_M#O^3(?C1vRXRR6N^eeB#YG?&`ZIn_yk=+O zbOGhSvWJ8Er_45vv7_#^`lk z{GIRzPUg&=E{Rm=M>?l<7Dr1>=KiX;`yJYr&+w(QT0Zw_ECIybv?ma8nv+Ws$!)J) zS79GU9}9=$qpkY5C3?U2l53W$-2KXuW53K~6)kEe0kyEKRVP5>FiwP`BzOVBfc=Ys zP(j${T;XqNbRph6XyE^SnlF+g*W30?busNCGMJ8Rf(ifr0hN!L-)m6A74Spkx-5*y z)W}({V;5Jm{||3LwQwgkAodR7fMtX~ zg}6iana|H@4@Ze4wY&F->FCV=5W7j^us_GEB=a%r`yg_DUYs)FFPahd>sv0+9_o zf6kw7tjy@OVgpjKwC*C4=uL96v!Ni|NV5TIwsPd}-;C^-5UgpzHFwZLLQ+x~5;j2q zg`>&Btd{4=*23*B|Kn>R!F58l{Pg$=VZ%Q!FXy%EpMSBLyiFX5oI3+Q`j$<72kNe_ zjuj$Q8teBwo~Q2CO?_LeUNyHc!X**u7eShA{rap3(^yMKQun-C#e}=CVw6GT2jphN z%lXzMNB*QLPk}NzzLu=HVzSPQH3eeMyB|@7dajG{e3RLpF7K7K1i0N#Sf}aoe567| z--y+PIh`#W?&gd#LsB!Pg_?Ea6f01a*)85nKJpx6j6!fi%-p|x4t3PcrVp=&fqpSVaOS1~ zGL)D=;i&uIcP330uvpB0TG%RW$E`gwZWfx;IByp4k>)QCVV{=~)3LE}nZ_7A00@9k zMI_=!%>sc7H7opDW~Owt8(txiAoE#U0Kc*4kih51>vizX)-MPH zd}QbxkSSz4)qq?A4=RS~Sl$#IRMX-nPl4hm^I>NDTF*VX4plTjD{;~!*~BtZqJuy{^YGzR&9x;yCJkFAtXJV$*MH4nO*Y^4Dt=Lpz02;6S(zVOFZ7iH4tZHIC;-V+zt9&%F$wrUj(mU5MlfCdQv8?g*TQci}Q<@)k@ zJ$~smaO$y>&&OvuQY0bv`#%J9;%Kp&AVT{LtQ7eJp^|R)FLbX@L(>UFrW~K(RURzB z$k;@-@VB#{tAhEYND)J)Q+nR^cELu@60c$D7gsPhF#!5r(f`{#A|}9!;!h!B zD)0r07WiaDsjT&8ML%6{?((?@3-CG0wh87Qq9gMid0R5PmIs*W*$*AS9c8Zig@R(K zODk&K1Yo<+c!Zs6#R?UcR5U+|==?}n;=bebpQLzV$>iMnv`paSjk2gdUf&_o{yR{DW7OR`fZ>5kF zmjAUuJmi%iK?QpRz6N?mNm9UuNj$v;s%iS2or={NimlmCjEvxS1#gGIS2o9S{lz!q zlu0wW@DegG>}j^-$2ro=gqyxI!-pSEB(WrI3zlittXTWZYMw6Nr=y2#$61?y9J5^2 zKl@6*sl>vk6bm$Gf<#Hx|Hfj#;80#RkjhfhA3{Tc4gsd&pkKHX^>P-!qbi23gRLje z3d12aTzK_#<7!0iawue7#=q>??}W1;2^twpcKjWUirIcQk$8&O1O5;MrW?R?>DHB* zu8y|OIXwE-=kzk)2X#D=$wseemwke(t;Xz$%KB+!4sWWK{gm9eB_Jw6T8n9R-~?TP zRe`rcP?kfjD*3BYdc!2 zjKAntM0`9vefwausSAN0eBP`DCimPAWFnq}Vna={R5vSQ!sod> zGBUO6xY}eCzEErdjn*B-(GLu%Qz>cf_!hM1Aob3^_|%|aNqfx@Xgf5!u&_`VU+;5* zLB|$*?ezSFeOG?nDYW04LPbUAZ?r0dg-9rAJ~Ya{y_RwelR^2OC;q7lvSpxv$eD`xQrq5F>4>K-j45x-u-{ zusL7l`((E z3L?6V(}qK83oEo^t1g%itd0Q~^_J_yPd=~5w#_TOciWTQr3{1wqqH0R&b*4&rsxtl z>N@&x|6fKKtiFI3zPY*@GjHQ?a~s)XQqN*&XlPe(oTi#DtmAW%I}kx~NuqDeYdB)= z-Knl)JPQr59F7kb>9e~1X8o@cpEqEoA~aMY;raPl;!RlwN2a~2OT=!y#~WuUzmmzr zW4*CTRVf-3%tpM@Qws-BJemv;k^OSaG{#m#&q(O^+srn|(nxY+dW;@gA&O}Vmvp7I zr|wQ!M%Uk8ZUhspM_u8O`jIyJsK_MKVZ zf+)pblJ@qDoQ<5t^RjATVCFFOa5!>kSg2n{@Tn!!(?~|Pwzks#{z8-~K>FDB3jw>m zxAtx8#@#yz!W-CqX^QxDt>*rG8GAg-w7tf`)|R@VvGFg&qYEVmO46pq>Fa0r%!Czz z)I^`de~1Nt(A>B3WXCj3XoGu0V8VNorTdBkIA|q4<2anQyYqhtd0)}oN9kuKD^ZtB zAJYM$!^Y!@95aQ_w&axWd*jQQ?Ww`gR|VVP=v%xHGx2% z>)A@j?cX|;eiv;Xr*qdUXONl^8ps{sr~RZ)3ljJFGCp92qJk|qp({j1-rj}4fC#%@ z9pLT!$7AMPKIbb)fuO>uH^0~Anv74E$%flFOAkJz(c?D@?Z|P>VqA# z#+~EC6p5*YI^{Uz0ZwWZDl#zg_|DV60VL>^dgb7cH}kf;9gcyNG(7kJ_2j`#kPzAj zj~|s2hRU3;PctavmvQjZJt6`YpI=~w;A6(zloy$aY2cAej9{z#wb$iwH;skOr0epJ jOTcyCEHyV0JQV(); - } - doRepaint(): void { - if (this.datas.points.length < 2) { - throw new Error('Link坐标数据异常'); - } - this.lineGraphic.clear(); - this.lineGraphic.lineStyle( - this.datas.lineWidth, - new Color(this.datas.lineColor) - ); - if (this.datas.curve) { - // 曲线 - const bps = convertToBezierParams(this.datas.points); - bps.forEach((bp) => { - this.lineGraphic.drawBezierCurve( - bp.p1, - bp.p2, - bp.cp1, - bp.cp2, - this.datas.segmentsCount - ); - }); - } else { - // 直线 - const start = this.getStartPoint(); - this.lineGraphic.moveTo(start.x, start.y); - for (let i = 0; i < this.datas.points.length; i++) { - const p = this.datas.points[i]; - this.lineGraphic.lineTo(p.x, p.y); - } - } - } - get linePoints(): IPointData[] { - return this.datas.points; - } - set linePoints(points: IPointData[]) { - const old = this.datas.clone(); - old.points = points; - this.updateData(old); - } - getStartPoint(): IPointData { - return this.datas.points[0]; - } - getEndPoint(): IPointData { - return this.datas.points[this.datas.points.length - 1]; - } -} - -export class LinkTemplate extends JlGraphicTemplate { - curve: boolean; - lineWidth: number; - lineColor: string; - segmentsCount: number; - constructor(dataTemplate: ILinkData) { - super(Link.Type, { - dataTemplate, - }); - this.lineWidth = 2; - this.lineColor = '#000000'; - this.curve = false; - this.segmentsCount = 10; - } - new(): Link { - return new Link(); - } -} diff --git a/src/graphics/link/LinkDrawAssistant.ts b/src/graphics/link/LinkDrawAssistant.ts deleted file mode 100644 index 63121b3..0000000 --- a/src/graphics/link/LinkDrawAssistant.ts +++ /dev/null @@ -1,451 +0,0 @@ -import { - Color, - DisplayObject, - FederatedMouseEvent, - FederatedPointerEvent, - Graphics, - IHitArea, - Point, -} from 'pixi.js'; -import { - AbsorbablePosition, - DraggablePoint, - IGraphicApp, - GraphicDrawAssistant, - GraphicInteractionPlugin, - GraphicTransformEvent, - IDrawApp, - JlGraphic, - KeyListener, - calculateMirrorPoint, - convertToBezierParams, - linePoint, - pointPolygon, -} from 'src/jlgraphic'; -import AbsorbablePoint, { - AbsorbableCircle, -} from 'src/jlgraphic/graphic/AbsorbablePosition'; -import { - BezierCurveEditPlugin, - ILineGraphic, - PolylineEditPlugin, - addWayPoint, - clearWayPoint, - getWaypointRangeIndex, - removeBezierWayPoint, - removeLineWayPoint, -} from 'src/jlgraphic/plugins/GraphicEditPlugin'; -import { ContextMenu } from 'src/jlgraphic/ui/ContextMenu'; -import { MenuItemOptions, MenuOptions } from 'src/jlgraphic/ui/Menu'; -import { ILinkData, Link, LinkTemplate } from './Link'; - -export interface ILinkDrawOptions { - newData: () => ILinkData; -} - -export class LinkDraw extends GraphicDrawAssistant { - points: Point[] = []; - graphic: Graphics = new Graphics(); - - // 快捷切曲线绘制 - keyqListener: KeyListener = new KeyListener({ - value: 'KeyQ', - global: true, - onPress: () => { - if (this.points.length == 0) { - this.graphicTemplate.curve = true; - } - }, - }); - // 快捷切直线绘制 - keyzListener: KeyListener = new KeyListener({ - value: 'KeyZ', - global: true, - onPress: () => { - if (this.points.length == 0) { - this.graphicTemplate.curve = false; - } - }, - }); - - constructor(app: IDrawApp, template: LinkTemplate) { - super(app, template, Link.Type, '轨道Link'); - this.container.addChild(this.graphic); - this.graphicTemplate.curve = true; - - LinkPointsEditPlugin.init(app); - } - - bind(): void { - super.bind(); - this.app.addKeyboardListener(this.keyqListener, this.keyzListener); - } - unbind(): void { - super.unbind(); - this.app.removeKeyboardListener(this.keyqListener, this.keyzListener); - } - - clearCache(): void { - this.points = []; - this.graphic.clear(); - } - onRightClick(): void { - this.createAndStore(true); - } - onLeftDown(e: FederatedPointerEvent): void { - const { x, y } = this.toCanvasCoordinates(e.global); - const p = new Point(x, y); - if (this.graphicTemplate.curve) { - if (this.points.length == 0) { - this.points.push(p); - } else { - this.points.push(p, p.clone()); - } - } else { - this.points.push(p); - } - } - onLeftUp(e: FederatedMouseEvent): void { - const template = this.graphicTemplate; - if (template.curve) { - const mp = this.toCanvasCoordinates(e.global); - if (this.points.length == 1) { - this.points.push(new Point(mp.x, mp.y)); - } else if (this.points.length > 1) { - const cp2 = this.points[this.points.length - 2]; - const p = this.points[this.points.length - 1]; - cp2.copyFrom(calculateMirrorPoint(p, mp)); - this.points.push(mp); - } - } - } - - redraw(p: Point): void { - if (this.points.length < 1) return; - this.graphic.clear(); - const template = this.graphicTemplate; - this.graphic.lineStyle(template.lineWidth, new Color(template.lineColor)); - const ps = [...this.points]; - if (template.curve) { - // 曲线 - if (ps.length == 1) { - this.graphic.moveTo(ps[0].x, ps[0].y); - this.graphic.lineTo(p.x, p.y); - } else { - if ((ps.length + 1) % 3 == 0) { - ps.push(p.clone(), p.clone()); - } else { - const cp = ps[ps.length - 2]; - const p1 = ps[ps.length - 1]; - const mp = calculateMirrorPoint(p1, p); - cp.copyFrom(mp); - } - - const bps = convertToBezierParams(ps); - bps.forEach((bp) => - this.graphic.drawBezierCurve( - bp.p1, - bp.p2, - bp.cp1, - bp.cp2, - template.segmentsCount - ) - ); - } - } else { - ps.push(p); - // 直线 - this.graphic.moveTo(ps[0].x, ps[0].y); - for (let i = 1; i < ps.length; i++) { - const p = ps[i]; - this.graphic.lineTo(p.x, p.y); - } - } - } - prepareData(data: ILinkData): boolean { - const template = this.graphicTemplate; - if ( - (!template.curve && this.points.length < 2) || - (template.curve && this.points.length < 4) - ) { - console.log('Link绘制因点不够取消绘制'); - return false; - } - if (template.curve) { - this.points.pop(); - } - data.curve = template.curve; - data.segmentsCount = template.segmentsCount; - data.points = this.points; - data.lineWidth = template.lineWidth; - data.lineColor = template.lineColor; - data.segmentsCount = template.segmentsCount; - return true; - } -} - -export class LinkGraphicHitArea implements IHitArea { - link: Link; - constructor(link: Link) { - this.link = link; - } - contains(x: number, y: number): boolean { - const p = new Point(x, y); - if (this.link.datas.curve) { - // 曲线 - const bps = convertToBezierParams(this.link.datas.points); - for (let i = 0; i < bps.length; i++) { - const bp = bps[i]; - if ( - pointPolygon( - p, - [bp.p1, bp.cp1, bp.cp2, bp.p2], - this.link.datas.lineWidth - ) - ) { - return true; - } - } - } else { - // 直线 - for (let i = 1; i < this.link.datas.points.length; i++) { - const p1 = this.link.datas.points[i - 1]; - const p2 = this.link.datas.points[i]; - if (linePoint(p1, p2, p, this.link.datas.lineWidth)) { - return true; - } - } - } - return false; - } -} - -/** - * 构建吸附位置 - * @param link - * @returns - */ -function buildAbsorbablePositions(link: Link): AbsorbablePosition[] { - const aps: AbsorbablePosition[] = []; - const links = link.queryStore.queryByType(Link.Type); - links.forEach((other) => { - if (other.id == link.id) { - return; - } - const apa = new AbsorbablePoint( - other.localToCanvasPoint(other.getStartPoint()) - ); - const apb = new AbsorbablePoint( - other.localToCanvasPoint(other.getEndPoint()) - ); - aps.push(apa, apb); - }); - - aps.push(new AbsorbableCircle(new Point(450, 410), 30)); - - return aps; -} - -/** - * 端点拖拽添加吸附位置 - * @param g - * @param dp - * @param index - */ -function onPolylineEditPointCreate( - g: ILineGraphic, - dp: DraggablePoint, - index: number -): void { - const link = g as Link; - if (index === 0 || index == link.datas.points.length - 1) { - // 端点 - dp.on('transformstart', (e: GraphicTransformEvent) => { - if (e.isShift()) { - link.getGraphicApp().setOptions({ - absorbablePositions: buildAbsorbablePositions(link), - }); - } - }); - } - dp.on('rightclick', (e: FederatedMouseEvent) => { - // dp.getGraphicApp().openContextMenu(EditPointContextMenu.DefaultMenu); - // 路径中的点 - const app = dp.getGraphicApp(); - app.registerMenu(EditPointContextMenu); - removeWaypointConfig.handler = () => { - removeLineWayPoint(link, index); - }; - clearWaypointsConfig.handler = () => { - clearWayPoint(link, false); - }; - EditPointContextMenu.open(e.global); - }); -} - -function onCurveEditPointCreate( - g: ILineGraphic, - dp: DraggablePoint, - index: number -): void { - const link = g as Link; - if (index === 0 || index == link.datas.points.length - 1) { - // 端点 - dp.on('transformstart', (e: GraphicTransformEvent) => { - if (e.isShift()) { - link.getGraphicApp().setOptions({ - absorbablePositions: buildAbsorbablePositions(link), - }); - } - }); - } - const c = index % 3; - dp.on('rightclick', (e: FederatedMouseEvent) => { - // dp.getGraphicApp().openContextMenu(EditPointContextMenu.DefaultMenu); - if (c === 0) { - // 路径中的点 - const app = dp.getGraphicApp(); - app.registerMenu(EditPointContextMenu); - removeWaypointConfig.handler = () => { - removeBezierWayPoint(link, index); - }; - clearWaypointsConfig.handler = () => { - clearWayPoint(link, true); - }; - EditPointContextMenu.open(e.global); - } - }); -} - -export const addWaypointConfig: MenuItemOptions = { - name: '添加路径点', -}; -export const addWaySegmentingConfig: MenuItemOptions = { - name: '细分', -}; -export const removeWaypointConfig: MenuItemOptions = { - name: '移除路径点', -}; -export const clearWaypointsConfig: MenuItemOptions = { - name: '清除所有路径点', -}; -const menuOptions: MenuOptions = { - name: '图形编辑点菜单', - groups: [ - { - items: [removeWaypointConfig, clearWaypointsConfig], - }, - ], -}; - -const EditPointContextMenu = ContextMenu.init(menuOptions); - -const LinkEditMenu: ContextMenu = ContextMenu.init({ - name: '轨道编辑菜单', - groups: [ - { - items: [addWaypointConfig, clearWaypointsConfig], - }, - ], -}); - -/** - * link路径编辑 - */ -export class LinkPointsEditPlugin extends GraphicInteractionPlugin { - static Name = 'LinkPointsDrag'; - constructor(app: IGraphicApp) { - super(LinkPointsEditPlugin.Name, app); - app.registerMenu(LinkEditMenu); - } - static init(app: IGraphicApp): LinkPointsEditPlugin { - return new LinkPointsEditPlugin(app); - } - filter(...grahpics: JlGraphic[]): Link[] | undefined { - return grahpics.filter((g) => g.type == Link.Type) as Link[]; - } - bind(g: Link): void { - g.lineGraphic.eventMode = 'static'; - g.lineGraphic.cursor = 'pointer'; - g.lineGraphic.hitArea = new LinkGraphicHitArea(g); - g.on('_rightclick', this.onContextMenu, this); - g.on('selected', this.onSelected, this); - g.on('unselected', this.onUnselected, this); - } - unbind(g: Link): void { - g.off('_rightclick', this.onContextMenu, this); - g.off('selected', this.onSelected, this); - g.off('unselected', this.onUnselected, this); - } - - onContextMenu(e: FederatedMouseEvent) { - const target = e.target as DisplayObject; - const link = target.getGraphic() as Link; - this.app.updateSelected(link); - const p = link.getGraphicApp().toCanvasCoordinates(e.global); - console.log('右键坐标', p); - - addWaypointConfig.handler = () => { - const linePoints = link.linePoints; - console.log('添加路径点', linePoints, p); - const { start, end } = getWaypointRangeIndex( - linePoints, - link.datas.curve, - p, - link.datas.lineWidth - ); - addWayPoint(link, link.datas.curve, start, end, p); - }; - clearWaypointsConfig.handler = () => { - clearWayPoint(link, link.datas.curve); - }; - LinkEditMenu.open(e.global); - } - - onSelected(g: DisplayObject): void { - const link = g as Link; - let lep; - if (link.datas.curve) { - // 曲线 - lep = link.getAssistantAppend( - BezierCurveEditPlugin.Name - ); - if (!lep) { - lep = new BezierCurveEditPlugin(link, { - onEditPointCreate: onCurveEditPointCreate, - }); - link.addAssistantAppend(lep); - } - } else { - // 直线 - lep = link.getAssistantAppend( - PolylineEditPlugin.Name - ); - if (!lep) { - lep = new PolylineEditPlugin(link, { - onEditPointCreate: onPolylineEditPointCreate, - }); - link.addAssistantAppend(lep); - } - } - lep.showAll(); - } - onUnselected(g: DisplayObject): void { - const link = g as Link; - let lep; - if (link.datas.curve) { - // 曲线 - lep = link.getAssistantAppend( - BezierCurveEditPlugin.Name - ); - } else { - // 直线 - lep = link.getAssistantAppend( - PolylineEditPlugin.Name - ); - } - if (lep) { - lep.hideAll(); - } - } -} diff --git a/src/graphics/platform/Platform.ts b/src/graphics/platform/Platform.ts deleted file mode 100644 index 72266a6..0000000 --- a/src/graphics/platform/Platform.ts +++ /dev/null @@ -1,203 +0,0 @@ -import { Color, Graphics, IPointData, Rectangle } from 'pixi.js'; -import { - GraphicData, - JlGraphic, - JlGraphicTemplate, - VectorText, - getRectangleCenter, -} from 'src/jlgraphic'; - -export interface IPlatformData extends GraphicData { - get code(): string; // 编号 - set code(v: string); - get hasdoor(): boolean; // 是否有屏蔽门 - set hasdoor(v: boolean); - get trainDirection(): string; // 行驶方向--屏蔽门上下 - set trainDirection(v: string); - get lineWidth(): number; // 线宽 - set lineWidth(v: number); - get lineColor(): string; // 站台线色 - set lineColor(v: string); - get lineColorDoor(): string; // 屏蔽门线色 - set lineColorDoor(v: string); - get point(): IPointData; // 位置坐标 - set point(point: IPointData); - get width(): number; // 宽度 - set width(v: number); - get height(): number; // 高度 - set height(v: number); - clone(): IPlatformData; - copyFrom(data: IPlatformData): void; - eq(other: IPlatformData): boolean; -} - -//站台颜色 -export enum PlatformColorEnum { - blue = '0x0fe81f', //站台的颜色 - lightBlue = '0x55d15d', - yellow = '0xfbff00', - white = '0xffffff', - lozengeRed = '0xff0000', //站台旁的菱形图标 - whiteNumbers = '0xffffff', //站台旁白色数字 - HCharYellow = '0xfbff00', //站台旁的H字符 - HCharWhite = '0xffffff', - HCharRed = '0xff0000', - doorBlue = '0x008000', //屏蔽门的颜色 - doorRed = '0xff0000', -} - -const platformConsts = { - width: 60, - height: 20, - lineWidth: 3, - besideFontSize: 12, - doorOpenSpacing: 5, - doorPlatformSpacing: 10, - besideSpacing: 10, -}; - -export class Platform extends JlGraphic { - static Type = 'Platform'; - - platformGraphic: Graphics; - doorGraphic: Graphics; - doorCloseGraphic: Graphics; - besideGraphic: Graphics; - codeGraph: VectorText = new VectorText(''); //站台旁数字、字符 - constructor() { - super(Platform.Type); - this.platformGraphic = new Graphics(); - this.doorGraphic = new Graphics(); - this.doorCloseGraphic = new Graphics(); - this.besideGraphic = new Graphics(); - this.addChild(this.platformGraphic); - this.addChild(this.doorGraphic); - this.addChild(this.doorCloseGraphic); - this.addChild(this.besideGraphic); - this.addChild(this.codeGraph); - this.codeGraph.setVectorFontSize(platformConsts.besideFontSize); - } - - get datas(): IPlatformData { - return this.getDatas(); - } - doRepaint(): void { - const width = this.datas.width; - const height = this.datas.height; - //屏蔽门 - const doorGraphic = this.doorGraphic; - const doorCloseGraphic = this.doorCloseGraphic; - doorGraphic.clear(); - doorCloseGraphic.clear(); - if (this.datas.hasdoor) { - doorGraphic.lineStyle( - this.datas.lineWidth, - new Color(this.datas.lineColorDoor) - ); - doorGraphic.moveTo(-width / 2 - this.datas.lineWidth / 2, 0); - doorGraphic.lineTo(-platformConsts.doorOpenSpacing, 0); - doorGraphic.moveTo(platformConsts.doorOpenSpacing, 0); - doorGraphic.lineTo(width / 2 + this.datas.lineWidth / 2, 0); - //屏蔽门闭合 - doorCloseGraphic.lineStyle( - this.datas.lineWidth, - new Color(this.datas.lineColorDoor) - ); - doorCloseGraphic.moveTo(-platformConsts.doorOpenSpacing, 0); - doorCloseGraphic.lineTo(platformConsts.doorOpenSpacing, 0); - doorGraphic.position.set( - 0, - -height / 2 - platformConsts.doorPlatformSpacing - ); - doorCloseGraphic.position.set( - 0, - -height / 2 - platformConsts.doorPlatformSpacing - ); - } - //站台 - const platformGraphic = this.platformGraphic; - platformGraphic.clear(); - platformGraphic.lineStyle( - this.datas.lineWidth, - new Color(this.datas.lineColor) - ); - platformGraphic.beginFill(this.datas.lineColor, 1); - platformGraphic.drawRect(0, 0, this.datas.width, this.datas.height); - platformGraphic.endFill; - const rectP = new Rectangle(0, 0, this.datas.width, this.datas.height); - platformGraphic.pivot = getRectangleCenter(rectP); - this.position.set(this.datas.point.x, this.datas.point.y); - //站台旁菱形图标 - const besideGraphic = this.besideGraphic; - besideGraphic.clear(); - besideGraphic.lineStyle(1, new Color(PlatformColorEnum.lozengeRed)); - besideGraphic.drawRect(0, 0, this.datas.height / 4, this.datas.height / 4); - const rect = new Rectangle( - 0, - 0, - this.datas.height / 4, - this.datas.height / 4 - ); - besideGraphic.pivot = getRectangleCenter(rect); - besideGraphic.rotation = Math.PI / 4; - besideGraphic.position.set( - -width / 2 - this.datas.lineWidth / 2 - platformConsts.besideSpacing, - 0 - ); - //站台旁的数字、字符 - const codeGraph = this.codeGraph; - codeGraph.text = 'H'; - codeGraph.anchor.set(0.5); - codeGraph.position.set( - -width / 2 - this.datas.lineWidth / 2 - platformConsts.besideSpacing, - 0 - ); - codeGraph.style.fill = PlatformColorEnum.HCharYellow; - //站台方向 - if (this.datas.trainDirection == 'right') { - doorGraphic.position.set( - 0, - height / 2 + platformConsts.doorPlatformSpacing - ); - doorCloseGraphic.position.set( - 0, - height / 2 + platformConsts.doorPlatformSpacing - ); - besideGraphic.position.set( - width / 2 + this.datas.lineWidth / 2 + platformConsts.besideSpacing, - 0 - ); - codeGraph.position.set( - width / 2 + this.datas.lineWidth / 2 + platformConsts.besideSpacing, - 0 - ); - } - //子元素显隐 - doorCloseGraphic.visible = false; - /* besideGraphic.visible = false; - codeGraph.visible = false; */ - } -} - -export class PlatformTemplate extends JlGraphicTemplate { - hasdoor: boolean; - trainDirection: string; - lineWidth: number; - lineColor: string; - lineColorDoor: string; - width: number; - height: number; - constructor() { - super(Platform.Type, {}); - this.hasdoor = true; - this.trainDirection = 'left'; - this.lineWidth = platformConsts.lineWidth; - this.lineColor = PlatformColorEnum.yellow; - this.lineColorDoor = PlatformColorEnum.doorBlue; - this.width = platformConsts.width; - this.height = platformConsts.height; - } - new(): Platform { - return new Platform(); - } -} diff --git a/src/graphics/platform/PlatformDrawAssistant.ts b/src/graphics/platform/PlatformDrawAssistant.ts deleted file mode 100644 index f186c10..0000000 --- a/src/graphics/platform/PlatformDrawAssistant.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { - Color, - FederatedPointerEvent, - Graphics, - Point, - Rectangle, -} from 'pixi.js'; -import { - GraphicDrawAssistant, - GraphicInteractionPlugin, - IDrawApp, - JlGraphic, - getRectangleCenter, -} from 'src/jlgraphic'; - -import { IPlatformData, Platform, PlatformTemplate } from './Platform'; - -export interface IPlatformDrawOptions { - newData: () => IPlatformData; -} - -export class PlatformDraw extends GraphicDrawAssistant< - PlatformTemplate, - IPlatformData -> { - point: Point = new Point(0, 0); - platformGraphic: Graphics = new Graphics(); - doorGraphic: Graphics = new Graphics(); - - constructor(app: IDrawApp, createData: () => IPlatformData) { - super(app, new PlatformTemplate(), '', '站台Platform'); - this.container.addChild(this.platformGraphic); - this.container.addChild(this.doorGraphic); - this.graphicTemplate.hasdoor = true; - platformInteraction.init(app); - } - - bind(): void { - super.bind(); - } - unbind(): void { - super.unbind(); - } - - clearCache(): void { - this.platformGraphic.clear(); - this.doorGraphic.clear(); - } - onLeftDown(e: FederatedPointerEvent): void { - const { x, y } = this.toCanvasCoordinates(e.global); - const p = new Point(x, y); - this.point = p; - this.createAndStore(true); - } - - redraw(p: Point): void { - const template = this.graphicTemplate; - //屏蔽门 - if (template.hasdoor) { - const doorGraphic = this.doorGraphic; - doorGraphic.clear(); - doorGraphic.lineStyle( - template.lineWidth, - new Color(template.lineColorDoor) - ); - const width = template.width; - const height = template.height; - doorGraphic.moveTo(-width / 2 - template.lineWidth / 2, -height / 2 - 10); - doorGraphic.lineTo(width / 2 + template.lineWidth / 2, -height / 2 - 10); - doorGraphic.position.set(p.x, p.y); - } - - //站台 - const platformGraphic = this.platformGraphic; - platformGraphic.clear(); - this.point.set(p.x, p.y); - const rect = new Rectangle(0, 0, template.width, template.height); - platformGraphic.pivot = getRectangleCenter(rect); - platformGraphic.lineStyle(template.lineWidth, template.lineColor); - platformGraphic.beginFill(template.lineColor, 1); - platformGraphic.drawRect(0, 0, template.width, template.height); - platformGraphic.endFill; - platformGraphic.position.set(this.point.x, this.point.y); - } - prepareData(data: IPlatformData): boolean { - const template = this.graphicTemplate; - data.hasdoor = template.hasdoor; - data.trainDirection = template.trainDirection; - data.point = this.point; - data.lineWidth = template.lineWidth; - data.lineColor = template.lineColor; - data.lineColorDoor = template.lineColorDoor; - data.width = template.width; - data.height = template.height; - return true; - } -} - -export class platformInteraction extends GraphicInteractionPlugin { - static Name = 'platform_transform'; - constructor(app: IDrawApp) { - super(platformInteraction.Name, app); - } - static init(app: IDrawApp) { - return new platformInteraction(app); - } - filter(...grahpics: JlGraphic[]): Platform[] | undefined { - return grahpics - .filter((g) => g.type === Platform.Type) - .map((g) => g as Platform); - } - bind(g: Platform): void { - g.eventMode = 'static'; - g.cursor = 'pointer'; - g.scalable = true; - g.rotatable = true; - } - unbind(g: Platform): void { - g.eventMode = 'none'; - g.scalable = false; - g.rotatable = false; - } -} diff --git a/src/graphics/rect/Rect.ts b/src/graphics/rect/Rect.ts deleted file mode 100644 index 5cde77a..0000000 --- a/src/graphics/rect/Rect.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { Color, Graphics, IPointData, Point } from 'pixi.js'; -import { GraphicData, JlGraphic, JlGraphicTemplate } from 'src/jlgraphic'; - -export interface IRectData extends GraphicData { - get code(): string; // 编号 - set code(v: string); - get lineWidth(): number; // 线宽 - set lineWidth(v: number); - get lineColor(): string; // 线色 - set lineColor(v: string); - get point(): IPointData; // 位置坐标 - set point(point: IPointData); - get width(): number; // 宽度 - set width(v: number); - get height(): number; // 高度 - set height(v: number); - get points(): IPointData[]; // 线坐标点 - set points(points: IPointData[]); - clone(): IRectData; - copyFrom(data: IRectData): void; - eq(other: IRectData): boolean; -} - -const rectConsts = { - lineWidth: 2, - lineColor: '0xff0000', - width: 60, - height: 20, -}; - -export class Rect extends JlGraphic { - static Type = 'Rect'; - rectGraphic: Graphics; - constructor() { - super(Rect.Type); - this.rectGraphic = new Graphics(); - this.addChild(this.rectGraphic); - } - - get datas(): IRectData { - return this.getDatas(); - } - doRepaint(): void { - const width = this.datas.width; - const height = this.datas.height; - if (this.linePoints.length == 0) { - const r1 = new Point(this.datas.point.x, this.datas.point.y); - const r2 = new Point(r1.x + width, r1.y); - const r3 = new Point(r1.x + width, r1.y + height); - const r4 = new Point(r1.x, r1.y + height); - this.datas.points = [r1, r2, r3, r4, r1]; - } - const rectGraphic = this.rectGraphic; - rectGraphic.clear(); - rectGraphic.lineStyle( - this.datas.lineWidth, - new Color(this.datas.lineColor) - ); - rectGraphic.drawPolygon(this.datas.points); - } - get linePoints(): IPointData[] { - return this.datas.points; - } - set linePoints(points: IPointData[]) { - const old = this.datas.clone(); - old.points = points; - this.updateData(old); - } -} - -export class RectTemplate extends JlGraphicTemplate { - lineWidth: number; - lineColor: string; - width: number; - height: number; - constructor() { - super(Rect.Type); - this.lineWidth = rectConsts.lineWidth; - this.lineColor = rectConsts.lineColor; - this.width = rectConsts.width; - this.height = rectConsts.height; - } - new(): Rect { - return new Rect(); - } -} diff --git a/src/graphics/rect/RectDrawAssistant.ts b/src/graphics/rect/RectDrawAssistant.ts deleted file mode 100644 index 306b2f0..0000000 --- a/src/graphics/rect/RectDrawAssistant.ts +++ /dev/null @@ -1,261 +0,0 @@ -import { - FederatedPointerEvent, - Graphics, - Point, - IHitArea, - DisplayObject, - FederatedMouseEvent, -} from 'pixi.js'; -import { - DraggablePoint, - GraphicApp, - GraphicDrawAssistant, - GraphicInteractionPlugin, - GraphicTransformEvent, - JlDrawApp, - JlGraphic, - linePoint, -} from 'src/jlgraphic'; - -import AbsorbablePoint, { - AbsorbablePosition, -} from 'src/jlgraphic/graphic/AbsorbablePosition'; -import { - ILineGraphic, - PolylineEditPlugin, - addWaySegmentingConfig, - addPolygonSegmentingPoint, - clearWayPoint, - clearWaypointsConfig, - getWayLineIndex, -} from 'src/jlgraphic/plugins/GraphicEditPlugin'; -import { ContextMenu } from 'src/jlgraphic/ui/ContextMenu'; - -import { IRectData, Rect, RectTemplate } from './Rect'; -import { Link } from '../link/Link'; - -export interface IRectDrawOptions { - newData: () => IRectData; -} - -export class RectDraw extends GraphicDrawAssistant { - point1: Point | null = null; - point2: Point | null = null; - rectGraphic: Graphics = new Graphics(); - - constructor(app: JlDrawApp, createData: () => IRectData) { - super(app, new RectTemplate(), createData, Rect.Type, '站台Rect'); - this.container.addChild(this.rectGraphic); - RectPointsEditPlugin.init(app); - } - - bind(): void { - super.bind(); - } - unbind(): void { - super.unbind(); - } - - clearCache(): void { - this.rectGraphic.clear(); - } - onLeftDown(e: FederatedPointerEvent): void { - const { x, y } = this.toCanvasCoordinates(e.global); - const p = new Point(x, y); - if (this.point1 === null) { - this.point1 = p; - } else { - this.point2 = p; - this.createAndStore(true); - this.point1 = null; - this.point2 = null; - } - } - - redraw(p: Point): void { - const template = this.graphicTemplate; - if (this.point1 === null) return; - const rectGraphic = this.rectGraphic; - rectGraphic.clear(); - rectGraphic.lineStyle(template.lineWidth, template.lineColor); - rectGraphic.drawRect(...this.normalize(this.point1, p)); - } - //根据画的两个点确定左上角的点的坐标和矩形宽高 - private normalize(p1: Point, p2: Point): [number, number, number, number] { - const { abs } = Math; - const x = p1.x < p2.x ? p1.x : p2.x; - const y = p1.y < p2.y ? p1.y : p2.y; - const w = abs(p1.x - p2.x); - const h = abs(p1.y - p2.y); - return [x, y, w, h]; - } - prepareData(data: IRectData): boolean { - if (this.point1 == null) { - console.log('Rect绘制因点不够取消绘制'); - return false; - } - const p1 = this.point1 as Point; - const p2 = this.point2 as Point; - const [x, y, width, height] = this.normalize(p1, p2); - const template = this.graphicTemplate; - data.point = new Point(x, y); - data.lineWidth = template.lineWidth; - data.lineColor = template.lineColor; - data.width = width; - data.height = height; - return true; - } -} - -//碰撞检测 -export class RectGraphicHitArea implements IHitArea { - rect: Rect; - constructor(rect: Rect) { - this.rect = rect; - } - contains(x: number, y: number): boolean { - let contains = false; - const p = new Point(x, y); - const rectData = this.rect.datas; - //contains = pointPolygon(p, rectData.points, rectData.lineWidth);是否包含多边形内部 - const tolerance = rectData.lineWidth; - for (let i = 0; i < rectData.points.length - 1; i++) { - const p1 = rectData.points[i]; - const p2 = rectData.points[i + 1]; - contains = contains || linePoint(p1, p2, p, tolerance); - if (contains) { - break; - } - } - return contains; - } -} - -/** - * 构建吸附位置 - * @param rect - * @returns - */ -function buildAbsorbablePositions(rect: Rect): AbsorbablePosition[] { - const aps: AbsorbablePosition[] = []; - const rects = rect.queryStore.queryByType(Rect.Type); - const links = rect.queryStore.queryByType(Link.Type); - - links.forEach((other) => { - const apa = new AbsorbablePoint( - other.localToCanvasPoint(other.getStartPoint()) - ); - const apb = new AbsorbablePoint( - other.localToCanvasPoint(other.getEndPoint()) - ); - aps.push(apa, apb); - }); - - rects.forEach((other) => { - if (other.id == rect.id) { - return; - } - other.linePoints.forEach((point) => { - const absorbablePoint = new AbsorbablePoint( - other.localToCanvasPoint(point) - ); - aps.push(absorbablePoint); - }); - }); - - return aps; -} - -/** - * 端点拖拽添加吸附位置 - * @param g - * @param dp - * @param index - */ -function onEditPointCreate(g: ILineGraphic, dp: DraggablePoint): void { - const rect = g as Rect; - // 端点 - dp.on('transformstart', (e: GraphicTransformEvent) => { - if (e.isShift()) { - rect.getGraphicApp().setOptions({ - absorbablePositions: buildAbsorbablePositions(rect), - }); - } - }); -} - -const RectEditMenu: ContextMenu = ContextMenu.init({ - name: '矩形编辑菜单', - groups: [ - { - items: [addWaySegmentingConfig, clearWaypointsConfig], - }, - ], -}); - -/** - * rect路径编辑 - */ -export class RectPointsEditPlugin extends GraphicInteractionPlugin { - static Name = 'RectPointsDrag'; - constructor(app: GraphicApp) { - super(RectPointsEditPlugin.Name, app); - app.registerMenu(RectEditMenu); - } - static init(app: GraphicApp): RectPointsEditPlugin { - return new RectPointsEditPlugin(app); - } - filter(...grahpics: JlGraphic[]): Rect[] | undefined { - return grahpics.filter((g) => g.type == Rect.Type) as Rect[]; - } - bind(g: Rect): void { - g.rectGraphic.eventMode = 'static'; - g.rectGraphic.cursor = 'pointer'; - g.rectGraphic.hitArea = new RectGraphicHitArea(g); - g.on('_rightclick', this.onContextMenu, this); - g.on('selected', this.onSelected, this); - g.on('unselected', this.onUnselected, this); - } - unbind(g: Rect): void { - g.off('_rightclick', this.onContextMenu, this); - g.off('selected', this.onSelected, this); - g.off('unselected', this.onUnselected, this); - } - - onContextMenu(e: FederatedMouseEvent) { - const target = e.target as DisplayObject; - const rect = target.getGraphic() as Rect; - this.app.updateSelected(rect); - addWaySegmentingConfig.handler = () => { - const linePoints = rect.linePoints; - const p = rect.screenToLocalPoint(e.global); - const { start, end } = getWayLineIndex(linePoints, p); - addPolygonSegmentingPoint(rect, start, end); - }; - clearWaypointsConfig.handler = () => { - clearWayPoint(rect, false); - }; - RectEditMenu.open(e.global); - } - - onSelected(g: DisplayObject): void { - const rect = g as Rect; - let lep = rect.getAssistantAppend( - PolylineEditPlugin.Name - ); - if (!lep) { - lep = new PolylineEditPlugin(rect, { onEditPointCreate }); - rect.addAssistantAppend(lep); - } - lep.showAll(); - } - onUnselected(g: DisplayObject): void { - const rect = g as Rect; - const lep = rect.getAssistantAppend( - PolylineEditPlugin.Name - ); - if (lep) { - lep.hideAll(); - } - } -} diff --git a/src/graphics/signal/Lamp.ts b/src/graphics/signal/Lamp.ts deleted file mode 100644 index 1b0d564..0000000 --- a/src/graphics/signal/Lamp.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { Container } from '@pixi/display'; -import { Graphics } from 'pixi.js'; - -export enum LampEnum { - lampPostColor = '0xc0c0c0', - lampDefaultColor = '0xff0000', - logicModeColor = '0x000000', -} - -const lampConsts = { - lampRadius: 10, - logicModeLineWidth: 2, - logicModeDistance: 7, -}; - -export class Lamp extends Container { - circleLamp: Graphics = new Graphics(); - logicMode: Graphics = new Graphics(); - - constructor() { - super(); - this.addChild(this.circleLamp); - this.addChild(this.logicMode); - } - paint(radiusX: number, radiusY: number) { - this.circleLamp.clear(); - this.circleLamp - .beginFill(LampEnum.lampDefaultColor, 1) - .drawCircle(radiusX, radiusY, lampConsts.lampRadius) - .endFill(); - - this.logicMode - .clear() - .lineStyle(lampConsts.logicModeLineWidth, LampEnum.logicModeColor) - .moveTo( - radiusX - lampConsts.logicModeDistance, - radiusY + lampConsts.logicModeDistance - ) - .lineTo( - radiusX + lampConsts.logicModeDistance, - radiusY - lampConsts.logicModeDistance - ) - .moveTo( - radiusX - lampConsts.logicModeDistance, - radiusY - lampConsts.logicModeDistance - ) - .lineTo( - radiusX + lampConsts.logicModeDistance, - radiusY + lampConsts.logicModeDistance - ); - } -} diff --git a/src/graphics/signal/LampMainBody.ts b/src/graphics/signal/LampMainBody.ts deleted file mode 100644 index 7436303..0000000 --- a/src/graphics/signal/LampMainBody.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Container } from '@pixi/display'; -import { Graphics } from 'pixi.js'; -import { Lamp } from './Lamp'; - -export enum LampEnum { - lampPostColor = '0xc0c0c0', -} - -const lampConsts = { - verticalLampPostLength: 20, - levelLampPostLength: 5, - postLineWidth: 3, - lampRadius: 10, -}; - -export class LampMainBody extends Container { - lampNum = 1; - lampPost: Graphics = new Graphics(); - lamps: Lamp[] = []; - - constructor() { - super(); - } - paint(lampNum: number) { - if (lampNum < 1) { - throw new Error('信号机灯数量异常'); - } - this.lampNum = lampNum; - this.removeChildren(0); - this.lampPost = new Graphics(); - this.lampPost - .lineStyle(lampConsts.postLineWidth, LampEnum.lampPostColor) - .moveTo(0, -lampConsts.verticalLampPostLength / 2) - .lineTo(0, lampConsts.verticalLampPostLength / 2) - .moveTo(0, 0) - .lineTo(lampConsts.levelLampPostLength, 0); - this.addChild(this.lampPost); - - this.lamps = []; - for (let i = 0; i < this.lampNum; i++) { - const lamp = new Lamp(); - const radiusX = - (1 + i * 2) * lampConsts.lampRadius + lampConsts.levelLampPostLength; - lamp.paint(radiusX, 0); - this.addChild(lamp); - this.lamps.push(lamp); - } - } - - // setState() {} -} diff --git a/src/graphics/signal/Signal.ts b/src/graphics/signal/Signal.ts deleted file mode 100644 index 27c385c..0000000 --- a/src/graphics/signal/Signal.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { Graphics } from 'pixi.js'; -import { - GraphicData, - JlGraphic, - JlGraphicTemplate, - VectorText, -} from 'src/jlgraphic'; -import { LampMainBody } from './LampMainBody'; -import { drawArrow } from '../CommonGraphics'; - -export interface ISignalData extends GraphicData { - get code(): string; // 编号 - set code(v: string); - clone(): ISignalData; - copyFrom(data: ISignalData): void; - eq(other: ISignalData): boolean; -} - -export enum SignalColorEnum { - humanControlColor = '0xffff00', - fleetModeColor = '0x00ff00', - codeColor = '0X000000', -} - -const signalConsts = { - lampNum: 1, - codeFontSize: 11, - nameOffsetY: 20, - fleetModeLength: 33, - fleetModeRadius: 10, - fleetModeLineWidth: 6, -}; -export class Signal extends JlGraphic { - static Type = 'signal'; - codeGraph: VectorText = new VectorText(''); - humanControl: Graphics = new Graphics(); - fleetMode: Graphics = new Graphics(); - lampMainBody: LampMainBody = new LampMainBody(); - - constructor() { - super(Signal.Type); - this.codeGraph.name = 'signalCode'; - this.addChild(this.codeGraph); - this.addChild(this.humanControl); - this.addChild(this.fleetMode); - this.addChild(this.lampMainBody); - } - - get datas(): ISignalData { - return this.getDatas(); - } - - paint(): void { - this.lampMainBody.paint(signalConsts.lampNum); - this.humanControl.beginFill(SignalColorEnum.humanControlColor, 1); - if (this.humanControl.drawRegularPolygon) { - this.humanControl.drawRegularPolygon(-10, 0, 10, 3, Math.PI / 2); - } - this.humanControl.endFill(); - this.fleetMode.beginFill(SignalColorEnum.fleetModeColor, 1); - drawArrow( - this.fleetMode, - this.lampMainBody.width + signalConsts.fleetModeLength, - 0, - signalConsts.fleetModeLength, - signalConsts.fleetModeRadius, - signalConsts.fleetModeLineWidth - ); - this.fleetMode.endFill(); - this.codeGraph.text = this.datas?.code || '信号机编号'; - this.codeGraph.style.fill = SignalColorEnum.codeColor; - this.codeGraph.setVectorFontSize(signalConsts.codeFontSize); - this.codeGraph.anchor.set(0.5); - this.codeGraph.style.fill = SignalColorEnum.codeColor; - const codeTransform = this.datas?.childTransforms?.find( - (item) => item.name === 'signalCode' - ); - if (codeTransform) { - const position = codeTransform?.transform.position; - const rotation = codeTransform?.transform?.rotation; - this.codeGraph.position.set(position?.x, position?.y); - this.codeGraph.rotation = rotation || 0; - } else { - this.codeGraph.position.set(0, signalConsts.nameOffsetY); - } - } - - doRepaint(): void { - this.paint(); - } -} - -export class SignalTemplate extends JlGraphicTemplate { - constructor(dataTemplate: ISignalData) { - super(Signal.Type, { - dataTemplate, - }); - } - new(): Signal { - return new Signal(); - } -} diff --git a/src/graphics/signal/SignalDrawAssistant.ts b/src/graphics/signal/SignalDrawAssistant.ts deleted file mode 100644 index c119cdc..0000000 --- a/src/graphics/signal/SignalDrawAssistant.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { FederatedPointerEvent, Point } from 'pixi.js'; -import { - AbsorbableLine, - AbsorbablePosition, - GraphicApp, - GraphicDrawAssistant, - GraphicInteractionPlugin, - GraphicTransformEvent, - JlDrawApp, - JlGraphic, -} from 'src/jlgraphic'; -import { ISignalData, Signal, SignalTemplate } from './Signal'; -import { IscsFan } from '../iscs-fan/IscsFan'; - -export interface ISignalDrawOptions { - newData: () => ISignalData; -} - -export class SignalDraw extends GraphicDrawAssistant< - SignalTemplate, - ISignalData -> { - _signal: Signal | null = null; - - constructor(app: JlDrawApp, template: SignalTemplate) { - super( - app, - template, - 'svguse: ../../drawIcon.svg#icon-signal', - '信号机Signal' - ); - - signalInteraction.init(app); - } - - public get signal(): Signal { - if (!this._signal) { - this._signal = this.graphicTemplate.new(); - this.signal.loadData(this.graphicTemplate.datas); - this.container.addChild(this.signal); - } - return this._signal; - } - - clearCache(): void { - //this.codeGraph.clear(); - } - onRightClick(): void { - this.createAndStore(true); - } - onLeftUp(e: FederatedPointerEvent): void { - this.container.position.copyFrom(this.toCanvasCoordinates(e.global)); - this.createAndStore(true); - } - - redraw(p: Point): void { - this.signal.paint(); - this.container.position.set(p.x, p.y); - } - prepareData(data: ISignalData): boolean { - data.transform = this.container.saveTransform(); - return true; - } -} - -export class signalInteraction extends GraphicInteractionPlugin { - static Name = 'signal_transform'; - constructor(app: JlDrawApp) { - super(signalInteraction.Name, app); - } - static init(app: JlDrawApp) { - return new signalInteraction(app); - } - filter(...grahpics: JlGraphic[]): Signal[] | undefined { - return grahpics - .filter((g) => g.type === Signal.Type) - .map((g) => g as Signal); - } - bind(g: Signal): void { - g.eventMode = 'static'; - g.cursor = 'pointer'; - g.scalable = true; - g.rotatable = true; - g.codeGraph.draggable = true; - g.codeGraph.selectable = true; - g.codeGraph.rotatable = true; - g.codeGraph.scalable = true; - g.codeGraph.transformSave = true; - g.codeGraph.eventMode = 'static'; - g.codeGraph.on('transformstart', (e: GraphicTransformEvent) => { - if (e.isShift()) { - console.log( - '信号机画布坐标', - e.target.position, - e.target.getPositionOnCanvas() - ); - const app = g.getGraphicApp(); - app.setOptions({ - absorbablePositions: buildAbsorbablePositions(app), - }); - } - }); - } - // onScaleDragEnd() { - // console.log('-----------------'); - // } - unbind(g: Signal): void { - g.eventMode = 'none'; - g.scalable = false; - g.rotatable = false; - g.codeGraph.draggable = false; - g.codeGraph.selectable = false; - g.codeGraph.rotatable = false; - g.codeGraph.scalable = false; - g.codeGraph.transformSave = false; - g.codeGraph.eventMode = 'none'; - } -} -function buildAbsorbablePositions(app: GraphicApp): AbsorbablePosition[] { - const canvas = app.canvas; - const store = app.queryStore; - const aps: AbsorbablePosition[] = []; - store.queryByType(IscsFan.Type).forEach((fan) => { - const p = fan.position; - aps.push( - new AbsorbableLine(new Point(0, p.y), new Point(canvas.width, p.y)) - ); - aps.push( - new AbsorbableLine(new Point(p.x, 0), new Point(p.x, canvas.height)) - ); - }); - return aps; -} diff --git a/src/graphics/station/Station.ts b/src/graphics/station/Station.ts deleted file mode 100644 index 8e94ae7..0000000 --- a/src/graphics/station/Station.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { Color, Graphics, IPointData, Point } from 'pixi.js'; -import { - GraphicData, - JlGraphic, - JlGraphicTemplate, - VectorText, -} from 'src/jlgraphic'; - -export interface IStationData extends GraphicData { - get code(): string; // 编号 - set code(v: string); - get hasCircle(): boolean; // 是否有圆圈--线网图 - set hasCircle(v: boolean); - get radius(): number; // 半径 - set radius(v: number); - get borderWidth(): number; // 线宽 - set borderWidth(v: number); - get borderColor(): string; // 圆边框线色 - set borderColor(v: string); - get fillColor(): string; // 圆填充颜色 - set fillColor(v: string); - get codeColor(): string; // 车站字体颜色 - set codeColor(v: string); - get codeFontSize(): number; // 车站字体大小 - set codeFontSize(v: number); - get point(): IPointData; // 位置坐标 - set point(point: IPointData); - get circlePoint(): IPointData; // 位置坐标 - set circlePoint(point: IPointData); - clone(): IStationData; - copyFrom(data: IStationData): void; - eq(other: IStationData): boolean; -} - -export class Station extends JlGraphic { - static Type = 'station'; - codeGraph: VectorText = new VectorText(''); //站台旁数字、字符 - circleGraphic: Graphics; - constructor() { - super(Station.Type); - this.circleGraphic = new Graphics(); - this.addChild(this.codeGraph); - this.addChild(this.circleGraphic); - } - - get datas(): IStationData { - return this.getDatas(); - } - doRepaint(): void { - this.circleGraphic.clear(); - this.position.set(this.datas.point.x, this.datas.point.y); - const codeGraph = this.codeGraph; - if (this.datas.code == '') { - codeGraph.text = '车站Station'; - } else { - codeGraph.text = this.datas.code; - } - codeGraph.style.fill = this.datas.codeColor; - codeGraph.setVectorFontSize(this.datas.codeFontSize); - codeGraph.anchor.set(0.5); - if (this.datas.hasCircle) { - const circleGraphic = this.circleGraphic; - circleGraphic.lineStyle( - this.datas.borderWidth, - new Color(this.datas.borderColor) - ); - circleGraphic.beginFill(this.datas.fillColor, 1); - circleGraphic.drawCircle(0, 0, this.datas.radius); - circleGraphic.endFill; - circleGraphic.position.set( - this.datas.circlePoint.x, - this.datas.circlePoint.y - ); - } - } -} - -export class StationTemplate extends JlGraphicTemplate { - hasCircle: boolean; - radius: number; - borderWidth: number; - borderColor: string; - fillColor: string; - codeColor: string; - codeFontSize: number; - circlePoint: IPointData; - constructor() { - super(Station.Type); - this.hasCircle = false; - this.radius = 5; - this.borderWidth = 1; - this.borderColor = '0xff0000'; - this.fillColor = '0xff0000'; - this.codeColor = '0xF48815'; - this.codeFontSize = 22; - this.circlePoint = new Point(0, -20); - } - new(): Station { - return new Station(); - } -} diff --git a/src/graphics/station/StationDrawAssistant.ts b/src/graphics/station/StationDrawAssistant.ts deleted file mode 100644 index a29669d..0000000 --- a/src/graphics/station/StationDrawAssistant.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { FederatedPointerEvent, Point } from 'pixi.js'; -import { - GraphicDrawAssistant, - GraphicInteractionPlugin, - JlDrawApp, - JlGraphic, - VectorText, -} from 'src/jlgraphic'; - -import { IStationData, Station, StationTemplate } from './Station'; - -export interface IStationDrawOptions { - newData: () => IStationData; -} - -export class StationDraw extends GraphicDrawAssistant< - StationTemplate, - IStationData -> { - point: Point = new Point(0, 0); - codeGraph: VectorText = new VectorText(''); - - constructor(app: JlDrawApp, createData: () => IStationData) { - super(app, new StationTemplate(), createData, Station.Type, '车站Station'); - this.container.addChild(this.codeGraph); - stationInteraction.init(app); - } - - bind(): void { - super.bind(); - } - unbind(): void { - super.unbind(); - } - - clearCache(): void { - //this.codeGraph.clear(); - } - onLeftDown(e: FederatedPointerEvent): void { - const { x, y } = this.toCanvasCoordinates(e.global); - const p = new Point(x, y); - this.point = p; - this.createAndStore(true); - } - - redraw(p: Point): void { - const codeGraph = this.codeGraph; - codeGraph.text = '车站Station'; - codeGraph.anchor.set(0.5); - codeGraph.style.fill = '0xf48815'; - codeGraph.position.set(p.x, p.y); - codeGraph.setVectorFontSize(22); - } - prepareData(data: IStationData): boolean { - const template = this.graphicTemplate; - data.point = this.point; - data.hasCircle = template.hasCircle; - data.radius = template.radius; - data.borderWidth = template.borderWidth; - data.borderColor = template.borderColor; - data.fillColor = template.fillColor; - data.codeColor = template.codeColor; - data.codeFontSize = template.codeFontSize; - data.circlePoint = template.circlePoint; - return true; - } -} - -export class stationInteraction extends GraphicInteractionPlugin { - static Name = 'station_transform'; - constructor(app: JlDrawApp) { - super(stationInteraction.Name, app); - } - static init(app: JlDrawApp) { - return new stationInteraction(app); - } - filter(...grahpics: JlGraphic[]): Station[] | undefined { - return grahpics - .filter((g) => g.type === Station.Type) - .map((g) => g as Station); - } - bind(g: Station): void { - g.eventMode = 'static'; - g.cursor = 'pointer'; - g.scalable = true; - g.rotatable = true; - } - unbind(g: Station): void { - g.eventMode = 'none'; - g.scalable = false; - g.rotatable = false; - } -} diff --git a/src/graphics/train/Train.ts b/src/graphics/train/Train.ts deleted file mode 100644 index 217ac3c..0000000 --- a/src/graphics/train/Train.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { Color, Graphics, IPointData } from 'pixi.js'; -import { - GraphicData, - JlGraphic, - JlGraphicTemplate, - VectorText, -} from 'src/jlgraphic'; - -export interface ITrainData extends GraphicData { - get code(): string; // 车号 - set code(v: string); - get codeColor(): string; // 车号颜色 - set codeColor(v: string); - get codeFontSize(): number; // 车号字体大小 - set codeFontSize(v: number); - get trainDirection(): string; // 行驶方向 - set trainDirection(v: string); - get hasBorder(): boolean; // 是否有边框 - set hasBorder(v: boolean); - get borderWidth(): number; // 边框线宽 - set borderWidth(v: number); - get borderColor(): string; // 边框颜色 - set borderColor(v: string); - get headColor(): string; // 箭头颜色 - set headColor(v: string); - get bodyColor(): string; // 背景色 - set bodyColor(v: string); - get point(): IPointData; // 位置坐标 - set point(point: IPointData); - clone(): ITrainData; - copyFrom(data: ITrainData): void; - eq(other: ITrainData): boolean; -} - -// 列车颜色 -export enum TrainColorEnum { - headColor = '0x00FF00', // 箭头颜色 - bodyColor = '0xA388B1', // 背景色 - codeColor = '0xffffff', // 车号颜色 - borderColor = '0xA3E198', // 边框的颜色 -} - -export const trainConsts = { - borderWidth: 1, - codeFontSize: 22, - marginX: 2, // 图形x轴边距 - pauseW: 2, // 停止框宽度 -}; - -export class Train extends JlGraphic { - static Type = 'Train'; - - arrowLeft: Graphics; - pauseLeft: Graphics; - arrowRight: Graphics; - pauseRight: Graphics; - codeRact: Graphics; - codeGraph: VectorText = new VectorText(''); //车号 - constructor() { - super(Train.Type); - this.arrowLeft = new Graphics(); - this.pauseLeft = new Graphics(); - this.arrowRight = new Graphics(); - this.pauseRight = new Graphics(); - this.codeRact = new Graphics(); - this.addChild(this.arrowLeft); - this.addChild(this.pauseLeft); - this.addChild(this.arrowRight); - this.addChild(this.pauseRight); - this.addChild(this.codeRact); - this.addChild(this.codeGraph); - this.codeGraph.setVectorFontSize(trainConsts.codeFontSize); - } - - get datas(): ITrainData { - return this.getDatas(); - } - doRepaint(): void { - this.position.set(this.datas.point.x, this.datas.point.y); - const codeGraph = this.codeGraph; - const codeRact = this.codeRact; - if (this.datas.code == '') { - codeGraph.text = '01110111'; - } else { - codeGraph.text = this.datas.code; - } - codeGraph.setVectorFontSize(this.datas.codeFontSize); - codeGraph.anchor.set(0.5); - const style = { - fill: this.datas.codeColor, - padding: 5, - }; - codeGraph.style = style; - const { - x: codeX, - y: codeY, - width: codeWidth, - height: codeHeight, - } = codeGraph.getLocalBounds(); - const marginX = trainConsts.marginX; - const pauseW = trainConsts.pauseW; - const arrowLeft = this.arrowLeft; - arrowLeft.beginFill(this.datas.headColor, 1); - arrowLeft.drawPolygon([ - -codeHeight * 0.4 - marginX - pauseW - marginX - codeWidth / 2, - 0, - -marginX - pauseW - marginX - codeWidth / 2, - codeHeight / 2, - -marginX - pauseW - marginX - codeWidth / 2, - -codeHeight / 2, - ]); - arrowLeft.endFill(); - this.pauseLeft.beginFill(this.datas.headColor, 1); - this.pauseLeft.drawRect(0, 0, pauseW, codeHeight); - this.pauseLeft.endFill(); - this.pauseLeft.position.set( - -marginX - pauseW - codeWidth / 2, - -codeHeight / 2 - ); - this.pauseRight.beginFill(this.datas.headColor, 1); - this.pauseRight.drawRect(0, 0, pauseW, codeHeight); - this.pauseRight.endFill(); - this.pauseRight.position.set(marginX + codeWidth / 2, -codeHeight / 2); - const arrowRight = this.arrowRight; - arrowRight.beginFill(this.datas.headColor, 1); - arrowRight.drawPolygon([ - codeWidth / 2 + marginX + pauseW + marginX + codeHeight * 0.4, - 0, - codeWidth / 2 + marginX + pauseW + marginX, - codeHeight / 2, - codeWidth / 2 + marginX + pauseW + marginX, - -codeHeight / 2, - ]); - arrowRight.endFill(); - if (this.datas.hasBorder) { - codeRact.visible = true; - codeRact.lineStyle( - this.datas.borderWidth, - new Color(this.datas.borderColor) - ); - codeRact.beginFill(new Color(this.datas.bodyColor)); - codeRact.drawRect(codeX, codeY, codeWidth, codeHeight); - codeRact.endFill(); - } else { - codeRact.visible = false; - } - // 运行方向控制箭头停止显隐 - if (this.datas.trainDirection == 'right') { - this.arrowLeft.visible = false; - this.arrowRight.visible = true; - this.pauseLeft.visible = false; - this.pauseRight.visible = true; - } else { - this.arrowLeft.visible = true; - this.arrowRight.visible = false; - this.pauseLeft.visible = true; - this.pauseRight.visible = false; - } - } -} - -export class TrainTemplate extends JlGraphicTemplate { - trainDirection: string; - codeFontSize: number; - hasBorder: boolean; - borderWidth: number; - borderColor: string; - headColor: string; - codeColor: string; - bodyColor: string; - constructor() { - super(Train.Type); - this.trainDirection = 'left'; - this.codeFontSize = trainConsts.codeFontSize; - this.hasBorder = true; - this.borderWidth = trainConsts.borderWidth; - this.borderColor = TrainColorEnum.borderColor; - this.headColor = TrainColorEnum.headColor; - this.codeColor = TrainColorEnum.codeColor; - this.bodyColor = TrainColorEnum.bodyColor; - } - new(): Train { - return new Train(); - } -} diff --git a/src/graphics/train/TrainDrawAssistant.ts b/src/graphics/train/TrainDrawAssistant.ts deleted file mode 100644 index 767a383..0000000 --- a/src/graphics/train/TrainDrawAssistant.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { Color, FederatedPointerEvent, Graphics, Point } from 'pixi.js'; -import { - GraphicDrawAssistant, - GraphicInteractionPlugin, - JlDrawApp, - JlGraphic, - VectorText, -} from 'src/jlgraphic'; - -import { ITrainData, Train, TrainTemplate, trainConsts } from './Train'; - -export interface ITrainDrawOptions { - newData: () => ITrainData; -} - -export class TrainDraw extends GraphicDrawAssistant { - point: Point = new Point(0, 0); - arrowLeft: Graphics = new Graphics(); - pauseLeft: Graphics = new Graphics(); - codeRact: Graphics = new Graphics(); - - constructor(app: JlDrawApp, createData: () => ITrainData) { - super(app, new TrainTemplate(), createData, Train.Type, '列车Train'); - this.container.addChild(this.arrowLeft); - this.container.addChild(this.pauseLeft); - this.container.addChild(this.codeRact); - this.graphicTemplate.hasBorder = true; - trainInteraction.init(app); - } - - bind(): void { - super.bind(); - } - unbind(): void { - super.unbind(); - } - - clearCache(): void { - this.arrowLeft.clear(); - this.pauseLeft.clear(); - this.codeRact.clear(); - } - onLeftDown(e: FederatedPointerEvent): void { - const { x, y } = this.toCanvasCoordinates(e.global); - const p = new Point(x, y); - this.point = p; - this.createAndStore(true); - } - - redraw(p: Point): void { - const template = this.graphicTemplate; - const codeGraph = new VectorText(''); // 车号 - codeGraph.setVectorFontSize(22); - codeGraph.anchor.set(0.5); - codeGraph.text = '01110111'; - const style = { padding: 5 }; - codeGraph.style = style; - const { width, height } = codeGraph.getLocalBounds(); - codeGraph.destroy(); - const marginX = trainConsts.marginX; - const pauseW = trainConsts.pauseW; - // 边框 - if (template.hasBorder) { - const codeRact = this.codeRact; - codeRact.clear(); - codeRact.lineStyle(template.borderWidth, new Color(template.borderColor)); - codeRact.beginFill(new Color(template.bodyColor)); - codeRact.drawRect(-width / 2, -height / 2, width, height); - codeRact.endFill(); - codeRact.position.set(p.x, p.y); - } - - // 箭头 - const arrowLeft = this.arrowLeft; - arrowLeft.clear(); - this.point.set(p.x, p.y); - arrowLeft.beginFill(template.headColor, 1); - arrowLeft.drawPolygon([ - -height * 0.4 - marginX - pauseW - marginX - width / 2, - 0, - -marginX - pauseW - marginX - width / 2, - height / 2, - -marginX - pauseW - marginX - width / 2, - -height / 2, - ]); - arrowLeft.endFill(); - arrowLeft.position.set(this.point.x, this.point.y); - - // 停止框 - const pauseLeft = this.pauseLeft; - pauseLeft.clear(); - pauseLeft.beginFill(template.headColor, 1); - pauseLeft.drawRect(0, 0, pauseW, height); - pauseLeft.endFill(); - pauseLeft.position.set( - this.point.x - marginX - pauseW - width / 2, - this.point.y - height / 2 - ); - } - prepareData(data: ITrainData): boolean { - const template = this.graphicTemplate; - data.code = '01110111'; - data.codeColor = template.codeColor; - data.codeFontSize = template.codeFontSize; - data.hasBorder = template.hasBorder; - data.trainDirection = template.trainDirection; - data.point = this.point; - data.borderWidth = template.borderWidth; - data.borderColor = template.borderColor; - data.headColor = template.headColor; - data.bodyColor = template.bodyColor; - return true; - } -} - -export class trainInteraction extends GraphicInteractionPlugin { - static Name = 'train_transform'; - constructor(app: JlDrawApp) { - super(trainInteraction.Name, app); - } - static init(app: JlDrawApp) { - return new trainInteraction(app); - } - filter(...grahpics: JlGraphic[]): Train[] | undefined { - return grahpics.filter((g) => g.type === Train.Type).map((g) => g as Train); - } - bind(g: Train): void { - g.eventMode = 'static'; - g.cursor = 'pointer'; - g.scalable = true; - g.rotatable = true; - } - unbind(g: Train): void { - g.eventMode = 'none'; - g.scalable = false; - g.rotatable = false; - } -} diff --git a/src/graphics/turnout/Turnout.ts b/src/graphics/turnout/Turnout.ts deleted file mode 100644 index 4a6c49a..0000000 --- a/src/graphics/turnout/Turnout.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { GraphicData, JlGraphic } from 'src/jlgraphic'; - -export type ITrunoutData = GraphicData; - -export class Turnout extends JlGraphic { - doRepaint(): void { - throw new Error('Method not implemented.'); - } -} diff --git a/src/graphics/turnout/TurnoutDrawAssistant.ts b/src/graphics/turnout/TurnoutDrawAssistant.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..e64f743 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,7 @@ +export * from './core'; +export * from './graphic'; +export * from './app'; +export * from './operation'; +export * from './utils'; +export * from './plugins'; +export * from './message'; diff --git a/src/jlgraphic/math/Constants.ts b/src/math/Constants.ts similarity index 100% rename from src/jlgraphic/math/Constants.ts rename to src/math/Constants.ts diff --git a/src/jlgraphic/math/Vector2.ts b/src/math/Vector2.ts similarity index 100% rename from src/jlgraphic/math/Vector2.ts rename to src/math/Vector2.ts diff --git a/src/jlgraphic/math/index.ts b/src/math/index.ts similarity index 100% rename from src/jlgraphic/math/index.ts rename to src/math/index.ts diff --git a/src/jlgraphic/message/BasicMessageClient.ts b/src/message/BasicMessageClient.ts similarity index 100% rename from src/jlgraphic/message/BasicMessageClient.ts rename to src/message/BasicMessageClient.ts diff --git a/src/jlgraphic/message/CentrifugeBroker.ts b/src/message/CentrifugeBroker.ts similarity index 100% rename from src/jlgraphic/message/CentrifugeBroker.ts rename to src/message/CentrifugeBroker.ts diff --git a/src/jlgraphic/message/MessageBroker.ts b/src/message/MessageBroker.ts similarity index 100% rename from src/jlgraphic/message/MessageBroker.ts rename to src/message/MessageBroker.ts diff --git a/src/jlgraphic/message/MqttBroker.ts b/src/message/MqttBroker.ts similarity index 100% rename from src/jlgraphic/message/MqttBroker.ts rename to src/message/MqttBroker.ts diff --git a/src/jlgraphic/message/WsMsgBroker.ts b/src/message/WsMsgBroker.ts similarity index 100% rename from src/jlgraphic/message/WsMsgBroker.ts rename to src/message/WsMsgBroker.ts diff --git a/src/message/index.ts b/src/message/index.ts new file mode 100644 index 0000000..349ebdd --- /dev/null +++ b/src/message/index.ts @@ -0,0 +1 @@ +export * from './MessageBroker'; diff --git a/src/jlgraphic/operation/JlOperation.ts b/src/operation/JlOperation.ts similarity index 94% rename from src/jlgraphic/operation/JlOperation.ts rename to src/operation/JlOperation.ts index 6b7f3a6..9e9a960 100644 --- a/src/jlgraphic/operation/JlOperation.ts +++ b/src/operation/JlOperation.ts @@ -70,7 +70,6 @@ export class OperationRecord { if (this.undoStack.length >= this.maxLen) { this.undoStack.shift(); } - // console.log('operation record', op) this.undoStack.push(op); this.redoStack.splice(0, this.redoStack.length); } @@ -79,7 +78,6 @@ export class OperationRecord { */ undo() { const op = this.undoStack.pop(); - // console.log('撤销', op); if (op) { op.undo1(); this.redoStack.push(op); @@ -90,7 +88,6 @@ export class OperationRecord { */ redo() { const op = this.redoStack.pop(); - // console.log('重做', op); if (op) { op.redo1(); this.undoStack.push(op); diff --git a/src/operation/index.ts b/src/operation/index.ts new file mode 100644 index 0000000..0d6da94 --- /dev/null +++ b/src/operation/index.ts @@ -0,0 +1 @@ +export * from './JlOperation'; diff --git a/src/jlgraphic/plugins/AnimationManager.ts b/src/plugins/AnimationManager.ts similarity index 100% rename from src/jlgraphic/plugins/AnimationManager.ts rename to src/plugins/AnimationManager.ts diff --git a/src/jlgraphic/plugins/CommonMousePlugin.ts b/src/plugins/CommonMousePlugin.ts similarity index 93% rename from src/jlgraphic/plugins/CommonMousePlugin.ts rename to src/plugins/CommonMousePlugin.ts index 13143c0..d02ba72 100644 --- a/src/jlgraphic/plugins/CommonMousePlugin.ts +++ b/src/plugins/CommonMousePlugin.ts @@ -153,10 +153,6 @@ export class CommonMouseTool extends AppInteractionPlugin { } onDragStart(event: AppDragEvent) { - // console.log( - // 'start', - // `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}` - // ); if (this.boxSelect && event.target.isCanvas() && event.isLeftButton) { this.box.visible = true; this.app.interactionPlugin(ViewportMovePlugin.Name).resume(); @@ -165,19 +161,11 @@ export class CommonMouseTool extends AppInteractionPlugin { } onDragMove(event: AppDragEvent) { - // console.log( - // 'moving', - // `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}` - // ); if (this.boxSelect && event.target.isCanvas()) { this.boxSelectDraw(event.start, event.end); } } onDragEnd(event: AppDragEvent) { - // console.log( - // 'end', - // `pointerType:${event.original.pointerType},pointerId:${event.original.pointerId},button: ${event.original.button},buttons:${event.original.buttons}` - // ); if (this.boxSelect && event.target.isCanvas() && event.isLeftButton) { this.boxSelectDraw(event.start, event.end); this.boxSelectGraphicCheck(); @@ -232,7 +220,6 @@ export class CommonMouseTool extends AppInteractionPlugin { const graphic = this.leftDownTarget.getGraphic(); if (graphic) { const app = this.app; - // console.log(this.leftDownTarget.isGraphic()); // 图形选中 if (!e.ctrlKey && !graphic.selected && graphic.selectable) { app.updateSelected(graphic); diff --git a/src/jlgraphic/plugins/CopyPlugin.ts b/src/plugins/CopyPlugin.ts similarity index 100% rename from src/jlgraphic/plugins/CopyPlugin.ts rename to src/plugins/CopyPlugin.ts diff --git a/src/jlgraphic/plugins/GraphicEditPlugin.ts b/src/plugins/GraphicEditPlugin.ts similarity index 99% rename from src/jlgraphic/plugins/GraphicEditPlugin.ts rename to src/plugins/GraphicEditPlugin.ts index c93631a..d09398d 100644 --- a/src/jlgraphic/plugins/GraphicEditPlugin.ts +++ b/src/plugins/GraphicEditPlugin.ts @@ -403,7 +403,6 @@ export class BezierCurveEditPlugin extends LineEditPlugin { } initEditPoints() { - // console.log('initEditPoints'); const cps = this.graphic.localToCanvasPoints(...this.linePoints); for (let i = 0; i < cps.length; i++) { const p = cps[i]; diff --git a/src/jlgraphic/plugins/GraphicTransformPlugin.ts b/src/plugins/GraphicTransformPlugin.ts similarity index 99% rename from src/jlgraphic/plugins/GraphicTransformPlugin.ts rename to src/plugins/GraphicTransformPlugin.ts index 1446cc4..848d430 100644 --- a/src/jlgraphic/plugins/GraphicTransformPlugin.ts +++ b/src/plugins/GraphicTransformPlugin.ts @@ -204,7 +204,6 @@ export class GraphicTransformPlugin extends InteractionPluginBase { aps.push(ap); } } - // console.log(positions, aps); return aps; } @@ -319,8 +318,6 @@ export class GraphicTransformPlugin extends InteractionPluginBase { ); } }); - // const dt = new Date().getTime() - start; - // console.log('拖拽耗时', `${dt}ms`, targets); } } } @@ -539,7 +536,6 @@ export class TransformPoints extends Container { KeyListener.create({ value: '' + i, onPress: () => { - // console.log('修改角度step'); this.angleStep = i; }, }) @@ -707,7 +703,6 @@ export class TransformPoints extends Container { // 计算缩放比例,并根据是否保持纵横比两种情况进行缩放处理 const sx = originWidth == 0 ? this.originScale.x : width / originWidth; const sy = originHeight == 0 ? this.originScale.y : height / originHeight; - // console.log(originWidth, originHeight, width, height, sx, sy); if (this.obj.keepAspectRatio) { let max = Math.max(sx, sy); if (originWidth == 0) { diff --git a/src/jlgraphic/plugins/InteractionPlugin.ts b/src/plugins/InteractionPlugin.ts similarity index 99% rename from src/jlgraphic/plugins/InteractionPlugin.ts rename to src/plugins/InteractionPlugin.ts index 23e2210..0a4f127 100644 --- a/src/jlgraphic/plugins/InteractionPlugin.ts +++ b/src/plugins/InteractionPlugin.ts @@ -238,7 +238,6 @@ export class DragPlugin extends OtherInteractionPlugin { // drag移动处理 if (this.target && this.drag && this.start) { - // console.log('drag move', e.movement); this.app.emit( 'drag_op_move', new AppDragEvent(this.app, 'move', this.target, e, this.start) @@ -249,7 +248,6 @@ export class DragPlugin extends OtherInteractionPlugin { onPointerUp(e: FederatedPointerEvent) { if (this.target && this.drag && this.start) { - // console.log('drag end'); this.app.emit( 'drag_op_end', new AppDragEvent(this.app, 'end', this.target, e, this.start) diff --git a/src/jlgraphic/plugins/KeyboardPlugin.ts b/src/plugins/KeyboardPlugin.ts similarity index 97% rename from src/jlgraphic/plugins/KeyboardPlugin.ts rename to src/plugins/KeyboardPlugin.ts index 6ce7d78..3152cfb 100644 --- a/src/jlgraphic/plugins/KeyboardPlugin.ts +++ b/src/plugins/KeyboardPlugin.ts @@ -18,7 +18,6 @@ export class GlobalKeyboardHelper { if (e.ctrlKey) { if (e.code == 'KeyS') { // 屏蔽全局Ctrl+S保存操作 - // console.log('屏蔽全局Ctrl+S') return false; } } @@ -81,7 +80,6 @@ export class JlGraphicAppKeyboardPlugin { const onMouseUpdateTarget = (e: MouseEvent) => { const node = e.target as Node; target = node; - // console.log('Mousedown Event', node.nodeName, node.nodeType, node.nodeValue) }; const keydownHandle = (e: KeyboardEvent) => { // console.debug(e.key, e.code, e.keyCode); @@ -147,7 +145,6 @@ export class JlGraphicAppKeyboardPlugin { stack.push(old); } map.set(keyListener.identifier, keyListener); - // console.log(this.getAllListenedKeys()); } /** * 移除按键监听,若是当前注册的监听,尝试从栈中取出作为按键监听器,若是旧的,则同时移除栈中的监听 @@ -172,7 +169,6 @@ export class JlGraphicAppKeyboardPlugin { stack.splice(index, 1); } } - // console.log(this); } getKeyListenerBy(key: string | number): Map | undefined { @@ -307,7 +303,6 @@ export class KeyListener { return; } if (this.pressTriggerEveryTime || !this.isPress) { - // console.log('Keydown: ', e, this.onPress); this.isPress = true; if (this.onPress) { this.onPress(e, app); @@ -338,7 +333,6 @@ export class KeyListener { release(e: KeyboardEvent, app: IGraphicApp): void { if (this.isPress) { - // console.log('Keyup : ', e.key, e); this.isPress = false; if (this.onRelease) { this.onRelease(e, app); diff --git a/src/plugins/index.ts b/src/plugins/index.ts new file mode 100644 index 0000000..75c00d9 --- /dev/null +++ b/src/plugins/index.ts @@ -0,0 +1,6 @@ +export * from './InteractionPlugin'; +export * from './CommonMousePlugin'; +export * from './KeyboardPlugin'; +export * from './CopyPlugin'; +export * from './GraphicTransformPlugin'; +export * from './AnimationManager'; diff --git a/src/jlgraphic/ui/ContextMenu.ts b/src/ui/ContextMenu.ts similarity index 100% rename from src/jlgraphic/ui/ContextMenu.ts rename to src/ui/ContextMenu.ts diff --git a/src/jlgraphic/ui/Menu.ts b/src/ui/Menu.ts similarity index 100% rename from src/jlgraphic/ui/Menu.ts rename to src/ui/Menu.ts diff --git a/src/jlgraphic/utils/GraphicUtils.ts b/src/utils/GraphicUtils.ts similarity index 100% rename from src/jlgraphic/utils/GraphicUtils.ts rename to src/utils/GraphicUtils.ts diff --git a/src/jlgraphic/utils/IntersectUtils.ts b/src/utils/IntersectUtils.ts similarity index 100% rename from src/jlgraphic/utils/IntersectUtils.ts rename to src/utils/IntersectUtils.ts diff --git a/src/jlgraphic/utils/debounce.ts b/src/utils/debounce.ts similarity index 100% rename from src/jlgraphic/utils/debounce.ts rename to src/utils/debounce.ts diff --git a/src/jlgraphic/utils/index.ts b/src/utils/index.ts similarity index 100% rename from src/jlgraphic/utils/index.ts rename to src/utils/index.ts diff --git a/tsconfig.json b/tsconfig.json index bf07cde..64a3a2c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,13 +7,12 @@ "target": "ESNext", "moduleResolution": "Node", "typeRoots": ["node_modules/@types"], - "sourceMap": true, "strict": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true, "lib": ["esnext", "dom"], "useDefineForClassFields": true }, - "include": ["src/**/*.ts", "rollup.config.ts", "src/jlgraphic/global.d.ts"], + "include": ["src/**/*.ts", "rollup.config.ts", "src/global.d.ts"], "exclude": ["node_modules"] }