Move the view moves of the network graph into a layout controller

NetworkLayoutController now handles the switch between the tree and the
force layout, the settling of the force layout and the move of the view
to a selected node, with a series center/zoom that ECharts animates.

The style fade and the selection glide go, as their PR is closed.

The first force view stores the chart size, so after a resize the
switch back fits the nodes instead of using stale pixels. The tree uses
Number.EPSILON as nodeScaleRatio, as ECharts reads 0 as 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
jbouwhandClaude Opus 5.5 committed 2026-12-01 16:15:22 +00:00
1 parent cfbc45bb2e
commit 149f159880
7 files changed
+507 -674

No files matched your search

+33 -281
View File
@@ -18,24 +18,13 @@ import type { HaECOption } from "../../resources/echarts/echarts";
import "./ha-chart-base";
import type { HaChartBase } from "./ha-chart-base";
import { deepEqual } from "../../common/util/deep-equal";
import type {
FollowRoam,
GraphView,
ViewNeighbor,
ViewTransform,
} from "./network-graph-view";
import type { FollowRoam, ViewNeighbor } from "./network-graph-view";
import { labelReach, selectedNodeRoam } from "./network-graph-view";
import {
easeInOutCubic,
labelReach,
layoutBounds,
layoutRoam,
partialRoam,
remainingFraction,
roamSource,
SELECTED_NODE_ANIMATION_DURATION,
selectedNodeRoam,
} from "./network-graph-view";
import { NetworkStyleFadeController } from "./network-style-fade-controller";
graphSeries,
graphView,
NetworkLayoutController,
} from "./network-layout-controller";
export interface NetworkNode {
id: string;
@@ -108,13 +97,6 @@ const LEGEND_SELECT_EVENTS = [
const FOLLOW_ROAM = "follow-selected-node";
// The nodes of another layout move for at most this many ms
const LAYOUT_ANIMATION_TIMEOUT = 1000;
// A frame that takes longer, such as the first one after new data, advances
// the animation by at most this, so the acceleration is not skipped
const MAX_ANIMATION_FRAME_TIME = 1000 / 30;
type Displayable = ReturnType<
ReturnType<EChartsType["getZr"]>["storage"]["getDisplayList"]
>[number];
@@ -155,12 +137,6 @@ export class HaNetworkGraph extends LitElement {
*/
@property({ attribute: false }) public treeLayout = false;
/**
* Fade colors and borders when the data changes. Off for graphs that update
* often, whose nodes and links would be fading most of the time.
*/
@property({ attribute: false }) public animateStyleChanges = false;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _highlightedNodes?: Set<string>;
@@ -173,10 +149,6 @@ export class HaNetworkGraph extends LitElement {
@state() private _showLabels = true;
// Without the force layout until the nodes moved back to their positions in
// it, as the first step of the force layout stops their animation
@state() private _settlingLayout = false;
// Not reactive: a new series option starts the layout again, so a drop only
// reaches the option with the next render
private _nodePositions: Record<string, { x: number; y: number }> = {};
@@ -199,33 +171,25 @@ export class HaNetworkGraph extends LitElement {
private _followedChart?: EChartsType;
private _selectAnimationFrame?: number;
private _stopWaitingForLayout?: () => void;
// From a switch between the tree and the force layout until its nodes moved
private _layoutSwitching = false;
// How the force layout first showed its nodes, which the view goes back to
// after the tree layout
private _initialForceView?: ViewTransform;
private _selectAnimationLastFrame?: number;
private _selectAnimationElapsed = 0;
private _selectAnimationEased = 0;
@query("ha-chart-base") private _baseChart?: HaChartBase;
private _layout = new NetworkLayoutController(this, {
chart: () => this._baseChart,
treeLayout: () => this.treeLayout,
reducedMotion: () => this._reducedMotion,
selectedNode: () => this.selectedNode,
selectedNodeRoam: (chart) => this._selectedNodeRoam(chart),
saveNodePositions: () => this._saveNodePositions(),
// A drag or zoom while the view moves still stops following
moveStarted: () => {
this._followSelectedNode = !!this.selectedNode;
this._updateFollowing();
},
moveEnded: () => this._centerOnSelectedNode(),
});
constructor() {
super();
// Adds itself to the controllers of this element
new NetworkStyleFadeController(this, {
chart: () => this._baseChart,
data: () => this.data,
enabled: () => this.animateStyleChanges && !this._reducedMotion,
});
if (!GraphChart) {
import("echarts/lib/chart/graph/install").then((module) => {
GraphChart = module;
@@ -240,14 +204,6 @@ export class HaNetworkGraph extends LitElement {
this._physicsEnabled =
this.data.nodes.length <= PHYSICS_DISABLE_THRESHOLD;
}
if (changedProperties.get("treeLayout") !== undefined) {
if (this.treeLayout) {
// The force layout comes back from here
this._saveNodePositions();
} else if (!this._reducedMotion && this._baseChart) {
this._settlingLayout = true;
}
}
}
protected render() {
@@ -266,7 +222,7 @@ export class HaNetworkGraph extends LitElement {
.data=${this._getSeries(
this.data,
!this.treeLayout &&
!this._settlingLayout &&
!this._layout.settling &&
(this._physicsEnabled ?? false),
this._reducedMotion,
this._showLabels,
@@ -352,155 +308,11 @@ export class HaNetworkGraph extends LitElement {
this._applyHighlighting();
this._updateMouseoverHandler();
}
// Another layout moves every node, so the view moves along. A roam while
// ECharts moves the nodes draws the edges at their end at once, so
// following the selected node waits for the nodes. A drag or zoom in the
// meantime still stops following.
if (changedProperties.get("treeLayout") !== undefined) {
this._layoutSwitching = true;
this._followSelectedNode = !!this.selectedNode;
this._stopSelectAnimation();
this._updateFollowing();
const finish = () => {
this._layoutSwitching = false;
this._settlingLayout = false;
this._centerOnSelectedNode();
};
const baseChart = this._baseChart;
if (!baseChart) {
// Nothing is drawn, so nothing moves
finish();
} else {
baseChart.updateComplete.then(() => {
this._moveViewToLayout();
this._afterLayoutAnimation(finish);
});
}
} else if (changedProperties.has("selectedNode")) {
this._moveToSelectedNode();
if (changedProperties.has("selectedNode")) {
this._layout.moveToSelectedNode();
}
}
private _afterLayoutAnimation(callback: () => void) {
this._stopWaitingForLayout?.();
const chart = this._baseChart?.chart;
if (!chart || chart.isDisposed() || this._reducedMotion) {
callback();
return;
}
const done = () => {
this._stopWaitingForLayout?.();
callback();
};
const timeout = window.setTimeout(done, LAYOUT_ANIMATION_TIMEOUT);
chart.on("finished", done);
this._stopWaitingForLayout = () => {
clearTimeout(timeout);
chart.off("finished", done);
this._stopWaitingForLayout = undefined;
};
}
// A new center and zoom of the series moves the view in the same animation
// as the nodes, as ECharts animates the transform of the group they are in
private _moveViewToLayout() {
const chart = this._baseChart?.chart;
const series = this._getGraphSeries(chart);
const view = series?.coordinateSystem;
const roam =
chart &&
view &&
(this.selectedNode
? this._selectedNodeRoam(chart)
: this._layoutRoam(chart));
if (!roam) {
return;
}
const viewRect = view.getViewRect();
const center = view.pointToData(
roamSource(roam, {
x: viewRect.x + viewRect.width / 2,
y: viewRect.y + viewRect.height / 2,
})
);
// The view keeps its zoom to itself, ECharts syncs it back to the option
const currentZoom: number = series.get("zoom") ?? 1;
chart.setOption({
series: [{ id: "network", center, zoom: currentZoom * (roam.zoom ?? 1) }],
});
}
// From layout to pixels
private _viewTransform(chart: EChartsType): ViewTransform {
const [x, y] = chart.convertToPixel({ seriesId: "network" }, [0, 0]);
const [x1] = chart.convertToPixel({ seriesId: "network" }, [1, 0]);
return { scale: x1 - x, x, y };
}
private _captureInitialForceView = () => {
const chart = this._baseChart?.chart;
// Not while the view moves after a switch from the tree layout
if (
this._initialForceView ||
this.treeLayout ||
this._settlingLayout ||
this._layoutSwitching ||
this._selectAnimationFrame !== undefined ||
!chart ||
chart.isDisposed() ||
!this._getGraphSeries(chart)?.forceLayout
) {
return;
}
this._initialForceView = this._viewTransform(chart);
chart.off("finished", this._captureInitialForceView);
};
private _graphView(chart: EChartsType, series: any): GraphView {
return {
width: chart.getWidth(),
height: chart.getHeight(),
zoom: series.coordinateSystem.getRoamTransform()[0],
treeLayout: this.treeLayout,
};
}
private _layoutRoam(chart: EChartsType): FollowRoam | undefined {
const series = this._getGraphSeries(chart);
if (!series?.coordinateSystem) {
return undefined;
}
const positions: (number[] | undefined)[] = [];
series.getGraph().eachNode((node: any) => {
positions.push(node.getLayout());
});
const bounds = layoutBounds(positions);
return bounds
? layoutRoam(
this._graphView(chart, series),
bounds,
this._viewTransform(chart),
this._initialForceView
)
: undefined;
}
private _moveToSelectedNode() {
this._followSelectedNode = !!this.selectedNode;
this._stopSelectAnimation();
// Without a chart yet there is no view to glide from. A layout switch
// moves the view to the node once its nodes moved.
if (
this.selectedNode &&
this._baseChart?.chart &&
!this._reducedMotion &&
!this._layoutSwitching
) {
this._selectAnimationFrame = requestAnimationFrame(this._animateView);
}
this._updateFollowing();
}
private _nodeMatchesFilter(node: NetworkNode, lowerFilter: string): boolean {
if (node.name?.toLowerCase().includes(lowerFilter)) {
return true;
@@ -540,8 +352,9 @@ export class HaNetworkGraph extends LitElement {
type: "graph",
layout: physicsEnabled ? "force" : "none",
// Nodes of a tree keep their size, like the labels, so a zoom spreads
// the rows instead of growing the nodes into each other
nodeScaleRatio: treeLayout ? 0 : 0.6,
// the rows instead of growing the nodes into each other. ECharts reads
// 0 as 1.
nodeScaleRatio: treeLayout ? Number.EPSILON : 0.6,
draggable: true,
roam: true,
roamTrigger: "global",
@@ -800,7 +613,9 @@ export class HaNetworkGraph extends LitElement {
chart?.getZr().on("dragstart", this._handleDragStart);
chart?.getZr().on("drag", this._handleDrag);
chart?.getZr().on("dragend", this._handleDragEnd);
chart?.on("finished", this._captureInitialForceView);
if (chart) {
this._layout.chartSetup(chart);
}
for (const event of LEGEND_SELECT_EVENTS) {
chart?.on(event, this._handleLegendChange);
}
@@ -953,56 +768,9 @@ export class HaNetworkGraph extends LitElement {
private _stopFollowing = () => {
this._followSelectedNode = false;
this._stopSelectAnimation();
this._updateFollowing();
};
// Moves the view to a newly selected node in steps, so the user can follow
// the change. The remaining distance is measured each frame, as the node can
// still move.
private _animateView = (now: number) => {
if (this._selectAnimationLastFrame !== undefined) {
this._selectAnimationElapsed += Math.min(
now - this._selectAnimationLastFrame,
MAX_ANIMATION_FRAME_TIME
);
}
this._selectAnimationLastFrame = now;
const progress = Math.min(
1,
this._selectAnimationElapsed / SELECTED_NODE_ANIMATION_DURATION
);
const eased = easeInOutCubic(progress);
const fraction =
progress >= 1 ? 1 : remainingFraction(eased, this._selectAnimationEased);
this._selectAnimationEased = eased;
const chart = this._followedChart;
const roam = chart && this._selectedNodeRoam(chart);
if (chart && roam) {
chart.dispatchAction({
type: "graphRoam",
from: FOLLOW_ROAM,
seriesId: "network",
...partialRoam(roam, fraction),
});
}
if (progress < 1) {
this._selectAnimationFrame = requestAnimationFrame(this._animateView);
return;
}
this._stopSelectAnimation();
};
private _stopSelectAnimation() {
if (this._selectAnimationFrame !== undefined) {
cancelAnimationFrame(this._selectAnimationFrame);
}
this._selectAnimationFrame = undefined;
this._selectAnimationLastFrame = undefined;
this._selectAnimationElapsed = 0;
this._selectAnimationEased = 0;
}
// A roam dispatched while ECharts renders is queued, so a flag set around
// dispatchAction would be cleared before the event fires
private _handleGraphRoam = (ev: unknown) => {
@@ -1013,13 +781,7 @@ export class HaNetworkGraph extends LitElement {
private _centerOnSelectedNode = () => {
const chart = this._followedChart;
// While the view moves to a new node, the animation follows it, and while
// the layout switches, the view moves along with the nodes
if (
!chart ||
this._selectAnimationFrame !== undefined ||
this._layoutSwitching
) {
if (!chart || this._layout.moving) {
return;
}
const roam = this._selectedNodeRoam(chart);
@@ -1058,7 +820,7 @@ export class HaNetworkGraph extends LitElement {
}
}
return selectedNodeRoam(
this._graphView(chart, series),
graphView(chart, series, this.treeLayout),
{ x, y },
neighbors,
this.treeLayout ? this._labelReach(series, node) : undefined
@@ -1084,12 +846,6 @@ export class HaNetworkGraph extends LitElement {
public disconnectedCallback(): void {
super.disconnectedCallback();
this._stopSelectAnimation();
this._stopWaitingForLayout?.();
// The layout no longer settles, so physics would stay off and the view
// would not follow on return
this._settlingLayout = false;
this._layoutSwitching = false;
if (this._emphasisGuardHandler) {
this._baseChart?.chart?.off("mouseover", this._emphasisGuardHandler);
this._baseChart?.chart?.off("mouseout", this._emphasisGuardHandler);
@@ -1125,11 +881,7 @@ export class HaNetworkGraph extends LitElement {
}
private _getGraphSeries(chart = this._baseChart?.chart): any {
if (!chart || chart.isDisposed()) {
return undefined;
}
// @ts-ignore private method but no other way to get the graph
return chart.getModel().getSeriesByIndex(0);
return graphSeries(chart);
}
static styles = css`
+12 -25
View File
@@ -47,7 +47,13 @@ export interface ViewTransform {
y: number;
}
export const SELECTED_NODE_ANIMATION_DURATION = 800;
/**
* The transform of a view and the size of the chart it was in
*/
export interface SizedViewTransform extends ViewTransform {
width: number;
height: number;
}
export const SELECTED_NODE_MAX_ZOOM = 2;
@@ -69,28 +75,6 @@ export const TREE_MIN_SELECTED_NODE_X = 32;
export const TREE_CHILD_SPACING = 8;
export const TREE_MIN_CHILD_GAP = 24;
export const easeInOutCubic = (t: number) =>
t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2;
/**
* The part of the remaining way that a frame covers, so the view follows the
* eased curve even when the target moves.
*/
export const remainingFraction = (eased: number, previousEased: number) =>
previousEased >= 1 ? 1 : (eased - previousEased) / (1 - previousEased);
/**
* The roam that covers a fraction of the way of a roam, so that a point that
* the roam moves to its origin gets that fraction of the way there.
*/
export const partialRoam = (roam: FollowRoam, fraction: number): FollowRoam => {
const zoom = roam.zoom === undefined ? undefined : roam.zoom ** fraction;
// The zoom around the origin follows the pan and scales the distance to the
// origin, so the pan makes up for it
const pan = 1 - (1 - fraction) / (zoom ?? 1);
return { ...roam, dx: roam.dx * pan, dy: roam.dy * pan, zoom };
};
/**
* The point that a roam moves to the given point
*/
@@ -281,7 +265,7 @@ export const fitRoam = (
* The roam to the view of a layout that was switched to: the whole tree
* layout, or the force layout as it first showed, as its nodes keep their
* positions. When nodes shown since, e.g. of another legend category, do not
* fit in that, the roam fits them.
* fit in that, or the chart has another size, the roam fits them.
*
* @param bounds the bounds of the nodes in the layout
* @param current the transform of the view now
@@ -291,12 +275,15 @@ export const layoutRoam = (
view: GraphView,
bounds: ViewBounds,
current: ViewTransform,
initial?: ViewTransform
initial?: SizedViewTransform
): FollowRoam | undefined => {
const margin = SELECTED_NODE_FIT_MARGIN;
if (
view.treeLayout ||
!initial ||
// Its pixels no longer match, as ECharts scales the graph to the chart
initial.width !== view.width ||
initial.height !== view.height ||
initial.scale * bounds.left + initial.x < margin ||
initial.scale * bounds.top + initial.y < margin ||
initial.scale * bounds.right + initial.x > view.width - margin ||
@@ -0,0 +1,281 @@
import type {
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import type { EChartsType } from "echarts/core";
import type { HaChartBase } from "./ha-chart-base";
import type {
FollowRoam,
GraphView,
SizedViewTransform,
ViewTransform,
} from "./network-graph-view";
import { layoutBounds, layoutRoam, roamSource } from "./network-graph-view";
// The nodes of another layout move for at most this many ms
export const LAYOUT_ANIMATION_TIMEOUT = 1000;
export const graphSeries = (chart: EChartsType | undefined): any => {
if (!chart || chart.isDisposed()) {
return undefined;
}
// @ts-ignore private method but no other way to get the graph
return chart.getModel().getSeriesByIndex(0);
};
export const graphView = (
chart: EChartsType,
series: any,
treeLayout: boolean
): GraphView => ({
width: chart.getWidth(),
height: chart.getHeight(),
zoom: series.coordinateSystem.getRoamTransform()[0],
treeLayout,
});
// From layout to pixels
const viewTransform = (chart: EChartsType): ViewTransform => {
const [x, y] = chart.convertToPixel({ seriesId: "network" }, [0, 0]);
const [x1] = chart.convertToPixel({ seriesId: "network" }, [1, 0]);
return { scale: x1 - x, x, y };
};
export interface NetworkLayoutControllerConfig {
chart: () => HaChartBase | undefined;
treeLayout: () => boolean;
reducedMotion: () => boolean;
selectedNode: () => string | undefined;
/** The roam to the selected node, undefined when it is in view */
selectedNodeRoam: (chart: EChartsType) => FollowRoam | undefined;
/** Before the positions of the force layout make way for the tree */
saveNodePositions: () => void;
/** When the view starts to move to the selected node or another layout */
moveStarted: () => void;
/** When the view is free again */
moveEnded: () => void;
}
/**
* Moves the view of a network graph to a selected node, and along with the
* nodes on a switch between the tree and the force layout. The view moves in
* the same animation as the nodes, as ECharts animates the transform of the
* group they are in.
*/
export class NetworkLayoutController implements ReactiveController {
/**
* Without the force layout until the nodes moved back to their positions in
* it, as the first step of the force layout stops their animation
*/
public settling = false;
/**
* While the view moves. A roam in the meantime would draw the edges at the
* end of their animation at once.
*/
public moving = false;
private _host: ReactiveControllerHost;
private _config: NetworkLayoutControllerConfig;
private _treeLayout?: boolean;
private _switched = false;
// Each move replaces the one before, and waits for the nodes of a layout
// switch that it replaces
private _move = 0;
private _layoutSwitch = false;
private _stopWaiting?: () => void;
// How the force layout first showed its nodes, which the view goes back to
// after the tree layout
private _initialForceView?: SizedViewTransform;
constructor(
host: ReactiveControllerHost,
config: NetworkLayoutControllerConfig
) {
this._host = host;
this._config = config;
host.addController(this);
}
public hostUpdate(): void {
const treeLayout = this._config.treeLayout();
const previous = this._treeLayout;
this._treeLayout = treeLayout;
if (previous === undefined || previous === treeLayout) {
return;
}
this._switched = true;
if (treeLayout) {
// The force layout comes back from here
this._config.saveNodePositions();
} else if (!this._config.reducedMotion() && this._config.chart()) {
this.settling = true;
}
}
public hostUpdated(): void {
if (this._switched) {
this._switched = false;
this._moveView(true);
}
}
public hostDisconnected(): void {
this._move++;
this._stopWaiting?.();
// The layout no longer settles, so physics would stay off and the view
// would not follow on return
this._layoutSwitch = false;
this.settling = false;
this.moving = false;
}
/**
* Moves the view to the selected node, after the chart drew the change
*/
public moveToSelectedNode() {
this._moveView(false);
}
/**
* Keeps the first view of the force layout. Call when the chart is set up.
*/
public chartSetup(chart: EChartsType) {
chart.on("finished", this._captureInitialForceView);
}
private _moveView(layoutSwitch: boolean) {
const move = ++this._move;
this._stopWaiting?.();
this._layoutSwitch ||= layoutSwitch;
this.moving = true;
this._config.moveStarted();
const done = () => {
this._layoutSwitch = false;
this.moving = false;
if (this.settling) {
this.settling = false;
this._host.requestUpdate();
}
this._config.moveEnded();
};
const baseChart = this._config.chart();
if (!baseChart) {
// Nothing is drawn, so nothing moves
done();
return;
}
baseChart.updateComplete.then(() => {
if (move !== this._move) {
return;
}
const chart = baseChart.chart;
const moved = chart && this._setRoam(chart, this._layoutSwitch);
// The nodes of another layout move also when the view stays
if (moved || this._layoutSwitch) {
this._afterAnimation(chart, done);
} else {
done();
}
});
}
// A new center and zoom of the series moves the view in the same animation
// as the nodes. Returns whether the view moves.
private _setRoam(chart: EChartsType, layoutSwitch: boolean): boolean {
const series = graphSeries(chart);
const view = series?.coordinateSystem;
if (!view) {
return false;
}
const roam = this._config.selectedNode()
? this._config.selectedNodeRoam(chart)
: layoutSwitch
? this._layoutRoam(chart, series)
: undefined;
if (!roam) {
return false;
}
const viewRect = view.getViewRect();
const center = view.pointToData(
roamSource(roam, {
x: viewRect.x + viewRect.width / 2,
y: viewRect.y + viewRect.height / 2,
})
);
// The view keeps its zoom to itself, ECharts syncs it back to the option
const currentZoom: number = series.get("zoom") ?? 1;
chart.setOption({
series: [{ id: "network", center, zoom: currentZoom * (roam.zoom ?? 1) }],
});
return true;
}
private _layoutRoam(chart: EChartsType, series: any) {
const positions: (number[] | undefined)[] = [];
series.getGraph().eachNode((node: any) => {
positions.push(node.getLayout());
});
const bounds = layoutBounds(positions);
return bounds
? layoutRoam(
graphView(chart, series, this._config.treeLayout()),
bounds,
viewTransform(chart),
this._initialForceView
)
: undefined;
}
private _afterAnimation(
chart: EChartsType | undefined,
callback: () => void
) {
// Also without animation while the force layout moves the nodes, as
// ECharts then shows each step at once
if (!chart || !graphSeries(chart)?.isAnimationEnabled()) {
callback();
return;
}
const done = () => {
this._stopWaiting?.();
callback();
};
// Not every change of the layout ends in a finished event
const timeout = window.setTimeout(done, LAYOUT_ANIMATION_TIMEOUT);
chart.on("finished", done);
this._stopWaiting = () => {
clearTimeout(timeout);
chart.off("finished", done);
this._stopWaiting = undefined;
};
}
private _captureInitialForceView = () => {
const chart = this._config.chart()?.chart;
// Not while the view moves after a switch from the tree layout
if (
this._initialForceView ||
this._config.treeLayout() ||
this.settling ||
this.moving ||
!chart ||
!graphSeries(chart)?.forceLayout
) {
return;
}
this._initialForceView = {
...viewTransform(chart),
width: chart.getWidth(),
height: chart.getHeight(),
};
chart.off("finished", this._captureInitialForceView);
};
}
@@ -1,190 +0,0 @@
import type {
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import type { EChartsType } from "echarts/core";
import type { HaChartBase } from "./ha-chart-base";
import { SELECTED_NODE_ANIMATION_DURATION } from "./network-graph-view";
// Fades along with the view moving to a selected node
const STYLE_FADE_DURATION = SELECTED_NODE_ANIMATION_DURATION;
export const FADED_STYLE_PROPERTIES = [
"opacity",
"fill",
"stroke",
"lineWidth",
] as const;
export type FadedStyle = Partial<
Record<(typeof FADED_STYLE_PROPERTIES)[number], unknown>
>;
export interface StyleFade {
from: FadedStyle;
to: FadedStyle;
// The style to set when the fade is done
final?: FadedStyle;
}
type Displayable = ReturnType<
ReturnType<EChartsType["getZr"]>["storage"]["getDisplayList"]
>[number];
const isColor = (value: unknown): value is string =>
typeof value === "string" && value !== "none" && value !== "transparent";
// ECharts gives a node without a border a stroke color too, with no width
const hasBorder = (style: FadedStyle) =>
isColor(style.stroke) &&
typeof style.lineWidth === "number" &&
style.lineWidth > 0;
export const fadedStyle = (style: Record<string, unknown>): FadedStyle => ({
opacity: style.opacity ?? 1,
fill: style.fill,
stroke: style.stroke,
lineWidth: style.lineWidth ?? 0,
});
/**
* The style properties that change and can be faded, or undefined when none
* do.
*/
export const styleFade = (
previous: FadedStyle,
next: FadedStyle
): StyleFade | undefined => {
const start = { ...previous };
const end = { ...next };
// A border that appears grows out of the fill, one that disappears keeps its
// color while it thins out
let final: FadedStyle | undefined;
if (!hasBorder(start) && hasBorder(end)) {
start.stroke = start.fill;
// A border hidden by its color can have a width too
start.lineWidth = 0;
} else if (hasBorder(start) && !hasBorder(end)) {
final = { stroke: end.stroke, lineWidth: end.lineWidth };
end.stroke = start.stroke;
end.lineWidth = 0;
}
const changed = FADED_STYLE_PROPERTIES.filter(
(key) =>
// Only colors can be animated, not gradients or patterns
typeof start[key] === typeof end[key] &&
typeof end[key] !== "object" &&
start[key] !== end[key]
);
if (!changed.length) {
return undefined;
}
const from: FadedStyle = Object.fromEntries(
changed.map((key) => [key, start[key]])
);
if (final) {
from.stroke = start.stroke;
}
return {
from,
to: Object.fromEntries(changed.map((key) => [key, end[key]])),
final,
};
};
export interface NetworkStyleFadeControllerConfig {
chart: () => HaChartBase | undefined;
// The data of the chart, a new object for every change
data: () => unknown;
enabled: () => boolean;
}
/**
* Fades the colors, borders and opacity of the nodes and edges of a graph
* when its data changes. ECharts applies a new style at once, so a node or edge
* that fades in or out would flash.
*/
export class NetworkStyleFadeController implements ReactiveController {
private _config: NetworkStyleFadeControllerConfig;
private _data?: unknown;
private _previousStyles?: Map<Displayable, FadedStyle>;
constructor(
host: ReactiveControllerHost,
config: NetworkStyleFadeControllerConfig
) {
this._config = config;
host.addController(this);
}
public hostUpdate(): void {
const data = this._config.data();
if (data === this._data) {
return;
}
this._data = data;
if (this._config.enabled()) {
this._previousStyles = this._getStyles();
}
}
public hostUpdated(): void {
const previous = this._previousStyles;
if (!previous) {
return;
}
this._previousStyles = undefined;
const baseChart = this._config.chart();
baseChart?.updateComplete.then(() =>
this._animateStyleChanges(baseChart.chart, previous)
);
}
public hostDisconnected(): void {
this._previousStyles = undefined;
}
private _getStyles(): Map<Displayable, FadedStyle> | undefined {
const chart = this._config.chart()?.chart;
if (!chart || chart.isDisposed()) {
return undefined;
}
return new Map(
chart
.getZr()
.storage.getDisplayList(true)
.map((el) => [el, fadedStyle(el.style as Record<string, unknown>)])
);
}
// Elements that stay are reused, so they can be animated from their
// previous style
private _animateStyleChanges(
chart: EChartsType | undefined,
previous: Map<Displayable, FadedStyle>
) {
if (!chart || chart.isDisposed()) {
return;
}
for (const el of chart.getZr().storage.getDisplayList(true)) {
const from = previous.get(el);
const fade =
from &&
styleFade(from, fadedStyle(el.style as Record<string, unknown>));
if (!fade) {
continue;
}
el.setStyle(fade.from);
el.animateTo(
{ style: fade.to },
{
duration: STYLE_FADE_DURATION,
easing: "cubicInOut",
done: fade.final ? () => el.setStyle(fade.final!) : undefined,
}
);
}
}
}
@@ -4,13 +4,10 @@ import type {
GraphView,
} from "../../../src/components/chart/network-graph-view";
import {
easeInOutCubic,
fitRoam,
labelReach,
layoutBounds,
layoutRoam,
partialRoam,
remainingFraction,
roamSource,
selectedNodeRoam,
TREE_LABEL_ROOM,
@@ -30,77 +27,6 @@ const forceView: GraphView = {
};
const treeView: GraphView = { ...forceView, treeLayout: true };
describe("easeInOutCubic", () => {
it("starts at 0, ends at 1 and passes the middle at 0.5", () => {
expect(easeInOutCubic(0)).toBe(0);
expect(easeInOutCubic(0.5)).toBe(0.5);
expect(easeInOutCubic(1)).toBe(1);
});
it("is symmetric and rises", () => {
let previous = 0;
for (let t = 0.05; t <= 1; t += 0.05) {
expect(easeInOutCubic(t)).toBeGreaterThan(previous);
expect(easeInOutCubic(t) + easeInOutCubic(1 - t)).toBeCloseTo(1);
previous = easeInOutCubic(t);
}
});
});
describe("remainingFraction", () => {
it("covers the eased part of the way when the target stays", () => {
let covered = 0;
let previousEased = 0;
for (const progress of [0.1, 0.3, 0.6, 0.9, 1]) {
const eased = easeInOutCubic(progress);
covered += (1 - covered) * remainingFraction(eased, previousEased);
previousEased = eased;
expect(covered).toBeCloseTo(eased);
}
expect(covered).toBe(1);
});
it("covers the rest once the way is done", () => {
expect(remainingFraction(1, 1)).toBe(1);
});
});
describe("partialRoam", () => {
// A graphRoam pans first and then zooms around the origin
const applyRoam = (
point: number,
roam: { dx: number; zoom?: number; originX: number }
) => roam.originX + (point + roam.dx - roam.originX) * (roam.zoom ?? 1);
it("moves a point that fraction of the way to the origin", () => {
const roam = { dx: 300, dy: -120, zoom: 2.5, originX: 400, originY: 200 };
const point = roam.originX - roam.dx;
for (const fraction of [0, 0.25, 0.5, 0.75, 1]) {
const step = partialRoam(roam, fraction);
expect(applyRoam(point, step)).toBeCloseTo(
point + (roam.originX - point) * fraction
);
}
});
it("zooms that fraction of the way on a log scale", () => {
const roam = { dx: 0, dy: 0, zoom: 4, originX: 0, originY: 0 };
expect(partialRoam(roam, 0.5).zoom).toBeCloseTo(2);
});
it("is the whole roam at the end", () => {
const roam = { dx: 10, dy: 20, zoom: 0.5, originX: 3, originY: 4 };
expect(partialRoam(roam, 1)).toEqual(roam);
});
it("only pans without a zoom", () => {
const step = partialRoam({ dx: 100, dy: 50, originX: 0, originY: 0 }, 0.25);
expect(step.zoom).toBeUndefined();
expect(step.dx).toBeCloseTo(25);
expect(step.dy).toBeCloseTo(12.5);
});
});
describe("roamSource", () => {
it("is the point that the roam moves to the given point", () => {
const roam = { dx: 120, dy: -40, zoom: 1.5, originX: 300, originY: 200 };
@@ -354,7 +280,7 @@ describe("fitRoam", () => {
describe("layoutRoam", () => {
const bounds = { left: -50, top: -50, right: 50, bottom: 50 };
const current = { scale: 1, x: 100, y: 50 };
const initial = { scale: 2, x: 400, y: 300 };
const initial = { scale: 2, x: 400, y: 300, width: 800, height: 600 };
const currentBounds = { left: 50, top: 0, right: 150, bottom: 100 };
it("goes back to the first view of the force layout", () => {
@@ -380,6 +306,13 @@ describe("layoutRoam", () => {
);
});
it("fits the nodes when the chart has another size", () => {
const wider = { ...forceView, width: 1200 };
expect(layoutRoam(wider, bounds, current, initial)).toEqual(
fitRoam(wider, currentBounds)
);
});
it("fits the nodes without a first view", () => {
expect(layoutRoam(forceView, bounds, current)).toEqual(
fitRoam(forceView, currentBounds)
@@ -0,0 +1,173 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type { HaChartBase } from "../../../src/components/chart/ha-chart-base";
import {
LAYOUT_ANIMATION_TIMEOUT,
NetworkLayoutController,
} from "../../../src/components/chart/network-layout-controller";
// A graph series without a view, so the view has nowhere to move. Reduced
// motion and a running force layout leave its animation off.
const createChart = (animated: boolean) => {
const handlers = new Map<string, Set<() => void>>();
const series = { isAnimationEnabled: () => animated };
return {
handlers,
isDisposed: () => false,
getModel: () => ({ getSeriesByIndex: () => series }),
on: (event: string, handler: () => void) => {
if (!handlers.has(event)) {
handlers.set(event, new Set());
}
handlers.get(event)!.add(handler);
},
off: (event: string, handler: () => void) => {
handlers.get(event)?.delete(handler);
},
trigger: (event: string) => {
for (const handler of [...(handlers.get(event) ?? [])]) {
handler();
}
},
};
};
const setup = (options: { chart?: boolean; reducedMotion?: boolean } = {}) => {
const chart = createChart(!options.reducedMotion);
const baseChart = { chart, updateComplete: Promise.resolve(true) };
const state = { treeLayout: false };
const host = {
addController: vi.fn(),
removeController: vi.fn(),
requestUpdate: vi.fn(),
updateComplete: Promise.resolve(true),
} as ReactiveControllerHost;
const config = {
chart: () =>
options.chart === false
? undefined
: (baseChart as unknown as HaChartBase),
treeLayout: () => state.treeLayout,
reducedMotion: () => options.reducedMotion ?? false,
selectedNode: () => undefined,
selectedNodeRoam: () => undefined,
saveNodePositions: vi.fn(),
moveStarted: vi.fn(),
moveEnded: vi.fn(),
};
const controller = new NetworkLayoutController(host, config);
const update = (treeLayout: boolean) => {
state.treeLayout = treeLayout;
controller.hostUpdate();
controller.hostUpdated();
};
return { chart, host, config, controller, update };
};
describe("NetworkLayoutController", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("does not move the view on the first update", () => {
const { config, controller, update } = setup();
update(true);
expect(controller.moving).toBe(false);
expect(config.saveNodePositions).not.toHaveBeenCalled();
expect(config.moveStarted).not.toHaveBeenCalled();
});
it("saves the positions of the force layout on a switch to the tree", () => {
const { config, controller, update } = setup();
update(false);
update(true);
expect(config.saveNodePositions).toHaveBeenCalledOnce();
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(true);
});
it("keeps physics off until the nodes are back in the force layout", async () => {
const { chart, config, controller, host, update } = setup();
update(true);
update(false);
expect(controller.settling).toBe(true);
expect(controller.moving).toBe(true);
await vi.waitFor(() =>
expect(chart.handlers.get("finished")?.size).toBe(1)
);
chart.trigger("finished");
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(false);
expect(host.requestUpdate).toHaveBeenCalledOnce();
expect(config.moveEnded).toHaveBeenCalledOnce();
expect(chart.handlers.get("finished")?.size).toBe(0);
});
it("stops waiting for the nodes after a timeout", async () => {
const { chart, controller, update } = setup();
update(true);
update(false);
await vi.waitFor(() =>
expect(chart.handlers.get("finished")?.size).toBe(1)
);
vi.advanceTimersByTime(LAYOUT_ANIMATION_TIMEOUT);
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(false);
expect(chart.handlers.get("finished")?.size).toBe(0);
});
it("does not wait without a chart or with reduced motion", async () => {
for (const options of [{ chart: false }, { reducedMotion: true }]) {
const { config, controller, update } = setup(options);
update(true);
update(false);
// eslint-disable-next-line no-await-in-loop
await vi.waitFor(() => expect(config.moveEnded).toHaveBeenCalledOnce());
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(false);
}
});
it("ends a selection at once when the view stays", async () => {
const { chart, config, controller } = setup();
controller.moveToSelectedNode();
expect(controller.moving).toBe(true);
expect(config.moveStarted).toHaveBeenCalledOnce();
await vi.waitFor(() => expect(config.moveEnded).toHaveBeenCalledOnce());
expect(controller.moving).toBe(false);
expect(chart.handlers.get("finished")).toBeUndefined();
});
it("waits for the nodes of a layout switch that a selection replaces", async () => {
const { chart, config, controller, update } = setup();
update(true);
update(false);
controller.moveToSelectedNode();
await vi.waitFor(() =>
expect(chart.handlers.get("finished")?.size).toBe(1)
);
expect(controller.settling).toBe(true);
chart.trigger("finished");
expect(controller.settling).toBe(false);
expect(config.moveEnded).toHaveBeenCalledOnce();
});
it("clears its state when the host disconnects", async () => {
const { chart, config, controller, update } = setup();
update(true);
update(false);
await vi.waitFor(() =>
expect(chart.handlers.get("finished")?.size).toBe(1)
);
controller.hostDisconnected();
expect(controller.settling).toBe(false);
expect(controller.moving).toBe(false);
expect(chart.handlers.get("finished")?.size).toBe(0);
vi.advanceTimersByTime(LAYOUT_ANIMATION_TIMEOUT);
expect(config.moveEnded).not.toHaveBeenCalled();
});
});
@@ -1,103 +0,0 @@
import { describe, expect, it } from "vitest";
import {
fadedStyle,
styleFade,
} from "../../../src/components/chart/network-style-fade-controller";
describe("fadedStyle", () => {
it("takes the faded properties with their defaults", () => {
expect(fadedStyle({ fill: "#fff", stroke: "#000", text: "x" })).toEqual({
opacity: 1,
fill: "#fff",
stroke: "#000",
lineWidth: 0,
});
});
});
describe("styleFade", () => {
const style = {
opacity: 1,
fill: "#ff0000",
stroke: "none",
lineWidth: 0,
};
it("is undefined when nothing changes", () => {
expect(styleFade(style, { ...style })).toBeUndefined();
});
it("fades only the changed properties", () => {
expect(styleFade(style, { ...style, opacity: 0.2 })).toEqual({
from: { opacity: 1 },
to: { opacity: 0.2 },
final: undefined,
});
});
it("grows a new border out of the fill", () => {
expect(
styleFade(style, { ...style, stroke: "#0000ff", lineWidth: 3 })
).toEqual({
from: { stroke: "#ff0000", lineWidth: 0 },
to: { stroke: "#0000ff", lineWidth: 3 },
final: undefined,
});
});
it("takes a stroke without width as no border", () => {
const noBorder = { ...style, stroke: "#141414" };
expect(
styleFade(noBorder, { ...style, stroke: "#0000ff", lineWidth: 3 })
).toEqual({
from: { stroke: "#ff0000", lineWidth: 0 },
to: { stroke: "#0000ff", lineWidth: 3 },
final: undefined,
});
expect(
styleFade({ ...style, stroke: "#0000ff", lineWidth: 3 }, noBorder)
).toEqual({
from: { stroke: "#0000ff", lineWidth: 3 },
to: { lineWidth: 0 },
final: { stroke: "#141414", lineWidth: 0 },
});
});
it("keeps the color of a border that thins out", () => {
expect(
styleFade({ ...style, stroke: "#0000ff", lineWidth: 3 }, style)
).toEqual({
from: { stroke: "#0000ff", lineWidth: 3 },
to: { lineWidth: 0 },
final: { stroke: "none", lineWidth: 0 },
});
});
it("fades a border hidden by its color only", () => {
const hidden = { ...style, stroke: "transparent", lineWidth: 10 };
const shown = { ...style, stroke: "#0000ff", lineWidth: 10 };
expect(styleFade(hidden, shown)).toEqual({
from: { stroke: "#ff0000", lineWidth: 0 },
to: { stroke: "#0000ff", lineWidth: 10 },
final: undefined,
});
expect(styleFade(shown, hidden)).toEqual({
from: { stroke: "#0000ff", lineWidth: 10 },
to: { lineWidth: 0 },
final: { stroke: "transparent", lineWidth: 10 },
});
});
it("skips gradients and values of another type", () => {
const gradient = { type: "linear", colorStops: [] };
expect(
styleFade({ ...style, fill: gradient }, { ...style, fill: "#00ff00" })
).toBeUndefined();
expect(
styleFade(
{ ...style, fill: gradient },
{ ...style, fill: { ...gradient } }
)
).toBeUndefined();
});
});