Skip to content
Snippets Groups Projects
README.md 19.5 KiB
Newer Older
lcottret's avatar
lcottret committed
# viz-core
lcottret's avatar
lcottret committed
## Description
viz-core is a collection of Vue components and composables that allow to visualise and handle networks.
lcottret's avatar
lcottret committed
[Demo of viz-core and its plugins](https://metexplore.pages.mia.inra.fr/metexplorevizv4/)
JeanClement's avatar
JeanClement committed

lcottret's avatar
lcottret committed
## Features
lcottret's avatar
lcottret committed
- Read files in [json Graph format](https://jsongraphformat.info/)
- Zoom
- Drag & Drop
- Undo & Redo
- Style managing
- Random graph creation
lcottret's avatar
lcottret committed
## Getting started
lcottret's avatar
lcottret committed
### Create a vue 3 project
lcottret's avatar
lcottret committed
First, you need to initialize a project. The simplest way is to create a Vue project to stay within the same environment as viz-core. To initialize your project, you can follow the instructions on the following page: [Vue 3 tutorial](https://vuejs.org/guide/quick-start.html).
lcottret's avatar
lcottret committed
We try to be up to date with the last versions of Vue. If you face to bugs with viz-core, please check that the version of Vue3 that you use and the version that is used in viz-core are compatible.
lcottret's avatar
lcottret committed
### Css styles
lcottret's avatar
lcottret committed
Ensure that your project does not contain any default styles (CSS). Since viz-core operates through SVG tags, incorrectly configuring the default style of your page could result in truncated or even non-functional SVGs.

lcottret's avatar
lcottret committed
### Install via npm
lcottret's avatar
lcottret committed

The viz-core package is currently only available on the MetaboHUB forge. To install it, you need to configure an .npmrc file to specify the retrieval path.

```.npmrc
@metabohub:registry=https://forgemia.inra.fr/api/v4/packages/npm/
```

lcottret's avatar
lcottret committed
Then you can install the package:

```
npm install @metabohub/viz-core
```

### Typescript configuration


Once the installation step is completed, you need to declare the module. To do this, add the following line in the env.d.ts file:

```ts 
declare module "@metabohub/viz-core";
```


lcottret's avatar
lcottret committed
## Usage

lcottret's avatar
lcottret committed
![Simple network](./public/doc/network.png)


lcottret's avatar
lcottret committed
### Javascript usage

```javascript
<script setup lang="js">

import { NetworkComponent } from "@metabohub/viz-core";
import { ref } from "vue";

const nodes = {
	A: {
		id: 'A',
		x: 50,
		y: 50
	},
	B: {
		id: 'B',
		x: 100,
		y: 100
	}
}

const links = [
	{
		source: nodes.A,
		target: nodes.B,
		id: ''
	}
]
const network = ref({ id: 'test', nodes: nodes, links: links });
const networkStyle = ref({ nodeStyles: {}, linkStyles: {} });

</script>

<template>
	<NetworkComponent :network="network" :graphStyleProperties="networkStyle">
	</NetworkComponent>
	<br />
	
</template>

<style>
@import "@metabohub/viz-core/dist/style.css";

</style>
lcottret's avatar
lcottret committed
### Typescript usage


```ts
<script setup lang="ts">
import type { Network } from "@metabohub/viz-core/src/types/Network";
import type { GraphStyleProperties } from "@metabohub/viz-core/src/types/GraphStyleProperties";

import { NetworkComponent } from "@metabohub/viz-core";
lcottret's avatar
lcottret committed
import { ref } from "vue";

const nodes = {
	A: {
		id: 'A',
		x: 50,
		y: 50
	},
	B: {
		id: 'B',
		x: 100,
		y: 100
	}
}

const links = [
	{
		source: nodes.A,
		target: nodes.B,
		id: ''
	}
]
lcottret's avatar
lcottret committed
const network = ref<Network>({ id: 'test', nodes: nodes, links: links });
const networkStyle = ref<GraphStyleProperties>({ nodeStyles: {}, linkStyles: {} });

lcottret's avatar
lcottret committed
	<NetworkComponent :network="network" :graphStyleProperties="networkStyle">
	</NetworkComponent>
</template>

<style>
@import "@metabohub/viz-core/dist/style.css";
</style>
lcottret's avatar
lcottret committed

lcottret's avatar
lcottret committed
## Import a json graph

Viz-core is compatible with the [json-graph format](https://jsongraphformat.info/).


Example: 

```json
{
  "graph": {
    "id": "example",
    "nodes": {
      "A": {
        "id": "A",
        "label": "Node A",
        "metadata": {
          "position": {
            "x": 50,
            "y": 50
          }
        }
      },
      "B": {
        "id": "B",
        "label": "Node B",
        "metadata": {
          "position": {
            "x": 100,
            "y": 100
          }
        }
      }
    },
    "edges": [
      {
        "id": "AB",
        "source": "A",
        "target": "B",
        "label": "Edge AB"
      }
    ]
  }
}
```

Use the importNetworkFromUrl method to import a json graph.

```javascript
import { importNetworkFromURL } from "@metabohub/viz-core";
const network = ref<Network>();
cont networkStyle = ref<GraphStyleProperties>();
importNetworkFromURL('/example.json', network, networkStyle);
```

## Navigation

By default, the network can be zoomed and moved. 
- Zoom with the wheel of the mouse and move the whole network
by
- Hold down the left mouse button and move the mouse to move the network. 

## Layout

#### Fixed layout

Node positions are those indicated in the Node objects by the values x and y, or 0 if no position is indicated.

#### Move nodes

You can move a node by holding down the left mouse button on a node and moving the mouse.




<!-- #### Basic force layout -->


lcottret's avatar
lcottret committed
### Style management

The style is managed via the graphStyleProperties props.
To apply a style on a node or a link, the "class" attribute must be filled.

Example:

lcottret's avatar
lcottret committed
![Styles network](./public/doc/networkWithStyle.png)


lcottret's avatar
lcottret committed
```javascript
const nodes = {
	A: {
		id: 'A',
		x: 50,
		y: 50, 
lcottret's avatar
lcottret committed
		classes: ['classNode1']
lcottret's avatar
lcottret committed
	},
	B: {
		id: 'B',
		x: 100,
		y: 100,
lcottret's avatar
lcottret committed
		classes: ['classNode2']
lcottret's avatar
lcottret committed
	}
}

const links = [
	{
		source: nodes.A,
		target: nodes.B,
		id: '',
lcottret's avatar
lcottret committed
		class: ['classLink1']
lcottret's avatar
lcottret committed
	}
]
```

Then, you define the style of each class in the a graphStyleProperties object:

```javascript
const networkStyle = ref({
	nodeStyles: {
		classNode1: {
			fill: 'red',
			stroke: 'gray',
			strokeWidth: 2,
		}, classNode2: {
			fill: 'blue',
			stroke: 'purple',
			strokeWidth: 4,
			shape: 'circle',
			width: 20,
			height: 20
		}
	},
	linkStyles: {
		classLink1: {
			stroke: 'red',
			strokeWidth: 2
		}, class2: {
			stroke: 'blue',
			strokeWidth: 2,
			opacity: 0.5
		}
	}
});

const network = ref({ id: 'test', nodes: nodes, links: links });
```

lcottret's avatar
lcottret committed
In json graph format :

```json
{
  "graph": {
    "id": "example",
    "metadata": {
      "style": {
        "nodeStyles": {
          "classNode1": {
            "fill": "red",
            "stroke": "gray",
            "strokeWidth": 2
          },
          "classNode2": {
            "fill": "blue",
            "stroke": "purple",
            "strokeWidth": 4,
            "shape": "circle",
            "width": 20,
            "height": 20
          }
        },
        "linkStyles": {
			"classLink1": {
				"stroke": "red",
				"strokeWidth": 2
			},
			"classLink2": {
				"stroke": "blue",
				"strokeWidth": 2,
				"opacity": 0.5
			}
		}
      }
    },
```

## Undo & Redo

Undo and redo can be applied on the whole network:


```typescript
const { undo, redo } = createUndoFunction(network);
```

If you want to store only the 10 last actions :


```typescript
const { undo, redo } = createUndoFunction(network, 10);
```

Call the undo method will restore the network value to its previous value.

However, when you move a node, the undo is often too sensitive : we often want that the last position corresponds
to the start of the drag.

To do this :

In the script:

```typescript
const { undo, redo, pause, commit, resume } = createUndoFunction(network);

const onDragStart = () => {
	pause();
}

const onDragEnd = () => {
	resume();
	commit();
}
```

In the template:

```html
<NetworkComponent 
 :network="network"
 :graphStyleProperties="networkStyle"
 @dragStart="onDragStart"
 @dragEnd="onDragEnd"
>
</NetworkComponent>
```


lcottret's avatar
lcottret committed
## Props

### NetworkComponent

| Props | Type | default | Description | Optional |
| ----- | ---- | ------- | ----------- | -------- |
| network | Network | {} | Network object that contains nodes and links of the network | No |
| graphStyleProperties | GraphStyleProperties | {} | Network style object taht contains classes and style associated with of nodes and links | Yes |
lcottret's avatar
lcottret committed
| hideAllNodes | Boolean | false | If true, hide all nodes | Yes | 
| hideAllLinks | Boolean | false | If true, hide all links | Yes | 
lcottret's avatar
lcottret committed

A `<slot />` tag is also available in the component. This tag allows you to add other components containing SVGs, which will be directly handled by the network's SVG tag, enabling you to add elements directly to the graph.

```ts
<template>
	<NetworkComponent 
		:network="network"
		:graphStyleProperties="networkStyle"
	>
		<yourComponent />
	</NetworkComponent>
</template>
```


lcottret's avatar
lcottret committed

JeanClement's avatar
JeanClement committed
## Types 

### Network

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| id | string | Network's id |
| label | string | Network's label |
| nodes | {[key: string] Node} | Object that contains nodes |
| links | Array<Link> | List that contains links |
| type | string | Network type (metabolic, proteomic, knowledge, ...) |
| rescale | boolean | Allows you to implement an automatic rescale |

### Node

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| id | string | Node's id |
| label | string | Node's label |
| x | number | X node's position |
| y | number | Y node's position |
| classes | Array<string> | Node's classes to manage style |
| hidden | boolean | Allows you to display or not the node |
| metadata | {[key: string]: string | number | {[key: string]: string | number} | Array<string> | boolean} | Node's metadata |

### Link

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| id | string | Link's id |
| label | string | Link's label |
| source | Node | Source node of the link |
| target | Node | Target node of the link |
| type | string | Link's type |
| classes | Array<string> | Link's classes to manage style |
| relation | string | Link's relation |
| directed | boolean | Allows you to choose if the link is directed or not |
| metadata | {[key: string]: string | number | {[key: string]: string | number} | Array<string> | boolean} | Link's metadata |

### GraphStyleProperties

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| nodeStyles | { [key: string]: NodeStyle } | Object that contains nodes classes name associated to their style |
| linkStyles | { [key: string]: LinkStyle } | Object that contains links classes name associated to their style |
| curveLine | boolean | Allows you to choose if links are curve or not |
| directed | boolean | Allows you to choose if links are directed or not |

### NodeStyle

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| height | number | Node's height |
| width | number | Node's width |
| fill | string | Node's color |
| strokeWidth | number | Node's border width |
| stroke | string | Node's border color |
| displayLabel | boolean | Allows you to display or not nodes label |
LIOTIER MARION's avatar
LIOTIER MARION committed
| labelPosition | string | Where to display the label compared to the node (middle (default), top or bottom) |
JeanClement's avatar
JeanClement committed
| label | string | Allows you to choose which node's attribut is display as label (id or label) |
LIOTIER MARION's avatar
LIOTIER MARION committed
| shape | string | Node's shape (rectangle, circle, diamond, triangle, inverseTriangle, imageRect or imageCircle) |
JeanClement's avatar
JeanClement committed
| opacity | number | Node's opacity (between 0 and 1) |

LIOTIER MARION's avatar
LIOTIER MARION committed
If the shape is an image, you need to add the image file path in the nodes metadata (`metadata.image: string`).

JeanClement's avatar
JeanClement committed
### LinkStyle

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| display | boolean | Allows you to display or not links |
| stroke | string | Link's color |
| strokeWidth | number | Link's width |
| opacity | number | Link's opacity (between 0 and 1) |

### ForceParams

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| charge | ForceChargeParams | Manage charge parameters for d3.forceSimulation |
| collide | ForceCollideParams | Manage collide parameters for d3.forceSimulation |
| gravity | ForceGravityParams | Manage gravity parameters for d3.forceSimulation |
| link | ForceLinkParams | Manage link parameters for d3.forceSimulation |

### ForceChargeParams

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| strength | number | Force applies mutually amongst all nodes |
| min | number | Minimal distance between two nodes |
| max | number | Maximal distance between two nodes | 

### ForceCollideParams 

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| strength | number | Force to prevent nodes overlapping |
| radius | number | Radius apply to nodes |
| iteration | number | Number of iterations per application |

### ForceGravityParams 

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| strength | number | Force applies on nodes to force them to be attract by the center |

### ForceLinkParams

| Attribut | Type | Description |
| -------- | ---- | ----------- |
| distance | number | Sets the distance accessor to the specified number or function, re-evaluates the distance accessor for each link, and returns this force |
| iteration | number | Sets the number of iterations per application to the specified number and returns this force |



JeanClement's avatar
JeanClement committed
## Events

### NetworkComponent 

| Name | Trigger | Output |
| ---- | ------- | ------ |
| nodeLeftClickEvent | left click on node | Event: MouseEvent, node: Node |
| nodeRightClickEvent | right click on node | Event: MouseEvent, node: Node |
| mouseOverNode | Mouse over a node | Event: MouseEvent, node: Node |
| mouseLeaveNode | Mouse leave a node | Event: MouseEvent, node: Node |
| dragStart | Start dragging a node | Void |
| dragEnd | Stop dragging a node | Void |

## Composables

### CreateRandomGraph

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| useRandomNetwork | numNodes: number, numLinks: number | Create a random graph that contains number of nodes and links define in arguments | Network |

### ReadJsonGraph

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| readJsonGraph | jsonGraph: string | Read graph data and return network and styles object | { network: Network, networkStyle: GraphStyleProperties } | 

### UseCreateForceLayout

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| createStaticForceLayout | network: Network, autoRescale: Boolean = false | Take a network and apply a d3 force layout algorithm on WITHOUT simulation | Promise<Network> |
| createForceLayout | network: Network, autoRescale: Boolean = false | Take a network and apply a d3 force layout algorithm on WITH simulation | Network |
| addNewParams | param: ForceParams | Add new parameters for d3.force layout | void |
| applyParamsToForceLayout | network: Network, callBack: Function = () => {} | If new parameters have been add, apply this parameters to d3.force layout and restart simulation | void |
JeanClement's avatar
JeanClement committed

### UseGraphManager

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| switchGraphMode | mode: boolean | Change a boolean to switch between two modes. For example between selection and zoom for graph panel | boolean |
| nodeSelection | node: Node | Select or unselect a node | void |
| defineBrush | network: Network, styles: {[key: string]: NodeStyle} | Define brush tag and functions to select multiple nodes at ctrl + left click | void |
| stopBrush | X | Remove brush tag and functions | void |
| switchCursor | style: string | Change cursor style for brush. Allow to switch between default (panzoom) and crosshair (brush) | void |
| verticalNodesAlign | network: Network, styles: {[key: string]: NodeStyle} | Align vertically selected nodes (in list) | void |
| horizontalNodesAlign | network: Network, styles: {[key: string]: NodeStyle} | Align horizontally selected nodes (in list) | void |
| unselectAll | network: Network | Unselect all selected nodes | void |

### UseImportNetwork

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| importNetworkFromURL | url: string, network: Ref<Network>, networkStyle: Ref<GraphStyleProperties>, callbackFunction = () => {} | Import network at JSONGraph format from an URL | void |
| importNetworkFromFile | file: File, network: Ref<Network>, networkStyle: Ref<GraphStyleProperties>, callbackFunction = () => {} | Import network at JSONGraph format from a file | void |

### UseManageNetworkData

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| checkNodesPosition | network: Network, threshold: number | Check if nodes of network have pos set to 0, 0. And returns a boolean according to a percentage threshold | boolean |
| removeNode | nodeId: string, network: Network, rIsoNode: boolean = false | Remove specific node from network object | void |
| removeAllSelectedNodes | network: Network, rIsoNode: boolean = false | Remove nodes from network object which have selected attribut at true | void |
JeanClement's avatar
JeanClement committed
| duplicateNode | nodeId: string, network: Network, networkStyle: GraphStyleProperties | Duplicate specific node in network object | void |
| removeIsolatedNodes | network: Network | Remove all nodes that are not connected with any other node | void |
| removeAllNodesByAttribut | network: Network, attribut: string, rIsoNode: boolean = false | Remove all nodes according to a specific metadata attribut | void |
| duplicateAllNodesByAttribut | network: Network, networkStyle: GraphStyleProperties, attribut: string | Duplicate all nodes according to a specific metadata attribut | void |
| switchLineStyle | networkStyle: GraphStyleProperties | Switch between line path and curve path | void |

### UseSaveNetwork

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| saveNetworkAsJSON | network: Network, networkStyle: GraphStyleProperties | Download JSONGraph of current visualisation for future use | void |

### UseStyleManager

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| addLinkStyle | link: Link, linkStyle: LinkStyle, styleName: string, networkStyle: GraphStyleProperties | Apply specific style to one link | void |
| removeLinkStyle | link: Link, styleName: string | Remove specific style to one link | void |
| addNodeStyle | node: Node, nodeStyle: NodeStyle, styleName: string, networkStyle: GraphStyleProperties | Apply specific style to one node | void |
| removeNodeStyle | node: Node, styleName: string | Remove specific style to one node | void |
| nodeBorderColorByAttribut | network: Network, networkStyle: GraphStyleProperties, attribut: string | Color node border according to a metadata attribut. Must be a string | void |
| updateClassStyle | networkStyle: GraphStyleProperties, className: string, styleObject: NodeStyle or LinkStyle, targetObject: string | Update style for a specific class | void |
| createClassStyle | network: Network, networkStyle: GraphStyleProperties, className: string, styleObject: NodeStyle or LinkStyle, targetObject: string, listTarget: Array<string> | Create new style class for a list of nodes or links | void |
| addMappingStyleOnNode | type: string, style: string, targetLabel: string, values: Function or {[key: string]: string or number} or string, mappingName: string, conditionName: string, data: {[key: string]: {[key: string]: string or number} or Array<string>}, network: Network, graphStyleProperties: GraphStyleProperties
 | Apply style on nodes according to mapping values | void |
| removeMappingStyleOnNode | network: Network, networkStyle: GraphStyleProperties, mappingName: string, conditionName: string, type: string, style: string | Remove specific mapping style over network | void |


### UseUndo

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| createUndoFunction | objectUndoable: any, capacityNumber: number | Create different methods from useRefHistory to a specific object to manage undo / redo functions | {undo: Function, redo: Function, commit: Function, resume: Function, pause: Function} |

### UseZoomSvg

| Name | Arguments | Description | Output |
| ---- | --------- | ----------- | ------ |
| initZoom | X | Apply d3.zoom() event on graph svg | d3.ZoomBehavior<Element, unknown> |
| stopZoom | X | Remove d3.zoom() event from graph SVG | void |
| rescale | zoomObject: d3.ZoomBehavior<Element, unknown> | Fit network to graph svg (screen) | void |