import * as d3 from 'd3'; import * as uuid from 'uuid'; import * as invariant from 'invariant'; import NodeView, { INode } from './node-view'; import EdgeView, { IEdge } from './edge-view'; import SlotView from './slot-view'; import { d3Selection, fromTransform, toTransform, ICoord } from './util'; import GEditor from './geditor'; import { SLOT_TYPE, EVENTS, DRAGGING_NODE_CONFIG_KEY, COPIED_NODE_OFFSET } from './constants'; export interface IGraph { readonly id: string; nodes: { [nodeId: string]: INode; }; edges: { [edgeId: string]: IEdge; }; } export interface ILayout { graph?: { translate?: [number, number]; scale?: number; }; nodes?: { [id: string]: [number, number]; }; } export interface InitialSettings { $canvas: d3Selection; geditor: GEditor; graph?: IGraph; layout?: ILayout; editable?: boolean; [key: string]: any; } export default class GraphView { public $el: d3Selection; public $canvas: d3Selection; protected geditor: GEditor; protected nodes = <{[nodeId: string]: NodeView}>{}; protected edges = <{[edgeId: string]: EdgeView}>{}; protected selectionIds: string[] = []; protected translate: [number, number]; protected scale: number; protected editable: boolean; private copyingHistory = { times: 0, translates: <[number, number][]>[], }; constructor(settings: InitialSettings) { const { $canvas, geditor, graph, layout, editable } = settings; this.$canvas = $canvas; this.$el = $canvas.append('g'); this.translate = layout.graph.translate; this.scale = layout.graph.scale; this.geditor = geditor; this.editable = typeof editable === 'undefined' ? true : editable; console.log(graph, layout); this.render(graph, layout); this.initEvents(); } protected render(graph: IGraph, layout: ILayout = {}) { this.$el.attr('transform', toTransform({ translate: this.translate, scale: this.scale, })); if (graph.nodes) { for (const [id, nodeConfig] of Object.entries(graph.nodes)) { this._createNode(nodeConfig, layout.nodes[id]); } } if (graph.edges) { for (const [id, edgeConfig] of Object.entries(graph.edges)) { const srcNodeView = this.nodes[edgeConfig.srcNodeId]; const destNodeView = this.nodes[edgeConfig.destNodeId]; const srcSlotView = srcNodeView.getSlotViewById(edgeConfig.srcSlotId); const destSlotView = destNodeView.getSlotViewById(edgeConfig.destSlotId); this._createEdge(edgeConfig, srcSlotView, destSlotView); } } } protected initEvents () { this.$canvas.on('click', () => this.onCanvasClick()); } protected onCanvasClick () { this.resetSelectionIds(); } protected _createNode (nodeConfig: INode, translate: [number, number]) { const nodeViewClass = this.geditor.getNodeViewClass(nodeConfig); const settings = { nodeConfig, translate, graphView: this, geditor: this.geditor, }; const nodeView = new nodeViewClass(settings); this.nodes[nodeView.id] = nodeView; return nodeView; } protected _createEdge (edgeConfig: IEdge, srcSlotView: SlotView, destSlotView: SlotView) { const edgeViewClass = this.geditor.getEdgeViewClass(edgeConfig); const settings = { edgeConfig, srcSlotView, destSlotView, graphView: this, geditor: this.geditor, }; const edgeView = new edgeViewClass(settings); this.edges[edgeView.id] = edgeView; return edgeView; } protected getEdgesByNodeId (nodeId: string) { return Object.values(this.edges).filter((edge: EdgeView) => { if (edge.srcNodeView.id === nodeId || edge.destNodeView.id === nodeId) { return true; } }); } protected getCopyingTranslates (translates: [number, number][]) { /** * Accumulate the translates If copying with the same selections for multiple times */ const historyTranslates = this.copyingHistory.translates; if (JSON.stringify(translates) === JSON.stringify(historyTranslates)) { this.copyingHistory.times += 1; } else { this.copyingHistory = { translates, times: 1, }; } const times = this.copyingHistory.times; return translates.map(t => t.map(v => v + times * COPIED_NODE_OFFSET)); } public isEntitySelected (entity: NodeView | EdgeView) { return !!this.selectionIds.find(id => id === entity.id); } public moveSelections (dx: number, dy: number) { const nodeIds = []; this.selectionIds.forEach((id) => { if (this.nodes[id]) { this.nodes[id].move(dx, dy); nodeIds.push(id); } }); Object.values(this.edges).forEach((edge: EdgeView) => { if (nodeIds.includes(edge.srcNodeView.id) || nodeIds.includes(edge.destNodeView.id)) { edge.update(); } }); } public updateRelatedEdgesPosition (nodeView: NodeView) { const edges = this.getEdgesByNodeId(nodeView.id); edges.forEach((edge: EdgeView) => { edge.update(); }); } public createNode (nodeConfig: INode, translate: [number, number]) { const nodeView = this._createNode(nodeConfig, translate); const data = { ...nodeConfig, id: nodeView.id }; if (data.inputSlots) { console.log(nodeConfig, data.inputSlots, nodeView); data.inputSlots = data.inputSlots.map((slot, index) => { return { ...slot, id: nodeView.inputSlots[index].id }; }); } if (data.outputSlots) { data.outputSlots = data.outputSlots.map((slot, index) => { return { ...slot, id: nodeView.outputSlots[index].id }; }); } this.geditor.emit(EVENTS.NODE_CREATED, data); return nodeView; } public createEdge (edgeConfig: IEdge, srcSlotView: SlotView, destSlotView: SlotView) { const edgeView = this._createEdge(edgeConfig, srcSlotView, destSlotView); const data = { ...edgeConfig, id: edgeView.id }; this.geditor.emit(EVENTS.EDGE_CREATED, data); return edgeView; } /** * @param {{ nodes: INode[], edges: IEdge[], translates: [number, number][] }} options * @memberof GraphView * @example * graphView.createByCopying({ * nodes: [nodeConfig1, nodeConfig2], * edges: [edgeConfig], * translates: [nodeTranslate1, nodeTranslate2] * }); */ public createByCopying (options: { nodes: INode[], edges: IEdge[], translates: [number, number][] }) { if (!this.editable) return; const idMappings = {}; const { nodes, edges, translates } = options; const selectionIds: string[] = []; const actualTranslates = this.getCopyingTranslates(translates); nodes.forEach((nodeConfig, index) => { invariant( nodeConfig.id, `id is required, createByCopying requires config of exists node(s)`, ); const inputSlots = nodeConfig.inputSlots || []; const outputSlots = nodeConfig.outputSlots || []; /** * Reset copied nodes/edges/slots unique id. */ const config:INode = { ...nodeConfig, id: null, inputSlots: inputSlots.map(slot => ({ ...slot, id: null })), outputSlots: outputSlots.map(slot => ({ ...slot, id: null })), }; const translate = <[number, number]>actualTranslates[index]; const copiedNode = this.createNode(config, translate); idMappings[nodeConfig.id] = copiedNode.id; inputSlots.forEach((slot, index) => { idMappings[slot.id] = copiedNode.inputSlots[index].id; }); outputSlots.forEach((slot, index) => { idMappings[slot.id] = copiedNode.outputSlots[index].id; }); selectionIds.push(copiedNode.id); }); edges.forEach((edgeConfig) => { const { srcNodeId, destNodeId, srcSlotId, destSlotId } = edgeConfig; if (idMappings[srcNodeId] && idMappings[destNodeId]) { const config = { srcNodeId: idMappings[srcNodeId], destNodeId: idMappings[destNodeId], srcSlotId: idMappings[srcSlotId], destSlotId: idMappings[destSlotId], }; const srcSlotView = this.getNodeById(config.srcNodeId).getSlotViewById(config.srcSlotId); const destSlotView = this.getNodeById(config.destNodeId).getSlotViewById(config.destSlotId); const copiedEdge = this.createEdge(config, srcSlotView, destSlotView); selectionIds.push(copiedEdge.id); } }); this.resetSelectionIds(...selectionIds); } public getSelections () { const selections = { nodes: [], edges: [], translates: [], }; this.selectionIds.forEach((id) => { if (this.nodes.hasOwnProperty(id)) { selections.nodes.push(id); selections.translates.push(this.getNodeById(id).getTranslate()); } else { selections.edges.push(id); } }); return selections; } public getTransform() { const str = this.$el.attr('transform'); return fromTransform(str); } public isEdgeExists(srcSlotId: string, destSlotId: string) { for (const edgeView of Object.values(this.edges)) { if ( edgeView.srcSlotView.id === srcSlotId && edgeView.destSlotView.id === destSlotId ) { return true; } } return false; } public isSlotConnected(slotView: SlotView) { // return false; return !!Object.values(this.edges).find((edgeView) => { // return edgeView.srcSlotView === slotView || edgeView.destSlotView === slotView; // TODO: 多条线从同一个点连出,连向同一个节点; return edgeView.srcSlotView === slotView; }); } public isSelectionExsits(id: string) { return this.selectionIds.includes(id); } public appendSelectionIds (...args: string[]) { const selectionIds = [...this.selectionIds, ...args]; this.resetSelectionIds(...selectionIds); } public removeSelectionId (entityId: string) { const selectionIds = this.selectionIds.filter(id => id !== entityId); this.resetSelectionIds(...selectionIds); } public resetSelectionIds (...args: string[]) { /** * Always call `handleDeslected` of all entities when selections changed. * In order to easily update the UI state. * For example: when one Node or Edge select, * all other Nodes and Edges must change their opacity to 0.8. */ const isSelectionsEmpty = args.length === 0; Object.values(this.nodes).forEach(nodeView => nodeView.handleDeselected({ isSelectionsEmpty })); Object.values(this.edges).forEach(edgeView => edgeView.handleDeselected({ isSelectionsEmpty })); this.selectionIds = args; const isBatchSelection = args.length > 1; this.selectionIds.forEach((id) => { (this.nodes[id] || this.edges[id]).handleSelected({ isBatchSelection }); }); this.geditor.emit(EVENTS.SELECTION_CHANGED, [...this.selectionIds]); } public removeSelections () { if (!this.selectionIds.length || !this.editable) return; const edges = this.selectionIds.filter(id => this.edges.hasOwnProperty(id)); const nodes = this.selectionIds.filter(id => this.nodes.hasOwnProperty(id)); nodes.forEach((id) => { this.getEdgesByNodeId(id).forEach((edgeView) => { !edges.includes(edgeView.id) && edges.push(edgeView.id); }); }); edges.forEach((id) => { if (!this.edges[id].getEditable()) return; this.edges[id].destroy(); delete this.edges[id]; try { this.geditor.emit(EVENTS.EDGE_REMOVED, id); } catch (ex) { console.error(ex); } }); nodes.forEach((id) => { if (!this.nodes[id].getEditable()) return; this.nodes[id].destroy(); delete this.nodes[id]; try { this.geditor.emit(EVENTS.NODE_REMOVED, id); } catch (ex) { console.error(ex); } }); this.resetSelectionIds(); } public removeEdgeBySlotView (slotView: SlotView) { const edgeViews = Object.values(this.edges).filter((edgeView) => { return ( edgeView.srcSlotView === slotView || edgeView.destSlotView === slotView ); }); edgeViews.forEach((edgeView) => { const id = edgeView.id; edgeView.destroy(); delete this.edges[id]; this.geditor.emit(EVENTS.EDGE_REMOVED, id); }); } public updateTransform (transform: ILayout['graph']) { const currentTransform = fromTransform(this.$el.attr('transform')); transform.translate = transform.translate || currentTransform.translate; transform.scale = transform.scale || currentTransform.scale; this.$el.attr('transform', toTransform(transform)); } public destroy() { } public groupSlotsByConnectivity (targetSlotView: SlotView) { const targetType = targetSlotView.type; const geditor = this.geditor; const connectableMethod = typeof geditor.methods.connectable === 'function' ? geditor.methods.connectable : geditor.connectable; const nodeViewList = Object.values(this.nodes); const connectable = <[SlotView]>[]; const unconnectable = <[SlotView]>[]; nodeViewList.forEach((nodeView) => { const slotViewList = targetType === SLOT_TYPE.OUTPUT_SLOT ? nodeView.inputSlots : nodeView.outputSlots; slotViewList.forEach((slotView) => { if (connectableMethod(targetSlotView, slotView, this)) { connectable.push(slotView); } else { unconnectable.push(slotView); } }); }); return { connectable, unconnectable, }; } public getEditable () { return this.editable; } public setEditable (editable = true) { this.editable = editable; } public getNodeById (nodeId: string) { return this.nodes[nodeId] || null; } public getEdgeById (edgeId: string) { return this.edges[edgeId] || null; } public getLayout () { const layout = { graph: {}, nodes: {}, }; const transform = fromTransform(this.$el.attr('transform')); Object.assign(layout.graph, transform); Object.values(this.nodes).forEach((nodeView) => { const translate = nodeView.getTranslate(); layout.nodes[nodeView.id] = translate; }); return layout; } }