ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
16_data_table/main.cpp

Example from examples/16_data_table/.

Example from examples/16_data_table/.

#include "ExampleHost.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
using namespace ZenitUI;
static constexpr const char *kStyle = R"zs(
:root {
font: inter;
font-size: 13px;
letter-spacing: 0px;
color: #E5E7EB;
}
.page {
width: 100%;
height: 100%;
background: #0D1017;
padding: 16px 20px;
gap: 12px;
}
.header-bar {
width: 100%;
gap: 10px;
wrap: true;
align-items: center;
justify: space-between;
}
.title {
font: inter-bold;
font-size: 21px;
color: #F8FAFC;
}
.subtitle {
font-size: 12px;
color: #94A3B8;
}
.count-pill {
padding: 5px 11px;
radius: 999px;
background: #162235;
border-width: 1px;
border-color: #2A4B7C;
color: #7DD3FC;
font: inter-semibold;
font-size: 12px;
}
.toolbar {
width: 100%;
padding: 10px 12px;
radius: 10px;
background: #141925;
border-width: 1px;
border-color: #252E42;
gap: 8px;
wrap: true;
align-items: center;
}
TextInput.search-box {
grow: 1;
min-width: 220px;
padding: 7px 11px;
radius: 7px;
background: #0E121B;
border-width: 1px;
border-color: #2B344A;
color: #F8FAFC;
font-size: 13px;
}
TextInput.search-box:focus {
border-color: #38BDF8;
}
Button.chip {
padding: 6px 10px;
radius: 7px;
background: #1C2334;
border-width: 1px;
border-color: #2E3850;
color: #CBD5E1;
font-size: 12px;
cursor: pointer;
transition: background 0.12s ease-out-quad;
}
Button.chip:hover {
background: #263047;
border-color: #38BDF8;
}
Button.chip:checked {
background: #2563EB;
border-color: #60A5FA;
color: #FFFFFF;
}
Button.mini {
padding: 6px 9px;
radius: 6px;
background: #1B2132;
border-width: 1px;
border-color: #2D364D;
color: #CBD5E1;
font-size: 12px;
cursor: pointer;
}
Button.mini:hover {
background: #263047;
border-color: #38BDF8;
}
/* ---- Table Styling ---- */
Table {
width: 100%;
grow: 1;
min-height: 0;
background: #111520;
border-width: 1px;
border-color: #262E42;
radius: 10px;
}
.table-header {
background: #171D2B;
border-width: 0px 0px 1px 0px;
border-color: #2B344A;
}
.table-header-cell {
border-width: 0px 1px 0px 0px;
border-color: #252E42;
}
.table-header-btn {
font: inter-semibold;
font-size: 12px;
color: #CBD5E1;
}
.table-header-btn:hover {
background: #222B40;
color: #F8FAFC;
}
.table-resize-handle:hover {
background: #38BDF888;
}
.table-row {
background: #111520;
border-width: 0px 0px 1px 0px;
border-color: #1B2130;
}
.table-row.alt {
background: #141926;
}
.table-row:hover {
background: #1C263B;
}
.table-row:checked {
background: #1D4ED8;
color: #FFFFFF;
}
/* ---- Custom Cell Widgets ---- */
.status-pill {
padding: 2px 8px;
radius: 999px;
font: inter-semibold;
font-size: 11px;
}
.status-online {
background: #064E3B;
color: #6EE7B7;
border-width: 1px;
border-color: #10B981;
}
.status-degraded {
background: #451A03;
color: #FCD34D;
border-width: 1px;
border-color: #F59E0B;
}
.status-offline {
background: #4C0519;
color: #FDA4AF;
border-width: 1px;
border-color: #F43F5E;
}
.cpu-cell {
width: 100%;
gap: 8px;
align-items: center;
}
.cpu-track {
grow: 1;
min-width: 40px;
height: 7px;
radius: 4px;
background: #1F273B;
overflow: hidden;
}
.cpu-fill {
height: 100%;
radius: 4px;
}
.cpu-text {
min-width: 34px;
font-size: 12px;
color: #CBD5E1;
text-align: end;
}
/* ---- Inspector / Status Footer ---- */
.footer-bar {
width: 100%;
padding: 9px 14px;
radius: 9px;
background: #141925;
border-width: 1px;
border-color: #252E42;
gap: 14px;
wrap: true;
align-items: center;
justify: space-between;
}
.status-accent {
font: inter-semibold;
font-size: 12px;
color: #7DD3FC;
}
.muted {
font-size: 12px;
color: #94A3B8;
}
)zs";
static constexpr const char *kMarkup = R"zm(
VStack.page {
HStack.header-bar {
VStack gap="3px" {
Text.title "Virtualized Data Table (10,000 Rows)"
Text.subtitle wrap="true" "Click column headers to sort, drag column edges to resize, scroll horizontally to test sticky header sync, or use Up/Down/Home/End/Enter."
}
Text.count-pill@match-pill "10,000 / 10,000 rows"
}
HStack.toolbar {
TextInput.search-box@search placeholder="Filter by ID, service, region, team, or notes..."
Button.chip@btn-st-all "All"
Button.chip@btn-st-online "Online"
Button.chip@btn-st-degraded "Degraded"
Button.chip@btn-st-offline "Offline"
Button.mini@btn-density "Row: 32px"
Button.mini@btn-reset-cols "Reset Widths"
Button.mini@btn-top "Top"
Button.mini@btn-mid "#5,000"
Button.mini@btn-bottom "Bottom"
}
Table@data-table row-height="32" header-height="36" {
TableColumn title="ID" id="id" width="74" min-width="56" align="end" sortable="true"
TableColumn title="Service" id="service" width="200" min-width="110" align="start" sortable="true"
TableColumn title="Region" id="region" width="115" min-width="80" align="start" sortable="true"
TableColumn title="Status" id="status" width="115" min-width="90" align="center" sortable="true"
TableColumn title="CPU Load" id="cpu" width="155" min-width="110" align="start" sortable="true"
TableColumn title="Memory" id="mem" width="105" min-width="80" align="end" sortable="true"
TableColumn title="Latency" id="latency" width="105" min-width="80" align="end" sortable="true"
TableColumn title="Owner Team" id="owner" width="175" min-width="100" align="start" sortable="true"
TableColumn title="Notes" id="notes" width="240" min-width="120" align="start" sortable="false" resizable="true"
}
HStack.footer-bar {
Text.status-accent@inspector wrap="true" "Click a row to inspect (double-click or Enter to activate)."
Text.muted@viewport-stats "Materialized: --"
}
}
)zm";
namespace
{
enum class ServiceStatus : int
{
Online = 0,
Degraded = 1,
Offline = 2
};
const char *statusLabel(ServiceStatus s) noexcept
{
switch (s)
{
case ServiceStatus::Online: return "Online";
case ServiceStatus::Degraded: return "Degraded";
case ServiceStatus::Offline: return "Offline";
}
return "Online";
}
struct ServiceRow
{
int id{0};
std::string service;
std::string region;
ServiceStatus status{ServiceStatus::Online};
int cpuPct{0};
int memMb{0};
float latencyMs{0.0f};
std::string owner;
std::string notes;
};
std::vector<ServiceRow> buildDataset(int count)
{
static const char *kPrefixes[] = {
"auth", "billing", "render", "atlas", "search",
"gateway", "metrics", "ingest", "worker", "cache"};
static const char *kSuffixes[] = {
"api", "edge", "node", "proxy", "sync", "core", "hub", "daemon"};
static const char *kRegions[] = {
"eu-south-1", "eu-west-1", "us-east-1", "us-west-2", "ap-north-1", "sa-east-1"};
static const char *kTeams[] = {
"Core Runtime", "Platform Infra", "Graphics & UI", "Data Pipeline", "Edge Security", "Observability"};
static const char *kNotes[] = {
"Nominal throughput across shard group",
"Scheduled rolling restart pending",
"Autoscaler holding steady headroom",
"Elevated p99 tail latency observed",
"Read replica synced within 2 ms",
"Canary build v2.14 active on 10% traffic"};
std::vector<ServiceRow> rows;
rows.reserve(static_cast<size_t>(count));
for (int i = 0; i < count; ++i)
{
const uint32_t h = static_cast<uint32_t>(i * 2654435761u);
const int statusRoll = static_cast<int>(h % 100u);
ServiceStatus st = ServiceStatus::Online;
if (statusRoll >= 92)
st = ServiceStatus::Offline;
else if (statusRoll >= 76)
st = ServiceStatus::Degraded;
const int cpu = (st == ServiceStatus::Offline)
? 0
: static_cast<int>(((h >> 8) % 97u) + 3u);
const int mem = static_cast<int>(128u + ((h >> 12) % 3968u));
const float lat = (st == ServiceStatus::Offline)
? 0.0f
: (1.2f + static_cast<float>((h >> 16) % 420u) * 0.45f);
ServiceRow r;
r.id = i + 1;
r.service = std::string(kPrefixes[i % 10]) + "-" +
kSuffixes[(i / 10) % 8] + "-" + std::to_string((i % 99) + 1);
r.region = kRegions[(h >> 4) % 6u];
r.status = st;
r.cpuPct = cpu;
r.memMb = mem;
r.latencyMs = lat;
r.owner = kTeams[(h >> 6) % 6u];
r.notes = kNotes[(h >> 10) % 6u];
rows.push_back(std::move(r));
}
return rows;
}
std::string toLowerCopy(std::string_view s)
{
std::string out(s);
std::transform(out.begin(), out.end(), out.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return out;
}
struct TableDemoState
{
std::vector<ServiceRow> records;
std::vector<int> visible;
std::string queryLower;
int statusFilter{-1}; // -1=All, 0=Online, 1=Degraded, 2=Offline
int sortCol{-1};
UI::SortDirection sortDir{UI::SortDirection::None};
bool compactRows{false};
int lastFirstVis{-2};
int lastLastVis{-2};
int lastLiveNodes{-1};
int lastTotalVis{-1};
TableDemoState() : records(buildDataset(10000))
{
visible.resize(records.size());
for (size_t i = 0; i < records.size(); ++i)
visible[i] = static_cast<int>(i);
}
};
} // namespace
int main()
{
cfg.title = "ZenitUI 16 — Virtualized Data Table (10,000 Rows)";
cfg.width = 1140;
cfg.height = 720;
cfg.minWidth = 560;
cfg.minHeight = 460;
auto state = std::make_shared<TableDemoState>();
std::weak_ptr<UI::Table> tableWeak;
std::weak_ptr<UI::Text> viewportStatsWeak;
return ZenitExample::runApp(
cfg,
[state, &tableWeak, &viewportStatsWeak](UIContext &ctx, IBackend &) -> std::shared_ptr<Layout>
{
ZenitExample::loadDefaultFonts(ctx);
ZMarkup::loadStyleString(kStyle, ctx.theme, "16_data_table.zstyle",
&styleSink, false, &ctx.markupRegistry());
for (const auto &d : styleSink.diagnostics())
std::fprintf(stderr, "[16_data_table][zstyle] %s\n", d.message.c_str());
auto ui = ZMarkup::build(kMarkup, ctx, &markupSink);
for (const auto &d : markupSink.diagnostics())
std::fprintf(stderr, "[16_data_table][zmarkup] %s\n", d.message.c_str());
ui.root()->retainObject(state);
ZMarkup::WeakUINode uiWeak = ui.weak();
auto tbl = ui.ref<UI::Table>("data-table");
tableWeak = tbl;
viewportStatsWeak = ui.ref<UI::Text>("viewport-stats");
auto syncFilterChips = [uiWeak, state]()
{
auto locked = uiWeak.lock();
if (!locked)
return;
if (auto b = locked->ref<UI::Button>("btn-st-all"))
b->setChecked(state->statusFilter == -1);
if (auto b = locked->ref<UI::Button>("btn-st-online"))
b->setChecked(state->statusFilter == static_cast<int>(ServiceStatus::Online));
if (auto b = locked->ref<UI::Button>("btn-st-degraded"))
b->setChecked(state->statusFilter == static_cast<int>(ServiceStatus::Degraded));
if (auto b = locked->ref<UI::Button>("btn-st-offline"))
b->setChecked(state->statusFilter == static_cast<int>(ServiceStatus::Offline));
if (auto b = locked->ref<UI::Button>("btn-density"))
b->setText(state->compactRows ? "Row: 26px" : "Row: 32px");
};
auto applyFilterAndSort = [uiWeak, state, tableWeak]()
{
state->visible.clear();
state->visible.reserve(state->records.size());
for (size_t i = 0; i < state->records.size(); ++i)
{
const auto &r = state->records[i];
if (state->statusFilter >= 0 && static_cast<int>(r.status) != state->statusFilter)
continue;
if (!state->queryLower.empty())
{
std::string hay = toLowerCopy(
std::to_string(r.id) + " " + r.service + " " + r.region + " " +
statusLabel(r.status) + " " + r.owner + " " + r.notes);
if (hay.find(state->queryLower) == std::string::npos)
continue;
}
state->visible.push_back(static_cast<int>(i));
}
if (state->sortCol >= 0 && state->sortDir != UI::SortDirection::None)
{
const int col = state->sortCol;
const bool desc = (state->sortDir == UI::SortDirection::Descending);
std::stable_sort(
state->visible.begin(), state->visible.end(),
[&](int aIdx, int bIdx) -> bool
{
const auto &a = state->records[static_cast<size_t>(aIdx)];
const auto &b = state->records[static_cast<size_t>(bIdx)];
int cmp = 0;
switch (col)
{
case 0: cmp = (a.id < b.id) ? -1 : (a.id > b.id ? 1 : 0); break;
case 1: cmp = a.service.compare(b.service); break;
case 2: cmp = a.region.compare(b.region); break;
case 3: cmp = static_cast<int>(a.status) - static_cast<int>(b.status); break;
case 4: cmp = a.cpuPct - b.cpuPct; break;
case 5: cmp = a.memMb - b.memMb; break;
case 6: cmp = (a.latencyMs < b.latencyMs) ? -1 : (a.latencyMs > b.latencyMs ? 1 : 0); break;
case 7: cmp = a.owner.compare(b.owner); break;
default: break;
}
return desc ? (cmp > 0) : (cmp < 0);
});
}
if (auto t = tableWeak.lock())
{
t->clearSelection(false);
t->setRowCount(static_cast<int>(state->visible.size()));
t->refreshRows();
}
if (auto locked = uiWeak.lock())
{
locked->setTextRef(
"match-pill",
std::to_string(state->visible.size()) + " / " +
std::to_string(state->records.size()) + " rows");
}
};
if (tbl)
{
// Zero-copy text provider for standard text columns
tbl->setCellTextProvider([state](int row, int col) -> std::string
{
if (row < 0 || row >= static_cast<int>(state->visible.size()))
return {};
const auto &r = state->records[static_cast<size_t>(state->visible[static_cast<size_t>(row)])];
char buf[32];
switch (col)
{
case 0: return "#" + std::to_string(r.id);
case 1: return r.service;
case 2: return r.region;
case 3: return statusLabel(r.status);
case 4: return std::to_string(r.cpuPct) + "%";
case 5: return std::to_string(r.memMb) + " MB";
case 6:
if (r.status == ServiceStatus::Offline)
return "--";
std::snprintf(buf, sizeof(buf), "%.1f ms", r.latencyMs);
return buf;
case 7: return r.owner;
case 8: return r.notes;
default: return {};
}
});
// Custom widget cells for Status (col 3) and CPU Load gauge (col 4)
tbl->setCellFactory([state](int row, int col) -> std::shared_ptr<Layout>
{
if (row < 0 || row >= static_cast<int>(state->visible.size()))
return nullptr;
const auto &r = state->records[static_cast<size_t>(state->visible[static_cast<size_t>(row)])];
if (col == 3)
{
auto pill = UI::Text::create(statusLabel(r.status));
pill->setInteractive(false);
pill->addClass("status-pill");
if (r.status == ServiceStatus::Online)
pill->addClass("status-online");
else if (r.status == ServiceStatus::Degraded)
pill->addClass("status-degraded");
else
pill->addClass("status-offline");
return pill;
}
if (col == 4)
{
auto wrap = UI::HStack();
wrap->setInteractive(false);
wrap->addClass("cpu-cell");
auto track = UI::Box();
track->setInteractive(false);
track->addClass("cpu-track");
auto fill = UI::Box();
fill->setInteractive(false);
fill->addClass("cpu-fill");
fill->getInlineBase().width = Percent(static_cast<float>(std::clamp(r.cpuPct, 0, 100)));
fill->getInlineBase().background =
(r.cpuPct >= 85) ? Color{244, 63, 94, 255}
: ((r.cpuPct >= 65) ? Color{245, 158, 11, 255}
: Color{56, 189, 248, 255});
track->addChild(fill);
auto lbl = UI::Text::create(std::to_string(r.cpuPct) + "%");
lbl->setInteractive(false);
lbl->addClass("cpu-text");
wrap->addChild(track);
wrap->addChild(lbl);
return wrap;
}
return nullptr;
});
tbl->onSortChanged = [state, applyFilterAndSort, uiWeak](int col, UI::SortDirection dir)
{
state->sortCol = col;
state->sortDir = dir;
applyFilterAndSort();
if (auto locked = uiWeak.lock())
{
const char *dirName = (dir == UI::SortDirection::Ascending)
? "ASC"
: ((dir == UI::SortDirection::Descending) ? "DESC" : "NONE");
locked->setTextRef(
"inspector",
(col < 0) ? "Sort cleared (original ID order)."
: ("Sorted column #" + std::to_string(col + 1) + " (" + dirName + ")."));
}
};
tbl->onColumnResized = [uiWeak, tableWeak](int col, float width)
{
if (auto locked = uiWeak.lock())
{
std::string name = "Col " + std::to_string(col + 1);
if (auto t = tableWeak.lock(); t && col >= 0 && col < t->columnCount())
name = t->columns()[static_cast<size_t>(col)].title;
locked->setTextRef(
"inspector",
"Resized '" + name + "' -> " + std::to_string(static_cast<int>(std::lround(width))) + " px");
}
};
auto describeRow = [state](int row, const char *verb) -> std::string
{
if (row < 0 || row >= static_cast<int>(state->visible.size()))
return "No row selected.";
const auto &r = state->records[static_cast<size_t>(state->visible[static_cast<size_t>(row)])];
char buf[192];
std::snprintf(buf, sizeof(buf),
"%s #%d %s [%s | %s] — CPU %d%%, RAM %d MB, %.1f ms (%s)",
verb, r.id, r.service.c_str(), r.region.c_str(),
statusLabel(r.status), r.cpuPct, r.memMb, r.latencyMs, r.owner.c_str());
return buf;
};
tbl->onSelectionChanged = [uiWeak, describeRow](int row)
{
if (auto locked = uiWeak.lock())
locked->setTextRef("inspector", describeRow(row, "Selected"));
};
tbl->onRowActivated = [uiWeak, describeRow](int row)
{
if (auto locked = uiWeak.lock())
locked->setTextRef("inspector", describeRow(row, "ACTIVATED"));
};
}
// ---- Toolbar controls ----
ui.onTextChangedRef("search", [state, applyFilterAndSort](const std::string &q)
{
state->queryLower = toLowerCopy(q);
applyFilterAndSort();
});
auto setStatusFilter = [state, syncFilterChips, applyFilterAndSort](int f)
{
state->statusFilter = f;
syncFilterChips();
applyFilterAndSort();
};
ui.onClickRef("btn-st-all", [setStatusFilter]() { setStatusFilter(-1); });
ui.onClickRef("btn-st-online", [setStatusFilter]() { setStatusFilter(static_cast<int>(ServiceStatus::Online)); });
ui.onClickRef("btn-st-degraded", [setStatusFilter]() { setStatusFilter(static_cast<int>(ServiceStatus::Degraded)); });
ui.onClickRef("btn-st-offline", [setStatusFilter]() { setStatusFilter(static_cast<int>(ServiceStatus::Offline)); });
ui.onClickRef("btn-density", [state, tableWeak, syncFilterChips]()
{
state->compactRows = !state->compactRows;
if (auto t = tableWeak.lock())
t->setRowHeight(state->compactRows ? 26.0f : 32.0f);
syncFilterChips();
});
ui.onClickRef("btn-reset-cols", [tableWeak, uiWeak]()
{
static constexpr float kDefaultWidths[9] = {
74.0f, 200.0f, 115.0f, 115.0f, 155.0f, 105.0f, 105.0f, 175.0f, 240.0f};
if (auto t = tableWeak.lock())
{
for (int i = 0; i < 9 && i < t->columnCount(); ++i)
t->setColumnWidth(i, kDefaultWidths[i], false);
}
if (auto locked = uiWeak.lock())
locked->setTextRef("inspector", "Restored default column widths (total 1,284 px).");
});
ui.onClickRef("btn-top", [tableWeak]()
{
if (auto t = tableWeak.lock())
t->scrollToRow(0);
});
ui.onClickRef("btn-mid", [tableWeak, state]()
{
if (auto t = tableWeak.lock(); t && !state->visible.empty())
t->scrollToRow(std::min(4999, static_cast<int>(state->visible.size()) - 1));
});
ui.onClickRef("btn-bottom", [tableWeak, state]()
{
if (auto t = tableWeak.lock(); t && !state->visible.empty())
t->scrollToRow(static_cast<int>(state->visible.size()) - 1);
});
syncFilterChips();
applyFilterAndSort();
return ui.root();
},
[state, &tableWeak, &viewportStatsWeak](UIContext &, float)
{
auto t = tableWeak.lock();
auto lbl = viewportStatsWeak.lock();
if (!t || !lbl || !t->body())
return;
const int total = t->getRowCount();
const int first = t->body()->getFirstVisibleItem();
const int last = t->body()->getLastVisibleItem();
const int live = static_cast<int>(t->body()->children.size());
if (first == state->lastFirstVis && last == state->lastLastVis &&
live == state->lastLiveNodes && total == state->lastTotalVis)
return;
state->lastFirstVis = first;
state->lastLastVis = last;
state->lastLiveNodes = live;
state->lastTotalVis = total;
if (total <= 0 || first < 0)
{
lbl->setText("Materialized: 0 rows");
return;
}
lbl->setText("Visible: #" + std::to_string(first + 1) + " - #" +
std::to_string(last + 1) + " (" + std::to_string(live) +
" live nodes / " + std::to_string(total) + ")");
});
}
Sink that accumulates diagnostics in insertion order.
Definition Diagnostics.hpp:151
Unified window, frame-loop, and subsystem host for interchangeable backends.
Definition Backend.hpp:49
static std::shared_ptr< Text > create(Args &&...args)
Definition Layout.hpp:1410
A push button.
Definition Button.hpp:32
Virtualized data table with sticky header, resizable columns, clickable column sorting,...
Definition Table.hpp:80
A read-only text node.
Definition Text.hpp:32
Non-owning handle to a UINode, safe to capture inside child callbacks.
Definition ZMarkup.hpp:757
SortDirection
Active sort order of a Table column.
Definition Table.hpp:28
std::shared_ptr< Layout > HStack(std::initializer_list< std::shared_ptr< Layout > > children={})
Create a horizontal-flow container (LayoutType::Horizontal).
Definition Layouts.hpp:41
std::shared_ptr< Layout > Box(std::initializer_list< std::shared_ptr< Layout > > children={})
Generic Flexbox container modified via CSS (direction).
Definition Layouts.hpp:53
bool loadStyleString(std::string_view src, Theme &theme, const std::string &fileName="<string>", DiagnosticSink *sink=nullptr, bool strict=false, const Registry *registry=nullptr)
Parse src and apply it to theme.
8-bit-per-channel RGBA color, non-premultiplied.
Definition CoreTypes.hpp:78
Per-instance UI context: backends, theme, text engine, frame state, and routing.
Definition UIContext.hpp:725
ZMarkup::Registry & markupRegistry()
Return this context's isolated ZMarkup::Registry, lazily initialized with built-in widgets.
Theme theme
Per-context stylesheet (rules, keyframes, and :root style).
Definition UIContext.hpp:911
Backend-agnostic window and graphics-context creation parameters.
Definition Backend.hpp:31