Skip to content

graph 实验性 ​

实验性

本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。

go
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 ​

go
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:

  1. cycles are broken by reversing DFS back edges;
  2. nodes get the longest-path rank, sources pulled next to their successors;
  3. long edges are split by virtual nodes, one per crossed rank;
  4. barycentric down / up sweeps order each rank, keeping the order with the fewest crossings;
  5. 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 ​

go
type Arrow uint8

Arrow selects the arrowheads of an edge.

go
const (
	ArrowEnd   Arrow = iota // at the target (the default)
	ArrowNone               // no arrowheads
	ArrowStart              // at the source
	ArrowBoth               // at both ends
)

Column ​

go
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 ​

go
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 ​

go
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 ​

go
func (v *DiagramView) CenterOn(id string)

CenterOn pans so node id is in the middle of the canvas.

func (*DiagramView) Clicked ​

go
func (v *DiagramView) Clicked() (string, bool)

Clicked returns the node clicked (pressed and released without dragging) this frame.

func (*DiagramView) ContextMenu ​

go
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 ​

go
func (v *DiagramView) DeleteRequested() bool

DeleteRequested reports Delete / Backspace with a selection this frame; removing the selected nodes and edges is up to the application.

func (*DiagramView) DoubleClicked ​

go
func (v *DiagramView) DoubleClicked() (string, bool)

DoubleClicked returns the node double-clicked this frame.

func (*DiagramView) EdgeClicked ​

go
func (v *DiagramView) EdgeClicked() (int, bool)

EdgeClicked returns the index of the edge clicked this frame.

func (*DiagramView) FitView ​

go
func (v *DiagramView) FitView()

FitView fits the whole graph into the canvas.

func (*DiagramView) Hovered ​

go
func (v *DiagramView) Hovered() (string, bool)

Hovered returns the node under the pointer.

func (*DiagramView) HoveredEdge ​

go
func (v *DiagramView) HoveredEdge() (int, bool)

HoveredEdge returns the index of the edge under the pointer.

func (*DiagramView) Moved ​

go
func (v *DiagramView) Moved() bool

Moved reports whether nodes were dragged or moved by keys this frame.

func (*DiagramView) ScreenRect ​

go
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 ​

go
func (v *DiagramView) Select(ids ...string)

Select replaces the node selection.

func (*DiagramView) Selected ​

go
func (v *DiagramView) Selected() []string

Selected returns the selected node IDs in graph order.

func (*DiagramView) SelectedEdges ​

go
func (v *DiagramView) SelectedEdges() []int

SelectedEdges returns the indices of the selected edges.

func (*DiagramView) Zoom ​

go
func (v *DiagramView) Zoom() float32

Zoom returns the zoom factor (screen pixels per graph unit).

func (*DiagramView) ZoomTo ​

go
func (v *DiagramView) ZoomTo(k float32)

ZoomTo sets the zoom factor about the canvas centre.

DiagramW ​

go
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 ​

go
func Diagram(c *ui.Context, g *Graph) *DiagramW

Diagram 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 ​

go
func ER(c *ui.Context, tables []Table, rels []Relation) *DiagramW

ER 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 ​

go
func (w *DiagramW) A11yLabel(s string) *DiagramW

A11yLabel sets the accessible name of the canvas (default Locale.Graph.Diagram).

func (*DiagramW) AutoLayout ​

go
func (w *DiagramW) AutoLayout(o LayoutOptions) *DiagramW

AutoLayout 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 ​

go
func (w *DiagramW) Edges(k EdgeKind) *DiagramW

Edges sets how edges with Kind EdgeDefault are routed (default Bézier).

func (*DiagramW) Grid ​

go
func (w *DiagramW) Grid(size float32) *DiagramW

Grid draws a dot grid every size graph units (0: none).

func (*DiagramW) Height ​

go
func (w *DiagramW) Height(h float32) *DiagramW

Height sets the canvas height (default 480; the width follows the parent).

func (*DiagramW) Key ​

go
func (w *DiagramW) Key(k any) *DiagramW

Key gives the diagram a stable identity (viewport, selection) when widgets are added or removed around it.

func (*DiagramW) Layout ​

go
func (w *DiagramW) Layout(o ...layout.Option) *DiagramW

Layout applies layout options to the canvas box (Grow, Margin ...).

func (*DiagramW) MarqueeDrag ​

go
func (w *DiagramW) MarqueeDrag() *DiagramW

MarqueeDrag 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 ​

go
func (w *DiagramW) MiniMap() *DiagramW

MiniMap shows an overview of the whole graph in the bottom end corner; pressing or dragging in it moves the view.

func (*DiagramW) NoToolbar ​

go
func (w *DiagramW) NoToolbar() *DiagramW

NoToolbar hides the zoom / fit / layout buttons.

func (*DiagramW) ReadOnly ​

go
func (w *DiagramW) ReadOnly() *DiagramW

ReadOnly disables node dragging and keyboard moves (panning, zooming and selection still work).

func (*DiagramW) Selection ​

go
func (w *DiagramW) Selection(ids *[]string) *DiagramW

Selection binds the selected node IDs to *ids: the diagram reads it every frame and writes it on change.

func (*DiagramW) Show ​

go
func (w *DiagramW) Show() *DiagramView

Show builds the diagram and handles this frame's input.

func (*DiagramW) Sides ​

go
func (w *DiagramW) Sides(s Side) *DiagramW

Sides 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 ​

go
func (w *DiagramW) Snap() *DiagramW

Snap snaps dragged nodes to the grid (Grid sets the step; 16 if unset).

func (*DiagramW) Style ​

go
func (w *DiagramW) Style(fn func(*Style)) *DiagramW

Style tweaks the resolved style for this diagram only.

func (*DiagramW) ZoomRange ​

go
func (w *DiagramW) ZoomRange(lo, hi float32) *DiagramW

ZoomRange limits the zoom factor (default 0.1 – 4).

Direction ​

go
type Direction uint8

Direction is the flow direction of a layered layout: the side ranks follow each other towards.

go
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 ​

go
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 ​

go
type EdgeKind uint8

EdgeKind selects how an edge is routed.

go
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 ​

go
type GitColumns uint8

GitColumns selects the text columns of a GitGraph besides the graph and the subject.

go
const (
	ColAuthor GitColumns = 1 << iota
	ColDate
	ColHash
	ColAll = ColAuthor | ColDate | ColHash
)

GitGraphView ​

go
type GitGraphView struct {
	*ui.Box
	// contains filtered or unexported fields
}

GitGraphView is a shown commit graph and what happened this frame.

func (*GitGraphView) Clicked ​

go
func (v *GitGraphView) Clicked() (Commit, bool)

Clicked returns the commit clicked this frame.

func (*GitGraphView) DoubleClicked ​

go
func (v *GitGraphView) DoubleClicked() (Commit, bool)

DoubleClicked returns the commit double-clicked this frame.

func (*GitGraphView) Hovered ​

go
func (v *GitGraphView) Hovered() (Commit, bool)

Hovered returns the commit under the pointer.

func (*GitGraphView) Layout ​

go
func (v *GitGraphView) Layout() *GitLayout

Layout returns the lane layout of the shown commits.

func (*GitGraphView) ScrollTo ​

go
func (v *GitGraphView) ScrollTo(hash string)

ScrollTo scrolls commit hash into view on the next frame.

GitGraphW ​

go
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 ​

go
func GitGraph(c *ui.Context, commits []Commit) *GitGraphW

GitGraph starts a commit graph of commits (newest first, every commit above its parents, as git log prints them).

func (*GitGraphW) A11yLabel ​

go
func (w *GitGraphW) A11yLabel(s string) *GitGraphW

A11yLabel sets the accessible name (default Locale.Graph.GitGraph).

func (*GitGraphW) Columns ​

go
func (w *GitGraphW) Columns(cols GitColumns) *GitGraphW

Columns chooses the text columns (default ColAll).

func (*GitGraphW) Height ​

go
func (w *GitGraphW) Height(h float32) *GitGraphW

Height sets the list height (default 420).

func (*GitGraphW) Key ​

go
func (w *GitGraphW) Key(k any) *GitGraphW

Key gives the list a stable identity when widgets around it change.

func (*GitGraphW) LaneWidth ​

go
func (w *GitGraphW) LaneWidth(px float32, maxLanes int) *GitGraphW

LaneWidth sets the lane spacing (default 16) and how many lanes are shown before the graph column is clipped (default 12).

func (*GitGraphW) Layout ​

go
func (w *GitGraphW) Layout(o ...layout.Option) *GitGraphW

Layout applies layout options to the list box.

func (*GitGraphW) RowHeight ​

go
func (w *GitGraphW) RowHeight(h float32) *GitGraphW

RowHeight sets the row height (default 30).

func (*GitGraphW) Selected ​

go
func (w *GitGraphW) Selected(hash *string) *GitGraphW

Selected binds the selected commit hash.

func (*GitGraphW) Show ​

go
func (w *GitGraphW) Show() *GitGraphView

Show builds the list and handles this frame's input.

func (*GitGraphW) Style ​

go
func (w *GitGraphW) Style(fn func(*Style)) *GitGraphW

Style tweaks the resolved style for this list only.

GitLayout ​

go
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 ​

go
func LayoutCommits(commits []Commit) *GitLayout

LayoutCommits 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 ​

go
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 ​

go
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 ​

go
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 ​

go
func (g *Graph) Bounds() geom.Rect

Bounds returns the union of the node boxes and edge bend points.

func (*Graph) Index ​

go
func (g *Graph) Index(id string) (int, bool)

Index returns the position of node id in Nodes.

func (*Graph) Node ​

go
func (g *Graph) Node(id string) *Node

Node 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 ​

go
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 ​

go
type LinePart uint8

LinePart says which part of a row a GitLine covers.

go
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 ​

go
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 ​

go
func (n *Node) Center() geom.Point

Center returns the centre of the node box.

func (*Node) Rect ​

go
func (n *Node) Rect() geom.Rect

Rect returns the node box in graph units.

NodePainter ​

go
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 ​

go
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 ​

go
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 ​

go
type Ref struct {
	Name string
	Kind RefKind
}

Ref is a branch, tag or HEAD pointing at a commit.

RefKind ​

go
type RefKind uint8

RefKind classifies a git ref for its badge colour.

go
const (
	RefBranch RefKind = iota // local branch
	RefRemote                // remote-tracking branch (origin/main)
	RefTag
	RefHead // HEAD (or the checked-out branch)
)

Relation ​

go
type Relation struct {
	From, FromColumn string
	To, ToColumn     string
	Label            string
}

Relation is a foreign key: From.FromColumn references To.ToColumn.

Shape ​

go
type Shape uint8

Shape is the outline of a built-in node template.

go
const (
	ShapeRect    Shape = iota // rounded rectangle (the default)
	ShapePill                 // fully rounded ends
	ShapeEllipse              // ellipse inscribed in the node box
	ShapeDiamond              // rhombus (decisions)
)

Side ​

go
type Side uint8

Side is the side of a node a port (or an edge end) sits on.

go
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 ​

go
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 ​

go
func StyleOf(th *theme.Theme) *Style

StyleOf derives the graph style from th.

Table ​

go
type Table struct {
	Name    string
	Comment string // shown under the name when set
	Columns []Column
}

Table is a database table of an ER diagram.

以 MIT 许可发布