gitstack

grindlemire/go-tui code browser

10.2 KB Go 411 lines 2026-06-03 ยท d15bb9f raw
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package provider

import (
	"fmt"
	"sort"
	"strings"

	"github.com/grindlemire/go-tui/internal/lsp/gopls"
	"github.com/grindlemire/go-tui/internal/lsp/log"
	"github.com/grindlemire/go-tui/internal/lsp/schema"
)

// --- Completion generators ---

func (c *completionProvider) getComponentCompletions() []CompletionItem {
	var items []CompletionItem
	for _, name := range c.index.All() {
		info, ok := c.index.Lookup(name)
		if !ok || info == nil {
			continue
		}

		// Build parameter string
		var params []string
		for _, p := range info.Params {
			params = append(params, fmt.Sprintf("%s %s", p.Name, p.Type))
		}
		detail := fmt.Sprintf("(%s)", strings.Join(params, ", "))

		items = append(items, CompletionItem{
			Label:      name,
			Kind:       CompletionItemKindFunction,
			Detail:     detail,
			InsertText: name + "()",
			FilterText: name,
		})
	}
	return items
}

func (c *completionProvider) getDSLKeywordCompletions() []CompletionItem {
	return []CompletionItem{
		{
			Label:      "for",
			Kind:       CompletionItemKindKeyword,
			Detail:     "Loop over items",
			InsertText: "for ${1:i}, ${2:item} := range ${3:items} {\n\t$0\n}",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: "Loop over a collection.\n\n```gsx\nfor i, item := range items {\n    <span>{item}</span>\n}\n```",
			},
		},
		{
			Label:      "if",
			Kind:       CompletionItemKindKeyword,
			Detail:     "Conditional rendering",
			InsertText: "if ${1:condition} {\n\t$0\n}",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: "Conditionally render content.\n\n```gsx\nif showHeader {\n    <span>Header</span>\n}\n```",
			},
		},
		{
			Label:      "let",
			Kind:       CompletionItemKindKeyword,
			Detail:     "Bind element to variable",
			InsertText: "let ${1:name} = ",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: "Bind an element to a variable for later reference.\n\n```gsx\nheader := <div>Header</div>\n```",
			},
		},
	}
}

func (c *completionProvider) getElementCompletions() []CompletionItem {
	var items []CompletionItem
	for _, tag := range schema.AllElementTags() {
		elem := schema.GetElement(tag)
		if elem == nil {
			continue
		}

		insertText := tag + ">$0</" + tag + ">"
		if elem.SelfClosing {
			insertText = tag + " />"
		}

		items = append(items, CompletionItem{
			Label:      tag,
			Kind:       CompletionItemKindClass,
			Detail:     elem.Category,
			InsertText: insertText,
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: elem.Description,
			},
		})
	}
	return items
}

func (c *completionProvider) getAttributeCompletions(tag string) []CompletionItem {
	elem := schema.GetElement(tag)
	if elem == nil {
		return nil
	}

	var items []CompletionItem
	for _, attr := range elem.Attributes {
		var insertText string
		if attr.Type == "bool" {
			insertText = attr.Name
		} else if attr.Type == "string" {
			insertText = attr.Name + `="${1}"`
		} else {
			insertText = attr.Name + "={$1}"
		}

		items = append(items, CompletionItem{
			Label:      attr.Name,
			Kind:       CompletionItemKindProperty,
			Detail:     attr.Type,
			InsertText: insertText,
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: attr.Description,
			},
		})
	}

	// Also offer event handler attributes that aren't already in the element's schema
	for _, handlerName := range schema.AllEventHandlerNames() {
		handler := schema.GetEventHandler(handlerName)
		if handler == nil {
			continue
		}
		// Skip if already in the element's attributes
		if schema.GetAttribute(tag, handlerName) != nil {
			continue
		}
		items = append(items, CompletionItem{
			Label:      handlerName,
			Kind:       CompletionItemKindEvent,
			Detail:     handler.Signature,
			InsertText: handlerName + "={$1}",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: handler.Description,
			},
		})
	}

	return items
}

func (c *completionProvider) getContextualCompletions(ctx *CursorContext) []CompletionItem {
	// If inside an element tag, offer attribute completions
	if ctx.InElement && ctx.AttrTag != "" {
		return c.getAttributeCompletions(ctx.AttrTag)
	}

	// Check if we can detect the enclosing tag from text
	tag := enclosingTagFromText(ctx)
	if tag != "" {
		return c.getAttributeCompletions(tag)
	}

	// Default: offer all top-level completions
	var items []CompletionItem
	items = append(items, c.getComponentCompletions()...)
	items = append(items, c.getDSLKeywordCompletions()...)
	items = append(items, c.getElementCompletions()...)
	return items
}

// enclosingTagFromText searches backwards from cursor for an unclosed < to find the tag name.
func enclosingTagFromText(ctx *CursorContext) string {
	offset := PositionToOffset(ctx.Document.Content, ctx.Position)
	content := ctx.Document.Content

	for i := offset - 1; i >= 0; i-- {
		if content[i] == '<' {
			// Extract tag name
			j := i + 1
			for j < len(content) && IsWordChar(content[j]) {
				j++
			}
			if j > i+1 {
				tagName := content[i+1 : j]
				// Check we haven't passed a > before cursor
				for k := j; k < offset; k++ {
					if content[k] == '>' {
						return "" // Past the tag
					}
				}
				return tagName
			}
			break
		}
		if content[i] == '>' {
			break // Hit a closing bracket
		}
	}
	return ""
}

// --- State method completions ---

// getStateMethodCompletions returns state method completions when the user types
// a state variable name followed by a dot (e.g., "count.").
func (c *completionProvider) getStateMethodCompletions(ctx *CursorContext) []CompletionItem {
	if len(ctx.Scope.StateVars) == 0 {
		return nil
	}

	// Check if the text before cursor looks like "stateVarName."
	offset := PositionToOffset(ctx.Document.Content, ctx.Position)
	if offset <= 1 {
		return nil
	}

	content := ctx.Document.Content
	// Look for a dot just before cursor
	dotPos := offset - 1
	// Skip back past whitespace to the dot
	for dotPos > 0 && (content[dotPos] == ' ' || content[dotPos] == '\t') {
		dotPos--
	}
	if dotPos < 0 || content[dotPos] != '.' {
		return nil
	}

	// Extract the word before the dot
	wordEnd := dotPos
	wordStart := wordEnd - 1
	for wordStart >= 0 && IsWordChar(content[wordStart]) {
		wordStart--
	}
	wordStart++
	if wordStart >= wordEnd {
		return nil
	}
	varName := content[wordStart:wordEnd]

	// Check if it matches a state variable
	isStateVar := false
	for _, sv := range ctx.Scope.StateVars {
		if sv.Name == varName {
			isStateVar = true
			break
		}
	}
	if !isStateVar {
		return nil
	}

	log.Server("State method completion for %q", varName)

	return []CompletionItem{
		{
			Label:      "Get()",
			Kind:       CompletionItemKindMethod,
			Detail:     "Get current value",
			InsertText: "Get()",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: "Returns the current value of the state variable.",
			},
		},
		{
			Label:      "Set(value)",
			Kind:       CompletionItemKindMethod,
			Detail:     "Set new value",
			InsertText: "Set(${1:value})",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: "Sets a new value for the state variable, triggering a re-render.",
			},
		},
		{
			Label:      "Update(fn)",
			Kind:       CompletionItemKindMethod,
			Detail:     "Update with function",
			InsertText: "Update(func(current ${1:T}) ${2:T} {\n\t${3:return current}\n})",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: "Updates the state using a function that receives the current value and returns the new value.",
			},
		},
		{
			Label:      "Bind(fn)",
			Kind:       CompletionItemKindMethod,
			Detail:     "Register change callback",
			InsertText: "Bind(${1:callback})",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: "Registers a callback that is called when the state changes.",
			},
		},
		{
			Label:      "Batch(fn)",
			Kind:       CompletionItemKindMethod,
			Detail:     "Batch multiple updates",
			InsertText: "Batch(func() {\n\t$0\n})",
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: "Batches multiple state updates into a single re-render.",
			},
		},
	}
}

// --- Tailwind class completions ---

func (c *completionProvider) getTailwindCompletions(prefix string) []CompletionItem {
	matches := schema.MatchClasses(prefix)

	var items []CompletionItem
	for _, cls := range matches {
		docValue := cls.Description
		items = append(items, CompletionItem{
			Label:      cls.Name,
			Kind:       CompletionItemKindConstant,
			Detail:     cls.Category,
			InsertText: cls.Name,
			FilterText: cls.Name,
			Documentation: &MarkupContent{
				Kind:  "markdown",
				Value: docValue,
			},
		})
	}

	sortCompletionsByCategory(items)
	return items
}

// sortCompletionsByCategory sorts completion items by category priority then name.
func sortCompletionsByCategory(items []CompletionItem) {
	categoryOrder := map[string]int{
		"layout":     1,
		"flex":       2,
		"spacing":    3,
		"typography": 4,
		"visual":     5,
	}

	sort.Slice(items, func(i, j int) bool {
		orderI := categoryOrder[items[i].Detail]
		orderJ := categoryOrder[items[j].Detail]
		if orderI == 0 {
			orderI = 100
		}
		if orderJ == 0 {
			orderJ = 100
		}
		if orderI != orderJ {
			return orderI < orderJ
		}
		return items[i].Label < items[j].Label
	})
}

// --- gopls completion delegation ---

func (c *completionProvider) getGoplsCompletions(ctx *CursorContext) ([]CompletionItem, error) {
	proxy := c.goplsProxy.GetProxy()
	if proxy == nil {
		return nil, nil
	}

	cached := c.virtualFiles.GetVirtualFile(ctx.Document.URI)
	if cached == nil || cached.SourceMap == nil {
		return nil, nil
	}

	goLine, goCol, found := cached.SourceMap.TuiToGo(ctx.Position.Line, ctx.Position.Character)
	if !found {
		log.Server("No mapping found for completion position %d:%d", ctx.Position.Line, ctx.Position.Character)
		return nil, nil
	}

	goplsItems, err := proxy.Completion(cached.GoURI, gopls.Position{
		Line:      goLine,
		Character: goCol,
	})
	if err != nil {
		return nil, err
	}

	var items []CompletionItem
	for _, gi := range goplsItems {
		item := CompletionItem{
			Label:      gi.Label,
			Kind:       CompletionItemKind(gi.Kind),
			Detail:     gi.Detail,
			InsertText: gi.InsertText,
			FilterText: gi.FilterText,
		}
		if gi.Documentation != nil {
			item.Documentation = &MarkupContent{
				Kind:  gi.Documentation.Kind,
				Value: gi.Documentation.Value,
			}
		}
		items = append(items, item)
	}

	return items, nil
}