Git Product home page Git Product logo

cytoscape.js-automove's Introduction

cytoscape-automove

Description

An extension for Cytoscape.js that automatically updates node positions based on specified rules (demo)

Common usecases:

  • Making one node move in step with another node
  • Constraining a node within a boundary
  • Using a node to represent an n-ary interaction

Dependencies

  • Cytoscape.js ^3.2.0

Usage instructions

Download the library:

  • via npm: npm install cytoscape-automove,
  • via bower: bower install cytoscape-automove, or
  • via direct download in the repository (probably from a tag).

Import the library as appropriate for your project:

ES import:

import cytoscape from 'cytoscape';
import automove from 'cytoscape-automove';

cytoscape.use( automove );

CommonJS require:

let cytoscape = require('cytoscape');
let automove = require('cytoscape-automove');

cytoscape.use( automove ); // register extension

AMD:

require(['cytoscape', 'cytoscape-automove'], function( cytoscape, automove ){
  automove( cytoscape ); // register extension
});

Plain HTML/JS has the extension registered for you automatically, because no require() is needed.

API

Each time cy.automove() is called, the specified rules are added to the core instance:

let defaults = {
  // specify nodes that should be automoved with one of
  // - a function that returns true for matching nodes
  // - a selector that matches the nodes
  // - a collection of nodes (very good for performance)
  nodesMatching: function( node ){ return false; },

  // specify how a node's position should be updated with one of
  // - function( node ){ return { x: 1, y: 2 }; } => put the node where the function returns
  // - { x1, y1, x2, y2 } => constrain the node position within the bounding box (in model co-ordinates)
  // - { x1, y1, x2, y2, type: 'inside' } => constrain the node position within the bounding box (in model co-ordinates)
  // - { x1, y1, x2, y2, type: 'outside' } => constrain the node position outside the bounding box (in model co-ordinates)
  // - 'mean' => put the node in the average position of its neighbourhood
  // - 'viewport' => keeps the node body within the viewport
  // - 'drag' => matching nodes are effectively dragged along
  reposition: 'mean',

  // specify when the repositioning should occur by specifying a function that
  // calls update() when reposition updates should occur
  // - function( update ){ /* ... */ update(); } => a manual function for updating
  // - 'matching' => automatically update on position events for nodesMatching
  // - set efficiently and automatically for
  //   - reposition: 'mean'
  //   - reposition: { x1, y1, x2, y2 }
  //   - reposition: 'viewport'
  //   - reposition: 'drag'
  // - default/undefined => on a position event for any node (not as efficient...)
  when: undefined,



  //
  // customisation options for non-function `reposition` values
  //

  // `reposition: 'mean'`

    // specify nodes that should be ignored in the mean calculation
    // - a function that returns true for nodes to be ignored
    // - a selector that matches the nodes to be ignored
    // - a collection of nodes to be ignored (very good for performance)
    meanIgnores: function( node ){ return false; },

    // specify whether moving a particular `nodesMatching` node causes repositioning
    // - true : the mid node can't be independently moved/dragged
    // - false : the mid node can be independently moved/dragged (useful if you want the mid node to use `reposition: 'drag' in another rule with its neighbourhood`)
    meanOnSelfPosition: function( node ){ return true; },

  // `reposition: 'drag'`

    // specify nodes that when dragged cause the matched nodes to move along (i.e. the master nodes)
    // - a function that returns true for nodes to be listened to for drag events
    // - a selector that matches the nodes to be listened to for drag events
    // - a collection of nodes to be listened to for drag events (very good for performance)
    dragWith: function( node ){ return false; }
};

let options = defaults;

let rule = cy.automove( options );

A rule has a number of functions available:

rule.apply(); // manually apply a rule

rule.enabled(); // get whether rule is enabled

rule.toggle(); // toggle whether the rule is enabled

rule.disable(); // temporarily disable the rule

rule.enable(); // re-enable the rule

rule.destroy(); // remove and clean up just this rule

You can also remove all the rules you previously specified:

cy.automove('destroy');

Events

  • automove : Emitted on a node when its position is changed by a rule
    • node.on('automove', function( event, rule ){})

Build targets

  • npm run test : Run Mocha tests in ./test
  • npm run build : Build ./src/** into cytoscape-automove.js
  • npm run watch : Automatically build on changes with live reloading (N.b. you must already have an HTTP server running)
  • npm run dev : Automatically build on changes with live reloading with webpack dev server
  • npm run lint : Run eslint on the source

N.b. all builds use babel, so modern ES features can be used in the src.

Publishing instructions

This project is set up to automatically be published to npm and bower. To publish:

  1. Build the extension : npm run build:release
  2. Commit the build : git commit -am "Build for release"
  3. Bump the version number and tag: npm version major|minor|patch
  4. Push to origin: git push && git push --tags
  5. Publish to npm: npm publish .
  6. If publishing to bower for the first time, you'll need to run bower register cytoscape-automove https://github.com/cytoscape/cytoscape.js-automove.git
  7. Make a new release for Zenodo.

cytoscape.js-automove's People

Contributors

alexcli avatar jsclee avatar maxkfranz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cytoscape.js-automove's Issues

`meanIgnores` : Option to exclude certain elements from calculation used in `reposition: 'mean'`

Sometimes, you don't want a particular node to affect the automoved node's position in reposition: 'mean'. For example, you may not want the ghost node to shift an intermediate node (i.e. edgeType === 'node') when used with the edgehandles extension.

Usecase : Editing interaction participants in Factoid

// for `reposition: 'mean'`, specify nodes that should be ignored in the mean calculation
// - a function that returns true for nodes to be ignored
// - a selector that matches the nodes to be ignored
// - a collection of nodes to be ignored (very good for performance)
meanIgnores: function( node ){ return false; }

Preset for dragging all nodes in a component together

Add a set of options that make it such that dragging a node drags along its component with it. This builds from #16.

This could be a nice-to-have feature in future. It's easy for the dev to implement this on his own if the graph is static, but it's better to have a built-in preset for the dynamic case to be performant.

Cannot drag successors of arbitrary node

I want to be able to drag an arbitrary node, and have it's successors move with it. This is a generally desirable thing in directed graphs (I don't think it's standard functionality though).
I have many plausible ways this might work, but don't; probably due to the execution order of click events. This is the neatest:
cy.automove({nodesMatching: function(node){return node.selected()? node.successors():null}, reposition:'drag',dragWith: cy.nodes()})

Sounds plausible, but nothing is ever detected as being selected. There is a similar problem with this slightly cruder approach:

cy.nodes().on('vmousedown', function(e){
cy.automove("destroy");
  var ele = e.target;
  console.log('clicked ' + ele.id());
cy.automove({nodesMatching: cy.$id(ele.id()).successors(), reposition:'drag',dragWith: cy.$id(ele.id())})
});

So, is there a way to achieve this without resorting to adding every permutation of nodes and successors, as rules? Or do we need a code change?

Thanks

Move 2 nodes in same y coordinate and keep same distance in x

Hi,

In the demo, node #e and #f is restricts to have same y.
I would like to tweak this to keep the same distance in horizontal.

I tried

// Make only #e grabbable but not #f, when I move e, f should always follow e.
{ data: { id: 'f' }, selectable: false, grabbable: false }

cy.automove({
  nodesMatching: '#e, #f',
  reposition: function( node ){
     var pos = node.position();
     if( node.grabbed() ){ return pos; }
     
     var otherNode = eAndF.not( node );
     return {
       x: otherNode.position('x') + 40,
       y: otherNode.position('y')
     };
  },
  when: 'matching'
});

However, this seems to trigger 'matching' rule recursively and results in infinite loop.

I tried to write custom when function but I could not figure out how to bind to some event.
If I don't bind, this only called once and it does not listen for any event.

when: function(update) {
  // some rule
  update();
}

How can I achieve #f node follow #e in same y coordinate and same horizontal distance?

TypeError: rule.listener is not a function

I can't seem to get this extension to work. On load I immediately get an error:

Uncaught TypeError: rule.listener is not a function
    at addRule (cytoscape-automove.js:388)
    at Core.automove (cytoscape-automove.js:489)
    ...

Here's what my setup looks like:

import cytoscape from 'cytoscape';
import automove from 'cytoscape-automove';

cytoscape.use(automove);

export default function CytoscapeGraph({ height }) {
	const graphRef = React.useRef();

	React.useEffect(() => {
		const cy = cytoscape({
			userZoomingEnabled: false,
			userPanningEnabled: false,
			style: { ... },
		});

		if (graphRef.current) {
			// this is where all the nodes and edges are added using cy.add()
			buildGraphFromActions(cy, actions);
			cy.mount(graphRef.current);
			cy.layout({ ... }).run();
			cy.automove({
				nodesMatching: cy.nodes(),
				reposition: node => {
					const pos = node.position();
					return { y: pos.y };
				},
			});
			cy.fit(cy.elements());
		}
		...
		return () => {
			cy.destroy();
		};
	}, [...]);

	return <div ref={graphRef} />;
}

If I add a when: update => update(), things don't blow up, but I don't see my reposition function get called at all. Does all this have something to do with the fact that I am building my graph after my initial cytoscape({ ... }) call?

Uncaught RangeError: Maximum call stack size exceeded - when creating rules

First off thank you this extension, its a real help in working with cytoscape.
I have a rather simple rule to keep my Y-axis fixed and only reposition x on drag (prevent user to change y axis). My graph is fairly large with 200 nodes. When I try this out it fails with Max call stack size error

Hope someone can shed some light on what can be made different to make it not recursively exceed stack size.

this._automoveRule = this.cy.automove({
      nodesMatching: this.cy.nodes(),
      reposition: (node) => {
        return {
          x: node.position().x,
          y: node.data().y
        };
      },
      when: 'matching'
    });

`reposition: 'drag'` : Option to drag certain elements along with others

Sometimes you want to treat certain nodes as being dragged along with a particular node when it's grabbed. For example, you might want to drag along an entire component when a node within it is dragged.

Usecase : Dragging interaction participants in Factoid along with an interaction

  • reposition: 'drag' enables the mode on nodesMatching -- these are the nodes that get dragged with the master nodes
  • dragWith: otherNodes specifies the master nodes that are listened to for drag events
    • otherNodes can be a collection, selector, orfunction( node ){ return trueOrFalse; }
// for `reposition: 'drag'`, specify nodes that when dragged cause the matched nodes to move along
// - a function that returns true for nodes to be listened to for drag events
// - a selector that matches the nodes to be listened to for drag events
// - a collection of nodes to be ignored (very good for performance)
dragWith: function( node ){ return false; }

ES import not working and 'this' not defined

Hi, I am a beginner programmer and I have two problems.

One, I cannot import import automove using the ES import functionality. I am trying to serve a static HTML page containing JS scripts using NodeJS and ExpressJS and in one of my public script files I make the call:

import automove from './cytoscape-automove.js'.

and I get the error: Uncaught SyntaxError: The requested module './cytoscape-automove.js' does not provide an export named 'automove'.

The second problem is if I try to load cytoscape-automove.js through an HTML <script type = 'module'> tag, I get the error: cytoscape-automove.js:9 Uncaught TypeError: Cannot set property 'cytoscapeAutomove' of undefined.

Looking through the code, I see that an argument of this is provided to the webpackUniversalModuleDefinition function and I would naively think that this is just a reference to the global object but unfortunately I am not familiar with webpack and how it bundles assets.

How to undo rules

Hello,

I just found this repo and it's been super useful. I am dynamically creating nodes in cytoscape and rules to go along with them. Basically I'm working with clusters where the root node has a layer of leaf nodes around it and they should move freely individually, but when the root moves, every leaf moves with it. It's been working quite well with the following:

var rules = cy.automove({ nodesMatching: cy.$("#"+port.id()), reposition: 'drag', dragWith: cy.$("#"+obj.id()) });

My problem now is that when I run rules.destroy() I expected the rules to stop their effect. Unfortunately I must be missing how to actually undo rules that were set into place. I couldn't figure it out and would appreciate any tips. Thanks!

demo.html doesn't work, or I don't understand it

I would like to use this extension to enable dragging of groups of nodes

but leaving aside how I will select them for the moment, I can't get anything to work.

when I download and run your demo.html -- nothing seems to work.

#mid starts way off-screen

#d isn't limited to a box

#e and #f aren't bounded and don't move together

#g can be dragged out of the window, then zoom out shows it again

(tried chrome 59 over mac os x 10.12.3)
(tried safari 10.0.3 over mac os x 10.12.3)
(tried opera 43 over mac os x 10.12.3)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.