stage

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

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

README

Kitex Stage

The stage package provides an interactive component development playground and sandbox for Kitex applications. It allows you to build, test, and preview components in complete isolation without running your main application.

stage

Features

  • 🎭 Isolated Scenes: Register components with different mock scenarios (e.g. Primary, Secondary, Disabled).
  • 🛠️ Dynamic Controls: Add interactive knobs (c.Text(), c.Bool(), c.Select(), c.Int()) to tweak properties and styles in real-time.
  • 🌍 Global Controls: Register toolbar controls (e.g. Theme, Locale) that affect all components and persist across scene selections.
  • 🎨 Context-Aware Decorators: Inject global providers (like Theme contexts) or layout wrappers around all scenes, driven by active global settings.
  • 📋 Event Action Log: Capture and view component actions and callback events locally.
  • ⌨️ Keyboard Navigation: Use global hotkeys to switch scenes without leaving the keyboard.
  • 🔍 Devtools Integration: Integrates directly with standard Kite web-inspector devtools (devtools.Install) for layout and DOM inspections.

Usage

Create a standalone playground command file (e.g., cmd/stage/main.go):

package main

import (
	"github.com/masterkeysrd/kite/extras/kitex"
	"github.com/masterkeysrd/kite/extras/stage"
	"github.com/masterkeysrd/kite/style"
)

func main() {
	stg := stage.New()

	// 1. Register global controls (toolbar controls)
	stg.GlobalSelect("Theme", []string{"Light", "Dark"}, "Dark")
	stg.GlobalBool("Show Border", true)

	// 2. Wrap all scenes with a context-aware decorator
	stg.WithContextDecorator(func(c *stage.Context, node kitex.Node) kitex.Node {
		theme := c.GlobalString("Theme", "Dark")
		showBorder := c.GlobalBool("Show Border", true)

		bgColor := style.Hex("#111827")
		if theme == "Light" {
			bgColor = style.Hex("#f3f4f6")
		}

		border := style.SingleBorder().Color(style.Hex("#4f46e5"))
		wrapperStyle := style.S().Padding(2).Background(bgColor).
			When(showBorder, style.S().Border(border))

		return kitex.Box.Style(wrapperStyle, node)
	})

	// 3. Register components and scenes
	stg.Register("Button", []stage.Scene{
		{
			Name: "Default",
			Render: func(c *stage.Context) kitex.Node {
				text := c.Text("Label", "Click Me")
				disabled := c.Bool("Disabled", false)

				return kitex.Button(kitex.ButtonProps{
					Disabled: disabled,
					OnPress: func() {
						c.Log("Button clicked!")
					},
				}, kitex.Text(text))
			},
		},
	})

	stg.Register("Counter", []stage.Scene{
		{
			Name: "Basic",
			Render: func(c *stage.Context) kitex.Node {
				// Integer controls render as steppers (+ / -) in the panel
				count := c.Int("Limit", 10)

				return kitex.Box(
					kitex.BoxProps{},
					kitex.Textf("Limit: %d", count),
				)
			},
		},
	})

	stg.Run()
}

Then run it in your terminal:

go run cmd/stage/main.go

Hotkeys

  • Up / Down Arrow: Select and switch between different scenes in the sidebar.
  • Tab: Cycle focus to input fields inside the controls panel.
  • Ctrl+C: Quit Stage.
  • F12: Toggles the web-inspector devtools browser dashboard.

Documentation

Overview

Package stage provides an interactive, isolated component development stage and playground for kitex applications.

Index

Constants

This section is empty.

Variables

View Source
var PlayableArea = kitex.FC("PlayableArea", func(props PlayableAreaProps) kitex.Node {

	knobValues, setKnobValues := kitex.UseState(make(map[string]any))
	logs, setLogs := kitex.UseState([]ActionLog{})

	setKnobValue := func(name string, val any) {
		prev := knobValues()
		next := make(map[string]any)
		maps.Copy(next, prev)
		next[name] = val
		setKnobValues(next)
	}

	globalsMap := make(map[string]Control)
	for _, ctrl := range props.Globals {
		globalsMap[ctrl.Name] = ctrl
	}

	sceneContext := NewContext(knobValues(), setKnobValue, nil).
		WithGlobals(globalsMap, props.GlobalValues)

	sceneContext.onLogAdded = func() {
		setLogs(sceneContext.Logs())
	}
	renderedScene := props.Scene.Render(sceneContext)
	if renderedScene != nil && props.Decorator != nil {
		renderedScene = props.Decorator(sceneContext, renderedScene)
	}

	// 4. Render toolbar widgets (global controls)
	var toolbarWidgets []kitex.Node
	for _, ctrl := range props.Globals {
		var inputWidget kitex.Node
		switch ctrl.Type {
		case ControlTypeText:
			currentStr := ""
			if val, ok := props.GlobalValues[ctrl.Name]; ok {
				currentStr, _ = val.(string)
			} else if ctrl.Default != nil {
				currentStr, _ = ctrl.Default.(string)
			}
			capturedName := ctrl.Name
			inputWidget = kitex.Input(kitex.InputProps{
				Value: currentStr,
				Style: style.S().
					Width(style.Cells(15)).
					Background(color.RGBA{R: 31, G: 41, B: 55, A: 255}).
					Padding(0, 1),
				OnInput: func(ie *event.InputEvent) {
					props.SetGlobalVal(capturedName, ie.Value)
				},
			})
		case ControlTypeBool:
			currentBool := false
			if val, ok := props.GlobalValues[ctrl.Name]; ok {
				currentBool, _ = val.(bool)
			} else if ctrl.Default != nil {
				currentBool, _ = ctrl.Default.(bool)
			}
			capturedName := ctrl.Name
			checkboxLabel := "[ ]"
			if currentBool {
				checkboxLabel = "[x]"
			}
			inputWidget = kitex.Button(
				kitex.ButtonProps{
					Style: style.S().
						Border(false).
						Background(color.RGBA{R: 55, G: 65, B: 81, A: 255}).
						Padding(0, 1),
					OnClick: func(e *event.MouseEvent) {
						props.SetGlobalVal(capturedName, !currentBool)
					},
				},
				kitex.Text(checkboxLabel),
			)
		case ControlTypeSelect:
			currentStr := ""
			if val, ok := props.GlobalValues[ctrl.Name]; ok {
				currentStr, _ = val.(string)
			} else if ctrl.Default != nil {
				currentStr, _ = ctrl.Default.(string)
			}
			capturedName := ctrl.Name
			capturedOptions := ctrl.Options
			cycleOptionsText := fmt.Sprintf("%s ▾", currentStr)
			if currentStr == "" {
				cycleOptionsText = "select..."
			}
			inputWidget = kitex.Button(
				kitex.ButtonProps{
					Style: style.S().
						Border(false).
						Background(color.RGBA{R: 55, G: 65, B: 81, A: 255}).
						Padding(0, 1),
					OnClick: func(e *event.MouseEvent) {
						nextIdx := 0
						for optIdx, opt := range capturedOptions {
							if opt == currentStr {
								nextIdx = (optIdx + 1) % len(capturedOptions)
								break
							}
						}
						if len(capturedOptions) > 0 {
							props.SetGlobalVal(capturedName, capturedOptions[nextIdx])
						}
					},
				},
				kitex.Text(cycleOptionsText),
			)
		case ControlTypeInt:
			currentInt := 0
			if val, ok := props.GlobalValues[ctrl.Name]; ok {
				switch v := val.(type) {
				case int:
					currentInt = v
				case float64:
					currentInt = int(v)
				}
			} else if ctrl.Default != nil {
				switch v := ctrl.Default.(type) {
				case int:
					currentInt = v
				case float64:
					currentInt = int(v)
				}
			}
			capturedName := ctrl.Name
			stepperBtnStyle := style.S().
				Border(false).
				Background(color.RGBA{R: 55, G: 65, B: 81, A: 255}).
				Foreground(color.RGBA{R: 209, G: 213, B: 219, A: 255}).
				Padding(0, 1)
			inputWidget = kitex.Box.Style(
				style.S().
					Display(style.DisplayFlex).
					FlexDirection(style.FlexRow).
					AlignItems(style.AlignCenter).
					Width(style.Cells(12)),
				kitex.Button(
					kitex.ButtonProps{
						Style: stepperBtnStyle,
						OnClick: func(e *event.MouseEvent) {
							props.SetGlobalVal(capturedName, currentInt-1)
						},
					},
					kitex.Text("−"),
				),
				kitex.Box.Style(
					style.S().
						Flex(1).
						Background(color.RGBA{R: 31, G: 41, B: 55, A: 255}).
						Foreground(color.RGBA{R: 229, G: 231, B: 235, A: 255}).
						Padding(0, 1),
					kitex.Text(strconv.Itoa(currentInt)),
				),
				kitex.Button(
					kitex.ButtonProps{
						Style: stepperBtnStyle,
						OnClick: func(e *event.MouseEvent) {
							props.SetGlobalVal(capturedName, currentInt+1)
						},
					},
					kitex.Text("+"),
				),
			)
		}

		toolbarWidgets = append(toolbarWidgets, kitex.Box.Style(
			style.S().
				Display(style.DisplayFlex).
				FlexDirection(style.FlexRow).
				AlignItems(style.AlignCenter).
				MarginRight(2),
			kitex.Box.Style(
				style.S().
					Foreground(color.RGBA{R: 156, G: 163, B: 175, A: 255}).
					MarginRight(1),
				kitex.Text(ctrl.Name+":"),
			),
			inputWidget,
		))
	}

	// 5. Render controls panel rows
	var controlRows []kitex.Node
	ctrls := sceneContext.Controls()
	sort.Slice(ctrls, func(i, j int) bool {
		return ctrls[i].Name < ctrls[j].Name
	})

	for _, ctrl := range ctrls {
		var inputWidget kitex.Node
		switch ctrl.Type {
		case ControlTypeText:
			currentStr := ""
			if val, ok := knobValues()[ctrl.Name]; ok {
				currentStr, _ = val.(string)
			} else if ctrl.Default != nil {
				currentStr, _ = ctrl.Default.(string)
			}
			capturedName := ctrl.Name
			inputWidget = kitex.Input(kitex.InputProps{
				Value: currentStr,
				Style: style.S().
					Width(style.Percent(100)).
					Background(color.RGBA{R: 31, G: 41, B: 55, A: 255}).
					Padding(0, 1),
				OnInput: func(ie *event.InputEvent) {
					setKnobValue(capturedName, ie.Value)
				},
			})
		case ControlTypeBool:
			currentBool := false
			if val, ok := knobValues()[ctrl.Name]; ok {
				currentBool, _ = val.(bool)
			} else if ctrl.Default != nil {
				currentBool, _ = ctrl.Default.(bool)
			}
			capturedName := ctrl.Name
			checkboxLabel := "[ ]"
			if currentBool {
				checkboxLabel = "[x]"
			}
			inputWidget = kitex.Button(
				kitex.ButtonProps{
					Style: style.S().
						Border(false).
						Background(color.RGBA{R: 55, G: 65, B: 81, A: 255}).
						Padding(0, 0),
					OnClick: func(e *event.MouseEvent) {
						setKnobValue(capturedName, !currentBool)
					},
				},
				kitex.Text(checkboxLabel),
			)
		case ControlTypeSelect:
			currentStr := ""
			if val, ok := knobValues()[ctrl.Name]; ok {
				currentStr, _ = val.(string)
			} else if ctrl.Default != nil {
				currentStr, _ = ctrl.Default.(string)
			}
			capturedName := ctrl.Name
			capturedOptions := ctrl.Options
			cycleOptionsText := fmt.Sprintf("%s ▾", currentStr)
			if currentStr == "" {
				cycleOptionsText = "select..."
			}
			inputWidget = kitex.Button(
				kitex.ButtonProps{
					Style: style.S().
						Border(false).
						Background(color.RGBA{R: 55, G: 65, B: 81, A: 255}).
						Padding(0, 1),
					OnClick: func(e *event.MouseEvent) {
						nextIdx := 0
						for optIdx, opt := range capturedOptions {
							if opt == currentStr {
								nextIdx = (optIdx + 1) % len(capturedOptions)
								break
							}
						}
						if len(capturedOptions) > 0 {
							setKnobValue(capturedName, capturedOptions[nextIdx])
						}
					},
				},
				kitex.Text(cycleOptionsText),
			)
		case ControlTypeInt:
			currentInt := 0
			if val, ok := knobValues()[ctrl.Name]; ok {
				switch v := val.(type) {
				case int:
					currentInt = v
				case float64:
					currentInt = int(v)
				}
			} else if ctrl.Default != nil {
				switch v := ctrl.Default.(type) {
				case int:
					currentInt = v
				case float64:
					currentInt = int(v)
				}
			}
			capturedName := ctrl.Name
			stepperBtnStyle := style.S().
				Border(false).
				Background(color.RGBA{R: 55, G: 65, B: 81, A: 255}).
				Foreground(color.RGBA{R: 209, G: 213, B: 219, A: 255}).
				Padding(0, 1)
			inputWidget = kitex.Box.Style(
				style.S().
					Display(style.DisplayFlex).
					FlexDirection(style.FlexRow).
					AlignItems(style.AlignCenter).
					Width(style.Percent(100)),
				kitex.Button(
					kitex.ButtonProps{
						Style: stepperBtnStyle,
						OnClick: func(e *event.MouseEvent) {
							setKnobValue(capturedName, currentInt-1)
						},
					},
					kitex.Text("−"),
				),
				kitex.Box.Style(
					style.S().
						Flex(1).
						Background(color.RGBA{R: 31, G: 41, B: 55, A: 255}).
						Foreground(color.RGBA{R: 229, G: 231, B: 235, A: 255}).
						Padding(0, 1),
					kitex.Text(strconv.Itoa(currentInt)),
				),
				kitex.Button(
					kitex.ButtonProps{
						Style: stepperBtnStyle,
						OnClick: func(e *event.MouseEvent) {
							setKnobValue(capturedName, currentInt+1)
						},
					},
					kitex.Text("+"),
				),
			)
		}

		controlRows = append(controlRows, kitex.Box.Style(
			style.S().
				Display(style.DisplayFlex).
				FlexDirection(style.FlexRow).
				Width(style.Percent(100)).
				AlignItems(style.AlignCenter).
				MarginBottom(1),
			kitex.Box.Style(
				style.S().
					Width(style.Percent(40)).
					MinWidth(style.Cells(0)).
					Foreground(color.RGBA{R: 156, G: 163, B: 175, A: 255}),
				kitex.Text(ctrl.Name),
			),
			kitex.Box.Style(
				style.S().
					Display(style.DisplayFlex).
					Width(style.Percent(60)).
					MinWidth(style.Cells(0)),
				inputWidget,
			),
		))
	}

	// 6. Render action logs rows
	var logRows []kitex.Node
	for _, l := range logs() {
		logRows = append(logRows, kitex.Box.Style(
			style.S().Display(style.DisplayFlex).FlexDirection(style.FlexRow).Width(style.Percent(100)),
			kitex.Box.Style(
				style.S().
					Width(style.Cells(10)).
					Foreground(color.RGBA{R: 107, G: 114, B: 128, A: 255}),
				kitex.Text(l.Timestamp),
			),
			kitex.Box.Style(
				style.S().Foreground(color.RGBA{R: 209, G: 213, B: 219, A: 255}),
				kitex.Text(l.Message),
			),
		))
	}

	return kitex.Box.Style(
		playableAreaStyle,

		func() kitex.Node {
			if len(props.Globals) > 0 {
				return kitex.Box.Style(
					toolbarStyle,
					toolbarWidgets...,
				)
			}
			return nil
		}(),

		kitex.Box.Style(
			canvasStyle,
			kitex.Box.Style(
				canvasInnerStyle,
				func() kitex.Node {
					if renderedScene != nil {
						return renderedScene
					}
					return kitex.Text("Select a scene to start")
				}(),
			),
		),

		kitex.Box.Style(
			detailPanelStyle,

			kitex.Box.Style(
				controlsPanelStyle,
				kitex.Box.Style(
					style.S().
						MarginBottom(1).
						BorderBottom(true, style.BorderSingle, color.RGBA{R: 75, G: 85, B: 99, A: 255}),
					kitex.Text("🛠️ CONTROLS"),
				),
				kitex.Box.Style(
					style.S().Flex(1).Overflow(style.OverflowAuto),
					controlRows...,
				),
			),

			kitex.Box.Style(
				logsPanelStyle,
				kitex.Box.Style(
					style.S().
						Display(style.DisplayFlex).
						FlexDirection(style.FlexRow).
						JustifyContent(style.JustifyBetween).
						MarginBottom(1).
						BorderBottom(true, style.BorderSingle, color.RGBA{R: 75, G: 85, B: 99, A: 255}),
					kitex.Text("📋 ACTION LOG"),
					kitex.Button(
						kitex.ButtonProps{
							Style: style.S().
								Border(false).
								Background(color.RGBA{R: 79, G: 70, B: 229, A: 255}).
								Padding(0, 1),
							OnClick: func(e *event.MouseEvent) {
								setLogs([]ActionLog{})
								if sceneContext != nil {
									sceneContext.ClearLogs()
								}
							},
						},
						kitex.Text("Clear"),
					),
				),
				kitex.Box.Style(
					style.S().Flex(1).Overflow(style.OverflowAuto),
					logRows...,
				),
			),
		),
	)
})

PlayableArea manages the active scene hooks, rendering, knobs context, and details panels. Because it is keyed by the active scene index, all hooks and knob values are cleanly destroyed and recreated when the active scene changes.

View Source
var StageApp = kitex.FC("StageApp", func(props StageAppProps) kitex.Node {
	// 1. Trie structure to support nested sections
	type trieNode struct {
		Name     string
		FullPath string
		Children map[string]*trieNode
		Scenes   []Scene
		CompName string
	}

	normalizeComponentPath := func(compName string) []string {
		if compName == "" {
			return []string{"Default", "Default"}
		}
		parts := strings.Split(compName, "/")
		if len(parts) == 1 {
			return []string{"Default", parts[0]}
		} else if len(parts) == 2 {
			return []string{"Default", parts[0], parts[1]}
		}
		return parts
	}

	buildTrie := func(components map[string][]Scene) *trieNode {
		root := &trieNode{
			Children: make(map[string]*trieNode),
		}
		for compName, scenes := range components {
			parts := normalizeComponentPath(compName)
			curr := root
			var pathBuilder []string
			for _, part := range parts {
				pathBuilder = append(pathBuilder, part)
				fullPath := strings.Join(pathBuilder, "/")
				if curr.Children == nil {
					curr.Children = make(map[string]*trieNode)
				}
				child, ok := curr.Children[part]
				if !ok {
					child = &trieNode{
						Name:     part,
						FullPath: fullPath,
						Children: make(map[string]*trieNode),
					}
					curr.Children[part] = child
				}
				curr = child
			}
			curr.Scenes = scenes
			curr.CompName = compName
		}
		return root
	}

	rootTrieNode := buildTrie(props.Stage.components)

	type sceneRef struct {
		compName  string
		sceneName string
		index     int
	}

	var allScenes []sceneRef
	var traverseTree func(*trieNode)
	traverseTree = func(node *trieNode) {
		var childKeys []string
		for k := range node.Children {
			childKeys = append(childKeys, k)
		}
		sort.Strings(childKeys)
		for _, k := range childKeys {
			traverseTree(node.Children[k])
		}

		for i, sc := range node.Scenes {
			allScenes = append(allScenes, sceneRef{
				compName:  node.CompName,
				sceneName: sc.Name,
				index:     i,
			})
		}
	}
	traverseTree(rootTrieNode)

	activeSceneIdx, setActiveSceneIdx := kitex.UseState(0)
	expandedComps, setExpandedComps := kitex.UseState(make(map[string]bool))
	globalValues, setGlobalValues := kitex.UseState(make(map[string]any))
	filterText, setFilterText := kitex.UseState("")
	rootRef := kitex.UseRef[dom.Node](nil)
	filterInputRef := kitex.UseRef[*element.InputElement](nil)

	// Trie filter matching helpers
	var nodeMatches func(*trieNode, string) bool
	nodeMatches = func(node *trieNode, query string) bool {
		if query == "" {
			return true
		}
		query = strings.ToLower(query)
		if strings.Contains(strings.ToLower(node.Name), query) {
			return true
		}
		for _, sc := range node.Scenes {
			if strings.Contains(strings.ToLower(sc.Name), query) {
				return true
			}
		}
		for _, child := range node.Children {
			if nodeMatches(child, query) {
				return true
			}
		}
		return false
	}

	type filteredSceneRef struct {
		sc    Scene
		index int
	}

	getFilteredScenes := func(node *trieNode, query string) []filteredSceneRef {
		var res []filteredSceneRef
		queryLower := strings.ToLower(query)
		compMatch := query == "" || strings.Contains(strings.ToLower(node.Name), queryLower)
		for i, sc := range node.Scenes {
			if compMatch || strings.Contains(strings.ToLower(sc.Name), queryLower) {
				res = append(res, filteredSceneRef{sc: sc, index: i})
			}
		}
		return res
	}

	isExpanded := func(path string, node *trieNode) bool {
		query := filterText()
		if query != "" {
			return nodeMatches(node, query)
		}

		m := expandedComps()
		if val, ok := m[path]; ok {
			return val
		}

		if len(allScenes) > 0 {
			parts := normalizeComponentPath(allScenes[0].compName)
			firstCompNormalized := strings.Join(parts, "/")
			return path == firstCompNormalized || strings.HasPrefix(firstCompNormalized, path+"/")
		}
		return false
	}

	toggleComp := func(path string, node *trieNode) {
		m := expandedComps()
		next := make(map[string]bool)
		maps.Copy(next, m)
		next[path] = !isExpanded(path, node)
		setExpandedComps(next)
	}

	expandComponent := func(compName string) {
		parts := normalizeComponentPath(compName)
		m := expandedComps()
		next := make(map[string]bool)
		maps.Copy(next, m)
		var pathBuilder []string
		for _, part := range parts {
			pathBuilder = append(pathBuilder, part)
			next[strings.Join(pathBuilder, "/")] = true
		}
		setExpandedComps(next)
	}

	setGlobalVal := func(name string, val any) {
		prev := globalValues()
		next := make(map[string]any)
		maps.Copy(next, prev)
		next[name] = val
		setGlobalValues(next)
	}

	// Active scene reference
	var activeScene *Scene
	if len(allScenes) > 0 && activeSceneIdx() >= 0 && activeSceneIdx() < len(allScenes) {
		ref := allScenes[activeSceneIdx()]
		activeScene = &props.Stage.components[ref.compName][ref.index]
	}

	// Render sidebar list items as a nested collapsible tree
	var visibleIndices []int
	var sidebarItems []kitex.Node

	sceneKeyToIndex := make(map[string]int)
	for i, ref := range allScenes {
		key := fmt.Sprintf("%s:%d", ref.compName, ref.index)
		sceneKeyToIndex[key] = i
	}

	var renderNode func(*trieNode, int)
	renderNode = func(node *trieNode, depth int) {
		if node.FullPath == "" {
			var childKeys []string
			for k, child := range node.Children {
				if nodeMatches(child, filterText()) {
					childKeys = append(childKeys, k)
				}
			}
			sort.Strings(childKeys)
			for i, k := range childKeys {
				if i > 0 {

					sidebarItems = append(sidebarItems, kitex.Box.Style(
						style.S().Height(style.Cells(1)),
					))
				}
				renderNode(node.Children[k], 0)
			}
			return
		}

		expanded := isExpanded(node.FullPath, node)
		var icon string
		hasChildren := len(node.Children) > 0
		hasScenes := len(node.Scenes) > 0

		if depth == 0 {
			if hasChildren {
				if expanded {
					icon = "◇ "
				} else {
					icon = "◆ "
				}
			} else {
				if expanded {
					icon = "✧ "
				} else {
					icon = "✦ "
				}
			}
		} else {
			if hasChildren {
				if expanded {
					icon = "▼ "
				} else {
					icon = "▶ "
				}
			} else if hasScenes {
				if expanded {
					icon = "⬡ "
				} else {
					icon = "⬢ "
				}
			}
		}

		headerStyle := style.S().
			Padding(0, 1+depth*2).
			Width(style.Percent(100)).
			Bold(true)

		if hasChildren {
			headerStyle = headerStyle.Foreground(color.RGBA{R: 209, G: 213, B: 219, A: 255})
		} else {
			headerStyle = headerStyle.Foreground(color.RGBA{R: 229, G: 231, B: 235, A: 255})
		}

		capturedPath := node.FullPath
		capturedNode := node
		sidebarItems = append(sidebarItems, kitex.Box(kitex.BoxProps{
			Style: headerStyle,
			OnClick: func(e *event.MouseEvent) {
				toggleComp(capturedPath, capturedNode)
			},
		}, kitex.Text(icon+node.Name)))

		if expanded {
			var childKeys []string
			for k, child := range node.Children {
				if nodeMatches(child, filterText()) {
					childKeys = append(childKeys, k)
				}
			}
			sort.Strings(childKeys)
			for _, k := range childKeys {
				renderNode(node.Children[k], depth+1)
			}

			for _, fsc := range getFilteredScenes(node, filterText()) {
				key := fmt.Sprintf("%s:%d", node.CompName, fsc.index)
				globalIdx, found := sceneKeyToIndex[key]
				if !found {
					continue
				}
				visibleIndices = append(visibleIndices, globalIdx)

				isSelected := globalIdx == activeSceneIdx()
				itemStyle := style.S().
					Padding(0, 1+(depth+1)*2+1).
					Width(style.Percent(100))
				if isSelected {
					itemStyle = itemStyle.
						Background(color.RGBA{R: 79, G: 70, B: 229, A: 255}).
						Foreground(color.RGBA{R: 255, G: 255, B: 255, A: 255})
				} else {
					itemStyle = itemStyle.
						Foreground(color.RGBA{R: 156, G: 163, B: 175, A: 255})
				}

				capturedIdx := globalIdx
				sidebarItems = append(sidebarItems, kitex.Box(kitex.BoxProps{
					Style: itemStyle,
					OnClick: func(e *event.MouseEvent) {
						setActiveSceneIdx(capturedIdx)
					},
				}, kitex.Text("▪ "+fsc.sc.Name)))
			}
		}
	}
	renderNode(rootTrieNode, 0)

	kitex.UseEffectCleanup(func() func() {
		if rootRef.Current == nil {
			return nil
		}
		doc := rootRef.Current.OwnerDocument()
		if doc == nil {
			return nil
		}

		listener := func(e event.Event) {
			ke := e.(*event.KeyEvent)
			isInputFocused := false
			if target := e.Target(); target != nil {
				if el, ok := target.(dom.Element); ok && el.TagName() == "input" {
					isInputFocused = true
				}
			}

			if ke.MatchString("/") {
				if !isInputFocused && filterInputRef.Current != nil {
					filterInputRef.Current.Focus()
					e.PreventDefault()
					return
				}
			}

			if ke.MatchString("escape") || ke.MatchString("esc") {
				if isInputFocused && filterInputRef.Current != nil {
					filterInputRef.Current.Blur()
					if rootRef.Current != nil {
						if el, ok := rootRef.Current.(dom.Element); ok {
							el.SetTabIndex(0)
							el.Focus()
						}
					}
					e.PreventDefault()
					return
				}
			}

			// Determine navigable list
			var navList []int
			if filterText() == "" {

				navList = make([]int, len(allScenes))
				for i := range allScenes {
					navList[i] = i
				}
			} else {

				navList = visibleIndices
			}

			current := activeSceneIdx()
			pos := -1
			for i, idx := range navList {
				if idx == current {
					pos = i
					break
				}
			}

			isUp := ke.MatchString("up") || (!isInputFocused && ke.MatchString("k"))
			isDown := ke.MatchString("down") || (!isInputFocused && ke.MatchString("j"))

			if isUp {
				if pos > 0 {
					targetIdx := navList[pos-1]
					setActiveSceneIdx(targetIdx)
					if filterText() == "" && targetIdx >= 0 && targetIdx < len(allScenes) {
						expandComponent(allScenes[targetIdx].compName)
					}
				}
				e.PreventDefault()
			} else if isDown {
				if pos >= 0 && pos < len(navList)-1 {
					targetIdx := navList[pos+1]
					setActiveSceneIdx(targetIdx)
					if filterText() == "" && targetIdx >= 0 && targetIdx < len(allScenes) {
						expandComponent(allScenes[targetIdx].compName)
					}
				} else if pos == -1 && len(navList) > 0 {
					targetIdx := navList[0]
					setActiveSceneIdx(targetIdx)
					if filterText() == "" && targetIdx >= 0 && targetIdx < len(allScenes) {
						expandComponent(allScenes[targetIdx].compName)
					}
				}
				e.PreventDefault()
			}
		}

		sub := doc.AddEventListener(event.EventKeyDown, listener)
		return func() {
			sub.Cancel()
		}
	}, len(allScenes), activeSceneIdx(), len(visibleIndices), filterText())

	return kitex.Box(kitex.BoxProps{
		Ref: rootRef,
		Style: style.S().
			Display(style.DisplayFlex).
			FlexDirection(style.FlexRow).
			Width(style.Percent(100)).
			Height(style.Percent(100)).
			Background(color.RGBA{R: 31, G: 41, B: 55, A: 255}),
	},

		kitex.Box.Style(
			sidebarStyle,
			kitex.Box.Style(
				style.S().
					MarginBottom(1).
					BorderBottom(true, style.BorderSingle, color.RGBA{R: 75, G: 85, B: 99, A: 255}),
				kitex.Text("📖 SCENES"),
			),
			kitex.Input(kitex.InputProps{
				Ref:         filterInputRef,
				Value:       filterText(),
				Placeholder: "Filter (press /)...",
				Style: style.S().
					Width(style.Percent(100)).
					MarginBottom(1).
					Background(color.RGBA{R: 31, G: 41, B: 55, A: 255}).
					Foreground(color.RGBA{R: 243, G: 244, B: 246, A: 255}).
					Padding(0, 1),
				OnValueChange: func(val string) {
					setFilterText(val)
				},
				OnKeyDown: func(ke *event.KeyEvent) {
					if ke.MatchString("escape") || ke.MatchString("enter") {
						if filterInputRef.Current != nil {
							filterInputRef.Current.Blur()
						}
						ke.PreventDefault()
					}
				},
			}),
			kitex.Box.Style(
				style.S().Flex(1).Overflow(style.OverflowAuto),
				sidebarItems...,
			),
		),

		func() kitex.Node {
			if activeScene != nil {
				key := fmt.Sprintf("scene-%d", activeSceneIdx())
				return PlayableArea.Props(PlayableAreaProps{
					Key:          key,
					Scene:        activeScene,
					Decorator:    props.Stage.decorator,
					Globals:      props.Stage.globals,
					GlobalValues: globalValues(),
					SetGlobalVal: setGlobalVal,
				})
			}
			return kitex.Box.Style(
				playableAreaStyle.Background(color.RGBA{R: 31, G: 41, B: 55, A: 255}),
				kitex.Text("Select a scene to start"),
			)
		}(),
	)
})

StageApp renders the interactive playground user interface.

Functions

func Register

func Register[P any](reg *Registry, config ComponentConfig[P])

Register registers a component in the registry using reflection-based control generation.

Types

type ActionLog

type ActionLog struct {
	Timestamp string `json:"timestamp"`
	Message   string `json:"message"`
}

ActionLog holds a single logged event from a running scene.

type ComponentConfig

type ComponentConfig[P any] struct {
	Name         string
	DefaultProps P
	Render       func(c *Context, props P) kitex.Node
	Controls     map[string]ControlOverride
	Scenes       []SceneConfig[P]
	Description  string
}

ComponentConfig specifies the configuration for a reflection-based component registration.

type Context

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

Context is passed to each Scene's Render function to register/query knobs and log actions.

func NewContext

func NewContext(values map[string]any, setVal func(name string, val any), onLogAdded func()) *Context

NewContext creates a new Context for scene execution.

func (*Context) Bool

func (c *Context) Bool(name string, defaultValue bool) bool

Bool registers/returns a boolean checkbox knob.

func (*Context) ClearLogs

func (c *Context) ClearLogs()

ClearLogs clears all logged actions.

func (*Context) Controls

func (c *Context) Controls() []Control

Controls returns all currently registered controls.

func (*Context) Global

func (c *Context) Global(name string) any

Global returns the current value of a global control by name.

func (*Context) GlobalBool

func (c *Context) GlobalBool(name string, defaultValue bool) bool

GlobalBool returns the value of a global control as a boolean.

func (*Context) GlobalInt

func (c *Context) GlobalInt(name string, defaultValue int) int

GlobalInt returns the value of a global control as an integer.

func (*Context) GlobalString

func (c *Context) GlobalString(name string, defaultValue string) string

GlobalString returns the value of a global control as a string.

func (*Context) Int

func (c *Context) Int(name string, defaultValue int) int

Int registers/returns an integer spinner knob.

func (*Context) Log

func (c *Context) Log(msg string)

Log adds an action log entry.

func (*Context) Logs

func (c *Context) Logs() []ActionLog

Logs returns a safe copy of all action logs.

func (*Context) Select

func (c *Context) Select(name string, options []string, defaultValue string) string

Select registers/returns a dropdown-like select input knob.

func (*Context) Text

func (c *Context) Text(name string, defaultValue string) string

Text registers/returns a text input knob.

func (*Context) WithGlobals

func (c *Context) WithGlobals(globals map[string]Control, globalValues map[string]any) *Context

WithGlobals assigns global controls and their current values to the Context.

type Control

type Control struct {
	Name    string      `json:"name"`
	Type    ControlType `json:"type"`
	Default any         `json:"default"`
	Options []string    `json:"options,omitempty"` // populated only for ControlTypeSelect
}

Control contains the metadata for a single scene knob.

type ControlOverride

type ControlOverride struct {
	Label       string
	Min, Max    int
	Step        int
	Options     []string
	Description string
	Hidden      bool
}

ControlOverride allows customizing or overriding the auto-generated TUI controls.

type ControlType

type ControlType string

ControlType represents the type of interactive knob/input control.

const (
	ControlTypeText   ControlType = "text"
	ControlTypeBool   ControlType = "bool"
	ControlTypeSelect ControlType = "select"
	ControlTypeInt    ControlType = "int"
)

type EmptyProps

type EmptyProps struct{}

EmptyProps is a default props type with no fields. Use it when registering components that do not have any controls/knobs.

type PlayableAreaProps

type PlayableAreaProps struct {
	Key          string
	Scene        *Scene
	Decorator    func(*Context, kitex.Node) kitex.Node
	Globals      []Control
	GlobalValues map[string]any
	SetGlobalVal func(string, any)
}

PlayableAreaProps is the properties for the PlayableArea component.

type Registry

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

Registry stores registered components and their scenes.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new component registry.

func (*Registry) RegisterRaw

func (r *Registry) RegisterRaw(component string, scenes []Scene)

RegisterRaw registers a list of raw scenes directly.

type Scene

type Scene struct {
	Name   string
	Render func(c *Context) kitex.Node
}

Scene represents a single rendering scenario of a component.

type SceneConfig

type SceneConfig[P any] struct {
	Name  string
	Props P
}

SceneConfig defines a scene variation with custom override props.

type Stage

type Stage struct {
	*Registry
	// contains filtered or unexported fields
}

Stage manages components and their scenes for isolation testing.

func New

func New() *Stage

New creates a new Stage manager.

func (*Stage) GlobalBool

func (s *Stage) GlobalBool(name string, defaultValue bool) *Stage

GlobalBool registers a global boolean control.

func (*Stage) GlobalInt

func (s *Stage) GlobalInt(name string, defaultValue int) *Stage

GlobalInt registers a global integer control.

func (*Stage) GlobalSelect

func (s *Stage) GlobalSelect(name string, options []string, defaultValue string) *Stage

GlobalSelect registers a global dropdown select control.

func (*Stage) GlobalText

func (s *Stage) GlobalText(name string, defaultValue string) *Stage

GlobalText registers a global text control.

func (*Stage) Merge

func (s *Stage) Merge(prefix string, reg *Registry)

Merge merges components from another sub-registry into this stage, prepending the given prefix (if any) to the component paths.

func (*Stage) Register

func (s *Stage) Register(component string, scenes []Scene)

Register registers a list of scenes for a component.

func (*Stage) Root

func (s *Stage) Root() kitex.Node

func (*Stage) Run

func (s *Stage) Run()

Run launches the Stage TUI explorer.

func (*Stage) WithContextDecorator

func (s *Stage) WithContextDecorator(fn func(*Context, kitex.Node) kitex.Node) *Stage

WithContextDecorator sets a context-aware wrapper function that is applied around every rendered scene node, exposing global controls to the decorator.

func (*Stage) WithDecorator

func (s *Stage) WithDecorator(fn func(kitex.Node) kitex.Node) *Stage

WithDecorator sets a wrapper function that is applied around every rendered scene node. Use it to inject global providers — theme contexts, store providers, or any kitex.Node wrapper — without modifying individual scenes.

Example:

stg := stage.New()
stg.WithDecorator(func(n kitex.Node) kitex.Node {
	return ThemeCtx.Provider(myTheme, n)
})

type StageAppProps

type StageAppProps struct {
	Stage *Stage
}

StageAppProps is the properties for the master StageApp component.

Jump to

Keyboard shortcuts

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