import * as _ from 'lodash'; import Konva from 'konva'; import { GraphDraw, LinkDraw, RulerDraw, PreviewDraw, RefLineDraw, BgDraw, ContextmenuDraw } from './draws'; import { LinkDrawPoint, GraphType, AssetType, RenderConfig, Draw, Handler, RenderEvents, LinkDrawPair, PageSettings, AssetSettings, ImageType, LinkSettings } from './types'; import { DragHandlers, ZoomHandlers, DragOutsideHandlers, SelectionHandlers, KeyMoveHandlers, ShutcutHandlers, LinkHandlers, GraphHandlers, TextHandlers } from './handlers'; import { AssetTool, SelectionTool, CopyTool, PositionTool, ZIndexTool, ImportExportTool, AlignTool, LinkTool, AttractTool, ComponentFactory } from './tools'; // 简单的事件系统替代 mitt class SimpleEventEmitter { private listeners: Map> = new Map(); on(event: string, handler: Function) { if (!this.listeners.has(event)) { this.listeners.set(event, new Set()); } this.listeners.get(event)!.add(handler); return () => this.off(event, handler); } off(event: string, handler: Function) { this.listeners.get(event)?.delete(handler); } emit(event: string, ...args: any[]) { this.listeners.get(event)?.forEach(handler => handler(...args)); } } // 渲染器 export class Render { stage: Konva.Stage; layer: Konva.Layer = new Konva.Layer({ id: 'main' }); // 主要层 layerFloor: Konva.Layer = new Konva.Layer(); // 辅助层 - 背景 layerCover: Konva.Layer = new Konva.Layer({ id: 'cover' }); // 辅助层 - 连接线、对齐线 config: RenderConfig; // 配置 draws: { [index: string]: (Draw & Handler) | undefined } = {}; // 附加工具 assetTool: AssetTool; // 素材工具 selectionTool: SelectionTool; // 选择工具 copyTool: CopyTool; // 复制工具 positionTool: PositionTool; // 定位工具 zIndexTool: ZIndexTool; // 层级工具 importExportTool: ImportExportTool; // 导入导出 alignTool: AlignTool; // 对齐工具 linkTool: LinkTool; // 连线工具 attractTool: AttractTool; // 磁贴工具 componentFactory: ComponentFactory; // 统一组件渲染 groupTransformer: Konva.Group = new Konva.Group(); // 多选器层 // 多选器 transformer: Konva.Transformer = new Konva.Transformer({ shouldOverdrawWholeArea: true, borderDash: [4, 4], padding: 1, rotationSnaps: [0, 45, 90, 135, 180, 225, 270, 315, 360], flipEnabled: false }); // 选择框 selectRect: Konva.Rect = new Konva.Rect({ id: 'selectRect', fill: 'rgba(0,0,255,0.1)', visible: false }); // 事件处理 handlers: { [index: string]: Handler } = {}; // 参数 bgSize = 20; rulerSize = 0; previewSize = 0.2; // 预览框大小(比例) pointSize = 6; history: string[] = []; historyIndex = -1; graphType: GraphType | undefined = undefined; // 画图类型 texting = false; // 添加文字中 showGrid = false; // 显示网格 showAttract = true; // 显示磁吸 // 事件发射器(替代 mitt) private emitter = new SimpleEventEmitter(); on: (event: K, handler: (payload: RenderEvents[K]) => void) => (() => void); off: (event: K, handler: (payload: RenderEvents[K]) => void) => void; emit: (event: K, payload: RenderEvents[K]) => void; constructor(stageEle: HTMLDivElement, config: RenderConfig) { this.config = config; // 绑定事件方法 this.on = this.emitter.on.bind(this.emitter) as any; this.off = this.emitter.off.bind(this.emitter) as any; this.emit = this.emitter.emit.bind(this.emitter) as any; if (this.config.showRuler) { this.rulerSize = 40; } this.stage = new Konva.Stage({ container: stageEle, x: this.rulerSize, y: this.rulerSize, width: config.width, height: config.height }); // 辅助层 - 顶层 this.groupTransformer.add(this.transformer); this.groupTransformer.add(this.selectRect); this.layerCover.add(this.groupTransformer); if (this.config.showBg) { // 背景 this.draws[BgDraw.NAME] = new BgDraw(this, this.layerFloor, { size: this.bgSize, showGrid: this.showGrid, readonly: this.config.readonly }); } this.draws[LinkDraw.NAME] = new LinkDraw(this, this.layerCover, { size: this.pointSize }); if (!this.config.readonly && this.config.showRuler) { this.draws[RulerDraw.NAME] = new RulerDraw(this, this.layerCover, { size: this.rulerSize }); } if (!this.config.readonly && this.config.showRefLine) { this.draws[RefLineDraw.NAME] = new RefLineDraw(this, this.layerCover, { padding: this.rulerSize }); } if (this.config.showContextmenu) { this.draws[ContextmenuDraw.NAME] = new ContextmenuDraw(this, this.layerCover, {}); } if (!this.config.readonly && this.config.showPreview) { this.draws[PreviewDraw.NAME] = new PreviewDraw(this, this.layerCover, { size: this.previewSize }); } this.draws[GraphDraw.NAME] = new GraphDraw(this, this.layerCover, {}); this.assetTool = new AssetTool(this); // 素材工具 this.selectionTool = new SelectionTool(this); // 选择工具 this.copyTool = new CopyTool(this); // 复制工具 this.positionTool = new PositionTool(this); // 定位工具 this.zIndexTool = new ZIndexTool(this); // 定位工具 this.importExportTool = new ImportExportTool(this); // 导入导出 this.alignTool = new AlignTool(this); // 对齐工具 this.linkTool = new LinkTool(this); // 对齐工具 this.attractTool = new AttractTool(this); // 磁贴工具 this.componentFactory = new ComponentFactory(this); // 统一组件渲染 // 事件处理 this.handlers[DragHandlers.NAME] = new DragHandlers(this); this.handlers[ZoomHandlers.NAME] = new ZoomHandlers(this); if (!this.config.readonly) { this.handlers[DragOutsideHandlers.NAME] = new DragOutsideHandlers(this); this.handlers[SelectionHandlers.NAME] = new SelectionHandlers(this); this.handlers[KeyMoveHandlers.NAME] = new KeyMoveHandlers(this); this.handlers[LinkHandlers.NAME] = new LinkHandlers(this); this.handlers[GraphHandlers.NAME] = new GraphHandlers(this); this.handlers[TextHandlers.NAME] = new TextHandlers(this); } if (!this.config.readonly && this.config.showRefLine) { if (this.draws[RefLineDraw.NAME] !== void 0) { this.handlers[RefLineDraw.NAME] = this.draws[RefLineDraw.NAME]!; } } this.handlers[ShutcutHandlers.NAME] = new ShutcutHandlers(this); // 初始化 this.init(); } // 初始化 init() { this.stage.add(this.layerFloor); this.draws[BgDraw.NAME]?.init(); this.stage.add(this.layer); this.stage.add(this.layerCover); this.draws[LinkDraw.NAME]?.init(); this.draws[RulerDraw.NAME]?.init(); this.draws[RefLineDraw.NAME]?.init(); this.draws[ContextmenuDraw.NAME]?.init(); this.draws[PreviewDraw.NAME]?.init(); // 事件绑定 this.eventBind(); // 更新历史 this.updateHistory(); } // 更新 stage 尺寸 resize(width: number, height: number) { this.stage.setAttrs({ width: width, height: height }); // 重绘 this.redraw(); } // 移除元素 remove(nodes: Konva.Node[]) { for (const node of nodes) { if (node instanceof Konva.Transformer) { // 移除已选择的节点 this.remove(this.selectionTool.selectingNodes); } else { // 移除相关联系线信息 const groupId = node.id(); for (const rn of this.layer.getChildren()) { if (rn.id() !== groupId && Array.isArray(rn.attrs.points)) { for (const point of rn.attrs.points) { if (Array.isArray(point.pairs)) { // 移除拐点记录 if (rn.attrs.manualPointsMap) { point.pairs .filter( (pair: LinkDrawPair) => pair.from.groupId === groupId || pair.to.groupId === groupId ) .forEach((pair: LinkDrawPair) => { rn.attrs.manualPointsMap[pair.id] = undefined; }); } // 连接线信息 point.pairs = point.pairs.filter( (pair: LinkDrawPair) => pair.from.groupId !== groupId && pair.to.groupId !== groupId ); } } rn.setAttrs({ points: rn.attrs.points }); } } // 移除未选择的节点 node.destroy(); } } if (nodes.length > 0) { // 清除选择 this.selectionTool.selectingClear(); this.linkTool.selectingClear(); // 更新历史 this.updateHistory(); // 重绘 this.redraw(); } } // 撤销 prevHistory() { const record = this.history[this.historyIndex - 1]; if (record) { this.importExportTool.restore(record, true); this.historyIndex--; // 历史变化事件 this.emit('history-change', { records: _.clone(this.history), index: this.historyIndex }); } } // 恢复 nextHistory() { const record = this.history[this.historyIndex + 1]; if (record) { this.importExportTool.restore(record, true); this.historyIndex++; // 历史变化事件 this.emit('history-change', { records: _.clone(this.history), index: this.historyIndex }); } } updateHistory() { this.history.splice(this.historyIndex + 1); this.history.push(this.importExportTool.save()); this.historyIndex = this.history.length - 1; // 历史变化事件 this.emit('history-change', { records: _.clone(this.history), index: this.historyIndex }); } // 事件绑定 eventBind() { for (const event of [ 'mousedown', 'mouseup', 'mousemove', 'wheel', 'contextmenu', 'pointerclick' ]) { this.stage.on(event, (e) => { e?.evt?.preventDefault(); for (const k in this.draws) { this.draws[k]?.handlers?.stage?.[event]?.(e); } for (const k in this.handlers) { this.handlers[k]?.handlers?.stage?.[event]?.(e); } }); } const container = this.stage.container(); container.tabIndex = 1; container.focus(); for (const event of [ 'mouseenter', 'dragenter', 'mousemove', 'mouseout', 'dragenter', 'dragover', 'drop', 'keydown', 'keyup' ]) { container.addEventListener(event, (e) => { e?.preventDefault(); if (['mouseenter', 'dragenter'].includes(event)) { // 激活 dom 事件 this.stage.container().focus(); } for (const k in this.draws) { this.draws[k]?.handlers?.dom?.[event]?.(e); } for (const k in this.handlers) { this.handlers[k]?.handlers?.dom?.[event]?.(e); } }); } for (const event of [ 'mousedown', 'transformstart', 'transform', 'transformend', 'dragstart', 'dragmove', 'dragend', 'mousemove', 'mouseleave', 'dblclick' ]) { this.transformer.on(event, (e) => { e?.evt?.preventDefault(); for (const k in this.draws) { this.draws[k]?.handlers?.transformer?.[event]?.(e); } for (const k in this.handlers) { this.handlers[k]?.handlers?.transformer?.[event]?.(e); } }); } this.handlers[SelectionHandlers.NAME]?.transformerConfig?.anchorDragBoundFunc && this.transformer.anchorDragBoundFunc( this.handlers[SelectionHandlers.NAME].transformerConfig!.anchorDragBoundFunc! ); } // 获取 stage 状态 getStageState() { return { width: this.stage.width() - this.rulerSize, height: this.stage.height() - this.rulerSize, scale: this.stage.scaleX(), x: this.stage.x(), y: this.stage.y() }; } // 相对大小(基于 stage,且无视 scale) toStageValue(boardPos: number) { return boardPos / this.stage.scaleX(); } // 绝对大小(基于可视区域像素) toBoardValue(stagePos: number) { return stagePos * this.stage.scaleX(); } // 忽略非素材 ignore(node: Konva.Node) { // 素材有各自根 group const isGroup = node instanceof Konva.Group; return !isGroup || this.ignoreSelect(node) || this.ignoreDraw(node) || this.ignoreLink(node); } // 忽略 选择时 辅助元素 ignoreSelect(node: Konva.Node) { return node.id() === 'selectRect' || node.id() === 'hoverRect'; } // 忽略各 draw 的根 group ignoreDraw(node: Konva.Node) { return [BgDraw.NAME, RulerDraw.NAME, RefLineDraw.NAME, ContextmenuDraw.NAME, PreviewDraw.NAME, LinkDraw.NAME, GraphDraw.NAME].includes(node.name()); } // 忽略各 draw 的根 group ignoreLink(node: Konva.Node) { return ["link-anchor", "linking-line", "link-point", "link-line", "link-manual-point"].includes(node.name()); } // 重绘(可选择) redraw(drawNames?: string[]) { const all = [ // layerFloor BgDraw.NAME, // 更新背景 // layerCover(按先后顺序) GraphDraw.NAME, // 更新图形调整点 LinkDraw.NAME, // 更新连线 RulerDraw.NAME, // 更新比例尺 RefLineDraw.NAME, // 更新参考线 PreviewDraw.NAME, // 更新预览 ContextmenuDraw.NAME // 更新右键菜单 ]; // 可以以此发现缺失的 draw // console.log('redraw', drawNames) if (Array.isArray(drawNames)) { // 选择性 draw 也要保持顺序 for (const name of all) { if (drawNames.includes(name)) { this.draws[name]?.draw(); } } } else { for (const name of all) { this.draws[name]?.draw(); } } } changeDraggable(disabled: boolean) { this.layer.children.forEach((asset) => { // 锁定节点始终保持不可拖拽 asset.draggable(disabled && !asset.attrs.locked); }); } // 改变画图类型 changeGraphType(type?: GraphType) { if (type) { this.texting = false; this.emit('texting-change', this.texting); } this.graphType = type; this.emit('graph-type-change', this.graphType); // 绘制 Graph 的时候,不允许直接拖动其他素材 this.changeDraggable(!this.config.readonly && this.graphType === void 0); } // 添加文字状态 changeTexting(texting: boolean) { if (texting) { this.graphType = undefined; this.emit('graph-type-change', this.graphType); } this.texting = texting; this.emit('texting-change', this.texting); document.body.style.cursor = this.texting ? 'text' : 'default'; } // 更改网格显示 changeShowGrid(show: boolean) { this.showGrid = show; (this.draws[BgDraw.NAME] as BgDraw)?.updateOption({ showGrid: show }); } // 更改磁吸显示 changeShowAttract(show: boolean) { this.showAttract = show; } // 页面设置 默认值 static PageSettingsDefault: PageSettings = { // 画布默认尺寸 pageWidth: 1280, pageHeight: 720, // 样式默认值 background: undefined, linkStroke: 'rgb(0,0,0)', linkStrokeWidth: 1, fontSize: 24, textFill: 'rgb(0,0,0)' }; // 获取页面设置 getPageSettings(): PageSettings { return this.stage.attrs.pageSettings ?? { ...Render.PageSettingsDefault }; } // 更新页面设置 setPageSettings(settings: PageSettings, update = false) { this.stage.setAttr('pageSettings', settings); this.emit('page-settings-change', settings); // 更新背景 this.updateBackground(); if (update) { // 更新历史 this.updateHistory(); } } // 获取背景 getBackground() { return this.draws[BgDraw.NAME]?.layer.findOne(`.${BgDraw.NAME}__background`) as Konva.Rect; } // 更新背景 updateBackground() { this.draws[BgDraw.NAME]?.draw(); this.draws[GraphDraw.NAME]?.draw(); this.draws[LinkDraw.NAME]?.draw(); this.draws[PreviewDraw.NAME]?.draw(); } // 素材设置 默认值 static AssetSettingsDefault: AssetSettings = { // stroke: '', // strokeWidth: 0, // fill: '', arrowStart: false, arrowEnd: false, fontSize: 0, textFill: '', text: 'Text', x: 0, y: 0, rotation: 0, tension: 0 }; // 获取素材设置 getAssetSettings(asset?: Konva.Node): AssetSettings { const attrs = asset?.attrs || {}; const base = attrs?.assetSettings ?? { ...Render.AssetSettingsDefault }; return { // 特定 ...base, // 继承全局 stroke: base.stroke, strokeWidth: base.strokeWidth, fontSize: base.fontSize || this.getPageSettings().fontSize, textFill: base.textFill || this.getPageSettings().textFill, // 绘制图形,默认不填充 x: parseFloat((asset?.position().x ?? 0).toFixed(1)), y: parseFloat((asset?.position().y ?? 0).toFixed(1)), rotation: parseFloat((asset?.rotation() ?? 0).toFixed(1)), width: parseFloat(((attrs.width ?? 0) * (asset?.scaleX?.() ?? 1)).toFixed(1)), height: parseFloat(((attrs.height ?? 0) * (asset?.scaleY?.() ?? 1)).toFixed(1)), tension: attrs.assetType === AssetType.Graph && attrs.graphType === "Curve" ? base.tension : undefined }; } // 设置 svgXML 样式(部分) setSvgXMLSettings(xml: string, settings: AssetSettings) { const reg = /<(circle|ellipse|line|path|polygon|rect|text|textPath|tref|tspan)[^>/]*\/?>/g; const shapes = xml.match(reg); const regStroke = / stroke="([^"]*)"/; const regFill = / fill="([^"]*)"/; for (const shape of shapes ?? []) { let result = shape; if (settings.stroke) { if (regStroke.test(shape)) { result = result.replace(regStroke, ` stroke="${settings.stroke}"`); } else { result = result.replace(/(<[^>/]*)(\/?>)/, `$1 stroke="${settings.stroke}" $2`); } } if (settings.fill) { if (regFill.test(shape)) { result = result.replace(regFill, ` fill="${settings.fill}"`); } else { result = result.replace(/(<[^>/]*)(\/?>)/, `$1 fill="${settings.fill}" $2`); } } xml = xml.replace(shape, result); } return xml; } rotatePoint({ x, y }: { x: number; y: number }, rad: number) { const rCos = Math.cos(rad); const rSin = Math.sin(rad); return { x: x * rCos - y * rSin, y: y * rCos + x * rSin }; } rotateAroundCenter(node: Konva.Node, rotation: number) { const topLeft = { x: -node.width() / 2, y: -node.height() / 2 }; const current = this.rotatePoint(topLeft, Konva.getAngle(node.rotation())); const rotated = this.rotatePoint(topLeft, Konva.getAngle(rotation)); const dx = rotated.x - current.x; const dy = rotated.y - current.y; node.rotation(rotation); node.x(node.x() + dx); node.y(node.y() + dy); } // 更新素材设置 async setAssetSettings(asset: Konva.Node, settings: AssetSettings, update = false) { if (asset instanceof Konva.Group) { this.componentFactory.updateComponentSetting({ node: asset, settings }); // 更新组件配置 if (asset.attrs.imageType === ImageType.svg) { const node = asset.children[0] as Konva.Shape; if (node instanceof Konva.Image) { if (node.attrs.svgXML) { // 仅在 stroke/fill 变化时才重建 SVG 节点 const currentSettings = asset.attrs.assetSettings; const strokeChanged = settings.stroke !== currentSettings?.stroke; const fillChanged = settings.fill !== currentSettings?.fill; if (strokeChanged || fillChanged) { const n = await this.assetTool.loadSvgXML( this.setSvgXMLSettings(node.attrs.svgXML, settings) ); // 保留旧节点的变换状态 n.x(node.x()); n.y(node.y()); n.scaleX(node.scaleX()); n.scaleY(node.scaleY()); n.rotation(node.rotation()); node.parent?.add(n); node.remove(); node.destroy(); n.zIndex(0); } } } } else if (asset.attrs.assetType === AssetType.Graph) { const node = asset.findOne('.graph'); if (node instanceof Konva.Shape) { node.strokeWidth(settings.strokeWidth); node.stroke(settings.stroke); if (node instanceof Konva.Arrow) { // 箭头跟随 stroke node.fill(settings.stroke); } else { node.fill(settings.fill); } if (node instanceof Konva.Arrow) { node.pointerAtBeginning(settings.arrowStart); node.pointerAtEnding(settings.arrowEnd); } if (node instanceof Konva.Arrow && asset.attrs.graphType === "Curve") { node.tension(settings.tension); } } } else if (asset.attrs.assetType === AssetType.Text) { const node = asset.findOne('Text'); const rect = asset.findOne('Rect'); if (node instanceof Konva.Text && rect instanceof Konva.Rect) { let sizeChanged = false; if (node.fontSize() !== settings.fontSize || node.text() !== settings.text) { sizeChanged = true; } node.fill(settings.textFill); node.fontSize(settings.fontSize); node.text(settings.text); // 内容为空时,给一个半透明背景色 rect.fill(node.text().trim() ? '' : 'rgba(0,0,0,0.1)'); rect.width(Math.max(node.width(), settings.fontSize)); rect.height(Math.max(node.height(), settings.fontSize)); // 刷新 transformer 大小 if (sizeChanged) { this.selectionTool.select([asset]); } } } // rotate 会影响 position,不能同时改变 if (Math.abs(settings.rotation - asset.rotation()) >= 0.1) { this.rotateAroundCenter(asset, settings.rotation); // tooltip 始终箭头朝下,不受 group 旋转影响 asset.findOne('.tooltip')?.rotation(-asset.rotation()); // 同步 position 的变化 this.emit('asset-position-change', [asset]); } else { const prevSettings = this.getAssetSettings(asset); asset.position({ x: parseFloat(settings.x.toFixed(1)), y: parseFloat(settings.y.toFixed(1)) }); // 外部调用变化同步 if (settings.x !== prevSettings.x || settings.y !== prevSettings.y) { this.emit('asset-position-change', [asset]); } } } // 通过 scale 实现视觉尺寸变更(设置 Group 的 width/height 只影响裁剪,不会缩放内部子元素) if (settings.width || settings.height) { const baseWidth = asset.width() || 1; const baseHeight = asset.height() || 1; asset.scaleX(settings.width / baseWidth); asset.scaleY(settings.height / baseHeight); } asset.setAttr('assetSettings', settings); if (update) { // 更新历史 this.updateHistory(); } this.draws[BgDraw.NAME]?.draw(); this.draws[GraphDraw.NAME]?.draw(); this.draws[LinkDraw.NAME]?.draw(); this.draws[PreviewDraw.NAME]?.draw(); } // 获取画布上所有素材节点及其配置 getAllAssets(): Array<{ id: string; assetType: AssetType; settings: AssetSettings, componentType?: string }> { const nodes = this.layer.getChildren((node) => !this.ignore(node)); return nodes.map((node) => ({ id: node.id(), assetType: node.attrs.assetType as AssetType, componentType: node.attrs.componentType, settings: this.getAssetSettings(node) })); } // 根据节点 id 动态更新组件属性 updateAssetById(id: string, settings: Partial) { const node: Konva.Group = this.layer.findOne(`#${id}`); if (!node) { console.warn(`[Render.updateAssetById] 未找到节点 id=${id}`); return; } // 合并现有设置与新设置 const currentSettings = this.getAssetSettings(node); const mergedSettings: AssetSettings = { ...currentSettings, ...settings }; // 调用现有方法应用 this.setAssetSettings(node, mergedSettings, false); } // 连接线设置 默认值 static LinkSettingsDefault: LinkSettings = { stroke: '', strokeWidth: 0, arrowStart: false, arrowEnd: false, tension: 0 }; // 连接线设置 async setLinkSettings(link: Konva.Line, settings: LinkSettings, update = false) { const group = this.layer.findOne(`#${link.attrs.groupId}`); if (Array.isArray(group?.attrs.points)) { const point = (group?.attrs.points as LinkDrawPoint[]).find( (o: LinkDrawPoint) => o.id === link.attrs.pointId ); if (point) { const pair = point.pairs.find((o) => o.id === link.attrs.pairId); if (pair) { pair.style = { ...pair.style, ...settings, strokeWidth: Number(settings.strokeWidth ?? pair.style.strokeWidth), }; group.setAttr('points', group?.attrs.points); } } } if (update) { // 更新历史 this.updateHistory(); } this.draws[BgDraw.NAME]?.draw(); this.draws[GraphDraw.NAME]?.draw(); this.draws[LinkDraw.NAME]?.draw(); this.draws[PreviewDraw.NAME]?.draw(); } // 获取连接线设置 getLinkSettings(link?: Konva.Line): LinkSettings { let settings: (Konva.LineConfig & LinkSettings) | undefined = undefined; if (link) { const group = this.layer.findOne(`#${link.attrs.groupId}`); if (Array.isArray(group?.attrs.points)) { const point = (group?.attrs.points as LinkDrawPoint[]).find( (o: LinkDrawPoint) => o.id === link.attrs.pointId ); if (point) { const pair = point.pairs.find((o) => o.id === link.attrs.pairId); if (pair) { settings = pair.style; } } } } const base = settings ?? { ...Render.LinkSettingsDefault }; return { // 特定 ...base, // 继承全局 stroke: (base.stroke as string) || this.getPageSettings().linkStroke, strokeWidth: base.strokeWidth || this.getPageSettings().linkStrokeWidth }; } }