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

Example from examples/07_dynamic_lists/.

Example from examples/07_dynamic_lists/.

#include "ExampleHost.hpp"
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
using namespace ZenitUI;
static constexpr const char *kStyle = R"zs(
:root {
font: inter;
font-size: 14px;
letter-spacing: 0px;
color: #E5E7EB;
}
.page {
width: 100%;
height: 100%;
background: #0D1017;
padding: 24px;
overflow-x: hidden;
overflow-y: auto;
}
.shell {
width: 100%;
max-width: 780px;
margin: auto;
gap: 16px;
}
.title {
font: inter-bold;
font-size: 24px;
color: #F8FAFC;
}
.muted {
font-size: 13px;
color: #94A3B8;
}
.card {
width: 100%;
background: #151924;
border-width: 1px;
border-color: #262E42;
radius: 12px;
padding: 18px;
gap: 14px;
}
.badge {
padding: 4px 10px;
radius: 999px;
background: #1E293B;
border-width: 1px;
border-color: #334155;
color: #7DD3FC;
font-size: 12px;
}
TextInput.task-input {
flex: 1;
min-width: 180px;
background: #10141F;
border-width: 1px;
border-color: #2B3347;
radius: 8px;
padding: 10px 12px;
color: #F8FAFC;
}
TextInput.task-input:focus {
border-color: #38BDF8;
}
Button.btn {
padding: 9px 16px;
radius: 8px;
background: #2563EB;
color: #FFFFFF;
cursor: pointer;
transition-time: 0.12;
}
Button.btn:hover {
background: #3B82F6;
}
Button.filter-btn {
padding: 7px 13px;
radius: 8px;
background: #1B2130;
border-width: 1px;
border-color: #2C354A;
color: #94A3B8;
cursor: pointer;
transition-time: 0.1;
}
Button.filter-btn:hover {
color: #F8FAFC;
border-color: #475569;
}
Button.filter-btn.active {
background: #1E3A5F;
border-color: #38BDF8;
color: #7DD3FC;
}
Button.btn-danger {
padding: 7px 13px;
radius: 8px;
background: #451A1A;
border-width: 1px;
border-color: #7F1D1D;
color: #FCA5A5;
cursor: pointer;
transition-time: 0.1;
}
Button.btn-danger:hover {
background: #7F1D1D;
color: #FFFFFF;
}
.task-row {
width: 100%;
padding: 11px 14px;
radius: 9px;
background: #10141F;
border-width: 1px;
border-color: #252D40;
gap: 12px;
align-items: center;
transition-time: 0.12;
}
.task-row:hover {
border-color: #384461;
}
.task-row.done {
opacity: 0.6;
background: #0E121B;
}
.task-title {
flex: 1;
min-width: 0px;
color: #F1F5F9;
}
.task-row.done .task-title {
color: #64748B;
}
Button.prio-btn {
padding: 4px 10px;
radius: 999px;
font-size: 12px;
cursor: pointer;
background: #1E293B;
color: #94A3B8;
}
Button.prio-btn.prio-med {
background: #422006;
color: #FBBF24;
}
Button.prio-btn.prio-high {
background: #450A0A;
color: #F87171;
}
Button.icon-btn {
padding: 5px 9px;
radius: 6px;
background: #1E2436;
color: #CBD5E1;
font-size: 12px;
cursor: pointer;
}
Button.icon-btn:hover {
background: #2C354D;
color: #FFFFFF;
}
Button.icon-btn.del:hover {
background: #DC2626;
}
.empty-state {
width: 100%;
padding: 28px 16px;
radius: 10px;
background: #10141F;
border-width: 1px;
border-color: #252D40;
align-items: center;
gap: 6px;
}
)zs";
static constexpr const char *kTaskRowPrefab = R"zm(
HStack.task-row {
Checkbox@done checked="false"
VStack flex="1" min-width="0px" gap="2px" {
Text.task-title@title wrap="true" ""
Text.muted@meta wrap="true" ""
}
Button.prio-btn@prio "Low"
Button.icon-btn@up "Up"
Button.icon-btn.del@del "x"
}
)zm";
static constexpr const char *kMarkup = R"zm(
ScrollView.page {
VStack.shell {
VStack width="100%" gap="4px" {
Text.title wrap="true" "Dynamic Lists — If & Keyed Each"
Text.muted wrap="true" "Declarative conditional blocks and keyed reconciliation that reuses existing nodes on reorder and edit."
}
VStack.card {
HStack width="100%" gap="10px" wrap="true" align-items="center" {
TextInput.task-input@newTask placeholder="Add a new task and press Enter..."
Button.btn@addBtn "+ Add Task"
}
HStack width="100%" justify="space-between" align-items="center" wrap="true" gap="10px" {
HStack gap="8px" wrap="true" align-items="center" {
Button.filter-btn.active@fAll "All"
Button.filter-btn@fActive "Active"
Button.filter-btn@fDone "Completed"
Button.filter-btn@sortBtn "Sort by Priority"
}
If@hasCompleted {
Button.btn-danger@clearDone "Clear Completed"
}
}
HStack width="100%" gap="8px" wrap="true" align-items="center" {
Text.badge@statsTotal "Tasks: 0"
Text.badge@statsCreated "Nodes Created: 0"
Text.badge@statsUpdates "In-Place Updates: 0"
}
}
VStack.card {
VStack width="100%" gap="8px" {
Each@tasks prefab="TaskRow" {
VStack.empty-state {
Text "Nothing to show here"
Text.muted wrap="true" "This fallback block is declared directly inside Each@tasks and mounts automatically when the list is empty."
}
}
}
}
}
}
)zm";
namespace
{
enum class FilterMode
{
All,
Active,
Completed
};
struct Task
{
int id{0};
std::string title;
int priority{0}; // 0 = Low, 1 = Med, 2 = High
bool done{false};
bool operator==(const Task &) const = default;
};
struct TaskAppState
{
std::vector<Task> all;
int nextId{1};
FilterMode filter{FilterMode::All};
int nodesCreated{0};
int updatesApplied{0};
Bindable<bool> hasCompleted{false};
};
const char *priorityLabel(int p)
{
switch (p)
{
case 2:
return "High";
case 1:
return "Med";
default:
return "Low";
}
}
} // namespace
int main()
{
cfg.title = "ZenitUI 07 — Dynamic Lists (If & Keyed Each)";
cfg.width = 900;
cfg.height = 700;
cfg.minWidth = 440;
cfg.minHeight = 460;
return ZenitExample::runApp(cfg, [](UIContext &ctx, IBackend &) -> std::shared_ptr<Layout>
{
ZenitExample::loadDefaultFonts(ctx);
ZMarkup::registerPrefab(ctx, "TaskRow", kTaskRowPrefab);
auto ui = ZMarkup::build(kMarkup, ctx);
auto state = std::make_shared<TaskAppState>();
ui.root()->retainObject(state);
// Non-owning handle safe to capture in child callbacks without cycles.
ZMarkup::WeakUINode uiWeak = ui.weak();
auto syncView = [state, uiWeak]() {
std::vector<Task> filtered;
filtered.reserve(state->all.size());
bool anyDone = false;
size_t activeCount = 0;
for (const auto &t : state->all)
{
if (t.done)
anyDone = true;
else
++activeCount;
if (state->filter == FilterMode::All ||
(state->filter == FilterMode::Active && !t.done) ||
(state->filter == FilterMode::Completed && t.done))
{
filtered.push_back(t);
}
}
state->hasCompleted.set(anyDone);
state->visibleTasks.set(std::move(filtered));
if (auto locked = uiWeak.lock())
{
locked->setTextRef("statsTotal",
"Tasks: " + std::to_string(state->all.size()) +
" (" + std::to_string(activeCount) + " active)");
locked->setTextRef("statsCreated",
"Nodes Created: " + std::to_string(state->nodesCreated));
locked->setTextRef("statsUpdates",
"In-Place Updates: " + std::to_string(state->updatesApplied));
locked->toggleClassRef("fAll", "active", state->filter == FilterMode::All);
locked->toggleClassRef("fActive", "active", state->filter == FilterMode::Active);
locked->toggleClassRef("fDone", "active", state->filter == FilterMode::Completed);
}
};
// 1. Bind conditional Clear Completed button to Bindable<bool>.
ui.bindCondition("hasCompleted", state->hasCompleted, true);
// 2. Bind keyed Each list: onCreate runs once per unique task.id; onUpdate refreshes in place.
ui.bindEachKeyed(
"tasks",
state->visibleTasks,
[](const Task &t) { return t.id; },
[state, syncView](ZMarkup::UINode &row, const Task &t) {
++state->nodesCreated;
const int taskId = t.id;
row.onToggleRef("done", [state, taskId, syncView](bool checked) {
for (auto &item : state->all)
{
if (item.id == taskId)
{
item.done = checked;
break;
}
}
syncView();
});
row.onClickRef("prio", [state, taskId, syncView]() {
for (auto &item : state->all)
{
if (item.id == taskId)
{
item.priority = (item.priority + 1) % 3;
break;
}
}
syncView();
});
row.onClickRef("up", [state, taskId, syncView]() {
for (size_t i = 1; i < state->all.size(); ++i)
{
if (state->all[i].id == taskId)
{
std::swap(state->all[i], state->all[i - 1]);
break;
}
}
syncView();
});
row.onClickRef("del", [state, taskId, syncView]() {
auto &v = state->all;
v.erase(std::remove_if(v.begin(), v.end(),
[taskId](const Task &x) { return x.id == taskId; }),
v.end());
syncView();
});
},
[state](ZMarkup::UINode &row, const Task &t, size_t visibleIndex) {
++state->updatesApplied;
row.setTextRef("title", t.title);
row.setTextRef("meta",
"Key #" + std::to_string(t.id) +
" | Row index " + std::to_string(visibleIndex));
row.setButtonTextRef("prio", priorityLabel(t.priority));
row.toggleClassRef("prio", "prio-med", t.priority == 1);
row.toggleClassRef("prio", "prio-high", t.priority == 2);
if (t.done)
row.root()->addClass("done");
else
row.root()->removeClass("done");
if (auto cb = row.ref<UI::Checkbox>("done"))
cb->setChecked(t.done);
},
false);
auto addTask = [state, uiWeak, syncView]() {
auto locked = uiWeak.lock();
if (!locked)
return;
auto input = locked->ref<UI::TextInput>("newTask");
if (!input)
return;
std::string txt = input->getText();
if (txt.empty())
return;
state->all.push_back({state->nextId++, std::move(txt), 1, false});
input->setText("");
syncView();
};
if (auto input = ui.ref<UI::TextInput>("newTask"))
input->onSubmit = [addTask](const std::string &) { addTask(); };
ui.onClickRef("addBtn", addTask);
ui.onClickRef("fAll", [state, syncView]() {
state->filter = FilterMode::All;
syncView();
});
ui.onClickRef("fActive", [state, syncView]() {
state->filter = FilterMode::Active;
syncView();
});
ui.onClickRef("fDone", [state, syncView]() {
state->filter = FilterMode::Completed;
syncView();
});
ui.onClickRef("sortBtn", [state, syncView]() {
std::stable_sort(state->all.begin(), state->all.end(),
[](const Task &a, const Task &b) {
if (a.done != b.done)
return !a.done;
return a.priority > b.priority;
});
syncView();
});
ui.onClickRef("clearDone", [state, syncView]() {
auto &v = state->all;
v.erase(std::remove_if(v.begin(), v.end(),
[](const Task &x) { return x.done; }),
v.end());
syncView();
});
// Initial seed data.
state->all = {
{state->nextId++, "Verify keyed reconciliation preserves Layout nodes", 2, false},
{state->nextId++, "Switch filters to inspect empty Each fallback block", 1, false},
{state->nextId++, "Reorder rows with Up and watch Nodes Created stay constant", 2, false},
{state->nextId++, "Inspect If@hasCompleted toggle on Clear Completed", 0, true},
};
syncView();
return ui.root(); });
}
Observable single-value container.
Definition Bindable.hpp:44
Unified window, frame-loop, and subsystem host for interchangeable backends.
Definition Backend.hpp:49
A checkbox with a custom-painted check mark.
Definition Checkbox.hpp:29
A single-line text editor.
Definition TextInput.hpp:27
const std::string & getText() const
Current content.
Definition TextInput.hpp:38
Root handle returned by build / instantiate: root node + build context + wiring helpers.
Definition ZMarkup.hpp:331
std::shared_ptr< T > ref(const std::string &name) const
Look up a live node by @ref.
Definition ZMarkup.hpp:363
Non-owning handle to a UINode, safe to capture inside child callbacks.
Definition ZMarkup.hpp:757
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.
Per-instance UI context: backends, theme, text engine, frame state, and routing.
Definition UIContext.hpp:725
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