mygoflow

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

mygoflow

English | 繁體中文 | 简体中文

A node editor library for MyGo, the GPU-drawn native UI toolkit (no webview). Think React Flow: a pannable, zoomable canvas, nodes that can hold any widget, bezier edges, and drag-to-connect.

Status: experimental (v0.x). Developed and tested against MyGo v0.10.0 only; MyGo itself is 0.x, so its API may change. Verified on Windows with the headless ui.Tester and real mouse input. Real trackpad gestures, macOS and Linux have not been tested. See "Known limitations" in docs/API.md.

Install

go get github.com/sao-coding/mygoflow
import "github.com/sao-coding/mygoflow"

Requires Go 1.27.4+ and MyGo v0.10.0 (github.com/egoist/mygo). No cgo, no webview.

Quick start

You own the state (Graph, Viewport). The Editor mutates it in place and reports through callbacks and reversible Change values. The snippet below is compile-checked by example_test.go.

graph := &mygoflow.Graph{}
graph.AddNode(&mygoflow.Node{ID: "a", Title: "A", X: 40, Y: 60, Outputs: []mygoflow.Port{{ID: "out"}}})
graph.AddNode(&mygoflow.Node{ID: "b", Title: "B", X: 360, Y: 120, Inputs: []mygoflow.Port{{ID: "in"}}})
graph.AddEdge(&mygoflow.Edge{From: mygoflow.PortRef{Node: "a", Port: "out"}, To: mygoflow.PortRef{Node: "b", Port: "in"}, Arrow: mygoflow.ArrowEnd})
viewport := &mygoflow.Viewport{}

editor := mygoflow.NewEditor(graph, viewport)
editor.History = &mygoflow.History{} // optional: Ctrl+Z / Ctrl+Y
editor.Content = func(c *ui.Context, n *mygoflow.Node) {
	ui.Text(c, "any ui widget can go inside a node")
}
editor.OnConnect = func(e *mygoflow.Edge) { /* sync to your store */ }

// Call once per frame inside your window's view function:
content := ui.View(func(c *ui.Context) { editor.View(c) })

Features

  • Pan (drag, scroll), zoom (pinch, Ctrl+wheel; cursor-anchored, clamped), FitView
  • Real widgets inside nodes (Button, TextInput, ...); node size auto-fits its content or is fixed
  • Edge path types (bezier, straight, step, smooth step), drag-to-connect (including reverse), connection validation, edge reconnecting, edge selection, self-references
  • Dashed and animated edges, edge labels, arrowheads and ER cardinality markers (one / many / zero-or-one / zero-or-many), port labels
  • Ports anchored to rows of your content, with automatic left/right side selection
  • Clean default node cards (dark and light styles), a NodeStyle for per-editor and per-node styling, and custom node types (Editor.NodeTypes) where you draw the whole card
  • Multi-select (Shift/Ctrl+click, box select), group drag, Delete
  • Reversible Change stream (OnChange) and an optional History (undo/redo)
  • Snap-to-grid, minimap, background grid, viewport culling (thousands of nodes)

Full reference: docs/API.md.

Examples

Both examples live in the same Go module as the library, so go tool mygo works from inside each directory.

AI workflow editor with an inspector sidebar — examples/basic

AI workflow editor

cd examples/basic
go tool mygo dev

Prompt → Knowledge base → Language model → Safety filter → Output. Nodes stay compact and hold only the most-used controls (Select, Slider, Switch, TextInput); the full settings live in a fixed-width inspector on the right (title, category, every field, and live edits to the same state). Multi-select shows a summary, an empty selection shows the graph summary, and a selected edge shows its endpoints, type, label and arrow. The output node's preview reflects upstream settings live. Ports and edges are colored by data type (and only same-type ports can connect); node headers are colored by category. The toolbar has Undo/Redo, zoom percentage, Fit and Snap.

Database ER diagram — examples/erd

ER diagram

cd examples/erd
go tool mygo dev

Six tables, one node each and one row per column (PK/FK badges, type, nullable marker). Foreign keys are edges from the FK row to the referenced PK row, labelled 1:N, with arrows toward the referenced table. Ports are anchored to rows (Port.Y) and pick the left or right side from the tables' relative positions (Port.Side), so edges flip sides and still land on the right row when you drag a table. The diagram is read-only (Editor.ReadOnly).

Development

go build ./... && go vet ./... && go test ./...

Tests use the headless ui.Tester; no window is opened.

License

MIT.

Documentation

Overview

Package mygoflow is a node editor for MyGo native UI (github.com/egoist/mygo/ui).

It provides a pannable, zoomable canvas, nodes that can hold any widget, bezier edges, drag-to-connect, multi-select, undo/redo, snap-to-grid and a minimap.

The caller owns the Graph and Viewport. The Editor mutates them in place and reports edits through the On* callbacks and reversible Change values; transient state such as selection and in-progress drags stays inside the Editor.

See NewEditor to get started, and docs/API.md in the repository for the full reference.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	DashDashed = [2]float32{6, 4}
	DashDotted = [2]float32{1.5, 4}
)

常用的虛線樣式(螢幕 px:{線段, 間隙})。

Functions

This section is empty.

Types

type ArrowKind

type ArrowKind uint8

ArrowKind 是邊的箭頭:End = 在 To 端(輸入埠)指向節點,Start = 在 From 端(輸出埠)指向來源節點。

const (
	ArrowNone  ArrowKind = iota
	ArrowEnd             // 箭頭在 To 端
	ArrowStart           // 箭頭在 From 端
	ArrowBoth
)

type Card added in v0.2.0

type Card struct {
	// contains filtered or unexported fields
}

Card 是傳給 NodeRenderer 的輔助物件。

func (*Card) Body added in v0.2.0

func (k *Card) Body(c *ui.Context, fn func())

Body 以 BodyPadding/BodyGap 的容器包住 fn 畫出的元素;固定高度的節點會裁切超出的部分。

func (*Card) Content added in v0.2.0

func (k *Card) Content(c *ui.Context)

Content 畫 Editor.Content 的內容,外包 BodyPadding/BodyGap 的容器。

func (*Card) Drag added in v0.2.0

func (k *Card) Drag(el ui.Element) ui.Element

Drag 把 el 設為此節點的拖曳把手(按住它拖曳整個節點;多選時群組一起移動)並回傳 el。 自訂卡片至少要有一個拖曳把手(通常是標題列)。

func (*Card) Header added in v0.2.0

func (k *Card) Header(c *ui.Context)

Header 畫內建的標題列(依 NodeStyle.Header:Plain / Colored / None),並自帶拖曳把手。

func (*Card) PortRows added in v0.2.0

func (k *Card) PortRows(c *ui.Context)

PortRows 畫內建的「列式埠標籤」(節點有任一埠有 Label 時才有內容)。

func (*Card) Selected added in v0.2.0

func (k *Card) Selected() bool

Selected 回報此節點是否被選取。

type Change

type Change struct {
	Kind  ChangeKind
	Moves []Move // ChangeMove
	// ChangeAddEdge / ChangeRemoveEdge:Edge 為邊的快照,Index 為它在 Graph.Edges 的位置。
	// ChangeReconnect:Edge 為新值、Old 為舊值(同一個 ID)。
	Edge  Edge
	Old   Edge
	Node  *Node // ChangeAddNode / ChangeRemoveNode
	Index int   // 邊或節點在切片中的位置(還原時插回原處)
	Batch []Change
}

Change 是一筆「可逆」的圖變更記錄。使用者擁有狀態,所以 Editor 不替使用者決定怎麼存; 它透過 OnChange 交出 Change,使用者可據以同步外部儲存、或交給 History 做 undo/redo。 Change 是值,內含的 Edge/Node 是快照(Node 為同一指標,因為還原時要放回同一個物件)。

func (Change) Inverse

func (c Change) Inverse() Change

Inverse 回傳 c 的反向變更。

type ChangeKind

type ChangeKind uint8

ChangeKind 是 Change 的種類。

const (
	ChangeMove       ChangeKind = iota + 1 // 一或多個節點移動(拖曳結束時提交一筆)
	ChangeAddEdge                          // 新增邊(連線)
	ChangeRemoveEdge                       // 刪除邊
	ChangeAddNode                          // 新增節點(目前只由 undo 產生;使用者自行加節點請用 Editor.ApplyChange)
	ChangeRemoveNode                       // 刪除節點(其邊以 Batch 中的 ChangeRemoveEdge 另外記錄)
	ChangeReconnect                        // 邊的端點改接到別的埠
	ChangeEditEdge                         // 邊的 Label/Arrow 改變(Edge 為新值、Old 為舊值)
	ChangeBatch                            // 多個 Change,依序套用;反向則逆序
)

type Edge

type Edge struct {
	ID       ID
	From, To PortRef
	Label    string    // 非空:在路徑中點畫標籤
	Arrow    ArrowKind // 箭頭(相容用);等同 StartMarker/EndMarker = MarkerArrow
	Color    ui.Color  // 邊的顏色(零值 = 來源輸出埠的 Port.Color,再沒有就用 Style.Edge)

	StartMarker, EndMarker MarkerKind // 兩端記號(箭頭、ER 的一/多…);零值 = 沿用 Arrow
	Path                   EdgeType   // 路徑型態;零值 = Editor.EdgeType
	Radius                 float32    // EdgeSmoothStep 的圓角半徑(圖單位);0 = Editor.CornerRadius
	Dash                   [2]float32 // {線段, 間隙},螢幕 px(不隨 zoom 縮放);零值 = 實線(Animated 時預設 {6,4})
	Animated               bool       // 虛線沿著來源→目標流動
}

Edge 從 From 節點的輸出埠連到 To 節點的輸入埠。

type EdgeType added in v0.2.0

type EdgeType uint8

EdgeType 是邊的路徑型態(同 React Flow 的 edge types)。

const (
	EdgeDefault    EdgeType = iota // 沿用 Editor.EdgeType
	EdgeBezier                     // 三次貝茲曲線
	EdgeStraight                   // 直線
	EdgeStep                       // 正交折線:垂直於埠所在的邊離開/進入
	EdgeSmoothStep                 // 正交折線 + 圓角(半徑 Edge.Radius / Editor.CornerRadius)
)

type Editor

type Editor struct {
	Graph    *Graph
	Viewport *Viewport
	Style    Style

	// Content 在每個「可見」節點的內容區呼叫,可放任意 ui widget。
	Content func(c *ui.Context, n *Node)

	MinZoom, MaxZoom float32 // 預設 0.2 / 4
	ZoomSpeed        float32 // Ctrl+滾輪:factor = exp(-DY*ZoomSpeed),預設 0.01
	HeaderHeight     float32 // 節點標題列高(圖單位),預設 28
	PortRadius       float32 // 預設 6
	HitTolerance     float32 // 邊的點選容忍度(螢幕 px),預設 6;換算圖座標為 /Zoom
	PortSnap         float32 // 放開連線時吸附埠的半徑(螢幕 px),預設 16
	SnapGrid         float32 // >0:拖曳節點時對齊到此圖單位的格點(預設 0 = 關)

	// 節點尺寸:Node.W/H 為 0 的軸自動貼合內容。量測前(第一幀)用 Default*,
	// 寬度自動時最小寬度為 MinNodeWidth。
	DefaultWidth, DefaultHeight, MinNodeWidth float32 // 預設 200 / 120 / 160

	DisableCull bool // true = 不做視口裁剪(build 全部節點)
	DisableGrid bool
	GridDots    bool    // true(預設)= 以點陣畫背景;false = 格線
	EdgeWidth   float32 // 邊的線寬(圖單位),預設 2
	// ReadOnly:不可新增/改接/刪除邊或節點(仍可移動節點、選取、pan/zoom)。用於唯讀圖表(如 ER 圖)。
	ReadOnly bool
	// 節點內容區(標題列下方)的內距與子元素間距,預設 8 / 6。想讓內容貼齊節點邊緣(如表格列)就設 0。
	// 固定在內容某一列的埠(Port.Y)要用這兩個值算出位置。
	BodyPadding, BodyGap float32
	NodeRadius           float32 // 節點圓角,預設 6

	// 節點卡片:NodeStyle 是全域預設樣式(Node.Style 可逐節點覆寫);NodeTypes 讓 Node.Type 對應自訂渲染器。
	NodeStyle NodeStyle
	NodeTypes map[string]NodeRenderer

	// 邊:EdgeType 是預設路徑型態(Edge.Path 可覆寫);CornerRadius 是 EdgeSmoothStep 的圓角(圖單位,預設 8);
	// AnimationSpeed 是動畫虛線的流動速度(螢幕 px/秒,預設 40);AnimationFPS 是動畫幀率上限(預設 30);
	// SideHysteresis:SideBoth 埠換邊所需的水平位移門檻(圖單位,預設 24)。
	EdgeType       EdgeType
	CornerRadius   float32
	AnimationSpeed float32
	AnimationFPS   float32
	SideHysteresis float32
	GridCache      bool // 以 ui.NewCanvas 快取背景格線(見 docs/API.md 的量測)

	Minimap      bool       // 顯示右下角 minimap
	MinimapSize  [2]float32 // 預設 {180, 120}
	MinimapCache bool       // 以 ui.NewCanvas 快取 minimap 的節點層,預設 true

	// History 非 nil 時,Editor 自動記錄使用者操作並處理 Ctrl+Z / Ctrl+Y / Ctrl+Shift+Z。
	// 邊標籤:固定「螢幕」字級 EdgeLabelSize(不隨 zoom 縮放,任何縮放下都可讀;pill 與點擊範圍亦為螢幕大小),
	// zoom 低於 EdgeLabelMinZoom 時隱藏以免擁擠。箭頭 ArrowSize 為圖單位,隨 zoom 縮放(與節點、邊同比例)。
	EdgeLabelSize, EdgeLabelMinZoom, ArrowSize float32 // 預設 12 / 0.4 / 10
	// 埠標籤:只要節點有任一埠有 Label,就改用「列式埠」排版:標題列下方每列 PortRowHeight(預設 22),
	// 第 i 個輸入與第 i 個輸出共用一列,埠中心在列中央;標籤是節點 layout 的一部分,所以計入自動尺寸。
	PortLabelSize, PortRowHeight float32 // 預設 12 / 22
	// InitEdge 在連線建立前呼叫,可設定新邊的 Label/Arrow 預設值。
	InitEdge func(e *Edge)

	History *History

	// 連線驗證(在內建規則之後呼叫:不可自連、不可重複)。from 為輸出埠、to 為輸入埠。
	CanConnect func(from, to PortRef) bool

	// 互動回呼(皆可為 nil)。Editor 已先就地修改 Graph/Viewport,再呼叫它們。
	OnNodeMoved       func(n *Node)               // 拖曳中每個被移動的節點每次移動都會呼叫
	OnConnect         func(e *Edge)               // 已加入 Graph.Edges
	OnEdgeRemoved     func(e *Edge)               // 已自 Graph.Edges 移除
	OnEdgeReconnected func(e *Edge, old Edge)     // 邊的端點已改接;old 為改接前的值
	OnEdgeDropped     func(e *Edge) (remove bool) // 拖曳邊的端點後放在空白處;回傳 true(或不設)= 刪除該邊,false = 還原
	OnNodeRemoved     func(n *Node)               // 已自 Graph.Nodes 移除
	OnSelectionChange func(s Selection)
	OnViewportChange  func(v Viewport)
	// OnChange 是「完整的圖變更串流」:使用者操作的提交(一次拖曳 = 一筆 ChangeMove)、
	// 以及 Undo/Redo/ApplyChange 套用的變更都會呼叫。內容可逆,見 Change.Inverse。
	OnChange func(c Change)
	// contains filtered or unexported fields
}

Editor 是節點編輯器。用 NewEditor 建立後常駐於使用者的 app 狀態, 在 view 函式中每幀呼叫 View。只能在 UI 執行緒使用。

Example

ExampleEditor 是 README 最小用法的編譯檢查版本(沒有 Output 註解,只編譯不執行)。

package main

import (
	"github.com/egoist/mygo/ui"

	"github.com/sao-coding/mygoflow"
)

func main() {
	// 使用者持有狀態:Graph 與 Viewport。
	graph := &mygoflow.Graph{}
	graph.AddNode(&mygoflow.Node{ID: "a", Title: "A", X: 40, Y: 60, Outputs: []mygoflow.Port{{ID: "out"}}})
	graph.AddNode(&mygoflow.Node{ID: "b", Title: "B", X: 360, Y: 120, Inputs: []mygoflow.Port{{ID: "in"}}})
	graph.AddEdge(&mygoflow.Edge{From: mygoflow.PortRef{Node: "a", Port: "out"}, To: mygoflow.PortRef{Node: "b", Port: "in"}, Arrow: mygoflow.ArrowEnd})
	viewport := &mygoflow.Viewport{}

	editor := mygoflow.NewEditor(graph, viewport)
	editor.History = &mygoflow.History{} // 可選:Ctrl+Z / Ctrl+Y
	editor.Content = func(c *ui.Context, n *mygoflow.Node) {
		ui.Text(c, "任意 ui widget 都可以放在節點裡")
	}
	editor.OnConnect = func(e *mygoflow.Edge) { /* 同步到你的儲存層 */ }

	// 在視窗的 view 函式裡每幀呼叫:ui.View(func(c *ui.Context) { editor.View(c) })
	_ = ui.View(func(c *ui.Context) { editor.View(c) })
}

func NewEditor

func NewEditor(g *Graph, vp *Viewport) *Editor

NewEditor 建立編輯器。vp 的 Zoom 為 0 時視為 1。

func (*Editor) ApplyChange

func (e *Editor) ApplyChange(c Change)

ApplyChange 把一筆 Change 套用到 Graph,修剪失效的選取並呼叫 OnChange(不進 History)。 用於 redo/undo、或把外部來源(協作、腳本)的變更套進來。互動用的 On* 回呼不會觸發。

func (*Editor) BuiltNodes

func (e *Editor) BuiltNodes() int

BuiltNodes 回傳最近一幀實際 build 的節點數(觀察裁剪用)。

func (*Editor) CanvasSize

func (e *Editor) CanvasSize() (w, h float32)

CanvasSize 回傳上一幀畫布的大小(螢幕 px);尚未量測時為 0。視窗縮放時它會改變, 可據此重新 FitView。

func (*Editor) ClearSelection

func (e *Editor) ClearSelection()

func (*Editor) DeleteSelection

func (e *Editor) DeleteSelection() bool

DeleteSelection 刪除目前選取的邊與節點(節點連帶其邊),一次提交為一筆 Change。

func (*Editor) EdgeEndpoints added in v0.2.0

func (e *Editor) EdgeEndpoints(id ID) (x0, y0, x1, y1 float32, ok bool)

EdgeEndpoints 回傳邊兩端的位置(圖座標),已套用 SideBoth 依相對位置選定的側與埠的 Y。找不到邊/埠時 ok = false。

func (*Editor) FitView

func (e *Editor) FitView(pad float32)

FitView 讓所有節點完整落在上一幀的畫布內(留 pad 螢幕 px 邊)。畫布尚未量測時不動作。

func (*Editor) GraphToScreen

func (e *Editor) GraphToScreen(gx, gy float32) (float32, float32)

func (*Editor) NodeSize

func (e *Editor) NodeSize(n *Node) (w, h float32)

NodeSize 回傳節點的有效尺寸:固定值,或上一幀量測值(尚未量測時為 Default*)。

func (*Editor) Origin

func (e *Editor) Origin() (x, y float32)

Origin 回傳上一幀畫布左上角在視窗中的位置。ScreenToGraph/GraphToScreen 與事件座標都是「畫布局部」座標, 與 Tester 或視窗座標相差 Origin(畫布不在視窗左上角時,如上方有工具列)。

func (*Editor) Redo

func (e *Editor) Redo() bool

Redo 重做。

func (*Editor) ScreenToGraph

func (e *Editor) ScreenToGraph(sx, sy float32) (float32, float32)

ScreenToGraph / GraphToScreen 在畫布局部座標(螢幕)與圖座標間換算。

func (*Editor) SelectEdge

func (e *Editor) SelectEdge(id ID)

func (*Editor) SelectNode

func (e *Editor) SelectNode(id ID)

SelectNode / SelectEdge 以程式「取代」選取為單一項目;SelectNodes 取代為多個節點。

func (*Editor) SelectNodes

func (e *Editor) SelectNodes(ids ...ID)

func (*Editor) Selection

func (e *Editor) Selection() Selection

Selection 回傳目前選取的副本。

func (*Editor) SetEdgeAnimated added in v0.2.0

func (e *Editor) SetEdgeAnimated(id ID, on bool) bool

func (*Editor) SetEdgeArrow

func (e *Editor) SetEdgeArrow(id ID, k ArrowKind) bool

func (*Editor) SetEdgeDash added in v0.2.0

func (e *Editor) SetEdgeDash(id ID, dash [2]float32) bool

func (*Editor) SetEdgeLabel

func (e *Editor) SetEdgeLabel(id ID, label string) bool

SetEdgeLabel / SetEdgeArrow 以可逆的 ChangeEditEdge 修改邊(進 History、觸發 OnChange)。 與其他程式化修改不同,它們走 Editor 是為了讓 undo/redo 與 OnChange 涵蓋標籤編輯; 直接改 Edge 欄位當然也可以,但不會被記錄。

func (*Editor) SetEdgeMarkers added in v0.2.0

func (e *Editor) SetEdgeMarkers(id ID, start, end MarkerKind) bool

func (*Editor) SetEdgePath added in v0.2.0

func (e *Editor) SetEdgePath(id ID, t EdgeType) bool

SetEdgePath / SetEdgeMarkers / SetEdgeDash / SetEdgeAnimated 以可逆的 ChangeEditEdge 修改邊的外觀(進 History、觸發 OnChange)。

func (*Editor) ToggleEdge

func (e *Editor) ToggleEdge(id ID)

func (*Editor) ToggleNode

func (e *Editor) ToggleNode(id ID)

ToggleNode / ToggleEdge 切換單一項目是否在選取中(Shift/Ctrl 點擊的行為)。

func (*Editor) Undo

func (e *Editor) Undo() bool

Undo 復原 History 的最後一筆。沒有 History 或沒有可復原的回傳 false。

func (*Editor) View

func (e *Editor) View(c *ui.Context)

View 建立編輯器的 UI,填滿父容器。每幀在 view 函式中呼叫。

func (*Editor) ZoomBy

func (e *Editor) ZoomBy(factor float32)

ZoomBy 以畫布中心為錨點把縮放乘上 factor(夾在 MinZoom..MaxZoom),供工具列的 +/− 按鈕使用。

type Graph

type Graph struct {
	Nodes []*Node
	Edges []*Edge
}

Graph 是文件狀態。

func (*Graph) AddEdge

func (g *Graph) AddEdge(e *Edge)

AddEdge 加入邊。ID 為空時自動產生唯一 ID。

func (*Graph) AddNode

func (g *Graph) AddNode(n *Node)

AddNode 加入節點(程式化修改不觸發回呼、不進 undo 歷史)。

func (*Graph) Apply

func (g *Graph) Apply(c Change)

Apply 把變更套用到 g(純資料操作,不通知、不處理選取)。 一般請用 Editor.ApplyChange,它會一併處理選取與回呼。

func (*Graph) Edge

func (g *Graph) Edge(id ID) *Edge

Edge 依 ID 取邊,找不到回傳 nil。

func (*Graph) NextEdgeID

func (g *Graph) NextEdgeID() ID

NextEdgeID 產生未被使用的邊 ID("e1"、"e2"…)。

func (*Graph) Node

func (g *Graph) Node(id ID) *Node

Node 依 ID 取節點,找不到回傳 nil。

type HeaderMode added in v0.2.0

type HeaderMode uint8

HeaderMode 是內建卡片的標題列樣式。

const (
	HeaderInherit HeaderMode = iota // 沿用上一層(節點 → Editor.NodeStyle)
	HeaderPlain                     // 只有標題文字與底部細線(預設;Node.Color 以小圓點呈現)
	HeaderColored                   // 實心色塊標題列(顏色 = NodeStyle.HeaderColor → Node.Color → Style.Header)
	HeaderNone                      // 沒有標題列(內容從節點頂端開始)
)

type History

type History struct {
	Limit int // 最多保留幾筆,0 = 不限
	// contains filtered or unexported fields
}

History 是選用的 undo/redo 堆疊。設到 Editor.History 後,Editor 會自動記錄使用者操作產生的 Change,並處理 Ctrl+Z(macOS 為 Cmd+Z)、Ctrl+Y、Ctrl+Shift+Z。

func (*History) CanRedo

func (h *History) CanRedo() bool

func (*History) CanUndo

func (h *History) CanUndo() bool

func (*History) Clear

func (h *History) Clear()

Clear 清空歷史。

func (*History) Push

func (h *History) Push(c Change)

Push 記錄一筆新變更(清空 redo)。

type ID

type ID string

ID 是節點與邊的穩定識別,不可重複。

type MarkerKind added in v0.2.0

type MarkerKind uint8

MarkerKind 是邊端點的記號。畫在曲線端點外、對齊該處路徑切線,大小為 Editor.ArrowSize(圖單位,隨 zoom 縮放)。

const (
	MarkerNone       MarkerKind = iota
	MarkerArrow                 // 實心箭頭
	MarkerOne                   // 恰好一個:兩條短橫槓(ER:||)
	MarkerMany                  // 多個:雞爪(ER:>)
	MarkerZeroOrOne             // 零或一個:一條橫槓 + 空心圓(ER:o|)
	MarkerZeroOrMany            // 零或多個:雞爪 + 空心圓(ER:o<)
)

type Move

type Move struct {
	ID       ID
	From, To [2]float32 // {X, Y}
}

Move 是一個節點的位移記錄。

type Node

type Node struct {
	ID      ID
	Title   string
	X, Y    float32
	W, H    float32
	Inputs  []Port
	Outputs []Port
	Color   ui.Color // 標題列顏色,例如依節點類別區分(零值 = Style.Header)
	Data    any      // 使用者自訂資料,函式庫不碰
	// Type 選擇節點的繪製方式:對應 Editor.NodeTypes 中的自訂渲染器;空字串或查不到 = 內建卡片。
	Type string
	// Style 非 nil 時覆寫此節點的卡片樣式(只覆寫有設定的欄位,見 NodeStyle)。
	Style *NodeStyle
}

Node 是圖中的節點。X、Y 為圖座標(graph space),與視口無關。

W、H 為 0 表示該軸「自動貼合內容」(量測自上一幀 layout,見 Editor.DefaultWidth/DefaultHeight); 大於 0 表示固定尺寸覆寫。埠位置、命中與裁剪使用有效尺寸(固定值或量測值)。

type NodeRenderer added in v0.2.0

type NodeRenderer func(c *ui.Context, n *Node, card *Card)

NodeRenderer 是自訂的節點卡片渲染器(對應 React Flow 的 nodeTypes):用你自己的 ui 元素畫卡片「內部」。 函式庫仍負責:絕對定位與縮放、拖曳/選取/焦點/快捷鍵、卡片底色/外框/陰影/選取外框(由 NodeStyle 控制, 全透明即可完全自繪)、埠與邊。你只需用 Port.Side/Port.Y 宣告埠的錨點。

Example

ExampleNodeRenderer compiles the "Custom nodes" snippet of docs/API.md: a node type whose whole card interior is drawn with your own ui elements. The library still handles dragging (through Card.Drag), selection, ports and edges.

package main

import (
	"github.com/egoist/mygo/ui"

	"github.com/sao-coding/mygoflow"
)

func main() {
	graph := &mygoflow.Graph{}
	graph.AddNode(&mygoflow.Node{
		ID: "t", Type: "table", Title: "users", X: 40, Y: 40, W: 220,
		// Anchor ports to rows of your own layout: SideBoth picks the nearer side per edge, Y is measured from the node top.
		Outputs: []mygoflow.Port{{ID: "team_id", Side: mygoflow.SideBoth, Y: 36 + 26*1 + 13, Hidden: true}},
	})
	editor := mygoflow.NewEditor(graph, &mygoflow.Viewport{})

	// Optional: change the card the library draws around your content (or make it fully transparent).
	editor.NodeStyle = mygoflow.NodeStyle{Radius: 8, Header: mygoflow.HeaderNone}
	editor.NodeStyle.Border = ui.RGB(70, 76, 94)

	editor.NodeTypes = map[string]mygoflow.NodeRenderer{
		"table": func(c *ui.Context, n *mygoflow.Node, card *mygoflow.Card) {
			ui.Column(c).FillWidth().Children(func() {
				// The drag handle: pressing it moves the node (the whole selection when several nodes are selected).
				card.Drag(ui.Box(c).FillWidth().Height(36).PaddingX(12)).Children(func() {
					ui.Text(c, n.Title).Bold()
				})
				ui.Row(c).FillWidth().Height(26).PaddingX(12).Children(func() { ui.Text(c, "id") })
				ui.Row(c).FillWidth().Height(26).PaddingX(12).Children(func() { ui.Text(c, "team_id") })
				if card.Selected() {
					ui.Text(c, "selected")
				}
			})
		},
	}
	_ = ui.View(func(c *ui.Context) { editor.View(c) })
}

type NodeStyle added in v0.2.0

type NodeStyle struct {
	Background    ui.Color // 底色(預設 Style.NodeBackground)
	Border        ui.Color // 外框顏色(預設 Style.NodeBorder)
	BorderWidth   float32  // 外框寬度(預設 1)
	Radius        float32  // 圓角(預設 Editor.NodeRadius)
	Shadow        ui.Color // 陰影顏色(預設 Style.NodeShadow)
	NoShadow      bool     // true = 不畫陰影
	Header        HeaderMode
	HeaderColor   ui.Color // HeaderColored 的色塊色
	TitleColor    ui.Color // 標題文字色(預設 Style.HeaderText)
	Selected      ui.Color // 選取外框顏色(預設 Style.Selection)
	SelectedWidth float32  // 選取外框寬度,螢幕 px(預設 1.5;不隨 zoom 縮放)
	SelectedGlow  bool     // true = 另外畫柔光外圈(預設關;預設的選取只有一圈清楚的實線外框)
	Hover         ui.Color // 滑鼠移上時的外框顏色(預設不變)
}

NodeStyle 是內建卡片的樣式。所有欄位的零值都表示「沿用」:Node.Style 沒設的欄位沿用 Editor.NodeStyle, Editor.NodeStyle 沒設的欄位沿用 Style 與內建預設。

type Port

type Port struct {
	ID    string
	Label string
	// Color 是埠與其資料型別的顏色(零值 = Style.Port)。從此埠出發的邊預設沿用此顏色(Edge.Color 可覆寫)。
	Color ui.Color
	// Side 覆寫埠所在的邊(零值 = Inputs 左、Outputs 右)。邊的貝茲曲線會依埠的邊決定出入方向。
	Side PortSide
	// Y > 0:埠固定在「距節點頂端 Y(圖單位)」處,不再依等距/列式排版;用於把埠對齊到節點內容中的某一列
	// (例如資料表的欄位)。Y 通常 = HeaderHeight + BodyPadding + 列索引*列高 + 列高/2,與內容的 layout 一致。
	Y float32
	// Hidden:不畫圓點、不可拖曳,但邊仍連到它的位置(唯讀圖表中只顯示有連線的埠時使用)。
	Hidden bool
}

Port 是節點上的連接埠。Inputs 畫在左側、Outputs 畫在右側,沿節點高度等距排列。 Label 目前僅保留(尚未繪製)。

type PortRef

type PortRef struct {
	Node ID
	Port string
}

PortRef 指向某節點的某個埠。

type PortSide added in v0.2.0

type PortSide uint8

PortSide 是埠所在的節點邊。

const (
	SideAuto  PortSide = iota // 預設:Inputs 在左、Outputs 在右
	SideLeft                  // 左緣(邊從此埠向左伸出)
	SideRight                 // 右緣(邊從此埠向右伸出)
	SideBoth                  // 左右皆可:每條邊依「另一端節點的相對位置」自動選較近的一側(帶遲滯,拖曳時不閃爍)
)

type Selection

type Selection struct {
	Nodes []ID
	Edges []ID
}

Selection 為目前選取(可多選)。

func (Selection) Empty

func (s Selection) Empty() bool

Empty 回報是否沒有任何選取。

func (Selection) HasEdge

func (s Selection) HasEdge(id ID) bool

func (Selection) HasNode

func (s Selection) HasNode(id ID) bool

HasNode / HasEdge 回報 id 是否在選取中。

type Style

type Style struct {
	Background, Grid, Edge, EdgeSelected, NodeBackground, Header, HeaderText, Port, Selection ui.Color
	MinimapBackground, MinimapNode, MinimapView                                               ui.Color
	// NodeBorder:節點 1px 外框;NodeShadow:節點陰影(透明 = 無);MinimapBorder:minimap 外框。
	NodeBorder, NodeShadow, MinimapBorder     ui.Color
	EdgeLabel, EdgeLabelBackground, PortLabel ui.Color
}

Style 為外觀設定,NewEditor 填入深色預設。

func DarkStyle added in v0.2.0

func DarkStyle() Style

DarkStyle 是預設的深色配色:中性灰的卡片、1px 淡外框、柔和陰影、點陣背景。

func LightStyle added in v0.2.0

func LightStyle() Style

LightStyle 是淺色配色(接近 React Flow 預設:白色卡片、淡灰底、細灰外框)。 節點內容的 widget 顏色由你的 ui.Theme 決定,用淺色版時請配 ui.LightTheme()。

type Viewport

type Viewport struct {
	PanX, PanY, Zoom float32
}

Viewport:螢幕座標 = 圖座標 * Zoom + Pan。

Directories

Path Synopsis
examples
basic command
示範:只使用 mygoflow 的公開 API,做一個「AI 工作流程」編輯器,右側有檢視/編輯設定的 inspector 側欄。
示範:只使用 mygoflow 的公開 API,做一個「AI 工作流程」編輯器,右側有檢視/編輯設定的 inspector 側欄。
erd command
Example: a database ER diagram built with mygoflow.
Example: a database ER diagram built with mygoflow.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL