Repository navigation
Expand file tree
/
Copy pathoption.go
More file actions
286 lines (247 loc) · 8.69 KB
/
Copy pathoption.go
File metadata and controls
286 lines (247 loc) · 8.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package treeview
import (
"context"
"slices"
"strings"
)
// SearchFn returns true if the node matches the search term.
type SearchFn[T any] func(ctx context.Context, node *Node[T], term string) bool
// FilterFn returns true if the item should be included in the tree.
type FilterFn[T any] func(item T) bool
// ExpandFn returns true if the node should be expanded during the build process.
type ExpandFn[T any] func(node *Node[T]) bool
// ProgressCallback is invoked during tree construction every time a node is created.
type ProgressCallback[T any] func(processed int, node *Node[T])
// FocusPolicyFn selects the next node to focus when the user moves up/down the
// list. The offset is usually ±1 but can be any integer.
type FocusPolicyFn[T any] func(ctx context.Context, visible []*Node[T], current *Node[T], offset int) (*Node[T], error)
// Option is the unified option type used by all tree constructors.
//
// It allows callers to provide build-time and run-time configuration in a
// single, flat list while preventing external packages from constructing their
// own option implementations. Options are sealed to the treeview package; use
// the exported With... helpers to construct them.
type Option[T any] struct {
apply func(*masterConfig[T])
}
// WithProvider specifies the NodeProvider to use for rendering nodes.
// The provider controls how nodes are formatted, styled, and displayed.
func WithProvider[T any](p NodeProvider[T]) Option[T] {
return Option[T]{apply: func(cfg *masterConfig[T]) {
cfg.provider = p
}}
}
// WithSearcher overwrites the algorithm used when the search feature is invoked.
func WithSearcher[T any](fn SearchFn[T]) Option[T] {
return Option[T]{apply: func(cfg *masterConfig[T]) {
cfg.searcher = fn
}}
}
// WithFocusPolicy replaces the logic that decides which node should be focused
// after search or navigation.
func WithFocusPolicy[T any](fn FocusPolicyFn[T]) Option[T] {
return Option[T]{apply: func(cfg *masterConfig[T]) {
cfg.focusPol = fn
}}
}
// WithExpandFunc installs a predicate that decides for each node whether it
// should start expanded.
func WithExpandFunc[T any](fn ExpandFn[T]) Option[T] {
return Option[T]{apply: func(cfg *masterConfig[T]) {
cfg.expandFunc = fn
}}
}
// WithExpandAll expands all nodes by default.
func WithExpandAll[T any]() Option[T] {
return Option[T]{apply: func(cfg *masterConfig[T]) {
cfg.expandFunc = func(*Node[T]) bool { return true }
}}
}
// WithFilterFunc installs a predicate that decides for each node whether it
// should be included in the tree.
func WithFilterFunc[T any](filter FilterFn[T]) Option[T] {
return Option[T]{apply: func(cfg *masterConfig[T]) {
cfg.filterFunc = filter
}}
}
// WithMaxDepth limits how deep the constructors descend.
// A depth of 0 keeps only root nodes, 1 includes roots plus their children, and
// a negative depth means no limit (default).
func WithMaxDepth[T any](d int) Option[T] {
return Option[T]{apply: func(c *masterConfig[T]) {
c.maxDepth = d
}}
}
// WithTraversalCap sets an upper bound on the total number of nodes created
// during tree construction. A value ≤ 0 is interpreted as no limit.
func WithTraversalCap[T any](cap int) Option[T] {
return Option[T]{apply: func(c *masterConfig[T]) {
c.traversalCap = cap
}}
}
// WithProgressCallback registers a callback that is invoked each time a new
// node is created during any of the constructor build phases. It is not
// invoked by NewTree (which accepts pre-built nodes) except once per root
// node supplied so callers have a consistent hook.
func WithProgressCallback[T any](cb ProgressCallback[T]) Option[T] {
return Option[T]{apply: func(c *masterConfig[T]) {
c.progressCb = cb
}}
}
// WithTruncate sets the maximum width for rendered lines. Lines longer than
// this width will be truncated with an ellipsis. A width of 0 disables
// truncation (default).
func WithTruncate[T any](width int) Option[T] {
return Option[T]{apply: func(c *masterConfig[T]) {
c.truncateWidth = width
}}
}
// masterConfig aggregates options from different domains (build, filesystem,
// tree) for use by the internal constructors.
type masterConfig[T any] struct {
// Options used during the build process.
maxDepth int
traversalCap int
expandFunc ExpandFn[T] // If the function returns true, the node is expanded immediately during the build process.
filterFunc FilterFn[T] // If the function returns true, the node is included in the tree.
progressCb ProgressCallback[T] // Optional progress reporting during construction.
// Options passed to the final tree.
searcher SearchFn[T]
focusPol FocusPolicyFn[T]
provider NodeProvider[T]
truncateWidth int // Maximum width for rendered lines (0 = no truncation)
}
// newMasterConfig creates a config, applies defaults, and then user-provided
// options.
func newMasterConfig[T any](opts []Option[T], defaults ...Option[T]) *masterConfig[T] {
cfg := &masterConfig[T]{
searcher: defaultSearchFn[T],
focusPol: defaultFocusPolicy[T],
provider: NewDefaultNodeProvider[T](),
expandFunc: nil,
filterFunc: nil,
maxDepth: -1,
traversalCap: 10000,
progressCb: nil,
}
// Apply provided defaults first
for _, opt := range defaults {
if opt.apply != nil {
opt.apply(cfg)
}
}
// Apply user-provided options.
for _, opt := range opts {
if opt.apply != nil {
opt.apply(cfg)
}
}
return cfg
}
// shouldFilter evaluates whether the given item should be excluded based on the configured filter function.
func (cfg *masterConfig[T]) shouldFilter(item T) bool {
if cfg.filterFunc == nil {
return false
}
return !cfg.filterFunc(item)
}
// handleExpansion checks if a node should be expanded based on the configured expand function and expands it if true.
func (cfg *masterConfig[T]) handleExpansion(node *Node[T]) {
if cfg.expandFunc == nil {
return
}
if cfg.expandFunc(node) {
node.Expand()
}
}
// hasTraversalCapBeenReached checks if the current node count has reached or exceeded the configured traversal cap.
func (cfg *masterConfig[T]) hasTraversalCapBeenReached(nodeCount int) bool {
if cfg.traversalCap <= 0 {
return false
}
return nodeCount >= cfg.traversalCap
}
// hasDepthLimitBeenReached checks if the given current depth has reached or exceeded the configured maximum depth limit.
func (cfg *masterConfig[T]) hasDepthLimitBeenReached(currentDepth int) bool {
if cfg.maxDepth < 0 {
return false
}
return currentDepth >= cfg.maxDepth
}
// reportProgress invokes the configured progress callback (if any).
func (cfg *masterConfig[T]) reportProgress(processed int, node *Node[T]) {
if cfg.progressCb == nil || node == nil {
return
}
cfg.progressCb(processed, node)
}
// defaultSearchFn implements a simple case-insensitive search strategy that matches any substring
// in the node's ID, name, or data (if it's a string or has a String() method).
func defaultSearchFn[T any](_ context.Context, node *Node[T], term string) bool {
// Empty term means no matches
if term == "" {
return false
}
// First, prepare the search comparison values
// We'll check both the node's ID and Name definitely
fields := []string{
strings.ToLower(node.ID()),
strings.ToLower(node.Name()),
"",
"",
}
// Then the data if it's a string or has a String() method.
if nodeData, ok := any(*node.Data()).(string); ok {
fields[2] = strings.ToLower(nodeData)
}
if nodeData, ok := any(*node.Data()).(interface{ String() string }); ok {
fields[3] = strings.ToLower(nodeData.String())
}
searchTerm := strings.ToLower(term)
// Substring match of any field
if slices.ContainsFunc(fields, func(field string) bool {
return strings.Contains(field, searchTerm)
}) {
return true
}
return false
}
// defaultFocusPolicy implements a simple focus navigation strategy.
// It moves through the visible nodes linearly, wrapping at boundaries.
func defaultFocusPolicy[T any](_ context.Context, visible []*Node[T], current *Node[T], offset int) (*Node[T], error) {
// Handle empty list
if len(visible) == 0 {
return nil, nil
}
// If no current focus, start at the beginning for positive offset
// or end for negative offset
if current == nil {
if offset > 0 {
return visible[0], nil
}
return visible[len(visible)-1], nil
}
// Find current position
currentIdx := -1
for i, node := range visible {
if node == current {
currentIdx = i
break
}
}
// If current node not in visible list, start from beginning/end
if currentIdx == -1 {
if offset > 0 {
return visible[0], nil
}
return visible[len(visible)-1], nil
}
// Calculate new position with wrapping
newIdx := currentIdx + offset
if newIdx < 0 {
newIdx = len(visible) - 1 // Wrap to end
} else if newIdx >= len(visible) {
newIdx = 0 // Wrap to beginning
}
return visible[newIdx], nil
}