import Konva from 'konva'; import { nanoid } from 'nanoid'; import { Render } from '../index'; import { LinkDraw, GraphDraw, RulerDraw, PreviewDraw } from '../draws'; import { AssetSettings, AssetType } from '../types'; import { BezierSceneFunc } from '../utils/bezier-scene-func'; // 导入导出 export class ImportExportTool { private render: Render; constructor(render: Render) { this.render = render; } /** * 获得显示内容 * @param withLink 是否包含线条 * @returns */ getView(withLink: boolean = false) { // 复制画布 const copy = this.render.stage.clone(); // 提取 main layer 备用 const main = copy.find('#main')[0] as Konva.Layer; const cover = copy.find('#cover')[0] as Konva.Layer; // 暂时清空所有 layer const copyChildren = copy.getChildren(); copy.removeChildren(); if (main && cover) { // 提取节点 let nodes = main.getChildren((node) => !this.render.ignore(node)); // 移除多余结构 for (const node of nodes) { // 如果当前被选中,listening 会是 false,需恢复 node.listening(true); // 恢复 draggable(因为,绘制 Graph 的时候,不允许直接拖动其他素材) node.draggable(!this.render.config.readonly && !node.attrs.locked); for (const child of (node as Konva.Group).children) { if (this.render.ignoreSelect(child)) { child.remove(); } } } if (withLink) { // 从 Link group 中提取 连接线 const linkDraw = cover.children.find((o) => o.attrs.name === LinkDraw.NAME) as Konva.Group; if (linkDraw) { nodes = nodes.concat(linkDraw.children.filter((o) => o.attrs.name === 'link-line')); } } // 重新装载节点 const layer = new Konva.Layer(); layer.add(...nodes); nodes = layer.getChildren(); for (const node of nodes) { if (node.attrs.nodeMousedownPos) { // 修正正在选中的节点透明度 node.setAttrs({ opacity: copy.attrs.lastOpacity ?? 1 }); } } // 重新装载 layer copy.add(layer); main.removeChildren(); cover.removeChildren(); } copyChildren.forEach((o) => o.destroy()); // 返回可视节点和 layer return copy; } // 保存 save() { const copy = this.getView(); const json = copy.toJSON(); copy.destroy(); // 通过 stage api 导出 json return json; } // 加载 image(用于导入) loadImage(src: string) { return new Promise((resolve) => { const img = new Image(); img.onload = () => { // 返回加载完成的图片 element resolve(img); }; img.onerror = () => { resolve(null); }; img.src = src; }); } // 汇总图片组件 getImgNodes(nodes: Konva.Node[] = []) { const temNodes = nodes.map(node => { if (node instanceof Konva.Group) { return this.getImgNodes(node.getChildren()); } else if (node instanceof Konva.Image) { return node; } }).flat(Infinity).filter(Boolean); return temNodes; } // 恢复图片(用于导入) async restoreImage(nodes: Konva.Node[] = []) { const imgNodes = this.getImgNodes(nodes); const tasks = imgNodes.map(node => { // 处理图片 if (node.attrs.svgXML) { // svg 素材 return this.render.assetTool.loadSvgXML(node.attrs.svgXML); } else if (node.attrs.gif) { // gif 素材 return this.render.assetTool.loadGif(node.attrs.gif); } else if (node.attrs.src) { // 其他图片素材 return this.loadImage(node.attrs.src); } }); Promise.all(tasks).then(res => { res.forEach((imageNode, index) => { const node = imgNodes[index]; // 处理图片 if (imageNode && node) { if (node.attrs.svgXML) { // svg 素材 node.image(imageNode.image()); } else if (node.attrs.gif) { // gif 素材 node.image(imageNode.image()); } else if (node.attrs.src) { // 其他图片素材 node.image(imageNode); } } }) }); } // 恢复图形 restoreGraph(nodes: Konva.Node[] = []) { for (const node of nodes) { if (node instanceof Konva.Group && node.attrs.assetType === AssetType.Graph) { if (node.attrs.graphType === "Bezier") { const graph = node.findOne('.graph'); if (graph instanceof Konva.Arrow) { graph.sceneFunc(BezierSceneFunc); } } const hoverRect = node.findOne('.hoverRect'); if (hoverRect instanceof Konva.Rect) { hoverRect.on('mouseenter', () => { // 防止进入调整点,重复处理 if (!node.attrs.hoverAnchor) { node.setAttr('hover', true); this.render.redraw([GraphDraw.NAME]); } setTimeout(() => { // 调整产生 redraw,导致离开调整点不触发其 mouseleave(进入其他元素区域除外) // 在此静态补充"离开调整点" // 不影响正常处理(调整点会不停 hoverAnchor = true) node.setAttr('hoverAnchor', false); }); // 显示 连接点 this.render.linkTool.pointsVisible(true, node); }); hoverRect.on('mouseleave', () => { // 延迟事件,使调整点的 mouseleave 优先 setTimeout(() => { // 防止进入调整点,重复处理 // 补充 2,快速调整会漏掉 if (!node.attrs.hoverAnchor) { node.setAttr('hover', false); node.setAttr('hoverAnchor', false); this.render.redraw([GraphDraw.NAME]); } }); // 隐藏 连接点 this.render.linkTool.pointsVisible(false, node); // 隐藏 hover 框 node.findOne('#hoverRect')?.visible(false); }); } } } } // 恢复(导入) async restore(json: string, silent = false) { if (!Object.keys(JSON.parse(json)).length) { return; } const readonly = this.render.config.readonly; try { this.render.emit('loading', true); // 清空选择 this.render.selectionTool.selectingClear(); this.render.linkTool.selectingClear(); // 清空 main layer 节点 this.render.layer.getChildren().forEach((o) => o.destroy()); this.render.layer.removeChildren(); // 加载 json,提取节点 const container = document.createElement('div'); // 反序列化 const stage = Konva.Node.create(json, container); const main = stage.getChildren()[0]; const nodes = main.getChildren(); // 恢复节点图片素材 await this.restoreImage(nodes); await this.restoreGraph(nodes); for (const node of nodes) { // 重置旧数据节点为可 draggable node.draggable(!readonly && !node.attrs.locked); // 组件鼠标移入移出事件 this.render.componentFactory.groupMouseenter({ group: node }); this.render.componentFactory.groupMouseleave({ group: node }); if (readonly) { this.render.componentFactory.readonlyInitComponentSetting({ node }); } } this.render.layer.add(...nodes); // 插入节点 // 同步页面设置 this.render.stage.setAttr('pageSettings', stage.attrs.pageSettings); this.render.emit('page-settings-change', this.render.getPageSettings()); // 更新背景 this.render.updateBackground(); // 上一步、下一步 无需更新 history 记录 if (!silent) { // 更新历史 this.render.updateHistory(); } // 隐藏 连接点 this.render.linkTool.pointsVisible(false); // 重绘 this.render.redraw([ GraphDraw.NAME, LinkDraw.NAME, RulerDraw.NAME, PreviewDraw.NAME ]); stage.destroy(); } catch (e) { console.error(e); } finally { this.render.emit('loading', false); } } // 获取图片 getImage(pixelRatio = 1, bgColor?: string) { // 在 getAssetView 的基础上,增加背景即可 const copy = this.getAssetView(); // 背景层 const bgLayer = new Konva.Layer(); // 背景矩形 const bg = new Konva.Rect({ listening: false }); bg.setAttrs({ x: 0, y: 0, width: copy.width(), height: copy.height(), fill: bgColor ?? this.render.getPageSettings().background }); // 添加背景 bgLayer.add(bg); const children = copy.getChildren() as Konva.Layer[]; copy.removeChildren(); copy.add(bgLayer); copy.add(children[0], ...children.slice(1)); const url = copy.toDataURL({ pixelRatio }); copy.destroy(); // 通过 stage api 导出图片 return url; } // 获取元素图片 getAssetImage(pixelRatio = 1, bgColor?: string) { // 获取可视节点和 layer const copy = this.getAssetView(); // 背景层 const bgLayer = new Konva.Layer(); // 背景矩形 const bg = new Konva.Rect({ listening: false }); bg.setAttrs({ x: -copy.x(), y: -copy.y(), width: copy.width(), height: copy.height(), fill: bgColor ?? this.render.getPageSettings().background }); // 添加背景 bgLayer.add(bg); // 插入背景 const children = copy.getChildren(); copy.removeChildren(); copy.add(bgLayer); copy.add(children[0], ...children.slice(1)); const url = copy.toDataURL({ pixelRatio }); copy.destroy(); // 通过 stage api 导出图片 return url; } // blob to base64 url blobToBase64(blob: Blob, type: string): Promise { return new Promise((resolve) => { const file = new File([blob], 'image', { type }); const fileReader = new FileReader(); fileReader.readAsDataURL(file); fileReader.onload = function () { resolve((this.result as string) ?? ''); }; }); } // 替换 svg blob: 链接 parseSvgImage(urls: string[]): Promise { return new Promise((resolve) => { if (urls.length > 0) { Promise.all(urls.map((o) => fetch(o))).then((rs: Response[]) => { // fetch // 替换为 svg 嵌套 Promise.all(rs.map((o) => o.text())).then((xmls: string[]) => { // svg xml resolve(xmls); }); }); } else { resolve([]); } }); } // 替换其他 image 链接 parseOtherImage(urls: string[]): Promise { return new Promise((resolve) => { if (urls.length > 0) { Promise.all(urls.map((o) => fetch(o))).then((rs: Response[]) => { // fetch // 替换为 base64 url image Promise.all(rs.map((o) => o.blob())).then((bs: Blob[]) => { // blob Promise.all(bs.map((o) => this.blobToBase64(o, 'image/*'))).then((urls: string[]) => { // base64 resolve(urls); }); }); }); } else { resolve([]); } }); } // 替换 image 链接 parseImage(xml: string): Promise { return new Promise((resolve) => { // 找出 blob:http 图片链接(目前发现只有 svg 是) const svgs = xml.match(/(?<=xlink:href=")blob:https?:\/\/[^"]+(?=")/g) ?? []; // 其他图片转为 base64 const imgs = xml.match(/(?<=xlink:href=")(? { // svg xml svgs.forEach((svg, idx) => { // 替换 xml = xml.replace( new RegExp(`<]* xlink:href="${svg}"[^><]*/>`), svgXmls[idx].match(/<]*>.*<\/svg>/)?.[0] ?? '' // 仅保留 svg 结构 ); }); // base64 imgs.forEach((img, idx) => { // 替换 xml = xml.replace(`"${img}"`, `"${imgUrls[idx]}"`); }); // 替换完成 resolve(xml); } ); }); } /** * 获得显示内容(用于另存为元素) * @returns Konva.Stage */ getAssetView() { const copy = this.getView(true); const children = copy.getChildren()[0].getChildren(); const nodes: Konva.Stage | Konva.Layer | Konva.Group | Konva.Node[] = [...children]; let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity, minStartX = Infinity, minStartY = Infinity; const stageState = this.render.getStageState(); for (const node of nodes) { if (node instanceof Konva.Group) { const { x, y, width, height } = ((rect) => ({ x: this.render.toStageValue(rect.x - stageState.x), y: this.render.toStageValue(rect.y - stageState.y), width: this.render.toStageValue(rect.width), height: this.render.toStageValue(rect.height) }))(node.getClientRect()); if (x < minX) { minX = x; } if (x + width > maxX) { maxX = x + width; } if (y < minY) { minY = y; } if (y + height > maxY) { maxY = y + height; } if (x < minStartX) { minStartX = x; } if (y < minStartY) { minStartY = y; } // 移除辅助元素 if (node instanceof Konva.Group) { const clickMask = node.findOne('#click-mask'); if (clickMask) { clickMask.destroy(); } } } else if (node instanceof Konva.Line && node.name() === 'link-line') { // 连线占用空间 const points = node.points(); for (let i = 0; i < points.length; i += 2) { const [x, y] = [points[i], points[i + 1]]; if (x < minX) { minX = x - 1; } if (x > maxX) { maxX = x + 1; } if (y < minY) { minY = y - 1; } if (y > maxY) { maxY = y + 1; } if (x < minStartX) { minStartX = x - 1; } if (y < minStartY) { minStartY = y - 1; } } } } for (const node of nodes) { if (node instanceof Konva.Group) { node.x(node.x() - minStartX); node.y(node.y() - minStartY); } else if (node instanceof Konva.Line && node.name() === 'link-line') { const points = node.points(); for (let i = 0; i < points.length; i += 2) { points[i] = points[i] - minStartX; points[i + 1] = points[i + 1] - minStartY; } node.points(points); } } copy.x(0); copy.y(0); copy.width(maxX - minX); copy.height(maxY - minY); copy.scale({ x: 1, y: 1 }); return copy; } /** * 获得元素(用于另存为元素) * @returns Konva.Stage */ getAsset() { const copy = this.getAssetView(); // 添加背景 const background = this.render.getBackground(); background.width(copy.width()); background.height(copy.height()); copy.children[0].add(background); background.moveToBottom(); const json = copy.toJSON(); const obj = JSON.parse(json); const assets = obj.children[0].children; for (const asset of assets) { if (asset.attrs.name === 'asset') { asset.attrs.name = 'sub-asset'; } if (asset.attrs.selected) { asset.attrs.selected = false; } } this.render.linkTool.jsonIdCover(assets); // 通过 stage api 导出 json const result = JSON.stringify({ ...obj.children[0], className: 'Group', attrs: { width: copy.width(), height: copy.height(), x: 0, y: 0 } }); copy.destroy(); return result; } /** * 添加文字素材 * @param pos 落点位置 * @param settings 设置项 * @returns */ addTextAsset(pos: Konva.Vector2d, settings?: Partial) { // 获取页面默认设置 const pageSettings = this.render.getPageSettings(); // 合并设置 const assetSettings: AssetSettings = { stroke: "#000000", strokeWidth: 1, fill: "#000000", arrowStart: false, arrowEnd: false, fontSize: pageSettings.fontSize, textFill: pageSettings.textFill, text: 'Text', x: pos.x, y: pos.y, rotation: 0, tension: 0.5, ...settings }; const group = new Konva.Group({ id: nanoid(), name: 'asset', assetType: AssetType.Text, draggable: true, position: { x: pos.x, y: pos.y } }); group.setAttr('assetSettings', assetSettings); const text = new Konva.Text({ text: assetSettings.text, fill: assetSettings.textFill, fontSize: assetSettings.fontSize, draggable: false, name: 'text-node' }); const bg = new Konva.Rect({ width: text.width(), height: text.height() }); group.add(text); group.add(bg); this.render.layer.add(group); this.render.layer.draw(); return group; } }