syralit

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 31 Imported by: 0

README

Syralit

Interactive data apps in Go.

CI Go Reference Go Report Card Go Version

Syralit is a Go-native framework for building interactive data apps, dashboards, and AI tool interfaces — inspired by Streamlit, designed for Go.

Write Go functions, get a live web app. No JavaScript, no HTML templates, no frontend build step.

package main

import sy "github.com/HazelnutParadise/syralit"

func main() {
    sy.App(func() {
        sy.Title("Hello Syralit")
        name := sy.TextInput("Your name")
        if name != "" {
            sy.Success("Hello, " + name + "!")
        }
    })
}

Installation

go install github.com/HazelnutParadise/syralit/cmd/syralit@latest

Quick Start

syralit new myapp    # scaffold a new project
cd myapp
syralit dev          # hot reload with state preservation

Or manually:

package main

import sy "github.com/HazelnutParadise/syralit"

func main() {
    sy.App(func() {
        sy.Title("My App")
        if sy.Button("Click me") {
            sy.Balloons()
        }
    })
}
go run .
# Open http://localhost:8600

Features

Input Widgets
Widget Returns Description
Button bool Clickable button (true for one rerun)
TextInput string Single-line text
PasswordInput string Masked text input
TextArea string Multi-line text
NumberInput float64 Number with min/max/step
Slider float64 Range slider
RangeSlider (float64, float64) Two-handle slider returning a (low, high) range
DateSlider string Slider over a date range, returns "YYYY-MM-DD"
SelectSlider string Discrete slider with labels
Checkbox bool Checkbox
Toggle bool Toggle switch
Radio string Radio button group
SelectBox string Dropdown (auto-searchable at 20+ items)
MultiSelect []string Multi-select dropdown
DateInput string Date picker (YYYY-MM-DD)
DateRangeInput (string, string) Start/end date pickers
TimeInput string Time picker (HH:MM)
ColorPicker string Color hex picker
FileUploader *UploadedFile File upload
CameraInput string Webcam capture
AudioInput string Microphone recording
ChatInput string Chat message input
Feedback string Thumbs up/down
SegmentedControl string Segmented buttons
Pills string Pill-style buttons
Pagination int Page selector

Plus: DownloadButton, LinkButton, PageLink, Badge.

Display

Title, Header, Subheader, Text, Textf, Markdown, Caption, Code (syntax highlighting via highlight.js), LaTeX (KaTeX), JSON (interactive tree), HTML, Image, ImageFromBytes, Audio, Video, Link, Metric (with delta indicators), Progress, Spinner, WriteStream (token-by-token streaming), Component (custom HTML/JS), IFrame, Exception (styled Go error box).

Data
Widget Description
Table Static string table
DataFrame Sortable table; optional row selection (sy.Selectable() → returns selected indices) and typed display via sy.ColConfig
DataEditor Editable table with 11 column types

DataEditor supports column configuration with types: text, number, checkbox, select, date, time, datetime, link, image, progress, list. Dynamic row add/delete with sy.DynamicRows().

sy.DataEditor(headers, rows,
    sy.ColConfig(map[string]sy.ColumnConfig{
        "Score": {Type: "number", Min: 0, Max: 100},
        "Pass":  {Type: "checkbox"},
        "Grade": {Type: "select", Options: []string{"A", "B", "C"}},
    }),
    sy.DynamicRows(),
)
Charts

Built-in interactive charts powered by Chart.js:

Chart Input Description
LineChart map[string][]float64 Line chart with multiple series
BarChart map[string][]float64 Bar chart
AreaChart map[string][]float64 Filled line chart
ScatterChart map[string][][2]float64 Scatter plot with xy pairs
PieChart map[string]float64 Pie chart
DoughnutChart map[string]float64 Doughnut chart
HistogramChart []float64, bins Histogram from raw data
RadarChart labels, map[string][]float64 Radar/spider chart
GraphvizChart dot string Graphviz DOT via viz.js

External charting library integrations (CDN-loaded, accepting JSON specs):

Chart Library Streamlit Equivalent
VegaLiteChart Vega-Lite / vega-embed st.altair_chart
PlotlyChart Plotly.js st.plotly_chart
PyplotChart SVG/PNG images st.pyplot
BokehChart BokehJS st.bokeh_chart
PydeckChart deck.gl st.pydeck_chart
Layout
// Columns (equal or weighted)
cols := sy.Columns(3)
cols[0](func() { sy.Text("Col 1") })

cols := sy.WeightedColumns(2, 1, 1)

// Tabs
tab := sy.Tabs([]string{"Tab1", "Tab2"})
tab("Tab1", func() { sy.Text("Content 1") })

// Other containers
sy.Sidebar(func() { ... })
sy.Expander("Title", func() { ... })
sy.Container(func() { ... }, sy.Border())
sy.Form("key", func() { ... })
sy.Status("Loading", "running", func() { ... })
sy.Fragment("key", func() { ... })  // partial rerun
State & Session
// Typed state (persists across reruns)
count := sy.State("count", 0)
count.Get()
count.Set(42)

// Query parameters
val := sy.QueryParam("page")

// Flow control
sy.Stop()   // halt rendering
sy.Rerun()  // force rerun
Multi-Page Apps
func init() {
    sy.AddPage("Home", homePage, sy.PageIcon("🏠"), sy.PageOrder(1))
    sy.AddPage("About", aboutPage, sy.PageIcon("ℹ️"), sy.PageOrder(2))
}

func main() { sy.App(nil) }
Auth
// Login gate blocks rendering until authenticated
username := sy.LoginGate(func(user, pass string) bool {
    return user == "admin" && pass == "secret"
})

// Role-based access
user := sy.User()  // map[string]string or nil
sy.Login(map[string]string{"name": "admin", "role": "admin"})
sy.Logout()
Caching
data := sy.CacheData("key", func() []Row {
    return fetchFromDB()
}, sy.TTL(5 * time.Minute))

db := sy.CacheResource("db", func() *sql.DB {
    return openDB()
})
Feedback & Notifications
sy.Success("Done!")
sy.Error("Failed!")
sy.Warning("Watch out")
sy.Info("Note")
sy.Toast("Message", "success")
sy.Balloons()
sy.Snow()
sy.Dialog("Settings", func() { ... })
Streaming (LLM Output)
sy.WriteStream(func(yield func(string)) {
    for _, word := range words {
        yield(word + " ")
        time.Sleep(30 * time.Millisecond)
    }
})
Chat UI
msgs := sy.State("msgs", []map[string]string{})
for _, m := range msgs.Get() {
    sy.ChatMessage(m["role"], func() {
        sy.Markdown(m["content"])
    })
}
if input := sy.ChatInput("Ask something..."); input != "" {
    msgs.Set(append(msgs.Get(), map[string]string{
        "role": "user", "content": input,
    }))
}
Maps
sy.Map([]sy.MapPoint{
    {Lat: 25.0330, Lon: 121.5654, Text: "Taipei 101"},
}, sy.Height(450))
Database
db := sy.Connection("mydb")
rows := sy.SQLQuery(db, "SELECT * FROM users")

Configuration

syralit.toml
title = "My App"
host = "0.0.0.0"
port = 8600

[theme]
primary_color = "#ff4b4b"
background_color = "#0e1117"
text_color = "#fafafa"

[secrets]
api_key = "sk-..."
db_dsn = "postgres://..."
Runtime Configuration
sy.SetPageConfig(
    sy.PageTitle("My App"),
    sy.PageLayout("wide"),
    sy.ConfigIcon("🚀"),
    sy.PrimaryColor("#ff4b4b"),
)

apiKey := sy.Secrets("api_key")

Common Options

sy.Key("unique_key")        // stable widget identity
sy.DefaultValue(val)         // initial value
sy.Placeholder("hint")      // placeholder text
sy.Help("tooltip")          // help tooltip
sy.Disabled()               // disable widget
sy.Min(0), sy.Max(100)      // numeric range
sy.Step(0.5)                // numeric step
sy.Height(300), sy.Width(400)
sy.ChartTitle("Title")      // chart title
sy.Border()                 // container border
sy.Color("green")           // element color
sy.Language("go")           // code language

// Button styling (Button, LinkButton, DownloadButton)
sy.Icon("🚀")               // prefix a button label with an icon
sy.ButtonType("secondary")  // "primary" (default), "secondary", "tertiary"
sy.UseContainerWidth()      // make a button span its container

sy.Border()                 // also: bordered Metric card
sy.MinDate("2026-01-01")    // DateInput / DateRangeInput lower bound
sy.MaxDate("2026-12-31")    // DateInput / DateRangeInput upper bound

Insyra Integration

Syralit has first-class support for Insyra DataTable and DataList via a cleanly separated adapter package. The core framework never imports Insyra.

import syi "github.com/HazelnutParadise/syralit/integrations/insyra"

// DataTable (multi-column)
syi.Table(dt)                           // render DataTable
syi.Preview(dt, 5)                      // first N rows
syi.EditableTable(dt, sy.Key("edit"))   // editable DataTable
col := syi.ColumnSelect("Column", dt)   // column picker
syi.Metrics(dt, col)                    // count, mean, min, max
syi.BarChart(dt, "Category", "Value")   // chart from columns
syi.LineChart(dt, "Month", "Revenue")
syi.ScatterChart(dt, "X", "Y")

// DataList (single series) — the symmetric counterpart
syi.List(dl)                            // single-column table
syi.ListPreview(dl, 5)                  // first N values
syi.EditableList(dl, sy.Key("edl"))     // editable single column → []any
syi.ListMetrics(dl)                     // count, mean, min, max
syi.ListDescribe(dl)                    // count/mean/std/min/25%/50%/75%/max
syi.ListBarChart(dl)                    // value over index
syi.ListLineChart(dl)
syi.ListAreaChart(dl)
syi.Histogram(dl, 20)                   // distribution (list-only)

Examples

The examples/ directory contains runnable demo apps:

Example Description
hello Minimal single-page app with basic widgets
showcase Comprehensive 6-page demo of all features
chatbot Chat UI with simulated streaming AI responses
form-app Conference registration form with validation
data-explorer 3-page sales dashboard with charts, filters, and data editing
auth-demo Authentication with LoginGate and role-based access control
mega-demo 10-page app showcasing every feature: all widgets, charts, layout, forms, data tables, chat, maps, state
insyra-demo Insyra DataTable integration demo

Run any example:

cd examples/chatbot
go run .

Agent Skills

The skills/ directory contains Agent Skills for building Syralit apps with AI coding assistants. The syralit-dev skill provides a complete API reference.

Install it into your project with the skills CLI:

npx skills add HazelnutParadise/syralit/skills

Or copy the skills/syralit-dev/ folder into your agent's skills directory manually (e.g. .claude/skills/).

CLI Commands

Command Description
syralit new <name> Scaffold a new project in a new folder
syralit new . Scaffold into the current directory (no wrapper folder)
syralit dev Hot reload with state preservation
syralit run Build and run once (no watching)
syralit build [-o out] [dir] Compile to a single self-contained executable

Static Files & Bundling

Drop files in a public/ directory and they're served at the site root — public/logo.png/logo.png. In syralit dev they're served from disk; for production, syralit build folds public/ (and any assets/ overrides) into the binary via //go:embed, so the result is one executable with the front-end, backend, and all your static files — nothing to copy alongside it.

syralit build              # → ./<dir-name>[.exe], everything embedded
syralit build -o myapp .   # custom output path

You can also wire static files manually with sy.Static(fsys) (served at the root) and sy.StaticAssets(fsys) (overrides the built-in front-end assets).

Testing

sy.RenderOnce(appFn) *Node runs an app function once in an isolated session and returns the UI tree — no server needed. Walk it with Node.Find(type):

tree := sy.RenderOnce(func() { sy.Metric("Users", "24,891") })
if len(tree.Find("metric")) != 1 { t.Fatal("expected a metric") }

Requirements

  • Go 1.25+

Changelog

See CHANGELOG.md.

License

MIT

Documentation

Index

Constants

View Source
const ConfigFileName = "syralit.toml"

ConfigFileName is the conventional per-project settings file. It is optional; when present at the project root it fills in any value not set explicitly in code or via CLI flags (precedence: flag > syralit.toml > built-in default).

Variables

This section is empty.

Functions

func AddPage

func AddPage(title string, fn func(), opts ...PageOption)

AddPage registers a page for sidebar navigation. Call it in init() so that adding a new .go file with an init+AddPage call is all that is needed to create a page — the compiled-language equivalent of Streamlit's pages/.

Pages are sorted by PageOrder (ascending), then by registration order.

func App

func App(fn func())

App starts a Syralit app with default config. It blocks until the server stops.

In single-page mode (no AddPage calls), fn is the sole page function. In multi-page mode (AddPage called in init()), fn is ignored and pages are rendered from the registry. Pass nil when using AddPage.

func AreaChart

func AreaChart(data map[string][]float64, opts ...Option)

AreaChart renders an area chart (filled line chart) from named series.

func Audio

func Audio(src string, opts ...Option)

Audio renders an HTML audio player. src can be a URL or data URI.

func AudioInput

func AudioInput(label string, opts ...Option) string

AudioInput renders a microphone recording widget. Returns the recorded audio as a base64 data URI (audio/webm), or "" if nothing recorded.

func Badge

func Badge(text string, opts ...Option)

Badge renders a small colored label. Color can be "blue", "green", "red", "orange", "gray", "violet", or any CSS color string.

func Balloons

func Balloons()

Balloons renders a celebratory balloon animation.

func BarChart

func BarChart(data map[string][]float64, opts ...Option)

BarChart renders a bar chart from named series.

func BokehChart

func BokehChart(spec map[string]any, opts ...Option)

BokehChart renders a Bokeh chart from a JSON spec. The spec is a map[string]any matching Bokeh's JSON document format. Rendered client-side using BokehJS (CDN).

This is the Go equivalent of Streamlit's st.bokeh_chart.

func Button

func Button(label string, opts ...Option) bool

func CacheData

func CacheData[T any](key string, fn func() T, opts ...CacheOption) T

CacheData returns a cached value for key. If the cache is empty or expired, fn is called to compute the value. The cache is process-global (shared across sessions), which is fine for Syralit's single-user, local-app positioning.

data := sy.CacheData("csv", func() [][]string {
    return loadCSV("data.csv")
})

func CacheResource

func CacheResource[T any](key string, fn func() T) T

CacheResource returns a cached singleton for key. Unlike CacheData, the value never expires and is intended for long-lived resources like database connections, ML models, or HTTP clients.

db := sy.CacheResource("db", func() *sql.DB {
    db, _ := sql.Open("postgres", dsn)
    return db
})

func CameraInput

func CameraInput(label string, opts ...Option) string

CameraInput renders a webcam capture widget. The user clicks "Take Photo" to capture a snapshot, which is returned as a base64-encoded JPEG data URI. Returns empty string until a photo is taken.

func Caption

func Caption(text string)

func ChatInput

func ChatInput(placeholder string, opts ...Option) string

ChatInput renders a chat text input pinned to the bottom of the content area. Returns the submitted text (non-empty only on the rerun triggered by Enter).

func ChatMessage

func ChatMessage(role string, fn func())

ChatMessage renders a chat bubble with avatar and role styling. Use inside a loop over your message history:

sy.ChatMessage("user", func() { sy.Text(msg.Content) })
sy.ChatMessage("assistant", func() { sy.Markdown(msg.Content) })

func Checkbox

func Checkbox(label string, opts ...Option) bool

func ClearCache

func ClearCache(keys ...string)

ClearCache removes cached entries. With no arguments it clears all entries; with keys it clears only the specified entries.

func CloseDialog

func CloseDialog(key string)

CloseDialog closes a dialog by its key.

func Code

func Code(code string, opts ...Option)

Code renders a preformatted code block. Use Language("go") for syntax hints.

func ColorPicker

func ColorPicker(label string, opts ...Option) string

func Component

func Component(html string, opts ...Option) any

Component renders a custom HTML/JS widget. The html parameter is rendered inside an iframe. The component can communicate with Syralit by calling parent.postMessage({syralitValue: value}, "*") to set its return value. Returns the last value sent by the component, or nil.

func Connection

func Connection(name string) *sql.DB

Connection returns a cached *sql.DB for the given name. The DSN is read from Secrets(name + "_DSN") or the [connections.<name>] section of syralit.toml. The driver must be registered by importing the appropriate database/sql driver package (e.g., _ "github.com/mattn/go-sqlite3").

db := sy.Connection("mydb")
rows, _ := db.Query("SELECT * FROM users")

func Container

func Container(fn func(), opts ...Option)

Container groups widgets into a plain wrapper (useful for conditional blocks). Use Border() to render a visible border and Height(px) for a scrollable area.

func DataEditor

func DataEditor(headers []string, rows [][]any, opts ...Option) [][]any

DataEditor renders an editable data table. Returns the current rows, reflecting any edits made by the user. Each cell edit triggers a rerun. Use ColConfig() to set column types (text, number, checkbox, select).

func DataFrame

func DataFrame(headers []string, rows [][]any, opts ...Option) []int

DataFrame renders a sortable, interactive data table. Sorting is handled client-side. Rows can contain any printable values. When made selectable with sy.Selectable(), DataFrame renders a row-selection checkbox column and returns the indices (into the original rows) the user has selected; otherwise it returns nil. Selection survives client-side sorting.

func DateInput

func DateInput(label string, opts ...Option) string

func DateRangeInput

func DateRangeInput(label string, opts ...Option) (string, string)

DateRangeInput is a pair of date pickers returning the selected (start, end) dates as "YYYY-MM-DD" strings (empty until picked) — the equivalent of Streamlit's st.date_input called with a (start, end) tuple. Inside a Form it is batched and commits on submit like any other input.

func DateSlider

func DateSlider(label, minDate, maxDate string, opts ...Option) string

DateSlider is a slider over a date range, returning the picked date as a "YYYY-MM-DD" string — the equivalent of Streamlit's st.slider with date values. minDate/maxDate are "YYYY-MM-DD"; the initial value defaults to minDate (override with sy.DefaultValue("YYYY-MM-DD")). It is form-batched.

func Dialog

func Dialog(title string, fn func(), opts ...Option)

Dialog renders a modal dialog overlay. Content is always rendered in the tree (for consistent widget IDs) but only visible when open. Use ShowDialog/CloseDialog to toggle, or let the user click the backdrop/×.

Key is required to identify the dialog for ShowDialog/CloseDialog.

func Divider

func Divider()

Divider renders a horizontal rule.

func DoughnutChart

func DoughnutChart(data map[string]float64, opts ...Option)

DoughnutChart renders a doughnut chart (pie with hole). Labels map to values.

func DownloadButton

func DownloadButton(label string, data []byte, filename string, opts ...Option)

DownloadButton renders a button that downloads data as a file when clicked. Data is base64-encoded and sent to the client. Use MimeType("text/csv") to set the content type.

func Echo

func Echo(code string, fn func())

Echo displays source code alongside its output. Pass the code text and a function that produces the output widgets.

func Empty

func Empty() func(func())

Empty renders nothing by default but occupies a slot in the layout. Call the returned function with a callback to populate it. Useful for replacing content across reruns.

placeholder := sy.Empty()
if ready {
    placeholder(func() { sy.Text("Data loaded") })
}

func Error

func Error(text string)

func Exception

func Exception(err error)

Exception renders a Go error in a styled, monospace error box — the equivalent of Streamlit's st.exception. A nil error renders nothing.

func Expander

func Expander(label string, fn func(), opts ...Option)

Expander renders a collapsible section. The expanded/collapsed state is tracked server-side and persists across reruns.

func Feedback

func Feedback(opts ...Option) string

Feedback renders a thumbs up/down rating widget. Returns "up", "down", or "" (no selection yet). Useful for collecting user feedback on AI responses.

func Form

func Form(key string, fn func())

Form groups widgets so their changes are batched and only sent when the user clicks FormSubmitButton. Inside a Form, widget changes do not trigger reruns.

func FormSubmitButton

func FormSubmitButton(label string, opts ...Option) bool

FormSubmitButton renders a submit button inside a Form. Returns true on the single rerun triggered by form submission.

func Fragment

func Fragment(key string, fn func())

Fragment wraps a function so that widget changes inside it only re-run this function, not the entire app. This improves performance for complex apps with independent sections.

sy.Fragment("chart-section", func() {
    x := sy.Slider("X", sy.Min(0), sy.Max(100), sy.Key("x"))
    sy.LineChart([]float64{float64(x), float64(x*2)})
})

func GraphvizChart

func GraphvizChart(dot string, opts ...Option)

GraphvizChart renders a Graphviz DOT graph using viz.js (CDN).

sy.GraphvizChart(`digraph { A -> B -> C; B -> D; }`)

func HTML

func HTML(html string)

HTML renders raw HTML content directly. Use with care — user-supplied content should be sanitized before passing to this function.

func Header(text string)

func HistogramChart

func HistogramChart(data []float64, bins int, opts ...Option)

HistogramChart renders a histogram from raw data values. The bins parameter sets the number of bins (defaults to 10 if zero).

func IFrame

func IFrame(url string, opts ...Option)

IFrame renders an external URL in an iframe.

func Image

func Image(src string, opts ...Option)

Image renders an image. src can be a URL or data URI. Use Alt("desc"), Width(300), ImageCaption("caption") options.

func ImageFromBytes

func ImageFromBytes(data []byte, opts ...Option)

ImageFromBytes renders an image from raw bytes. The MIME type should be specified via MimeType("image/png") or similar; defaults to image/png.

func Info

func Info(text string)

func JSON

func JSON(data any)

JSON renders a formatted JSON viewer for any serializable value.

func LaTeX

func LaTeX(formula string)

LaTeX renders a mathematical formula using KaTeX (loaded from CDN on first use). The formula string should use LaTeX syntax without delimiters.

func LineChart

func LineChart(data map[string][]float64, opts ...Option)

LineChart renders a line chart from named series.

sy.LineChart(map[string][]float64{
    "Revenue": {10, 20, 30, 25, 35},
    "Cost":    {5, 8, 12, 10, 15},
})
func Link(text, url string)

Link renders a clickable hyperlink that opens in a new tab.

func LinkButton

func LinkButton(label, url string, opts ...Option)

LinkButton renders a button-styled hyperlink that opens in a new tab.

func Login

func Login(user map[string]string)

Login sets the current session's authenticated user. Call this after validating credentials.

func LoginGate

func LoginGate(check func(username, password string) bool) string

LoginGate renders a login form and blocks the rest of the app until the user authenticates. The check function receives (username, password) and returns true if the credentials are valid. Returns the logged-in username.

user := sy.LoginGate(func(u, p string) bool {
    return u == "admin" && p == sy.Secrets("ADMIN_PASS")
})
sy.Title("Welcome, " + user)

func Logout

func Logout()

Logout clears the current session's authenticated user.

func Map

func Map(points []MapPoint, opts ...Option)

Map renders an interactive map with markers using Leaflet.js (CDN). Points are displayed as markers with optional popup text.

sy.Map([]sy.MapPoint{
    {Lat: 25.033, Lon: 121.565, Text: "Taipei 101"},
    {Lat: 25.047, Lon: 121.517, Text: "Taipei Main Station"},
}, sy.Height(400))

func Markdown

func Markdown(text string)

func Metric

func Metric(label, value string, opts ...Option)

Metric renders a big-number metric with optional delta indicator. Use Delta("1.2 °F") and DeltaColor("inverse") options.

func MultiSelect

func MultiSelect(label string, options []string, opts ...Option) []string
func Navigation(pages []Page) string

Navigation provides a declarative way to define multi-page apps inline. It registers pages, renders the active one, and returns the active page title. Unlike AddPage (which is called in init()), Navigation is called inside the app function and can be used with dynamic page lists.

active := sy.Navigation([]sy.Page{
    {Title: "Home", Fn: homePage, Icon: "🏠"},
    {Title: "Settings", Fn: settingsPage, Icon: "⚙️"},
})

func NumberInput

func NumberInput(label string, opts ...Option) float64
func PageLink(label string, page string, opts ...Option)

PageLink renders a navigation link to another page in the app (or an external URL). When clicked for an internal page, a page_change is sent.

func Pagination

func Pagination(totalPages int, opts ...Option) int

Pagination renders a page selector for paginating data. Returns the current page number (1-based). totalPages is the total number of pages.

func PasswordInput

func PasswordInput(label string, opts ...Option) string

PasswordInput renders a password text input (masked characters).

func PieChart

func PieChart(data map[string]float64, opts ...Option)

PieChart renders a pie chart from labelled values.

sy.PieChart(map[string]float64{
    "Go": 45,
    "Python": 35,
    "Rust": 20,
})

func Pills

func Pills(label string, options []string, opts ...Option) string

Pills renders a set of selectable tag-like buttons. Returns the selected option string. Use for filter or category selection.

func PlotlyChart

func PlotlyChart(spec map[string]any, opts ...Option)

PlotlyChart renders a Plotly chart from a figure spec. The spec is a map[string]any matching the Plotly JSON schema (data + layout). Rendered client-side using Plotly.js (CDN).

This is the Go equivalent of Streamlit's st.plotly_chart — Plotly figures in Python serialize to JSON, so accepting the JSON spec directly provides the same capability.

sy.PlotlyChart(map[string]any{
    "data": []map[string]any{{
        "x": []string{"giraffes", "orangutans", "monkeys"},
        "y": []float64{20, 14, 23},
        "type": "bar",
    }},
    "layout": map[string]any{"title": "Animals"},
})

func Popover

func Popover(label string, fn func(), opts ...Option)

Popover renders a button that shows a floating panel with the content produced by fn.

func Progress

func Progress(value float64)

Progress renders a progress bar. value is 0.0 to 1.0.

func PydeckChart

func PydeckChart(spec map[string]any, opts ...Option)

PydeckChart renders a deck.gl 3D map visualization from a JSON spec. The spec is a map[string]any matching deck.gl's JSON schema. Rendered client-side using deck.gl (CDN).

This is the Go equivalent of Streamlit's st.pydeck_chart — PyDeck is a Python API that generates deck.gl JSON specs.

sy.PydeckChart(map[string]any{
    "initialViewState": map[string]any{
        "latitude": 37.76, "longitude": -122.4,
        "zoom": 11, "pitch": 50,
    },
    "layers": []map[string]any{{
        "@@type": "HexagonLayer",
        "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-bike-parking.json",
        "getPosition": "@@=[lng, lat]",
        "radius": 200,
        "elevationScale": 4,
        "extruded": true,
    }},
})

func PyplotChart

func PyplotChart(data string, opts ...Option)

PyplotChart renders a static chart image from raw PNG/SVG bytes. This is the Go equivalent of Streamlit's st.pyplot — in Python, matplotlib figures are exported as images. In Go, any charting library that can export PNG or SVG can be used.

The format is auto-detected: if data starts with "<svg" it is treated as inline SVG; otherwise it is treated as a base64-encoded PNG data URI.

// From SVG string:
sy.PyplotChart(svgString)
// From PNG bytes:
sy.PyplotChart(base64.StdEncoding.EncodeToString(pngBytes))

func QueryParam

func QueryParam(key string) string

QueryParam returns a single URL query parameter value.

func QueryParams

func QueryParams() map[string]string

QueryParams returns a copy of the URL query parameters from the current session's WebSocket connection. Useful for deep linking and sharing app state via URL.

params := sy.QueryParams()
filter := params["filter"]

func RadarChart

func RadarChart(labels []string, data map[string][]float64, opts ...Option)

RadarChart renders a radar/spider chart from named series.

func Radio

func Radio(label string, options []string, opts ...Option) string

func RangeSlider

func RangeSlider(label string, min, max float64, opts ...Option) (float64, float64)

RangeSlider is a two-handle slider returning the selected (low, high) range — the equivalent of Streamlit's st.slider called with a tuple value. The initial range defaults to [min, max]; override with sy.DefaultValue([2]float64{lo, hi}). Inside a Form it is batched and commits on submit like any other input.

func Rerun

func Rerun()

Rerun triggers an immediate re-execution of the app function. The current execution is halted (like Stop) and the session is flagged for re-rendering.

func Run

func Run(cfg Config, fn func()) error

Run starts a Syralit app with explicit config. Values left unset are filled from syralit.toml in the working directory if present, then by defaults.

func RunDev

func RunDev(opts DevOptions) error

RunDev starts the hot reload supervisor. The supervisor owns the outward port and the browser connections for its whole lifetime ("the app never stops"), while the user's program runs as a child process that is rebuilt and restarted on file changes. Session state is carried across restarts (SPEC §10.3).

func SQLQuery

func SQLQuery(db *sql.DB, query string, args ...any) ([]string, [][]any)

SQLQuery executes a SQL query and returns the results as headers and rows, ready to pass to DataFrame or DataEditor.

func ScatterChart

func ScatterChart(data map[string][][2]float64, opts ...Option)

ScatterChart renders a scatter plot. Each series maps to a slice of [x, y] coordinate pairs.

sy.ScatterChart(map[string][][2]float64{
    "Group A": {{1, 2}, {3, 4}, {5, 6}},
})

func Secrets

func Secrets(key string) string

Secrets returns a secret value from the [secrets] section of syralit.toml, falling back to an environment variable of the same name. This lets apps keep API keys out of source code.

apiKey := sy.Secrets("OPENAI_API_KEY")

func SegmentedControl

func SegmentedControl(label string, options []string, opts ...Option) string

SegmentedControl renders a row of mutually exclusive buttons. Returns the selected option string. Similar to Radio but rendered as a single bar.

func SelectBox

func SelectBox(label string, options []string, opts ...Option) string

func SelectSlider

func SelectSlider(label string, options []string, opts ...Option) string

SelectSlider renders a slider that snaps to labelled options, returning the selected label string. options must have at least 2 elements.

func SetPageConfig

func SetPageConfig(opts ...PageConfigOption)

SetPageConfig configures page-level settings such as the browser tab title and content layout. Call this at the top of your page function.

func ShowDialog

func ShowDialog(key string)

ShowDialog opens a dialog by its key.

func Sidebar(fn func())

Sidebar adds user-defined content to the sidebar (below the page links). In single-page mode this also causes the sidebar to appear.

func Slider

func Slider(label string, min, max float64, opts ...Option) float64

func Snow

func Snow()

Snow renders a falling snow animation.

func Spinner

func Spinner(text ...string)

Spinner renders a loading indicator with optional text.

func Static

func Static(fsys fs.FS)

Static mounts a filesystem whose files are served at the site root, so an embedded public/ directory becomes reachable at "/...". Call it before App or Run. Multiple calls stack (first match wins); the reserved /_syralit/* routes always take precedence, and "/" always renders the app shell.

//go:embed all:public
var public embed.FS

func main() {
    sub, _ := fs.Sub(public, "public")
    sy.Static(sub)
    sy.App(myApp)
}

The `syralit build` command writes this wiring for you automatically.

func StaticAssets

func StaticAssets(fsys fs.FS)

StaticAssets overlays a filesystem on the built-in front-end assets served at /_syralit/assets/. A file here (e.g. a custom runtime.css) shadows the framework's copy — the production equivalent of `syralit dev`'s assets/ dir.

func Status

func Status(label, state string, fn func())

Status renders a collapsible status container with a state indicator. state is "running", "complete", or "error". While "running", a spinner is shown next to the label.

sy.Status("Loading data", "running", func() {
    sy.Text("Fetching from API...")
    sy.Progress(0.5)
})

func Stop

func Stop()

Stop halts the current rerun early. Widgets rendered so far are kept. Useful for conditional guards:

if !loggedIn { sy.Warning("Please log in"); sy.Stop() }

func Subheader

func Subheader(text string)

func Success

func Success(text string)

func SwitchPage

func SwitchPage(title string)

SwitchPage programmatically navigates to a different page. The current rerun is stopped and the next render will show the target page.

func Table

func Table(headers []string, rows [][]string)

Table renders a static data table.

func Tabs

func Tabs(labels []string, opts ...Option) func(string, func())

Tabs creates a tabbed container. It returns a function to define each tab's content. The active tab is tracked server-side. All tab content is rendered and sent; the client shows only the active tab.

func Text

func Text(text string)

func TextArea

func TextArea(label string, opts ...Option) string

func TextInput

func TextInput(label string, opts ...Option) string

func Textf

func Textf(format string, a ...any)

func TimeInput

func TimeInput(label string, opts ...Option) string

func Title

func Title(text string)

func Toast

func Toast(text string, level ...string)

Toast shows a brief notification that auto-dismisses. Level is one of "info", "success", "warning", "error".

func Toggle

func Toggle(label string, opts ...Option) bool

func User

func User() map[string]string

User returns the current session's authenticated user info. Returns nil if no user is logged in.

func VegaLiteChart

func VegaLiteChart(spec map[string]any, opts ...Option)

VegaLiteChart renders a Vega-Lite chart from a spec. The spec is a map[string]any matching the Vega-Lite JSON schema. The chart is rendered client-side using the Vega-Lite JavaScript library (CDN).

This is the Go equivalent of Streamlit's st.altair_chart — Altair is a Python API that generates Vega-Lite JSON specs, so accepting the spec directly provides the same capability.

sy.VegaLiteChart(map[string]any{
    "mark": "bar",
    "encoding": map[string]any{
        "x": map[string]any{"field": "category", "type": "nominal"},
        "y": map[string]any{"field": "value", "type": "quantitative"},
    },
    "data": map[string]any{
        "values": []map[string]any{
            {"category": "A", "value": 28},
            {"category": "B", "value": 55},
        },
    },
})

func Video

func Video(src string, opts ...Option)

Video renders an HTML video player. src can be a URL or data URI. Use Width(640) to constrain the player width.

func Warning

func Warning(text string)

func Write

func Write(args ...any)

Write renders any value: strings are treated as Markdown, errors as Error blocks, and everything else is formatted as JSON.

func WriteStream

func WriteStream(fn func(yield func(string)), opts ...Option)

WriteStream renders text that streams in token by token. The function receives a yield callback; call it with each text chunk. Useful for displaying LLM responses as they arrive.

sy.WriteStream(func(yield func(string)) {
    for token := range llm.Stream(prompt) {
        yield(token)
    }
})

Types

type CacheOption

type CacheOption func(*cacheOpts)

CacheOption configures caching behavior. See TTL.

func TTL

func TTL(d time.Duration) CacheOption

TTL sets the time-to-live for cached data. After this duration the cached value expires and fn is re-invoked on the next call.

type Column

type Column func(fn func())

Column renders children into one column of a Columns layout.

func Columns

func Columns(n int, opts ...Option) []Column

Columns creates n side-by-side columns. Call each returned Column with a callback to populate it.

func WeightedColumns

func WeightedColumns(weights ...float64) []Column

WeightedColumns creates columns with custom widths specified as fractions. Example: WeightedColumns(2, 1) creates a 2:1 split (66%/33%).

type ColumnConfig

type ColumnConfig struct {
	Type    string   // column type (see above)
	Options []string // for "select" type: dropdown options
	Width   int      // optional column width in pixels
	Min     float64  // for "number" or "progress": minimum value
	Max     float64  // for "number" or "progress": maximum value
}

ColumnConfig defines the type and options for a DataEditor column. Supported types: "text", "number", "checkbox", "select", "date", "time", "datetime", "link", "image", "progress", "list".

type Config

type Config struct {
	Title string
	Host  string
	Port  int
	Theme Theme
}

Config controls the dev server. Fields beyond these (Theme, upload limits) are reserved for later stages; see SPEC §6.1 / §15.

type DevOptions

type DevOptions struct {
	Dir       string // project directory to build & watch (default ".")
	Target    string // build target package (default Dir)
	Host      string // outward bind host (default 127.0.0.1)
	Port      int    // outward port (default 8600)
	Title     string // page title
	AssetsDir string // optional: serve front-end assets from disk and hot-reload them
	PublicDir string // optional: serve user static files (public/) from disk at site root
	Theme     Theme
}

DevOptions configures the hot reload supervisor.

type MapPoint

type MapPoint struct {
	Lat  float64
	Lon  float64
	Text string // optional popup text
}

MapPoint represents a single marker on a Map widget.

type Node

type Node struct {
	ID       string         `json:"id,omitempty"`
	Type     string         `json:"type"`
	Props    map[string]any `json:"props,omitempty"`
	Children []*Node        `json:"children,omitempty"`
}

Node is one element in the UI tree that a rerun produces. The whole tree is serialized to JSON and sent to the browser, where the client runtime renders and reconciles it. See docs/event-protocol — Type drives which DOM element the client builds, Props carries its attributes, and ID is the stable widget key.

func RenderOnce

func RenderOnce(appFn func()) *Node

RenderOnce executes appFn once in a fresh, isolated session and returns the root Node of the UI tree it produces. No server is started and no socket is opened — it is meant for unit-testing widgets and integrations. Walk the result with Node.Find / Node.Children. Note: it renders appFn directly and does not consult pages registered via AddPage.

func (*Node) Find

func (n *Node) Find(typ string) []*Node

Find returns every descendant of the given type (depth-first, including n itself if it matches). It's a convenience for tests built on RenderOnce.

type Option

type Option func(*widgetOpts)

Option configures a widget. See Key, Min, Max, Step, Placeholder, etc.

func Alt

func Alt(v string) Option

func Border

func Border() Option

func ButtonType

func ButtonType(v string) Option

ButtonType selects a button's visual style: "primary" (default, accent fill), "secondary" (outlined), or "tertiary" (text only).

func ChartTitle

func ChartTitle(t string) Option

func ColConfig

func ColConfig(configs map[string]ColumnConfig) Option

ColConfig is an Option that sets column configurations for DataEditor.

func Color

func Color(c string) Option

func DefaultValue

func DefaultValue(v any) Option

func Delta

func Delta(v string) Option

func DeltaColor

func DeltaColor(v string) Option

func Disabled

func Disabled() Option

func DynamicRows

func DynamicRows() Option

func Expanded

func Expanded() Option

func Gap

func Gap(px int) Option

func Height

func Height(v int) Option

func Help

func Help(v string) Option

func Icon

func Icon(v string) Option

Icon prefixes a button's label with an icon (emoji or short string).

func ImageCaption

func ImageCaption(v string) Option

func Key

func Key(k string) Option

func LabelCollapsed

func LabelCollapsed() Option

func LabelHidden

func LabelHidden() Option

func Language

func Language(v string) Option

func Max

func Max(v float64) Option

func MaxChars

func MaxChars(v int) Option

func MaxDate

func MaxDate(d string) Option

func MaxSelections

func MaxSelections(n int) Option

func MimeType

func MimeType(v string) Option

func Min

func Min(v float64) Option

func MinDate

func MinDate(d string) Option

MinDate / MaxDate bound a DateInput or DateRangeInput to a "YYYY-MM-DD" range.

func Placeholder

func Placeholder(v string) Option

func Selectable

func Selectable() Option

Selectable enables row selection on a DataFrame; the call then returns the selected row indices.

func Step

func Step(v float64) Option

func UseContainerWidth

func UseContainerWidth() Option

UseContainerWidth makes a button span the full width of its container.

func VerticalAlignment

func VerticalAlignment(align string) Option

func Width

func Width(v int) Option

func XLabels

func XLabels(l []string) Option

type Page

type Page struct {
	Title string
	Fn    func()
	Icon  string
}

Page represents a page definition for use with Navigation.

type PageConfigOption

type PageConfigOption func(*pageConfig)

PageConfigOption configures the page via SetPageConfig.

func BackgroundColor

func BackgroundColor(color string) PageConfigOption

BackgroundColor sets the main background color.

func ConfigIcon

func ConfigIcon(i string) PageConfigOption

ConfigIcon sets the favicon (emoji or URL).

func ConfigLogo(src string) PageConfigOption

ConfigLogo sets the sidebar logo image URL.

func PageLayout

func PageLayout(l string) PageConfigOption

PageLayout sets the content layout. "centered" (default) or "wide".

func PageTitle

func PageTitle(t string) PageConfigOption

PageTitle sets the browser tab title.

func PrimaryColor

func PrimaryColor(color string) PageConfigOption

PrimaryColor sets the accent/primary color for the theme.

func TextColor

func TextColor(color string) PageConfigOption

TextColor sets the primary text color.

type PageOption

type PageOption func(*pageEntry)

PageOption configures a page entry in the sidebar.

func PageIcon

func PageIcon(icon string) PageOption

PageIcon sets the emoji icon displayed next to the page title in the sidebar.

func PageOrder

func PageOrder(n int) PageOption

PageOrder sets an explicit sort position for this page. Lower values appear first. Pages without an explicit order use their registration sequence (which in Go is file-name-alphabetical within a package).

type SessionStore

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

SessionStore is the non-generic session store API (SPEC §7).

func Session

func Session() *SessionStore

Session returns the current rerun's session store for untyped access.

func (*SessionStore) Get

func (s *SessionStore) Get(key string) (any, bool)

func (*SessionStore) Set

func (s *SessionStore) Set(key string, value any)

type StateValue

type StateValue[T any] struct {
	// contains filtered or unexported fields
}

func State

func State[T any](key string, def T) *StateValue[T]

State returns a typed handle to a value that persists across reruns within the current session. On first use the default is stored; later reruns see whatever was last Set.

count := sy.State("count", 0)
if sy.Button("Add") { count.Set(count.Get() + 1) }
sy.Textf("Count: %d", count.Get())

Note (deviation from SPEC §7): SPEC sketched both a `type State[T]` interface and a `sy.State(...)` constructor, which collide in Go (a package can't have a type and a func with the same name). We keep the constructor and return the concrete *StateValue[T].

func (*StateValue[T]) Clear

func (s *StateValue[T]) Clear()

func (*StateValue[T]) Get

func (s *StateValue[T]) Get() T

func (*StateValue[T]) Set

func (s *StateValue[T]) Set(v T)

type Theme

type Theme struct {
	Mode   string // "light" | "dark" | "system"
	Accent string // CSS color, e.g. "#7C3AED"
	Radius string // CSS length, e.g. "12px"
}

Theme controls the front-end look (SPEC §17).

type UploadedFile

type UploadedFile struct {
	Name string
	Size int64
	Type string
	Data []byte
}

UploadedFile holds the data from a FileUploader widget.

func FileUploader

func FileUploader(label string, opts ...Option) *UploadedFile

FileUploader renders a file upload widget and returns the uploaded file (or nil if nothing has been uploaded). The file data is sent as base64 over the WebSocket, so this is suited for files up to a few MB.

Directories

Path Synopsis
cmd
syralit command
Command syralit is the Syralit development CLI.
Command syralit is the Syralit development CLI.
examples
auth-demo command
chatbot command
data-explorer command
form-app command
hello command
insyra-demo command
mega-demo command
showcase command
integrations
insyra
Package syinsyra provides first-class Insyra integration for Syralit.
Package syinsyra provides first-class Insyra integration for Syralit.

Jump to

Keyboard shortcuts

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