Kitex
← All examples · Run any demo natively with go run ./examples/<name>.
Kitex Dashboard (examples/kitex_demo)
Section titled “Kitex Dashboard (examples/kitex_demo)”Run go run ./examples/kitex_demo to add, reverse, shuffle, increment, and delete keyed kitex.Map list items.
type Styles struct { ItemRow st.Style ItemLabel st.Style IncrementBtn st.Style DeleteBtn st.Style AppContainer st.Style AppTitle st.Style Instructions st.Style ActionPanel st.Style AddBtn st.Style ReverseBtn st.Style ShuffleBtn st.Style ListContainer st.Style}
var styles = Styles{ ItemRow: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow). AlignItems(st.AlignCenter). Margin(0, 0, 1, 0). Padding(0, 1). Border(st.SingleBorder()). Background(st.RGB(35, 35, 50)),
ItemLabel: st.S(). Width(st.Percent(40)). Foreground(st.RGB(220, 220, 230)),
IncrementBtn: st.S(). Margin(0, 1). Background(st.RGB(60, 120, 220)). Foreground(color.White). Hover(st.S(). Background(st.RGB(80, 140, 240))),
DeleteBtn: st.S(). Margin(0, 1). Background(st.RGB(200, 60, 60)). Foreground(color.White). Hover(st.S(). Background(st.RGB(240, 80, 80))),
AppContainer: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Width(st.Percent(100)). Height(st.Percent(100)). Padding(1, 2). Background(st.RGB(20, 20, 30)),
AppTitle: st.S(). Margin(0, 0, 1, 0). Foreground(st.RGB(90, 140, 255)). Bold(true). TextAlign(st.TextAlignCenter),
Instructions: st.S(). Margin(0, 0, 1, 0). Foreground(st.RGB(150, 150, 170)),
ActionPanel: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow). Margin(0, 0, 1, 0),
AddBtn: st.S(). Margin(0, 1). Background(st.RGB(50, 180, 100)). Foreground(color.White). Hover(st.S(). Background(st.RGB(70, 210, 120))),
ReverseBtn: st.S(). Margin(0, 1). Background(st.RGB(160, 80, 220)). Foreground(color.White). Hover(st.S(). Background(st.RGB(190, 100, 250))),
ShuffleBtn: st.S(). Margin(0, 1). Background(st.RGB(220, 130, 40)). Foreground(color.White). Hover(st.S(). Background(st.RGB(250, 160, 60))),
ListContainer: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Padding(1, 1). Border(st.DoubleBorder()). Background(st.RGB(25, 25, 38)),}
type ItemData struct { Key string ID string}
type ItemProps struct { Key string ID string OnDelete func()}
var ListItem = kx.FC("ListItem", func(props ItemProps) kx.Node { getClicks, setClicks := kx.UseState(0)
return kx.Box.Style(styles.ItemRow, kx.Span.Style(styles.ItemLabel, kx.Textf("Item %s (Clicks: %d)", props.ID, getClicks()), ),
kx.Button(kx.ButtonProps{ OnPress: func() { setClicks.Update(func(n int) int { return n + 1 }) }, Style: styles.IncrementBtn, }, kx.Text(" +1 ")),
kx.Button(kx.ButtonProps{ OnPress: props.OnDelete, Style: styles.DeleteBtn, }, kx.Text(" Delete ")), )})
var App = kx.FC("App", func(_ kx.NoProps) kx.Node { getItems, setItems := kx.UseState([]ItemData{ { Key: "1", ID: "A", }, { Key: "2", ID: "B", }, { Key: "3", ID: "C", }, }) getNextID, setNextID := kx.UseState(4)
handleDelete := func(key string) { setItems.Update(func(current []ItemData) []ItemData { nextItems := make([]ItemData, 0, len(current)) for _, item := range current { if item.Key != key { nextItems = append(nextItems, item) } } return nextItems }) }
renderItem := func(item ItemData, _ int) kx.Node { k := item.Key return ListItem.Props(ItemProps{ Key: k, ID: item.ID, OnDelete: func() { handleDelete(k) }, }) }
return kx.Box.Style(styles.AppContainer, kx.Box.Style(styles.AppTitle, kx.Text("⚡ Kitex VDOM Reconciler Dashboard ⚡"), ),
kx.Box.Style(styles.Instructions, kx.Text("Click buttons below to Add, Reverse, Shuffle, or edit items."), ),
kx.Box.Style(styles.ActionPanel, kx.Button(kx.ButtonProps{ OnPress: func() { nid := getNextID() label := string(rune('A' + (nid-1)%26)) if nid > 26 { label = fmt.Sprintf("%s%d", label, nid) } setItems.Update(func(items []ItemData) []ItemData { return append(items, ItemData{ Key: fmt.Sprintf("%d", nid), ID: label, }) }) setNextID.Update(func(n int) int { return n + 1 }) }, Style: styles.AddBtn, }, kx.Text(" Add Item ")),
kx.Button(kx.ButtonProps{ OnPress: func() { setItems.Update(func(items []ItemData) []ItemData { n := len(items) reversed := make([]ItemData, n) for i, item := range items { reversed[n-1-i] = item } return reversed }) }, Style: styles.ReverseBtn, }, kx.Text(" Reverse List ")),
kx.Button(kx.ButtonProps{ OnPress: func() { setItems.Update(func(items []ItemData) []ItemData { n := len(items) shuffled := make([]ItemData, n) copy(shuffled, items) rand.Shuffle(n, func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] }) return shuffled }) }, Style: styles.ShuffleBtn, }, kx.Text(" Shuffle List ")), ),
kx.Box.Style(styles.ListContainer, kx.Map(getItems(), renderItem)), )})Convenience Hooks (examples/kitex_hooks)
Section titled “Convenience Hooks (examples/kitex_hooks)”Run go run ./examples/kitex_hooks to test UseRef, UseFocus, and global UseKeyboard input tracking.
type Styles struct { AppContainer st.Style Card st.Style Title st.Style LastKeyBox st.Style}
var styles = Styles{ AppContainer: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). JustifyContent(st.JustifyCenter). AlignItems(st.AlignCenter). Width(st.Percent(100)). Height(st.Percent(100)). Background(st.RGB(20, 20, 20)),
Card: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). AlignItems(st.AlignCenter). Gap(1),
Title: st.S(). Foreground(st.RGB(90, 140, 255)). Bold(true),
LastKeyBox: st.S(). Margin(1, 0). Padding(0, 1). Border(st.SingleBorder()). Background(st.RGB(30, 30, 40)),}
var App = kx.FC("App", func(_ kx.NoProps) kx.Node { buttonRef := kx.UseRef[dom.Element](nil) isFocused := kx.UseFocus(buttonRef) getLastKey, setLastKey := kx.UseState("None")
kx.UseKeyboard(func(e event.KeyEvent) { setLastKey(e.Text) })
borderColor := st.RGB(0, 255, 0) if isFocused { borderColor = st.RGB(255, 0, 0) }
return kx.Box.Style( styles.AppContainer, kx.Box.Style(styles.Card, kx.Span.Style(styles.Title, kx.Text("⚡ Kitex Convenience Hooks Demo ⚡"), ), kx.Text("Press any key to update · [Tab] toggles focus."),
kx.Box.Style(styles.LastKeyBox, kx.Textf("Last key: %s", getLastKey()), ),
kx.Button(kx.ButtonProps{ Ref: buttonRef, Style: st.S(). Width(st.Cells(25)). Height(st.Cells(3)). Padding(0, 1). Border(st.SingleBorder().Color(borderColor)). Background(st.RGB(40, 40, 40)), }, kx.Textf("Focused: %v", isFocused)), ), )})Context System (examples/kitex_context_demo)
Section titled “Context System (examples/kitex_context_demo)”Run go run ./examples/kitex_context_demo to watch outer, nested, and default consumers react to kitex.CreateContext providers.
type Styles struct { Btn st.Style AppContainer st.Style AppTitle st.Style ButtonRow st.Style ProviderBox st.Style}
var styles = Styles{ Btn: st.S(). Margin(0, 1). Padding(0, 1). Background(st.RGB(70, 70, 90)). Foreground(color.White),
AppContainer: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Padding(1, 2). Background(st.RGB(15, 15, 20)),
AppTitle: st.S(). Margin(0, 0, 1, 0). Foreground(st.RGB(255, 200, 50)). Bold(true),
ButtonRow: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow). Margin(0, 0, 1, 0),
ProviderBox: st.S(). Margin(1, 0). Padding(1, 1). Border(st.SingleBorder()),}
func getThemeStyle(theme Theme) st.Style { var bg, fg color.Color switch theme { case ThemeDark: bg = st.RGB(25, 25, 30) fg = st.RGB(240, 240, 245) case ThemeBlue: bg = st.RGB(15, 35, 75) fg = st.RGB(210, 230, 255) default: // ThemeLight bg = st.RGB(245, 245, 245) fg = st.RGB(30, 30, 35) }
return st.S(). Margin(1, 0). Padding(1, 2). Border(st.SingleBorder()). Background(bg). Foreground(fg)}
type Theme string
const ( ThemeLight Theme = "light" ThemeDark Theme = "dark" ThemeBlue Theme = "blue")
var ThemeContext = kx.CreateContext(ThemeLight)
var ConsumerComponent = kx.FC("ConsumerComponent", func(_ kx.NoProps) kx.Node { theme := kx.UseContext(ThemeContext) themeStyle := getThemeStyle(theme)
return kx.Box.Style(themeStyle, kx.Textf("Consumer (Current Theme: %s)", theme), )})
var DefaultConsumer = kx.FC("DefaultConsumer", func(_ kx.NoProps) kx.Node { theme := kx.UseContext(ThemeContext) themeStyle := getThemeStyle(theme)
themeStyle = themeStyle.Border(st.DoubleBorder())
return kx.Box.Style(themeStyle, kx.Textf("Default Consumer - Outside Provider (Theme: %s)", theme), )})
var App = kx.FC("App", func(_ kx.NoProps) kx.Node { outerTheme, setOuterTheme := kx.UseState(ThemeDark) innerTheme, setInnerTheme := kx.UseState(ThemeBlue)
toggleOuter := func() { switch outerTheme() { case ThemeLight: setOuterTheme(ThemeDark) case ThemeDark: setOuterTheme(ThemeBlue) case ThemeBlue: setOuterTheme(ThemeLight) } }
toggleInner := func() { switch innerTheme() { case ThemeLight: setInnerTheme(ThemeDark) case ThemeDark: setInnerTheme(ThemeBlue) case ThemeBlue: setInnerTheme(ThemeLight) } }
return kx.Box.Style(styles.AppContainer,
kx.Box.Style(styles.AppTitle, kx.Text("⚛️ Kitex Context System Demo")),
kx.Box.Style(styles.ButtonRow, kx.Button(kx.ButtonProps{ OnPress: toggleOuter, Style: styles.Btn, }, kx.Text("Toggle Outer Theme")),
kx.Button(kx.ButtonProps{ OnPress: toggleInner, Style: styles.Btn, }, kx.Text("Toggle Inner Theme")), ),
DefaultConsumer(),
ThemeContext.Provider(outerTheme(), kx.Box.Style(styles.ProviderBox, kx.Textf("Outer Provider (Providing: %s)", outerTheme()),
ConsumerComponent(),
ThemeContext.Provider(innerTheme(), kx.Box.Style(styles.ProviderBox, kx.Textf( "Nested Inner Provider (Providing: %s)", innerTheme(), ),
ConsumerComponent(), ), ), ), ), )})Refs (examples/kitex_ref_demo)
Section titled “Refs (examples/kitex_ref_demo)”Run go run ./examples/kitex_ref_demo to compare mutable non-rendering refs with DOM Input refs for programmatic focus.
type Styles struct { AppContainer st.Style AppTitle st.Style AppDescription st.Style Card1 st.Style SectionHeader st.Style ContentRow st.Style ButtonRow st.Style IncrementBtn st.Style ForceRenderBtn st.Style Card2 st.Style InputRow st.Style InputField st.Style FocusBtn st.Style}
var styles = Styles{ AppContainer: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Width(st.Percent(100)). Height(st.Percent(100)). Padding(1, 2). Background(st.RGB(20, 20, 26)),
AppTitle: st.S(). Margin(0, 0, 1, 0). Foreground(st.RGB(242, 194, 48)). Bold(true). TextAlign(st.TextAlignCenter),
AppDescription: st.S(). Margin(0, 0, 1, 0). Foreground(st.RGB(160, 160, 180)),
Card1: st.S(). Margin(0, 0, 1, 0). Padding(1, 1). Border(st.SingleBorder()). Background(st.RGB(30, 30, 40)),
SectionHeader: st.S(). Margin(0, 0, 1, 0). Bold(true),
ContentRow: st.S(). Margin(0, 0, 1, 0),
ButtonRow: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow),
IncrementBtn: st.S(). Margin(0, 1). Background(st.RGB(70, 130, 180)). Foreground(color.White),
ForceRenderBtn: st.S(). Margin(0, 1). Background(st.RGB(60, 179, 113)). Foreground(color.White),
Card2: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Padding(1, 1). Border(st.SingleBorder()). Background(st.RGB(30, 30, 40)),
InputRow: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow). AlignItems(st.AlignCenter). Margin(0, 0, 1, 0),
InputField: st.S(). Padding(0, 1). Border(st.SingleBorder()). Background(st.RGB(50, 50, 60)). Foreground(color.White),
FocusBtn: st.S(). Background(st.RGB(219, 112, 147)). Foreground(color.White),}
var App = kx.FC("App", func(_ kx.NoProps) kx.Node {
getRenderCount, setRenderCount := kx.UseState(1)
clicksRef := kx.UseRef(0)
inputRef := kx.UseRef[el.Element](nil)
handleRefClick := func(e *event.MouseEvent) { clicksRef.Current++ }
handleForceRender := func(e *event.MouseEvent) { setRenderCount(getRenderCount() + 1) }
handleFocusInput := func(e *event.MouseEvent) { if inputRef.Current != nil {
doc := inputRef.Current.OwnerDocument() if doc != nil { doc.Focus(inputRef.Current) } } }
return kx.Box.Style( styles.AppContainer,
kx.Box.Style( styles.AppTitle, kx.Text("✨ Kitex Ref & Hook Demonstration ✨"), ),
kx.Box.Style( styles.AppDescription, kx.Text( "This demo shows how UseRef stores persistent mutable "+ "values without triggering re-renders, and how it binds "+ "to real DOM elements.", ), ),
kx.Box.Style( styles.Card1, kx.Box.Style( styles.SectionHeader, kx.Text("1. Non-Rendering Ref State"), ),
kx.Box.Style( styles.ContentRow, kx.Textf( "Ref Clicks (won't update UI directly): %d", clicksRef.Current, ), ),
kx.Box.Style( styles.ContentRow, kx.Textf( "Total Renders (force-render to update UI): %d", getRenderCount(), ), ),
kx.Box.Style( styles.ButtonRow, kx.Button(kx.ButtonProps{ OnClick: handleRefClick, Style: styles.IncrementBtn, }, kx.Text(" Increment Ref Clicks ")),
kx.Button(kx.ButtonProps{ OnClick: handleForceRender, Style: styles.ForceRenderBtn, }, kx.Text(" Force Render ")), ), ),
kx.Box.Style( styles.Card2, kx.Box.Style( styles.SectionHeader, kx.Text("2. DOM Element Ref Wiring & Programmatic Focus"), ),
kx.Box.Style( styles.ContentRow, kx.Text( "Use the button below to programmatically focus the "+ "input field using its Ref pointer:", ), ),
kx.Box.Style( styles.InputRow, kx.Input(kx.InputProps{ Ref: inputRef, Value: "Focus me programmatically!", Style: styles.InputField, }), ),
kx.Box.Style( styles.ButtonRow, kx.Button(kx.ButtonProps{ OnClick: handleFocusInput, Style: styles.FocusBtn, }, kx.Text(" Focus Input Field via Ref ")), ), ), )})Effect Hooks (examples/kitex_effects_demo)
Section titled “Effect Hooks (examples/kitex_effects_demo)”Run go run ./examples/kitex_effects_demo to manage background tickers and pub/sub subscriptions with UseEffectCleanup.
type Styles struct { TimerBox st.Style SectionHeader st.Style ContentRow st.Style SubscriptionBox st.Style AppContainer st.Style AppTitle st.Style AppDescription st.Style ActionsPanel st.Style BroadcastBtn st.Style ToggleBtn st.Style}
var styles = Styles{ TimerBox: st.S(). Margin(0, 0, 1, 0). Padding(1, 1). Border(st.SingleBorder()). Background(st.RGB(30, 30, 40)),
SectionHeader: st.S(). Margin(0, 0, 1, 0). Bold(true),
ContentRow: st.S(). Margin(0, 0, 1, 0),
SubscriptionBox: st.S(). Margin(0, 0, 1, 0). Padding(1, 1). Border(st.SingleBorder()). Background(st.RGB(30, 40, 30)),
AppContainer: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Width(st.Percent(100)). Height(st.Percent(100)). Padding(1, 2). Background(st.RGB(20, 20, 26)),
AppTitle: st.S(). Margin(0, 0, 1, 0). Foreground(st.RGB(90, 140, 255)). Bold(true). TextAlign(st.TextAlignCenter),
AppDescription: st.S(). Margin(0, 0, 1, 0). Foreground(st.RGB(160, 160, 180)),
ActionsPanel: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow). Margin(0, 0, 1, 0),
BroadcastBtn: st.S(). Margin(0, 1). Background(st.RGB(60, 120, 220)). Foreground(color.White),
ToggleBtn: st.S(). Margin(0, 1). Background(st.RGB(160, 80, 220)). Foreground(color.White),}
type PubSub struct { mu sync.Mutex subs map[int]func(string) next int}
func (ps *PubSub) Subscribe(fn func(string)) func() { ps.mu.Lock() defer ps.mu.Unlock() if ps.subs == nil { ps.subs = make(map[int]func(string)) } idx := ps.next ps.next++ ps.subs[idx] = fn return func() { ps.mu.Lock() defer ps.mu.Unlock() delete(ps.subs, idx) }}
func (ps *PubSub) Publish(msg string) { ps.mu.Lock() defer ps.mu.Unlock() for _, sub := range ps.subs { if sub != nil { sub(msg) } }}
var brokerContext = kx.CreateContext[*PubSub](nil)
var TimerComponent = kx.FC("TimerComponent", func(_ kx.NoProps) kx.Node { getSeconds, setSeconds := kx.UseState(0) getIsActive, setIsActive := kx.UseState(true)
kx.UseEffectCleanup(func() func() { if !getIsActive() { return func() {} } ticker := time.NewTicker(time.Second) done := make(chan struct{})
go func() { for { select { case <-ticker.C: setSeconds(getSeconds() + 1) case <-done: return } } }()
return func() { ticker.Stop() close(done) } }, getIsActive())
statusText := "RUNNING" btnText := " Pause Timer " btnBg := st.RGB(220, 80, 80) if !getIsActive() { statusText = "PAUSED" btnText = " Resume Timer " btnBg = st.RGB(80, 180, 100) }
return kx.Box.Style(styles.TimerBox, kx.Box.Style(styles.SectionHeader, kx.Text("⏳ 1. UseEffect Timer Demonstration"), ),
kx.Box.Style(styles.ContentRow, kx.Textf( "Elapsed Time: %d seconds (%s)", getSeconds(), statusText, ), ),
kx.Button(kx.ButtonProps{ OnClick: func(e *event.MouseEvent) { setIsActive(!getIsActive()) }, Style: st.S(). Background(btnBg). Foreground(color.White), }, kx.Text(btnText)), )})
var Subscription = kx.FC("Subscription", func(_ kx.NoProps) kx.Node { broker := kx.UseContext(brokerContext) getMessage, setMessage := kx.UseState("No broadcasts received yet.") getMsgCount, setMsgCount := kx.UseState(0)
kx.UseEffectCleanup(func() func() { unsub := broker.Subscribe(func(msg string) { setMessage(msg) setMsgCount(getMsgCount() + 1) }) return unsub })
return kx.Box.Style(styles.SubscriptionBox, kx.Box.Style(styles.SectionHeader, kx.Text("📢 2. UseEffect Subscription Demonstration"), ),
kx.Box.Style(styles.ContentRow, kx.Textf("Last Broadcast: %s", getMessage()), ),
kx.Box.Style(styles.ContentRow, kx.Textf("Total Messages Received: %d", getMsgCount()), ), )})
var App = kx.FC("App", func(_ kx.NoProps) kx.Node { broker := kx.UseMemo(func() *PubSub { return &PubSub{} }) getShowSub, setShowSub := kx.UseState(true)
publishPhrases := []string{ "Hello from the outer bounds of Kitex!", "Effects are working flawlessly in the event loop.", "Timers and subscriptions are running asynchronously.", "Zero engine changes were made for this effect system!", "Go-based Virtual DOM is responsive and reactive.", }
handlePublish := func(e *event.MouseEvent) { phrase := publishPhrases[rand.Intn(len(publishPhrases))] broker.Publish(phrase) }
return kx.Box.Style(styles.AppContainer, kx.Box.Style(styles.AppTitle, kx.Text("⚡ Kitex Effect Hooks & Lifecycle Demo ⚡"), ),
kx.Box.Style(styles.AppDescription, kx.Text( "Click buttons (or Tab + Space) to broadcast, pause, or unmount effects.", ), ),
kx.Box.Style(styles.ActionsPanel, kx.Button(kx.ButtonProps{ OnClick: handlePublish, Style: styles.BroadcastBtn, }, kx.Text(" Broadcast Phrase ")),
kx.Button(kx.ButtonProps{ OnClick: func(e *event.MouseEvent) { setShowSub(!getShowSub()) }, Style: styles.ToggleBtn, }, kx.Text(func() string { if getShowSub() { return " Unmount Subscription Component " } return " Mount Subscription Component " }())), ),
TimerComponent(),
brokerContext.Provider(broker, kx.If(getShowSub(), Subscription)), )})Autocomplete (examples/kitex_autocomplete_demo)
Section titled “Autocomplete (examples/kitex_autocomplete_demo)”Run go run ./examples/kitex_autocomplete_demo to filter commands and select suggestions inside an anchored kitex.Overlay.
type Styles struct { Root st.Style Card st.Style Title st.Style BodyText st.Style Input st.Style Status st.Style OverlayCard st.Style MenuTitle st.Style MenuList st.Style MenuRow st.Style MenuRowActive st.Style MenuRowIdle st.Style MenuDetail st.Style NoMatch st.Style}
var styles = Styles{ Root: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). JustifyContent(st.JustifyCenter). AlignItems(st.AlignCenter). Width(st.Percent(100)). Height(st.Percent(100)). Background(st.Hex("#11141c")),
Card: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Width(st.Cells(58)). Background(st.Hex("#1c202c")). Border(st.DoubleBorder().Color(st.Hex("#56658c"))). Padding(1, 2),
Title: st.S(). Margin(0, 0, 1, 0). Foreground(st.Hex("#c9d6ff")). Bold(true),
BodyText: st.S(). Margin(0, 0, 1, 0). Foreground(st.Hex("#96a0be")),
Input: st.S(). Width(st.Percent(100)). Padding(0, 1). Border(st.SingleBorder().Color(st.Hex("#586896"))). Background(st.Hex("#141822")). Foreground(st.Hex("#ebeeff")),
Status: st.S(). Margin(1, 0, 0, 0). Foreground(st.Hex("#7bcda5")),
OverlayCard: st.S(). Width(st.Cells(42)). Padding(0, 1). Border(st.SingleBorder().Color(st.Hex("#6c7cab"))). Background(st.Hex("#181c26")),
MenuTitle: st.S(). Margin(0, 0, 1, 0). Foreground(st.Hex("#b0bcdc")). Bold(true),
MenuList: st.S(). ListStyleType(st.ListStyleNone). Margin(0). Padding(0),
MenuRow: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Margin(0, 0, 1, 0). Padding(0, 1),
MenuRowActive: st.S(). Background(st.Hex("#3f5491")). Foreground(st.Hex("#f5f8ff")),
MenuRowIdle: st.S(). Background(st.Hex("#212634")). Foreground(st.Hex("#e2e7f8")),
MenuDetail: st.S(). Foreground(st.Hex("#8e97b2")),
NoMatch: st.S(). Padding(0, 1). Foreground(st.Hex("#c49797")),}
type suggestion struct { Label string Detail string}
var commandSuggestions = []suggestion{ { Label: "git status", Detail: "Show the current worktree status.", }, { Label: "git switch -c feature/autocomplete", Detail: "Create and switch to a new branch.", }, { Label: "go test ./...", Detail: "Run the full Go test suite.", }, { Label: "go test ./extras/kitex", Detail: "Run the Kitex package tests.", }, { Label: "npm run dev", Detail: "Start the local development server.", }, { Label: "docker compose up", Detail: "Start the local service stack.", }, { Label: "kubectl get pods", Detail: "Inspect the current Kubernetes pods.", }, { Label: "gh pr create", Detail: "Open a pull request from the current branch.", },}
func clampIndex(idx, length int) int { if length <= 0 { return 0 } if idx < 0 { return 0 } if idx >= length { return length - 1 } return idx}
func AutocompleteMenu( filtered []suggestion, selectedIndex int, applySuggestion func(suggestion),) kx.Node { return kx.Box.Style(styles.OverlayCard, kx.Box.Style(styles.MenuTitle, kx.Text("Autocomplete")), kx.IfElse(len(filtered) == 0, kx.Box.Style(styles.NoMatch, kx.Text("No matches for the current query."), ), kx.UL.Style(styles.MenuList, kx.Map(filtered, func(item suggestion, idx int) kx.Node { rowStyle := styles.MenuRow. Merge(styles.MenuRowIdle). When(idx == selectedIndex, styles.MenuRowActive) return kx.LI(kx.LIProps{ Key: fmt.Sprintf("%s-%d", item.Label, idx), Style: rowStyle, OnClick: func(*event.MouseEvent) { applySuggestion(item) }, }, kx.Text(item.Label), kx.Box.Style(styles.MenuDetail, kx.Text(item.Detail)), ) }), ), ), )}
var App = kx.FC("App", func(_ kx.NoProps) kx.Node { inputRef := kx.UseRef[dom.Element](nil) getQuery, setQuery := kx.UseState("") getMenuOpen, setMenuOpen := kx.UseState(false) getSelectedIndex, setSelectedIndex := kx.UseState(0)
filtered := kx.UseMemo(func() []suggestion { query := strings.TrimSpace(strings.ToLower(getQuery())) matches := make([]suggestion, 0, len(commandSuggestions)) for _, item := range commandSuggestions { label := strings.ToLower(item.Label) detail := strings.ToLower(item.Detail) if strings.Contains(label, query) || strings.Contains(detail, query) { matches = append(matches, item) } if len(matches) == 5 { break } } return matches }, getQuery())
selectedIndex := clampIndex(getSelectedIndex(), len(filtered))
isInputFocused := func() bool { if inputRef.Current == nil { return false } doc := inputRef.Current.OwnerDocument() return doc != nil && doc.CurrentFocus() == inputRef.Current }
applySuggestion := func(item suggestion) { setMenuOpen(false) setSelectedIndex(0) setQuery(item.Label) if inputRef.Current != nil { if doc := inputRef.Current.OwnerDocument(); doc != nil { doc.Focus(inputRef.Current) } } }
kx.UseLayoutEffect(func() { if inputRef.Current != nil { if doc := inputRef.Current.OwnerDocument(); doc != nil { doc.Focus(inputRef.Current) } } })
kx.UseEffect(func() { if !getMenuOpen() { return } if len(filtered) == 0 { setSelectedIndex(0) return } if idx := getSelectedIndex(); idx != selectedIndex { setSelectedIndex(selectedIndex) } }, getMenuOpen(), len(filtered), getSelectedIndex(), selectedIndex)
statusText := "Ctrl+Space opens autocomplete for the focused input." if len(filtered) > 0 && getMenuOpen() { statusText = fmt.Sprintf("Preview: %s", filtered[selectedIndex].Label) }
menu := kx.Empty() if getMenuOpen() && inputRef.Current != nil { menu = kx.Overlay(kx.OverlayProps{ Anchor: inputRef.Current, Placement: geom.PlacementBottom, Flip: true, ZIndex: 100, }, AutocompleteMenu(filtered, selectedIndex, applySuggestion)) }
return kx.Box.Style(styles.Root, kx.Box.Style(styles.Card, kx.Box.Style(styles.Title, kx.Text("Kitex Autocomplete Demo")), kx.Box.Style(styles.BodyText, kx.Text( "Type to filter shell-style commands. Press Ctrl+Space "+ "while the input is focused to open the autocomplete "+ "menu.", ), ), kx.Input(kx.InputProps{ Ref: inputRef, Value: getQuery(), Placeholder: "Try: git, go, docker, kubectl...", Style: styles.Input, OnValueChange: func(val string) { if getMenuOpen() { setSelectedIndex(0) } setQuery(val) }, OnKeyDown: func(ke *event.KeyEvent) { if !isInputFocused() { return }
switch { case ke.MatchString("ctrl+space"): setMenuOpen(!getMenuOpen()) setSelectedIndex(0) ke.PreventDefault() ke.StopPropagation() case getMenuOpen() && ke.MatchString("escape"): setMenuOpen(false) ke.PreventDefault() ke.StopPropagation() case getMenuOpen() && len(filtered) > 0 && ke.MatchString("down"): setSelectedIndex((selectedIndex + 1) % len(filtered)) ke.PreventDefault() ke.StopPropagation() case getMenuOpen() && len(filtered) > 0 && ke.MatchString("up"): next := selectedIndex - 1 if next < 0 { next = len(filtered) - 1 } setSelectedIndex(next) ke.PreventDefault() ke.StopPropagation() case getMenuOpen() && len(filtered) > 0 && ke.MatchString("enter"): applySuggestion(filtered[selectedIndex]) ke.PreventDefault() ke.StopPropagation() } }, }), menu,
kx.Box.Style(styles.Status, kx.Text(statusText)), ), )})Reducer Form (examples/reducer)
Section titled “Reducer Form (examples/reducer)”Run go run ./examples/reducer to drive multi-field form state transitions with kitex.UseReducer.
type Styles struct { FieldRow st.Style RolesContainer st.Style ButtonRow st.Style Root st.Style Card st.Style Title st.Style Label st.Style Input st.Style RoleButton st.Style LastRoleButton st.Style Submit st.Style Reset st.Style Preview st.Style PreviewTitle st.Style Success st.Style Selected st.Style}
var styles = Styles{ FieldRow: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow). AlignItems(st.AlignCenter). Width(st.Percent(100)). Margin(0, 0, 1, 0),
RolesContainer: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow). Flex(1),
ButtonRow: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexRow). JustifyContent(st.JustifyCenter). Width(st.Percent(100)). Margin(1, 0, 1, 0),
Root: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). JustifyContent(st.JustifyCenter). AlignItems(st.AlignCenter). Width(st.Percent(100)). Height(st.Percent(100)). Padding(1, 2). Background(colBG),
Card: st.S(). Display(st.DisplayFlex). FlexDirection(st.FlexColumn). Width(st.Percent(80)). Padding(1, 2). Border(st.DoubleBorder().Color(colBorder)). Background(colCard),
Title: st.S(). Margin(0, 0, 1, 0). Foreground(colHeader). Bold(true). TextAlign(st.TextAlignCenter),
Label: st.S(). Width(st.Cells(10)). Foreground(colText),
Input: st.S(). Flex(1). Padding(0, 1). Border(st.SingleBorder().Color(colBorder)). Background(colInput). Foreground(colText),
RoleButton: st.S(). Margin(0, 1, 0, 0). Background(colInput). Foreground(colText),
LastRoleButton: st.S(). Background(colInput). Foreground(colText),
Submit: st.S(). Margin(0, 2, 0, 0). Background(colButton). Foreground(colText),
Reset: st.S(). Background(colResetBtn). Foreground(colText),
Preview: st.S(). Width(st.Percent(100)). Padding(1, 1). Border(st.SingleBorder().Color(colBorder)). Background(colInput),
PreviewTitle: st.S(). Margin(0, 0, 1, 0). Foreground(colHeader). Bold(true),
Success: st.S(). Margin(1, 0, 0, 0). Foreground(colSuccess). Bold(true),
Selected: st.S(). Background(colHeader),}
type FormState struct { Name string Email string Role string Submitted bool}
type Action struct { Type string Value string}
func formReducer(state FormState, action Action) FormState { switch action.Type { case "SET_NAME": state.Name = action.Value state.Submitted = false case "SET_EMAIL": state.Email = action.Value state.Submitted = false case "SET_ROLE": state.Role = action.Value state.Submitted = false case "SUBMIT": state.Submitted = true case "RESET": state.Name = "" state.Email = "" state.Role = "Developer" state.Submitted = false } return state}
var ( colBG = st.RGB(20, 20, 30) colCard = st.RGB(30, 30, 45) colInput = st.RGB(40, 40, 60) colText = st.RGB(220, 220, 240) colHeader = st.RGB(120, 140, 255) colSuccess = st.RGB(100, 220, 140) colButton = st.RGB(70, 90, 200) colResetBtn = st.RGB(180, 60, 60) colBorder = st.RGB(60, 60, 90))
var App = kx.FC("App", func(_ kx.NoProps) kx.Node { getState, dispatch := kx.UseReducer(formReducer, FormState{ Name: "", Email: "", Role: "Developer", Submitted: false, })
state := getState()
return kx.Box.Style(styles.Root, kx.Box.Style(styles.Card,
kx.Box.Style(styles.Title, kx.Text("⚡ Kitex VDOM UseReducer Form Demo ⚡"), ),
kx.Box.Style(styles.FieldRow, kx.Span.Style(styles.Label, kx.Text("Name: "), ), kx.Input(kx.InputProps{ Value: state.Name, OnValueChange: func(value string) { dispatch(Action{ Type: "SET_NAME", Value: value, }) }, Style: styles.Input, }), ),
kx.Box.Style(styles.FieldRow, kx.Span.Style(styles.Label, kx.Text("Email: "), ), kx.Input(kx.InputProps{ Value: state.Email, OnValueChange: func(value string) { dispatch(Action{ Type: "SET_EMAIL", Value: value, }) }, Style: styles.Input, }), ),
kx.Box.Style(styles.FieldRow, kx.Span.Style(styles.Label, kx.Text("Role: "), ), kx.Box.Style(styles.RolesContainer, kx.Button(kx.ButtonProps{ OnPress: func() { dispatch(Action{ Type: "SET_ROLE", Value: "Developer", }) }, Style: styles.RoleButton.When(state.Role == "Developer", styles.Selected), }, kx.Text(" Developer ")), kx.Button(kx.ButtonProps{ OnPress: func() { dispatch(Action{ Type: "SET_ROLE", Value: "Designer", }) }, Style: styles.RoleButton.When(state.Role == "Designer", styles.Selected), }, kx.Text(" Designer ")), kx.Button(kx.ButtonProps{ OnPress: func() { dispatch(Action{ Type: "SET_ROLE", Value: "Manager", }) }, Style: styles.LastRoleButton.When(state.Role == "Manager", styles.Selected), }, kx.Text(" Manager ")), ), ),
kx.Box.Style(styles.ButtonRow, kx.Button(kx.ButtonProps{ OnPress: func() { dispatch(Action{Type: "SUBMIT"}) }, Style: styles.Submit, }, kx.Text(" SUBMIT ")), kx.Button(kx.ButtonProps{ OnPress: func() { dispatch(Action{Type: "RESET"}) }, Style: styles.Reset, }, kx.Text(" RESET ")), ),
kx.Box.Style(styles.Preview, kx.Box.Style(styles.PreviewTitle, kx.Text("State Live Preview:"), ), kx.Box(kx.BoxProps{}, kx.Textf("Name: %s", state.Name)), kx.Box(kx.BoxProps{}, kx.Textf("Email: %s", state.Email)), kx.Box(kx.BoxProps{}, kx.Textf("Role: %s", state.Role)), func() kx.Node { if state.Submitted { return kx.Box.Style(styles.Success, kx.Text("✓ Form Submitted Successfully!"), ) } return nil }(), ), ), )})