GoloScript UI Module
Terminal User Interface Helpers for GoloScript
The gololang.Ui module provides a comprehensive set of functions for creating rich, colorful, and interactive terminal user interfaces in GoloScript. From simple colored text to spinners, markdown rendering, and interactive prompts, this module makes it easy to build engaging CLI applications.
Installation
The UI module is part of the GoloScript standard library. Simply import it in your script:
module MyApp
import gololang.Ui
Quick Start
module QuickDemo
import gololang.Ui
function main = |args| {
# Simple colored output
colorPrintln("Hello, World!", "green")
# Semantic messages
success("Operation completed!")
error("Something went wrong!")
warning("Be careful!")
info("Just so you know...")
# Interactive prompt
let name = prompt("What's your name?", "User")
colorPrintln("Hello, " + name + "!", "cyan")
# Spinner animation
spinnerNew("loader", "Processing", "please wait...")
spinnerStart("loader")
sleep(2000)
spinnerSuccess("loader", "Done!")
}
Color and Style Functions
Basic Color Printing
colorPrint(text, color)
Print colored text without a newline.
colorPrint("Loading", "yellow")
colorPrint("...", "red")
colorPrintln(text, color)
Print colored text with a newline.
colorPrintln("Success!", "green")
Available Colors
Standard colors:
black,red,green,yellow,blue,magenta,cyan,white
Bright colors:
brightRed,brightGreen,brightYellow,brightBlue,brightMagenta,brightCyan,brightWhite
Background colors:
bgBlack,bgRed,bgGreen,bgYellow,bgBlue,bgMagenta,bgCyan,bgWhitebgBrightRed,bgBrightGreen, etc.
Styles:
bold,dim,italic,underline
Multi-Style Printing
printStyled(text, styles)
Apply multiple styles to text.
printStyled("Important!", ["bold", "red", "bgWhite"])
printStyled("Highlighted", ["underline", "brightYellow"])
Semantic Messages
These functions provide consistent, recognizable message formats:
success(message)
Green message with checkmark (✓)
success("File saved successfully")
error(message)
Red message with cross (✗)
error("Failed to connect to server")
warning(message)
Yellow message with warning symbol (⚠)
warning("Disk space running low")
info(message)
Cyan message with info symbol (ℹ)
info("Server started on port 8080")
Text Formatting
These functions return ANSI-formatted strings that can be combined:
Color Functions
println(red("Error: ") + "Could not find file")
println(green("✓ ") + "Test passed")
println(yellow("WARNING: ") + "Deprecated function")
Available color functions: red(), green(), yellow(), blue(), magenta(), cyan(), white(), brightRed(), brightGreen(), brightYellow(), brightBlue()
Style Functions
bold(text)
println(bold("Important Notice"))
italic(text)
println(italic("Emphasis added"))
underline(text)
println(underline("Click here"))
colorize(text, style)
Generic colorization function.
println(colorize("Custom", "magenta"))
Layout Helpers
Lines and Separators
line(length, color)
Print a horizontal line.
line(50, "cyan") # Colored line
line(40, null) # Plain line
separator()
Print a dim separator line (80 characters).
separator()
Headers
header(text, width, color)
Print centered header text.
header("My Application", 80, "blue")
header("Section Title", null, "green") # Width defaults to 80
header("Bold Only", null, null) # Bold style only
Blank Lines
blank(count)
Print blank lines.
blank(1) # One blank line
blank(3) # Three blank lines
blank(null) # One blank line (default)
Markdown Rendering
Static Markdown
markdown(text)
Render complete markdown (with syntax highlighting).
let md = """
# Title
This is **bold** and this is *italic*.
- List item 1
- List item 2
"""
markdown(md)
Streaming Markdown
Perfect for rendering AI responses or progressive content:
markdownStreamStart(parserId)
Initialize a markdown stream.
markdownStreamAppend(parserId, chunk)
Append content chunk to the stream.
markdownStreamEnd(parserId)
Finalize and render the stream.
markdownStreamStart("ai-response")
# Simulate streaming chunks
markdownStreamAppend("ai-response", "# AI Response\n\n")
markdownStreamAppend("ai-response", "This is ")
markdownStreamAppend("ai-response", "**streaming** ")
markdownStreamAppend("ai-response", "markdown!\n")
markdownStreamEnd("ai-response")
User Input
Text Input
prompt(message, defaultValue?)
Prompt for user input with optional default.
let name = prompt("Enter your name:", "Anonymous")
let email = prompt("Email address:", null)
promptPassword(message)
Prompt for password (masked input).
let password = promptPassword("Enter password:")
promptMultiline(message, initialContent?)
Prompt for multi-line text input.
let description = promptMultiline("Enter description:", null)
let template = promptMultiline("Edit template:", "Default content\nLine 2")
Confirmation
confirm(message)
Ask for yes/no confirmation.
if confirm("Delete all files?") {
println("Deleting...")
} else {
println("Cancelled")
}
Spinners
Spinners provide visual feedback for long-running operations.
Basic Usage
# Create spinner
spinnerNew("task1", "Loading data", "please wait...")
# Start animation
spinnerStart("task1")
# Do work...
sleep(2000)
# Stop with success
spinnerSuccess("task1", "Data loaded!")
Spinner Functions
spinnerNew(id, prefix, suffix?)
Create a new spinner with unique ID.
spinnerNew("download", "Downloading", "0%")
spinnerNew("simple", "Processing", null)
spinnerStart(id)
Start the spinner animation.
spinnerStart("download")
spinnerStop(id, message?)
Stop the spinner with optional message.
spinnerStop("download", "Download complete")
spinnerStop("download", null) # Stop without message
spinnerSuccess(id, message)
Stop with success indicator (✓).
spinnerSuccess("download", "100% complete!")
spinnerError(id, message)
Stop with error indicator (✗).
spinnerError("download", "Download failed")
Dynamic Updates
spinnerSetPrefix(id, prefix)
Update spinner prefix while running.
spinnerSetPrefix("download", "Downloading file.zip")
spinnerSetSuffix(id, suffix)
Update spinner suffix while running.
spinnerSetSuffix("download", "45%")
spinnerSetFrames(id, frameType)
Change the animation style.
spinnerSetFrames("loader", "dots")
spinnerSetFrames("loader", "braille")
Available frame types:
braille- Smooth braille dots (default)dots- Simple dotsascii- ASCII-safe charactersprogressive- Progressive blocksarrows- Rotating arrowscircle- Circle animationpulsingStar- Pulsing starsimpleDots- Minimal dotsbouncingBar- Bouncing barbouncingBall- Bouncing ball
Advanced Spinner Example
function downloadFile = |url| {
spinnerNew("dl", "Initializing", "0%")
spinnerStart("dl")
# Simulate download progress
var progress = 0
while progress < 100 {
sleep(100)
progress = progress + 10
spinnerSetSuffix("dl", progress + "%")
if progress == 50 {
spinnerSetPrefix("dl", "Downloading large file")
}
}
spinnerSuccess("dl", "Download complete!")
}
Complete API Reference
Color and Style
colorPrint(text, color)- Print colored textcolorPrintln(text, color)- Print colored text with newlineprintStyled(text, styles)- Print with multiple stylescolorize(text, color)- Return ANSI-formatted stringgetColorCode(color)- Get raw ANSI code
Semantic Messages
success(message)- Success messageerror(message)- Error messagewarning(message)- Warning messageinfo(message)- Info message
Text Formatting
bold(text)- Bold textitalic(text)- Italic textunderline(text)- Underlined textred(text),green(text),yellow(text),blue(text), etc.
Layout
line(length, color)- Horizontal lineseparator()- Standard separatorheader(text, width, color)- Centered headerblank(count)- Blank lines
Markdown
markdown(text)- Render markdownmarkdownStreamStart(parserId)- Start streammarkdownStreamAppend(parserId, chunk)- Append to streammarkdownStreamEnd(parserId)- End stream
User Input
prompt(message, defaultValue?)- Text inputpromptPassword(message)- Password inputpromptMultiline(message, initialContent?)- Multi-line inputconfirm(message)- Yes/no confirmation
Spinners
spinnerNew(id, prefix, suffix?)- Create spinnerspinnerStart(id)- Start animationspinnerStop(id, message?)- Stop spinnerspinnerSuccess(id, message)- Stop with successspinnerError(id, message)- Stop with errorspinnerSetPrefix(id, prefix)- Update prefixspinnerSetSuffix(id, suffix)- Update suffixspinnerSetFrames(id, frameType)- Change animation
Examples
Complete CLI Application
module TodoApp
import gololang.Ui
function main = |args| {
# Header
blank(1)
header("📝 Todo Manager", 60, "cyan")
separator()
blank(1)
# Welcome message
info("Welcome to Todo Manager!")
blank(1)
# Get user input
let taskName = prompt("Enter task name:", null)
let priority = prompt("Priority (low/medium/high):", "medium")
# Confirm
if confirm("Add this task?") {
# Show progress
spinnerNew("add", "Adding task", null)
spinnerStart("add")
sleep(1000)
spinnerSuccess("add", "Task added successfully!")
# Summary
blank(1)
success("Task created:")
println(" Name: " + bold(taskName))
println(" Priority: " + yellow(priority))
} else {
warning("Task cancelled")
}
blank(1)
separator()
}
Markdown Report Generator
module ReportGen
import gololang.Ui
function generateReport = {
let report = """
# System Report
## Status
All systems **operational** ✓
## Metrics
- CPU Usage: *45%*
- Memory: *2.1 GB / 8 GB*
- Disk: *120 GB free*
## Alerts
No critical alerts at this time.
#### uptime: 15 days, 4 hours
"""
header("System Report", 80, "blue")
blank(1)
markdown(report)
}