Documentation
¶
Index ¶
- Constants
- Variables
- func ClampCursor(cur, count int) int
- func HighlightShellSpans(cmd string, scheme *theme.Scheme, base color.Color) []trail.Node
- func MenuDigit(k key.Key) int
- func ResolveTokenStyle(t *theme.Scheme, tokType chroma.TokenType) style.Style
- func StepCursor(cur, count int, k event.KeyEvent) (next int, handled bool)
- type ActionMenuItem
- type ActionMenuProps
- type AttachmentRefNode
- type AutocompleteEdit
- type AutocompleteOptions
- type AutocompleteProps
- type AutocompleteState
- type AutocompleteView
- type ButtonColor
- type ButtonProps
- type ButtonVariant
- type CodeBlockProps
- type Column
- type Cursor
- type KeyBinding
- type KeyboardHintProps
- type MarkdownProps
- type MathBlockNode
- type MathInlineNode
- type Option
- type OptionListProps
- type OptionListStyles
- type ScrollOptions
- type ScrollState
- type ScrollViewerAction
- type ScrollViewerProps
Constants ¶
const DefaultAutocompleteMaxVisible = 5
DefaultAutocompleteMaxVisible is the default number of visible options in autocomplete.
const DefaultPickerMaxVisible = 8
DefaultPickerMaxVisible is the default number of visible options in a picker before scrolling.
Variables ¶
var ActionMenu = trail.FC("ActionMenu", func(props ActionMenuProps) trail.Node { scheme := theme.UseTheme() cursor := UseCursor(len(props.Items), props.InitialIndex) cur := cursor.Index if props.Selected != nil { cur = ClampCursor(*props.Selected, len(props.Items)) } setIndex := func(next int) { next = ClampCursor(next, len(props.Items)) if props.Selected == nil { cursor.Set(next) } if next != cur && props.OnChange != nil { props.OnChange(next) } } trail.UseInput(func(input string, k event.KeyEvent) { if props.Disabled || len(props.Items) == 0 { return } for i, item := range props.Items { if matchMenuShortcut(input, k, item.Shortcut) { setIndex(i) if props.OnSelect != nil { props.OnSelect(i, item) } return } } if props.Numbered { if d := MenuDigit(k.Key); d >= 1 && d <= len(props.Items) { idx := d - 1 setIndex(idx) if props.OnSelect != nil { props.OnSelect(idx, props.Items[idx]) } return } } if next, handled := StepCursor(cur, len(props.Items), k); handled { if next != cur { setIndex(next) } return } if k.MatchString("enter") && props.OnSelect != nil { props.OnSelect(cur, props.Items[cur]) } }, trail.InputOptions{IsActive: !props.Disabled}) if len(props.Items) == 0 { return nil } selectedStyle := style.S().Bold(true).Foreground(scheme.Color.Icon.Primary).WhiteSpace(style.WhiteSpacePreWrap) unselectedStyle := style.S().Foreground(scheme.Color.Text.Primary).WhiteSpace(style.WhiteSpacePreWrap) if props.UnselectedStyle != nil { unselectedStyle = *props.UnselectedStyle } defaultBadgeStyle := style.S().Foreground(scheme.Color.Text.Muted).WhiteSpace(style.WhiteSpacePre) maxLabelWidth := 0 for i, item := range props.Items { if item.Badge == "" { continue } w := utf8.RuneCountInString(actionMenuDisplayLabel(i, item, props.Numbered)) if w > maxLabelWidth { maxLabelWidth = w } } indentStr := "" if props.Indent > 0 { indentStr = strings.Repeat(" ", props.Indent) } rows := make([]trail.Node, 0, len(props.Items)) for i, item := range props.Items { displayLabel := actionMenuDisplayLabel(i, item, props.Numbered) prefix := " " rowStyle := unselectedStyle prefixStyle := unselectedStyle.WhiteSpace(style.WhiteSpacePre) if i == cur { prefix = "❯ " rowStyle = selectedStyle prefixStyle = selectedStyle.WhiteSpace(style.WhiteSpacePre) } var spans []trail.Node if item.Badge != "" { padLen := max(maxLabelWidth-utf8.RuneCountInString(displayLabel)+3, 1) padding := strings.Repeat(" ", padLen) badgeSty := defaultBadgeStyle if item.BadgeStyle != nil { badgeSty = item.BadgeStyle.WhiteSpace(style.WhiteSpacePre) } spans = append(spans, trail.Span(trail.SpanProps{Style: prefixStyle}, trail.Text(indentStr+prefix)), trail.Span(trail.SpanProps{Style: rowStyle.WhiteSpace(style.WhiteSpacePre)}, trail.Text(displayLabel+padding)), trail.Span(trail.SpanProps{Style: badgeSty}, trail.Text(item.Badge)), ) } else { spans = append(spans, trail.Span(trail.SpanProps{Style: prefixStyle}, trail.Text(indentStr+prefix)), trail.Span(trail.SpanProps{Style: rowStyle}, trail.Text(displayLabel)), ) } rows = append(rows, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow).Width(style.Percent(100)), }, spans...)) } return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).Width(style.Percent(100)), }, rows...) })
ActionMenu is an embeddable interactive selection menu supporting arrow/vi navigation, optional numbering, per-item letter shortcuts, and aligned badges.
var Autocomplete = trail.FC("Autocomplete", func(props AutocompleteProps) trail.Node { scheme := theme.UseTheme() state := props.State if !state.IsOpen { return nil } if state.Error != nil { return trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Error), }, trail.Text(fmt.Sprintf("Autocomplete: %v", state.Error))) } if state.IsLoading && len(state.Result.Candidates) == 0 { return trail.Text("Completing...") } var content trail.Node if view := props.Views[state.Result.Source]; view != nil { content = view(state.Result, state.Selected) } else { options := make([]Option, len(state.Result.Candidates)) for i, candidate := range state.Result.Candidates { label := candidate.Label if label == "" { label = candidate.Value } options[i] = Option{ Value: candidate.Value, Label: label, Description: candidate.Description, } } content = OptionList(OptionListProps{ Options: options, Selected: state.Selected, MaxVisible: DefaultAutocompleteMaxVisible, }) } if len(state.Result.Candidates) == 0 { return content } bindings := props.Bindings if len(bindings) == 0 { bindings = defaultAutocompleteBindings } return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).Width(style.Percent(100)), }, content, KeyboardHint(KeyboardHintProps{Bindings: bindings})) })
Autocomplete renders suggestions without resolving or executing them.
var Button = kitex.FCC("Button", func(props ButtonProps) kitex.Node { isHovered, setIsHovered := kitex.UseState(false) isFocused, setIsFocused := kitex.UseState(false) t := theme.UseTheme() if t == nil { return kitex.Button(kitex.ButtonProps{ Key: props.Key, Disabled: props.Disabled, Active: props.Active, OnClick: func(e event.Event) { if props.OnClick != nil && !props.Disabled { props.OnClick() } }, }, props.Children...) } var textCol, bgCol, borderCol color.Color switch props.Color { case ButtonSecondary: textCol = t.Color.Text.Secondary bgCol = t.Color.Surface.Selected borderCol = t.Color.Border.Default case ButtonTertiary: textCol = t.Color.Text.Warning bgCol = t.Color.Tint.Warning borderCol = t.Color.Border.Warning case ButtonSuccess: textCol = t.Color.Text.Success bgCol = t.Color.Tint.Success borderCol = t.Color.Border.Success case ButtonInfo: textCol = t.Color.Text.Info bgCol = t.Color.Tint.Info borderCol = t.Color.Border.Info case ButtonError: textCol = t.Color.Text.Error bgCol = t.Color.Tint.Error borderCol = t.Color.Border.Error case ButtonBase: textCol = t.Color.Text.Primary bgCol = t.Color.Surface.Panel borderCol = t.Color.Border.Default default: textCol = t.Color.Text.Accent bgCol = t.Color.Tint.Accent borderCol = t.Color.Border.Accent } if props.Disabled { textCol = t.Color.Text.Disabled bgCol = t.Color.Surface.Disabled borderCol = t.Color.Border.Subtle } else if isHovered() || isFocused() { borderCol = t.Color.Border.Focus } s := ButtonBaseStyle switch props.Variant { case ButtonTonal: s = s.Background(bgCol).Foreground(textCol) case ButtonSolid: s = s.Background(bgCol).Foreground(textCol) case ButtonOutline: s = s.Border(style.SingleBorder().Color(borderCol)).Foreground(textCol) if isHovered() || isFocused() { s = s.Background(t.Color.Surface.Hover) } case ButtonText: s = s.Foreground(textCol) if isHovered() || isFocused() { s = s.Background(t.Color.Surface.Hover) } default: s = s.Background(bgCol).Foreground(textCol) } s = s.Merge(props.Style) if isHovered() || isFocused() { s = s.Merge(props.HoverStyle) } if props.Active { s = s.Merge(props.ActiveStyle) } var content []kitex.Node if props.StartIcon != nil { content = append(content, kitex.Box(kitex.BoxProps{}, props.StartIcon)) } content = append(content, props.Children...) if props.EndIcon != nil { content = append(content, kitex.Box(kitex.BoxProps{}, props.EndIcon)) } return kitex.Button(kitex.ButtonProps{ Key: props.Key, Style: s, Disabled: props.Disabled, Active: props.Active, OnClick: func(e event.Event) { if props.OnClick != nil && !props.Disabled { props.OnClick() } }, OnMouseEnter: func(e event.Event) { setIsHovered(true) }, OnMouseLeave: func(e event.Event) { setIsHovered(false) }, OnFocus: func(e event.Event) { setIsFocused(true) }, OnBlur: func(e event.Event) { setIsFocused(false) }, }, content...) })
Button is an interactive component that triggers an action. It integrates with the theme system to react to theme changes.
var ( // ButtonBaseStyle is the base style for all buttons. ButtonBaseStyle = style.S(). Display(style.DisplayFlex). AlignItems(style.AlignCenter). Gap(1). Border(false). Padding(0, 1) )
var CodeBlock = kitex.FC("CodeBlock", func(props CodeBlockProps) kitex.Node { t := theme.UseTheme() return kitex.UseMemo(func() kitex.Node { codeStr := strings.ReplaceAll(props.Code, "\t", " ") lang := props.Lang if strings.TrimSpace(codeStr) == "" { return nil } if lang == "" { lang = "code" } titleStyle := style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). JustifyContent(style.JustifyBetween). PaddingHorizontal(1). Bold(true). Background(t.Color.Surface.Code). Foreground(t.Color.Text.Primary). BorderBottom(true, style.SingleBorder(), t.Color.Border.Default) padCode := 1 if props.Compact { padCode = 0 } whiteSpace := style.WhiteSpacePre if props.Wrap { whiteSpace = style.WhiteSpacePreWrap } codeStyle := style.S(). Padding(padCode). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)). WhiteSpace(whiteSpace). Foreground(t.Color.Text.Secondary) if props.Wrap { codeStyle = codeStyle. OverflowX(style.OverflowHidden). OverflowWrap(style.OverflowWrapBreakWord) } else { codeStyle = codeStyle. OverflowX(style.OverflowAuto) } wrapperStyle := style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)). WhiteSpace(whiteSpace) if props.Wrap { wrapperStyle = wrapperStyle. Overflow(style.OverflowHidden). OverflowWrap(style.OverflowWrapBreakWord) } if !props.HideHeader { wrapperStyle = wrapperStyle. MarginBottom(1). Background(t.Color.Surface.Code). Border(true, style.SingleBorder(), t.Color.Border.Default) } else if !props.Compact { wrapperStyle = wrapperStyle.Background(t.Color.Surface.Code) } wrapperStyle = wrapperStyle.Merge(props.Style) var contentNodes []kitex.Node lexer := lexers.Get(lang) if lexer == nil { lexer = lexers.Fallback } lexer = chroma.Coalesce(lexer) iterator, err := lexer.Tokenise(nil, codeStr) if err != nil { fallbackStyle := style.S().WhiteSpace(whiteSpace) if props.Wrap { fallbackStyle = fallbackStyle. OverflowWrap(style.OverflowWrapBreakWord). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)) } contentNodes = []kitex.Node{ kitex.Span( kitex.SpanProps{Style: fallbackStyle}, kitex.Text(codeStr), ), } } else { var currentType chroma.TokenType var currentText strings.Builder var hasPending bool flushCurrent := func() { if hasPending { tokenStyle := ResolveTokenStyle(t, currentType) if props.Wrap { tokenStyle = tokenStyle. WhiteSpace(style.WhiteSpacePreWrap). OverflowWrap(style.OverflowWrapBreakWord). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)) } contentNodes = append(contentNodes, kitex.Span( kitex.SpanProps{Style: tokenStyle}, kitex.Text(currentText.String()), )) currentText.Reset() hasPending = false } } for tok := iterator(); tok != chroma.EOF; tok = iterator() { if !hasPending { currentType = tok.Type currentText.WriteString(tok.Value) hasPending = true } else if tok.Type == currentType { currentText.WriteString(tok.Value) } else { flushCurrent() currentType = tok.Type currentText.WriteString(tok.Value) hasPending = true } } flushCurrent() } rowStyle := style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)) padY := 1 if props.Compact { padY = 0 } gutterStyle := style.S(). PaddingVertical(padY). PaddingLeft(1). PaddingRight(1). TextAlign(style.TextAlignRight). WhiteSpace(style.WhiteSpacePre) if props.GutterMinWidth > 0 { gutterStyle = gutterStyle.MinWidth(style.Cells(props.GutterMinWidth)) } gutterStyle = gutterStyle.Foreground(t.Color.Text.Muted) separatorStyle := style.S(). PaddingVertical(padY). Foreground(t.Color.Border.Default) codeBoxStyle := style.S(). PaddingVertical(padY). PaddingLeft(1). PaddingRight(1). Flex(1, 1, style.Cells(0)). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)). MinHeight(style.Cells(0)). WhiteSpace(whiteSpace). Foreground(t.Color.Text.Secondary) if props.Wrap { codeBoxStyle = codeBoxStyle. OverflowX(style.OverflowHidden). OverflowWrap(style.OverflowWrapBreakWord) } else { codeBoxStyle = codeBoxStyle. OverflowX(style.OverflowAuto) } var gutterText string var separatorText string if props.ShowLineNumbers { start := props.StartLine if start <= 0 { start = 1 } lineCount := 0 if codeStr != "" { lineCount = strings.Count(codeStr, "\n") + 1 } var gutterBuilder strings.Builder var sepBuilder strings.Builder for i := 0; i < lineCount; i++ { if i > 0 { gutterBuilder.WriteByte('\n') sepBuilder.WriteByte('\n') } fmt.Fprintf(&gutterBuilder, "%d", start+i) sepBuilder.WriteString("│") } gutterText = gutterBuilder.String() separatorText = sepBuilder.String() } var codeContainer kitex.Node if props.ShowLineNumbers { codeContainer = kitex.Box(kitex.BoxProps{Style: rowStyle}, kitex.Box(kitex.BoxProps{Style: gutterStyle}, kitex.Text(gutterText), ), kitex.Box(kitex.BoxProps{Style: separatorStyle}, kitex.Text(separatorText), ), kitex.Box(kitex.BoxProps{Style: codeBoxStyle}, contentNodes..., ), ) } else { codeContainer = kitex.Box(kitex.BoxProps{Style: codeStyle}, contentNodes..., ) } return kitex.Box(kitex.BoxProps{Style: wrapperStyle}, kitex.If(!props.HideHeader, func() kitex.Node { return kitex.Box(kitex.BoxProps{Style: titleStyle}, kitex.Span(kitex.SpanProps{}, kitex.Text(strings.ToUpper(lang))), kitex.Span(kitex.SpanProps{}, kitex.Text("READONLY")), ) }), codeContainer, ) }, []any{ t, props.Code, props.Lang, props.HideHeader, props.ShowLineNumbers, props.StartLine, props.Compact, props.Wrap, props.GutterMinWidth, props.Style, }) })
CodeBlock renders a syntax-highlighted code block using chroma, fully styled using the active TUI theme.
var KeyboardHint = trail.FC("KeyboardHint", func(props KeyboardHintProps) trail.Node { if len(props.Bindings) == 0 { return nil } scheme := theme.UseTheme() prefixStyle := style.S().Flex(0, 0).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Muted) keyStyle := style.S().Bold(true).WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Icon.Primary) labelStyle := style.S().WhiteSpace(style.WhiteSpacePre).Foreground(scheme.Color.Text.Secondary) pairStyle := style.S().Display(style.DisplayFlex).Flex(0, 0).FlexDirection(style.FlexRow) items := make([]trail.Node, 0, len(props.Bindings)) for _, b := range props.Bindings { pair := []trail.Node{ trail.Span(trail.SpanProps{Style: keyStyle}, trail.Text(b.Key)), } if b.Label != "" { pair = append(pair, trail.Span(trail.SpanProps{Style: labelStyle}, trail.Text(" "+b.Label))) } items = append(items, trail.Box(trail.BoxProps{Style: pairStyle}, pair...)) } return trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexRow). Width(style.Percent(100)). MarginTop(1), }, trail.Span(trail.SpanProps{Style: prefixStyle}, trail.Text("Keyboard: ")), trail.Box(trail.BoxProps{ Style: style.S(). Display(style.DisplayFlex). Flex(1). MinWidth(style.Cells(0)). FlexDirection(style.FlexRow). FlexWrap(style.FlexWrapOn). Gap(0, 2), }, items...), ) })
KeyboardHint renders a "Keyboard: <key> <label> ..." bar with keys highlighted in the primary icon color, wrapping whole key/label pairs onto continuation lines aligned after the "Keyboard: " gutter on narrow screens.
var Markdown = kitex.FC("Markdown", func(props MarkdownProps) kitex.Node { t := theme.UseTheme() node := kitex.UseMemo(func() kitex.Node { if strings.TrimSpace(props.Source) == "" { return nil } attMap := make(map[string]api.Attachment, len(props.Attachments)) for _, att := range props.Attachments { if att.Ref != "" { attMap[att.Ref] = att } } src := []byte(props.Source) md := goldmark.New( goldmark.WithExtensions(extension.Table), goldmark.WithParserOptions( parser.WithBlockParsers(util.Prioritized(mathBlockParser{}, 850)), parser.WithInlineParsers( util.Prioritized(mathInlineParser{}, 150), util.Prioritized(&attachmentRefParser{attachments: attMap}, 999), ), ), ) doc := md.Parser().Parse(text.NewReader(src)) // renderInline renders inline nodes (Text, Span) inside a block. var renderInline func(n ast.Node) kitex.Node // renderBlock renders block-level nodes (Box). var renderBlock func(n ast.Node) kitex.Node // renderBlockChildren collects block children of a parent. var renderBlockChildren func(parent ast.Node) []kitex.Node mathSpan := func(seg mathSegment) trail.Node { s := style.S() if seg.style&mathBold != 0 { s = s.Bold(true) } if seg.style&mathMono != 0 { s = s.Foreground(t.Color.Text.Accent).Background(t.Color.Surface.Code) } return trail.Span(trail.SpanProps{Style: s}, trail.Text(seg.text)) } var renderInlineChildren = func(parent ast.Node) []kitex.Node { var out []kitex.Node var textBuf strings.Builder flushText := func() { if s := textBuf.String(); s != "" { out = append(out, kitex.Text(s)) textBuf.Reset() } } for child := parent.FirstChild(); child != nil; child = child.NextSibling() { if m, ok := child.(*MathInlineNode); ok { for _, seg := range translateMath(m.Raw) { if seg.style == 0 { textBuf.WriteString(seg.text) } else { flushText() out = append(out, mathSpan(seg)) } } } else if tn, ok := child.(*ast.Text); ok { textBuf.WriteString(string(tn.Value(src))) if tn.SoftLineBreak() || tn.HardLineBreak() { textBuf.WriteByte('\n') } } else { flushText() if n := renderInline(child); n != nil { out = append(out, n) } } } flushText() return out } renderBlockChildren = func(parent ast.Node) []kitex.Node { var out []kitex.Node for child := parent.FirstChild(); child != nil; child = child.NextSibling() { if n := renderBlock(child); n != nil { out = append(out, n) } } return out } renderInline = func(n ast.Node) kitex.Node { switch node := n.(type) { case *AttachmentRefNode: return renderAttachmentRefPill(node, t, props.OnAttachmentClick, props.IsDirectory) case *ast.Text: val := string(node.Value(src)) if val == "" { return nil } if node.SoftLineBreak() || node.HardLineBreak() { return kitex.Text(val + "\n") } return kitex.Text(val) case *ast.CodeSpan: var b strings.Builder for child := node.FirstChild(); child != nil; child = child.NextSibling() { if tn, ok := child.(*ast.Text); ok { b.Write(tn.Value(src)) } } spanText := b.String() spanStyle := style.S(). Display(style.DisplayInlineBlock). WhiteSpace(style.WhiteSpacePreWrap). OverflowWrap(style.OverflowWrapAnywhere). Background(t.Color.Surface.Code). Foreground(t.Color.Text.Accent) return kitex.Span(kitex.SpanProps{Style: spanStyle}, kitex.Text(spanText), ) case *ast.Emphasis: children := renderInlineChildren(node) if len(children) == 0 { return nil } empStyle := style.S() if node.Level == 1 { empStyle = empStyle.Italic(true) } else { empStyle = empStyle.Bold(true) } return kitex.Span(kitex.SpanProps{Style: empStyle}, children...) case *ast.Link: children := renderInlineChildren(node) if len(children) == 0 { return nil } linkStyle := style.S().Underline(true).Foreground(t.Color.Text.Accent) return kitex.Span(kitex.SpanProps{Style: linkStyle}, children...) case *ast.AutoLink: return kitex.Text(string(node.Label(src))) case *ast.RawHTML: return kitex.Text(strings.TrimSpace(string(node.Segments.Value(src)))) case *ast.String: return kitex.Text(strings.TrimSpace(string(node.Value))) default: children := renderInlineChildren(node) if len(children) > 0 { return kitex.Fragment(children...) } return nil } } renderBlock = func(n ast.Node) kitex.Node { switch node := n.(type) { case *ast.Document: docStyle := style.S(). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)). WhiteSpace(style.WhiteSpacePreWrap). OverflowWrap(style.OverflowWrapAnywhere). Foreground(t.Color.Text.Primary). Merge(props.Style) return kitex.Box(kitex.BoxProps{Style: docStyle}, renderBlockChildren(node)...) case *MathBlockNode: var children []trail.Node for _, seg := range translateMath(node.Raw) { if seg.style == 0 { children = append(children, trail.Text(seg.text)) } else { children = append(children, mathSpan(seg)) } } s := style.S().PaddingLeft(2) if node.NextSibling() != nil { s = s.MarginBottom(1) } return trail.Box(trail.BoxProps{Style: s}, trail.Span(trail.SpanProps{}, children...)) case *ast.Paragraph: children := renderInlineChildren(node) if len(children) == 0 { return nil } pStyle := style.S(). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)) _, inListItem := node.Parent().(*ast.ListItem) _, inBlockquote := node.Parent().(*ast.Blockquote) if inListItem { if node.Parent().FirstChild() == node { return kitex.Fragment(children...) } pStyle = pStyle.MarginTop(1) } else if inBlockquote { if node.NextSibling() != nil { pStyle = pStyle.MarginBottom(1) } } else { if node.NextSibling() != nil { pStyle = pStyle.MarginBottom(1) } } spanStyle := style.S(). WhiteSpace(style.WhiteSpacePreWrap). OverflowWrap(style.OverflowWrapAnywhere) return kitex.Box(kitex.BoxProps{Style: pStyle}, kitex.Span(kitex.SpanProps{Style: spanStyle}, children...), ) case *ast.TextBlock: children := renderInlineChildren(node) if len(children) == 0 { return nil } _, inListItem := node.Parent().(*ast.ListItem) if inListItem { if node.Parent().FirstChild() == node { return kitex.Fragment(children...) } } spanStyle := style.S(). WhiteSpace(style.WhiteSpacePreWrap). OverflowWrap(style.OverflowWrapAnywhere) return kitex.Box(kitex.BoxProps{ Style: style.S(). Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)), }, kitex.Span(kitex.SpanProps{Style: spanStyle}, children...), ) case *ast.Heading: children := renderInlineChildren(node) if len(children) == 0 { return nil } marginBottom := 1 if node.Level == 1 { marginBottom = 2 } var hStyle style.Style if node.NextSibling() != nil { hStyle = style.S().MarginBottom(marginBottom) } else { hStyle = style.S() } hStyle = hStyle. Width(style.Percent(100)). MaxWidth(style.Percent(100)). MinWidth(style.Percent(0)) spanStyle := style.S(). Bold(true). WhiteSpace(style.WhiteSpacePreWrap). OverflowWrap(style.OverflowWrapAnywhere). Foreground(t.Color.Text.Primary) return kitex.Box(kitex.BoxProps{Style: hStyle}, kitex.Span(kitex.SpanProps{Style: spanStyle}, children...), ) case *ast.CodeBlock: var b strings.Builder for i := 0; i < node.Lines().Len(); i++ { seg := node.Lines().At(i) b.Write(seg.Value(src)) } marginBottom := 1 if node.NextSibling() == nil { marginBottom = 0 } plain := props.PlainCodeBlocks || t.Transparent cbStyle := style.S().MarginBottom(marginBottom) if plain { cbStyle = cbStyle.PaddingLeft(2) } return CodeBlock(CodeBlockProps{ Code: strings.TrimRight(b.String(), "\n"), Lang: "code", HideHeader: plain, Compact: plain, Style: cbStyle, }) case *ast.FencedCodeBlock: var b strings.Builder for i := 0; i < node.Lines().Len(); i++ { seg := node.Lines().At(i) b.Write(seg.Value(src)) } lang := "code" if node.Info != nil { if parts := strings.Fields(string(node.Info.Value(src))); len(parts) > 0 { lang = parts[0] } } marginBottom := 1 if node.NextSibling() == nil { marginBottom = 0 } plain := props.PlainCodeBlocks || t.Transparent cbStyle := style.S().MarginBottom(marginBottom) if plain { cbStyle = cbStyle.PaddingLeft(2) } return CodeBlock(CodeBlockProps{ Code: strings.TrimRight(b.String(), "\n"), Lang: lang, HideHeader: plain, Compact: plain, Style: cbStyle, }) case *ast.List: return renderList(node, t, renderBlock) case *ast.Blockquote: children := renderBlockChildren(node) if len(children) == 0 { return nil } qStyle := style.S().PaddingLeft(1). BorderLeft(true, style.SingleBorder(), t.Color.Border.Default) innerBox := kitex.Box(kitex.BoxProps{Style: qStyle}, children...) marginBottom := 1 if node.NextSibling() == nil { marginBottom = 0 } return kitex.Box(kitex.BoxProps{Style: style.S().MinWidth(style.Percent(0)).MarginBottom(marginBottom)}, innerBox) case *ast.ThematicBreak: marginBottom := 1 if node.NextSibling() == nil { marginBottom = 0 } tbStyle := style.S().MarginBottom(marginBottom). Foreground(t.Color.Border.Default). BorderBottom(true, style.SingleBorder(), t.Color.Border.Default) return kitex.Box(kitex.BoxProps{Style: tbStyle}) case *extast.Table: return renderTable(node, t, renderInlineChildren) default: blockChildren := renderBlockChildren(node) if len(blockChildren) > 0 { return kitex.Fragment(blockChildren...) } inlineChildren := renderInlineChildren(node) if len(inlineChildren) > 0 { return kitex.Box(kitex.BoxProps{}, inlineChildren...) } return nil } } return renderBlock(doc) }, []any{t, props.Source, props.Style, props.PlainCodeBlocks, props.Attachments}) return node })
Markdown renders markdown content into Kite UI nodes using goldmark.
var OptionList = trail.FC("OptionList", func(props OptionListProps) trail.Node { offset, setOffset := kitex.UseState(0) scheme := theme.UseTheme() styles := OptionListStyles{ Option: style.S().Foreground(scheme.Color.Text.Secondary), Selected: style.S().Bold(true).Foreground(scheme.Color.Icon.Primary), Description: style.S().Foreground(scheme.Color.Text.Muted), } if props.Styles != nil { styles = *props.Styles } sectionStyle := style.S().Bold(true).Foreground(scheme.Color.Text.Muted) start := 0 end := len(props.Options) targetOff := 0 if props.MaxVisible > 0 && len(props.Options) > props.MaxVisible { off := offset() if props.Selected >= 0 { if props.Selected < off { off = props.Selected } else if props.Selected >= off+props.MaxVisible { off = props.Selected - props.MaxVisible + 1 } } maxOff := len(props.Options) - props.MaxVisible if off < 0 { off = 0 } else if off > maxOff { off = maxOff } targetOff = off start = off end = off + props.MaxVisible } kitex.UseEffect(func() { if targetOff != offset() { setOffset(targetOff) } }, []any{targetOff}) if len(props.Options) == 0 { if props.EmptyText == "" { return nil } return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: styles.Option.WhiteSpace(style.WhiteSpacePre), }, trail.Text(props.EmptyText))) } above := start below := len(props.Options) - end visibleOpts := props.Options[start:end] hasCells := len(visibleOpts[0].Cells) > 0 trs := make([]trail.Node, 0, len(visibleOpts)) numCols := max(len(props.Columns), 1) previousGroup := "" if start > 0 { previousGroup = props.groupOf(props.Options[start-1]) } for relIdx, opt := range visibleOpts { origIdx := start + relIdx rowStyle := styles.Option prefix := " " if props.Selected < 0 { rowStyle = styles.Description } else if origIdx == props.Selected { rowStyle = styles.Selected prefix = "❯ " } group := props.groupOf(opt) if group != "" && group != previousGroup { trs = append(trs, optionSectionRow(group, numCols, len(trs) == 0, sectionStyle)) } previousGroup = group var tds []trail.Node if hasCells && len(opt.Cells) > 0 { cells := slices.Clone(opt.Cells) last := len(cells) - 1 cells[last] = withCurrentSuffix(cells[last], opt.Current) for colIdx, cell := range cells { tdStyle := style.S().Padding(0, 2, 0, 0) text := cell spanStyle := rowStyle if colIdx == 0 { tdStyle = tdStyle.WhiteSpace(style.WhiteSpacePre) text = prefix + cell spanStyle = rowStyle.WhiteSpace(style.WhiteSpacePre) } if colIdx < len(props.Columns) { colSpec := props.Columns[colIdx] if colSpec.Width > 0 { tdStyle = tdStyle.Width(style.Cells(colSpec.Width)). MinWidth(style.Cells(colSpec.Width)) if colIdx != 0 { tdStyle = tdStyle.WhiteSpace(style.WhiteSpaceNoWrap) } } else { tdStyle = tdStyle.Width(style.Percent(100)) } if colSpec.Align != 0 { tdStyle = tdStyle.TextAlign(colSpec.Align) if colSpec.Align == style.TextAlignRight { if colIdx == len(cells)-1 { tdStyle = tdStyle.Padding(0, 0, 0, 0) } else { tdStyle = tdStyle.Padding(0, 2, 0, 0) } } } if props.Selected != origIdx { spanStyle = rowStyle.Merge(colSpec.Style) } } if colIdx == 0 && opt.Icon != nil { tds = append(tds, kitex.TD(kitex.TDProps{ Style: tdStyle, }, optionIconRow(prefix, opt.Icon, cell, spanStyle))) } else if colIdx < len(opt.CellNodes) && opt.CellNodes[colIdx] != nil { tds = append(tds, kitex.TD(kitex.TDProps{ Style: tdStyle, }, opt.CellNodes[colIdx])) } else { tds = append(tds, kitex.TD(kitex.TDProps{ Style: tdStyle, }, trail.Span(trail.SpanProps{Style: spanStyle}, trail.Text(text)))) } } } else { desc := format.CompactSingleLine(opt.Description, 60) labelCell := trail.Span(trail.SpanProps{ Style: rowStyle.WhiteSpace(style.WhiteSpacePre), }, trail.Text(prefix+opt.Label)) if opt.Icon != nil { labelCell = optionIconRow(prefix, opt.Icon, opt.Label, rowStyle.WhiteSpace(style.WhiteSpacePre)) } tds = []trail.Node{ kitex.TD(kitex.TDProps{ Style: style.S().Padding(0, 2, 0, 0).WhiteSpace(style.WhiteSpacePre), }, labelCell), kitex.TD(kitex.TDProps{ Style: style.S(), }, trail.Span(trail.SpanProps{ Style: styles.Description, }, trail.Text(withCurrentSuffix(desc, opt.Current)))), } } trs = append(trs, kitex.TR(kitex.TRProps{}, tds...)) } tableStyle := style.S() if len(props.Columns) > 0 { tableStyle = tableStyle.Width(style.Percent(100)) } tableNode := kitex.Table(kitex.TableProps{ Style: tableStyle, }, kitex.TBody(kitex.TBodyProps{}, trs...)) if above == 0 && below == 0 { return tableNode } var nodes []trail.Node if above > 0 { nodes = append(nodes, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: styles.Description.WhiteSpace(style.WhiteSpacePre), }, trail.Text(fmt.Sprintf(" ↑ %d more", above))))) } nodes = append(nodes, tableNode) if below > 0 { nodes = append(nodes, trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexRow), }, trail.Span(trail.SpanProps{ Style: styles.Description.WhiteSpace(style.WhiteSpacePre), }, trail.Text(fmt.Sprintf(" ↓ %d more", below))))) } return trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn).Width(style.Percent(100)), }, nodes...) })
OptionList is a trail functional component rendering a selectable or informational list of options as a table.
var ScrollViewer = trail.FCC("ScrollViewer", func(props ScrollViewerProps) trail.Node { scheme := theme.UseTheme() winSize := trail.UseWindowSize() scroll := UseScroll(ScrollOptions{ InitialPos: props.InitialScroll, FollowTail: props.FollowTail, ExtraDeps: props.ExtraDeps, OnChange: props.OnScroll, }) trail.UseInput(func(input string, k event.KeyEvent) { if props.Disabled { return } for _, act := range props.Actions { if matchScrollViewerKeys(input, k, act.Keys) { if act.Handler != nil { act.Handler() } return } } if k.MatchString("esc", "escape") { if props.OnClose != nil { props.OnClose() } return } scroll.HandleKey(input, k) }, trail.InputOptions{IsActive: !props.Disabled}) maxHeight := props.MaxHeight if maxHeight <= 0 { if winSize.Height > 0 { maxHeight = max(10, min(28, winSize.Height-6)) } else { maxHeight = 18 } } var children []trail.Node if len(props.Header) > 0 { headerItems := slices.Clone(props.Header) if !scroll.AutoScroll && scroll.Pos > 0 { mutedStyle := style.S().Foreground(scheme.Color.Text.Muted).WhiteSpace(style.WhiteSpacePreWrap) headerItems = append(headerItems, trail.Span(trail.SpanProps{ Style: mutedStyle, }, trail.Text(fmt.Sprintf(" • line +%d", scroll.Pos)))) } headerStyle := style.S().FlexDirection(style.FlexRow).Width(style.Percent(100)) if props.HeaderMarginBottom > 0 { headerStyle = headerStyle.Margin(0, 0, props.HeaderMarginBottom, 0) } children = append(children, trail.Box(trail.BoxProps{Style: headerStyle}, headerItems...)) } if len(props.Meta) > 0 { children = append(children, props.Meta...) } var viewportContent trail.Node switch { case len(props.Children) > 0: viewportContent = trail.Box(trail.BoxProps{ Style: style.S().FlexDirection(style.FlexColumn), }, props.Children...) case strings.TrimSpace(props.Markdown) != "": viewportContent = Markdown(MarkdownProps{Source: props.Markdown}) case props.EmptyText != "": viewportContent = trail.Span(trail.SpanProps{ Style: style.S().Foreground(scheme.Color.Text.Muted), }, trail.Text(props.EmptyText)) } viewportStyle := style.S(). Width(style.Percent(100)). MaxHeight(style.Cells(maxHeight)). OverflowY(style.OverflowAuto). ScrollbarY(true) if props.ViewportStyle != nil { viewportStyle = viewportStyle.Merge(*props.ViewportStyle) } children = append(children, trail.Box(trail.BoxProps{ Ref: scroll.Ref, Style: viewportStyle, }, viewportContent)) if len(props.Bindings) > 0 { children = append(children, KeyboardHint(KeyboardHintProps{ Bindings: props.Bindings, })) } outerStyle := style.S(). Width(style.Percent(100)). FlexDirection(style.FlexColumn) if props.OuterStyle != nil { outerStyle = outerStyle.Merge(*props.OuterStyle) } return trail.Box(trail.BoxProps{Style: outerStyle}, children...) })
ScrollViewer renders a full scrollable Markdown or custom-node inspector with an optional header (showing " • line +N" when scrolled), static metadata, custom key actions, and a bottom KeyboardHint bar.
Functions ¶
func ClampCursor ¶
ClampCursor constrains cur to [0, count-1], returning 0 when count <= 0 or cur < 0.
func HighlightShellSpans ¶
func MenuDigit ¶
MenuDigit maps an unmodified '1'..'9' key press to its 1-based menu index, returning 0 for any other key.
func ResolveTokenStyle ¶
ResolveTokenStyle maps a chroma.TokenType to an editor color dynamically from the active theme.
Types ¶
type ActionMenuItem ¶
type ActionMenuItem struct {
ID string
Label string
Shortcut string
Badge string
BadgeStyle *style.Style
}
ActionMenuItem defines one selectable row in an ActionMenu.
type ActionMenuProps ¶
type ActionMenuProps struct {
Items []ActionMenuItem
InitialIndex int
Selected *int
OnChange func(index int)
OnSelect func(index int, item ActionMenuItem)
Numbered bool
Indent int
Disabled bool
UnselectedStyle *style.Style
}
ActionMenuProps defines the properties for the ActionMenu component.
type AttachmentRefNode ¶
type AttachmentRefNode struct {
ast.BaseInline
RefType string // "file", "sym", "skill", or "rule"
Label string
Target string
SymKind string
IsDir bool
}
AttachmentRefNode is a custom inline AST node representing a @file:, @sym:, @rule:, or structured @attachment token.
func (*AttachmentRefNode) Dump ¶
func (n *AttachmentRefNode) Dump(src []byte, level int)
func (*AttachmentRefNode) Kind ¶
func (n *AttachmentRefNode) Kind() ast.NodeKind
type AutocompleteEdit ¶
AutocompleteEdit replaces a draft and restores its UTF-8 byte cursor.
type AutocompleteOptions ¶
type AutocompleteOptions struct {
Engine *autocomplete.Engine
Value string
Cursor int
Disabled bool
}
AutocompleteOptions identifies the current draft and source snapshot. Supply a new Engine when the underlying source data changes.
type AutocompleteProps ¶
type AutocompleteProps struct {
State AutocompleteState
Views map[string]AutocompleteView
Bindings []KeyBinding // optional keyboard hint footer; falls back to defaultAutocompleteBindings
}
AutocompleteProps presents the state resolved by UseAutocomplete.
type AutocompleteState ¶
type AutocompleteState struct {
Result autocomplete.Result
Selected int
IsOpen bool
IsLoading bool
Error error
Up func() bool
Down func() bool
Dismiss func() bool
Accept func() (AutocompleteEdit, error)
}
AutocompleteState is shared by the input's keyboard handling and the view.
func UseAutocomplete ¶
func UseAutocomplete(opts AutocompleteOptions) AutocompleteState
UseAutocomplete resolves completions using the enclosing wind.Provider. It never submits input or executes candidates.
type AutocompleteView ¶
type AutocompleteView func(autocomplete.Result, int) trail.Node
AutocompleteView renders a source's candidates without changing their order.
type ButtonColor ¶
type ButtonColor string
ButtonColor defines color variants for the Button component.
const ( ButtonPrimary ButtonColor = "primary" ButtonSecondary ButtonColor = "secondary" ButtonTertiary ButtonColor = "tertiary" ButtonSuccess ButtonColor = "success" ButtonInfo ButtonColor = "info" ButtonError ButtonColor = "error" ButtonBase ButtonColor = "base" )
type ButtonProps ¶
type ButtonProps struct {
// Key is an optional unique identifier for the component.
Key string
// Variant specifies the visual variant of the button.
Variant ButtonVariant
// Color specifies the color variant of the button.
Color ButtonColor
// Disabled indicates if the button is interactive.
Disabled bool
// Active indicates if the button is in an active or selected state.
Active bool
// OnClick is the callback triggered when the button is clicked.
OnClick func()
// Style allows passing additional style overrides.
Style style.Style
// HoverStyle allows passing additional style overrides for the hovered state.
HoverStyle style.Style
// ActiveStyle allows passing additional style overrides when the button is active.
ActiveStyle style.Style
// StartIcon is an optional icon to display before the text.
StartIcon kitex.Node
// EndIcon is an optional icon to display after the text.
EndIcon kitex.Node
// Children is the content of the button.
Children []kitex.Node
}
ButtonProps defines the properties for the Button component.
type ButtonVariant ¶
type ButtonVariant string
ButtonVariant defines visual styles for the Button component.
const ( // ButtonText is a button with no background or border. ButtonText ButtonVariant = "text" // ButtonSolid is a button with a solid background. ButtonSolid ButtonVariant = "solid" // ButtonOutline is a button with a border. ButtonOutline ButtonVariant = "outline" // ButtonTonal is a button with a soft/tinted background (e.g. selected pills, theme button, enable all). ButtonTonal ButtonVariant = "tonal" )
type CodeBlockProps ¶
type CodeBlockProps struct {
Code string
Lang string
Style style.Style
HideHeader bool
ShowLineNumbers bool
StartLine int
Compact bool
Wrap bool
GutterMinWidth int
}
CodeBlockProps defines properties for the CodeBlock rendering component.
type Column ¶
type Column struct {
Width int // 0 = flexible / remaining space, >0 = fixed width in cells
Align style.TextAlign // style.TextAlignLeft (default), style.TextAlignCenter, style.TextAlignRight
Style style.Style // optional style override for unselected rows
}
Column defines the width, alignment, and optional cell style for a column in OptionList.
type Cursor ¶
type Cursor struct {
Index int
Set func(i int)
Move func(delta int)
HandleKey func(k event.KeyEvent) bool
}
Cursor holds the clamped index and movement helpers returned by UseCursor.
type KeyBinding ¶
KeyBinding represents a single keyboard shortcut and its action description.
type KeyboardHintProps ¶
type KeyboardHintProps struct {
Bindings []KeyBinding
}
KeyboardHintProps defines the properties for the KeyboardHint component.
type MarkdownProps ¶
type MarkdownProps struct {
Source string
Style style.Style
PlainCodeBlocks bool
Attachments []api.Attachment
// OnAttachmentClick is called when a @file:, @sym:, or @skill: pill is clicked.
// Receives the ref type ("file", "sym", "skill") and the raw value from the token.
// If nil, pills are rendered as static badges.
OnAttachmentClick func(refType, rawValue string)
IsDirectory func(path string) bool
}
MarkdownProps defines properties for the Markdown rendering component.
type MathBlockNode ¶
func (*MathBlockNode) Dump ¶
func (n *MathBlockNode) Dump(src []byte, level int)
func (*MathBlockNode) IsRaw ¶
func (n *MathBlockNode) IsRaw() bool
func (*MathBlockNode) Kind ¶
func (*MathBlockNode) Kind() ast.NodeKind
type MathInlineNode ¶
type MathInlineNode struct {
ast.BaseInline
Raw string
}
func (*MathInlineNode) Dump ¶
func (n *MathInlineNode) Dump(src []byte, level int)
func (*MathInlineNode) Kind ¶
func (*MathInlineNode) Kind() ast.NodeKind
type Option ¶
type Option struct {
Value string
Label string
Description string
// Search holds row text that should answer the picker's filter box without
// being rendered, e.g. a grouping key that only appears as a section heading.
Search string
Cells []string
CellNodes []trail.Node
Current bool
// Icon renders in the cursor gutter between the selection marker and the first
// cell, so a row can carry a status glyph without spending a column on it.
Icon trail.Node
}
Option represents a selectable item in an interactive command picker or autocomplete list.
type OptionListProps ¶
type OptionListProps struct {
Options []Option
Selected int // index of highlighted row, or -1 if no row is highlighted with "❯ "
EmptyText string // optional message when len(Options) == 0 (e.g. " No matching options.")
MaxVisible int // max number of rows visible simultaneously before sliding-window pagination
Columns []Column // column specifications (width, alignment, style override)
Styles *OptionListStyles
// GroupLabel returns the heading a row belongs under. A muted heading row is
// rendered whenever it changes, which keeps a listing scannable without
// spending a column on the grouping.
GroupLabel func(opt Option) string
}
OptionListProps defines the properties for the OptionList component.
type OptionListStyles ¶
OptionListStyles optionally overrides the theme's list styles.
type ScrollOptions ¶
type ScrollOptions struct {
InitialPos int
PageStep int
FollowTail bool
PageOnly bool
ExtraDeps []any
OnChange func(pos int)
}
ScrollOptions configures UseScroll.
type ScrollState ¶
type ScrollState struct {
Ref kitex.Ref[dom.Element]
Pos int
AutoScroll bool
SetPos func(pos int)
Reset func()
HandleKey func(input string, k event.KeyEvent) bool
}
ScrollState exposes the element ref, current offset, and key handler returned by UseScroll.
func UseScroll ¶
func UseScroll(opts ScrollOptions) ScrollState
UseScroll manages vertical scroll state and layout-effect synchronization for a scrollable trail.Box.
type ScrollViewerAction ¶
type ScrollViewerAction struct {
Keys []string
Handler func()
}
ScrollViewerAction binds one or more keys to a custom action in ScrollViewer.
type ScrollViewerProps ¶
type ScrollViewerProps struct {
Header []trail.Node
HeaderMarginBottom int
Meta []trail.Node
Markdown string
EmptyText string
InitialScroll int
OnScroll func(pos int)
MaxHeight int
OuterStyle *style.Style
ViewportStyle *style.Style
Disabled bool
FollowTail bool
ExtraDeps []any
OnClose func()
Actions []ScrollViewerAction
Bindings []KeyBinding
Children []trail.Node
}
ScrollViewerProps defines the properties for the ScrollViewer component.