Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Animate default edges in resources explorer #1142

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 21 additions & 54 deletions dashboard/components/explorer/DependencyGraph.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, memo, useEffect } from 'react';
import React, { useState, memo } from 'react';
import CytoscapeComponent from 'react-cytoscapejs';
import Cytoscape, { EventObject } from 'cytoscape';
import Cytoscape from 'cytoscape';
import popper from 'cytoscape-popper';

import nodeHtmlLabel, {
CytoscapeNodeHtmlParams
// @ts-ignore
} from 'cytoscape-node-html-label';

// @ts-ignore
import nodeHtmlLabel from 'cytoscape-node-html-label';
// @ts-ignore
import COSEBilkent from 'cytoscape-cose-bilkent';

import EmptyState from '@components/empty-state/EmptyState';

import Tooltip from '@components/tooltip/Tooltip';
import WarningIcon from '@components/icons/WarningIcon';
import { ReactFlowData } from './hooks/useDependencyGraph';
import {
edgeAnimationConfig,
edgeStyleConfig,
graphLayoutConfig,
leafStyleConfig,
Expand All @@ -28,6 +20,7 @@ import {
nodeStyeConfig,
zoomLevelBreakpoint
} from './config';
import { animateEdges } from './animateEdge';

export type DependencyGraphProps = {
data: ReactFlowData;
Expand All @@ -40,17 +33,6 @@ const DependencyGraph = ({ data }: DependencyGraphProps) => {

const dataIsEmpty: boolean = data.nodes.length === 0;

// Type technically is Cytoscape.EdgeCollection but that throws an unexpected error
const loopAnimation = (eles: any) => {
const ani = eles.animation(edgeAnimationConfig[0], edgeAnimationConfig[1]);

ani
.reverse()
.play()
.promise('complete')
.then(() => loopAnimation(eles));
};

const cyActionHandlers = (cy: Cytoscape.Core) => {
// make sure we did not init already, otherwise this will be bound more than once
if (!initDone) {
Expand Down Expand Up @@ -79,8 +61,6 @@ const DependencyGraph = ({ data }: DependencyGraphProps) => {
cy.nodes().leaves().addClass('leaf');
// same for root notes
cy.nodes().roots().addClass('root');
// Animate edges
cy.edges().forEach(loopAnimation);

// Add hover tooltip on edges
cy.edges().bind('mouseover', event => {
Expand All @@ -107,50 +87,37 @@ const DependencyGraph = ({ data }: DependencyGraphProps) => {
});

// Hide labels when being zoomed out
cy.on('zoom', event => {
cy.on('zoom', () => {
const opacity = cy.zoom() <= zoomLevelBreakpoint ? 0 : 1;

Array.from(
document.querySelectorAll('.dependency-graph-node-label'),
document.querySelectorAll<HTMLDivElement>(
'.dependency-graph-node-label'
),
e => {
// @ts-ignore
e.style.opacity = opacity;
e.style.opacity = opacity.toString();
return e;
}
);
});
// Make sure to tell we inited successfully and prevent another init
setInitDone(true);
} else {
// Because the animation requires the DOM, we need to wait until the DOM is ready
animateEdges(
{
direction: 'alternate',
mode: 'speed',
modeValue: 0.2,
randomOffset: true
},
cy
);
}
};

return (
<div className="relative h-full flex-1 bg-dependency-graph bg-[length:40px_40px]">
<CytoscapeComponent
className="h-full w-full"
elements={CytoscapeComponent.normalizeElements({
nodes: data.nodes,
edges: data.edges
})}
maxZoom={maxZoom}
minZoom={minZoom}
layout={graphLayoutConfig}
stylesheet={[
{
selector: 'node',
style: nodeStyeConfig
},
{
selector: 'edge',
style: edgeStyleConfig
},
{
selector: '.leaf',
style: leafStyleConfig
}
]}
cy={(cy: Cytoscape.Core) => cyActionHandlers(cy)}
/>
{dataIsEmpty ? (
<>
<div className="translate-y-[201px]">
Expand Down
161 changes: 161 additions & 0 deletions dashboard/components/explorer/animateEdge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import { Core, EdgeSingular, NodeSingular } from 'cytoscape';
import { IPoint } from 'cytoscape-layers';
import { edgeAnimationConfig, edgeStyleConfig } from './config';

// maybe this can be needed in the future
export function dashAnimation(
edge: EdgeSingular,
duration: number,
offset: number
) {
return edge
.animation({
style: {
'line-dash-offset': offset,
'line-dash-pattern': edgeAnimationConfig.style['line-dash-pattern']
},
duration,
position: edge.sourceEndpoint(),
renderedPosition: edge.sourceEndpoint(),
easing: edgeAnimationConfig.easing as 'linear'
})
.play()
.promise('complete');
}

type Options = {
direction: 'alternate' | 'forward' | 'backward';
mode: 'speed' | 'duration';
modeValue: number;
randomOffset: boolean;
};

function getOrSet<T>(
elem: NodeSingular | EdgeSingular,
key: string,
value: () => T
): T {
const v = elem.scratch(key);
if (v != null) {
return v;
}
const vSet = value();
elem.scratch(key, vSet);
return vSet;
}

function dist(start: IPoint, end: IPoint) {
return Math.sqrt((start.x - end.x) ** 2 + (start.y - end.y) ** 2);
}

export const animateEdges = async (options: Options, cy: Core) => {
let cyLayers;

function computeFactor(
elapsed: number,
offset: number,
start: IPoint,
end: IPoint
) {
const distance = dist(start, end);
let duration = options.modeValue;

if (options.mode !== 'duration' && options.modeValue !== 0) {
duration = distance / options.modeValue;
}

if (
!Number.isFinite(duration) ||
Number.isNaN(duration) ||
duration === 0
) {
return 0;
}

let f = elapsed / duration;

if (options.direction === 'alternate') {
f = f / 2 + offset;
const v = 2 * (f - Math.floor(f) - 0.5);
return Math.abs(v);
}

f += offset;
const v = f - Math.floor(f);
return options.direction === 'forward' ? v : 1 - v;
}

// let animationId: number | null = null;

if (
typeof window !== 'undefined' &&
window.document.URL.includes('explorer')
) {
// Modified but mainly taken from: https://github.com/sgratzl/cytoscape.js-layers/blob/main/samples/animatedEdges.ts
const cytoLayersModule = await import('cytoscape-layers');
cyLayers = cytoLayersModule.layers(cy);
const animationLayer = cyLayers.nodeLayer.insertBefore('canvas');

let start: number | null = null;

let elapsed = 0;
const update = (time: number) => {
if (start == null) {
start = time;
}
elapsed = time - start;
animationLayer.update();
requestAnimationFrame(update);
};
cyLayers.renderPerEdge(
animationLayer,
(
ctx: CanvasRenderingContext2D,
edge: EdgeSingular,
path: Path2D,
startPoint: IPoint,
end: IPoint
) => {
const offset = options.randomOffset
? getOrSet(edge, '_animOffset', () => Math.random())
: 0;
const g = ctx.createLinearGradient(
startPoint.x,
startPoint.y,
end.x,
end.y
);

const v = computeFactor(elapsed, offset, startPoint, end);

const colorStop1 = edgeStyleConfig['line-gradient-stop-colors']
? edgeStyleConfig['line-gradient-stop-colors'][0]
: '#008484';
const colorStop2 = edgeStyleConfig['line-gradient-stop-colors']
? edgeStyleConfig['line-gradient-stop-colors'][1]
: '#33CCCC';

if (typeof colorStop1 === 'string' && typeof colorStop2 === 'string') {
g.addColorStop(Math.max(v - 0.1, 0), colorStop1);
g.addColorStop(v, 'white');
g.addColorStop(Math.min(v + 0.1, 1), colorStop2);
}
ctx.strokeStyle = g;
ctx.lineWidth = 3;
ctx.stroke(path);
},
{
checkBounds: true,
checkBoundsPointCount: 5
}
);
return requestAnimationFrame(update);
}
return {
stop: (animationId: number) => {
if (animationId !== null) {
cancelAnimationFrame(animationId);
}
}
};
};
19 changes: 7 additions & 12 deletions dashboard/components/explorer/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,14 @@ export const leafStyleConfig = {
opacity: 1
} as Cytoscape.Css.Node;

export const edgeAnimationConfig = [
{
zoom: { level: 1 },
easing: 'linear',
style: {
'line-dash-offset': 24,
'line-dash-pattern': [4, 4]
}
export const edgeAnimationConfig = {
easing: 'linear',
style: {
'line-dash-offset': 24,
'line-dash-pattern': [4, 4]
},
{
duration: 4000
}
];
duration: 4000
};

export const nodeHTMLLabelConfig = {
query: 'node', // cytoscape query selector
Expand Down
15 changes: 13 additions & 2 deletions dashboard/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"classnames": "^2.3.2",
"cytoscape": "^3.26.0",
"cytoscape-cose-bilkent": "^4.1.0",
"cytoscape-layers": "^2.4.2",
"cytoscape-node-html-label": "^1.2.2",
"cytoscape-popper": "^2.0.0",
"html-to-image": "^1.11.11",
Expand Down