graph 实验性
实验性
本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。
import "github.com/tangoui/tango/ui/graph"本页由
site/tools/apigen从源码注释生成(按 darwin 构建标签选文件),请勿手改。
Package graph holds the graph widgets of the Tango self-drawn UI: a node-link diagram canvas (Diagram), an entity-relationship preset built on it (ER) and a git commit graph (GitGraph).
A Diagram draws an application-owned *Graph: nodes (built-in templates or a custom painter) joined by straight, orthogonal or Bézier edges with arrows, labels and port anchors. The canvas pans (drag the background, Space+drag, the wheel, two-finger touch), zooms (Ctrl/⌘+wheel, pinch, toolbar buttons), selects (click, Shift/⌘+click, Shift+drag marquee), drags nodes (optionally snapped to a grid) and shows a minimap. Only the visible part of the graph is drawn, so graphs of thousands of nodes stay smooth.
g := &graph.Graph{Nodes: nodes, Edges: edges}
v := graph.Diagram(c, g).Height(480).Grid(16).Snap().MiniMap().AutoLayout(graph.LayoutOptions{}).Show()
if id, ok := v.DoubleClicked(); ok { open(id) }
Layout computes a layered (Sugiyama-style) placement: cycle removal, longest-path layering, barycentric crossing reduction and an iterative coordinate assignment; edges spanning several layers get bend points.
graph.Layout(g, graph.LayoutOptions{Direction: graph.LeftRight})
ER draws database tables (a name header and one row per column with its type and primary / foreign key marks) and connects foreign keys from the referencing column row to the referenced one:
graph.ER(c, tables, relations).Height(560).Show()
GitGraph lays commits out in lanes (LayoutCommits: branch lines, merge curves, per-branch colours) and shows them in a virtual list with ref badges, author, date and hash columns, hover and selection. Only the rows in view are built, so histories of tens of thousands of commits scroll smoothly.
graph.GitGraph(c, commits).Selected(&hash).Height(420).Show()
Geometry: the diagram keeps its left-to-right geometry in right-to-left scopes (a diagram's coordinates are data, like a chart's), while the toolbar and minimap move to the mirrored corners; GitGraph mirrors its columns with the scope like any list.
Experimental: this package's API may change in any 0.x release (see docs/release.md, "API 稳定性").
函数
func Layout
func Layout(g *Graph, o LayoutOptions)Layout places every node of g with a layered (Sugiyama-style) layout and sets the bend points of edges that span several ranks:
- cycles are broken by reversing DFS back edges;
- nodes get the longest-path rank, sources pulled next to their successors;
- long edges are split by virtual nodes, one per crossed rank;
- barycentric down / up sweeps order each rank, keeping the order with the fewest crossings;
- positions across the ranks are refined towards the neighbours' average under the minimum-gap constraints (an exact weighted isotonic fit per rank), which straightens long edges.
The result's top-left is at the origin. Nodes with a zero Size get o.DefaultSize. Self loops and edges to missing nodes are ignored.
类型
Arrow
type Arrow uint8Arrow selects the arrowheads of an edge.
const (
ArrowEnd Arrow = iota // at the target (the default)
ArrowNone // no arrowheads
ArrowStart // at the source
ArrowBoth // at both ends
)Column
type Column struct {
Name string
Type string
PK bool // part of the primary key
FK bool // references another table (set automatically for Relation.FromColumn)
}Column is one column of a Table.
Commit
type Commit struct {
Hash string
Parents []string
Refs []Ref
Author string
Time time.Time
Subject string
}Commit is one entry of a GitGraph, newest first (git log order: every commit above its parents).
DiagramView
type DiagramView struct {
*ui.Box
// contains filtered or unexported fields
}DiagramView is a shown diagram: its box plus what happened this frame. The action methods (FitView, ZoomTo, CenterOn, Select) take effect on the next frame.
func (*DiagramView) CenterOn
func (v *DiagramView) CenterOn(id string)CenterOn pans so node id is in the middle of the canvas.
func (*DiagramView) Clicked
func (v *DiagramView) Clicked() (string, bool)Clicked returns the node clicked (pressed and released without dragging) this frame.
func (*DiagramView) ContextMenu
func (v *DiagramView) ContextMenu() (node string, pos geom.Point, ok bool)ContextMenu reports a secondary click this frame: the node under it (empty for the background) and the window position.
func (*DiagramView) DeleteRequested
func (v *DiagramView) DeleteRequested() boolDeleteRequested reports Delete / Backspace with a selection this frame; removing the selected nodes and edges is up to the application.
func (*DiagramView) DoubleClicked
func (v *DiagramView) DoubleClicked() (string, bool)DoubleClicked returns the node double-clicked this frame.
func (*DiagramView) EdgeClicked
func (v *DiagramView) EdgeClicked() (int, bool)EdgeClicked returns the index of the edge clicked this frame.
func (*DiagramView) FitView
func (v *DiagramView) FitView()FitView fits the whole graph into the canvas.
func (*DiagramView) Hovered
func (v *DiagramView) Hovered() (string, bool)Hovered returns the node under the pointer.
func (*DiagramView) HoveredEdge
func (v *DiagramView) HoveredEdge() (int, bool)HoveredEdge returns the index of the edge under the pointer.
func (*DiagramView) Moved
func (v *DiagramView) Moved() boolMoved reports whether nodes were dragged or moved by keys this frame.
func (*DiagramView) ScreenRect
func (v *DiagramView) ScreenRect(id string) (geom.Rect, bool)ScreenRect returns where node id was drawn in the last frame (window coordinates), for anchoring popovers and menus.
func (*DiagramView) Select
func (v *DiagramView) Select(ids ...string)Select replaces the node selection.
func (*DiagramView) Selected
func (v *DiagramView) Selected() []stringSelected returns the selected node IDs in graph order.
func (*DiagramView) SelectedEdges
func (v *DiagramView) SelectedEdges() []intSelectedEdges returns the indices of the selected edges.
func (*DiagramView) Zoom
func (v *DiagramView) Zoom() float32Zoom returns the zoom factor (screen pixels per graph unit).
func (*DiagramView) ZoomTo
func (v *DiagramView) ZoomTo(k float32)ZoomTo sets the zoom factor about the canvas centre.
DiagramW
type DiagramW struct {
// contains filtered or unexported fields
}DiagramW builds a node-link diagram canvas; configure it with the modifiers and finish with Show.
func Diagram
func Diagram(c *ui.Context, g *Graph) *DiagramWDiagram starts a diagram of g. The graph is owned by the caller; the diagram writes node positions (dragging, AutoLayout, keyboard moves) and the measured sizes of nodes with a zero Size back into it.
func ER
func ER(c *ui.Context, tables []Table, rels []Relation) *DiagramWER starts an entity-relationship diagram of tables. Each table is a node with a name header and one row per column (key marks, name, type); relations run from the referencing column row to the referenced one. The graph is kept between frames and laid out left to right whenever the tables or relations change; dragged positions are kept otherwise. All Diagram modifiers apply (Height, MiniMap, Edges ...); the selection holds table names.
func (*DiagramW) A11yLabel
func (w *DiagramW) A11yLabel(s string) *DiagramWA11yLabel sets the accessible name of the canvas (default Locale.Graph.Diagram).
func (*DiagramW) AutoLayout
func (w *DiagramW) AutoLayout(o LayoutOptions) *DiagramWAutoLayout lays the graph out with Layout whenever its set of nodes and edges changes (and on the first Show), then fits the view. The toolbar gets a button that lays it out again.
func (*DiagramW) Edges
func (w *DiagramW) Edges(k EdgeKind) *DiagramWEdges sets how edges with Kind EdgeDefault are routed (default Bézier).
func (*DiagramW) Grid
func (w *DiagramW) Grid(size float32) *DiagramWGrid draws a dot grid every size graph units (0: none).
func (*DiagramW) Height
func (w *DiagramW) Height(h float32) *DiagramWHeight sets the canvas height (default 480; the width follows the parent).
func (*DiagramW) Key
func (w *DiagramW) Key(k any) *DiagramWKey gives the diagram a stable identity (viewport, selection) when widgets are added or removed around it.
func (*DiagramW) Layout
func (w *DiagramW) Layout(o ...layout.Option) *DiagramWLayout applies layout options to the canvas box (Grow, Margin ...).
func (*DiagramW) MarqueeDrag
func (w *DiagramW) MarqueeDrag() *DiagramWMarqueeDrag makes a drag on the background draw a selection marquee (Space+drag or a two-finger drag pans). By default the background drag pans and Shift+drag draws the marquee.
func (*DiagramW) MiniMap
func (w *DiagramW) MiniMap() *DiagramWMiniMap shows an overview of the whole graph in the bottom end corner; pressing or dragging in it moves the view.
func (*DiagramW) NoToolbar
func (w *DiagramW) NoToolbar() *DiagramWNoToolbar hides the zoom / fit / layout buttons.
func (*DiagramW) ReadOnly
func (w *DiagramW) ReadOnly() *DiagramWReadOnly disables node dragging and keyboard moves (panning, zooming and selection still work).
func (*DiagramW) Selection
func (w *DiagramW) Selection(ids *[]string) *DiagramWSelection binds the selected node IDs to *ids: the diagram reads it every frame and writes it on change.
func (*DiagramW) Show
func (w *DiagramW) Show() *DiagramViewShow builds the diagram and handles this frame's input.
func (*DiagramW) Sides
func (w *DiagramW) Sides(s Side) *DiagramWSides sets where edge ends without a fixed port attach: SideHorizontal (left / right), SideVertical (top / bottom) or SideAuto (whichever side faces the other end). The default follows the AutoLayout direction.
func (*DiagramW) Snap
func (w *DiagramW) Snap() *DiagramWSnap snaps dragged nodes to the grid (Grid sets the step; 16 if unset).
func (*DiagramW) Style
func (w *DiagramW) Style(fn func(*Style)) *DiagramWStyle tweaks the resolved style for this diagram only.
func (*DiagramW) ZoomRange
func (w *DiagramW) ZoomRange(lo, hi float32) *DiagramWZoomRange limits the zoom factor (default 0.1 – 4).
Direction
type Direction uint8Direction is the flow direction of a layered layout: the side ranks follow each other towards.
const (
TopDown Direction = iota // ranks run top to bottom (the default)
LeftRight // ranks run left to right
BottomUp // ranks run bottom to top
RightLeft // ranks run right to left
)Edge
type Edge struct {
ID string // optional; used for edge selection (defaults to "From->To#index")
From, To string
FromPort string
ToPort string
Label string
Kind EdgeKind
Arrow Arrow
Dashed bool
Status string // accent colour like Node.Status
// Bends are intermediate points in graph units. Layout sets them for
// edges that span several ranks; dragging an end node clears them.
// Orthogonal edges jog through them along the flow.
Bends []geom.Point
Data any
}Edge joins two nodes, optionally at named ports.
EdgeKind
type EdgeKind uint8EdgeKind selects how an edge is routed.
const (
EdgeDefault EdgeKind = iota // the diagram's default (DiagramW.Edges; Bézier unless set)
EdgeBezier // cubic curve leaving and entering perpendicular to the sides
EdgeStraight // straight segments (through Bends)
EdgeOrthogonal // horizontal and vertical segments with rounded corners
)GitColumns
type GitColumns uint8GitColumns selects the text columns of a GitGraph besides the graph and the subject.
const (
ColAuthor GitColumns = 1 << iota
ColDate
ColHash
ColAll = ColAuthor | ColDate | ColHash
)GitGraphView
type GitGraphView struct {
*ui.Box
// contains filtered or unexported fields
}GitGraphView is a shown commit graph and what happened this frame.
func (*GitGraphView) Clicked
func (v *GitGraphView) Clicked() (Commit, bool)Clicked returns the commit clicked this frame.
func (*GitGraphView) DoubleClicked
func (v *GitGraphView) DoubleClicked() (Commit, bool)DoubleClicked returns the commit double-clicked this frame.
func (*GitGraphView) Hovered
func (v *GitGraphView) Hovered() (Commit, bool)Hovered returns the commit under the pointer.
func (*GitGraphView) Layout
func (v *GitGraphView) Layout() *GitLayoutLayout returns the lane layout of the shown commits.
func (*GitGraphView) ScrollTo
func (v *GitGraphView) ScrollTo(hash string)ScrollTo scrolls commit hash into view on the next frame.
GitGraphW
type GitGraphW struct {
// contains filtered or unexported fields
}GitGraphW builds a commit graph list; configure it with the modifiers and finish with Show.
func GitGraph
func GitGraph(c *ui.Context, commits []Commit) *GitGraphWGitGraph starts a commit graph of commits (newest first, every commit above its parents, as git log prints them).
func (*GitGraphW) A11yLabel
func (w *GitGraphW) A11yLabel(s string) *GitGraphWA11yLabel sets the accessible name (default Locale.Graph.GitGraph).
func (*GitGraphW) Columns
func (w *GitGraphW) Columns(cols GitColumns) *GitGraphWColumns chooses the text columns (default ColAll).
func (*GitGraphW) Height
func (w *GitGraphW) Height(h float32) *GitGraphWHeight sets the list height (default 420).
func (*GitGraphW) Key
func (w *GitGraphW) Key(k any) *GitGraphWKey gives the list a stable identity when widgets around it change.
func (*GitGraphW) LaneWidth
func (w *GitGraphW) LaneWidth(px float32, maxLanes int) *GitGraphWLaneWidth sets the lane spacing (default 16) and how many lanes are shown before the graph column is clipped (default 12).
func (*GitGraphW) Layout
func (w *GitGraphW) Layout(o ...layout.Option) *GitGraphWLayout applies layout options to the list box.
func (*GitGraphW) RowHeight
func (w *GitGraphW) RowHeight(h float32) *GitGraphWRowHeight sets the row height (default 30).
func (*GitGraphW) Selected
func (w *GitGraphW) Selected(hash *string) *GitGraphWSelected binds the selected commit hash.
func (*GitGraphW) Show
func (w *GitGraphW) Show() *GitGraphViewShow builds the list and handles this frame's input.
func (*GitGraphW) Style
func (w *GitGraphW) Style(fn func(*Style)) *GitGraphWStyle tweaks the resolved style for this list only.
GitLayout
type GitLayout struct {
Rows []GitRow
Lanes int // lanes used at most in any row
}GitLayout is the lane layout of a commit list.
func LayoutCommits
func LayoutCommits(commits []Commit) *GitLayoutLayoutCommits assigns lanes to commits (newest first) the way git log --graph does: a commit takes the lane that waits for it (the leftmost if several lines meet there; the others end in it), its first parent continues that lane, further parents join the lane already waiting for them or get a free one, and lanes are reused once free. Each new branch line gets the next colour. Parents that are not in the list end their line at the bottom of the row. It runs in O(commits × lanes).
GitLine
type GitLine struct {
From, To int
Part LinePart
Color int // index into Style.Lanes (cycled)
}GitLine is one branch line segment inside a row.
GitRow
type GitRow struct {
Lane int // lane of the commit dot
Color int
Merge bool // more than one parent
Lines []GitLine
}GitRow is the graph cell of one commit.
Graph
type Graph struct {
Nodes []Node
Edges []Edge
// contains filtered or unexported fields
}Graph is the data a Diagram draws. The application owns it; the diagram writes node positions (dragging, auto layout) and measured sizes back.
func (*Graph) Bounds
func (g *Graph) Bounds() geom.RectBounds returns the union of the node boxes and edge bend points.
func (*Graph) Index
func (g *Graph) Index(id string) (int, bool)Index returns the position of node id in Nodes.
func (*Graph) Node
func (g *Graph) Node(id string) *NodeNode returns the node with id (nil when absent). The lookup index is rebuilt on demand, so nodes may be appended, removed or reordered between calls.
LayoutOptions
type LayoutOptions struct {
Direction Direction
RankSep float32 // gap between ranks in graph units (default 64)
NodeSep float32 // gap between neighbouring nodes of a rank (default 32)
// Sweeps is the number of crossing-reduction sweeps (each one down
// and one up; default 12).
Sweeps int
// DefaultSize is used for nodes whose Size is zero (default 140×40).
DefaultSize geom.Size
}LayoutOptions configure Layout.
LinePart
type LinePart uint8LinePart says which part of a row a GitLine covers.
const (
LineThrough LinePart = iota // top to bottom in lane From (= To): a branch passing by
LineIn // from lane From at the top to the commit dot in lane To
LineOut // from the commit dot in lane From to lane To at the bottom
)Node
type Node struct {
ID string
Label string
Detail string // second line of the built-in template
Icon *icon.Icon // leading icon of the built-in template
Status string // "success" | "warning" | "error" | "info" | "processing": accent colour
Shape Shape
Pos geom.Point // top-left corner
Size geom.Size // zero: measured from the label by the built-in template (stored back on Show)
Ports []Port
// Draw replaces the built-in template. The selection outline is still
// drawn around the node.
Draw NodePainter
// Fixed nodes cannot be dragged (they can still be selected).
Fixed bool
Data any
}Node is one vertex of a Graph. Positions and sizes are in graph units (one unit is one logical pixel at zoom 1).
func (*Node) Center
func (n *Node) Center() geom.PointCenter returns the centre of the node box.
func (*Node) Rect
func (n *Node) Rect() geom.RectRect returns the node box in graph units.
NodePainter
type NodePainter func(l *paint.List, r geom.Rect, s NodeState)NodePainter draws a node in screen space: r is the node box already scaled by s.Zoom, so sizes in graph units multiply by s.Zoom.
NodeState
type NodeState struct {
Zoom float32 // screen pixels per graph unit
Selected bool
Hovered bool
Theme *theme.Theme
Style *Style
}NodeState is what a node painter needs besides its rectangle.
Port
type Port struct {
ID string
Side Side
// Offset is the distance in graph units from the start of the side
// (its left end for top / bottom, its top for left / right); zero or
// less means the middle of the side.
Offset float32
}Port is a named anchor on a node's border that edges attach to.
Ref
type Ref struct {
Name string
Kind RefKind
}Ref is a branch, tag or HEAD pointing at a commit.
RefKind
type RefKind uint8RefKind classifies a git ref for its badge colour.
const (
RefBranch RefKind = iota // local branch
RefRemote // remote-tracking branch (origin/main)
RefTag
RefHead // HEAD (or the checked-out branch)
)Relation
type Relation struct {
From, FromColumn string
To, ToColumn string
Label string
}Relation is a foreign key: From.FromColumn references To.ToColumn.
Shape
type Shape uint8Shape is the outline of a built-in node template.
const (
ShapeRect Shape = iota // rounded rectangle (the default)
ShapePill // fully rounded ends
ShapeEllipse // ellipse inscribed in the node box
ShapeDiamond // rhombus (decisions)
)Side
type Side uint8Side is the side of a node a port (or an edge end) sits on.
const (
SideAuto Side = iota // the side facing the other end of the edge
SideTop // top edge, Offset from the left
SideRight // right edge, Offset from the top
SideBottom // bottom edge, Offset from the left
SideLeft // left edge, Offset from the top
SideHorizontal // left or right, whichever faces the other end; Offset from the top
SideVertical // top or bottom, whichever faces the other end; Offset from the left
)Style
type Style struct {
Canvas theme.Color // diagram background
GridDot theme.Color // background grid dots
NodeBg theme.Color
NodeBorder theme.Color
NodeText theme.Color
NodeDetail theme.Color // second line, ER column types
NodeRadius float32
NodeShadow []paint.Shadow
Font float32 // node label size at zoom 1
FontSM float32 // detail / column / label size at zoom 1
Selection theme.Color // outline of selected nodes and edges
Hover theme.Color // border of the hovered node
Edge theme.Color
EdgeWidth float32 // screen pixels
LabelBg theme.Color
LabelText theme.Color
Marquee theme.Color // marquee fill
MarqueeBorder theme.Color
MiniBg theme.Color
MiniBorder theme.Color
MiniNode theme.Color
MiniView theme.Color // visible-area fill
MiniViewBorder theme.Color
ToolbarBg theme.Color
ToolbarShadow []paint.Shadow
// ER tables.
HeaderBg theme.Color
HeaderText theme.Color
RowHover theme.Color
KeyPK theme.Color // primary-key mark
KeyFK theme.Color // foreign-key mark
// GitGraph.
Lanes []theme.Color // branch colours, cycled
RowSel theme.Color // selected row background
RowSelText theme.Color
Hash theme.Color
Subject theme.Color
Meta theme.Color // author / date
}Style holds the colours and metrics of the graph widgets. StyleOf derives it from the theme tokens, so it follows the design system and its dark variant; tweak it per widget with the Style modifiers.
func StyleOf
func StyleOf(th *theme.Theme) *StyleStyleOf derives the graph style from th.
Table
type Table struct {
Name string
Comment string // shown under the name when set
Columns []Column
}Table is a database table of an ER diagram.