use std::collections::{HashMap, HashSet};
use egui::{Color32, Pos2};
use gqlitedb::{Edge, Node, Table, Value};
use petgraph::{
Directed,
stable_graph::{EdgeIndex, NodeIndex},
};
const LABEL_COLUMN: &str = "label";
const COLOR_COLUMN: &str = "color";
#[derive(Clone, Debug)]
pub(crate) struct NodePayload
{
pub node: Node,
pub caption: String,
pub colour: Option<Color32>,
}
#[derive(Clone, Debug)]
pub(crate) struct EdgePayload
{
pub edge: Edge,
}
pub(crate) type Graph = egui_graphs::Graph<NodePayload, EdgePayload, Directed>;
pub(crate) struct ExtractedGraph
{
pub graph: Graph,
}
impl ExtractedGraph
{
pub fn is_empty(&self) -> bool
{
self.graph.g().node_count() == 0
}
fn place_on_spiral(&mut self)
{
let indices: Vec<NodeIndex> = self.graph.g().node_indices().collect();
for (k, idx) in indices.into_iter().enumerate()
{
self
.graph
.node_mut(idx)
.unwrap()
.set_location(spiral_position(k));
}
}
}
#[derive(Default, PartialEq, Debug)]
pub(crate) struct RowStyle
{
pub caption: Option<String>,
pub colour: Option<Color32>,
}
struct GraphBuilder
{
graph: Graph,
nodes: HashMap<u128, NodeIndex>,
edges: HashSet<u128>,
}
impl GraphBuilder
{
fn new() -> Self
{
Self {
graph: Graph::new(),
nodes: HashMap::new(),
edges: HashSet::new(),
}
}
fn add_node(&mut self, node: &Node) -> NodeIndex
{
let key = node.key().uuid();
if let Some(idx) = self.nodes.get(&key)
{
return *idx;
}
let payload = node_payload(node);
let caption = payload.caption.clone();
let colour = payload.colour;
let idx = self.graph.add_node_with_label_and_location(
payload,
caption,
spiral_position(self.nodes.len()),
);
if let Some(colour) = colour
{
self.graph.node_mut(idx).unwrap().set_color(colour);
}
self.nodes.insert(key, idx);
idx
}
fn add_edge(&mut self, source: &Node, edge: &Edge, destination: &Node)
{
let source = self.add_node(source);
let destination = self.add_node(destination);
if self.edges.insert(edge.key().uuid())
{
let caption = edge_caption(edge);
self.graph.add_edge_with_label(
source,
destination,
EdgePayload { edge: edge.clone() },
caption,
);
}
}
fn add_value(&mut self, value: &Value)
{
match value
{
Value::Node(node) =>
{
self.add_node(node);
}
Value::SinglePath(path) =>
{
self.add_edge(path.source(), &path.to_edge(), path.destination());
}
Value::Path(path) =>
{
let mut previous = path.source();
self.add_node(previous);
for (edge, node) in path.elements()
{
self.add_edge(previous, edge, node);
previous = node;
}
}
_ =>
{}
}
}
fn apply_row_styles(&mut self, table: &Table)
{
let mut captioned = HashSet::new();
let mut coloured = HashSet::new();
for row in table.row_iter()
{
let row = row.iter().as_slice();
let Some(owner) = row_owner(row)
else
{
continue;
};
let key = owner.key().uuid();
let idx = self.nodes[&key];
let style = row_style(table.headers(), row);
let node = self.graph.node_mut(idx).unwrap();
if let Some(caption) = style.caption
&& captioned.insert(key)
{
node.payload_mut().caption = caption.clone();
node.set_label(caption);
}
if let Some(colour) = style.colour
&& coloured.insert(key)
{
node.payload_mut().colour = Some(colour);
node.set_color(colour);
}
}
}
}
fn node_payload(node: &Node) -> NodePayload
{
NodePayload {
node: node.clone(),
caption: default_caption(node),
colour: node.labels().first().map(|label| label_colour(label)),
}
}
fn spiral_position(k: usize) -> Pos2
{
let angle = k as f32 * 2.399_963;
let radius = 30.0 * (k as f32).sqrt();
Pos2::new(radius * angle.cos(), radius * angle.sin())
}
pub(crate) fn extract_graph(table: &Table) -> ExtractedGraph
{
let mut builder = GraphBuilder::new();
for row in table.row_iter()
{
for value in row.iter()
{
builder.add_value(value);
}
}
builder.apply_row_styles(table);
ExtractedGraph {
graph: builder.graph,
}
}
pub(crate) fn default_caption(node: &Node) -> String
{
if node.labels().is_empty()
{
format!("{:032x}", node.key().uuid())[..8].to_string()
}
else
{
node.labels().join(":")
}
}
pub(crate) fn edge_caption(edge: &Edge) -> String
{
edge.labels().join(":")
}
const LABEL_PALETTE: [Color32; 10] = [
Color32::from_rgb(0x4e, 0x79, 0xa7),
Color32::from_rgb(0xf2, 0x8e, 0x2b),
Color32::from_rgb(0xe1, 0x57, 0x59),
Color32::from_rgb(0x76, 0xb7, 0xb2),
Color32::from_rgb(0x59, 0xa1, 0x4f),
Color32::from_rgb(0xed, 0xc9, 0x48),
Color32::from_rgb(0xb0, 0x7a, 0xa1),
Color32::from_rgb(0xff, 0x9d, 0xa7),
Color32::from_rgb(0x9c, 0x75, 0x5f),
Color32::from_rgb(0xba, 0xb0, 0xac),
];
pub(crate) fn label_colour(label: &str) -> Color32
{
let mut hash: u32 = 0x811c_9dc5;
for byte in label.bytes()
{
hash ^= u32::from(byte);
hash = hash.wrapping_mul(0x0100_0193);
}
LABEL_PALETTE[hash as usize % LABEL_PALETTE.len()]
}
const NAMED_COLOURS: [(&str, [u8; 3]); 14] = [
("black", [0x00, 0x00, 0x00]),
("white", [0xff, 0xff, 0xff]),
("gray", [0x80, 0x80, 0x80]),
("grey", [0x80, 0x80, 0x80]),
("red", [0xe6, 0x39, 0x46]),
("green", [0x2a, 0x9d, 0x48]),
("blue", [0x1d, 0x6f, 0xd8]),
("yellow", [0xf4, 0xc4, 0x30]),
("orange", [0xf2, 0x8e, 0x2b]),
("purple", [0x8e, 0x44, 0xad]),
("pink", [0xff, 0x9d, 0xa7]),
("brown", [0x8b, 0x5a, 0x2b]),
("cyan", [0x00, 0xb7, 0xc7]),
("magenta", [0xd0, 0x3f, 0xb5]),
];
pub(crate) fn parse_colour(value: &Value) -> Option<Color32>
{
let Value::String(text) = value
else
{
return None;
};
if let Some(hex) = text.strip_prefix('#')
{
if !(hex.len() == 6 || hex.len() == 8) || !hex.bytes().all(|b| b.is_ascii_hexdigit())
{
return None;
}
let channel = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap();
let alpha = if hex.len() == 8 { channel(6) } else { 0xff };
return Some(Color32::from_rgba_unmultiplied(
channel(0),
channel(2),
channel(4),
alpha,
));
}
NAMED_COLOURS
.iter()
.find(|(name, _)| *name == text)
.map(|(_, [r, g, b])| Color32::from_rgb(*r, *g, *b))
}
pub(crate) fn row_owner(row: &[Value]) -> Option<&Node>
{
let mut nodes = row.iter().filter_map(|value| match value
{
Value::Node(node) => Some(node),
_ => None,
});
let owner = nodes.next()?;
if nodes.next().is_some()
{
None
}
else
{
Some(owner)
}
}
fn is_scalar(value: &Value) -> bool
{
matches!(
value,
Value::Boolean(_)
| Value::Integer(_)
| Value::Float(_)
| Value::String(_)
| Value::TimeStamp(_)
| Value::Key(_)
)
}
pub(crate) fn row_style(headers: &[String], row: &[Value]) -> RowStyle
{
let mut label = None;
let mut colour = None;
let mut parts = Vec::new();
for (header, value) in headers.iter().zip(row)
{
match header.as_str()
{
LABEL_COLUMN =>
{
if is_scalar(value)
{
label = Some(value.to_string());
}
}
COLOR_COLUMN => colour = parse_colour(value),
_ =>
{
if is_scalar(value)
{
parts.push(value.to_string());
}
}
}
}
let caption = label.or_else(|| (!parts.is_empty()).then(|| parts.join(" ")));
RowStyle { caption, colour }
}
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub(crate) enum ResultView
{
#[default]
Table,
Graph,
}
pub(crate) fn view_after_result(current: ResultView, drawable: bool) -> ResultView
{
if drawable { current } else { ResultView::Table }
}
pub(crate) fn effective_view(view: ResultView, has_graph: bool) -> ResultView
{
if has_graph { view } else { ResultView::Table }
}
const GRAPH_ID: &str = "gqlitebrowser_graph";
type ForceState = egui_graphs::FruchtermanReingoldWithCenterGravityState;
type ForceLayout =
egui_graphs::LayoutForceDirected<egui_graphs::FruchtermanReingoldWithCenterGravity>;
type HierarchicalState = egui_graphs::LayoutStateHierarchical;
type HierarchicalLayout = egui_graphs::LayoutHierarchical;
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum LayoutKind
{
#[default]
ForceDirected,
HierarchicalTopDown,
HierarchicalLeftRight,
}
impl LayoutKind
{
const ALL: [LayoutKind; 3] = [
LayoutKind::ForceDirected,
LayoutKind::HierarchicalTopDown,
LayoutKind::HierarchicalLeftRight,
];
fn name(self) -> &'static str
{
match self
{
LayoutKind::ForceDirected => "Force-directed",
LayoutKind::HierarchicalTopDown => "Hierarchical, top-down",
LayoutKind::HierarchicalLeftRight => "Hierarchical, left-right",
}
}
fn orientation(self) -> egui_graphs::LayoutHierarchicalOrientation
{
match self
{
LayoutKind::HierarchicalLeftRight => egui_graphs::LayoutHierarchicalOrientation::LeftRight,
_ => egui_graphs::LayoutHierarchicalOrientation::TopDown,
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub(crate) struct ElementDetails
{
pub kind: &'static str,
pub key: String,
pub labels: Vec<String>,
pub properties: Vec<(String, String)>,
pub endpoints: Option<(String, String)>,
}
#[derive(Clone, PartialEq, Debug)]
pub(crate) enum Inspector
{
Counts
{
nodes: usize,
edges: usize,
},
Element(ElementDetails),
}
fn key_text(key: u128) -> String
{
format!("{key:032x}")
}
fn properties_text(properties: &gqlitedb::ValueMap) -> Vec<(String, String)>
{
properties
.iter()
.map(|(name, value)| (name.clone(), value.to_string()))
.collect()
}
pub(crate) fn describe_node(node: &Node) -> ElementDetails
{
ElementDetails {
kind: "Node",
key: key_text(node.key().uuid()),
labels: node.labels().clone(),
properties: properties_text(node.properties()),
endpoints: None,
}
}
pub(crate) fn describe_edge(edge: &Edge, source: &str, destination: &str) -> ElementDetails
{
ElementDetails {
kind: "Relationship",
key: key_text(edge.key().uuid()),
labels: edge.labels().clone(),
properties: properties_text(edge.properties()),
endpoints: Some((source.to_string(), destination.to_string())),
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Selection
{
Node(NodeIndex),
Edge(EdgeIndex),
}
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub(crate) struct GraphViewState
{
layout: LayoutKind,
labels_always: bool,
#[serde(skip)]
extracted: Option<ExtractedGraph>,
#[serde(skip)]
needs_reset: bool,
#[serde(skip)]
auto_fit: bool,
}
impl Default for GraphViewState
{
fn default() -> Self
{
Self {
layout: LayoutKind::default(),
labels_always: true,
extracted: None,
needs_reset: false,
auto_fit: true,
}
}
}
impl GraphViewState
{
pub fn set_results(&mut self, table: &Table)
{
let extracted = extract_graph(table);
self.extracted = if extracted.is_empty()
{
None
}
else
{
Some(extracted)
};
self.needs_reset = true;
self.auto_fit = true;
}
pub fn clear(&mut self)
{
self.extracted = None;
}
pub fn restart_layout(&mut self)
{
if let Some(extracted) = self.extracted.as_mut()
{
extracted.place_on_spiral();
}
self.needs_reset = true;
self.auto_fit = true;
}
pub fn set_layout(&mut self, layout: LayoutKind)
{
if self.layout != layout
{
self.layout = layout;
self.restart_layout();
}
}
pub fn selection(&self) -> Option<Selection>
{
let graph = &self.extracted.as_ref()?.graph;
if let Some(node) = graph.selected_nodes().first()
{
Some(Selection::Node(*node))
}
else
{
graph
.selected_edges()
.first()
.map(|edge| Selection::Edge(*edge))
}
}
pub fn inspector(&self) -> Option<Inspector>
{
let graph = &self.extracted.as_ref()?.graph;
let caption = |idx: NodeIndex| {
graph
.node(idx)
.map(|n| n.payload().caption.clone())
.unwrap_or_default()
};
let element = match self.selection()
{
Some(Selection::Node(idx)) => graph.node(idx).map(|n| describe_node(&n.payload().node)),
Some(Selection::Edge(idx)) =>
{
graph
.edge(idx)
.zip(graph.edge_endpoints(idx))
.map(|(e, (source, destination))| {
describe_edge(&e.payload().edge, &caption(source), &caption(destination))
})
}
None => None,
};
Some(match element
{
Some(details) => Inspector::Element(details),
None => Inspector::Counts {
nodes: graph.g().node_count(),
edges: graph.g().edge_count(),
},
})
}
pub fn fit(&mut self)
{
self.auto_fit = true;
}
pub fn has_graph(&self) -> bool
{
self.extracted.is_some()
}
fn user_took_over(changes: &[egui_graphs::GraphChange], camera_input: bool) -> bool
{
camera_input
|| changes.iter().any(|change| {
matches!(
change,
egui_graphs::GraphChange::NodeDragStarted { .. }
| egui_graphs::GraphChange::NodeMoved { .. }
)
})
}
fn reset_widget(&self, ui: &mut egui::Ui)
{
let id = Some(GRAPH_ID.to_string());
match self.layout
{
LayoutKind::ForceDirected => egui_graphs::reset::<ForceState>(ui, id),
LayoutKind::HierarchicalTopDown | LayoutKind::HierarchicalLeftRight =>
{
egui_graphs::reset_metadata(ui, id.clone());
egui_graphs::set_layout_state(
ui,
HierarchicalState {
orientation: self.layout.orientation(),
..Default::default()
},
id,
);
}
}
}
fn toolbar(&mut self, ui: &mut egui::Ui)
{
ui.horizontal(|ui| {
let mut layout = self.layout;
egui::ComboBox::from_label("Layout")
.selected_text(layout.name())
.show_ui(ui, |ui| {
for kind in LayoutKind::ALL
{
ui.selectable_value(&mut layout, kind, kind.name());
}
});
self.set_layout(layout);
if ui.button("Fit").clicked()
{
self.fit();
}
if ui.button("Re-layout").clicked()
{
self.restart_layout();
}
ui.checkbox(&mut self.labels_always, "Labels");
});
}
pub fn ui(&mut self, ui: &mut egui::Ui)
{
if self.extracted.is_none()
{
return;
}
self.toolbar(ui);
if let Some(inspector) = self.inspector()
{
egui::Panel::right("graph_inspector")
.resizable(true)
.default_size(240.0)
.show(ui, |ui| inspector_ui(ui, &inspector));
}
if self.needs_reset
{
self.reset_widget(ui);
self.needs_reset = false;
}
let Some(extracted) = self.extracted.as_mut()
else
{
return;
};
let navigation = egui_graphs::SettingsNavigation::new()
.with_fit_to_screen_enabled(self.auto_fit)
.with_zoom_and_pan_enabled(true);
let interaction = egui_graphs::SettingsInteraction::new()
.with_dragging_enabled(true)
.with_node_selection_enabled(true)
.with_edge_selection_enabled(true);
let style = egui_graphs::SettingsStyle::new().with_labels_always(self.labels_always);
let response = match self.layout
{
LayoutKind::ForceDirected => show_graph::<ForceState, ForceLayout>(
ui,
&mut extracted.graph,
&navigation,
&interaction,
&style,
),
LayoutKind::HierarchicalTopDown | LayoutKind::HierarchicalLeftRight =>
{
show_graph::<HierarchicalState, HierarchicalLayout>(
ui,
&mut extracted.graph,
&navigation,
&interaction,
&style,
)
}
};
let widget = &response.response;
let zoomed = widget.hovered() && ui.input(|i| i.zoom_delta() != 1.0);
let panned = (widget.dragged_by(egui::PointerButton::Primary)
|| widget.dragged_by(egui::PointerButton::Middle))
&& widget.drag_delta() != egui::Vec2::ZERO;
if Self::user_took_over(&response.changes, zoomed || panned)
{
self.auto_fit = false;
}
}
}
fn inspector_ui(ui: &mut egui::Ui, inspector: &Inspector)
{
egui::ScrollArea::vertical().show(ui, |ui| match inspector
{
Inspector::Counts { nodes, edges } =>
{
ui.heading("Graph");
ui.label(format!("Nodes: {nodes}"));
ui.label(format!("Relationships: {edges}"));
}
Inspector::Element(details) =>
{
ui.heading(details.kind);
egui::Grid::new("graph_inspector_summary")
.num_columns(2)
.show(ui, |ui| {
ui.label("Key");
ui.add(egui::Label::new(&details.key).wrap());
ui.end_row();
ui.label("Labels");
ui.add(egui::Label::new(details.labels.join(", ")).wrap());
ui.end_row();
if let Some((source, destination)) = &details.endpoints
{
ui.label("From");
ui.add(egui::Label::new(source).wrap());
ui.end_row();
ui.label("To");
ui.add(egui::Label::new(destination).wrap());
ui.end_row();
}
});
ui.separator();
ui.strong("Properties");
if details.properties.is_empty()
{
ui.label("No properties.");
}
else
{
egui::Grid::new("graph_inspector_properties")
.num_columns(2)
.striped(true)
.show(ui, |ui| {
for (name, value) in &details.properties
{
ui.label(name);
ui.add(egui::Label::new(value).wrap());
ui.end_row();
}
});
}
}
});
}
fn show_graph<S, L>(
ui: &mut egui::Ui,
graph: &mut Graph,
navigation: &egui_graphs::SettingsNavigation,
interaction: &egui_graphs::SettingsInteraction,
style: &egui_graphs::SettingsStyle,
) -> egui_graphs::GraphViewResponse
where
S: egui_graphs::LayoutState,
L: egui_graphs::Layout<S>,
{
egui_graphs::GraphView::<S, L>::new()
.with_id(Some(GRAPH_ID.to_string()))
.with_navigations(navigation)
.with_interactions(interaction)
.with_styles(style)
.show(ui, graph)
}
#[cfg(test)]
mod tests
{
use super::*;
use gqlitedb::{Path, SinglePath, ValueMap, value_map};
use graphcore::Key;
fn node(id: u128, labels: &[&str]) -> Node
{
Node::new(
None,
Key::new(id),
labels.iter().map(|l| l.to_string()).collect(),
Default::default(),
)
}
fn node_with_properties(id: u128, labels: &[&str], properties: ValueMap) -> Node
{
Node::new(
None,
Key::new(id),
labels.iter().map(|l| l.to_string()).collect(),
properties,
)
}
fn edge(id: u128, label: &str) -> Edge
{
Edge::new(
None,
Key::new(id),
vec![label.to_string()],
Default::default(),
)
}
fn single_path(source: &Node, edge: &Edge, destination: &Node) -> Value
{
SinglePath::new(source.clone(), edge.clone(), destination.clone()).into()
}
fn table(headers: &[&str], rows: Vec<Vec<Value>>) -> Table
{
Table::new(
headers.iter().map(|h| h.to_string()).collect(),
rows.into_iter().flatten().collect(),
)
.unwrap()
}
fn headers(names: &[&str]) -> Vec<String>
{
names.iter().map(|h| h.to_string()).collect()
}
fn node_index(graph: &Graph, id: u128) -> NodeIndex
{
graph
.nodes_iter()
.find(|(_, n)| n.payload().node.key().uuid() == id)
.map(|(idx, _)| idx)
.unwrap()
}
fn edge_count(graph: &Graph) -> usize
{
graph.g().edge_count()
}
fn node_count(graph: &Graph) -> usize
{
graph.g().node_count()
}
fn caption_of(graph: &Graph, id: u128) -> String
{
let idx = node_index(graph, id);
let node = graph.node(idx).unwrap();
assert_eq!(node.payload().caption, node.label());
node.label()
}
fn colour_of(graph: &Graph, id: u128) -> Option<Color32>
{
let idx = node_index(graph, id);
let node = graph.node(idx).unwrap();
assert_eq!(node.payload().colour, node.color());
node.color()
}
#[test]
fn node_returned_in_several_rows_is_added_once()
{
let alice = node(1, &["Person"]);
let t = table(&["n"], vec![vec![alice.clone().into()], vec![alice.into()]]);
let g = extract_graph(&t).graph;
assert_eq!(node_count(&g), 1);
assert_eq!(edge_count(&g), 0);
}
#[test]
fn single_path_gives_two_nodes_and_one_directed_edge()
{
let (alice, bob) = (node(1, &["Person"]), node(2, &["Person"]));
let knows = edge(10, "KNOWS");
let t = table(&["p"], vec![vec![single_path(&alice, &knows, &bob)]]);
let g = extract_graph(&t).graph;
assert_eq!(node_count(&g), 2);
assert_eq!(edge_count(&g), 1);
let (idx, e) = g.edges_iter().next().unwrap();
assert_eq!(e.payload().edge.key().uuid(), 10);
assert_eq!(
g.edge_endpoints(idx).unwrap(),
(node_index(&g, 1), node_index(&g, 2))
);
}
#[test]
fn self_loop_gives_one_node_and_one_edge()
{
let alice = node(1, &["Person"]);
let likes = edge(10, "LIKES");
let t = table(&["p"], vec![vec![single_path(&alice, &likes, &alice)]]);
let g = extract_graph(&t).graph;
assert_eq!(node_count(&g), 1);
assert_eq!(edge_count(&g), 1);
}
#[test]
fn path_with_three_hops_gives_a_chain()
{
let n: Vec<Node> = (1..=4).map(|i| node(i, &["Stop"])).collect();
let path = Path::new(
n[0].clone(),
vec![
(edge(10, "NEXT"), n[1].clone()),
(edge(11, "NEXT"), n[2].clone()),
(edge(12, "NEXT"), n[3].clone()),
],
);
let t = table(&["p"], vec![vec![path.into()]]);
let g = extract_graph(&t).graph;
assert_eq!(node_count(&g), 4);
assert_eq!(edge_count(&g), 3);
for (edge_id, from, to) in [(10, 1, 2), (11, 2, 3), (12, 3, 4)]
{
let (idx, _) = g
.edges_iter()
.find(|(_, e)| e.payload().edge.key().uuid() == edge_id)
.unwrap();
assert_eq!(
g.edge_endpoints(idx).unwrap(),
(node_index(&g, from), node_index(&g, to))
);
}
}
#[test]
fn same_relationship_in_both_directions_is_drawn_once()
{
let (alice, bob) = (node(1, &["Person"]), node(2, &["Person"]));
let knows = edge(10, "KNOWS");
let t = table(
&["p"],
vec![
vec![single_path(&alice, &knows, &bob)],
vec![single_path(&alice, &knows, &bob)],
],
);
let g = extract_graph(&t).graph;
assert_eq!(node_count(&g), 2);
assert_eq!(edge_count(&g), 1);
}
#[test]
fn nodes_only_gives_nodes_and_no_edges()
{
let t = table(
&["n"],
vec![
vec![node(1, &["Person"]).into()],
vec![node(2, &["Person"]).into()],
vec![node(3, &["Person"]).into()],
],
);
let g = extract_graph(&t).graph;
assert_eq!(node_count(&g), 3);
assert_eq!(edge_count(&g), 0);
}
#[test]
fn path_column_and_node_column_draw_standalone_nodes()
{
let (alice, bob, carol) = (
node(1, &["Person"]),
node(2, &["Person"]),
node(3, &["Person"]),
);
let knows = edge(10, "KNOWS");
let t = table(
&["n", "p"],
vec![
vec![alice.clone().into(), single_path(&alice, &knows, &bob)],
vec![carol.into(), Value::Null],
],
);
let g = extract_graph(&t).graph;
assert_eq!(node_count(&g), 3);
assert_eq!(edge_count(&g), 1);
}
#[test]
fn bare_edge_is_ignored()
{
let alice = node(1, &["Person"]);
let t = table(
&["n", "r"],
vec![vec![alice.into(), edge(10, "KNOWS").into()]],
);
let g = extract_graph(&t).graph;
assert_eq!(node_count(&g), 1);
assert_eq!(edge_count(&g), 0);
}
#[test]
fn nodes_and_paths_inside_arrays_and_maps_are_not_drawn()
{
let (alice, bob) = (node(1, &["Person"]), node(2, &["Person"]));
let knows = edge(10, "KNOWS");
let t = table(
&["a", "m"],
vec![vec![
Value::Array(vec![alice.clone().into(), bob.clone().into()]),
value_map!("path" => single_path(&alice, &knows, &bob)).into(),
]],
);
let extracted = extract_graph(&t);
assert!(extracted.is_empty());
}
#[test]
fn edges_and_scalars_only_give_an_empty_graph()
{
let t = table(
&["r", "since"],
vec![vec![edge(10, "KNOWS").into(), Value::Integer(2020)]],
);
assert!(extract_graph(&t).is_empty());
}
#[test]
fn default_caption_joins_labels()
{
assert_eq!(default_caption(&node(1, &["Person"])), "Person");
assert_eq!(
default_caption(&node(1, &["Person", "Employee"])),
"Person:Employee"
);
}
#[test]
fn default_caption_without_labels_is_start_of_key()
{
let n = node(0xabcdef01_2345_6789_abcd_ef0123456789, &[]);
assert_eq!(default_caption(&n), "abcdef01");
}
#[test]
fn edge_caption_joins_labels()
{
assert_eq!(edge_caption(&edge(10, "KNOWS")), "KNOWS");
}
#[test]
fn label_colour_is_stable_and_from_the_palette()
{
assert_eq!(label_colour("Person"), label_colour("Person"));
assert!(LABEL_PALETTE.contains(&label_colour("Person")));
assert!(LABEL_PALETTE.contains(&label_colour("")));
let colours: HashSet<Color32> = ["Person", "Station", "Stop", "City", "Company"]
.iter()
.map(|l| label_colour(l))
.collect();
assert!(colours.len() > 1);
}
#[test]
fn extracted_nodes_use_default_caption_and_label_colour()
{
let t = table(
&["n"],
vec![
vec![node(1, &["Person", "Employee"]).into()],
vec![node(2, &[]).into()],
],
);
let g = extract_graph(&t).graph;
assert_eq!(caption_of(&g, 1), "Person:Employee");
assert_eq!(colour_of(&g, 1), Some(label_colour("Person")));
assert_eq!(caption_of(&g, 2), "00000000");
assert_eq!(colour_of(&g, 2), None);
}
#[test]
fn extracted_edges_use_edge_caption()
{
let (alice, bob) = (node(1, &["Person"]), node(2, &["Person"]));
let t = table(
&["p"],
vec![vec![single_path(&alice, &edge(10, "KNOWS"), &bob)]],
);
let g = extract_graph(&t).graph;
let (_, e) = g.edges_iter().next().unwrap();
assert_eq!(e.label(), "KNOWS");
}
#[test]
fn parse_colour_accepts_hex_and_names()
{
assert_eq!(
parse_colour(&"#ff0000".into()),
Some(Color32::from_rgb(0xff, 0, 0))
);
assert_eq!(
parse_colour(&"#FF000080".into()),
Some(Color32::from_rgba_unmultiplied(0xff, 0, 0, 0x80))
);
assert_eq!(
parse_colour(&"#AbCdEf".into()),
Some(Color32::from_rgb(0xab, 0xcd, 0xef))
);
assert_eq!(
parse_colour(&"red".into()),
Some(Color32::from_rgb(0xe6, 0x39, 0x46))
);
assert_eq!(parse_colour(&"grey".into()), parse_colour(&"gray".into()));
}
#[test]
fn parse_colour_rejects_invalid_values()
{
for text in [
"#ff00",
"#ff00000",
"#gg0000",
"#ff00\u{e9}0",
"notacolour",
"Red",
"",
]
{
assert_eq!(parse_colour(&text.into()), None, "{text}");
}
assert_eq!(parse_colour(&Value::Integer(0xff0000)), None);
assert_eq!(parse_colour(&Value::Null), None);
}
#[test]
fn row_owner_is_the_single_top_level_node()
{
let alice = node(1, &["Person"]);
let bob = node(2, &["Person"]);
let knows = edge(10, "KNOWS");
let row: Vec<Value> = vec![alice.clone().into(), "Alice".into()];
assert_eq!(row_owner(&row).map(|n| n.key().uuid()), Some(1));
let row: Vec<Value> = vec!["Alice".into()];
assert!(row_owner(&row).is_none());
let row: Vec<Value> = vec![alice.clone().into(), bob.clone().into()];
assert!(row_owner(&row).is_none());
let row: Vec<Value> = vec![single_path(&alice, &knows, &bob), "Alice".into()];
assert!(row_owner(&row).is_none());
let row: Vec<Value> = vec![Value::Array(vec![alice.into()]), "Alice".into()];
assert!(row_owner(&row).is_none());
}
#[test]
fn row_style_uses_label_column_only()
{
let row: Vec<Value> = vec![node(1, &[]).into(), "Alice".into(), Value::Integer(42)];
let style = row_style(&headers(&["n", "label", "n.id"]), &row);
assert_eq!(style.caption.as_deref(), Some("Alice"));
}
#[test]
fn row_style_joins_scalar_columns()
{
let row: Vec<Value> = vec![node(1, &[]).into(), "Alice".into(), Value::Integer(42)];
let style = row_style(&headers(&["n", "n.name", "n.id"]), &row);
assert_eq!(style.caption.as_deref(), Some("Alice 42"));
}
#[test]
fn row_style_skips_null_and_array_cells()
{
let row: Vec<Value> = vec![
node(1, &[]).into(),
Value::Null,
Value::Array(vec![Value::Integer(1)]),
"Alice".into(),
];
let style = row_style(&headers(&["n", "n.age", "n.tags", "n.name"]), &row);
assert_eq!(style.caption.as_deref(), Some("Alice"));
}
#[test]
fn row_style_null_label_falls_back_to_scalar_columns()
{
let row: Vec<Value> = vec![node(1, &[]).into(), Value::Null, "Alice".into()];
let style = row_style(&headers(&["n", "label", "n.name"]), &row);
assert_eq!(style.caption.as_deref(), Some("Alice"));
}
#[test]
fn row_style_color_is_not_part_of_the_caption()
{
let row: Vec<Value> = vec![node(1, &[]).into(), "Alice".into(), "red".into()];
let style = row_style(&headers(&["n", "n.name", "color"]), &row);
assert_eq!(style.caption.as_deref(), Some("Alice"));
assert_eq!(style.colour, parse_colour(&"red".into()));
}
#[test]
fn row_style_column_names_are_case_sensitive()
{
let row: Vec<Value> = vec![
node(1, &[]).into(),
"Alice".into(),
"red".into(),
"x".into(),
];
let style = row_style(&headers(&["n", "Label", "colour", "n.id"]), &row);
assert_eq!(style.caption.as_deref(), Some("Alice red x"));
assert_eq!(style.colour, None);
}
#[test]
fn row_style_without_scalars_is_empty()
{
let row: Vec<Value> = vec![node(1, &[]).into()];
assert_eq!(row_style(&headers(&["n"]), &row), RowStyle::default());
}
#[test]
fn owner_gets_caption_and_colour_from_its_row()
{
let t = table(
&["n", "label", "color"],
vec![vec![
node(1, &["Person"]).into(),
"Alice".into(),
"#00ff00".into(),
]],
);
let g = extract_graph(&t).graph;
assert_eq!(caption_of(&g, 1), "Alice");
assert_eq!(colour_of(&g, 1), Some(Color32::from_rgb(0, 0xff, 0)));
}
#[test]
fn scalar_columns_become_the_caption()
{
let t = table(
&["n", "n.name", "n.id"],
vec![vec![
node(1, &["Person"]).into(),
"Alice".into(),
Value::Integer(42),
]],
);
assert_eq!(caption_of(&extract_graph(&t).graph, 1), "Alice 42");
}
#[test]
fn path_nodes_without_owner_keep_their_labels()
{
let (alice, bob) = (node(1, &["Person"]), node(2, &["Person"]));
let t = table(
&["p", "a.name"],
vec![vec![
single_path(&alice, &edge(10, "KNOWS"), &bob),
"Alice".into(),
]],
);
let g = extract_graph(&t).graph;
assert_eq!(caption_of(&g, 1), "Person");
assert_eq!(caption_of(&g, 2), "Person");
}
#[test]
fn invalid_color_falls_back_to_label_colour()
{
let t = table(
&["n", "color"],
vec![vec![node(1, &["Person"]).into(), "notacolour".into()]],
);
assert_eq!(
colour_of(&extract_graph(&t).graph, 1),
Some(label_colour("Person"))
);
}
#[test]
fn first_row_wins_for_caption_and_colour()
{
let alice = node(1, &["Person"]);
let t = table(
&["n", "label", "color"],
vec![
vec![alice.clone().into(), "First".into(), "red".into()],
vec![alice.into(), "Second".into(), "blue".into()],
],
);
let g = extract_graph(&t).graph;
assert_eq!(caption_of(&g, 1), "First");
assert_eq!(colour_of(&g, 1), parse_colour(&"red".into()));
}
#[test]
fn owner_styled_in_a_later_row_when_first_row_has_no_value()
{
let alice = node(1, &["Person"]);
let t = table(
&["n", "label"],
vec![
vec![alice.clone().into(), Value::Null],
vec![alice.into(), "Alice".into()],
],
);
assert_eq!(caption_of(&extract_graph(&t).graph, 1), "Alice");
}
fn people_table() -> Table
{
let a = node(1, &["Person"]);
let b = node(2, &["Person"]);
let c = node(3, &["Person"]);
table(
&["p"],
vec![
vec![single_path(&a, &edge(10, "KNOWS"), &b)],
vec![single_path(&b, &edge(11, "KNOWS"), &c)],
],
)
}
#[test]
fn spiral_positions_are_distinct()
{
let positions: Vec<Pos2> = (0..50).map(spiral_position).collect();
for i in 0..positions.len()
{
for j in (i + 1)..positions.len()
{
assert!(positions[i].distance(positions[j]) > 10.0, "{i} {j}");
}
}
}
#[test]
fn extracted_nodes_start_apart()
{
let extracted = extract_graph(&people_table());
let locations: Vec<Pos2> = extracted
.graph
.nodes_iter()
.map(|(_, n)| n.location())
.collect();
assert_eq!(locations.len(), 3);
assert!(locations[0].distance(locations[1]) > 10.0);
assert!(locations[1].distance(locations[2]) > 10.0);
assert!(locations[0].distance(locations[2]) > 10.0);
}
#[test]
fn view_after_result_keeps_graph_while_drawable()
{
assert_eq!(
view_after_result(ResultView::Graph, true),
ResultView::Graph
);
assert_eq!(
view_after_result(ResultView::Table, true),
ResultView::Table
);
}
#[test]
fn view_after_result_resets_to_table_when_not_drawable()
{
assert_eq!(
view_after_result(ResultView::Graph, false),
ResultView::Table
);
assert_eq!(
view_after_result(ResultView::Table, false),
ResultView::Table
);
}
#[test]
fn effective_view_needs_a_graph()
{
assert_eq!(effective_view(ResultView::Graph, true), ResultView::Graph);
assert_eq!(effective_view(ResultView::Graph, false), ResultView::Table);
assert_eq!(effective_view(ResultView::Table, true), ResultView::Table);
}
#[test]
fn result_view_defaults_to_table()
{
assert_eq!(ResultView::default(), ResultView::Table);
}
#[test]
fn state_starts_without_graph()
{
let state = GraphViewState::default();
assert!(!state.has_graph());
}
#[test]
fn set_results_with_paths_has_graph()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
assert!(state.has_graph());
assert!(state.needs_reset);
assert!(state.auto_fit);
}
#[test]
fn set_results_without_nodes_has_no_graph()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
state.set_results(&table(&["x"], vec![vec![Value::from(1_i64)]]));
assert!(!state.has_graph());
}
#[test]
fn set_results_with_zero_rows_has_no_graph()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
state.set_results(&Table::new(headers(&["p"]), vec![]).unwrap());
assert!(!state.has_graph());
}
#[test]
fn clear_drops_graph()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
state.clear();
assert!(!state.has_graph());
}
#[test]
fn set_results_turns_auto_fit_back_on()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
state.auto_fit = false;
state.set_results(&people_table());
assert!(state.auto_fit);
}
fn run_frame(ctx: &egui::Context, state: &mut GraphViewState)
{
let output = ctx.run_ui(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
Pos2::ZERO,
egui::vec2(800.0, 600.0),
)),
..Default::default()
},
|ui| state.ui(ui),
);
output.drop_without_applying_deltas();
}
#[test]
fn user_took_over_on_camera_input_or_node_drag()
{
use egui_graphs::GraphChange;
let node = NodeIndex::new(0);
let drag = GraphChange::NodeDragStarted { node };
let moved = GraphChange::NodeMoved {
node,
delta: egui::Vec2::ZERO,
new_position: Pos2::ZERO,
};
assert!(GraphViewState::user_took_over(&[], true));
assert!(GraphViewState::user_took_over(&[drag], false));
assert!(GraphViewState::user_took_over(&[moved], false));
assert!(!GraphViewState::user_took_over(&[], false));
}
#[test]
fn user_took_over_ignores_fit_and_selection_changes()
{
use egui_graphs::GraphChange;
let node = NodeIndex::new(0);
let panned = GraphChange::Panned {
delta: egui::Vec2::ZERO,
new_pan: egui::Vec2::ZERO,
};
let zoomed = GraphChange::Zoomed {
delta: 1.0,
new_zoom: 1.0,
};
let selected = GraphChange::NodeSelected { node };
assert!(!GraphViewState::user_took_over(
&[panned, zoomed, selected],
false
));
}
#[test]
fn ui_without_graph_draws_nothing()
{
let ctx = egui::Context::default();
let mut state = GraphViewState::default();
run_frame(&ctx, &mut state);
assert!(!state.has_graph());
}
#[test]
fn ui_consumes_reset_and_keeps_auto_fit_without_input()
{
let ctx = egui::Context::default();
let mut state = GraphViewState::default();
state.set_results(&people_table());
run_frame(&ctx, &mut state);
assert!(!state.needs_reset);
run_frame(&ctx, &mut state);
assert!(state.auto_fit);
}
#[test]
fn zoom_gesture_turns_auto_fit_off()
{
let ctx = egui::Context::default();
let mut state = GraphViewState::default();
state.set_results(&people_table());
run_frame(&ctx, &mut state);
let output = ctx.run_ui(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
Pos2::ZERO,
egui::vec2(800.0, 600.0),
)),
events: vec![
egui::Event::PointerMoved(Pos2::new(400.0, 300.0)),
egui::Event::Zoom(1.5),
],
..Default::default()
},
|ui| state.ui(ui),
);
output.drop_without_applying_deltas();
assert!(!state.auto_fit);
}
#[test]
fn layout_keeps_nodes_apart()
{
let ctx = egui::Context::default();
let mut state = GraphViewState::default();
state.set_results(&people_table());
for _ in 0..30
{
run_frame(&ctx, &mut state);
}
let locations: Vec<Pos2> = state
.extracted
.as_ref()
.unwrap()
.graph
.nodes_iter()
.map(|(_, n)| n.location())
.collect();
assert_eq!(locations.len(), 3);
for i in 0..3
{
for j in (i + 1)..3
{
assert!(locations[i].distance(locations[j]) > 10.0, "{i} {j}");
}
}
}
#[test]
fn layout_kind_defaults_to_force_directed()
{
assert_eq!(LayoutKind::default(), LayoutKind::ForceDirected);
}
#[test]
fn default_state_has_labels_on_and_force_layout()
{
let state = GraphViewState::default();
assert_eq!(state.layout, LayoutKind::ForceDirected);
assert!(state.labels_always);
}
#[test]
fn set_layout_changes_layout_and_restarts()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
state.needs_reset = false;
state.auto_fit = false;
state.set_layout(LayoutKind::HierarchicalTopDown);
assert_eq!(state.layout, LayoutKind::HierarchicalTopDown);
assert!(state.needs_reset);
assert!(state.auto_fit);
}
#[test]
fn set_same_layout_does_nothing()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
state.needs_reset = false;
state.auto_fit = false;
state.set_layout(LayoutKind::ForceDirected);
assert!(!state.needs_reset);
assert!(!state.auto_fit);
}
#[test]
fn set_results_keeps_the_chosen_layout()
{
let mut state = GraphViewState::default();
state.set_layout(LayoutKind::HierarchicalLeftRight);
state.set_results(&people_table());
assert_eq!(state.layout, LayoutKind::HierarchicalLeftRight);
}
#[test]
fn fit_turns_auto_fit_on_without_resetting_the_layout()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
state.needs_reset = false;
state.auto_fit = false;
state.fit();
assert!(state.auto_fit);
assert!(!state.needs_reset);
}
#[test]
fn restart_layout_puts_nodes_back_on_the_spiral()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
let graph = &mut state.extracted.as_mut().unwrap().graph;
let first = graph.g().node_indices().next().unwrap();
graph
.node_mut(first)
.unwrap()
.set_location(Pos2::new(900.0, 900.0));
state.needs_reset = false;
state.auto_fit = false;
state.restart_layout();
assert!(state.needs_reset);
assert!(state.auto_fit);
let locations: Vec<Pos2> = state
.extracted
.as_ref()
.unwrap()
.graph
.nodes_iter()
.map(|(_, n)| n.location())
.collect();
let expected: Vec<Pos2> = (0..3).map(spiral_position).collect();
assert_eq!(locations, expected);
}
#[test]
fn restart_layout_without_graph_still_schedules_a_reset()
{
let mut state = GraphViewState::default();
state.restart_layout();
assert!(state.needs_reset);
assert!(!state.has_graph());
}
#[test]
fn saved_state_keeps_only_layout_and_labels()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
state.set_layout(LayoutKind::HierarchicalLeftRight);
state.labels_always = false;
state.auto_fit = false;
let text = ron::to_string(&state).unwrap();
let loaded: GraphViewState = ron::from_str(&text).unwrap();
assert_eq!(loaded.layout, LayoutKind::HierarchicalLeftRight);
assert!(!loaded.labels_always);
assert!(!loaded.has_graph());
assert!(!loaded.needs_reset);
assert!(loaded.auto_fit);
}
#[test]
fn state_saved_without_graph_view_settings_loads_defaults()
{
let loaded: GraphViewState = ron::from_str("()").unwrap();
assert_eq!(loaded.layout, LayoutKind::ForceDirected);
assert!(loaded.labels_always);
assert!(loaded.auto_fit);
}
fn run_frames(state: &mut GraphViewState, count: usize)
{
let ctx = egui::Context::default();
for _ in 0..count
{
run_frame(&ctx, state);
}
}
fn chain_locations(state: &GraphViewState) -> Vec<Pos2>
{
state
.extracted
.as_ref()
.unwrap()
.graph
.nodes_iter()
.map(|(_, n)| n.location())
.collect()
}
#[test]
fn top_down_layout_puts_a_chain_on_increasing_rows()
{
let mut state = GraphViewState::default();
state.set_layout(LayoutKind::HierarchicalTopDown);
state.set_results(&people_table());
run_frames(&mut state, 3);
let l = chain_locations(&state);
assert!(l[0].y < l[1].y && l[1].y < l[2].y, "{l:?}");
}
#[test]
fn left_right_layout_puts_a_chain_on_increasing_columns()
{
let mut state = GraphViewState::default();
state.set_layout(LayoutKind::HierarchicalLeftRight);
state.set_results(&people_table());
run_frames(&mut state, 3);
let l = chain_locations(&state);
assert!(l[0].x < l[1].x && l[1].x < l[2].x, "{l:?}");
}
#[test]
fn switching_layout_while_shown_relays_out_the_graph()
{
let ctx = egui::Context::default();
let mut state = GraphViewState::default();
state.set_results(&people_table());
for _ in 0..5
{
run_frame(&ctx, &mut state);
}
state.set_layout(LayoutKind::HierarchicalTopDown);
for _ in 0..3
{
run_frame(&ctx, &mut state);
}
let l = chain_locations(&state);
assert!(l[0].y < l[1].y && l[1].y < l[2].y, "{l:?}");
state.set_layout(LayoutKind::HierarchicalLeftRight);
for _ in 0..3
{
run_frame(&ctx, &mut state);
}
let l = chain_locations(&state);
assert!(l[0].x < l[1].x && l[1].x < l[2].x, "{l:?}");
}
#[test]
fn ui_with_labels_off_does_not_panic()
{
let mut state = GraphViewState {
labels_always: false,
..Default::default()
};
state.set_results(&people_table());
run_frames(&mut state, 2);
assert!(state.has_graph());
}
#[test]
fn nothing_is_selected_without_a_graph()
{
assert_eq!(GraphViewState::default().selection(), None);
}
#[test]
fn nothing_is_selected_in_a_new_graph()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
assert_eq!(state.selection(), None);
}
#[test]
fn selection_reads_the_node_selected_in_the_graph()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
let graph = &mut state.extracted.as_mut().unwrap().graph;
let idx = node_index(graph, 2);
graph.set_selected_nodes(vec![idx]);
assert_eq!(state.selection(), Some(Selection::Node(idx)));
}
#[test]
fn selection_reads_the_edge_selected_in_the_graph()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
let graph = &mut state.extracted.as_mut().unwrap().graph;
let idx = graph.g().edge_indices().next().unwrap();
graph.set_selected_edges(vec![idx]);
assert_eq!(state.selection(), Some(Selection::Edge(idx)));
}
#[test]
fn new_results_clear_the_selection()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
let graph = &mut state.extracted.as_mut().unwrap().graph;
let idx = node_index(graph, 2);
graph.set_selected_nodes(vec![idx]);
state.set_results(&people_table());
assert_eq!(state.selection(), None);
}
fn click_at(ctx: &egui::Context, state: &mut GraphViewState, pos: Pos2)
{
let button = |pressed| egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
};
for events in [
vec![egui::Event::PointerMoved(pos)],
vec![button(true)],
vec![button(false)],
vec![],
]
{
let output = ctx.run_ui(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
Pos2::ZERO,
egui::vec2(800.0, 600.0),
)),
events,
..Default::default()
},
|ui| state.ui(ui),
);
output.drop_without_applying_deltas();
}
}
fn click_until(
ctx: &egui::Context,
state: &mut GraphViewState,
found: impl Fn(Option<Selection>) -> bool,
) -> bool
{
for y in (30..600).step_by(6)
{
for x in (0..800).step_by(6)
{
click_at(ctx, state, Pos2::new(x as f32, y as f32));
if found(state.selection())
{
return true;
}
}
}
false
}
fn settled_chain() -> (egui::Context, GraphViewState)
{
let ctx = egui::Context::default();
let mut state = GraphViewState::default();
state.set_layout(LayoutKind::HierarchicalTopDown);
state.set_results(&people_table());
for _ in 0..4
{
run_frame(&ctx, &mut state);
}
(ctx, state)
}
#[test]
fn clicking_a_node_selects_it()
{
let (ctx, mut state) = settled_chain();
let found = click_until(&ctx, &mut state, |s| matches!(s, Some(Selection::Node(_))));
assert!(found);
}
#[test]
fn changing_the_layout_keeps_the_selection()
{
let (ctx, mut state) = settled_chain();
assert!(click_until(&ctx, &mut state, |s| matches!(
s,
Some(Selection::Node(_))
)));
let selected = state.selection();
state.set_layout(LayoutKind::HierarchicalLeftRight);
for _ in 0..3
{
run_frame(&ctx, &mut state);
}
assert_eq!(state.selection(), selected);
}
#[test]
fn clicking_a_relationship_selects_it_and_deselects_the_node()
{
let (ctx, mut state) = settled_chain();
assert!(click_until(&ctx, &mut state, |s| matches!(
s,
Some(Selection::Node(_))
)));
assert!(click_until(&ctx, &mut state, |s| matches!(
s,
Some(Selection::Edge(_))
)));
let graph = &state.extracted.as_ref().unwrap().graph;
assert!(graph.selected_nodes().is_empty());
assert_eq!(graph.selected_edges().len(), 1);
}
#[test]
fn clicking_empty_space_clears_the_selection()
{
let (ctx, mut state) = settled_chain();
assert!(click_until(&ctx, &mut state, |s| s.is_some()));
click_at(&ctx, &mut state, Pos2::new(5.0, 590.0));
assert_eq!(state.selection(), None);
}
#[test]
fn describe_node_lists_key_labels_and_sorted_properties()
{
let alice = node_with_properties(
0xabc,
&["Person", "Employee"],
value_map!("name" => "Alice", "age" => 34_i64),
);
let details = describe_node(&alice);
assert_eq!(details.kind, "Node");
assert_eq!(details.key, "00000000000000000000000000000abc");
assert_eq!(details.labels, vec!["Person", "Employee"]);
assert_eq!(
details.properties,
vec![
("age".to_string(), "34".to_string()),
("name".to_string(), "Alice".to_string())
]
);
assert_eq!(details.endpoints, None);
}
#[test]
fn describe_node_without_labels_or_properties_is_empty()
{
let details = describe_node(&node(1, &[]));
assert!(details.labels.is_empty());
assert!(details.properties.is_empty());
}
#[test]
fn describe_edge_has_endpoints_and_properties()
{
let knows = Edge::new(
None,
Key::new(10),
vec!["KNOWS".to_string()],
value_map!("since" => 2020_i64),
);
let details = describe_edge(&knows, "Alice", "Bob");
assert_eq!(details.kind, "Relationship");
assert_eq!(details.key, "0000000000000000000000000000000a");
assert_eq!(details.labels, vec!["KNOWS"]);
assert_eq!(
details.properties,
vec![("since".to_string(), "2020".to_string())]
);
assert_eq!(
details.endpoints,
Some(("Alice".to_string(), "Bob".to_string()))
);
}
#[test]
fn inspector_is_none_without_a_graph()
{
assert_eq!(GraphViewState::default().inspector(), None);
}
#[test]
fn inspector_shows_counts_when_nothing_is_selected()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
assert_eq!(
state.inspector(),
Some(Inspector::Counts { nodes: 3, edges: 2 })
);
}
#[test]
fn inspector_describes_the_selected_node()
{
let mut state = GraphViewState::default();
state.set_results(&people_table());
let graph = &mut state.extracted.as_mut().unwrap().graph;
let idx = node_index(graph, 2);
graph.set_selected_nodes(vec![idx]);
let Some(Inspector::Element(details)) = state.inspector()
else
{
panic!("expected an element");
};
assert_eq!(details.kind, "Node");
assert_eq!(details.key, key_text(2));
assert_eq!(details.labels, vec!["Person"]);
}
#[test]
fn inspector_describes_the_selected_relationship_with_endpoint_captions()
{
let a = node_with_properties(1, &["Person"], value_map!("name" => "Alice"));
let b = node_with_properties(2, &["Company"], Default::default());
let t = table(
&["p", "label"],
vec![vec![
single_path(&a, &edge(10, "WORKS_AT"), &b),
Value::Null,
]],
);
let mut state = GraphViewState::default();
state.set_results(&t);
let graph = &mut state.extracted.as_mut().unwrap().graph;
let idx = graph.g().edge_indices().next().unwrap();
graph.set_selected_edges(vec![idx]);
let Some(Inspector::Element(details)) = state.inspector()
else
{
panic!("expected an element");
};
assert_eq!(details.kind, "Relationship");
assert_eq!(details.labels, vec!["WORKS_AT"]);
assert_eq!(
details.endpoints,
Some(("Person".to_string(), "Company".to_string()))
);
}
#[test]
fn ui_draws_the_inspector_for_a_selected_node()
{
let (ctx, mut state) = settled_chain();
assert!(click_until(&ctx, &mut state, |s| matches!(
s,
Some(Selection::Node(_))
)));
run_frame(&ctx, &mut state);
assert!(matches!(state.inspector(), Some(Inspector::Element(_))));
}
#[test]
fn ui_draws_the_inspector_for_a_selected_relationship()
{
let (ctx, mut state) = settled_chain();
assert!(click_until(&ctx, &mut state, |s| matches!(
s,
Some(Selection::Edge(_))
)));
run_frame(&ctx, &mut state);
assert!(matches!(state.inspector(), Some(Inspector::Element(_))));
}
}