id调整&框架调整
This commit is contained in:
parent
5c8ef2ad03
commit
13d9e8615a
4
.gitmodules
vendored
4
.gitmodules
vendored
@ -1,3 +1,7 @@
|
||||
[submodule "xian-ncc-da-message"]
|
||||
path = xian-ncc-da-message
|
||||
url = https://git.code.tencent.com/xian-ncc-da/xian-ncc-da-message.git
|
||||
[submodule "graphic-pixi"]
|
||||
path = graphic-pixi
|
||||
url = https://git.code.tencent.com/jl-framework/graphic-pixi.git
|
||||
branch = xian-ncc-da
|
||||
|
10182
package-lock.json
generated
Normal file
10182
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -14,18 +14,23 @@
|
||||
"build": "set NODE_ENV=dev&&quasar build",
|
||||
"prod": "set NODE_ENV=prod&&quasar build",
|
||||
"dev-show": "set NODE_ENV=dev-show&&quasar build",
|
||||
|
||||
"protoc": "node scripts/proto.cjs",
|
||||
"sync": "node scripts/sync.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@pixi/filter-outline": "^5.2.0",
|
||||
"@pixi/graphics-extras": "^7.2.4",
|
||||
"@quasar/extras": "^1.0.0",
|
||||
"@stomp/stompjs": "^7.0.0",
|
||||
"axios": "^1.2.1",
|
||||
"centrifuge": "^4.0.1",
|
||||
"dotenv": "^16.3.1",
|
||||
"google-protobuf": "^3.21.2",
|
||||
"jl-graphic": "git+https://git.code.tencent.com/jl-framework/graphic-pixi.git#v0.1.0",
|
||||
"js-base64": "^3.7.5",
|
||||
"pinia": "^2.0.11",
|
||||
"pixi-viewport": "^5.0.1",
|
||||
"pixi.js": "^7.2.4",
|
||||
"quasar": "^2.6.0",
|
||||
"save-dev": "0.0.1-security",
|
||||
"vue": "^3.0.0",
|
||||
@ -41,7 +46,6 @@
|
||||
"eslint": "^8.10.0",
|
||||
"eslint-config-prettier": "^8.1.0",
|
||||
"eslint-plugin-vue": "^9.0.0",
|
||||
"pixi.js": "7.2.4",
|
||||
"prettier": "^2.5.1",
|
||||
"protoc-gen-ts": "^0.8.6",
|
||||
"ts-md5": "^1.3.1",
|
||||
|
70
scripts/sync.cjs
Normal file
70
scripts/sync.cjs
Normal file
@ -0,0 +1,70 @@
|
||||
/**
|
||||
* 同步图形框架文件到 src/jl-graphic/
|
||||
*/
|
||||
const {
|
||||
readdirSync,
|
||||
existsSync,
|
||||
copyFileSync,
|
||||
mkdirSync,
|
||||
rmSync,
|
||||
} = require('fs');
|
||||
const { resolve } = require('path');
|
||||
|
||||
const jlGraphicSrcPath = resolve(__dirname, '../graphic-pixi/src/jlgraphic');
|
||||
const jlGraphicLibPath = resolve(__dirname, '../src/jl-graphic');
|
||||
|
||||
/**
|
||||
* 检查并初始化当前项目引入的jl-graphic库
|
||||
*/
|
||||
function checkAndInitJlGraphicLib() {
|
||||
const exist = existsSync(jlGraphicLibPath);
|
||||
if (exist) {
|
||||
console.log('jl-graphic文件夹已存在,清空');
|
||||
readdirSync(jlGraphicLibPath, {
|
||||
withFileTypes: true,
|
||||
}).forEach((file) => {
|
||||
if (file.isDirectory()) {
|
||||
rmSync(resolve(jlGraphicLibPath, file.name), { recursive: true });
|
||||
} else {
|
||||
rmSync(resolve(jlGraphicLibPath, file.name));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log('jl-graphic文件夹不存在,创建');
|
||||
// 文件夹不存在,创建
|
||||
mkdirSync(jlGraphicLibPath);
|
||||
}
|
||||
}
|
||||
|
||||
function copyJlGraphicFiles() {
|
||||
readdirSync(jlGraphicSrcPath, {
|
||||
withFileTypes: true,
|
||||
}).forEach((file) => {
|
||||
recursiveCopyFiles(file);
|
||||
});
|
||||
}
|
||||
|
||||
function recursiveCopyFiles(file, path = []) {
|
||||
if (file.isFile()) {
|
||||
const fileSrcPath = resolve(jlGraphicSrcPath, ...path, file.name);
|
||||
const fileDestPath = resolve(jlGraphicLibPath, ...path, file.name);
|
||||
console.log(`copy file ${fileSrcPath} -> ${fileDestPath}`);
|
||||
copyFileSync(fileSrcPath, fileDestPath);
|
||||
} else if (file.isDirectory()) {
|
||||
const srcDir = resolve(jlGraphicSrcPath, ...path, file.name);
|
||||
const dirPath = resolve(jlGraphicLibPath, ...path, file.name);
|
||||
mkdirSync(dirPath);
|
||||
readdirSync(srcDir, {
|
||||
withFileTypes: true,
|
||||
}).forEach((subFile) => {
|
||||
recursiveCopyFiles(subFile, [...path, file.name]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
checkAndInitJlGraphicLib();
|
||||
copyJlGraphicFiles();
|
||||
}
|
||||
|
||||
main();
|
@ -1,5 +1,5 @@
|
||||
import { type GraphicDataBase } from 'src/drawApp/graphics/GraphicDataBase';
|
||||
import { IDrawApp, JlGraphic } from 'jl-graphic';
|
||||
import { IDrawApp, JlGraphic } from 'src/jl-graphic';
|
||||
import { useDrawStore } from 'src/stores/draw-store';
|
||||
import { onMounted, onUnmounted, reactive } from 'vue';
|
||||
|
||||
|
@ -72,7 +72,7 @@
|
||||
<script setup lang="ts">
|
||||
import DraggableDialog from '../common/DraggableDialog.vue';
|
||||
import { onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { JlGraphic } from 'jl-graphic';
|
||||
import { JlGraphic } from 'src/jl-graphic';
|
||||
import { Station } from 'src/graphics/station/Station';
|
||||
import { useLineStore } from 'src/stores/line-store';
|
||||
import { QForm, useQuasar } from 'quasar';
|
||||
|
@ -98,7 +98,7 @@
|
||||
<script setup lang="ts">
|
||||
import DraggableDialog from '../common/DraggableDialog.vue';
|
||||
import { onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { JlGraphic } from 'jl-graphic';
|
||||
import { JlGraphic } from 'src/jl-graphic';
|
||||
import { Station } from 'src/graphics/station/Station';
|
||||
import { useLineStore } from 'src/stores/line-store';
|
||||
import { QForm, useQuasar } from 'quasar';
|
||||
|
@ -78,7 +78,7 @@ import {
|
||||
IAreaConfigItem,
|
||||
queryDeviceRangeById,
|
||||
} from 'src/api/ConfigApi';
|
||||
import { JlGraphic } from 'jl-graphic';
|
||||
import { JlGraphic } from 'src/jl-graphic';
|
||||
import { saveAlertTypeData, showAlertTypeData } from '../alarm/alarmInfoEnum';
|
||||
import { Section } from 'src/graphics/section/Section';
|
||||
import { useRangeConfigStore } from 'src/stores/range-config-store';
|
||||
|
@ -6,13 +6,14 @@ import {
|
||||
GraphicTransform,
|
||||
IChildTransform,
|
||||
IGraphicTransform,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
// import { toStorageTransform } from '..';
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { IPointData, Point } from 'pixi.js';
|
||||
import { state } from 'src/protos/device_status';
|
||||
|
||||
export interface ICommonInfo {
|
||||
id: number;
|
||||
id: string;
|
||||
graphicType: string;
|
||||
transform: IGraphicTransform;
|
||||
childTransforms: IChildTransform[];
|
||||
@ -59,7 +60,7 @@ export abstract class GraphicDataBase implements GraphicData {
|
||||
|
||||
static defaultCommonInfo(graphicType: string): graphicData.CommonInfo {
|
||||
return new graphicData.CommonInfo({
|
||||
id: 0,
|
||||
id: '',
|
||||
graphicType: graphicType,
|
||||
transform: new graphicData.Transform({
|
||||
position: new graphicData.Point({ x: 0, y: 0 }),
|
||||
@ -75,10 +76,10 @@ export abstract class GraphicDataBase implements GraphicData {
|
||||
return this._data as D;
|
||||
}
|
||||
|
||||
get id(): number {
|
||||
get id(): string {
|
||||
return this._data.common.id;
|
||||
}
|
||||
set id(v: number) {
|
||||
set id(v: string) {
|
||||
this._data.common.id = v;
|
||||
}
|
||||
get graphicType(): string {
|
||||
|
@ -3,18 +3,20 @@ import { IPointData, DisplayObject, FederatedMouseEvent } from 'pixi.js';
|
||||
import { ILinkData, Link } from 'src/graphics/link/Link';
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { GraphicDataBase } from './GraphicDataBase';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import {
|
||||
IGraphicApp,
|
||||
GraphicInteractionPlugin,
|
||||
JlGraphic,
|
||||
ContextMenu,
|
||||
MenuItemOptions,
|
||||
} from 'src/jl-graphic';
|
||||
import {
|
||||
addWayPoint,
|
||||
clearWayPoint,
|
||||
getWaypointRangeIndex,
|
||||
PolylineEditPlugin,
|
||||
removeLineWayPoint,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
|
||||
export class LinkData extends GraphicDataBase implements ILinkData {
|
||||
constructor(data?: graphicData.Link) {
|
||||
|
@ -13,10 +13,10 @@ import {
|
||||
IGraphicApp,
|
||||
GraphicInteractionPlugin,
|
||||
JlGraphic,
|
||||
MenuItemOptions,
|
||||
ContextMenu,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { LogicSectionGraphicHitArea } from 'src/graphics/logicSection/LogicSectionDrawAssistant';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { useLineStore } from 'src/stores/line-store';
|
||||
import { setTrackStatus } from 'src/api/TurnoutApi';
|
||||
import { successNotify } from 'src/utils/CommonNotify';
|
||||
|
@ -7,13 +7,13 @@ import {
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { GraphicDataBase, GraphicStateBase } from './GraphicDataBase';
|
||||
import { state } from 'src/protos/device_status';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import {
|
||||
IGraphicApp,
|
||||
GraphicInteractionPlugin,
|
||||
JlGraphic,
|
||||
MenuItemOptions,
|
||||
ContextMenu,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { DisplayObject, FederatedMouseEvent } from 'pixi.js';
|
||||
import { mockPlatformApi } from 'src/api/PlatformApi';
|
||||
import { useLineStore } from 'src/stores/line-store';
|
||||
@ -59,16 +59,16 @@ export class PlatformData extends GraphicDataBase implements IPlatformData {
|
||||
set up(v: boolean) {
|
||||
this.data.up = v;
|
||||
}
|
||||
get refStation(): number {
|
||||
get refStation(): string {
|
||||
return this.data.refStation;
|
||||
}
|
||||
set refStation(v: number) {
|
||||
set refStation(v: string) {
|
||||
this.data.refStation = v;
|
||||
}
|
||||
get refSectionId(): number {
|
||||
get refSectionId(): string {
|
||||
return this.data.refSectionId;
|
||||
}
|
||||
set refSectionId(v: number) {
|
||||
set refSectionId(v: string) {
|
||||
this.data.refSectionId = v;
|
||||
}
|
||||
|
||||
|
@ -10,15 +10,17 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
IGraphicApp,
|
||||
JlGraphic,
|
||||
ContextMenu,
|
||||
MenuItemOptions,
|
||||
} from 'src/jl-graphic';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { FederatedMouseEvent, DisplayObject, IPointData } from 'pixi.js';
|
||||
import {
|
||||
addWayPoint,
|
||||
clearWayPoint,
|
||||
getWaypointRangeIndex,
|
||||
PolylineEditPlugin,
|
||||
removeLineWayPoint,
|
||||
} from 'jl-graphic';
|
||||
import { FederatedMouseEvent, DisplayObject, IPointData } from 'pixi.js';
|
||||
} from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
import { RunLineGraphicHitArea } from 'src/graphics/runLine/RunLineDrawAssistant';
|
||||
import { Dialog } from 'quasar';
|
||||
import SetDashLineDialog from '../../components/draw-app/dialogs/SetDashLineDialog.vue';
|
||||
@ -71,10 +73,10 @@ export class RunLineData extends GraphicDataBase implements IRunLineData {
|
||||
set containSta(v: string[]) {
|
||||
this.data.containSta = v;
|
||||
}
|
||||
get linkPathLines(): number[] {
|
||||
get linkPathLines(): string[] {
|
||||
return this.data.linkPathLines;
|
||||
}
|
||||
set linkPathLines(v: number[]) {
|
||||
set linkPathLines(v: string[]) {
|
||||
this.data.linkPathLines = v;
|
||||
}
|
||||
get lineId(): string {
|
||||
|
@ -3,7 +3,11 @@ import { GraphicDataBase } from './GraphicDataBase';
|
||||
import { ISectionData, Section } from 'src/graphics/section/Section';
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { DisplayObject, FederatedMouseEvent, IPointData } from 'pixi.js';
|
||||
import { GraphicInteractionPlugin, IGraphicApp, JlGraphic } from 'jl-graphic';
|
||||
import {
|
||||
GraphicInteractionPlugin,
|
||||
IGraphicApp,
|
||||
JlGraphic,
|
||||
} from 'src/jl-graphic';
|
||||
import { SectionGraphicHitArea } from 'src/graphics/section/SectionDrawAssistant';
|
||||
|
||||
export class SectionData extends GraphicDataBase implements ISectionData {
|
||||
@ -59,10 +63,10 @@ export class SectionData extends GraphicDataBase implements ISectionData {
|
||||
set axleCountings(axleCountings: string[]) {
|
||||
this.data.axleCountings = axleCountings;
|
||||
}
|
||||
get children(): number[] {
|
||||
get children(): string[] {
|
||||
return this.data.children;
|
||||
}
|
||||
set children(children: number[]) {
|
||||
set children(children: string[]) {
|
||||
this.data.children = children;
|
||||
}
|
||||
get destinationCode(): string {
|
||||
|
@ -11,9 +11,9 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
IGraphicApp,
|
||||
JlGraphic,
|
||||
ContextMenu,
|
||||
MenuItemOptions,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { FederatedMouseEvent, DisplayObject } from 'pixi.js';
|
||||
import { state } from 'src/protos/device_status';
|
||||
import { mockSignalApi } from 'src/api/PlatformApi';
|
||||
|
@ -7,13 +7,13 @@ import {
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { GraphicDataBase, GraphicStateBase } from './GraphicDataBase';
|
||||
import { state } from 'src/protos/device_status';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import {
|
||||
IGraphicApp,
|
||||
GraphicInteractionPlugin,
|
||||
JlGraphic,
|
||||
MenuItemOptions,
|
||||
ContextMenu,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { DisplayObject, FederatedMouseEvent } from 'pixi.js';
|
||||
import { KilometerSystem } from 'src/graphics/signal/Signal';
|
||||
import { useLineStore } from 'src/stores/line-store';
|
||||
|
@ -4,14 +4,14 @@ import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { GraphicDataBase, GraphicStateBase } from './GraphicDataBase';
|
||||
import { state } from 'src/protos/device_status';
|
||||
import { train } from 'src/protos/train';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import {
|
||||
IGraphicApp,
|
||||
GraphicInteractionPlugin,
|
||||
JlGraphic,
|
||||
VectorText,
|
||||
MenuItemOptions,
|
||||
ContextMenu,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import {
|
||||
Color,
|
||||
Container,
|
||||
|
@ -31,10 +31,10 @@ export class TrainWindowData
|
||||
set code(v: string) {
|
||||
this.data.code = v;
|
||||
}
|
||||
get refDeviceId(): number[] {
|
||||
get refDeviceId(): string[] {
|
||||
return this.data.refDeviceId;
|
||||
}
|
||||
set refDeviceId(v: number[]) {
|
||||
set refDeviceId(v: string[]) {
|
||||
this.data.refDeviceId = v;
|
||||
}
|
||||
clone(): TrainWindowData {
|
||||
|
@ -13,13 +13,13 @@ import {
|
||||
IGraphicApp,
|
||||
GraphicInteractionPlugin,
|
||||
JlGraphic,
|
||||
ContextMenu,
|
||||
MenuItemOptions,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import {
|
||||
ForkHitArea,
|
||||
TurnoutSectionHitArea,
|
||||
} from 'src/graphics/turnout/TurnoutDrawAssistant';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { setSwitchStatus } from 'src/api/TurnoutApi';
|
||||
import { useLineStore } from 'src/stores/line-store';
|
||||
import { successNotify } from 'src/utils/CommonNotify';
|
||||
|
@ -12,9 +12,9 @@ import {
|
||||
KeyListener,
|
||||
newDrawApp,
|
||||
IGraphicStorage,
|
||||
ContextMenu,
|
||||
MenuItemOptions,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { IscsFanData } from './graphics/IscsFanInteraction';
|
||||
import { LinkData } from './graphics/LinkInteraction';
|
||||
import { TrainData, TrainState } from './graphics/TrainInteraction';
|
||||
|
@ -3,7 +3,7 @@ import {
|
||||
GraphicState,
|
||||
IGraphicApp,
|
||||
newGraphicApp,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import {
|
||||
TrainData,
|
||||
TrainOperateInteraction,
|
||||
@ -58,7 +58,8 @@ import {
|
||||
import { TrainWindowData } from './graphics/TrainWindowInteraction';
|
||||
import { SeparatorTemplate } from 'src/graphics/separator/Separator';
|
||||
import { SeparatorData } from './graphics/SeparatorInteraction';
|
||||
import { ContextMenu, MenuItemOptions } from 'jl-graphic';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import {
|
||||
LogicSection,
|
||||
LogicSectionTemplate,
|
||||
|
@ -3,7 +3,7 @@ import {
|
||||
GraphicData,
|
||||
GraphicState,
|
||||
newGraphicApp,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { getPublishLineNet } from 'src/api/PublishApi';
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { state } from 'src/protos/ws_message';
|
||||
|
@ -7,13 +7,7 @@ import { SectionTemplate } from 'src/graphics/section/Section';
|
||||
import { Signal, SignalTemplate } from 'src/graphics/signal/Signal';
|
||||
import { Station, StationTemplate } from 'src/graphics/station/Station';
|
||||
import { Turnout, TurnoutTemplate } from 'src/graphics/turnout/Turnout';
|
||||
import {
|
||||
IGraphicApp,
|
||||
GraphicData,
|
||||
newGraphicApp,
|
||||
MenuItemOptions,
|
||||
ContextMenu,
|
||||
} from 'jl-graphic';
|
||||
import { IGraphicApp, GraphicData, newGraphicApp } from 'src/jl-graphic';
|
||||
import {
|
||||
LogicSectionData,
|
||||
LogicSectionState,
|
||||
@ -31,6 +25,8 @@ import { getPublishMapInfoByLineId } from 'src/api/PublishApi';
|
||||
import { useRangeConfigStore } from 'src/stores/range-config-store';
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { toUint8Array } from 'js-base64';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { CanvasData, IGraphicAppConfig } from 'src/jl-graphic/app/JlGraphicApp';
|
||||
|
||||
let rangeConfigApp: IGraphicApp;
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { Graphics } from 'pixi.js';
|
||||
import { calculateMirrorPoint } from 'jl-graphic';
|
||||
import { calculateMirrorPoint } from 'src/jl-graphic';
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
import { Turnout, TurnoutPort } from './turnout/Turnout';
|
||||
import { Section, SectionPort } from './section/Section';
|
||||
@ -111,6 +111,6 @@ export function protoPort2Data(port: graphicData.RelatedRef.DevicePort) {
|
||||
|
||||
export interface IRelatedRefData {
|
||||
deviceType: graphicData.RelatedRef.DeviceType; //关联的设备类型
|
||||
id: number; //关联的设备ID
|
||||
id: string; //关联的设备ID
|
||||
devicePort: graphicData.RelatedRef.DevicePort; //关联的设备端口
|
||||
}
|
||||
|
@ -5,7 +5,7 @@ import {
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
VectorText,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { IRelatedRefData, protoPort2Data } from '../CommonGraphics';
|
||||
import { KilometerSystem } from '../signal/Signal';
|
||||
|
||||
|
@ -8,7 +8,7 @@ import {
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
distance2,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import {
|
||||
IAxleCountingData,
|
||||
|
@ -3,7 +3,7 @@ import {
|
||||
GraphicData,
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import ISCS_FAN_Assets from './iscs-fan-spritesheet.png';
|
||||
import ISCS_FAN_JSON from './iscs-fan-data.json';
|
||||
|
||||
|
@ -4,7 +4,7 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
JlDrawApp,
|
||||
JlGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { IIscsFanData, IscsFan, IscsFanTemplate } from './IscsFan';
|
||||
|
||||
export class IscsFanDraw extends GraphicDrawAssistant<
|
||||
|
@ -4,8 +4,8 @@ import {
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
convertToBezierParams,
|
||||
ILineGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { ILineGraphic } from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
|
||||
export interface ILinkData extends GraphicData {
|
||||
get code(): string; // 编号
|
||||
|
@ -21,12 +21,15 @@ import {
|
||||
convertToBezierParams,
|
||||
linePoint,
|
||||
pointPolygon,
|
||||
AbsorbablePoint,
|
||||
} from 'src/jl-graphic';
|
||||
import AbsorbablePoint, {
|
||||
AbsorbableCircle,
|
||||
} from 'src/jl-graphic/graphic/AbsorbablePosition';
|
||||
import {
|
||||
BezierCurveEditPlugin,
|
||||
ILineGraphic,
|
||||
PolylineEditPlugin,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
import { ILinkData, Link, LinkTemplate } from './Link';
|
||||
|
||||
export interface ILinkDrawOptions {
|
||||
|
@ -7,8 +7,8 @@ import {
|
||||
JlGraphicTemplate,
|
||||
VectorText,
|
||||
getParallelOfPolyline,
|
||||
ILineGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { ILineGraphic } from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
import { SectionConsts } from '../section/Section';
|
||||
import { Station } from '../station/Station';
|
||||
|
||||
|
@ -5,7 +5,7 @@ import {
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
linePoint,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { LogicSection, LogicSectionTemplate } from './LogicSection';
|
||||
import { LogicSectionData } from 'src/drawApp/graphics/LogicSectionInteraction';
|
||||
import { Graphics, IHitArea, Point } from 'pixi.js';
|
||||
|
@ -2,14 +2,14 @@ import {
|
||||
JlGraphic,
|
||||
GraphicData,
|
||||
JlGraphicTemplate,
|
||||
VectorText,
|
||||
isPointOnLine,
|
||||
calculateFootPointFromPointToLine,
|
||||
distance,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { Graphics, IPointData, Point } from 'pixi.js';
|
||||
import { RunLine } from '../runLine/RunLine';
|
||||
import { getDrawApp } from 'src/drawApp';
|
||||
// calculateDistanceFromPointToLine
|
||||
import { calculateFootPointFromPointToLine, distance } from 'src/jl-graphic';
|
||||
import { StationLine } from '../stationLine/StationLine';
|
||||
export interface KilometerPoint {
|
||||
get point(): IPointData;
|
||||
|
@ -10,7 +10,7 @@ import {
|
||||
calculateFootPointFromPointToLine,
|
||||
calculateDistanceFromPointToLine,
|
||||
distance,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import {
|
||||
IPathLineData,
|
||||
PathLineTemplate,
|
||||
|
@ -8,7 +8,7 @@ import {
|
||||
calculateMirrorPoint,
|
||||
distance2,
|
||||
getRectangleCenter,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { Station } from '../station/Station';
|
||||
import { Section } from '../section/Section';
|
||||
|
||||
@ -21,10 +21,10 @@ export interface IPlatformData extends GraphicData {
|
||||
set direction(v: string);
|
||||
get up(): boolean; // 站台上下行
|
||||
set up(v: boolean);
|
||||
get refStation(): number; // 关联的车站
|
||||
set refStation(v: number);
|
||||
get refSectionId(): number; // 关联的物理区段
|
||||
set refSectionId(v: number);
|
||||
get refStation(): string; // 关联的车站
|
||||
set refStation(v: string);
|
||||
get refSectionId(): string; // 关联的物理区段
|
||||
set refSectionId(v: string);
|
||||
clone(): IPlatformData;
|
||||
copyFrom(data: IPlatformData): void;
|
||||
eq(other: IPlatformData): boolean;
|
||||
|
@ -6,7 +6,7 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import { IPlatformData, Platform, PlatformTemplate } from './Platform';
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { Color, Graphics, IPointData } from 'pixi.js';
|
||||
import { GraphicData, JlGraphic, JlGraphicTemplate } from 'jl-graphic';
|
||||
import { GraphicData, JlGraphic, JlGraphicTemplate } from 'src/jl-graphic';
|
||||
|
||||
export interface IPolygonData extends GraphicData {
|
||||
get code(): string; // 编号
|
||||
|
@ -14,11 +14,15 @@ import {
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
linePoint,
|
||||
AbsorbablePoint,
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import AbsorbablePoint, {
|
||||
AbsorbablePosition,
|
||||
} from 'src/jl-graphic/graphic/AbsorbablePosition';
|
||||
import {
|
||||
ILineGraphic,
|
||||
PolylineEditPlugin,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
|
||||
import { IPolygonData, Polygon, PolygonTemplate } from './Polygon';
|
||||
|
||||
|
@ -2,7 +2,7 @@ import { IPointData, Point } from 'pixi.js';
|
||||
import {
|
||||
calculateDistanceFromPointToLine,
|
||||
calculateFootPointFromPointToLine,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { Polygon } from './Polygon';
|
||||
|
||||
//计算线段细分坐标--线段分成几份
|
||||
|
@ -4,7 +4,7 @@ import {
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
getRectangleCenter,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
export interface IRectData extends GraphicData {
|
||||
get code(): string; // 编号
|
||||
|
@ -5,7 +5,7 @@ import {
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
pointBox,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import { IRectData, Rect, RectTemplate } from './Rect';
|
||||
|
||||
|
@ -8,13 +8,13 @@ import {
|
||||
getIntersectionPoint,
|
||||
distance,
|
||||
DashedLine,
|
||||
calculateDistanceFromPointToLine,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { RunLineName } from './RunLineName';
|
||||
import { PathLine } from '../pathLine/PathLine';
|
||||
import { PathLineDraw } from '../pathLine/PathLineDrawAssistant';
|
||||
import { getDrawApp } from 'src/drawApp';
|
||||
import { StationLine } from '../stationLine/StationLine';
|
||||
import { calculateDistanceFromPointToLine } from 'src/jl-graphic';
|
||||
|
||||
export interface IRunLineData extends GraphicData {
|
||||
get code(): string;
|
||||
@ -27,8 +27,8 @@ export interface IRunLineData extends GraphicData {
|
||||
set nameBgColor(v: string);
|
||||
get containSta(): string[];
|
||||
set containSta(v: string[]);
|
||||
get linkPathLines(): number[];
|
||||
set linkPathLines(v: number[]);
|
||||
get linkPathLines(): string[];
|
||||
set linkPathLines(v: string[]);
|
||||
get lineId(): string;
|
||||
set lineId(v: string);
|
||||
get dashPointIndexs(): number[];
|
||||
|
@ -8,16 +8,17 @@ import {
|
||||
AbsorbablePosition,
|
||||
DraggablePoint,
|
||||
GraphicTransformEvent,
|
||||
PolylineEditPlugin,
|
||||
ILineGraphic,
|
||||
AbsorbableLine,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import {
|
||||
IRunLineData,
|
||||
RunLine,
|
||||
RunLineTemplate,
|
||||
runLineConsts,
|
||||
} from './RunLine';
|
||||
import {
|
||||
PolylineEditPlugin,
|
||||
ILineGraphic,
|
||||
} from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
import {
|
||||
FederatedPointerEvent,
|
||||
Point,
|
||||
@ -26,6 +27,7 @@ import {
|
||||
IHitArea,
|
||||
DisplayObject,
|
||||
} from 'pixi.js';
|
||||
import { AbsorbableLine } from 'src/jl-graphic/graphic/AbsorbablePosition';
|
||||
|
||||
export interface IRunLineDrawOptions {
|
||||
newData: () => IRunLineData;
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { Container } from '@pixi/display';
|
||||
import { Graphics } from 'pixi.js';
|
||||
import { VectorText } from 'jl-graphic';
|
||||
import { VectorText } from 'src/jl-graphic';
|
||||
import { IRunLineData } from './RunLine';
|
||||
|
||||
const nameConsts = {
|
||||
|
@ -7,16 +7,16 @@ import {
|
||||
VectorText,
|
||||
distance2,
|
||||
splitLineEvenly,
|
||||
ILineGraphic,
|
||||
epsilon,
|
||||
Vector2,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { ILineGraphic } from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
import { epsilon } from 'src/jl-graphic/math';
|
||||
import {
|
||||
IRelatedRefData,
|
||||
createRelatedRefProto,
|
||||
protoPort2Data,
|
||||
} from '../CommonGraphics';
|
||||
import { Turnout } from '../turnout/Turnout';
|
||||
import Vector2 from 'src/jl-graphic/math/Vector2';
|
||||
import { AxleCounting } from '../axleCounting/AxleCounting';
|
||||
|
||||
export enum SectionType {
|
||||
@ -42,8 +42,8 @@ export interface ISectionData extends GraphicData {
|
||||
set sectionType(type: SectionType);
|
||||
get axleCountings(): string[];
|
||||
set axleCountings(axleCountings: string[]);
|
||||
get children(): number[];
|
||||
set children(children: number[]);
|
||||
get children(): string[];
|
||||
set children(children: string[]);
|
||||
get destinationCode(): string;
|
||||
set destinationCode(destinationCode: string);
|
||||
get turning(): boolean;
|
||||
|
@ -12,18 +12,7 @@ import {
|
||||
VectorText,
|
||||
calculateLineMidpoint,
|
||||
linePoint,
|
||||
IEditPointOptions,
|
||||
ILineGraphic,
|
||||
PolylineEditPlugin,
|
||||
addWayPoint,
|
||||
clearWayPoint,
|
||||
getWaypointRangeIndex,
|
||||
AbsorbablePoint,
|
||||
AbsorbableLine,
|
||||
AbsorbablePosition,
|
||||
MenuItemOptions,
|
||||
ContextMenu,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import {
|
||||
ISectionData,
|
||||
Section,
|
||||
@ -40,7 +29,21 @@ import {
|
||||
IPointData,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import {
|
||||
IEditPointOptions,
|
||||
ILineGraphic,
|
||||
PolylineEditPlugin,
|
||||
addWayPoint,
|
||||
clearWayPoint,
|
||||
getWaypointRangeIndex,
|
||||
} from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
import AbsorbablePoint, {
|
||||
AbsorbableLine,
|
||||
AbsorbablePosition,
|
||||
} from 'src/jl-graphic/graphic/AbsorbablePosition';
|
||||
import { Turnout, TurnoutPort } from '../turnout/Turnout';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { Dialog } from 'quasar';
|
||||
import { SectionData } from 'src/drawApp/graphics/SectionInteraction';
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { Color, Graphics } from 'pixi.js';
|
||||
import { GraphicData, JlGraphic, JlGraphicTemplate } from 'jl-graphic';
|
||||
import { GraphicData, JlGraphic, JlGraphicTemplate } from 'src/jl-graphic';
|
||||
|
||||
export interface ISeparatorData extends GraphicData {
|
||||
get code(): string; // 编号
|
||||
|
@ -7,7 +7,7 @@ import {
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
linePoint,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { Section, SectionType } from '../section/Section';
|
||||
import {
|
||||
ISeparatorData,
|
||||
|
@ -1,5 +1,9 @@
|
||||
import { Graphics, Point } from 'pixi.js';
|
||||
import { calculateMirrorPoint, GraphicAnimation, JlGraphic } from 'jl-graphic';
|
||||
import {
|
||||
calculateMirrorPoint,
|
||||
GraphicAnimation,
|
||||
JlGraphic,
|
||||
} from 'src/jl-graphic';
|
||||
import { Lamp } from './Lamp';
|
||||
import { ISignalState } from './Signal';
|
||||
|
||||
|
@ -4,8 +4,8 @@ import {
|
||||
GraphicState,
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
calculateMirrorPoint,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { calculateMirrorPoint } from 'src/jl-graphic';
|
||||
import { LampMainBody } from './LampMainBody';
|
||||
import { drawArrow } from '../CommonGraphics';
|
||||
import { SignalCode } from './SignalCode';
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { Container, Graphics, Point } from 'pixi.js';
|
||||
import { VectorText } from 'jl-graphic';
|
||||
import { VectorText } from 'src/jl-graphic';
|
||||
import { ISignalData, ISignalState } from './Signal';
|
||||
|
||||
export enum CodeColorEnum {
|
||||
|
@ -7,7 +7,7 @@ import {
|
||||
GraphicTransformEvent,
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import { ISignalData, Signal, SignalTemplate } from './Signal';
|
||||
|
||||
|
@ -5,7 +5,7 @@ import {
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
VectorText,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { LogicSection } from '../logicSection/LogicSection';
|
||||
import { Platform } from '../platform/Platform';
|
||||
import { KilometerSystem, Signal } from '../signal/Signal';
|
||||
|
@ -6,7 +6,7 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import { IStationData, Station, StationTemplate } from './Station';
|
||||
|
||||
|
@ -4,7 +4,7 @@ import {
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
VectorText,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { graphicData } from 'src/protos/stationLayoutGraphics';
|
||||
|
||||
export interface IStationLineData extends GraphicData {
|
||||
|
@ -6,7 +6,7 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import {
|
||||
IStationLineData,
|
||||
|
@ -7,7 +7,7 @@ import {
|
||||
JlGraphicTemplate,
|
||||
VectorText,
|
||||
calculateMirrorPoint,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { train } from 'src/protos/train';
|
||||
import { state } from 'src/protos/device_status';
|
||||
import { TrainWindow } from '../trainWindow/TrainWindow';
|
||||
|
@ -4,7 +4,7 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import { ITrainData, Train, TrainTemplate } from './Train';
|
||||
|
||||
|
@ -5,7 +5,7 @@ import {
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
distance,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import trainLineSprites from './trainLineSprites.png';
|
||||
|
||||
import { Assets, Sprite, Texture } from 'pixi.js';
|
||||
|
@ -4,7 +4,7 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { ITrainLineData, TrainLine, ItrainLineTemplate } from './TrainLine';
|
||||
|
||||
export class TrainLineDraw extends GraphicDrawAssistant<
|
||||
|
@ -5,15 +5,15 @@ import {
|
||||
JlGraphicTemplate,
|
||||
distance2,
|
||||
getRectangleCenter,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { LogicSection } from '../logicSection/LogicSection';
|
||||
import { Section } from '../section/Section';
|
||||
|
||||
export interface ITrainWindowData extends GraphicData {
|
||||
get code(): string; // 编号
|
||||
set code(v: string);
|
||||
get refDeviceId(): number[]; // 关联的区段的id
|
||||
set refDeviceId(v: number[]);
|
||||
get refDeviceId(): string[]; // 关联的区段的id
|
||||
set refDeviceId(v: string[]);
|
||||
clone(): ITrainWindowData;
|
||||
copyFrom(data: ITrainWindowData): void;
|
||||
eq(other: ITrainWindowData): boolean;
|
||||
|
@ -7,7 +7,7 @@ import {
|
||||
GraphicInteractionPlugin,
|
||||
IDrawApp,
|
||||
JlGraphic,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
|
||||
import {
|
||||
ITrainWindowData,
|
||||
|
@ -5,7 +5,7 @@ import {
|
||||
JlDrawApp,
|
||||
JlGraphic,
|
||||
JlGraphicTemplate,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { TrainWindow } from './TrainWindow';
|
||||
import { TrainWindowDraw } from './TrainWindowDrawAssistant';
|
||||
import { AxleCounting } from '../axleCounting/AxleCounting';
|
||||
|
@ -10,16 +10,16 @@ import {
|
||||
angleOfIncludedAngle,
|
||||
distance2,
|
||||
getParallelOfPolyline,
|
||||
epsilon,
|
||||
Vector2,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import { Section, SectionPort } from '../section/Section';
|
||||
import { epsilon } from 'src/jl-graphic/math';
|
||||
import {
|
||||
IRelatedRefData,
|
||||
createRelatedRefProto,
|
||||
protoPort2Data,
|
||||
} from '../CommonGraphics';
|
||||
import { KilometerSystem } from '../signal/Signal';
|
||||
import Vector2 from 'src/jl-graphic/math/Vector2';
|
||||
import { Station } from '../station/Station';
|
||||
|
||||
export interface ITurnoutData extends GraphicData {
|
||||
|
@ -11,13 +11,7 @@ import {
|
||||
VectorText,
|
||||
linePoint,
|
||||
polylinePoint,
|
||||
GraphicEditPlugin,
|
||||
getWaypointRangeIndex,
|
||||
AbsorbablePoint,
|
||||
AbsorbableLine,
|
||||
ContextMenu,
|
||||
MenuItemOptions,
|
||||
} from 'jl-graphic';
|
||||
} from 'src/jl-graphic';
|
||||
import {
|
||||
ITurnoutData,
|
||||
Turnout,
|
||||
@ -34,7 +28,16 @@ import {
|
||||
IPointData,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import {
|
||||
GraphicEditPlugin,
|
||||
getWaypointRangeIndex,
|
||||
} from 'src/jl-graphic/plugins/GraphicEditPlugin';
|
||||
import { Section, SectionPort } from '../section/Section';
|
||||
import AbsorbablePoint, {
|
||||
AbsorbableLine,
|
||||
} from 'src/jl-graphic/graphic/AbsorbablePosition';
|
||||
import { ContextMenu } from 'src/jl-graphic/ui/ContextMenu';
|
||||
import { MenuItemOptions } from 'src/jl-graphic/ui/Menu';
|
||||
|
||||
export class TurnoutDraw extends GraphicDrawAssistant<
|
||||
TurnoutTemplate,
|
||||
|
110
src/jl-graphic/app/BasicOperation.ts
Normal file
110
src/jl-graphic/app/BasicOperation.ts
Normal file
@ -0,0 +1,110 @@
|
||||
import { GraphicData, JlGraphic } from '../core';
|
||||
import { JlOperation } from '../operation';
|
||||
import { ICanvasProperties, IGraphicApp, IJlCanvas } from './JlGraphicApp';
|
||||
|
||||
/**
|
||||
* 更新画布操作
|
||||
*/
|
||||
export class UpdateCanvasOperation extends JlOperation {
|
||||
obj: IJlCanvas;
|
||||
old: ICanvasProperties;
|
||||
data: ICanvasProperties;
|
||||
description = '';
|
||||
|
||||
constructor(
|
||||
app: IGraphicApp,
|
||||
obj: IJlCanvas,
|
||||
old: ICanvasProperties,
|
||||
data: ICanvasProperties
|
||||
) {
|
||||
super(app, 'update-canvas');
|
||||
this.app = app;
|
||||
this.obj = obj;
|
||||
this.old = old;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
undo(): JlGraphic[] {
|
||||
this.obj.update(this.old);
|
||||
return [];
|
||||
}
|
||||
redo(): JlGraphic[] {
|
||||
this.obj.update(this.data);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 创建图形操作
|
||||
*/
|
||||
export class GraphicCreateOperation extends JlOperation {
|
||||
obj: JlGraphic[];
|
||||
description = '';
|
||||
|
||||
constructor(app: IGraphicApp, obj: JlGraphic[]) {
|
||||
super(app, 'graphic-create');
|
||||
this.app = app;
|
||||
this.obj = obj;
|
||||
}
|
||||
|
||||
undo(): JlGraphic[] | void {
|
||||
this.app.deleteGraphics(...this.obj);
|
||||
}
|
||||
redo(): JlGraphic[] {
|
||||
this.app.addGraphics(...this.obj);
|
||||
return this.obj;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 删除图形操作
|
||||
*/
|
||||
export class GraphicDeleteOperation extends JlOperation {
|
||||
obj: JlGraphic[];
|
||||
|
||||
constructor(app: IGraphicApp, obj: JlGraphic[]) {
|
||||
super(app, 'graphic-delete');
|
||||
this.app = app;
|
||||
this.obj = obj;
|
||||
}
|
||||
|
||||
undo(): JlGraphic[] {
|
||||
this.app.addGraphics(...this.obj);
|
||||
return this.obj;
|
||||
}
|
||||
redo(): void {
|
||||
this.app.deleteGraphics(...this.obj);
|
||||
}
|
||||
}
|
||||
|
||||
export class GraphicDataUpdateOperation extends JlOperation {
|
||||
obj: JlGraphic[];
|
||||
oldData: GraphicData[];
|
||||
newData: GraphicData[];
|
||||
constructor(
|
||||
app: IGraphicApp,
|
||||
obj: JlGraphic[],
|
||||
oldData: GraphicData[],
|
||||
newData: GraphicData[]
|
||||
) {
|
||||
super(app, 'graphic-drag');
|
||||
this.obj = [...obj];
|
||||
this.oldData = oldData;
|
||||
this.newData = newData;
|
||||
}
|
||||
|
||||
undo(): void | JlGraphic[] {
|
||||
for (let i = 0; i < this.obj.length; i++) {
|
||||
const g = this.obj[i];
|
||||
// g.exitChildEdit();
|
||||
g.updateData(this.oldData[i]);
|
||||
}
|
||||
return this.obj;
|
||||
}
|
||||
redo(): void | JlGraphic[] {
|
||||
for (let i = 0; i < this.obj.length; i++) {
|
||||
const g = this.obj[i];
|
||||
// g.exitChildEdit();
|
||||
g.updateData(this.newData[i]);
|
||||
}
|
||||
return this.obj;
|
||||
}
|
||||
}
|
674
src/jl-graphic/app/JlDrawApp.ts
Normal file
674
src/jl-graphic/app/JlDrawApp.ts
Normal file
@ -0,0 +1,674 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
/* eslint-disable @typescript-eslint/no-empty-function */
|
||||
import {
|
||||
BitmapFont,
|
||||
BitmapText,
|
||||
Container,
|
||||
DisplayObject,
|
||||
FederatedMouseEvent,
|
||||
IPointData,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import { GraphicIdGenerator } from '../core/IdGenerator';
|
||||
import { GraphicData, GraphicTemplate, JlGraphic } from '../core/JlGraphic';
|
||||
import {
|
||||
AppDragEvent,
|
||||
AppInteractionPlugin,
|
||||
CombinationKey,
|
||||
GraphicTransformEvent,
|
||||
InteractionPlugin,
|
||||
KeyListener,
|
||||
ShiftData,
|
||||
} from '../plugins';
|
||||
import { CommonMouseTool } from '../plugins/CommonMousePlugin';
|
||||
import { MenuItemOptions } from '../ui/Menu';
|
||||
import {
|
||||
DOWN,
|
||||
DebouncedFunction,
|
||||
LEFT,
|
||||
RIGHT,
|
||||
UP,
|
||||
debounce,
|
||||
recursiveChildren,
|
||||
} from '../utils';
|
||||
import {
|
||||
GraphicDataUpdateOperation,
|
||||
UpdateCanvasOperation,
|
||||
} from './BasicOperation';
|
||||
import {
|
||||
GraphicApp,
|
||||
GraphicAppOptions,
|
||||
ICanvasProperties,
|
||||
IGraphicApp,
|
||||
IJlCanvas,
|
||||
} from './JlGraphicApp';
|
||||
|
||||
/**
|
||||
* 图形绘制助手
|
||||
*/
|
||||
export abstract class GraphicDrawAssistant<
|
||||
GT extends GraphicTemplate,
|
||||
GD extends GraphicData
|
||||
> extends AppInteractionPlugin {
|
||||
readonly __GraphicDrawAssistant = true;
|
||||
app: IDrawApp;
|
||||
type: string; // 图形对象类型
|
||||
description: string; // 描述
|
||||
icon: string; // 界面显示的图标
|
||||
container: Container = new Container();
|
||||
graphicTemplate: GT;
|
||||
|
||||
escListener: KeyListener = new KeyListener({
|
||||
value: 'Escape',
|
||||
onRelease: () => {
|
||||
this.onEsc();
|
||||
},
|
||||
});
|
||||
|
||||
onEsc() {
|
||||
this.createAndStore(true);
|
||||
}
|
||||
|
||||
constructor(
|
||||
graphicApp: IDrawApp,
|
||||
graphicTemplate: GT,
|
||||
icon: string,
|
||||
description: string
|
||||
) {
|
||||
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);
|
||||
}
|
||||
|
||||
public get canvas(): IJlCanvas {
|
||||
return this.app.canvas;
|
||||
}
|
||||
|
||||
bind(): void {
|
||||
this.app.drawing = true;
|
||||
const canvas = this.canvas;
|
||||
canvas.addChild(this.container);
|
||||
canvas.on('mousedown', this.onLeftDown, this);
|
||||
canvas.on('mousemove', this.onMouseMove, this);
|
||||
canvas.on('mouseup', this.onLeftUp, this);
|
||||
canvas.on('rightdown', this.onRightDown, this);
|
||||
canvas.on('rightup', this.onRightUp, this);
|
||||
canvas.on('_rightclick', this.onRightClick, this);
|
||||
|
||||
this.app.viewport.wheel({
|
||||
percent: 0.01,
|
||||
});
|
||||
this.app.addKeyboardListener(this.escListener);
|
||||
|
||||
this.app.viewport.drag({
|
||||
mouseButtons: 'right',
|
||||
});
|
||||
}
|
||||
unbind(): void {
|
||||
this.clearCache();
|
||||
const canvas = this.canvas;
|
||||
if (this.container?.parent) {
|
||||
canvas.removeChild(this.container);
|
||||
}
|
||||
canvas.off('mousedown', this.onLeftDown, this);
|
||||
canvas.off('mousemove', this.onMouseMove, this);
|
||||
canvas.off('mouseup', this.onLeftUp, this);
|
||||
canvas.off('rightdown', this.onRightDown, this);
|
||||
canvas.off('rightup', this.onRightUp, this);
|
||||
|
||||
this.app.viewport.plugins.remove('wheel');
|
||||
|
||||
this.app.removeKeyboardListener(this.escListener);
|
||||
|
||||
this.app.viewport.plugins.remove('drag');
|
||||
this.app.drawing = false;
|
||||
}
|
||||
|
||||
onLeftDown(e: FederatedMouseEvent) {}
|
||||
|
||||
onMouseMove(e: FederatedMouseEvent) {
|
||||
this.redraw(this.toCanvasCoordinates(e.global));
|
||||
}
|
||||
|
||||
onLeftUp(e: FederatedMouseEvent) {}
|
||||
onRightDown(e: FederatedMouseEvent) {}
|
||||
onRightUp(e: FederatedMouseEvent) {}
|
||||
onRightClick(e: FederatedMouseEvent) {
|
||||
this.finish();
|
||||
}
|
||||
/**
|
||||
* 获取下一个id
|
||||
*/
|
||||
nextId(): string {
|
||||
return GraphicIdGenerator.next();
|
||||
}
|
||||
|
||||
clearCache(): void {}
|
||||
|
||||
/**
|
||||
* 重绘
|
||||
* @param cp 鼠标所在画布坐标
|
||||
*/
|
||||
abstract redraw(cp: Point): void;
|
||||
|
||||
abstract prepareData(data: GD): boolean;
|
||||
|
||||
toCanvasCoordinates(p: Point): Point {
|
||||
return this.app.toCanvasCoordinates(p);
|
||||
}
|
||||
/**
|
||||
* 保存创建的图形对象
|
||||
*/
|
||||
storeGraphic(...graphics: JlGraphic[]): void {
|
||||
this.app.addGraphicAndRecord(...graphics);
|
||||
}
|
||||
/**
|
||||
* 创建并添加到图形App
|
||||
*/
|
||||
createAndStore(finish: boolean): JlGraphic | null {
|
||||
const data = this.graphicTemplate.datas as GD;
|
||||
data.id = this.nextId();
|
||||
data.graphicType = this.graphicTemplate.type;
|
||||
if (!this.prepareData(data)) {
|
||||
if (finish) {
|
||||
this.finish();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const template = this.graphicTemplate;
|
||||
const g = template.new();
|
||||
g.loadData(data);
|
||||
this.storeGraphic(g);
|
||||
if (finish) {
|
||||
this.finish(g);
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制完成
|
||||
*/
|
||||
finish(...graphics: JlGraphic[]): void {
|
||||
this.clearCache();
|
||||
this.app.interactionPlugin(CommonMouseTool.Name).resume();
|
||||
this.app.updateSelected(...graphics);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制助手类型
|
||||
*/
|
||||
export type DrawAssistant = GraphicDrawAssistant<GraphicTemplate, GraphicData>;
|
||||
|
||||
/**
|
||||
* 绘制配置选项
|
||||
*/
|
||||
export type DrawAppOptions = GraphicAppOptions;
|
||||
|
||||
/**
|
||||
* 绘制应用接口
|
||||
*/
|
||||
export interface IDrawApp extends IGraphicApp {
|
||||
/**
|
||||
* 是否正在绘制图形
|
||||
*/
|
||||
get drawing(): boolean;
|
||||
/**
|
||||
* 更新绘制中状态
|
||||
*/
|
||||
set drawing(value: boolean);
|
||||
/**
|
||||
* 设置配置选项
|
||||
* @param options
|
||||
*/
|
||||
setOptions(options: DrawAppOptions): void;
|
||||
/**
|
||||
* 获取绘制助手
|
||||
*/
|
||||
getDrawAssistant<DA extends DrawAssistant>(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 class JlDrawApp extends GraphicApp implements IDrawApp {
|
||||
font: BitmapFont = BitmapFont.from(
|
||||
'coordinates',
|
||||
{
|
||||
fontFamily: 'Roboto',
|
||||
fontSize: 16,
|
||||
fill: '#ff2700',
|
||||
},
|
||||
{ chars: ['画布坐标:() 屏幕坐标:() 缩放:.,', ['0', '9']] }
|
||||
);
|
||||
coordinates: BitmapText = new BitmapText('画布坐标: (0, 0) 屏幕坐标:(0, 0)', {
|
||||
fontName: 'coordinates',
|
||||
});
|
||||
scaleText: BitmapText = new BitmapText('缩放: 1', {
|
||||
fontName: 'coordinates',
|
||||
});
|
||||
|
||||
drawAssistants: DrawAssistant[] = [];
|
||||
_drawing = false;
|
||||
|
||||
private debouncedFormDataUpdator: DebouncedFunction<(g: JlGraphic) => void>;
|
||||
|
||||
get drawing(): boolean {
|
||||
return this._drawing;
|
||||
}
|
||||
set drawing(value: boolean) {
|
||||
this._drawing = value;
|
||||
}
|
||||
|
||||
constructor(options: DrawAppOptions) {
|
||||
super(options);
|
||||
|
||||
this.appendDrawStatesDisplay();
|
||||
|
||||
// 拖拽操作记录
|
||||
this.appOperationRecord();
|
||||
// 绑定通用键盘操作
|
||||
this.bindKeyboardOperation();
|
||||
this.formDataSyncListen();
|
||||
|
||||
this.debouncedFormDataUpdator = debounce(this.doFormDataUpdate, 60);
|
||||
}
|
||||
|
||||
setOptions(options: DrawAppOptions): void {
|
||||
super.setOptions(options);
|
||||
}
|
||||
|
||||
registerInteractionPlugin(...plugins: InteractionPlugin[]): void {
|
||||
plugins.forEach((plugin) => {
|
||||
if (plugin instanceof GraphicDrawAssistant) {
|
||||
this.drawAssistants.push(plugin);
|
||||
}
|
||||
super.registerInteractionPlugin(plugin);
|
||||
});
|
||||
}
|
||||
|
||||
getDrawAssistant<DA extends DrawAssistant>(graphicType: string): DA {
|
||||
const sda = this.drawAssistants
|
||||
.filter((da) => da.type === graphicType)
|
||||
.pop();
|
||||
if (!sda) {
|
||||
throw new Error(`未找到图形绘制助手: ${graphicType}`);
|
||||
}
|
||||
return sda as DA;
|
||||
}
|
||||
|
||||
private appOperationRecord() {
|
||||
let dragStartDatas: GraphicData[] = [];
|
||||
this.on('drag_op_start', (e: AppDragEvent) => {
|
||||
// 图形拖拽,记录初始数据
|
||||
if (!e.target.isCanvas()) {
|
||||
dragStartDatas = this.selectedGraphics.map((g) => g.saveData());
|
||||
}
|
||||
});
|
||||
// 图形拖拽操作监听
|
||||
this.on('drag_op_end', () => {
|
||||
// 图形拖拽,记录操作
|
||||
if (dragStartDatas.length > 0) {
|
||||
const newData = this.selectedGraphics.map((g) => g.saveData());
|
||||
this.opRecord.record(
|
||||
new GraphicDataUpdateOperation(
|
||||
this,
|
||||
this.selectedGraphics,
|
||||
dragStartDatas,
|
||||
newData
|
||||
)
|
||||
);
|
||||
dragStartDatas = [];
|
||||
}
|
||||
});
|
||||
// 菜单操作
|
||||
let preMenuHandleDatas: GraphicData[] = [];
|
||||
this.on('pre-menu-handle', (menu: MenuItemOptions) => {
|
||||
if (menu.name === '撤销' || menu.name === '重做') {
|
||||
return;
|
||||
}
|
||||
preMenuHandleDatas = this.selectedGraphics.map((g) => g.saveData());
|
||||
});
|
||||
this.on('post-menu-handle', () => {
|
||||
if (preMenuHandleDatas.length > 0) {
|
||||
const newData = this.selectedGraphics.map((g) => g.saveData());
|
||||
this.opRecord.record(
|
||||
new GraphicDataUpdateOperation(
|
||||
this,
|
||||
this.selectedGraphics,
|
||||
preMenuHandleDatas,
|
||||
newData
|
||||
)
|
||||
);
|
||||
preMenuHandleDatas = [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制状态信息显示
|
||||
*/
|
||||
private appendDrawStatesDisplay(): void {
|
||||
this.pixi.stage.addChild(this.coordinates);
|
||||
this.pixi.stage.addChild(this.scaleText);
|
||||
const bound = this.coordinates.getLocalBounds();
|
||||
this.scaleText.position.set(bound.width + 10, 0);
|
||||
this.canvas.on('mousemove', (e) => {
|
||||
if (e.target) {
|
||||
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', () => {
|
||||
this.scaleText.text = `缩放: ${this.viewport.scaled}`;
|
||||
});
|
||||
}
|
||||
|
||||
bindKeyboardOperation(): void {
|
||||
this.addKeyboardListener(
|
||||
// Ctrl + A
|
||||
new KeyListener({
|
||||
value: 'KeyA',
|
||||
combinations: [CombinationKey.Ctrl],
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
if (e.ctrlKey) {
|
||||
(app as JlDrawApp).selectAllGraphics();
|
||||
}
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
// 复制功能
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'KeyD',
|
||||
combinations: [CombinationKey.Shift],
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
this.graphicCopyPlugin.init();
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
// Ctrl + Z
|
||||
value: 'KeyZ',
|
||||
global: true,
|
||||
combinations: [CombinationKey.Ctrl],
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
app.opRecord.undo();
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
// Ctrl + Shift + Z
|
||||
value: 'KeyZ',
|
||||
global: true,
|
||||
combinations: [CombinationKey.Ctrl, CombinationKey.Shift],
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
app.opRecord.redo();
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'Delete',
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
app.deleteGraphicAndRecord(...app.selectedGraphics);
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'ArrowUp',
|
||||
pressTriggerAsOriginalEvent: true,
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
updateGraphicPositionOnKeyboardEvent(app, UP);
|
||||
},
|
||||
onRelease: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
recordGraphicMoveOperation(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'ArrowDown',
|
||||
pressTriggerAsOriginalEvent: true,
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
updateGraphicPositionOnKeyboardEvent(app, DOWN);
|
||||
},
|
||||
onRelease: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
recordGraphicMoveOperation(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'ArrowLeft',
|
||||
pressTriggerAsOriginalEvent: true,
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
updateGraphicPositionOnKeyboardEvent(app, LEFT);
|
||||
},
|
||||
onRelease: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
recordGraphicMoveOperation(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
this.addKeyboardListener(
|
||||
new KeyListener({
|
||||
value: 'ArrowRight',
|
||||
pressTriggerAsOriginalEvent: true,
|
||||
onPress: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
updateGraphicPositionOnKeyboardEvent(app, RIGHT);
|
||||
},
|
||||
onRelease: (e: KeyboardEvent, app: IGraphicApp) => {
|
||||
recordGraphicMoveOperation(app);
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形对象存储处理,默认添加图形交互
|
||||
* @param graphic
|
||||
*/
|
||||
beforeGraphicStore(graphic: JlGraphic): void {
|
||||
graphic.eventMode = 'static';
|
||||
graphic.selectable = true;
|
||||
graphic.draggable = true;
|
||||
graphic.on('repaint', () => {
|
||||
this.handleFormDataUpdate(graphic);
|
||||
});
|
||||
graphic.on('transformend', () => {
|
||||
this.handleFormDataUpdate(graphic);
|
||||
});
|
||||
}
|
||||
|
||||
formData: GraphicData | undefined = undefined;
|
||||
|
||||
/**
|
||||
* 绑定form表单对象
|
||||
* @param form
|
||||
*/
|
||||
bindFormData(form: GraphicData): void {
|
||||
this.formData = form;
|
||||
if (this.formData && this.selectedGraphics.length == 1) {
|
||||
if (this.formData.graphicType == this.selectedGraphics[0].type) {
|
||||
this.formData.copyFrom(this.selectedGraphics[0].saveData());
|
||||
} else {
|
||||
this.formData = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除form绑定
|
||||
* @param form
|
||||
*/
|
||||
unbindFormData(form: GraphicData): void {
|
||||
if (this.formData == form) {
|
||||
this.formData = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private formDataSyncListen(): void {
|
||||
this.on('graphicselected', () => {
|
||||
if (this.selectedGraphics.length == 1) {
|
||||
this.handleFormDataUpdate(this.selectedGraphics[0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理表单数据更新(使用debounce限流)
|
||||
*/
|
||||
private handleFormDataUpdate(g: JlGraphic): void {
|
||||
this.debouncedFormDataUpdator(this, g);
|
||||
}
|
||||
|
||||
private doFormDataUpdate(g: JlGraphic): void {
|
||||
if (this.selectedGraphics.length > 1) return;
|
||||
if (this.formData && g.type === this.formData.graphicType) {
|
||||
this.formData.copyFrom(g.saveData());
|
||||
}
|
||||
}
|
||||
|
||||
updateCanvasAndRecord(data: ICanvasProperties) {
|
||||
const old = this.canvas.properties.clone();
|
||||
this.canvas.update(data);
|
||||
const newVal = this.canvas.properties.clone();
|
||||
this.opRecord.record(
|
||||
new UpdateCanvasOperation(this, this.canvas, old, newVal)
|
||||
);
|
||||
}
|
||||
|
||||
updateGraphicAndRecord(g: JlGraphic, data: GraphicData) {
|
||||
const old = g.saveData();
|
||||
g.updateData(data);
|
||||
const newVal = g.saveData();
|
||||
this.opRecord.record(
|
||||
new GraphicDataUpdateOperation(this, [g], [old], [newVal])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let dragStartDatas: GraphicData[] = [];
|
||||
|
||||
function handleArrowKeyMoveGraphics(
|
||||
app: IGraphicApp,
|
||||
handler: (obj: DisplayObject) => void
|
||||
) {
|
||||
if (
|
||||
app.selectedGraphics.length === 1 &&
|
||||
app.selectedGraphics[0].hasSelectedChilds()
|
||||
) {
|
||||
recursiveChildren(app.selectedGraphics[0], (child) => {
|
||||
if (child.selected && child.draggable) {
|
||||
handler(child);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
app.selectedGraphics.forEach((g) => {
|
||||
handler(g);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function updateGraphicPositionOnKeyboardEvent(
|
||||
app: IGraphicApp,
|
||||
dp: IPointData
|
||||
) {
|
||||
let dragStart = false;
|
||||
if (dragStartDatas.length === 0) {
|
||||
dragStartDatas = app.selectedGraphics.map((g) => g.saveData());
|
||||
dragStart = true;
|
||||
}
|
||||
handleArrowKeyMoveGraphics(app, (g) => {
|
||||
if (dragStart) {
|
||||
g.shiftStartPoint = g.position.clone();
|
||||
g.emit(
|
||||
'transformstart',
|
||||
GraphicTransformEvent.shift(g, ShiftData.new(g.shiftStartPoint))
|
||||
);
|
||||
} else {
|
||||
g.shiftLastPoint = g.position.clone();
|
||||
}
|
||||
g.position.x += dp.x;
|
||||
g.position.y += dp.y;
|
||||
if (!dragStart) {
|
||||
if (g.shiftStartPoint && g.shiftLastPoint) {
|
||||
g.emit(
|
||||
'transforming',
|
||||
GraphicTransformEvent.shift(
|
||||
g,
|
||||
ShiftData.new(
|
||||
g.shiftStartPoint,
|
||||
g.position.clone(),
|
||||
g.shiftLastPoint
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function recordGraphicMoveOperation(app: IGraphicApp) {
|
||||
if (
|
||||
dragStartDatas.length > 0 &&
|
||||
dragStartDatas.length === app.selectedGraphics.length
|
||||
) {
|
||||
const newData = app.selectedGraphics.map((g) => g.saveData());
|
||||
app.opRecord.record(
|
||||
new GraphicDataUpdateOperation(
|
||||
app,
|
||||
app.selectedGraphics,
|
||||
dragStartDatas,
|
||||
newData
|
||||
)
|
||||
);
|
||||
|
||||
handleArrowKeyMoveGraphics(app, (g) => {
|
||||
if (g.shiftStartPoint) {
|
||||
g.emit(
|
||||
'transformend',
|
||||
GraphicTransformEvent.shift(
|
||||
g,
|
||||
ShiftData.new(g.shiftStartPoint, g.position.clone())
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
dragStartDatas = [];
|
||||
}
|
1356
src/jl-graphic/app/JlGraphicApp.ts
Normal file
1356
src/jl-graphic/app/JlGraphicApp.ts
Normal file
File diff suppressed because it is too large
Load Diff
47
src/jl-graphic/app/index.ts
Normal file
47
src/jl-graphic/app/index.ts
Normal file
@ -0,0 +1,47 @@
|
||||
import {
|
||||
DrawAppOptions,
|
||||
DrawAssistant,
|
||||
GraphicDrawAssistant,
|
||||
IDrawApp,
|
||||
JlDrawApp,
|
||||
} from './JlDrawApp';
|
||||
import {
|
||||
AppConsts,
|
||||
GraphicApp,
|
||||
GraphicAppOptions,
|
||||
ICanvasProperties,
|
||||
IGraphicApp,
|
||||
IGraphicScene,
|
||||
IGraphicStorage,
|
||||
IJlCanvas,
|
||||
} from './JlGraphicApp';
|
||||
import { GraphicDataUpdateOperation } from './BasicOperation';
|
||||
|
||||
/**
|
||||
* 实例化图形app
|
||||
* @param options
|
||||
* @returns
|
||||
*/
|
||||
export function newGraphicApp(options: GraphicAppOptions): IGraphicApp {
|
||||
return new GraphicApp(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 实例化绘图app
|
||||
* @param options
|
||||
* @returns
|
||||
*/
|
||||
export function newDrawApp(options: DrawAppOptions): IDrawApp {
|
||||
return new JlDrawApp(options);
|
||||
}
|
||||
|
||||
export { AppConsts, GraphicDrawAssistant, GraphicDataUpdateOperation };
|
||||
export type {
|
||||
DrawAssistant,
|
||||
ICanvasProperties,
|
||||
IDrawApp,
|
||||
IGraphicApp,
|
||||
IGraphicScene,
|
||||
IGraphicStorage,
|
||||
IJlCanvas,
|
||||
};
|
187
src/jl-graphic/core/GraphicRelation.ts
Normal file
187
src/jl-graphic/core/GraphicRelation.ts
Normal file
@ -0,0 +1,187 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { JlGraphic } from './JlGraphic';
|
||||
|
||||
/**
|
||||
* 图形关系数据
|
||||
*/
|
||||
export class GraphicRelationParam {
|
||||
g: JlGraphic;
|
||||
param: any;
|
||||
constructor(g: JlGraphic, param: any = null) {
|
||||
this.g = g;
|
||||
this.param = param;
|
||||
}
|
||||
isTheGraphic(g: JlGraphic): boolean {
|
||||
return this.g.id === g.id;
|
||||
}
|
||||
getGraphic<G extends JlGraphic>(): G {
|
||||
return this.g as G;
|
||||
}
|
||||
getParam<P>(): P {
|
||||
return this.param as P;
|
||||
}
|
||||
equals(other: GraphicRelationParam): boolean {
|
||||
return this.isTheGraphic(other.g) && this.param === other.param;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 图形关系
|
||||
*/
|
||||
export class GraphicRelation {
|
||||
rp1: GraphicRelationParam;
|
||||
rp2: GraphicRelationParam;
|
||||
constructor(rp1: GraphicRelationParam, rp2: GraphicRelationParam) {
|
||||
this.rp1 = rp1;
|
||||
this.rp2 = rp2;
|
||||
}
|
||||
|
||||
contains(g: JlGraphic): boolean {
|
||||
return this.rp1.isTheGraphic(g) || this.rp2.isTheGraphic(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取给定图形的关系参数
|
||||
* @param g
|
||||
* @returns
|
||||
*/
|
||||
getRelationParam(g: JlGraphic): GraphicRelationParam {
|
||||
if (!this.contains(g)) {
|
||||
throw new Error(
|
||||
`图形关系${this.rp1.g.id}-${this.rp2.g.id}中不包含给定图形${g.id}`
|
||||
);
|
||||
}
|
||||
if (this.rp1.isTheGraphic(g)) {
|
||||
return this.rp1;
|
||||
} else {
|
||||
return this.rp2;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取关联的另一个图形的关系参数
|
||||
* @param g
|
||||
* @returns
|
||||
*/
|
||||
getOtherRelationParam(g: JlGraphic): GraphicRelationParam {
|
||||
if (!this.contains(g)) {
|
||||
throw new Error(
|
||||
`图形关系${this.rp1.g.id}-${this.rp2.g.id}中不包含给定图形${g.id}`
|
||||
);
|
||||
}
|
||||
if (this.rp1.isTheGraphic(g)) {
|
||||
return this.rp2;
|
||||
} else {
|
||||
return this.rp1;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取关联的另一个图形对象
|
||||
* @param g
|
||||
* @returns graphic
|
||||
*/
|
||||
getOtherGraphic<G extends JlGraphic>(g: JlGraphic): G {
|
||||
return this.getOtherRelationParam(g).g as G;
|
||||
}
|
||||
|
||||
equals(orp1: GraphicRelationParam, orp2: GraphicRelationParam): boolean {
|
||||
if (this.rp1.isTheGraphic(orp1.g)) {
|
||||
return this.rp1.equals(orp1) && this.rp2.equals(orp2);
|
||||
} else if (this.rp1.isTheGraphic(orp2.g)) {
|
||||
return this.rp1.equals(orp2) && this.rp2.equals(orp1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
isEqualOther(other: GraphicRelation): boolean {
|
||||
return this.equals(other.rp1, other.rp2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形关系管理
|
||||
*/
|
||||
export class RelationManage {
|
||||
relations: GraphicRelation[] = [];
|
||||
|
||||
isContainsRelation(
|
||||
rp1: GraphicRelationParam,
|
||||
rp2: GraphicRelationParam
|
||||
): boolean {
|
||||
const relation = this.relations.find((relation) =>
|
||||
relation.equals(rp1, rp2)
|
||||
);
|
||||
return !!relation;
|
||||
}
|
||||
addRelation(
|
||||
rp1: GraphicRelationParam | JlGraphic,
|
||||
rp2: GraphicRelationParam | JlGraphic
|
||||
): void {
|
||||
if (!(rp1 instanceof GraphicRelationParam)) {
|
||||
rp1 = new GraphicRelationParam(rp1);
|
||||
}
|
||||
if (!(rp2 instanceof GraphicRelationParam)) {
|
||||
rp2 = new GraphicRelationParam(rp2);
|
||||
}
|
||||
if (!this.isContainsRelation(rp1, rp2)) {
|
||||
const relation = new GraphicRelation(rp1, rp2);
|
||||
this.relations.push(relation);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图形的所有关系
|
||||
* @param g
|
||||
* @returns
|
||||
*/
|
||||
getRelationsOfGraphic(g: JlGraphic): GraphicRelation[] {
|
||||
return this.relations.filter((rl) => rl.contains(g));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定图形的指定关系图形类型的所有关系
|
||||
* @param g 指定图形
|
||||
* @param type 关联图形的类型
|
||||
* @returns
|
||||
*/
|
||||
getRelationsOfGraphicAndOtherType(
|
||||
g: JlGraphic,
|
||||
type: string
|
||||
): GraphicRelation[] {
|
||||
return this.relations.filter(
|
||||
(rl) => rl.contains(g) && rl.getOtherGraphic(g).type === type
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除关系
|
||||
* @param relation
|
||||
*/
|
||||
private deleteRelation(relation: GraphicRelation): void {
|
||||
const index = this.relations.findIndex((rl) => rl.isEqualOther(relation));
|
||||
if (index >= 0) {
|
||||
this.relations.splice(index, 1);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 删除指定图形的所有关系
|
||||
* @param g
|
||||
*/
|
||||
deleteRelationOfGraphic(g: JlGraphic): void {
|
||||
const relations = this.getRelationsOfGraphic(g);
|
||||
relations.forEach((rl) => this.deleteRelation(rl));
|
||||
}
|
||||
/**
|
||||
* 删除指定图形的所有关系
|
||||
* @param g
|
||||
*/
|
||||
deleteRelationOfGraphicAndOtherType(g: JlGraphic, type: string): void {
|
||||
const relations = this.getRelationsOfGraphicAndOtherType(g, type);
|
||||
relations.forEach((rl) => this.deleteRelation(rl));
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空
|
||||
*/
|
||||
clear() {
|
||||
this.relations.splice(0, this.relations.length);
|
||||
}
|
||||
}
|
206
src/jl-graphic/core/GraphicStore.ts
Normal file
206
src/jl-graphic/core/GraphicStore.ts
Normal file
@ -0,0 +1,206 @@
|
||||
import { RelationManage } from './GraphicRelation';
|
||||
import { JlGraphic } from './JlGraphic';
|
||||
|
||||
export interface GraphicQueryStore {
|
||||
/**
|
||||
* 获取所有图形对象
|
||||
*/
|
||||
getAllGraphics(): JlGraphic[];
|
||||
/**
|
||||
* 根据id获取图形
|
||||
*/
|
||||
queryById<T extends JlGraphic>(id: string): T;
|
||||
/**
|
||||
* 根据id模糊查询图形
|
||||
* @param id
|
||||
*/
|
||||
queryByIdAmbiguous(id: string): JlGraphic[];
|
||||
|
||||
/**
|
||||
* 根据类型获取图形列表
|
||||
*/
|
||||
queryByType<T extends JlGraphic>(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<T extends JlGraphic>(
|
||||
code: string,
|
||||
type: string
|
||||
): T | undefined;
|
||||
/**
|
||||
* 根据code和类型模糊查询图形
|
||||
* @param code
|
||||
* @param type
|
||||
*/
|
||||
queryByCodeAndTypeAmbiguous<T extends JlGraphic>(
|
||||
code: string,
|
||||
type: string
|
||||
): T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形存储
|
||||
*/
|
||||
export class GraphicStore implements GraphicQueryStore {
|
||||
store: Map<string, JlGraphic>;
|
||||
relationManage: RelationManage;
|
||||
constructor() {
|
||||
this.store = new Map<string, JlGraphic>();
|
||||
this.relationManage = new RelationManage();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有图形对象
|
||||
*/
|
||||
getAllGraphics(): JlGraphic[] {
|
||||
return [...this.store.values()];
|
||||
}
|
||||
queryById<T extends JlGraphic>(id: string): T {
|
||||
const graphic = this.store.get(id) as T;
|
||||
if (!graphic) throw Error(`未找到id为 [${id}] 的图形.`);
|
||||
return this.store.get(id) as T;
|
||||
}
|
||||
queryByIdAmbiguous(id: string): JlGraphic[] {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.id.search(id) >= 0) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByType<T extends JlGraphic>(type: string): T[] {
|
||||
const list: T[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.type === type) {
|
||||
list.push(g as T);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByCode(code: string): JlGraphic[] | undefined {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.code === code) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByCodeAmbiguous(code: string): JlGraphic[] {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.code.search(code) >= 0) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByIdOrCode(s: string): JlGraphic[] {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.isIdOrCode(s)) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByIdOrCodeAndType(s: string, type: string): JlGraphic[] {
|
||||
const list: JlGraphic[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.isIdOrCode(s) && g.type === type) {
|
||||
list.push(g);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
queryByCodeAndType<T extends JlGraphic>(
|
||||
code: string,
|
||||
type: string
|
||||
): T | undefined {
|
||||
for (const item of this.store.values()) {
|
||||
if (item.code === code && item.type === type) {
|
||||
return item as T;
|
||||
}
|
||||
}
|
||||
}
|
||||
queryByCodeAndTypeAmbiguous<T extends JlGraphic>(
|
||||
code: string,
|
||||
type: string
|
||||
): T[] {
|
||||
const list: T[] = [];
|
||||
this.store.forEach((g) => {
|
||||
if (g.type === type && g.code.search(code) >= 0) {
|
||||
list.push(g as T);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 存储图形对象
|
||||
* @param graphics 要存储的图形
|
||||
*/
|
||||
storeGraphics(graphic: JlGraphic): boolean {
|
||||
if (!graphic.id || graphic.id.trim() === '') {
|
||||
throw new Error(`存储图形对象异常: id为空, ${graphic}`);
|
||||
}
|
||||
if (this.store.has(graphic.id)) {
|
||||
// 已经存在
|
||||
const exist = this.store.get(graphic.id);
|
||||
console.error(`已经存在id=${graphic.id}的设备${exist}`);
|
||||
return false;
|
||||
} else {
|
||||
this.store.set(graphic.id, graphic);
|
||||
graphic.queryStore = this;
|
||||
graphic.relationManage = this.relationManage;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 删除图形
|
||||
* @param graph 要删除的图形
|
||||
*/
|
||||
deleteGraphics(graphic: JlGraphic): JlGraphic | undefined {
|
||||
const id = graphic.id;
|
||||
const remove = this.store.get(id);
|
||||
if (remove) {
|
||||
this.store.delete(id);
|
||||
// 删除图形关系
|
||||
this.relationManage.deleteRelationOfGraphic(remove);
|
||||
}
|
||||
return remove;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空
|
||||
*/
|
||||
clear() {
|
||||
this.relationManage.clear();
|
||||
this.store.clear();
|
||||
}
|
||||
}
|
28
src/jl-graphic/core/IdGenerator.ts
Normal file
28
src/jl-graphic/core/IdGenerator.ts
Normal file
@ -0,0 +1,28 @@
|
||||
/**
|
||||
* ID生成器
|
||||
*/
|
||||
export class IdGenerator {
|
||||
serial = 0;
|
||||
type: string;
|
||||
|
||||
constructor(type: string) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
next(): string {
|
||||
++this.serial;
|
||||
// console.log(this.getType() + this.serial)
|
||||
return this.getType() + this.serial;
|
||||
}
|
||||
|
||||
getType(): string {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
initSerial(serial: number): void {
|
||||
// console.log(serial)
|
||||
this.serial = serial;
|
||||
}
|
||||
}
|
||||
|
||||
export const GraphicIdGenerator: IdGenerator = new IdGenerator('');
|
1029
src/jl-graphic/core/JlGraphic.ts
Normal file
1029
src/jl-graphic/core/JlGraphic.ts
Normal file
File diff suppressed because it is too large
Load Diff
4
src/jl-graphic/core/index.ts
Normal file
4
src/jl-graphic/core/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export * from './JlGraphic';
|
||||
export * from './IdGenerator';
|
||||
export * from './GraphicRelation';
|
||||
export * from './GraphicStore';
|
158
src/jl-graphic/global.d.ts
vendored
Normal file
158
src/jl-graphic/global.d.ts
vendored
Normal file
@ -0,0 +1,158 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
declare namespace GlobalMixins {
|
||||
type JlCanvasType = import('./app').IJlCanvas;
|
||||
type CanvasProperties = import('./app').ICanvasProperties;
|
||||
type GraphicApp = import('./app').IGraphicApp;
|
||||
type JlGraphicType = import('./core').JlGraphic;
|
||||
type GraphicData = import('./core').GraphicData;
|
||||
type GraphicState = import('./core').GraphicState;
|
||||
type GraphicTransform = import('./core').GraphicTransform;
|
||||
type GraphicTransformEvent = import('./plugins').GraphicTransformEvent;
|
||||
type BoundsGraphic = import('./plugins').BoundsGraphic;
|
||||
type IPointDataType = import('pixi.js').IPointData;
|
||||
type PointType = import('pixi.js').Point;
|
||||
type FederatedMouseEvent = import('pixi.js').FederatedMouseEvent;
|
||||
type DisplayObjectType = import('pixi.js').DisplayObject;
|
||||
type ContainerType = import('pixi.js').Container;
|
||||
interface DisplayObjectEvents {
|
||||
'enter-absorbable-area': [number | undefined, number | undefined];
|
||||
'out-absorbable-area': [number | undefined, number | undefined];
|
||||
dataupdate: [newVal: any, oldVal: any];
|
||||
stateupdate: [newVal: any, oldVal: any];
|
||||
repaint: [DisplayObjectType];
|
||||
transformstart: [e: GraphicTransformEvent];
|
||||
transforming: [e: GraphicTransformEvent];
|
||||
transformend: [e: GraphicTransformEvent];
|
||||
_rightclick: [e: FederatedMouseEvent];
|
||||
_leftclick: [e: FederatedMouseEvent];
|
||||
selected: [DisplayObjectType];
|
||||
unselected: [DisplayObjectType];
|
||||
childselected: [DisplayObjectType];
|
||||
childunselected: [DisplayObjectType];
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
||||
interface GraphicAppEvents {
|
||||
// propertiesupdate: [selectedData: GraphicData | CanvasProperties | null];
|
||||
}
|
||||
|
||||
interface DisplayObject {
|
||||
_selectable: boolean;
|
||||
_selected: boolean;
|
||||
selectable: boolean; //是否可选中
|
||||
selected: boolean; // 是否选中
|
||||
_childEdit: boolean; // 子元素编辑模式
|
||||
childEdit: boolean;
|
||||
_transformSave: boolean; // 变换是否保存
|
||||
transformSave: boolean; //
|
||||
_assistantAppendMap: Map<string, DisplayObjectType> | null; // 辅助附加图形map
|
||||
assistantAppendMap: Map<string, DisplayObjectType>;
|
||||
_draggable: boolean; // 是否可拖拽
|
||||
draggable: boolean;
|
||||
_shiftStartPoint: PointType | null; // 位移起始坐标
|
||||
shiftStartPoint: PointType | null;
|
||||
_shiftLastPoint: PointType | null; // 位移上一个事件时坐标
|
||||
shiftLastPoint: PointType | null;
|
||||
_scalable: boolean; // 是否可缩放
|
||||
scalable: boolean;
|
||||
_keepAspectRatio: boolean; // 缩放是否保持纵横比,默认保持
|
||||
keepAspectRatio: boolean;
|
||||
_rotatable: boolean; // 是否可旋转
|
||||
rotatable: boolean;
|
||||
worldAngle: number; // 世界角度,(-180, 180]
|
||||
/**
|
||||
* 获取所有父级元素叠加缩放
|
||||
*/
|
||||
getAllParentScaled(): PointType;
|
||||
/**
|
||||
* 获取位置在画布的坐标
|
||||
*/
|
||||
getPositionOnCanvas(): PointType;
|
||||
/**
|
||||
* 通过画布坐标更新位置
|
||||
* @param p 画布坐标
|
||||
*/
|
||||
updatePositionByCanvasPosition(p: IPointData): void;
|
||||
/**
|
||||
* 保存变换数据
|
||||
*/
|
||||
saveTransform(): GraphicTransform;
|
||||
/**
|
||||
* 加载变换
|
||||
* @param transform 变换数据
|
||||
*/
|
||||
loadTransform(transform: GraphicTransform): void;
|
||||
isChild(obj: DisplayObject): boolean; // 是否子元素
|
||||
isParent(obj: DisplayObject): boolean; // 是否父元素
|
||||
isAssistantAppend(): boolean; // 是否辅助附加图形
|
||||
addAssistantAppend<D extends DisplayObjectType>(...appends: D[]): void;
|
||||
removeAssistantAppend(...appends: DisplayObjectType[]): void;
|
||||
removeAssistantAppendByName(...names: string[]): void;
|
||||
removeAllAssistantAppend(): void;
|
||||
getAssistantAppend<D extends DisplayObjectType>(
|
||||
name: string
|
||||
): D | undefined; // 获取辅助附加图形对象
|
||||
isGraphic(): boolean; // 是否业务图形对象
|
||||
getGraphic<G extends JlGraphicType>(): G | null; // 获取所属的图形对象
|
||||
isGraphicChild(): boolean; // 是否图形子元素
|
||||
onAddToCanvas(): void; // 添加到画布处理
|
||||
onRemoveFromCanvas(): void; //从画布移除处理
|
||||
isInCanvas(): boolean; // 是否添加到画布中
|
||||
getCanvas(): JlCanvasType; // 获取所在画布
|
||||
isCanvas(): boolean; // 是否画布对象
|
||||
getViewport(): Viewport; // 获取视口
|
||||
getGraphicApp(): GraphicApp; // 获取图形app
|
||||
/**
|
||||
* 图形本地坐标转为画布坐标
|
||||
* @param p 图形本地坐标
|
||||
*/
|
||||
localToCanvasPoint(p: IPointData): PointType;
|
||||
/**
|
||||
* 批量转换图形本地坐标为画布坐标
|
||||
* @param points 图形本地坐标
|
||||
*/
|
||||
localToCanvasPoints(...points: IPointData[]): PointType[];
|
||||
/**
|
||||
* 画布坐标转为图形本地坐标
|
||||
* @param p 画布坐标
|
||||
*/
|
||||
canvasToLocalPoint(p: IPointData): PointType;
|
||||
/**
|
||||
* 批量转换画布坐标为图形本地坐标
|
||||
* @param points 画布坐标
|
||||
*/
|
||||
canvasToLocalPoints(...points: IPointData[]): PointType[];
|
||||
/**
|
||||
* 本地坐标转为屏幕坐标
|
||||
* @param p 本地坐标
|
||||
*/
|
||||
localToScreenPoint(p: IPointData): PointType;
|
||||
/**
|
||||
* 批量转换本地坐标为屏幕坐标
|
||||
* @param points 本地坐标
|
||||
*/
|
||||
localToScreenPoints(...points: IPointData[]): PointType[];
|
||||
/**
|
||||
* 屏幕坐标转为本地坐标
|
||||
* @param p 屏幕坐标
|
||||
*/
|
||||
screenToLocalPoint(p: IPointData): PointType;
|
||||
/**
|
||||
* 批量转换屏幕坐标为本地坐标
|
||||
* @param points 屏幕坐标
|
||||
*/
|
||||
screenToLocalPoints(...points: IPointData[]): PointType[]; // 批量
|
||||
|
||||
localBoundsToCanvasPoints(): PointType[]; // 本地包围框转为多边形点坐标
|
||||
}
|
||||
|
||||
interface Graphics {
|
||||
drawBezierCurve(
|
||||
p1: IPointData,
|
||||
p2: IPointData,
|
||||
cp1: IPointData,
|
||||
cp2: IPointData,
|
||||
segmentsCount: number
|
||||
): Graphics;
|
||||
}
|
||||
}
|
252
src/jl-graphic/graphic/AbsorbablePosition.ts
Normal file
252
src/jl-graphic/graphic/AbsorbablePosition.ts
Normal file
@ -0,0 +1,252 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import {
|
||||
Color,
|
||||
Container,
|
||||
DisplayObject,
|
||||
Graphics,
|
||||
IPointData,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import {
|
||||
calculateFootPointFromPointToLine,
|
||||
calculateIntersectionPointOfCircleAndPoint,
|
||||
distance,
|
||||
distance2,
|
||||
isLineContainOther,
|
||||
linePoint,
|
||||
} from '../utils';
|
||||
import { VectorGraphic, VectorGraphicUtil } 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 const AbsorbablePointParam = {
|
||||
lineWidth: 1,
|
||||
lineColor: '#000000',
|
||||
fillColor: '#E77E0E',
|
||||
radius: 5, // 半径
|
||||
};
|
||||
|
||||
const AbsorbablePointGraphic = new Graphics();
|
||||
// AbsorbablePointGraphic.lineStyle(
|
||||
// AbsorbablePointParam.lineWidth,
|
||||
// AbsorbablePointParam.lineColor
|
||||
// );
|
||||
AbsorbablePointGraphic.beginFill(AbsorbablePointParam.fillColor);
|
||||
AbsorbablePointGraphic.drawCircle(0, 0, AbsorbablePointParam.radius);
|
||||
AbsorbablePointGraphic.endFill();
|
||||
|
||||
/**
|
||||
* 可吸附点
|
||||
*/
|
||||
export default class AbsorbablePoint
|
||||
extends Graphics
|
||||
implements AbsorbablePosition, VectorGraphic
|
||||
{
|
||||
_point: Point;
|
||||
absorbRange: number;
|
||||
scaledListenerOn = false;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param point 画布坐标
|
||||
* @param absorbRange
|
||||
*/
|
||||
constructor(point: IPointData, absorbRange = 10) {
|
||||
super(AbsorbablePointGraphic.geometry);
|
||||
this._point = new Point(point.x, point.y);
|
||||
this.absorbRange = absorbRange;
|
||||
this.position.copyFrom(this._point);
|
||||
this.interactive;
|
||||
VectorGraphicUtil.handle(this);
|
||||
}
|
||||
compareTo(other: AbsorbablePosition): number {
|
||||
if (other instanceof AbsorbablePoint) {
|
||||
return this.absorbRange - other.absorbRange;
|
||||
}
|
||||
throw new Error('非可吸附点');
|
||||
}
|
||||
isOverlapping(other: AbsorbablePosition): boolean {
|
||||
if (other instanceof AbsorbablePoint) {
|
||||
return (
|
||||
this._point.equals(other._point) &&
|
||||
this.absorbRange === other.absorbRange
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
tryAbsorb(...objs: DisplayObject[]): void {
|
||||
for (let i = 0; i < objs.length; i++) {
|
||||
const obj = objs[i];
|
||||
const canvasPosition = obj.getPositionOnCanvas();
|
||||
if (
|
||||
distance(
|
||||
this._point.x,
|
||||
this._point.y,
|
||||
canvasPosition.x,
|
||||
canvasPosition.y
|
||||
) < this.absorbRange
|
||||
) {
|
||||
obj.updatePositionByCanvasPosition(this._point);
|
||||
}
|
||||
}
|
||||
}
|
||||
updateOnScaled() {
|
||||
const scaled = this.getAllParentScaled();
|
||||
const scale = Math.max(scaled.x, scaled.y);
|
||||
this.scale.set(1 / scale, 1 / scale);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 可吸附线
|
||||
*/
|
||||
export class AbsorbableLine extends Graphics implements AbsorbablePosition {
|
||||
p1: Point;
|
||||
p2: Point;
|
||||
absorbRange: number;
|
||||
_color = '#E77E0E';
|
||||
|
||||
/**
|
||||
*
|
||||
* @param p1 画布坐标
|
||||
* @param p2 画布坐标
|
||||
* @param absorbRange
|
||||
*/
|
||||
constructor(p1: IPointData, p2: IPointData, absorbRange = 20) {
|
||||
super();
|
||||
this.p1 = new Point(p1.x, p1.y);
|
||||
this.p2 = new Point(p2.x, p2.y);
|
||||
this.absorbRange = absorbRange;
|
||||
this.redraw();
|
||||
}
|
||||
isOverlapping(other: AbsorbablePosition): boolean {
|
||||
if (other instanceof AbsorbableLine) {
|
||||
const contain = isLineContainOther(
|
||||
{ p1: this.p1, p2: this.p2 },
|
||||
{ p1: other.p1, p2: other.p2 }
|
||||
);
|
||||
return contain;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
compareTo(other: AbsorbablePosition): number {
|
||||
if (other instanceof AbsorbableLine) {
|
||||
return distance2(this.p1, this.p2) - distance2(other.p1, other.p2);
|
||||
}
|
||||
throw new Error('非可吸附线');
|
||||
}
|
||||
redraw() {
|
||||
this.clear();
|
||||
this.lineStyle(1, new Color(this._color));
|
||||
this.moveTo(this.p1.x, this.p1.y);
|
||||
this.lineTo(this.p2.x, this.p2.y);
|
||||
}
|
||||
|
||||
tryAbsorb(...objs: DisplayObject[]): void {
|
||||
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)) {
|
||||
const fp = calculateFootPointFromPointToLine(
|
||||
this.p1,
|
||||
this.p2,
|
||||
canvasPosition
|
||||
);
|
||||
obj.updatePositionByCanvasPosition(fp);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 可吸附圆
|
||||
*/
|
||||
export class AbsorbableCircle extends Graphics implements AbsorbablePosition {
|
||||
absorbRange: number;
|
||||
p0: Point;
|
||||
radius: number;
|
||||
_color = '#E77E0E';
|
||||
|
||||
/**
|
||||
*
|
||||
* @param p 画布坐标
|
||||
* @param radius
|
||||
* @param absorbRange
|
||||
*/
|
||||
constructor(p: IPointData, radius: number, absorbRange = 10) {
|
||||
super();
|
||||
this.p0 = new Point(p.x, p.y);
|
||||
this.radius = radius;
|
||||
this.absorbRange = absorbRange;
|
||||
this.redraw();
|
||||
}
|
||||
isOverlapping(other: AbsorbablePosition): boolean {
|
||||
if (other instanceof AbsorbableCircle) {
|
||||
return this.p0.equals(other.p0) && this.radius === other.radius;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
compareTo(other: AbsorbablePosition): number {
|
||||
if (other instanceof AbsorbableCircle) {
|
||||
return this.absorbRange - other.absorbRange;
|
||||
}
|
||||
throw new Error('非可吸附圆');
|
||||
}
|
||||
|
||||
redraw() {
|
||||
this.clear();
|
||||
this.lineStyle(1, new Color(this._color));
|
||||
this.drawCircle(this.p0.x, this.p0.y, this.radius);
|
||||
}
|
||||
|
||||
tryAbsorb(...objs: DisplayObject[]): void {
|
||||
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
|
||||
) {
|
||||
// 吸附,计算直线与圆交点,更新对象坐标
|
||||
const p = calculateIntersectionPointOfCircleAndPoint(
|
||||
this.p0,
|
||||
this.radius,
|
||||
canvasPosition
|
||||
);
|
||||
obj.updatePositionByCanvasPosition(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
102
src/jl-graphic/graphic/DashedLine.ts
Normal file
102
src/jl-graphic/graphic/DashedLine.ts
Normal file
@ -0,0 +1,102 @@
|
||||
import { Container, Graphics, IPointData, Point } from 'pixi.js';
|
||||
import { angleToAxisx } from '../utils';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const DefaultDashedLineOptions: ICompleteDashedLineOptions = {
|
||||
length: 4,
|
||||
startSpace: 0,
|
||||
space: 4,
|
||||
lineWidth: 1,
|
||||
color: '#0000ff',
|
||||
};
|
||||
|
||||
export class DashedLine extends Container {
|
||||
p1: Point;
|
||||
p2: Point;
|
||||
_options: ICompleteDashedLineOptions;
|
||||
constructor(p1: IPointData, p2: IPointData, options?: IDashedLineOptions) {
|
||||
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();
|
||||
}
|
||||
|
||||
setOptions(options: IDashedLineOptions) {
|
||||
if (options.startSpace != undefined) {
|
||||
this._options.startSpace = options.startSpace;
|
||||
}
|
||||
if (options.length != undefined) {
|
||||
this._options.length = options.length;
|
||||
}
|
||||
if (options.space != undefined) {
|
||||
this._options.space = options.space;
|
||||
}
|
||||
if (options.lineWidth != undefined) {
|
||||
this._options.lineWidth = options.lineWidth;
|
||||
}
|
||||
if (options.color != undefined) {
|
||||
this._options.color = options.color;
|
||||
}
|
||||
this.redraw();
|
||||
}
|
||||
|
||||
redraw() {
|
||||
this.removeChildren();
|
||||
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) {
|
||||
let dashedLen = option.length;
|
||||
if (len + option.length > total) {
|
||||
dashedLen = total - len;
|
||||
}
|
||||
const line = new Graphics();
|
||||
line.lineStyle(option.lineWidth, option.color);
|
||||
line.moveTo(len, 0);
|
||||
line.lineTo(len + dashedLen, 0);
|
||||
this.addChild(line);
|
||||
len = len + dashedLen + option.space;
|
||||
}
|
||||
|
||||
this.pivot.set(0, option.lineWidth / 2);
|
||||
this.position.set(p1.x, p1.y);
|
||||
this.angle = angleToAxisx(p1, p2);
|
||||
}
|
||||
}
|
45
src/jl-graphic/graphic/DraggablePoint.ts
Normal file
45
src/jl-graphic/graphic/DraggablePoint.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import { Graphics, IPointData } from 'pixi.js';
|
||||
import { VectorGraphic, VectorGraphicUtil } from './VectorGraphic';
|
||||
|
||||
/**
|
||||
* 拖拽点参数
|
||||
*/
|
||||
export const DraggablePointParam = {
|
||||
lineWidth: 1,
|
||||
lineColor: 0x000000,
|
||||
fillColor: 0xffffff,
|
||||
radius: 5, // 半径
|
||||
};
|
||||
|
||||
const DraggablePointGraphic = new Graphics();
|
||||
DraggablePointGraphic.lineStyle(
|
||||
DraggablePointParam.lineWidth,
|
||||
DraggablePointParam.lineColor
|
||||
);
|
||||
DraggablePointGraphic.beginFill(DraggablePointParam.fillColor);
|
||||
DraggablePointGraphic.drawCircle(0, 0, DraggablePointParam.radius);
|
||||
DraggablePointGraphic.endFill();
|
||||
|
||||
/**
|
||||
* 拖拽点,用于更新图形属性
|
||||
*/
|
||||
export class DraggablePoint extends Graphics implements VectorGraphic {
|
||||
scaledListenerOn = false;
|
||||
/**
|
||||
*
|
||||
* @param point 画布坐标点
|
||||
*/
|
||||
constructor(point: IPointData) {
|
||||
super(DraggablePointGraphic.geometry);
|
||||
this.position.copyFrom(point);
|
||||
this.eventMode = 'static';
|
||||
this.draggable = true;
|
||||
this.cursor = 'crosshair';
|
||||
VectorGraphicUtil.handle(this);
|
||||
}
|
||||
updateOnScaled() {
|
||||
const scaled = this.getAllParentScaled();
|
||||
const scale = Math.max(scaled.x, scaled.y);
|
||||
this.scale.set(1 / scale, 1 / scale);
|
||||
}
|
||||
}
|
44
src/jl-graphic/graphic/VectorGraphic.ts
Normal file
44
src/jl-graphic/graphic/VectorGraphic.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { DisplayObject } from 'pixi.js';
|
||||
|
||||
export interface VectorGraphic extends DisplayObject {
|
||||
scaledListenerOn: boolean;
|
||||
updateOnScaled(): void;
|
||||
}
|
||||
|
||||
export class VectorGraphicUtil {
|
||||
static handle(obj: VectorGraphic): void {
|
||||
const vg = obj;
|
||||
const onScaleChange = function (obj: DisplayObject) {
|
||||
if (vg.isParent(obj)) {
|
||||
vg.updateOnScaled();
|
||||
}
|
||||
};
|
||||
const registerScaleChange = function registerScaleChange(
|
||||
obj: VectorGraphic
|
||||
): void {
|
||||
if (!obj.scaledListenerOn) {
|
||||
obj.scaledListenerOn = true;
|
||||
obj.getGraphicApp().on('viewport-scaled', onScaleChange);
|
||||
}
|
||||
};
|
||||
const unregisterScaleChange = function unregisterScaleChange(
|
||||
obj: VectorGraphic
|
||||
): void {
|
||||
obj.scaledListenerOn = false;
|
||||
obj.getGraphicApp().off('viewport-scaled', onScaleChange);
|
||||
};
|
||||
obj.onAddToCanvas = function onAddToCanvas() {
|
||||
obj.updateOnScaled();
|
||||
registerScaleChange(obj);
|
||||
};
|
||||
obj.onRemoveFromCanvas = function onRemoveFromCanvas() {
|
||||
unregisterScaleChange(obj);
|
||||
};
|
||||
|
||||
obj.on('added', (container) => {
|
||||
if (container.isInCanvas()) {
|
||||
obj.onAddToCanvas();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
37
src/jl-graphic/graphic/VectorText.ts
Normal file
37
src/jl-graphic/graphic/VectorText.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { ICanvas, ITextStyle, Text, TextStyle } from 'pixi.js';
|
||||
import { VectorGraphic, VectorGraphicUtil } from '.';
|
||||
|
||||
/**
|
||||
* 矢量文字.实现原理:在缩放发生变化时,更新fontSize
|
||||
*/
|
||||
export class VectorText extends Text implements VectorGraphic {
|
||||
vectorFontSize = 8;
|
||||
scaled = 1;
|
||||
scaledListenerOn = false;
|
||||
|
||||
constructor(
|
||||
text?: string | number,
|
||||
style?: Partial<ITextStyle> | TextStyle,
|
||||
canvas?: ICanvas
|
||||
) {
|
||||
super(text, style, canvas);
|
||||
VectorGraphicUtil.handle(this);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置矢量文字的字体大小
|
||||
*/
|
||||
setVectorFontSize(fontSize: number) {
|
||||
if (this.vectorFontSize !== fontSize) {
|
||||
this.vectorFontSize = fontSize;
|
||||
this.updateOnScaled();
|
||||
}
|
||||
}
|
||||
}
|
5
src/jl-graphic/graphic/index.ts
Normal file
5
src/jl-graphic/graphic/index.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export * from './VectorGraphic';
|
||||
export * from './VectorText';
|
||||
export * from './DraggablePoint';
|
||||
export * from './AbsorbablePosition';
|
||||
export * from './DashedLine';
|
7
src/jl-graphic/index.ts
Normal file
7
src/jl-graphic/index.ts
Normal file
@ -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';
|
26
src/jl-graphic/math/Constants.ts
Normal file
26
src/jl-graphic/math/Constants.ts
Normal file
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 浮点数相等判断误差值
|
||||
*/
|
||||
export const epsilon = 0.00001;
|
||||
|
||||
/**
|
||||
* 判断浮点数是不是0
|
||||
* @param v
|
||||
* @returns
|
||||
*/
|
||||
export function isZero(v: number) {
|
||||
if (Math.abs(v) < epsilon) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 两浮点数是否相等
|
||||
* @param f1
|
||||
* @param f2
|
||||
* @returns
|
||||
*/
|
||||
export function floatEquals(f1: number, f2: number): boolean {
|
||||
return isZero(f1 - f2);
|
||||
}
|
360
src/jl-graphic/math/Vector2.ts
Normal file
360
src/jl-graphic/math/Vector2.ts
Normal file
@ -0,0 +1,360 @@
|
||||
/* eslint-disable @typescript-eslint/no-this-alias */
|
||||
|
||||
import { epsilon } from './Constants';
|
||||
|
||||
export default class Vector2 {
|
||||
constructor(values?: [number, number]) {
|
||||
if (values !== undefined) {
|
||||
this.xy = values;
|
||||
}
|
||||
}
|
||||
|
||||
static from(p: { x: number; y: number }): Vector2 {
|
||||
return new Vector2([p.x, p.y]);
|
||||
}
|
||||
|
||||
private values = new Float32Array(2);
|
||||
|
||||
static readonly zero = new Vector2([0, 0]);
|
||||
static readonly one = new Vector2([1, 1]);
|
||||
|
||||
get x(): number {
|
||||
return this.values[0];
|
||||
}
|
||||
|
||||
set x(value: number) {
|
||||
this.values[0] = value;
|
||||
}
|
||||
get y(): number {
|
||||
return this.values[1];
|
||||
}
|
||||
set y(value: number) {
|
||||
this.values[1] = value;
|
||||
}
|
||||
|
||||
get xy(): [number, number] {
|
||||
return [this.values[0], this.values[1]];
|
||||
}
|
||||
|
||||
set xy(values: [number, number]) {
|
||||
this.values[0] = values[0];
|
||||
this.values[1] = values[1];
|
||||
}
|
||||
|
||||
at(index: number): number {
|
||||
return this.values[index];
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.x = 0;
|
||||
this.y = 0;
|
||||
}
|
||||
|
||||
copy(dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = this.x;
|
||||
dest.y = this.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
negate(dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = this;
|
||||
}
|
||||
|
||||
dest.x = -this.x;
|
||||
dest.y = -this.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
equals(vector: Vector2, threshold = epsilon): boolean {
|
||||
if (Math.abs(this.x - vector.x) > threshold) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Math.abs(this.y - vector.y) > threshold) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
length(): number {
|
||||
return Math.sqrt(this.squaredLength());
|
||||
}
|
||||
|
||||
squaredLength(): number {
|
||||
const x = this.x;
|
||||
const y = this.y;
|
||||
|
||||
return x * x + y * y;
|
||||
}
|
||||
|
||||
add(vector: Vector2): Vector2 {
|
||||
this.x += vector.x;
|
||||
this.y += vector.y;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
subtract(vector: Vector2): Vector2 {
|
||||
this.x -= vector.x;
|
||||
this.y -= vector.y;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
multiply(vector: Vector2): Vector2 {
|
||||
this.x *= vector.x;
|
||||
this.y *= vector.y;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
divide(vector: Vector2): Vector2 {
|
||||
this.x /= vector.x;
|
||||
this.y /= vector.y;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
scale(value: number, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = this;
|
||||
}
|
||||
|
||||
dest.x *= value;
|
||||
dest.y *= value;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
normalize(dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = this;
|
||||
}
|
||||
|
||||
let length = this.length();
|
||||
|
||||
if (length === 1) {
|
||||
return this;
|
||||
}
|
||||
|
||||
if (length === 0) {
|
||||
dest.x = 0;
|
||||
dest.y = 0;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
length = 1.0 / length;
|
||||
|
||||
dest.x *= length;
|
||||
dest.y *= length;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
// multiplyMat2(matrix: mat2, dest?: Vector2): Vector2 {
|
||||
// if (!dest) {
|
||||
// dest = this;
|
||||
// }
|
||||
|
||||
// return matrix.multiplyVec2(this, dest);
|
||||
// }
|
||||
|
||||
// multiplyMat3(matrix: mat3, dest?: Vector2): Vector2 {
|
||||
// if (!dest) {
|
||||
// dest = this;
|
||||
// }
|
||||
|
||||
// return matrix.multiplyVec2(this, dest);
|
||||
// }
|
||||
|
||||
// static cross(vector: Vector2, vector2: Vector2, dest?: vec3): vec3 {
|
||||
// if (!dest) {
|
||||
// dest = new vec3();
|
||||
// }
|
||||
|
||||
// const x = vector.x;
|
||||
// const y = vector.y;
|
||||
|
||||
// const x2 = vector2.x;
|
||||
// const y2 = vector2.y;
|
||||
|
||||
// const z = x * y2 - y * x2;
|
||||
|
||||
// dest.x = 0;
|
||||
// dest.y = 0;
|
||||
// dest.z = z;
|
||||
|
||||
// return dest;
|
||||
// }
|
||||
|
||||
/**
|
||||
* 向量点乘
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @returns
|
||||
*/
|
||||
static dot(vector: Vector2, vector2: Vector2): number {
|
||||
return vector.x * vector2.x + vector.y * vector2.y;
|
||||
}
|
||||
/**
|
||||
* 向量长度
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @returns
|
||||
*/
|
||||
static distance(vector: Vector2, vector2: Vector2): number {
|
||||
return Math.sqrt(this.squaredDistance(vector, vector2));
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量长度平方
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @returns
|
||||
*/
|
||||
static squaredDistance(vector: Vector2, vector2: Vector2): number {
|
||||
const x = vector2.x - vector.x;
|
||||
const y = vector2.y - vector.y;
|
||||
|
||||
return x * x + y * y;
|
||||
}
|
||||
|
||||
/**
|
||||
* v2->v1的方向的单位向量
|
||||
* @param v1
|
||||
* @param v2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static direction(v1: Vector2, v2: Vector2, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
length = 1 / length;
|
||||
|
||||
dest.x = x * length;
|
||||
dest.y = y * length;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
static mix(
|
||||
vector: Vector2,
|
||||
vector2: Vector2,
|
||||
time: number,
|
||||
dest?: Vector2
|
||||
): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
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
|
||||
* @param vector2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static sum(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = vector.x + vector2.x;
|
||||
dest.y = vector.y + vector2.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量减法
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static difference(
|
||||
vector: Vector2,
|
||||
vector2: Vector2,
|
||||
dest?: Vector2
|
||||
): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = vector.x - vector2.x;
|
||||
dest.y = vector.y - vector2.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量乘法
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static product(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = vector.x * vector2.x;
|
||||
dest.y = vector.y * vector2.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向量除法
|
||||
* @param vector
|
||||
* @param vector2
|
||||
* @param dest
|
||||
* @returns
|
||||
*/
|
||||
static quotient(vector: Vector2, vector2: Vector2, dest?: Vector2): Vector2 {
|
||||
if (!dest) {
|
||||
dest = new Vector2();
|
||||
}
|
||||
|
||||
dest.x = vector.x / vector2.x;
|
||||
dest.y = vector.y / vector2.y;
|
||||
|
||||
return dest;
|
||||
}
|
||||
}
|
4
src/jl-graphic/math/index.ts
Normal file
4
src/jl-graphic/math/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
/// 向量和矩阵代码源自开源代码:https://github.com/matthiasferch/tsm
|
||||
|
||||
export * from './Constants';
|
||||
export * from './Vector2';
|
156
src/jl-graphic/message/BasicMessageClient.ts
Normal file
156
src/jl-graphic/message/BasicMessageClient.ts
Normal file
@ -0,0 +1,156 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { IGraphicScene } from '../app';
|
||||
import { CompleteMessageCliOption, IMessageClient } from './MessageBroker';
|
||||
|
||||
export interface MessageClientEvents {
|
||||
connected: [ctx: any];
|
||||
disconnected: [ctx: any];
|
||||
}
|
||||
|
||||
export type HandleMessage = (data: any) => void;
|
||||
|
||||
export interface IMessageHandler {
|
||||
/**
|
||||
* id
|
||||
*/
|
||||
get App(): IGraphicScene;
|
||||
/**
|
||||
* 处理消息数据
|
||||
* @param data
|
||||
*/
|
||||
handle(data: any): void;
|
||||
}
|
||||
|
||||
export abstract class MessageClient
|
||||
extends EventEmitter<MessageClientEvents>
|
||||
implements IMessageClient
|
||||
{
|
||||
options: CompleteMessageCliOption;
|
||||
subClients: SubscriptionClient[] = []; // 订阅客户端
|
||||
constructor(options: CompleteMessageCliOption) {
|
||||
super();
|
||||
this.options = options;
|
||||
}
|
||||
/**
|
||||
* 订阅消息
|
||||
* @param destination
|
||||
* @param handle
|
||||
*/
|
||||
abstract subscribe(
|
||||
destination: string,
|
||||
handle: HandleMessage
|
||||
): IUnsubscriptor;
|
||||
|
||||
unsubscribe(destination: string): void {
|
||||
this.unsubscribe0(destination);
|
||||
const idx = this.subClients.findIndex(
|
||||
(cli) => cli.destination === destination
|
||||
);
|
||||
if (idx >= 0) {
|
||||
this.subClients.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
abstract unsubscribe0(destination: string): void;
|
||||
|
||||
getOrNewSubClient(destination: string): SubscriptionClient {
|
||||
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;
|
||||
}
|
||||
|
||||
addSubscription(destination: string, handler: IMessageHandler): void {
|
||||
const cli = this.getOrNewSubClient(destination);
|
||||
cli.addHandler(handler);
|
||||
}
|
||||
removeSubscription(destination: string, handle: IMessageHandler): void {
|
||||
this.getOrNewSubClient(destination).removeHandler(handle);
|
||||
}
|
||||
|
||||
abstract get connected(): boolean;
|
||||
|
||||
abstract close(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅取消接口
|
||||
*/
|
||||
export interface IUnsubscriptor {
|
||||
/**
|
||||
* 取消订阅
|
||||
*/
|
||||
unsubscribe(): void;
|
||||
}
|
||||
|
||||
export class SubscriptionClient {
|
||||
mc: MessageClient;
|
||||
destination: string;
|
||||
protocol: 'json' | 'protobuf';
|
||||
handlers: IMessageHandler[] = [];
|
||||
unsubscriptor?: IUnsubscriptor;
|
||||
constructor(
|
||||
mc: MessageClient,
|
||||
destination: string,
|
||||
protocal: 'json' | 'protobuf'
|
||||
) {
|
||||
this.mc = mc;
|
||||
this.destination = destination;
|
||||
this.protocol = protocal;
|
||||
this.mc.on('disconnected', this.onDisconnect, this);
|
||||
this.mc.on('connected', this.trySubscribe, this);
|
||||
}
|
||||
|
||||
addHandler(handler: IMessageHandler) {
|
||||
if (this.handlers.filter((h) => h.App === handler.App).length == 0) {
|
||||
this.handlers.push(handler);
|
||||
}
|
||||
if (!this.unsubscriptor) {
|
||||
this.trySubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
removeHandler(handler: IMessageHandler) {
|
||||
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(`订阅${this.destination}没有消息监听处理,移除订阅`);
|
||||
this.unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
trySubscribe(): void {
|
||||
if (this.mc.connected) {
|
||||
this.unsubscriptor = this.mc.subscribe(this.destination, (data) => {
|
||||
this.handleMessage(data);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
unsubscribe(): void {
|
||||
this.mc.unsubscribe(this.destination);
|
||||
}
|
||||
|
||||
handleMessage(data: any) {
|
||||
if (this.protocol === 'json') {
|
||||
console.debug('收到消息:', data);
|
||||
}
|
||||
this.handlers.forEach((handler) => {
|
||||
try {
|
||||
handler.handle(data);
|
||||
} catch (error) {
|
||||
console.error('图形应用状态消息处理异常', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onDisconnect() {
|
||||
this.unsubscriptor = undefined;
|
||||
}
|
||||
}
|
70
src/jl-graphic/message/CentrifugeBroker.ts
Normal file
70
src/jl-graphic/message/CentrifugeBroker.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import { State, Subscription } from 'centrifuge';
|
||||
import Centrifuge from 'centrifuge/build/protobuf';
|
||||
import {
|
||||
HandleMessage,
|
||||
IUnsubscriptor,
|
||||
MessageClient,
|
||||
} from './BasicMessageClient';
|
||||
import { CompleteMessageCliOption } from './MessageBroker';
|
||||
|
||||
export class CentrifugeMessagingClient extends MessageClient {
|
||||
cli: Centrifuge;
|
||||
|
||||
constructor(options: CompleteMessageCliOption) {
|
||||
super(options);
|
||||
this.options = options;
|
||||
if (this.options.protocol === 'json') {
|
||||
this.cli = new Centrifuge(options.wsUrl, {
|
||||
token: options.token,
|
||||
protocol: options.protocol,
|
||||
});
|
||||
} else {
|
||||
this.cli = new Centrifuge(options.wsUrl, {
|
||||
token: options.token,
|
||||
protocol: options.protocol,
|
||||
});
|
||||
}
|
||||
|
||||
this.cli
|
||||
.on('connecting', (ctx) => {
|
||||
console.debug(`centrifuge连接中: ${ctx}, ${ctx.reason}`);
|
||||
})
|
||||
.on('connected', (ctx) => {
|
||||
console.debug(`连接成功: ${ctx.transport}`);
|
||||
this.emit('connected', ctx);
|
||||
})
|
||||
.on('disconnected', (ctx) => {
|
||||
console.log(`断开连接: ${ctx.code}, ${ctx.reason}`);
|
||||
this.emit('disconnected', ctx);
|
||||
})
|
||||
.on('error', (ctx) => {
|
||||
console.error('centrifuge错误', ctx);
|
||||
})
|
||||
.connect();
|
||||
}
|
||||
|
||||
get connected(): boolean {
|
||||
return this.cli.state === State.Connected;
|
||||
}
|
||||
|
||||
subscribe(destination: string, handle: HandleMessage): IUnsubscriptor {
|
||||
let sub = this.cli.getSubscription(destination);
|
||||
if (!sub) {
|
||||
sub = this.cli.newSubscription(destination);
|
||||
sub.on('publication', (ctx) => {
|
||||
handle(ctx.data);
|
||||
});
|
||||
}
|
||||
sub.subscribe();
|
||||
return sub;
|
||||
}
|
||||
|
||||
unsubscribe0(destination: string): void {
|
||||
const subClient = this.getOrNewSubClient(destination);
|
||||
this.cli.removeSubscription(subClient.unsubscriptor as Subscription);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.cli.disconnect();
|
||||
}
|
||||
}
|
267
src/jl-graphic/message/MessageBroker.ts
Normal file
267
src/jl-graphic/message/MessageBroker.ts
Normal file
@ -0,0 +1,267 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { IGraphicScene } from '../app';
|
||||
import { GraphicQueryStore, GraphicState, JlGraphic } from '../core';
|
||||
import {
|
||||
IMessageHandler,
|
||||
IUnsubscriptor,
|
||||
MessageClientEvents,
|
||||
} from './BasicMessageClient';
|
||||
import { CentrifugeMessagingClient } from './CentrifugeBroker';
|
||||
import { StompMessagingClient } from './WsMsgBroker';
|
||||
|
||||
export enum ClientEngine {
|
||||
Stomp,
|
||||
Centrifugo,
|
||||
}
|
||||
|
||||
export interface MessageCliOption {
|
||||
/**
|
||||
* 客户端引擎
|
||||
*/
|
||||
engine?: ClientEngine;
|
||||
/**
|
||||
* 消息协议,默认protobuf
|
||||
*/
|
||||
protocol?: 'json' | 'protobuf';
|
||||
/**
|
||||
* websocket url地址
|
||||
*/
|
||||
wsUrl: string;
|
||||
/**
|
||||
* 认证token
|
||||
*/
|
||||
token?: string;
|
||||
}
|
||||
|
||||
export interface CompleteMessageCliOption extends MessageCliOption {
|
||||
protocol: 'json' | 'protobuf';
|
||||
}
|
||||
|
||||
const DefaultStompOption: CompleteMessageCliOption = {
|
||||
engine: ClientEngine.Stomp,
|
||||
protocol: 'protobuf',
|
||||
wsUrl: '',
|
||||
token: '',
|
||||
};
|
||||
|
||||
export interface IMessageClient extends EventEmitter<MessageClientEvents> {
|
||||
/**
|
||||
* 添加订阅
|
||||
* @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 class WsMsgCli {
|
||||
private static client: IMessageClient;
|
||||
private static options: CompleteMessageCliOption;
|
||||
private static appMsgBroker: AppWsMsgBroker[] = [];
|
||||
static new(options: MessageCliOption) {
|
||||
if (WsMsgCli.client) {
|
||||
// 已经创建
|
||||
return;
|
||||
}
|
||||
WsMsgCli.options = Object.assign({}, DefaultStompOption, options);
|
||||
if (WsMsgCli.options.engine == ClientEngine.Centrifugo) {
|
||||
WsMsgCli.client = new CentrifugeMessagingClient(WsMsgCli.options);
|
||||
} else {
|
||||
WsMsgCli.client = new StompMessagingClient(WsMsgCli.options);
|
||||
}
|
||||
const cli = WsMsgCli.client;
|
||||
cli.on('connected', () => {
|
||||
WsMsgCli.emitConnectStateChangeEvent(true);
|
||||
});
|
||||
cli.on('disconnected', () => {
|
||||
WsMsgCli.emitConnectStateChangeEvent(false);
|
||||
});
|
||||
}
|
||||
|
||||
static isInitiated(): boolean {
|
||||
return !!WsMsgCli.client;
|
||||
}
|
||||
|
||||
static emitConnectStateChangeEvent(connected: boolean) {
|
||||
WsMsgCli.appMsgBroker.forEach((broker) => {
|
||||
broker.app.emit('websocket-connect-state-change', connected);
|
||||
});
|
||||
}
|
||||
|
||||
static isConnected(): boolean {
|
||||
return WsMsgCli.client && WsMsgCli.client.connected;
|
||||
}
|
||||
|
||||
static registerSubscription(destination: string, handler: IMessageHandler) {
|
||||
WsMsgCli.client.addSubscription(destination, handler);
|
||||
}
|
||||
|
||||
static unregisterSubscription(destination: string, handler: IMessageHandler) {
|
||||
WsMsgCli.client.removeSubscription(destination, handler);
|
||||
}
|
||||
|
||||
static registerAppMsgBroker(broker: AppWsMsgBroker) {
|
||||
WsMsgCli.appMsgBroker.push(broker);
|
||||
}
|
||||
|
||||
static removeAppMsgBroker(broker: AppWsMsgBroker) {
|
||||
const index = WsMsgCli.appMsgBroker.findIndex((mb) => mb == broker);
|
||||
if (index >= 0) {
|
||||
WsMsgCli.appMsgBroker.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static hasAppMsgBroker(): boolean {
|
||||
return WsMsgCli.appMsgBroker.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭websocket连接
|
||||
*/
|
||||
static close() {
|
||||
if (WsMsgCli.client) {
|
||||
WsMsgCli.client.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 状态订阅消息转换器
|
||||
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[];
|
||||
}
|
||||
|
||||
// 图形app状态订阅
|
||||
export interface AppStateSubscription {
|
||||
/**
|
||||
* 订阅路径
|
||||
*/
|
||||
destination: string;
|
||||
/**
|
||||
* 图形状态消息转换
|
||||
*/
|
||||
messageConverter?: GraphicStateMessageConvert;
|
||||
/**
|
||||
* 根据状态查询图形对象,默认为根据code和type查询图形对象
|
||||
*/
|
||||
graphicQueryer?: GraphicQuery;
|
||||
/**
|
||||
* 当未根据状态找到图形对象时是否创建新对象
|
||||
* 值为设备类型列表
|
||||
*/
|
||||
createOnNotFound?: ICreateOnNotFound;
|
||||
/**
|
||||
* 订阅消息处理
|
||||
*/
|
||||
messageHandle?: SubscriptionMessageHandle;
|
||||
/**
|
||||
* 订阅成功对象,用于取消订阅
|
||||
* 非客户端使用
|
||||
*/
|
||||
subscription?: IUnsubscriptor;
|
||||
}
|
||||
|
||||
class AppMessageHandler implements IMessageHandler {
|
||||
app: IGraphicScene;
|
||||
sub: AppStateSubscription;
|
||||
constructor(app: IGraphicScene, subOptions: AppStateSubscription) {
|
||||
this.app = app;
|
||||
if (!subOptions.messageConverter && !subOptions.messageHandle) {
|
||||
throw new Error(`没有消息处理器或图形状态消息转换器: ${subOptions}`);
|
||||
}
|
||||
this.sub = subOptions;
|
||||
}
|
||||
get App(): IGraphicScene {
|
||||
return this.app;
|
||||
}
|
||||
handle(data: any): void {
|
||||
const sub = this.sub;
|
||||
if (sub.messageConverter) {
|
||||
const graphicStates = sub.messageConverter(data);
|
||||
this.app.handleGraphicStates(
|
||||
graphicStates,
|
||||
sub.graphicQueryer,
|
||||
sub.createOnNotFound
|
||||
);
|
||||
} else if (sub.messageHandle) {
|
||||
sub.messageHandle(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形APP的websocket消息代理
|
||||
*/
|
||||
export class AppWsMsgBroker {
|
||||
app: IGraphicScene;
|
||||
subscriptions: Map<string, AppMessageHandler> = new Map<
|
||||
string,
|
||||
AppMessageHandler
|
||||
>();
|
||||
|
||||
constructor(app: IGraphicScene) {
|
||||
this.app = app;
|
||||
WsMsgCli.registerAppMsgBroker(this);
|
||||
}
|
||||
|
||||
subscribe(sub: AppStateSubscription) {
|
||||
const handler = new AppMessageHandler(this.app, sub);
|
||||
WsMsgCli.registerSubscription(sub.destination, handler);
|
||||
this.subscriptions.set(sub.destination, handler);
|
||||
}
|
||||
|
||||
unsbuscribe(destination: string) {
|
||||
const oldSub = this.subscriptions.get(destination);
|
||||
if (oldSub) {
|
||||
WsMsgCli.unregisterSubscription(destination, oldSub);
|
||||
}
|
||||
}
|
||||
|
||||
unsubscribeAll() {
|
||||
this.subscriptions.forEach((record, destination) => {
|
||||
this.unsbuscribe(destination);
|
||||
});
|
||||
}
|
||||
|
||||
resubscribeAll() {
|
||||
this.subscriptions.forEach((handler, destination) => {
|
||||
WsMsgCli.registerSubscription(destination, handler);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消所有订阅,从通用Stomp客户端移除此消息代理
|
||||
*/
|
||||
close() {
|
||||
WsMsgCli.removeAppMsgBroker(this);
|
||||
this.unsubscribeAll();
|
||||
}
|
||||
}
|
86
src/jl-graphic/message/WsMsgBroker.ts
Normal file
86
src/jl-graphic/message/WsMsgBroker.ts
Normal file
@ -0,0 +1,86 @@
|
||||
import { Client as StompClient, type Frame } from '@stomp/stompjs';
|
||||
import {
|
||||
HandleMessage,
|
||||
IUnsubscriptor,
|
||||
MessageClient,
|
||||
} from './BasicMessageClient';
|
||||
import { CompleteMessageCliOption } from './MessageBroker';
|
||||
|
||||
const ReconnectDelay = 3000;
|
||||
const HeartbeatIncoming = 30000;
|
||||
const HeartbeatOutgoing = 30000;
|
||||
|
||||
export class StompMessagingClient extends MessageClient {
|
||||
cli: StompClient;
|
||||
|
||||
constructor(options: CompleteMessageCliOption) {
|
||||
super(options);
|
||||
this.options = options;
|
||||
this.cli = new StompClient({
|
||||
brokerURL: options.wsUrl,
|
||||
connectHeaders: {
|
||||
Authorization: options.token ? options.token : '',
|
||||
},
|
||||
reconnectDelay: ReconnectDelay,
|
||||
heartbeatIncoming: HeartbeatIncoming,
|
||||
heartbeatOutgoing: HeartbeatOutgoing,
|
||||
});
|
||||
|
||||
this.cli.onConnect = () => {
|
||||
// this.subClients.forEach((cli) => {
|
||||
// this.subscribe(cli.destination, cli.handleMessage);
|
||||
// });
|
||||
this.emit('connected', '');
|
||||
};
|
||||
this.cli.onStompError = (frame: Frame) => {
|
||||
const errMsg = frame.headers['message'];
|
||||
if (errMsg === '401') {
|
||||
console.warn('认证失败,断开WebSocket连接');
|
||||
this.cli.deactivate();
|
||||
} else {
|
||||
console.error('收到Stomp错误消息', frame);
|
||||
}
|
||||
};
|
||||
|
||||
this.cli.onDisconnect = (frame: Frame) => {
|
||||
console.log('Stomp 断开连接', frame);
|
||||
this.emit('disconnected', frame);
|
||||
};
|
||||
// websocket错误处理
|
||||
this.cli.onWebSocketError = (err: Event) => {
|
||||
console.error('websocket错误', err);
|
||||
};
|
||||
|
||||
this.cli.activate();
|
||||
}
|
||||
|
||||
get connected(): boolean {
|
||||
return this.cli.connected;
|
||||
}
|
||||
|
||||
subscribe(destination: string, handle: HandleMessage): IUnsubscriptor {
|
||||
const sub = this.cli.subscribe(
|
||||
destination,
|
||||
(frame) => {
|
||||
if (this.options.protocol === 'json') {
|
||||
const data = JSON.parse(frame.body);
|
||||
handle(data);
|
||||
} else {
|
||||
handle(frame.binaryBody);
|
||||
}
|
||||
},
|
||||
{
|
||||
id: destination,
|
||||
}
|
||||
);
|
||||
return sub;
|
||||
}
|
||||
|
||||
unsubscribe0(destination: string): void {
|
||||
this.cli.unsubscribe(destination);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.cli.deactivate();
|
||||
}
|
||||
}
|
1
src/jl-graphic/message/index.ts
Normal file
1
src/jl-graphic/message/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './MessageBroker';
|
99
src/jl-graphic/operation/JlOperation.ts
Normal file
99
src/jl-graphic/operation/JlOperation.ts
Normal file
@ -0,0 +1,99 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { IGraphicApp } from '../app/JlGraphicApp';
|
||||
import { JlGraphic } from '../core/JlGraphic';
|
||||
|
||||
/**
|
||||
* 操作
|
||||
*/
|
||||
export abstract class JlOperation {
|
||||
type: string; // 操作类型/名称
|
||||
app: IGraphicApp;
|
||||
obj?: any; // 操作对象
|
||||
data?: any; // 操作数据
|
||||
description?: string = ''; // 操作描述
|
||||
|
||||
constructor(app: IGraphicApp, type: string) {
|
||||
this.app = app;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
undo1(): void {
|
||||
const updates = this.undo();
|
||||
if (updates) {
|
||||
this.app.updateSelected(...updates);
|
||||
}
|
||||
}
|
||||
redo1(): void {
|
||||
const updates = this.redo();
|
||||
if (updates) {
|
||||
this.app.updateSelected(...updates);
|
||||
}
|
||||
}
|
||||
|
||||
abstract undo(): JlGraphic[] | void;
|
||||
abstract redo(): JlGraphic[] | void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 操作记录
|
||||
*/
|
||||
export class OperationRecord {
|
||||
undoStack: JlOperation[] = [];
|
||||
redoStack: JlOperation[] = [];
|
||||
private maxLen: number;
|
||||
|
||||
constructor(maxLen = 100) {
|
||||
this.maxLen = maxLen;
|
||||
}
|
||||
|
||||
public get hasUndo(): boolean {
|
||||
return this.undoStack.length > 0;
|
||||
}
|
||||
|
||||
public get hasRedo(): boolean {
|
||||
return this.redoStack.length > 0;
|
||||
}
|
||||
|
||||
setMaxLen(v: number) {
|
||||
this.maxLen = v;
|
||||
const len = this.undoStack.length;
|
||||
if (len > v) {
|
||||
const removeCount = len - v;
|
||||
this.undoStack.splice(0, removeCount);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 记录
|
||||
* @param op
|
||||
*/
|
||||
record(op: JlOperation) {
|
||||
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);
|
||||
}
|
||||
/**
|
||||
* 撤销
|
||||
*/
|
||||
undo() {
|
||||
const op = this.undoStack.pop();
|
||||
// console.log('撤销', op);
|
||||
if (op) {
|
||||
op.undo1();
|
||||
this.redoStack.push(op);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 重做
|
||||
*/
|
||||
redo() {
|
||||
const op = this.redoStack.pop();
|
||||
// console.log('重做', op);
|
||||
if (op) {
|
||||
op.redo1();
|
||||
this.undoStack.push(op);
|
||||
}
|
||||
}
|
||||
}
|
1
src/jl-graphic/operation/index.ts
Normal file
1
src/jl-graphic/operation/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './JlOperation';
|
93
src/jl-graphic/plugins/AnimationManager.ts
Normal file
93
src/jl-graphic/plugins/AnimationManager.ts
Normal file
@ -0,0 +1,93 @@
|
||||
import { IGraphicScene } from '../app';
|
||||
import { GraphicAnimation, JlGraphic } from '../core';
|
||||
|
||||
/**
|
||||
* 图形动画管理
|
||||
*/
|
||||
export class AnimationManager {
|
||||
app: IGraphicScene;
|
||||
_pause: boolean;
|
||||
/**
|
||||
* key - graphic.id
|
||||
*/
|
||||
graphicAnimationMap: Map<string, Map<string, GraphicAnimation>>;
|
||||
constructor(app: IGraphicScene) {
|
||||
this.app = app;
|
||||
this._pause = false;
|
||||
this.graphicAnimationMap = new Map<string, Map<string, GraphicAnimation>>();
|
||||
// 动画控制
|
||||
app.pixi.ticker.add(this.run, this);
|
||||
}
|
||||
|
||||
private run(dt: number) {
|
||||
if (this._pause) {
|
||||
// 暂停
|
||||
return;
|
||||
}
|
||||
this.graphicAnimationMap.forEach((map) => {
|
||||
map.forEach((animation) => {
|
||||
if (animation.running) {
|
||||
animation.run(dt);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pause() {
|
||||
this._pause = true;
|
||||
}
|
||||
|
||||
resume() {
|
||||
this._pause = false;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.app.pixi.ticker.remove(this.run, this);
|
||||
}
|
||||
/**
|
||||
* 图形对象的所有动画map
|
||||
* @param graphic
|
||||
* @returns
|
||||
*/
|
||||
animationMap(graphic: JlGraphic): Map<string, GraphicAnimation> {
|
||||
let map = this.graphicAnimationMap.get(graphic.id);
|
||||
if (!map) {
|
||||
map = new Map<string, GraphicAnimation>();
|
||||
this.graphicAnimationMap.set(graphic.id, map);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册图形动画
|
||||
* @param graphic
|
||||
* @param animation
|
||||
*/
|
||||
registerAnimation(graphic: JlGraphic, animation: GraphicAnimation) {
|
||||
this.animationMap(graphic).set(animation.name, animation);
|
||||
}
|
||||
/**
|
||||
* 删除图形动画
|
||||
* @param graphic
|
||||
* @param name
|
||||
*/
|
||||
unregisterAnimation(graphic: JlGraphic, name: string) {
|
||||
this.animationMap(graphic).delete(name);
|
||||
}
|
||||
/**
|
||||
* 删除所有图形动画
|
||||
* @param graphic
|
||||
*/
|
||||
unregisterGraphicAnimations(graphic: JlGraphic) {
|
||||
this.animationMap(graphic).clear();
|
||||
}
|
||||
/**
|
||||
* 获取图形指定名称动画
|
||||
* @param graphic
|
||||
* @param name
|
||||
* @returns
|
||||
*/
|
||||
animation(graphic: JlGraphic, name: string): GraphicAnimation | undefined {
|
||||
return this.animationMap(graphic).get(name);
|
||||
}
|
||||
}
|
401
src/jl-graphic/plugins/CommonMousePlugin.ts
Normal file
401
src/jl-graphic/plugins/CommonMousePlugin.ts
Normal file
@ -0,0 +1,401 @@
|
||||
import {
|
||||
Color,
|
||||
DisplayObject,
|
||||
FederatedMouseEvent,
|
||||
Graphics,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import { ICanvasProperties, IGraphicScene } from '../app';
|
||||
import { JlGraphic } from '../core';
|
||||
import {
|
||||
AppDragEvent,
|
||||
AppInteractionPlugin,
|
||||
ViewportMovePlugin,
|
||||
} from './InteractionPlugin';
|
||||
|
||||
type GraphicSelectFilter = (graphic: JlGraphic) => boolean;
|
||||
|
||||
export interface IMouseToolOptions {
|
||||
/**
|
||||
* 是否启用框选,默认启用
|
||||
*/
|
||||
boxSelect?: boolean;
|
||||
/**
|
||||
* 是否启用视口拖拽(默认右键),默认启用
|
||||
*/
|
||||
viewportDrag?: boolean;
|
||||
/**
|
||||
* 是否启用左键视口拖拽
|
||||
*/
|
||||
viewportDragLeft?: boolean;
|
||||
/**
|
||||
* 是否启用鼠标滚轮缩放,默认启用
|
||||
*/
|
||||
wheelZoom?: boolean;
|
||||
/**
|
||||
* 可选择图形过滤器
|
||||
*/
|
||||
selectFilter?: GraphicSelectFilter;
|
||||
}
|
||||
|
||||
class CompleteMouseToolOptions implements IMouseToolOptions {
|
||||
boxSelect: boolean;
|
||||
viewportDrag: boolean;
|
||||
viewportDragLeft: boolean;
|
||||
wheelZoom: boolean;
|
||||
selectFilter?: GraphicSelectFilter | undefined;
|
||||
constructor() {
|
||||
this.boxSelect = true;
|
||||
this.viewportDrag = true;
|
||||
this.wheelZoom = true;
|
||||
this.viewportDragLeft = false;
|
||||
}
|
||||
update(options: IMouseToolOptions) {
|
||||
if (options.boxSelect != undefined) {
|
||||
this.boxSelect = options.boxSelect;
|
||||
}
|
||||
if (options.viewportDrag != undefined) {
|
||||
this.viewportDrag = options.viewportDrag;
|
||||
}
|
||||
if (options.viewportDragLeft != undefined) {
|
||||
this.viewportDragLeft = options.viewportDragLeft;
|
||||
}
|
||||
if (options.wheelZoom != undefined) {
|
||||
this.wheelZoom = options.wheelZoom;
|
||||
}
|
||||
this.selectFilter = options.selectFilter;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用交互工具
|
||||
*/
|
||||
export class CommonMouseTool extends AppInteractionPlugin {
|
||||
static Name = 'mouse-tool';
|
||||
static SelectBox = '__select_box';
|
||||
options: CompleteMouseToolOptions;
|
||||
box: Graphics;
|
||||
_boxLineColor: Color;
|
||||
leftDownTarget: DisplayObject | null = null;
|
||||
|
||||
drag = false;
|
||||
graphicSelect = false;
|
||||
|
||||
rightTarget: DisplayObject | null = null;
|
||||
|
||||
constructor(scene: IGraphicScene) {
|
||||
super(CommonMouseTool.Name, scene);
|
||||
this.options = new CompleteMouseToolOptions();
|
||||
|
||||
this.box = new Graphics();
|
||||
this._boxLineColor = new Color();
|
||||
|
||||
scene.canvas.on('dataupdate', this.updateBoxLineColor, this);
|
||||
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();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static new(app: IGraphicScene) {
|
||||
return new CommonMouseTool(app);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算对比色
|
||||
* @param rgb
|
||||
* @returns
|
||||
*/
|
||||
private calContrastColor(rgb: number): number {
|
||||
if (rgb > 0.45 && rgb < 0.55) {
|
||||
return 0;
|
||||
} else {
|
||||
return 1 - rgb;
|
||||
}
|
||||
}
|
||||
|
||||
private updateBoxLineColor(cp: ICanvasProperties) {
|
||||
// 根据画布背景调整线色
|
||||
const color = new Color(cp.backgroundColor);
|
||||
// 对比色
|
||||
const r = this.calContrastColor(color.red);
|
||||
const g = this.calContrastColor(color.green);
|
||||
const b = this.calContrastColor(color.blue);
|
||||
this._boxLineColor.setValue([r, g, b]);
|
||||
}
|
||||
|
||||
bind(): void {
|
||||
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);
|
||||
this.app.on('drag_op_move', this.onDragMove, this);
|
||||
this.app.on('drag_op_end', this.onDragEnd, this);
|
||||
if (this.options.viewportDrag) {
|
||||
if (this.options.viewportDragLeft) {
|
||||
this.app.viewport.drag({
|
||||
mouseButtons: 'left',
|
||||
});
|
||||
canvas.on('mousedown', this.setLeftCursor, this);
|
||||
canvas.on('mouseup', this.resumeLeftCursor, this);
|
||||
canvas.on('mouseupoutside', this.resumeLeftCursor, this);
|
||||
} else {
|
||||
this.app.viewport.drag({
|
||||
mouseButtons: 'right',
|
||||
});
|
||||
canvas.on('rightdown', this.setCursor, this);
|
||||
canvas.on('rightup', this.resumeCursor, this);
|
||||
canvas.on('rightupoutside', this.resumeCursor, this);
|
||||
}
|
||||
}
|
||||
if (this.options.wheelZoom) {
|
||||
this.app.viewport.wheel({
|
||||
percent: 0.01,
|
||||
});
|
||||
}
|
||||
}
|
||||
unbind(): void {
|
||||
const canvas = this.app.canvas;
|
||||
// 确保所有事件取消监听
|
||||
canvas.off('mousedown', this.onMouseDown, this);
|
||||
canvas.off('mouseup', this.onMouseUp, this);
|
||||
|
||||
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.viewport.plugins.remove('drag');
|
||||
canvas.off('mousedown', this.setLeftCursor, this);
|
||||
canvas.off('mouseup', this.resumeLeftCursor, this);
|
||||
canvas.off('mouseupoutside', this.resumeLeftCursor, this);
|
||||
canvas.off('rightdown', this.setCursor, this);
|
||||
canvas.off('rightup', this.resumeCursor, this);
|
||||
canvas.off('rightupoutside', this.resumeCursor, this);
|
||||
|
||||
this.app.viewport.plugins.remove('wheel');
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
this.drag = true;
|
||||
}
|
||||
|
||||
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();
|
||||
this.app.interactionPlugin(ViewportMovePlugin.Name).pause();
|
||||
this.box.clear();
|
||||
this.box.visible = false;
|
||||
}
|
||||
}
|
||||
|
||||
setLeftCursor(e: FederatedMouseEvent) {
|
||||
const target = e.target as DisplayObject;
|
||||
this.leftDownTarget = target;
|
||||
if (target.isCanvas() && this.app.pixi.view.style) {
|
||||
this.app.pixi.view.style.cursor = 'grab';
|
||||
}
|
||||
}
|
||||
|
||||
resumeLeftCursor() {
|
||||
if (
|
||||
this.leftDownTarget &&
|
||||
this.leftDownTarget.isCanvas() &&
|
||||
this.app.pixi.view.style
|
||||
) {
|
||||
this.app.pixi.view.style.cursor = 'inherit';
|
||||
}
|
||||
this.leftDownTarget = null;
|
||||
}
|
||||
|
||||
setCursor(e: FederatedMouseEvent) {
|
||||
const target = e.target as DisplayObject;
|
||||
this.rightTarget = target;
|
||||
if (target.isCanvas() && this.app.pixi.view.style) {
|
||||
this.app.pixi.view.style.cursor = 'grab';
|
||||
}
|
||||
}
|
||||
|
||||
resumeCursor() {
|
||||
if (
|
||||
this.rightTarget &&
|
||||
this.rightTarget.isCanvas() &&
|
||||
this.app.pixi.view.style
|
||||
) {
|
||||
this.app.pixi.view.style.cursor = 'inherit';
|
||||
}
|
||||
this.rightTarget = null;
|
||||
}
|
||||
|
||||
onMouseDown(e: FederatedMouseEvent) {
|
||||
this.leftDownTarget = e.target as DisplayObject;
|
||||
this.graphicSelect = false;
|
||||
// 图形
|
||||
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);
|
||||
graphic.childEdit = false;
|
||||
this.graphicSelect = true;
|
||||
} else if (!e.ctrlKey && graphic.selected && graphic.childEdit) {
|
||||
if (
|
||||
this.leftDownTarget.isGraphicChild() &&
|
||||
this.leftDownTarget.selectable
|
||||
) {
|
||||
graphic.setChildSelected(this.leftDownTarget);
|
||||
} else {
|
||||
graphic.exitChildEdit();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 选中处理
|
||||
* @param e
|
||||
*/
|
||||
onMouseUp(e: FederatedMouseEvent) {
|
||||
const app = this.app;
|
||||
if (!this.drag) {
|
||||
const target = e.target as DisplayObject;
|
||||
const graphic = (e.target as DisplayObject).getGraphic();
|
||||
if (
|
||||
graphic &&
|
||||
graphic.selected &&
|
||||
!this.graphicSelect &&
|
||||
app.selectedGraphics.length == 1 &&
|
||||
target === this.leftDownTarget &&
|
||||
target.isGraphicChild() &&
|
||||
target.selectable
|
||||
) {
|
||||
graphic.childEdit = true;
|
||||
}
|
||||
if (e.ctrlKey) {
|
||||
// 多选
|
||||
if (graphic) {
|
||||
if (graphic.childEdit && target === this.leftDownTarget) {
|
||||
graphic.invertChildSelected(target);
|
||||
} else {
|
||||
graphic.invertSelected();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 非多选
|
||||
if ((e.target as DisplayObject).isCanvas()) {
|
||||
this.app.updateSelected();
|
||||
} else {
|
||||
if (
|
||||
graphic &&
|
||||
graphic.childEdit &&
|
||||
app.selectedGraphics.length === 1 &&
|
||||
target === this.leftDownTarget
|
||||
) {
|
||||
graphic.setChildSelected(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 多个图形选中,退出子元素编辑模式
|
||||
const selecteds = this.app.selectedGraphics;
|
||||
if (selecteds.length > 1) {
|
||||
selecteds.forEach((g) => g.exitChildEdit());
|
||||
}
|
||||
}
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理缓存
|
||||
*/
|
||||
clearCache() {
|
||||
this.drag = false;
|
||||
this.leftDownTarget = null;
|
||||
}
|
||||
|
||||
public get boxSelect(): boolean | undefined {
|
||||
return this.options.boxSelect;
|
||||
}
|
||||
|
||||
public get selectFilter(): GraphicSelectFilter | undefined {
|
||||
return this.options.selectFilter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 框选图形绘制并检查
|
||||
*/
|
||||
boxSelectDraw(start: Point, end: Point): void {
|
||||
if (!this.drag) return;
|
||||
// 绘制框选矩形框
|
||||
this.box.clear();
|
||||
this.box.lineStyle({ width: 2, color: this._boxLineColor });
|
||||
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;
|
||||
}
|
||||
const width = Math.abs(dsx);
|
||||
const height = Math.abs(dsy);
|
||||
this.box.drawRect(x, y, width, height);
|
||||
}
|
||||
|
||||
/**
|
||||
* 框选图形判断
|
||||
* @returns
|
||||
*/
|
||||
boxSelectGraphicCheck(): void {
|
||||
if (!this.drag) return;
|
||||
// 遍历筛选
|
||||
const boxRect = this.box.getLocalBounds();
|
||||
const app = this.app;
|
||||
const selects: JlGraphic[] = [];
|
||||
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(...selects);
|
||||
}
|
||||
}
|
142
src/jl-graphic/plugins/CopyPlugin.ts
Normal file
142
src/jl-graphic/plugins/CopyPlugin.ts
Normal file
@ -0,0 +1,142 @@
|
||||
import { Container, FederatedPointerEvent, Point } from 'pixi.js';
|
||||
import { IGraphicScene } from '../app';
|
||||
import { JlGraphic } from '../core';
|
||||
import { KeyListener } from './KeyboardPlugin';
|
||||
|
||||
/**
|
||||
* 图形复制插件
|
||||
*/
|
||||
export class GraphicCopyPlugin {
|
||||
container: Container;
|
||||
scene: IGraphicScene;
|
||||
keyListeners: KeyListener[];
|
||||
copys: JlGraphic[];
|
||||
start?: Point;
|
||||
running = false;
|
||||
moveLimit?: 'x' | 'y';
|
||||
constructor(scene: IGraphicScene) {
|
||||
this.scene = scene;
|
||||
this.container = new Container();
|
||||
this.copys = [];
|
||||
this.keyListeners = [];
|
||||
this.keyListeners.push(
|
||||
new KeyListener({
|
||||
// ESC 用于取消复制操作
|
||||
value: 'Escape',
|
||||
global: true,
|
||||
// combinations: [CombinationKey.Ctrl],
|
||||
onPress: () => {
|
||||
this.cancle();
|
||||
},
|
||||
}),
|
||||
new KeyListener({
|
||||
// X 限制只能在x轴移动
|
||||
value: 'KeyX',
|
||||
global: true,
|
||||
// combinations: [CombinationKey.Ctrl],
|
||||
onPress: () => {
|
||||
this.updateMoveLimit('x');
|
||||
},
|
||||
}),
|
||||
new KeyListener({
|
||||
// Y 限制只能在y轴移动
|
||||
value: 'KeyY',
|
||||
global: true,
|
||||
// combinations: [CombinationKey.Ctrl],
|
||||
onPress: () => {
|
||||
this.updateMoveLimit('y');
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateMoveLimit(limit?: 'x' | 'y'): void {
|
||||
if (this.moveLimit === limit) {
|
||||
this.moveLimit = undefined;
|
||||
} else {
|
||||
this.moveLimit = limit;
|
||||
}
|
||||
}
|
||||
|
||||
init(): void {
|
||||
if (this.running) return;
|
||||
if (this.scene.selectedGraphics.length === 0) {
|
||||
throw new Error('没有选中图形,复制取消');
|
||||
}
|
||||
this.running = true;
|
||||
this.copys = [];
|
||||
this.container.alpha = 0.5;
|
||||
this.scene.canvas.addChild(this.container);
|
||||
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((kl) => {
|
||||
this.scene.app.addKeyboardListener(kl);
|
||||
});
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.running = false;
|
||||
this.start = undefined;
|
||||
this.moveLimit = undefined;
|
||||
this.copys = [];
|
||||
this.container.removeChildren();
|
||||
this.scene.canvas.removeChild(this.container);
|
||||
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((kl) => {
|
||||
this.scene.app.removeKeyboardListener(kl);
|
||||
});
|
||||
}
|
||||
|
||||
onPointerMove(e: FederatedPointerEvent): void {
|
||||
const cp = this.scene.toCanvasCoordinates(e.global);
|
||||
if (!this.start) {
|
||||
this.start = cp;
|
||||
} else {
|
||||
if (this.moveLimit === 'x') {
|
||||
const dx = cp.x - this.start.x;
|
||||
this.container.position.x = dx;
|
||||
this.container.position.y = 0;
|
||||
} else if (this.moveLimit === 'y') {
|
||||
const dy = cp.y - this.start.y;
|
||||
this.container.position.x = 0;
|
||||
this.container.position.y = dy;
|
||||
} else {
|
||||
const dx = cp.x - this.start.x;
|
||||
const dy = cp.y - this.start.y;
|
||||
this.container.position.x = dx;
|
||||
this.container.position.y = dy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onFinish(): void {
|
||||
console.log('复制确认');
|
||||
// 将图形添加到app
|
||||
this.copys.forEach((g) => {
|
||||
g.position.x += this.container.position.x;
|
||||
g.position.y += this.container.position.y;
|
||||
});
|
||||
this.scene.app.addGraphicAndRecord(...this.copys);
|
||||
this.scene.detectRelations();
|
||||
this.scene.updateSelected(...this.copys);
|
||||
this.clear();
|
||||
}
|
||||
|
||||
cancle(): void {
|
||||
console.log('复制操作取消');
|
||||
this.scene.canvas.removeChild(this.container);
|
||||
this.clear();
|
||||
}
|
||||
}
|
514
src/jl-graphic/plugins/GraphicEditPlugin.ts
Normal file
514
src/jl-graphic/plugins/GraphicEditPlugin.ts
Normal file
@ -0,0 +1,514 @@
|
||||
import {
|
||||
Color,
|
||||
Container,
|
||||
DisplayObject,
|
||||
Graphics,
|
||||
IDestroyOptions,
|
||||
IPointData,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import { JlGraphic } from '../core';
|
||||
import { DraggablePoint } from '../graphic';
|
||||
import {
|
||||
calculateDistanceFromPointToLine,
|
||||
calculateFootPointFromPointToLine,
|
||||
calculateLineSegmentingPoint,
|
||||
calculateMirrorPoint,
|
||||
convertToBezierParams,
|
||||
distance2,
|
||||
linePoint,
|
||||
pointPolygon,
|
||||
} from '../utils';
|
||||
import { GraphicTransformEvent, ShiftData } from './GraphicTransformPlugin';
|
||||
|
||||
export abstract class GraphicEditPlugin<
|
||||
DO extends DisplayObject = DisplayObject
|
||||
> extends Container {
|
||||
graphic: DO;
|
||||
constructor(g: DO) {
|
||||
super();
|
||||
this.graphic = g;
|
||||
this.zIndex = 2;
|
||||
this.sortableChildren = true;
|
||||
this.graphic.on('transformstart', this.hideAll, this);
|
||||
this.graphic.on('transformend', this.showAll, this);
|
||||
this.graphic.on('repaint', this.updateEditedPointsPosition, this);
|
||||
}
|
||||
|
||||
destroy(options?: boolean | IDestroyOptions | undefined): void {
|
||||
this.graphic.off('transformstart', this.hideAll, this);
|
||||
this.graphic.off('transformend', this.showAll, this);
|
||||
this.graphic.off('repaint', this.updateEditedPointsPosition, this);
|
||||
super.destroy(options);
|
||||
}
|
||||
|
||||
abstract updateEditedPointsPosition(): void;
|
||||
|
||||
hideAll() {
|
||||
this.visible = false;
|
||||
}
|
||||
showAll() {
|
||||
this.updateEditedPointsPosition();
|
||||
this.visible = true;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ILineGraphic extends JlGraphic {
|
||||
get linePoints(): IPointData[];
|
||||
set linePoints(points: IPointData[]);
|
||||
}
|
||||
|
||||
export abstract class LineEditPlugin extends GraphicEditPlugin<ILineGraphic> {
|
||||
linePoints: IPointData[];
|
||||
editedPoints: DraggablePoint[] = [];
|
||||
constructor(g: ILineGraphic) {
|
||||
super(g);
|
||||
this.linePoints = g.linePoints;
|
||||
this.graphic.on('dataupdate', this.reset, this);
|
||||
}
|
||||
|
||||
destroy(options?: boolean | IDestroyOptions | undefined): void {
|
||||
this.graphic.off('dataupdate', this.reset, this);
|
||||
super.destroy(options);
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.linePoints = this.graphic.linePoints;
|
||||
this.removeChildren();
|
||||
this.editedPoints.splice(0, this.editedPoints.length);
|
||||
this.initEditPoints();
|
||||
}
|
||||
|
||||
abstract initEditPoints(): void;
|
||||
}
|
||||
|
||||
export function getWayLineIndex(
|
||||
points: IPointData[],
|
||||
p: IPointData
|
||||
): { start: number; end: number } {
|
||||
let start = 0;
|
||||
let end = 0;
|
||||
let minDistance = 0;
|
||||
for (let i = 1; i < points.length; i++) {
|
||||
const sp = points[i - 1];
|
||||
const ep = points[i];
|
||||
let distance = calculateDistanceFromPointToLine(sp, ep, p);
|
||||
distance = Math.round(distance * 100) / 100;
|
||||
if (i == 1) {
|
||||
minDistance = distance;
|
||||
}
|
||||
if (distance == minDistance) {
|
||||
const minX = Math.min(sp.x, ep.x);
|
||||
const maxX = Math.max(sp.x, ep.x);
|
||||
const minY = Math.min(sp.y, ep.y);
|
||||
const maxY = Math.max(sp.y, ep.y);
|
||||
const point = calculateFootPointFromPointToLine(sp, ep, p);
|
||||
if (
|
||||
point.x >= minX &&
|
||||
point.x <= maxX &&
|
||||
point.y >= minY &&
|
||||
point.y <= maxY
|
||||
) {
|
||||
start = i - 1;
|
||||
}
|
||||
}
|
||||
if (distance < minDistance) {
|
||||
minDistance = distance;
|
||||
start = i - 1;
|
||||
}
|
||||
}
|
||||
end = start + 1;
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
export function getWaypointRangeIndex(
|
||||
points: IPointData[],
|
||||
curve: boolean,
|
||||
p: IPointData,
|
||||
lineWidth: number
|
||||
): { start: number; end: number } {
|
||||
let start = 0;
|
||||
let end = 0;
|
||||
if (!curve) {
|
||||
// 直线
|
||||
for (let i = 1; i < points.length; i++) {
|
||||
const sp = points[i - 1];
|
||||
const ep = points[i];
|
||||
const fp = calculateFootPointFromPointToLine(sp, ep, p);
|
||||
if (linePoint(sp, ep, fp, 1, true)) {
|
||||
start = i - 1;
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 贝塞尔曲线
|
||||
const bps = convertToBezierParams(points);
|
||||
for (let i = 0; i < bps.length; i++) {
|
||||
const bp = bps[i];
|
||||
if (pointPolygon(p, [bp.p1, bp.cp1, bp.cp2, bp.p2], lineWidth)) {
|
||||
start = i * 3;
|
||||
end = start + 3;
|
||||
}
|
||||
}
|
||||
// assertBezierPoints(points);
|
||||
// for (let i = 0; i < points.length - 3; i += 3) {
|
||||
// const p1 = points[i];
|
||||
// const cp1 = points[i + 1];
|
||||
// const cp2 = points[i + 2];
|
||||
// const p2 = points[i + 3];
|
||||
// if (pointPolygon(p, [p1, cp1, cp2, p2], lineWidth)) {
|
||||
// start = i;
|
||||
// end = i + 3;
|
||||
// }
|
||||
// }
|
||||
}
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
export type onEditPointCreate = (
|
||||
g: ILineGraphic,
|
||||
dp: DraggablePoint,
|
||||
index: number
|
||||
) => void;
|
||||
|
||||
export interface IEditPointOptions {
|
||||
/**
|
||||
* 编辑点创建处理
|
||||
*/
|
||||
onEditPointCreate?: onEditPointCreate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 折线编辑(兼容线段)
|
||||
*/
|
||||
export class PolylineEditPlugin extends LineEditPlugin {
|
||||
static Name = 'line_points_edit';
|
||||
options: IEditPointOptions;
|
||||
constructor(g: ILineGraphic, options?: IEditPointOptions) {
|
||||
super(g);
|
||||
this.options = Object.assign({}, options);
|
||||
this.name = PolylineEditPlugin.Name;
|
||||
this.initEditPoints();
|
||||
}
|
||||
|
||||
initEditPoints() {
|
||||
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
|
||||
for (let i = 0; i < cps.length; i++) {
|
||||
const p = cps[i];
|
||||
const dp = new DraggablePoint(p);
|
||||
|
||||
dp.on('transforming', () => {
|
||||
const tlp = this.graphic.canvasToLocalPoint(dp.position);
|
||||
const cp = this.linePoints[i];
|
||||
cp.x = tlp.x;
|
||||
cp.y = tlp.y;
|
||||
this.graphic.repaint();
|
||||
});
|
||||
if (this.options.onEditPointCreate) {
|
||||
this.options.onEditPointCreate(this.graphic, dp, i);
|
||||
}
|
||||
this.editedPoints.push(dp);
|
||||
}
|
||||
this.addChild(...this.editedPoints);
|
||||
}
|
||||
updateEditedPointsPosition() {
|
||||
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
|
||||
if (cps.length === this.editedPoints.length) {
|
||||
for (let i = 0; i < cps.length; i++) {
|
||||
const cp = cps[i];
|
||||
this.editedPoints[i].position.copyFrom(cp);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface BezierCurveEditPointOptions extends IEditPointOptions {
|
||||
// 曲线控制点辅助连线颜色
|
||||
auxiliaryLineColor?: string;
|
||||
// // 拖拽点颜色
|
||||
// pointColor?: string;
|
||||
// 连接点处是否平滑(点左右控制点是否在一条直线),默认true
|
||||
smooth?: boolean;
|
||||
// 控制点是否完全对称(对称必平滑)
|
||||
symmetry?: boolean;
|
||||
}
|
||||
|
||||
export interface ICompleteBezierCurveEditPointOptions
|
||||
extends BezierCurveEditPointOptions {
|
||||
smooth: boolean;
|
||||
}
|
||||
|
||||
export function addWayPoint(
|
||||
graphic: ILineGraphic,
|
||||
curve: boolean,
|
||||
start: number,
|
||||
end: number,
|
||||
p: IPointData
|
||||
) {
|
||||
if (!curve) {
|
||||
addLineWayPoint(graphic, start, end, p);
|
||||
} else {
|
||||
addBezierWayPoint(graphic, start, end, p);
|
||||
}
|
||||
}
|
||||
|
||||
export function addLineWayPoint(
|
||||
graphic: ILineGraphic,
|
||||
start: number,
|
||||
end: number,
|
||||
p: IPointData
|
||||
) {
|
||||
const linePoints = graphic.linePoints;
|
||||
const points = linePoints.slice(0, start + 1);
|
||||
points.push(new Point(p.x, p.y));
|
||||
points.push(...linePoints.slice(end));
|
||||
graphic.linePoints = points;
|
||||
}
|
||||
|
||||
export function addPolygonSegmentingPoint(
|
||||
graphic: ILineGraphic,
|
||||
start: number,
|
||||
end: number,
|
||||
knife = 2
|
||||
) {
|
||||
const linePoints = graphic.linePoints;
|
||||
const points = linePoints.slice(0, start + 1);
|
||||
points.push(
|
||||
...calculateLineSegmentingPoint(linePoints[start], linePoints[end], knife)
|
||||
);
|
||||
points.push(...linePoints.slice(end));
|
||||
graphic.linePoints = points;
|
||||
}
|
||||
|
||||
function assertBezierWayPoint(i: number) {
|
||||
const c = i % 3;
|
||||
if (c !== 0) {
|
||||
throw new Error(`i=${i}的点不是路径点`);
|
||||
}
|
||||
}
|
||||
|
||||
export function addBezierWayPoint(
|
||||
graphic: ILineGraphic,
|
||||
start: number,
|
||||
end: number,
|
||||
p: IPointData
|
||||
) {
|
||||
if (start === end) {
|
||||
console.error('添加贝塞尔曲线路径点开始结束点相等', start);
|
||||
throw new Error('开始结束点不能一致');
|
||||
}
|
||||
assertBezierWayPoint(start);
|
||||
assertBezierWayPoint(end);
|
||||
const linePoints = graphic.linePoints;
|
||||
const points = linePoints.slice(0, start + 2);
|
||||
const ap = new Point(p.x, p.y);
|
||||
points.push(ap.clone(), ap.clone(), ap.clone());
|
||||
points.push(...linePoints.slice(end - 1));
|
||||
graphic.linePoints = points;
|
||||
}
|
||||
|
||||
export function removeWayPoint(
|
||||
graphic: ILineGraphic,
|
||||
curve: boolean,
|
||||
i: number
|
||||
) {
|
||||
if (!curve) {
|
||||
removeLineWayPoint(graphic, i);
|
||||
} else {
|
||||
removeBezierWayPoint(graphic, i);
|
||||
}
|
||||
}
|
||||
|
||||
export function removeLineWayPoint(graphic: ILineGraphic, i: number) {
|
||||
const linePoints = graphic.linePoints;
|
||||
if (linePoints.length > 2) {
|
||||
const points = linePoints.slice(0, i);
|
||||
points.push(...linePoints.slice(i + 1));
|
||||
graphic.linePoints = points;
|
||||
}
|
||||
}
|
||||
|
||||
export function removeBezierWayPoint(graphic: ILineGraphic, i: number) {
|
||||
let points;
|
||||
const linePoints = graphic.linePoints;
|
||||
const c = i % 3;
|
||||
if (c !== 0) {
|
||||
throw new Error(`i=${i}的点${linePoints[i]}不是路径点`);
|
||||
}
|
||||
if (i === 0) {
|
||||
// 第一个点
|
||||
if (linePoints.length > 4) {
|
||||
points = linePoints.slice(3);
|
||||
} else {
|
||||
console.error('不能移除:剩余点数不足');
|
||||
}
|
||||
} else if (i === linePoints.length - 1) {
|
||||
// 最后一个点
|
||||
if (linePoints.length > 4) {
|
||||
points = linePoints.slice(0, linePoints.length - 3);
|
||||
} else {
|
||||
console.error('无法移除:剩余点数不足');
|
||||
}
|
||||
} else {
|
||||
// 中间点
|
||||
points = linePoints.slice(0, i - 1);
|
||||
points.push(...linePoints.slice(i + 2));
|
||||
}
|
||||
if (points) {
|
||||
graphic.linePoints = points;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除路径点(只留端点),适用于直线和贝塞尔曲线
|
||||
* @param graphic
|
||||
* @param curve
|
||||
*/
|
||||
export function clearWayPoint(graphic: ILineGraphic, curve: boolean) {
|
||||
const linePoints = graphic.linePoints;
|
||||
if (!curve) {
|
||||
if (linePoints.length > 2) {
|
||||
const points = linePoints.slice(0, 1);
|
||||
points.push(...linePoints.slice(-1));
|
||||
graphic.linePoints = points;
|
||||
}
|
||||
} else {
|
||||
if (linePoints.length > 4) {
|
||||
const points = linePoints.slice(0, 2);
|
||||
points.push(...linePoints.slice(-2));
|
||||
graphic.linePoints = points;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 贝塞尔曲线编辑
|
||||
*/
|
||||
export class BezierCurveEditPlugin extends LineEditPlugin {
|
||||
static Name = 'bezier_curve_points_edit';
|
||||
options: ICompleteBezierCurveEditPointOptions;
|
||||
// 曲线控制点辅助线
|
||||
auxiliaryLines: Graphics[] = [];
|
||||
constructor(g: ILineGraphic, options?: BezierCurveEditPointOptions) {
|
||||
super(g);
|
||||
this.options = Object.assign({}, { smooth: true }, options);
|
||||
this.name = BezierCurveEditPlugin.Name;
|
||||
this.initEditPoints();
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.auxiliaryLines.splice(0, this.auxiliaryLines.length);
|
||||
super.reset();
|
||||
}
|
||||
|
||||
initEditPoints() {
|
||||
// console.log('initEditPoints');
|
||||
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
|
||||
for (let i = 0; i < cps.length; i++) {
|
||||
const p = cps[i];
|
||||
const dp = new DraggablePoint(p);
|
||||
const startOrEnd = i == 0 || i == cps.length - 1;
|
||||
const c = i % 3;
|
||||
if (c === 1) {
|
||||
// 前一路径点的控制点
|
||||
dp.zIndex = 2;
|
||||
const fp = cps[i - 1];
|
||||
const line = new Graphics();
|
||||
this.drawAuxiliaryLine(line, fp, p);
|
||||
this.auxiliaryLines.push(line);
|
||||
} else if (c === 2) {
|
||||
// 后一路径点的控制点
|
||||
dp.zIndex = 3;
|
||||
const np = cps[i + 1];
|
||||
const line = new Graphics();
|
||||
this.drawAuxiliaryLine(line, p, np);
|
||||
this.auxiliaryLines.push(line);
|
||||
}
|
||||
dp.on('transforming', (e: GraphicTransformEvent) => {
|
||||
const tlp = this.graphic.canvasToLocalPoint(dp.position);
|
||||
const cp = this.linePoints[i];
|
||||
cp.x = tlp.x;
|
||||
cp.y = tlp.y;
|
||||
if (this.options.smooth || this.options.symmetry) {
|
||||
if (c === 0 && !startOrEnd) {
|
||||
const shiftData = e.getData<ShiftData>();
|
||||
const fp = this.linePoints[i - 1];
|
||||
const np = this.linePoints[i + 1];
|
||||
fp.x = fp.x + shiftData.dx;
|
||||
fp.y = fp.y + shiftData.dy;
|
||||
np.x = np.x + shiftData.dx;
|
||||
np.y = np.y + shiftData.dy;
|
||||
} else if (c === 1 && i !== 1) {
|
||||
const bp = this.linePoints[i - 1];
|
||||
const fp2 = this.linePoints[i - 2];
|
||||
let mp;
|
||||
if (this.options.symmetry) {
|
||||
mp = calculateMirrorPoint(bp, cp);
|
||||
} else {
|
||||
const distance = distance2(bp, fp2);
|
||||
mp = calculateMirrorPoint(bp, cp, distance);
|
||||
}
|
||||
fp2.x = mp.x;
|
||||
fp2.y = mp.y;
|
||||
} else if (c === 2 && i !== cps.length - 2) {
|
||||
const bp = this.linePoints[i + 1];
|
||||
const np2 = this.linePoints[i + 2];
|
||||
let mp;
|
||||
if (this.options.symmetry) {
|
||||
mp = calculateMirrorPoint(bp, cp);
|
||||
} else {
|
||||
const distance = distance2(bp, np2);
|
||||
mp = calculateMirrorPoint(bp, cp, distance);
|
||||
}
|
||||
np2.x = mp.x;
|
||||
np2.y = mp.y;
|
||||
}
|
||||
}
|
||||
this.graphic.repaint();
|
||||
});
|
||||
if (this.options.onEditPointCreate) {
|
||||
this.options.onEditPointCreate(this.graphic, dp, i);
|
||||
}
|
||||
this.editedPoints.push(dp);
|
||||
if (this.auxiliaryLines.length > 0) {
|
||||
this.addChild(...this.auxiliaryLines);
|
||||
}
|
||||
}
|
||||
this.addChild(...this.editedPoints);
|
||||
}
|
||||
|
||||
drawAuxiliaryLine(line: Graphics, p1: IPointData, p2: IPointData) {
|
||||
line.clear();
|
||||
if (this.options.auxiliaryLineColor) {
|
||||
line.lineStyle(1, new Color(this.options.auxiliaryLineColor));
|
||||
} else {
|
||||
line.lineStyle(1, new Color('blue'));
|
||||
}
|
||||
line.moveTo(p1.x, p1.y);
|
||||
line.lineTo(p2.x, p2.y);
|
||||
}
|
||||
|
||||
updateEditedPointsPosition() {
|
||||
const cps = this.graphic.localToCanvasPoints(...this.linePoints);
|
||||
if (cps.length === this.editedPoints.length) {
|
||||
for (let i = 0; i < cps.length; i++) {
|
||||
const cp = cps[i];
|
||||
this.editedPoints[i].position.copyFrom(cp);
|
||||
const c = i % 3;
|
||||
const d = Math.floor(i / 3);
|
||||
if (c === 1 || c === 2) {
|
||||
const li = d * 2 + c - 1;
|
||||
const line = this.auxiliaryLines[li];
|
||||
if (c === 1) {
|
||||
const fp = cps[i - 1];
|
||||
this.drawAuxiliaryLine(line, fp, cp);
|
||||
} else {
|
||||
const np = cps[i + 1];
|
||||
this.drawAuxiliaryLine(line, cp, np);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
913
src/jl-graphic/plugins/GraphicTransformPlugin.ts
Normal file
913
src/jl-graphic/plugins/GraphicTransformPlugin.ts
Normal file
@ -0,0 +1,913 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import {
|
||||
Container,
|
||||
DisplayObject,
|
||||
Graphics,
|
||||
IDestroyOptions,
|
||||
Point,
|
||||
Polygon,
|
||||
} from 'pixi.js';
|
||||
import {
|
||||
AppDragEvent,
|
||||
InteractionPluginBase,
|
||||
InteractionPluginType,
|
||||
KeyListener,
|
||||
} from '.';
|
||||
import { IGraphicScene } from '../app';
|
||||
import { JlGraphic } from '../core';
|
||||
import { AbsorbablePosition, VectorText } from '../graphic';
|
||||
import { DraggablePoint } from '../graphic/DraggablePoint';
|
||||
import {
|
||||
DebouncedFunction,
|
||||
angleToAxisx,
|
||||
calculateLineMidpoint,
|
||||
convertRectangleToPolygonPoints,
|
||||
debounce,
|
||||
distance,
|
||||
recursiveChildren,
|
||||
} from '../utils';
|
||||
|
||||
export class ShiftData {
|
||||
/**
|
||||
* 起始位置
|
||||
*/
|
||||
startPosition: Point;
|
||||
/**
|
||||
* 上一次终点位置
|
||||
*/
|
||||
lastPosition?: Point;
|
||||
/**
|
||||
* 当前位置
|
||||
*/
|
||||
currentPosition?: Point;
|
||||
constructor(
|
||||
startPosition: Point,
|
||||
currentPosition?: Point,
|
||||
lastPosition?: Point
|
||||
) {
|
||||
this.startPosition = startPosition;
|
||||
this.lastPosition = lastPosition;
|
||||
this.currentPosition = currentPosition;
|
||||
}
|
||||
static new(
|
||||
startPosition: Point,
|
||||
currentPosition?: Point,
|
||||
lastPosition?: Point
|
||||
) {
|
||||
return new ShiftData(startPosition, currentPosition, lastPosition);
|
||||
}
|
||||
|
||||
public get dx(): number {
|
||||
if (!this.lastPosition || !this.currentPosition) {
|
||||
throw new Error('错误的位移数据或阶段');
|
||||
}
|
||||
return this.currentPosition.x - this.lastPosition.x;
|
||||
}
|
||||
|
||||
public get dy(): number {
|
||||
if (!this.lastPosition || !this.currentPosition) {
|
||||
throw new Error('错误的位移数据或阶段');
|
||||
}
|
||||
return this.currentPosition.y - this.lastPosition.y;
|
||||
}
|
||||
|
||||
public get dsx(): number {
|
||||
if (!this.currentPosition) {
|
||||
throw new Error('错误的位移数据或阶段');
|
||||
}
|
||||
return this.currentPosition.x - this.startPosition.x;
|
||||
}
|
||||
|
||||
public get dsy(): number {
|
||||
if (!this.currentPosition) {
|
||||
throw new Error('错误的位移数据或阶段');
|
||||
}
|
||||
return this.currentPosition.y - this.startPosition.y;
|
||||
}
|
||||
}
|
||||
|
||||
export class ScaleData {
|
||||
start: Point;
|
||||
current?: Point;
|
||||
last?: Point;
|
||||
constructor(start: Point, current?: Point, last?: Point) {
|
||||
this.start = start;
|
||||
this.current = current;
|
||||
this.last = last;
|
||||
}
|
||||
static new(start: Point, current?: Point, last?: Point) {
|
||||
return new ScaleData(start, current, last);
|
||||
}
|
||||
}
|
||||
|
||||
export type TransformData = ShiftData | null;
|
||||
|
||||
/**
|
||||
* 图形平移事件
|
||||
*/
|
||||
export class GraphicTransformEvent {
|
||||
/**
|
||||
* 图形对象
|
||||
*/
|
||||
target: DisplayObject;
|
||||
type: 'shift' | 'rotate' | 'scale' | 'skew';
|
||||
data: TransformData;
|
||||
|
||||
constructor(
|
||||
target: DisplayObject,
|
||||
type: 'shift' | 'rotate' | 'scale' | 'skew',
|
||||
data: TransformData
|
||||
) {
|
||||
this.target = target;
|
||||
this.type = type;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
getData<D extends TransformData>(): D {
|
||||
return this.data as D;
|
||||
}
|
||||
|
||||
static shift(target: DisplayObject, data: ShiftData) {
|
||||
return new GraphicTransformEvent(target, 'shift', data);
|
||||
}
|
||||
|
||||
static scale(target: DisplayObject) {
|
||||
return new GraphicTransformEvent(target, 'scale', null);
|
||||
}
|
||||
|
||||
static rotate(target: DisplayObject) {
|
||||
return new GraphicTransformEvent(target, 'rotate', null);
|
||||
}
|
||||
|
||||
static skew(target: DisplayObject) {
|
||||
return new GraphicTransformEvent(target, 'skew', null);
|
||||
}
|
||||
|
||||
isShift(): boolean {
|
||||
return this.type === 'shift';
|
||||
}
|
||||
isRotate(): boolean {
|
||||
return this.type === 'rotate';
|
||||
}
|
||||
isScale(): boolean {
|
||||
return this.type === 'scale';
|
||||
}
|
||||
isSkew(): boolean {
|
||||
return this.type === 'skew';
|
||||
}
|
||||
}
|
||||
|
||||
export class GraphicTransformPlugin extends InteractionPluginBase {
|
||||
static Name = '__graphic_transform_plugin';
|
||||
|
||||
/**
|
||||
* 可吸附位置列表
|
||||
*/
|
||||
absorbablePositions?: AbsorbablePosition[];
|
||||
apContainer: Container;
|
||||
static AbsorbablePosisiontsName = '__AbsorbablePosisionts';
|
||||
|
||||
constructor(app: IGraphicScene) {
|
||||
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
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤重复的吸附位置
|
||||
* @param positions
|
||||
* @returns
|
||||
*/
|
||||
filterAbsorbablePositions(
|
||||
positions: AbsorbablePosition[]
|
||||
): AbsorbablePosition[] {
|
||||
const aps: AbsorbablePosition[] = [];
|
||||
for (let i = 0; i < positions.length; i++) {
|
||||
const ap1 = positions[i];
|
||||
let ap: AbsorbablePosition | null = 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;
|
||||
}
|
||||
}
|
||||
if (ap != null) {
|
||||
aps.push(ap);
|
||||
}
|
||||
}
|
||||
// console.log(positions, aps);
|
||||
return aps;
|
||||
}
|
||||
|
||||
static new(app: IGraphicScene) {
|
||||
return new GraphicTransformPlugin(app);
|
||||
}
|
||||
|
||||
bind(): void {
|
||||
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
|
||||
);
|
||||
}
|
||||
unbind(): void {
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
getDraggedTargets(e: AppDragEvent): DisplayObject[] {
|
||||
const targets: DisplayObject[] = [];
|
||||
if (e.target.isGraphicChild() && e.target.selected && e.target.draggable) {
|
||||
const graphic = e.target.getGraphic() as JlGraphic;
|
||||
// 图形子元素
|
||||
recursiveChildren(graphic, (child) => {
|
||||
if (child.selected && child.draggable) {
|
||||
targets.push(child);
|
||||
}
|
||||
});
|
||||
} else if (
|
||||
(e.target.isGraphic() || e.target.isGraphicChild()) &&
|
||||
e.target.getGraphic()?.draggable
|
||||
) {
|
||||
// 图形对象
|
||||
targets.push(...this.app.selectedGraphics);
|
||||
} else if (e.target.draggable) {
|
||||
targets.push(e.target);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
onDragStart(e: AppDragEvent) {
|
||||
if (!e.target.isCanvas() && e.isLeftButton) {
|
||||
const targets: DisplayObject[] = this.getDraggedTargets(e);
|
||||
if (targets.length > 0) {
|
||||
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();
|
||||
this.apContainer.addChild(...this.absorbablePositions);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onDragMove(e: AppDragEvent) {
|
||||
if (!e.target.isCanvas() && e.isLeftButton) {
|
||||
const targets: DisplayObject[] = this.getDraggedTargets(e);
|
||||
if (targets.length > 0) {
|
||||
// 处理位移
|
||||
targets.forEach((target) => {
|
||||
if (target.shiftStartPoint) {
|
||||
target.shiftLastPoint = target.position.clone();
|
||||
const { dx, dy } = e.toTargetShiftLen(target.parent);
|
||||
target.position.set(
|
||||
target.shiftStartPoint.x + dx,
|
||||
target.shiftStartPoint.y + dy
|
||||
);
|
||||
}
|
||||
});
|
||||
// 处理吸附
|
||||
if (this.absorbablePositions) {
|
||||
for (let i = 0; i < this.absorbablePositions.length; i++) {
|
||||
const ap = this.absorbablePositions[i];
|
||||
ap.tryAbsorb(...targets);
|
||||
}
|
||||
}
|
||||
// const start = new Date().getTime();
|
||||
|
||||
// 事件发布
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onDragEnd(e: AppDragEvent) {
|
||||
if (!e.target.isCanvas() && e.isLeftButton) {
|
||||
const targets: DisplayObject[] = this.getDraggedTargets(e);
|
||||
targets.forEach((target) => {
|
||||
if (target.shiftStartPoint) {
|
||||
target.emit(
|
||||
'transformend',
|
||||
GraphicTransformEvent.shift(
|
||||
target,
|
||||
ShiftData.new(target.shiftStartPoint, target.position.clone())
|
||||
)
|
||||
);
|
||||
}
|
||||
target.shiftStartPoint = null;
|
||||
});
|
||||
}
|
||||
this.clearCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理缓存
|
||||
*/
|
||||
clearCache() {
|
||||
// 移除吸附图形
|
||||
this.absorbablePositions = [];
|
||||
this.apContainer.removeChildren();
|
||||
}
|
||||
|
||||
onGraphicSelectedChange(g: DisplayObject, selected: boolean) {
|
||||
let br = g.getAssistantAppend<BoundsGraphic>(BoundsGraphic.Name);
|
||||
if (!br) {
|
||||
// 绘制辅助包围框
|
||||
br = new BoundsGraphic(g);
|
||||
}
|
||||
|
||||
if (selected) {
|
||||
if (br) {
|
||||
br.redraw();
|
||||
br.visible = true;
|
||||
}
|
||||
} else {
|
||||
if (br) {
|
||||
br.visible = false;
|
||||
}
|
||||
}
|
||||
if (g.scalable || g.rotatable) {
|
||||
// 缩放点
|
||||
let sp = g.getAssistantAppend<TransformPoints>(TransformPoints.Name);
|
||||
if (!sp) {
|
||||
sp = new TransformPoints(g);
|
||||
}
|
||||
if (selected) {
|
||||
sp.update();
|
||||
sp.visible = true;
|
||||
} else {
|
||||
sp.visible = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// onGraphicChildSelectedChange(child: DisplayObject, selected: boolean) {
|
||||
// let br = child.getAssistantAppend<BoundsGraphic>(BoundsGraphic.Name);
|
||||
// if (!br) {
|
||||
// // 绘制辅助包围框
|
||||
// br = new BoundsGraphic(child);
|
||||
// }
|
||||
// if (selected) {
|
||||
// br.redraw();
|
||||
// br.visible = true;
|
||||
// } else {
|
||||
// br.visible = false;
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩放、旋转辅助
|
||||
*/
|
||||
export 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: DisplayObject;
|
||||
|
||||
ltScalePoint: DraggablePoint;
|
||||
ltLocal: Point = new Point();
|
||||
tScalePoint: DraggablePoint;
|
||||
tLocal: Point = new Point();
|
||||
tCanvas: Point = new Point();
|
||||
rtScalePoint: DraggablePoint;
|
||||
rtLocal: Point = new Point();
|
||||
rScalePoint: DraggablePoint;
|
||||
rLocal: Point = new Point();
|
||||
rbScalePoint: DraggablePoint;
|
||||
rbLocal: Point = new Point();
|
||||
bScalePoint: DraggablePoint;
|
||||
bLocal: Point = new Point();
|
||||
lbScalePoint: DraggablePoint;
|
||||
lbLocal: Point = new Point();
|
||||
lScalePoint: DraggablePoint;
|
||||
lLocal: Point = new Point();
|
||||
originScale: Point = new Point();
|
||||
scalePivot: Point = new Point();
|
||||
|
||||
/**
|
||||
* 旋转拖拽点
|
||||
*/
|
||||
rotatePoint: DraggablePoint;
|
||||
/**
|
||||
* 旋转中心坐标
|
||||
*/
|
||||
rotatePivot: Point;
|
||||
/**
|
||||
* 起始旋转坐标
|
||||
*/
|
||||
rotateLastPoint: Point;
|
||||
/**
|
||||
* 起始图形角度
|
||||
*/
|
||||
startAngle = 0;
|
||||
/**
|
||||
* 当前角度信息文本辅助
|
||||
*/
|
||||
angleAssistantText: VectorText;
|
||||
/**
|
||||
* 旋转角度步长
|
||||
*/
|
||||
angleStep = 1;
|
||||
/**
|
||||
* 修改旋转步长键盘监听
|
||||
*/
|
||||
rotateAngleStepKeyListeners: KeyListener[] = [];
|
||||
|
||||
constructor(obj: DisplayObject) {
|
||||
super();
|
||||
this.obj = obj;
|
||||
this.name = TransformPoints.Name;
|
||||
|
||||
this.angleAssistantText = new VectorText('');
|
||||
this.angleAssistantText.setVectorFontSize(16);
|
||||
this.angleAssistantText.anchor.set(0.5);
|
||||
|
||||
// 创建缩放拖拽点
|
||||
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 as Container, (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);
|
||||
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 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: () => {
|
||||
// console.log('修改角度step');
|
||||
this.angleStep = i;
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
this.obj.addAssistantAppend(this);
|
||||
}
|
||||
|
||||
onObjTransformStart() {
|
||||
this.visible = false;
|
||||
}
|
||||
onObjTransformEnd() {
|
||||
this.update();
|
||||
this.visible = true;
|
||||
}
|
||||
onGraphicRepaint() {
|
||||
if (this.visible) {
|
||||
this.update();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 旋转开始
|
||||
* @param de
|
||||
*/
|
||||
onRotateStart(de: GraphicTransformEvent) {
|
||||
this.hideAll();
|
||||
const assistantPoint = this.obj.localToCanvasPoint(this.obj.pivot);
|
||||
this.rotatePivot.copyFrom(assistantPoint);
|
||||
this.rotateLastPoint.copyFrom(de.target.position);
|
||||
this.startAngle = this.obj.angle;
|
||||
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);
|
||||
}
|
||||
updateAngleAssistantText(de: GraphicTransformEvent) {
|
||||
this.angleAssistantText.text = this.obj.angle + '°';
|
||||
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
|
||||
*/
|
||||
onRotateMove(de: GraphicTransformEvent) {
|
||||
// 旋转角度计算逻辑:取锚点y负方向一点作为旋转点,求旋转点和锚点所形成的直线与x轴角度,此角度+90°即为最终旋转角度,再将旋转角度限制到(-180,180]之间
|
||||
let angle = angleToAxisx(this.rotatePivot, de.target.position);
|
||||
angle = Math.floor(angle / this.angleStep) * this.angleStep;
|
||||
const parentAngle = this.obj.parent.worldAngle;
|
||||
angle = (angle + 90 - parentAngle) % 360;
|
||||
if (angle > 180) {
|
||||
angle = angle - 360;
|
||||
}
|
||||
this.obj.angle = angle;
|
||||
this.updateAngleAssistantText(de);
|
||||
// this.obj.emit('rotatemove', this.obj);
|
||||
}
|
||||
/**
|
||||
* 旋转结束
|
||||
* @param de
|
||||
*/
|
||||
onRotateEnd() {
|
||||
this.showAll();
|
||||
this.obj.getCanvas().removeAssistantAppends(this.angleAssistantText);
|
||||
this.rotateAngleStepKeyListeners.forEach((listener) =>
|
||||
this.obj.getGraphicApp().removeKeyboardListener(listener)
|
||||
);
|
||||
this.obj.emit('transformend', GraphicTransformEvent.rotate(this.obj));
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩放开始
|
||||
*/
|
||||
onScaleDragStart() {
|
||||
this.hideAll();
|
||||
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))
|
||||
);
|
||||
this.tLocal.copyFrom(calculateLineMidpoint(p0, p1));
|
||||
this.rtLocal.copyFrom(p1);
|
||||
this.rLocal.copyFrom(calculateLineMidpoint(p1, p2));
|
||||
this.rbLocal.copyFrom(p2);
|
||||
this.bLocal.copyFrom(calculateLineMidpoint(p2, p3));
|
||||
this.lbLocal.copyFrom(p3);
|
||||
this.lLocal.copyFrom(calculateLineMidpoint(p0, p3));
|
||||
this.originScale = this.obj.scale.clone();
|
||||
this.obj.emit('transformstart', GraphicTransformEvent.scale(this.obj));
|
||||
}
|
||||
|
||||
onScaleDragMove(e: GraphicTransformEvent) {
|
||||
// 缩放计算逻辑:共8个方向缩放点,根据所拖拽的方向:
|
||||
// 1,计算缩放为1时的此点在拖拽开始时的位置到锚点x、y距离,
|
||||
// 2,计算拖拽点的当前位置到锚点的x、y方向距离,
|
||||
// PS:以上两个计算都是在local(也就是图形对象本地)坐标系,
|
||||
// 用当前距离除以原始距离即为缩放比例
|
||||
const defaultScale = new Point(1, 1);
|
||||
let originWidth = 0;
|
||||
let originHeight = 0;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
this.obj.scale.copyFrom(defaultScale);
|
||||
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);
|
||||
originHeight = Math.abs(this.ltLocal.y - this.scalePivot.y);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (e.target == this.tScalePoint) {
|
||||
// 上
|
||||
originHeight = Math.abs(this.tLocal.y - this.scalePivot.y);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (e.target == this.rtScalePoint) {
|
||||
// 右上
|
||||
originWidth = Math.abs(this.rtLocal.x - this.scalePivot.x);
|
||||
originHeight = Math.abs(this.rtLocal.y - this.scalePivot.y);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (e.target == this.rScalePoint) {
|
||||
// 右
|
||||
originWidth = Math.abs(this.rLocal.x - this.scalePivot.x);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
} else if (e.target == this.rbScalePoint) {
|
||||
// 右下
|
||||
originWidth = Math.abs(this.rbLocal.x - this.scalePivot.x);
|
||||
originHeight = Math.abs(this.rbLocal.y - this.scalePivot.y);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (e.target == this.bScalePoint) {
|
||||
// 下
|
||||
originHeight = Math.abs(this.bLocal.y - this.scalePivot.y);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else if (e.target == this.lbScalePoint) {
|
||||
// 左下
|
||||
originWidth = Math.abs(this.lbLocal.x - this.scalePivot.x);
|
||||
originHeight = Math.abs(this.lbLocal.y - this.scalePivot.y);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
height = Math.abs(point.y - this.scalePivot.y);
|
||||
} else {
|
||||
// 左
|
||||
originWidth = Math.abs(this.lLocal.x - this.scalePivot.x);
|
||||
width = Math.abs(point.x - this.scalePivot.x);
|
||||
}
|
||||
// 计算缩放比例,并根据是否保持纵横比两种情况进行缩放处理
|
||||
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) {
|
||||
max = sy;
|
||||
} else if (originHeight == 0) {
|
||||
max = sx;
|
||||
}
|
||||
this.obj.scale.set(max, max);
|
||||
} else {
|
||||
this.obj.scale.x = sx;
|
||||
this.obj.scale.y = sy;
|
||||
}
|
||||
}
|
||||
|
||||
onScaleDragEnd() {
|
||||
this.showAll();
|
||||
this.obj.emit('transformend', GraphicTransformEvent.scale(this.obj));
|
||||
}
|
||||
|
||||
hideOthers(dg: DisplayObject) {
|
||||
this.children.forEach((child) => {
|
||||
if (child.name !== dg.name) {
|
||||
child.visible = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
hideAll() {
|
||||
this.children.forEach((child) => (child.visible = false));
|
||||
}
|
||||
|
||||
showAll() {
|
||||
this.update();
|
||||
this.children.forEach((child) => (child.visible = true));
|
||||
}
|
||||
|
||||
getObjBounds(): { width: number; height: number } {
|
||||
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
|
||||
*/
|
||||
update() {
|
||||
if (this.obj.scalable) {
|
||||
this.updateScalePoints();
|
||||
}
|
||||
if (this.obj.rotatable) {
|
||||
this.updateRotatePoint();
|
||||
}
|
||||
}
|
||||
|
||||
updateRotatePoint() {
|
||||
const rect = this.obj.getLocalBounds();
|
||||
const lp = this.obj.pivot.clone();
|
||||
const dy = 10 / this.obj.scale.y;
|
||||
lp.y = rect.y - dy;
|
||||
const p = this.obj.localToCanvasPoint(lp);
|
||||
this.rotatePoint.position.copyFrom(p);
|
||||
}
|
||||
|
||||
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]);
|
||||
this.rScalePoint.position.copyFrom(
|
||||
calculateLineMidpoint(points[1], points[2])
|
||||
);
|
||||
this.rbScalePoint.position.copyFrom(points[2]);
|
||||
this.bScalePoint.position.copyFrom(
|
||||
calculateLineMidpoint(points[2], points[3])
|
||||
);
|
||||
this.lbScalePoint.position.copyFrom(points[3]);
|
||||
this.lScalePoint.position.copyFrom(
|
||||
calculateLineMidpoint(points[3], points[0])
|
||||
);
|
||||
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';
|
||||
this.tScalePoint.cursor = 'n-resize';
|
||||
this.rtScalePoint.cursor = 'ne-resize';
|
||||
this.rScalePoint.cursor = 'e-resize';
|
||||
this.rbScalePoint.cursor = 'se-resize';
|
||||
this.bScalePoint.cursor = 's-resize';
|
||||
this.lbScalePoint.cursor = 'sw-resize';
|
||||
this.lScalePoint.cursor = 'w-resize';
|
||||
} else if (
|
||||
(angle >= 22.5 && angle <= 67.5) ||
|
||||
(angle360 >= 180 + 22.5 && angle360 <= 180 + 67.5)
|
||||
) {
|
||||
this.ltScalePoint.cursor = 'n-resize';
|
||||
this.tScalePoint.cursor = 'ne-resize';
|
||||
this.rtScalePoint.cursor = 'e-resize';
|
||||
this.rScalePoint.cursor = 'se-resize';
|
||||
this.rbScalePoint.cursor = 's-resize';
|
||||
this.bScalePoint.cursor = 'sw-resize';
|
||||
this.lbScalePoint.cursor = 'w-resize';
|
||||
this.lScalePoint.cursor = 'nw-resize';
|
||||
} else if (
|
||||
(angle >= 67.5 && angle < 112.5) ||
|
||||
(angle360 >= 180 + 67.5 && angle360 <= 180 + 112.5)
|
||||
) {
|
||||
this.ltScalePoint.cursor = 'ne-resize';
|
||||
this.tScalePoint.cursor = 'e-resize';
|
||||
this.rtScalePoint.cursor = 'se-resize';
|
||||
this.rScalePoint.cursor = 's-resize';
|
||||
this.rbScalePoint.cursor = 'sw-resize';
|
||||
this.bScalePoint.cursor = 'w-resize';
|
||||
this.lbScalePoint.cursor = 'nw-resize';
|
||||
this.lScalePoint.cursor = 'n-resize';
|
||||
} else {
|
||||
this.ltScalePoint.cursor = 'e-resize';
|
||||
this.tScalePoint.cursor = 'se-resize';
|
||||
this.rtScalePoint.cursor = 's-resize';
|
||||
this.rScalePoint.cursor = 'sw-resize';
|
||||
this.rbScalePoint.cursor = 'w-resize';
|
||||
this.bScalePoint.cursor = 'nw-resize';
|
||||
this.lbScalePoint.cursor = 'n-resize';
|
||||
this.lScalePoint.cursor = 'ne-resize';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 包围盒矩形图形,现使用外边框转画布多边形实现
|
||||
*/
|
||||
export class BoundsGraphic extends Graphics {
|
||||
static Name = '_BoundsRect';
|
||||
static BoundsLineStyle = {
|
||||
width: 1,
|
||||
color: 0x29b6f2,
|
||||
alpha: 1,
|
||||
};
|
||||
obj: DisplayObject;
|
||||
debouncedRedraw: DebouncedFunction<() => void>;
|
||||
constructor(graphic: DisplayObject) {
|
||||
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 as Container, (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(): void {
|
||||
this.visible = false;
|
||||
}
|
||||
onObjTransformEnd(): void {
|
||||
this.redraw();
|
||||
this.visible = true;
|
||||
}
|
||||
|
||||
onGraphicRepaint(): void {
|
||||
if (this.visible) {
|
||||
this.redraw();
|
||||
}
|
||||
}
|
||||
|
||||
destroy(options?: boolean | IDestroyOptions | undefined): void {
|
||||
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;
|
||||
}
|
||||
}
|
489
src/jl-graphic/plugins/InteractionPlugin.ts
Normal file
489
src/jl-graphic/plugins/InteractionPlugin.ts
Normal file
@ -0,0 +1,489 @@
|
||||
import {
|
||||
DisplayObject,
|
||||
FederatedMouseEvent,
|
||||
FederatedPointerEvent,
|
||||
Point,
|
||||
} from 'pixi.js';
|
||||
import { IGraphicAppConfig, IGraphicScene } from '../app/JlGraphicApp';
|
||||
import { JlGraphic } from '../core/JlGraphic';
|
||||
|
||||
export 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 abstract class InteractionPluginBase implements InteractionPlugin {
|
||||
readonly _type: string;
|
||||
name: string; // 唯一标识
|
||||
app: IGraphicScene;
|
||||
_pause: boolean;
|
||||
|
||||
constructor(app: IGraphicScene, name: string, type: string) {
|
||||
this._type = type;
|
||||
this.app = app;
|
||||
this.name = name;
|
||||
this._pause = true;
|
||||
app.registerInteractionPlugin(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复
|
||||
*/
|
||||
resume(): void {
|
||||
this.bind();
|
||||
this._pause = false;
|
||||
this.app.emit('interaction-plugin-resume', this);
|
||||
}
|
||||
/**
|
||||
* 停止
|
||||
*/
|
||||
pause(): void {
|
||||
this.unbind();
|
||||
this._pause = true;
|
||||
this.app.emit('interaction-plugin-pause', this);
|
||||
}
|
||||
|
||||
abstract bind(): void;
|
||||
abstract unbind(): void;
|
||||
/**
|
||||
* 是否生效
|
||||
*/
|
||||
isActive(): boolean {
|
||||
return !this._pause;
|
||||
}
|
||||
isGraphicPlugin(): boolean {
|
||||
return this._type === InteractionPluginType.Graphic;
|
||||
}
|
||||
isAppPlugin(): boolean {
|
||||
return this._type === InteractionPluginType.App;
|
||||
}
|
||||
isOtherPlugin(): boolean {
|
||||
return this._type === InteractionPluginType.Other;
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class OtherInteractionPlugin extends InteractionPluginBase {
|
||||
constructor(app: IGraphicScene, name: string) {
|
||||
super(app, name, InteractionPluginType.Other);
|
||||
}
|
||||
}
|
||||
|
||||
export 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
|
||||
) {
|
||||
this.app = app;
|
||||
this.type = type;
|
||||
this.target = target;
|
||||
this.original = original;
|
||||
this.start = start;
|
||||
}
|
||||
|
||||
public get isMouse(): boolean {
|
||||
return this.original.pointerType === 'mouse';
|
||||
}
|
||||
|
||||
public get isLeftButton(): boolean {
|
||||
return (
|
||||
this.isMouse &&
|
||||
((this.original.button === -1 && this.original.buttons === 1) ||
|
||||
(this.original.button === 0 && this.original.buttons === 0))
|
||||
);
|
||||
}
|
||||
|
||||
public get isRightButton(): boolean {
|
||||
return (
|
||||
this.isMouse &&
|
||||
((this.original.button === -1 && this.original.buttons === 2) ||
|
||||
(this.original.button === 2 && this.original.buttons === 0))
|
||||
);
|
||||
}
|
||||
|
||||
public get isMiddleButton(): boolean {
|
||||
return (
|
||||
this.isMouse &&
|
||||
((this.original.button === -1 && this.original.buttons === 4) ||
|
||||
(this.original.button === 1 && this.original.buttons === 0))
|
||||
);
|
||||
}
|
||||
|
||||
public get isTouch(): boolean {
|
||||
return this.original.pointerType === 'touch';
|
||||
}
|
||||
|
||||
/**
|
||||
* 终点坐标(画布坐标)
|
||||
*/
|
||||
public get end(): Point {
|
||||
return this.app.toCanvasCoordinates(this.original.global);
|
||||
}
|
||||
|
||||
public get dx(): number {
|
||||
const move = this.original.movement;
|
||||
return move.x / this.app.viewport.scaled;
|
||||
}
|
||||
|
||||
public get dy(): number {
|
||||
const move = this.original.movement;
|
||||
return move.y / this.app.viewport.scaled;
|
||||
}
|
||||
|
||||
public get dsx(): number {
|
||||
return this.end.x - this.start.x;
|
||||
}
|
||||
|
||||
public get dsy(): number {
|
||||
return this.end.y - this.start.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为目标对象的位移距离
|
||||
*/
|
||||
toTargetShiftLen(target: DisplayObject): { dx: number; dy: number } {
|
||||
const sl = target.canvasToLocalPoint(this.start);
|
||||
const el = target.canvasToLocalPoint(this.end);
|
||||
return { dx: el.x - sl.x, dy: el.y - sl.y };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拖拽操作插件
|
||||
*/
|
||||
export class DragPlugin extends OtherInteractionPlugin {
|
||||
static Name = '__drag_operation_plugin';
|
||||
private threshold = 3;
|
||||
target: DisplayObject | null = null;
|
||||
start: Point | null = null;
|
||||
startClientPoint: Point | null = null;
|
||||
drag = false;
|
||||
constructor(app: IGraphicScene) {
|
||||
super(app, DragPlugin.Name);
|
||||
app.on('options-update', (options: IGraphicAppConfig) => {
|
||||
if (options.threshold !== undefined) {
|
||||
this.threshold = options.threshold;
|
||||
}
|
||||
});
|
||||
}
|
||||
static new(app: IGraphicScene) {
|
||||
return new DragPlugin(app);
|
||||
}
|
||||
bind(): void {
|
||||
const canvas = this.app.canvas;
|
||||
canvas.on('pointerdown', this.onPointerDown, this);
|
||||
}
|
||||
unbind(): void {
|
||||
const canvas = this.app.canvas;
|
||||
canvas.off('pointerdown', this.onPointerDown, this);
|
||||
canvas.off('pointerup', this.onPointerUp, this);
|
||||
canvas.off('pointerupoutside', this.onPointerUp, this);
|
||||
}
|
||||
onPointerDown(e: FederatedPointerEvent) {
|
||||
this.target = e.target as DisplayObject;
|
||||
this.start = this.app.toCanvasCoordinates(e.global);
|
||||
this.startClientPoint = e.global.clone();
|
||||
const canvas = this.app.canvas;
|
||||
canvas.on('pointermove', this.onPointerMove, this);
|
||||
canvas.on('pointerup', this.onPointerUp, this);
|
||||
canvas.on('pointerupoutside', this.onPointerUp, this);
|
||||
}
|
||||
onPointerMove(e: FederatedPointerEvent) {
|
||||
if (this.start && this.startClientPoint) {
|
||||
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)
|
||||
);
|
||||
this.drag = true;
|
||||
}
|
||||
|
||||
// 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)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
);
|
||||
} else if (this.target && this.start && !this.drag) {
|
||||
// this.target.emit('click', this.target);
|
||||
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) {
|
||||
graphic.emit('_rightclick', e);
|
||||
}
|
||||
} else if (ade.isLeftButton) {
|
||||
this.target.emit('_leftclick', e);
|
||||
if (graphic != null) {
|
||||
graphic.emit('_leftclick', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
/**
|
||||
* 清理缓存
|
||||
*/
|
||||
clearCache() {
|
||||
this.drag = false;
|
||||
this.start = null;
|
||||
this.startClientPoint = null;
|
||||
this.target = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 视口移动插件
|
||||
*/
|
||||
export class ViewportMovePlugin extends OtherInteractionPlugin {
|
||||
static Name = '__viewport_move_plugin';
|
||||
|
||||
static MoveInterval = 20; // 移动间隔,单位ms
|
||||
static TriggerRange = 100; // 边界触发范围,单位px
|
||||
static DefaultMoveSpeed = 200 / ViewportMovePlugin.MoveInterval; // 默认移动速度
|
||||
|
||||
moveHandler: NodeJS.Timeout | null = null;
|
||||
moveSpeedx = 0;
|
||||
moveSpeedy = 0;
|
||||
|
||||
constructor(app: IGraphicScene) {
|
||||
super(app, ViewportMovePlugin.Name);
|
||||
}
|
||||
|
||||
static new(app: IGraphicScene): ViewportMovePlugin {
|
||||
return new ViewportMovePlugin(app);
|
||||
}
|
||||
pause(): void {
|
||||
super.pause();
|
||||
this.stopMove();
|
||||
}
|
||||
bind(): void {
|
||||
this.app.canvas.on('pointermove', this.viewportMove, this);
|
||||
}
|
||||
|
||||
unbind(): void {
|
||||
this.app.canvas.off('pointermove', this.viewportMove, this);
|
||||
}
|
||||
|
||||
startMove(moveSpeedx: number, moveSpeedy: number) {
|
||||
this.moveSpeedx = moveSpeedx;
|
||||
this.moveSpeedy = moveSpeedy;
|
||||
if (this.moveHandler == null) {
|
||||
const viewport = this.app.viewport;
|
||||
this.moveHandler = setInterval(() => {
|
||||
viewport.moveCorner(
|
||||
viewport.corner.x + this.moveSpeedx,
|
||||
viewport.corner.y + this.moveSpeedy
|
||||
);
|
||||
}, ViewportMovePlugin.MoveInterval);
|
||||
}
|
||||
}
|
||||
|
||||
stopMove() {
|
||||
if (this.moveHandler != null) {
|
||||
clearInterval(this.moveHandler);
|
||||
this.moveHandler = null;
|
||||
this.app.canvas.cursor = 'auto';
|
||||
}
|
||||
}
|
||||
|
||||
private calculateBoundaryMoveSpeed(sp: Point): {
|
||||
moveSpeedx: number;
|
||||
moveSpeedy: number;
|
||||
} {
|
||||
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);
|
||||
} else if (sp.x > viewport.screenWidth - range) {
|
||||
moveSpeedx = this.calculateMoveSpeed(sp.x + range - viewport.screenWidth);
|
||||
} else {
|
||||
moveSpeedx = 0;
|
||||
}
|
||||
if (sp.y < range) {
|
||||
moveSpeedy = this.calculateMoveSpeed(sp.y - range);
|
||||
} else if (sp.y > viewport.screenHeight - range) {
|
||||
moveSpeedy = this.calculateMoveSpeed(
|
||||
sp.y + range - viewport.screenHeight
|
||||
);
|
||||
} else {
|
||||
moveSpeedy = 0;
|
||||
}
|
||||
return { moveSpeedx, moveSpeedy };
|
||||
}
|
||||
|
||||
calculateMoveSpeed(dd: number): number {
|
||||
return (
|
||||
(dd / ViewportMovePlugin.TriggerRange) *
|
||||
ViewportMovePlugin.DefaultMoveSpeed
|
||||
);
|
||||
}
|
||||
|
||||
viewportMove(e: FederatedMouseEvent) {
|
||||
const sp = e.global;
|
||||
const { moveSpeedx, moveSpeedy } = this.calculateBoundaryMoveSpeed(sp);
|
||||
if (moveSpeedx == 0 && moveSpeedy == 0) {
|
||||
this.app.canvas.cursor = 'auto';
|
||||
this.stopMove();
|
||||
} else {
|
||||
this.app.canvas.cursor = 'grab';
|
||||
this.startMove(moveSpeedx, moveSpeedy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用交互插件,同时只能生效一个
|
||||
*/
|
||||
export abstract class AppInteractionPlugin extends InteractionPluginBase {
|
||||
constructor(name: string, app: IGraphicScene) {
|
||||
super(app, name, InteractionPluginType.App);
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复,app交互插件同时只能生效一个
|
||||
*/
|
||||
resume(): void {
|
||||
this.app.pauseAppInteractionPlugins();
|
||||
super.resume();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图形交互插件,可同时生效
|
||||
*/
|
||||
export abstract class GraphicInteractionPlugin<G extends JlGraphic>
|
||||
implements InteractionPlugin
|
||||
{
|
||||
readonly _type = InteractionPluginType.Graphic;
|
||||
app: IGraphicScene;
|
||||
name: string; // 唯一标识
|
||||
_pause: boolean;
|
||||
constructor(name: string, app: IGraphicScene) {
|
||||
this.app = app;
|
||||
this.name = name;
|
||||
this._pause = true;
|
||||
app.registerInteractionPlugin(this);
|
||||
this.resume();
|
||||
// 新增的图形对象绑定
|
||||
this.app.on('graphicstored', (g) => {
|
||||
if (this.isActive()) {
|
||||
this.binds(this.filter(g));
|
||||
}
|
||||
});
|
||||
this.app.on('graphicdeleted', (g) => {
|
||||
if (this.isActive()) {
|
||||
this.unbinds(this.filter(g));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
isActive(): boolean {
|
||||
return !this._pause;
|
||||
}
|
||||
isAppPlugin(): boolean {
|
||||
return false;
|
||||
}
|
||||
isOtherPlugin(): boolean {
|
||||
return false;
|
||||
}
|
||||
isGraphicPlugin(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
resume(): void {
|
||||
const list = this.filter(...this.app.queryStore.getAllGraphics());
|
||||
this.binds(list);
|
||||
this._pause = false;
|
||||
this.app.emit('interaction-plugin-resume', this);
|
||||
}
|
||||
pause(): void {
|
||||
const list = this.filter(...this.app.queryStore.getAllGraphics());
|
||||
this.unbinds(list);
|
||||
this._pause = true;
|
||||
this.app.emit('interaction-plugin-pause', this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤需要的图形对象
|
||||
*/
|
||||
abstract filter(...grahpics: JlGraphic[]): G[] | undefined;
|
||||
|
||||
binds(list?: G[]): void {
|
||||
if (list) {
|
||||
list.forEach((g) => this.bind(g));
|
||||
}
|
||||
}
|
||||
unbinds(list?: G[]): void {
|
||||
if (list) {
|
||||
list.forEach((g) => this.unbind(g));
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 绑定图形对象的交互处理
|
||||
* @param g 图形对象
|
||||
*/
|
||||
abstract bind(g: G): void;
|
||||
/**
|
||||
* 取消图形对象的交互处理
|
||||
* @param g 图形对象
|
||||
*/
|
||||
abstract unbind(g: G): void;
|
||||
}
|
351
src/jl-graphic/plugins/KeyboardPlugin.ts
Normal file
351
src/jl-graphic/plugins/KeyboardPlugin.ts
Normal file
@ -0,0 +1,351 @@
|
||||
import { IGraphicApp } from '../app/JlGraphicApp';
|
||||
|
||||
let target: Node | undefined;
|
||||
|
||||
export class GlobalKeyboardHelper {
|
||||
appKeyboardPluginMap: JlGraphicAppKeyboardPlugin[] = [];
|
||||
|
||||
constructor() {
|
||||
window.onkeydown = (e: KeyboardEvent) => {
|
||||
this.appKeyboardPluginMap.forEach((plugin) => {
|
||||
const listenerMap = plugin.getKeyListener(e);
|
||||
listenerMap?.forEach((listener) => {
|
||||
if (listener.global) {
|
||||
listener.press(e, plugin.app);
|
||||
}
|
||||
});
|
||||
});
|
||||
if (e.ctrlKey) {
|
||||
if (e.code == 'KeyS') {
|
||||
// 屏蔽全局Ctrl+S保存操作
|
||||
// console.log('屏蔽全局Ctrl+S')
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (target && target.nodeName == 'CANVAS') {
|
||||
// 事件的目标是画布时,屏蔽总的键盘操作操作
|
||||
if (e.ctrlKey) {
|
||||
if (e.code == 'KeyA' || e.code == 'KeyS') {
|
||||
// 屏蔽Canvas上的Ctrl+A、Ctrl+S操作
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
window.onkeyup = (e: KeyboardEvent) => {
|
||||
this.appKeyboardPluginMap.forEach((plugin) => {
|
||||
const listenerMap = plugin.getKeyListener(e);
|
||||
listenerMap?.forEach((listener) => {
|
||||
if (listener.global) {
|
||||
listener.release(e, plugin.app);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
registerGAKPlugin(plugin: JlGraphicAppKeyboardPlugin) {
|
||||
if (!this.appKeyboardPluginMap.find((pg) => pg == plugin)) {
|
||||
this.appKeyboardPluginMap.push(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
removeGAKPlugin(plugin: JlGraphicAppKeyboardPlugin) {
|
||||
const index = this.appKeyboardPluginMap.findIndex((pg) => pg == plugin);
|
||||
if (index >= 0) {
|
||||
this.appKeyboardPluginMap.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const GlobalKeyboardPlugin = new GlobalKeyboardHelper();
|
||||
|
||||
export class JlGraphicAppKeyboardPlugin {
|
||||
app: IGraphicApp;
|
||||
/**
|
||||
* 结构为Map<key.code|key.key|key.keyCode, Map<KeyListener.identifier, KeyListener>>
|
||||
*/
|
||||
keyListenerMap: Map<number | string, Map<string, KeyListener>> = new Map<
|
||||
number | string,
|
||||
Map<string, KeyListener>
|
||||
>(); // 键值监听map
|
||||
keyListenerStackMap: Map<string, KeyListener[]> = new Map<
|
||||
string,
|
||||
KeyListener[]
|
||||
>(); // 键值监听栈(多次注册相同的监听会把之前注册的监听器入栈,移除最新的监听会从栈中弹出一个作为指定事件监听处理器)
|
||||
|
||||
constructor(app: IGraphicApp) {
|
||||
this.app = app;
|
||||
GlobalKeyboardPlugin.registerGAKPlugin(this);
|
||||
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);
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
const keyupHandle = (e: KeyboardEvent) => {
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', onMouseUpdateTarget, false);
|
||||
document.addEventListener('keydown', keydownHandle, false);
|
||||
document.addEventListener('keyup', keyupHandle, false);
|
||||
this.app.on('destroy', () => {
|
||||
document.removeEventListener('mousedown', onMouseUpdateTarget, false);
|
||||
document.removeEventListener('keydown', keydownHandle, false);
|
||||
document.removeEventListener('keyup', keyupHandle, false);
|
||||
});
|
||||
}
|
||||
|
||||
private getOrInit(key: string | number): Map<string, KeyListener> {
|
||||
let map = this.keyListenerMap.get(key);
|
||||
if (map === undefined) {
|
||||
map = new Map<string, KeyListener>();
|
||||
this.keyListenerMap.set(key, map);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private getOrInitStack(key: string): KeyListener[] {
|
||||
let stack = this.keyListenerStackMap.get(key);
|
||||
if (stack === undefined) {
|
||||
stack = [];
|
||||
this.keyListenerStackMap.set(key, stack);
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册按键监听,若有旧的,旧的入栈
|
||||
* @param keyListener
|
||||
*/
|
||||
addKeyListener(keyListener: KeyListener) {
|
||||
const map = this.getOrInit(keyListener.value);
|
||||
// 查询是否有旧的监听,若有入栈
|
||||
const old = map.get(keyListener.identifier);
|
||||
if (old) {
|
||||
const stack = this.getOrInitStack(keyListener.identifier);
|
||||
stack.push(old);
|
||||
}
|
||||
map.set(keyListener.identifier, keyListener);
|
||||
// console.log(this.getAllListenedKeys());
|
||||
}
|
||||
/**
|
||||
* 移除按键监听,若是当前注册的监听,尝试从栈中取出作为按键监听器,若是旧的,则同时移除栈中的监听
|
||||
* @param keyListener
|
||||
*/
|
||||
removeKeyListener(keyListener: KeyListener) {
|
||||
keyListener.onRemove();
|
||||
const map = this.getOrInit(keyListener.value);
|
||||
const old = map.get(keyListener.identifier);
|
||||
map.delete(keyListener.identifier);
|
||||
const stack = this.getOrInitStack(keyListener.identifier);
|
||||
if (old && old === keyListener) {
|
||||
// 是旧的监听
|
||||
const listener = stack.pop();
|
||||
if (listener) {
|
||||
map.set(keyListener.identifier, listener);
|
||||
}
|
||||
} else {
|
||||
// 移除栈中的
|
||||
const index = stack.findIndex((ls) => ls === keyListener);
|
||||
if (index >= 0) {
|
||||
stack.splice(index, 1);
|
||||
}
|
||||
}
|
||||
// console.log(this);
|
||||
}
|
||||
|
||||
getKeyListenerBy(key: string | number): Map<string, KeyListener> | undefined {
|
||||
return this.keyListenerMap.get(key);
|
||||
}
|
||||
|
||||
getKeyListener(e: KeyboardEvent): Map<string, KeyListener> | undefined {
|
||||
return (
|
||||
this.getKeyListenerBy(e.key) ||
|
||||
this.getKeyListenerBy(e.code) ||
|
||||
this.getKeyListenerBy(e.keyCode)
|
||||
);
|
||||
}
|
||||
|
||||
isKeyListened(key: string | number): boolean {
|
||||
return this.getOrInit(key).size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有注册监听的键值(组合键)
|
||||
*/
|
||||
getAllListenedKeys(): string[] {
|
||||
const keys: string[] = [];
|
||||
this.keyListenerMap.forEach((v) =>
|
||||
v.forEach((_listener, ck) => keys.push(ck))
|
||||
);
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
|
||||
type KeyboardKeyHandler = (e: KeyboardEvent, app: IGraphicApp) => void;
|
||||
|
||||
export enum CombinationKey {
|
||||
Ctrl = 'Ctrl',
|
||||
Alt = 'Alt',
|
||||
Shift = 'Shift',
|
||||
}
|
||||
export interface KeyListenerOptions {
|
||||
// 具体的键值,可以是key/code/keycode(keycode已经弃用,建议优先使用key或code),例如:KeyA/(a/A)分别表示键盘A建,其中KeyA为键盘事件的code字段,a/A为键盘事件的key字段
|
||||
value: string | number;
|
||||
// 组合键
|
||||
combinations?: CombinationKey[];
|
||||
// 是否监听全局,为false则只在画布为焦点时才处理
|
||||
global?: boolean;
|
||||
// 按下操作处理
|
||||
onPress?: KeyboardKeyHandler;
|
||||
// 按下操作是否每次触发,默认一次
|
||||
pressTriggerAsOriginalEvent?: boolean;
|
||||
// 释放/抬起操作处理
|
||||
onRelease?: KeyboardKeyHandler;
|
||||
}
|
||||
|
||||
export interface ICompleteKeyListenerOptions {
|
||||
// 具体的键值,可以是key/code/keycode(keycode已经弃用,建议优先使用key或code),例如:KeyA/(a/A)分别表示键盘A建,其中KeyA为键盘事件的code字段,a/A为键盘事件的key字段
|
||||
value: string | number;
|
||||
// 组合键
|
||||
combinations: CombinationKey[];
|
||||
// 是否监听全局,为false则只在画布为焦点时才处理
|
||||
global: boolean;
|
||||
// 按下操作处理
|
||||
onPress?: KeyboardKeyHandler;
|
||||
pressTriggerAsOriginalEvent: boolean;
|
||||
// 释放/抬起操作处理
|
||||
onRelease?: KeyboardKeyHandler;
|
||||
}
|
||||
|
||||
const DefaultKeyListenerOptions: ICompleteKeyListenerOptions = {
|
||||
value: '',
|
||||
combinations: [],
|
||||
global: false,
|
||||
onPress: undefined,
|
||||
pressTriggerAsOriginalEvent: false,
|
||||
onRelease: undefined,
|
||||
};
|
||||
|
||||
export class KeyListener {
|
||||
// value 支持keyCode,key,code三种值
|
||||
readonly options: ICompleteKeyListenerOptions;
|
||||
private isPress = false;
|
||||
|
||||
constructor(options: KeyListenerOptions) {
|
||||
this.options = Object.assign({}, DefaultKeyListenerOptions, options);
|
||||
}
|
||||
|
||||
static create(options: KeyListenerOptions): KeyListener {
|
||||
return new KeyListener(options);
|
||||
}
|
||||
|
||||
public get value(): string | number {
|
||||
return this.options.value;
|
||||
}
|
||||
|
||||
public get combinations(): string[] {
|
||||
return this.options.combinations;
|
||||
}
|
||||
|
||||
public get identifier(): string {
|
||||
return this.options.combinations.join('+') + '+' + this.options.value;
|
||||
}
|
||||
|
||||
public get global(): boolean | undefined {
|
||||
return this.options.global;
|
||||
}
|
||||
|
||||
public get onPress(): KeyboardKeyHandler | undefined {
|
||||
return this.options.onPress;
|
||||
}
|
||||
|
||||
public set onPress(v: KeyboardKeyHandler | undefined) {
|
||||
this.options.onPress = v;
|
||||
}
|
||||
|
||||
public get onRelease(): KeyboardKeyHandler | undefined {
|
||||
return this.options.onRelease;
|
||||
}
|
||||
|
||||
public set onRelease(v: KeyboardKeyHandler | undefined) {
|
||||
this.options.onRelease = v;
|
||||
}
|
||||
|
||||
public get pressTriggerEveryTime(): boolean {
|
||||
return this.options.pressTriggerAsOriginalEvent;
|
||||
}
|
||||
|
||||
public set pressTriggerEveryTime(v: boolean) {
|
||||
this.options.pressTriggerAsOriginalEvent = v;
|
||||
}
|
||||
|
||||
press(e: KeyboardEvent, app: IGraphicApp): void {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 检查组合键是否匹配
|
||||
*/
|
||||
checkCombinations(e: KeyboardEvent): boolean {
|
||||
const cbs = this.combinations;
|
||||
if (cbs.length > 0) {
|
||||
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;
|
||||
}
|
||||
} else {
|
||||
return !e.altKey && !e.ctrlKey && !e.shiftKey;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
onRemove(): void {
|
||||
// 重置按下状态
|
||||
this.isPress = false;
|
||||
}
|
||||
}
|
6
src/jl-graphic/plugins/index.ts
Normal file
6
src/jl-graphic/plugins/index.ts
Normal file
@ -0,0 +1,6 @@
|
||||
export * from './InteractionPlugin';
|
||||
export * from './CommonMousePlugin';
|
||||
export * from './KeyboardPlugin';
|
||||
export * from './CopyPlugin';
|
||||
export * from './GraphicTransformPlugin';
|
||||
export * from './AnimationManager';
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user