ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
Style.hpp
Go to the documentation of this file.
1#pragma once
2
20
21#include "Common.hpp"
22
23#include "Easing.hpp"
24#include "Unit.hpp"
25#include "UIEnums.hpp"
26
27#include <ostream>
28#include <atomic>
29#include <cstdint>
30#include <initializer_list>
31
32namespace ZenitUI
33{
37
47 template <typename T>
48 struct Opt
49 {
50 T value{};
51 bool is_set{false};
52
53 Opt() = default;
54 Opt(const T &v) : value(v), is_set(true) {}
55 Opt(T &&v) : value(std::move(v)), is_set(true) {}
56 Opt &operator=(const T &v)
57 {
58 value = v;
59 is_set = true;
60 return *this;
61 }
62 Opt &operator=(T &&v)
63 {
64 value = std::move(v);
65 is_set = true;
66 return *this;
67 }
68 void reset() { is_set = false; }
69 T get_or(const T &fallback) const { return is_set ? value : fallback; }
70 };
71
80 class SharedPropMap
81 {
82 public:
83 using Map = std::unordered_map<std::string, std::string>;
84 using const_iterator = Map::const_iterator;
85
86 private:
87 struct Data
88 {
89 mutable std::atomic<uint32_t> refCount{1};
90 uint64_t id{0};
91 Map map;
92 };
93
94 Data *data_{nullptr};
95
96 static uint64_t nextId() noexcept
97 {
98 static std::atomic<uint64_t> counter{1};
99 return counter.fetch_add(1u, std::memory_order_relaxed);
100 }
101
102 static const Map &emptyMap() noexcept
103 {
104 static const Map kEmpty{};
105 return kEmpty;
106 }
107
108 static void release(Data *p) noexcept
109 {
110 if (p && p->refCount.fetch_sub(1u, std::memory_order_acq_rel) == 1u)
111 delete p;
112 }
113
114 void detachAndBump()
115 {
116 if (!data_)
117 {
118 data_ = new Data();
119 data_->id = nextId();
120 return;
121 }
122 if (data_->refCount.load(std::memory_order_acquire) > 1u)
123 {
124 auto *copy = new Data();
125 copy->id = nextId();
126 copy->map = data_->map;
127 release(data_);
128 data_ = copy;
129 return;
130 }
131 data_->id = nextId();
132 }
133
134 public:
135 SharedPropMap() noexcept = default;
136 SharedPropMap(const Map &m)
137 {
138 if (!m.empty())
139 {
140 data_ = new Data();
141 data_->id = nextId();
142 data_->map = m;
143 }
144 }
145 SharedPropMap(Map &&m)
146 {
147 if (!m.empty())
148 {
149 data_ = new Data();
150 data_->id = nextId();
151 data_->map = std::move(m);
152 }
153 }
154 SharedPropMap(const SharedPropMap &o) noexcept : data_(o.data_)
155 {
156 if (data_)
157 data_->refCount.fetch_add(1u, std::memory_order_relaxed);
158 }
159 SharedPropMap(SharedPropMap &&o) noexcept : data_(o.data_)
160 {
161 o.data_ = nullptr;
162 }
163 SharedPropMap &operator=(const SharedPropMap &o) noexcept
164 {
165 if (this == &o)
166 return *this;
167 Data *old = data_;
168 data_ = o.data_;
169 if (data_)
170 data_->refCount.fetch_add(1u, std::memory_order_relaxed);
171 release(old);
172 return *this;
173 }
174 SharedPropMap &operator=(SharedPropMap &&o) noexcept
175 {
176 if (this == &o)
177 return *this;
178 release(data_);
179 data_ = o.data_;
180 o.data_ = nullptr;
181 return *this;
182 }
183 SharedPropMap &operator=(const Map &m)
184 {
185 if (m.empty())
186 {
187 clear();
188 return *this;
189 }
190 detachAndBump();
191 data_->map = m;
192 return *this;
193 }
194 ~SharedPropMap() noexcept { release(data_); }
195
196 bool empty() const noexcept { return !data_ || data_->map.empty(); }
197 size_t size() const noexcept { return data_ ? data_->map.size() : 0u; }
198 uint64_t versionId() const noexcept { return empty() ? 0ULL : data_->id; }
199 bool sharesStorageWith(const SharedPropMap &o) const noexcept { return data_ == o.data_; }
200
201 const Map &asMap() const noexcept { return data_ ? data_->map : emptyMap(); }
202 operator const Map &() const noexcept { return asMap(); }
203
204 const_iterator begin() const noexcept { return asMap().begin(); }
205 const_iterator end() const noexcept { return asMap().end(); }
206 const_iterator cbegin() const noexcept { return asMap().cbegin(); }
207 const_iterator cend() const noexcept { return asMap().cend(); }
208
209 const_iterator find(const std::string &k) const { return asMap().find(k); }
210 size_t count(const std::string &k) const { return data_ ? data_->map.count(k) : 0u; }
211 bool contains(const std::string &k) const { return data_ && data_->map.find(k) != data_->map.end(); }
212 const std::string &at(const std::string &k) const { return asMap().at(k); }
213
214 std::string &operator[](const std::string &k)
215 {
216 detachAndBump();
217 return data_->map[k];
218 }
219 std::string &operator[](std::string &&k)
220 {
221 detachAndBump();
222 return data_->map[std::move(k)];
223 }
224
225 template <typename... Args>
226 auto emplace(Args &&...args)
227 {
228 detachAndBump();
229 return data_->map.emplace(std::forward<Args>(args)...);
230 }
231
232 template <typename V>
233 auto insert_or_assign(const std::string &k, V &&v)
234 {
235 detachAndBump();
236 return data_->map.insert_or_assign(k, std::forward<V>(v));
237 }
238
239 size_t erase(const std::string &k)
240 {
241 if (!data_ || data_->map.find(k) == data_->map.end())
242 return 0u;
243 detachAndBump();
244 const size_t n = data_->map.erase(k);
245 if (data_->map.empty())
246 {
247 release(data_);
248 data_ = nullptr;
249 }
250 return n;
251 }
252
253 void clear() noexcept
254 {
255 release(data_);
256 data_ = nullptr;
257 }
258
259 void mergeFrom(const SharedPropMap &other)
260 {
261 if (other.empty())
262 return;
263 if (empty())
264 {
265 *this = other;
266 return;
267 }
268 if (data_ == other.data_)
269 return;
270 detachAndBump();
271 for (const auto &[k, v] : other.asMap())
272 data_->map[k] = v;
273 }
274
275 bool operator==(const SharedPropMap &o) const
276 {
277 if (data_ == o.data_)
278 return true;
279 if (empty() && o.empty())
280 return true;
281 return asMap() == o.asMap();
282 }
283 bool operator!=(const SharedPropMap &o) const { return !(*this == o); }
284 };
285
286 static_assert(sizeof(SharedPropMap) == sizeof(void *), "SharedPropMap must remain pointer-sized");
287
292 template <typename T>
293 class SharedVector
294 {
295 public:
296 using Vec = std::vector<T>;
297 using value_type = T;
298 using iterator = typename Vec::iterator;
299 using const_iterator = typename Vec::const_iterator;
300
301 private:
302 struct Data
303 {
304 mutable std::atomic<uint32_t> refCount{1};
305 Vec vec;
306 };
307
308 Data *data_{nullptr};
309
310 static const Vec &emptyVec() noexcept
311 {
312 static const Vec kEmpty{};
313 return kEmpty;
314 }
315
316 static Vec &emptyMutVec() noexcept
317 {
318 static Vec kEmpty{};
319 return kEmpty;
320 }
321
322 static void release(Data *p) noexcept
323 {
324 if (p && p->refCount.fetch_sub(1u, std::memory_order_acq_rel) == 1u)
325 delete p;
326 }
327
328 Vec &detach()
329 {
330 if (!data_)
331 {
332 data_ = new Data();
333 return data_->vec;
334 }
335 if (data_->refCount.load(std::memory_order_acquire) > 1u)
336 {
337 auto *copy = new Data();
338 copy->vec = data_->vec;
339 release(data_);
340 data_ = copy;
341 }
342 return data_->vec;
343 }
344
345 public:
346 SharedVector() noexcept = default;
347 SharedVector(const Vec &v)
348 {
349 if (!v.empty())
350 {
351 data_ = new Data();
352 data_->vec = v;
353 }
354 }
355 SharedVector(Vec &&v)
356 {
357 if (!v.empty())
358 {
359 data_ = new Data();
360 data_->vec = std::move(v);
361 }
362 }
363 SharedVector(std::initializer_list<T> init)
364 {
365 if (init.size() > 0)
366 {
367 data_ = new Data();
368 data_->vec.assign(init.begin(), init.end());
369 }
370 }
371 SharedVector(const SharedVector &o) noexcept : data_(o.data_)
372 {
373 if (data_)
374 data_->refCount.fetch_add(1u, std::memory_order_relaxed);
375 }
376 SharedVector(SharedVector &&o) noexcept : data_(o.data_)
377 {
378 o.data_ = nullptr;
379 }
380 SharedVector &operator=(const SharedVector &o) noexcept
381 {
382 if (this == &o)
383 return *this;
384 Data *old = data_;
385 data_ = o.data_;
386 if (data_)
387 data_->refCount.fetch_add(1u, std::memory_order_relaxed);
388 release(old);
389 return *this;
390 }
391 SharedVector &operator=(SharedVector &&o) noexcept
392 {
393 if (this == &o)
394 return *this;
395 release(data_);
396 data_ = o.data_;
397 o.data_ = nullptr;
398 return *this;
399 }
400 SharedVector &operator=(const Vec &v)
401 {
402 if (v.empty())
403 {
404 clear();
405 return *this;
406 }
407 detach() = v;
408 return *this;
409 }
410 SharedVector &operator=(Vec &&v)
411 {
412 if (v.empty())
413 {
414 clear();
415 return *this;
416 }
417 detach() = std::move(v);
418 return *this;
419 }
420 ~SharedVector() noexcept { release(data_); }
421
422 bool empty() const noexcept { return !data_ || data_->vec.empty(); }
423 size_t size() const noexcept { return data_ ? data_->vec.size() : 0u; }
424 bool sharesStorageWith(const SharedVector &o) const noexcept { return data_ == o.data_; }
425
426 const Vec &asVector() const noexcept { return data_ ? data_->vec : emptyVec(); }
427 operator const Vec &() const noexcept { return asVector(); }
428
429 const_iterator begin() const noexcept { return asVector().begin(); }
430 const_iterator end() const noexcept { return asVector().end(); }
431 const_iterator cbegin() const noexcept { return asVector().cbegin(); }
432 const_iterator cend() const noexcept { return asVector().cend(); }
433
434 iterator begin() { return empty() ? emptyMutVec().begin() : detach().begin(); }
435 iterator end() { return empty() ? emptyMutVec().end() : detach().end(); }
436
437 const T &operator[](size_t i) const { return asVector()[i]; }
438 T &operator[](size_t i) { return detach()[i]; }
439
440 const T &front() const { return asVector().front(); }
441 T &front() { return detach().front(); }
442
443 const T &back() const { return asVector().back(); }
444 T &back() { return detach().back(); }
445
446 void push_back(const T &v) { detach().push_back(v); }
447 void push_back(T &&v) { detach().push_back(std::move(v)); }
448
449 template <typename... Args>
450 T &emplace_back(Args &&...args)
451 {
452 return detach().emplace_back(std::forward<Args>(args)...);
453 }
454
455 void reserve(size_t n)
456 {
457 if (n > 0)
458 detach().reserve(n);
459 }
460
461 void clear() noexcept
462 {
463 release(data_);
464 data_ = nullptr;
465 }
466
467 bool operator==(const SharedVector &o) const
468 {
469 if (data_ == o.data_)
470 return true;
471 if (empty() && o.empty())
472 return true;
473 return asVector() == o.asVector();
474 }
475 bool operator!=(const SharedVector &o) const { return !(*this == o); }
476 };
477
485 struct Spacing
486 {
487 Value top{0.0f}, right{0.0f}, bottom{0.0f}, left{0.0f};
488
489 Spacing() = default;
490 Spacing(float all) : top(all), right(all), bottom(all), left(all) {}
491 Spacing(Value all) : top(all), right(all), bottom(all), left(all) {}
492 Spacing(Value v, Value h) : top(v), right(h), bottom(v), left(h) {}
493 Spacing(Value v, Value h, Value b) : top(v), right(h), bottom(b), left(h) {}
494 Spacing(Value t, Value r, Value b, Value l) : top(t), right(r), bottom(b), left(l) {}
495
496 bool operator==(const Spacing &o) const
497 {
498 return top == o.top && right == o.right && bottom == o.bottom && left == o.left;
499 }
500 bool operator!=(const Spacing &o) const { return !(*this == o); }
501 };
502
504 inline std::ostream &operator<<(std::ostream &os, const FontStack &stack)
505 {
506 os << "[";
507 for (size_t i = 0; i < stack.size(); ++i)
508 {
509 if (i)
510 os << ", ";
511 os << stack[i];
512 }
513 os << "]";
514 return os;
515 }
516
525 {
526 std::string prop;
527 float duration{0.15f};
528 TransitionFunction ease{TransitionFunction::Linear};
529 float delay{0.0f};
530 };
531
539 {
540 std::string name;
541 float duration{1.0f};
542 TransitionFunction ease{TransitionFunction::Linear};
543 float delay{0.0f};
544 int iterations{1};
545 bool alternate{false};
546 bool fillForwards{false};
547 bool blocksInput{false};
548 };
549
551 enum class Position : uint8_t
552 {
553 Static,
554 Relative,
555 Absolute
556 };
557
561 struct ZIndex
562 {
563 bool isAuto{true};
564 int value{0};
565
566 ZIndex() = default;
567 ZIndex(int v) : isAuto(false), value(v) {}
568
569 static ZIndex Auto() { return ZIndex(); }
570
571 bool operator==(const ZIndex &o) const { return isAuto == o.isAuto && value == o.value; }
572 bool operator!=(const ZIndex &o) const { return !(*this == o); }
573 };
574
578 enum class Overflow : uint8_t
579 {
580 Visible,
581 Hidden,
582 Scroll,
583 Auto
584 };
585
587 enum class WhiteSpace : uint8_t
588 {
589 Normal,
590 Nowrap
591 };
592
594 enum class TextOverflow : uint8_t
595 {
596 Visible,
597 Ellipsis
598 };
599
604 {
605 std::string name;
606 int16_t left{0}, top{0}, right{0}, bottom{0};
607
608 bool isNineSlice() const { return left || top || right || bottom; }
609
610 bool operator==(const TextureRef &o) const
611 {
612 return name == o.name &&
613 left == o.left && top == o.top &&
614 right == o.right && bottom == o.bottom;
615 }
616 bool operator!=(const TextureRef &o) const { return !(*this == o); }
617 };
618
627
632 {
633 enum class Kind : uint8_t
634 {
635 Tag,
636 Class,
637 Id,
639 };
640
643 {
644 std::string name;
645 Kind kind{Kind::Any};
646 std::vector<std::pair<Kind, std::string>> extras;
647
648 bool requireHover{false};
649 bool requirePressed{false};
650 bool requireFocus{false};
651 bool requireDisabled{false};
652 bool requireChecked{false};
653 };
654
656 struct Negation
657 {
658 std::vector<NegatedItem> items;
659 };
660
661 std::string name;
662 Kind kind{Kind::Tag};
664
665 std::vector<std::pair<Kind, std::string>> extras;
666 std::vector<Negation> negations;
667
668 bool requireHover{false};
669 bool requirePressed{false};
670 bool requireFocus{false};
671 bool requireDisabled{false};
672 bool requireChecked{false};
673 };
674
679 {
680 std::string name;
681 std::vector<std::string> args;
682
683 bool operator==(const FilterRef &o) const { return name == o.name && args == o.args; }
684 bool operator!=(const FilterRef &o) const { return !(*this == o); }
685 };
686
687 inline bool operator==(const std::vector<FilterRef> &a, const std::vector<FilterRef> &b)
688 {
689 if (a.size() != b.size())
690 return false;
691 for (size_t i = 0; i < a.size(); ++i)
692 if (!(a[i] == b[i]))
693 return false;
694 return true;
695 }
696 inline bool operator!=(const std::vector<FilterRef> &a, const std::vector<FilterRef> &b)
697 {
698 return !(a == b);
699 }
700
705 {
706 Value x{0.0f}, y{0.0f}, blur{0.0f};
707 Color color{Colors::Blank};
708 bool enabled{false};
709
710 bool operator==(const BoxShadow &o) const
711 {
712 return x == o.x && y == o.y && blur == o.blur && color == o.color && enabled == o.enabled;
713 }
714 bool operator!=(const BoxShadow &o) const { return !(*this == o); }
715 };
716
717 enum class Direction : uint8_t
718 {
719 Auto,
720 Row,
721 Column
722 };
723
726 {
727 enum class Kind : uint8_t
728 {
729 Auto,
730 Fixed,
732 };
733
734 Kind kind{Kind::Auto};
735 Value size{Value::autoSize()};
736 float fr{0.0f};
737
738 static GridTrack Auto() { return GridTrack{Kind::Auto, Value::autoSize(), 0.0f}; }
739 static GridTrack Fixed(Value v) { return GridTrack{Kind::Fixed, std::move(v), 0.0f}; }
740 static GridTrack Fr(float f) { return GridTrack{Kind::Flex, Value::autoSize(), f}; }
741
742 bool operator==(const GridTrack &o) const
743 {
744 return kind == o.kind && size == o.size && fr == o.fr;
745 }
746 bool operator!=(const GridTrack &o) const { return !(*this == o); }
747 };
748
749 inline bool operator==(const std::vector<GridTrack> &a, const std::vector<GridTrack> &b)
750 {
751 if (a.size() != b.size())
752 return false;
753 for (size_t i = 0; i < a.size(); ++i)
754 if (!(a[i] == b[i]))
755 return false;
756 return true;
757 }
758 inline bool operator!=(const std::vector<GridTrack> &a, const std::vector<GridTrack> &b)
759 {
760 return !(a == b);
761 }
762
765 {
766 int16_t start{0};
767 int16_t span{1};
768
769 static GridPlacement Auto(int sp = 1)
770 {
771 return GridPlacement{0, static_cast<int16_t>(sp < 1 ? 1 : sp)};
772 }
773 static GridPlacement Line(int line, int sp = 1)
774 {
775 return GridPlacement{static_cast<int16_t>(line), static_cast<int16_t>(sp < 1 ? 1 : sp)};
776 }
777
778 bool isAuto() const noexcept { return start <= 0; }
779
780 bool operator==(const GridPlacement &o) const
781 {
782 return start == o.start && span == o.span;
783 }
784 bool operator!=(const GridPlacement &o) const { return !(*this == o); }
785 };
786
787// ---------------------------------------------------------------------------
788// Master property list.
789//
790// X(TYPE, NAME, DEFAULT) is expanded by every consumer of the style system:
791// Opt<T> field declarations in `Style`, plain T fields in `ComputedStyle`,
792// equality/lerp/overlay implementations, the `propTable()` reflection table,
793// and the `transitionDirtyMask_` static_assert in StyleResolver.cpp.
794// ---------------------------------------------------------------------------
795#define BUBBLE_STYLE_PROPS(X) \
796 /* ---- 8-byte aligned ---- */ \
797 X(Spacing, margin, Spacing()) \
798 X(Spacing, padding, Spacing()) \
799 X(Spacing, borderWidth, Spacing()) \
800 X(BoxShadow, boxShadow, BoxShadow{}) \
801 X(TextureRef, backgroundTexture, TextureRef{}) \
802 X(std::string, effect, "") \
803 X(SharedVector<FilterRef>, filters, SharedVector<FilterRef>{}) \
804 X(SharedVector<GridTrack>, gridTemplateColumns, SharedVector<GridTrack>{}) \
805 X(SharedVector<GridTrack>, gridTemplateRows, SharedVector<GridTrack>{}) \
806 X(Value, width, Value::autoSize()) \
807 X(Value, height, Value::autoSize()) \
808 X(Value, minWidth, Value::autoSize()) \
809 X(Value, minHeight, Value::autoSize()) \
810 X(Value, maxWidth, Value::autoSize()) \
811 X(Value, maxHeight, Value::autoSize()) \
812 X(Value, flexBasis, Value::autoSize()) \
813 X(Value, gap, Value(0.0f)) \
814 X(Value, columnGap, Value::autoSize()) \
815 X(Value, rowGap, Value::autoSize()) \
816 X(Value, radius, Value(0.0f)) \
817 X(Value, translateX, Value(0.0f)) \
818 X(Value, translateY, Value(0.0f)) \
819 X(Value, fontSize, Value(20.0f)) \
820 X(Value, letterSpacing, Value(2.0f)) \
821 X(Value, top, Value::autoSize()) \
822 X(Value, left, Value::autoSize()) \
823 X(Value, right, Value::autoSize()) \
824 X(Value, bottom, Value::autoSize()) \
825 X(FontStack, font, FontStack{}) \
826 /* ---- 4-byte aligned ---- */ \
827 X(ZIndex, zIndex, ZIndex::Auto()) \
828 X(float, grow, 0.0f) \
829 X(float, shrink, 1.0f) \
830 X(float, opacity, 1.0f) \
831 X(float, scale, 1.0f) \
832 X(float, rotation, 0.0f) \
833 X(float, transitionTime, 0.0f) \
834 X(TransitionFunction, ease, TransitionFunction::Linear) \
835 X(Color, background, Colors::Blank) \
836 X(Color, color, Colors::White) \
837 X(Color, tint, Colors::White) \
838 X(Color, borderColor, Colors::Blank) \
839 /* ---- 2-byte aligned ---- */ \
840 X(GridPlacement, gridColumn, GridPlacement{}) \
841 X(GridPlacement, gridRow, GridPlacement{}) \
842 /* ---- 1-byte aligned ---- */ \
843 X(Align, alignH, Align::Auto) \
844 X(Align, alignV, Align::Auto) \
845 X(Align, alignItems, Align::Stretch) \
846 X(Align, verticalAlign, Align::Auto) \
847 X(Align, textAlign, Align::Auto) \
848 X(Justify, justify, Justify::Start) \
849 X(Overflow, overflowX, Overflow::Visible) \
850 X(Overflow, overflowY, Overflow::Visible) \
851 X(Position, position, Position::Static) \
852 X(WhiteSpace, whiteSpace, WhiteSpace::Normal) \
853 X(TextOverflow, textOverflow, TextOverflow::Visible) \
854 X(Direction, direction, Direction::Auto) \
855 X(CursorShape, cursor, CursorShape::Auto) \
856 X(TextDirection, dir, TextDirection::Auto) \
857 X(bool, wrap, false)
858
862 inline bool isInheritedProp(std::string_view name)
863 {
864 switch (name.size())
865 {
866 case 3:
867 return name == "dir";
868 case 4:
869 return name == "font";
870 case 5:
871 return name == "color";
872 case 6:
873 return name == "cursor";
874 case 8:
875 return name == "fontSize";
876 case 9:
877 return name == "textAlign";
878 case 13:
879 return name == "letterSpacing";
880 default:
881 return false;
882 }
883 }
884
885 struct Style;
886 inline bool clearStyleProp(Style &s, std::string_view name);
887
888 inline std::string kebabToCamel(std::string_view s)
889 {
890 std::string out;
891 out.reserve(s.size());
892 bool upperNext = false;
893 for (char c : s)
894 {
895 if (c == '-')
896 upperNext = true;
897 else
898 {
899 out.push_back(upperNext && c >= 'a' && c <= 'z'
900 ? static_cast<char>(c - 'a' + 'A')
901 : c);
902 upperNext = false;
903 }
904 }
905 return out;
906 }
907
908 inline std::string camelToKebab(std::string_view s)
909 {
910 std::string out;
911 out.reserve(s.size() + 4);
912 for (char c : s)
913 {
914 if (c >= 'A' && c <= 'Z')
915 {
916 out.push_back('-');
917 out.push_back(static_cast<char>(c - 'A' + 'a'));
918 }
919 else
920 {
921 out.push_back(c);
922 }
923 }
924 return out;
925 }
926
931 struct Style
932 {
933#define X(T, name, def) Opt<T> name;
934 BUBBLE_STYLE_PROPS(X)
935#undef X
936
939 SharedPropMap customProps;
940 SharedPropMap unresolvedProps;
941
943 Style &overlay(const Style &o)
944 {
945 const bool hadUnresolved = !unresolvedProps.empty();
946#define X(T, name, def) \
947 if (o.name.is_set) \
948 { \
949 name = o.name; \
950 if (hadUnresolved) \
951 eraseUnresolvedForProp_(#name); \
952 }
953 BUBBLE_STYLE_PROPS(X)
954#undef X
955 if (hadUnresolved)
956 {
957 if (o.overflowX.is_set && o.overflowY.is_set)
958 unresolvedProps.erase("overflow");
959 if (o.grow.is_set && o.shrink.is_set && o.flexBasis.is_set)
960 unresolvedProps.erase("flex");
961 }
962 if (o.transitions.is_set)
963 transitions = o.transitions;
964 if (o.animations.is_set)
965 animations = o.animations;
966
967 if (!o.customProps.empty())
968 customProps.mergeFrom(o.customProps);
969 if (!o.unresolvedProps.empty())
970 for (const auto &[k, v] : o.unresolvedProps)
971 {
972 unresolvedProps[k] = v;
973 clearStyleProp(*this, k);
974 }
975
976 return *this;
977 }
978
979 private:
980 void eraseUnresolvedForProp_(std::string_view camelName)
981 {
982 if (unresolvedProps.empty())
983 return;
984 unresolvedProps.erase(std::string(camelName));
985 unresolvedProps.erase(camelToKebab(camelName));
986 if (camelName == "filters")
987 unresolvedProps.erase("filter");
988 else if (camelName == "direction")
989 unresolvedProps.erase("flex-direction");
990 }
991 };
992
997 inline bool clearStyleProp(Style &s, std::string_view name)
998 {
999 if (name == "overflow")
1000 {
1001 s.overflowX.reset();
1002 s.overflowY.reset();
1003 return true;
1004 }
1005 if (name == "flex")
1006 {
1007 s.grow.reset();
1008 s.shrink.reset();
1009 s.flexBasis.reset();
1010 return true;
1011 }
1012
1013 std::string normalized = kebabToCamel(name);
1014 if (normalized == "filter")
1015 normalized = "filters";
1016 else if (normalized == "flexDirection")
1017 normalized = "direction";
1018
1019 bool cleared = false;
1020#define X(T, n, def) \
1021 if (!cleared && normalized == #n) \
1022 { \
1023 s.n.reset(); \
1024 cleared = true; \
1025 }
1026 BUBBLE_STYLE_PROPS(X)
1027#undef X
1028 return cleared;
1029 }
1030
1036 {
1037#define X(T, name, def) T name = def;
1038 BUBBLE_STYLE_PROPS(X)
1039#undef X
1040
1041 SharedVector<TransitionSpec> transitions;
1042 SharedVector<AnimationRef> animations;
1043 SharedPropMap customProps;
1044
1048 static ComputedStyle from(const Style &s,
1049 const ComputedStyle *parent = nullptr,
1050 const Style *root = nullptr)
1051 {
1052 ComputedStyle c;
1053#define X(T, name, def) \
1054 if (s.name.is_set) \
1055 c.name = s.name.value; \
1056 else if (parent && isInheritedProp(#name)) \
1057 c.name = parent->name; \
1058 else if (root && root->name.is_set) \
1059 c.name = root->name.value; \
1060 else \
1061 c.name = def;
1062 BUBBLE_STYLE_PROPS(X)
1063#undef X
1064 if (c.overflowX == Overflow::Visible && c.overflowY != Overflow::Visible)
1065 c.overflowX = Overflow::Auto;
1066 else if (c.overflowY == Overflow::Visible && c.overflowX != Overflow::Visible)
1067 c.overflowY = Overflow::Auto;
1068
1069 if (s.transitions.is_set)
1070 c.transitions = s.transitions.value;
1071 if (s.animations.is_set)
1072 c.animations = s.animations.value;
1073
1074 if (parent)
1075 c.customProps = parent->customProps;
1076 else if (root)
1077 c.customProps = root->customProps;
1078 c.customProps.mergeFrom(s.customProps);
1079 return c;
1080 }
1081 };
1082
1084 inline bool operator==(const ComputedStyle &a, const ComputedStyle &b)
1085 {
1086#define X(T, name, def) \
1087 if (!(a.name == b.name)) \
1088 return false;
1089 BUBBLE_STYLE_PROPS(X)
1090#undef X
1091 return true;
1092 }
1093 inline bool operator!=(const ComputedStyle &a, const ComputedStyle &b) { return !(a == b); }
1094
1095 // ---- Interpolation helpers ----
1096
1097 inline float lerpProp(float a, float b, float t) { return a + (b - a) * t; }
1098
1099 inline Color lerpProp(const Color &a, const Color &b, float t)
1100 {
1101 auto mix = [t](uint8_t x, uint8_t y)
1102 {
1103 float v = static_cast<float>(x) + (static_cast<float>(y) - static_cast<float>(x)) * t;
1104 return static_cast<uint8_t>(std::clamp(std::lround(v), 0L, 255L));
1105 };
1106 return {mix(a.r, b.r), mix(a.g, b.g), mix(a.b, b.b), mix(a.a, b.a)};
1107 }
1108
1109 inline FontStack lerpProp(const FontStack &a, const FontStack &b, float t)
1110 {
1111 return t > 0.0f ? b : a;
1112 }
1113
1114 inline Value lerpProp(const Value &a, const Value &b, float t)
1115 {
1116 if (a.isAuto() && b.isAuto())
1117 return Value::autoSize();
1118 if (a.isAuto() || b.isAuto())
1119 return t > 0.0f ? b : a;
1120
1121 if (!a.isComplex() && !b.isComplex() && a.unit() == b.unit())
1122 return Value(a.scalar() + (b.scalar() - a.scalar()) * t, a.unit());
1123
1124 if (a.getOp() != ValueOp::None || b.getOp() != ValueOp::None)
1125 return a + (b - a).mulWith(Value::number(t));
1126
1127 float ca[7] = {0}, cb[7] = {0};
1128 for (size_t i = 0; i < a.termCount(); ++i)
1129 {
1130 const auto term = a.termAt(i);
1131 int idx = static_cast<int>(term.unit);
1132 if (idx >= 0 && idx < 7)
1133 ca[idx] += term.coeff;
1134 }
1135 for (size_t i = 0; i < b.termCount(); ++i)
1136 {
1137 const auto term = b.termAt(i);
1138 int idx = static_cast<int>(term.unit);
1139 if (idx >= 0 && idx < 7)
1140 cb[idx] += term.coeff;
1141 }
1142
1143 Value::Term buf[7];
1144 size_t count = 0;
1145 for (int i = 0; i < 7; ++i)
1146 {
1147 float v = ca[i] + (cb[i] - ca[i]) * t;
1148 if (v != 0.0f)
1149 buf[count++] = {v, static_cast<Unit>(i)};
1150 }
1151 return Value::fromLinearTerms(buf, count);
1152 }
1153
1154 inline Spacing lerpProp(const Spacing &a, const Spacing &b, float t)
1155 {
1156 return Spacing(lerpProp(a.top, b.top, t), lerpProp(a.right, b.right, t),
1157 lerpProp(a.bottom, b.bottom, t), lerpProp(a.left, b.left, t));
1158 }
1159
1160 template <typename E, typename = std::enable_if_t<std::is_enum_v<E>>>
1161 inline E lerpProp(E a, E b, float t) { return t > 0.0f ? b : a; }
1162
1163 inline ZIndex lerpProp(const ZIndex &a, const ZIndex &b, float t) { return t > 0.0f ? b : a; }
1164
1165 inline std::string lerpProp(const std::string &a, const std::string &b, float t)
1166 {
1167 return t > 0.0f ? b : a;
1168 }
1169
1170 inline SharedVector<FilterRef> lerpProp(const SharedVector<FilterRef> &a,
1171 const SharedVector<FilterRef> &b,
1172 float t)
1173 {
1174 return t > 0.0f ? b : a;
1175 }
1176
1177 inline TextureRef lerpProp(const TextureRef &a, const TextureRef &b, float t)
1178 {
1179 return t > 0.0f ? b : a;
1180 }
1181
1182 inline BoxShadow lerpProp(const BoxShadow &a, const BoxShadow &b, float t)
1183 {
1184 return t > 0.0f ? b : a;
1185 }
1186
1187 inline SharedVector<GridTrack> lerpProp(const SharedVector<GridTrack> &a,
1188 const SharedVector<GridTrack> &b,
1189 float t)
1190 {
1191 return t > 0.0f ? b : a;
1192 }
1193
1194 inline GridPlacement lerpProp(const GridPlacement &a, const GridPlacement &b, float t)
1195 {
1196 return t > 0.0f ? b : a;
1197 }
1198
1200 inline ComputedStyle lerpStyle(const ComputedStyle &a, const ComputedStyle &b, float t)
1201 {
1202 ComputedStyle r;
1203#define X(T, name, def) r.name = lerpProp(a.name, b.name, t);
1204 BUBBLE_STYLE_PROPS(X)
1205#undef X
1206 r.transitions = b.transitions;
1207 r.customProps = b.customProps;
1208 return r;
1209 }
1210
1214 inline ComputedStyle lerpStyleTimed(const ComputedStyle &a, const ComputedStyle &b, float realElapsed)
1215 {
1216 ComputedStyle r;
1217
1218 auto timingFor = [&](const char *propName) -> std::pair<float, TransitionFunction>
1219 {
1220 for (const auto &spec : b.transitions)
1221 {
1222 if (spec.prop == propName || spec.prop == "all")
1223 return {spec.duration, spec.ease};
1224 }
1225 return {b.transitionTime, b.ease};
1226 };
1227
1228#define X(T, name, def) \
1229 { \
1230 if (a.name == b.name) \
1231 { \
1232 r.name = a.name; \
1233 } \
1234 else \
1235 { \
1236 auto [dur, ease] = timingFor(#name); \
1237 float tp = (dur > 0.0f) ? std::clamp(realElapsed / dur, 0.0f, 1.0f) : 1.0f; \
1238 r.name = lerpProp(a.name, b.name, getRatio(tp, ease)); \
1239 } \
1240 }
1241 BUBBLE_STYLE_PROPS(X)
1242#undef X
1243
1244 r.transitions = b.transitions;
1245 r.customProps = b.customProps;
1246 return r;
1247 }
1248
1252 inline bool stylesDiffer(const Style &a, const Style &b)
1253 {
1254#define X(T, name, def) \
1255 if (a.name.is_set != b.name.is_set) \
1256 return true; \
1257 if (a.name.is_set && !(a.name.value == b.name.value)) \
1258 return true;
1259 BUBBLE_STYLE_PROPS(X)
1260#undef X
1261
1262 if (a.animations.is_set != b.animations.is_set)
1263 return true;
1264 if (a.animations.is_set)
1265 {
1266 const auto &av = a.animations.value;
1267 const auto &bv = b.animations.value;
1268 if (av.size() != bv.size())
1269 return true;
1270 for (size_t i = 0; i < av.size(); ++i)
1271 {
1272 if (av[i].name != bv[i].name ||
1273 av[i].duration != bv[i].duration ||
1274 av[i].delay != bv[i].delay ||
1275 av[i].iterations != bv[i].iterations ||
1276 av[i].alternate != bv[i].alternate ||
1277 av[i].fillForwards != bv[i].fillForwards ||
1278 av[i].ease != bv[i].ease)
1279 return true;
1280 }
1281 }
1282 return false;
1283 }
1284
1285 template <typename T>
1286 inline Opt<T> lerpOpt(const Opt<T> &a, const Opt<T> &b, float t)
1287 {
1288 if (a.is_set && b.is_set)
1289 return Opt<T>(lerpProp(a.value, b.value, t));
1290 return b;
1291 }
1292
1293 inline Style lerpStyleParts(const Style &a, const Style &b, float t)
1294 {
1295 Style r;
1296#define X(T, name, def) r.name = lerpOpt(a.name, b.name, t);
1297 BUBBLE_STYLE_PROPS(X)
1298#undef X
1299 r.transitions = b.transitions;
1300 r.animations = b.animations;
1301 r.customProps = b.customProps;
1302 r.unresolvedProps = b.unresolvedProps;
1303 return r;
1304 }
1305
1306 inline void overlayComputed(ComputedStyle &dst, const Style &src)
1307 {
1308#define X(T, name, def) \
1309 if (src.name.is_set) \
1310 dst.name = src.name.value;
1311 BUBBLE_STYLE_PROPS(X)
1312#undef X
1313 }
1314
1315 template <typename F>
1316 inline void forEachSetStyleProp(const Style &s, F &&fn)
1317 {
1318#define X(T, name, def) \
1319 if (s.name.is_set) \
1320 fn(#name);
1321 BUBBLE_STYLE_PROPS(X)
1322#undef X
1323 }
1324
1325 inline bool copyStyleProp(Style &dst, const Style &src, std::string_view name)
1326 {
1327#define X(T, n, def) \
1328 if (name == #n) \
1329 { \
1330 if (src.n.is_set) \
1331 { \
1332 dst.n = src.n; \
1333 return true; \
1334 } \
1335 return false; \
1336 }
1337 BUBBLE_STYLE_PROPS(X)
1338#undef X
1339 return false;
1340 }
1341
1342 inline bool hasStyleProp(const Style &s, std::string_view name)
1343 {
1344#define X(T, n, def) \
1345 if (name == #n) \
1346 return s.n.is_set;
1347 BUBBLE_STYLE_PROPS(X)
1348#undef X
1349 return false;
1350 }
1351
1352 using PropValue = std::variant<bool, float, Value, Color, Spacing, Align, Justify,
1354 std::string, FontStack, TextureRef,
1358
1360 {
1361 const char *name;
1362 const char *type;
1363 const char *defaultExpr;
1364 PropValue (*get)(const ComputedStyle &);
1365 void (*set)(ComputedStyle &, const PropValue &);
1366 };
1367
1368 inline const std::vector<PropDesc> &propTable()
1369 {
1370 static const std::vector<PropDesc> table = {
1371#define X(T, name, def) PropDesc{#name, #T, #def, \
1372 [](const ComputedStyle &c) -> PropValue { return c.name; }, \
1373 [](ComputedStyle &c, const PropValue &v) { if (const T* p = std::get_if<T>(&v)) c.name = *p; }},
1374 BUBBLE_STYLE_PROPS(X)
1375#undef X
1376 };
1377 return table;
1378 }
1379
1380 inline const PropDesc *findProp(std::string_view name)
1381 {
1382 for (const auto &d : propTable())
1383 {
1384 if (name == d.name)
1385 return &d;
1386 }
1387 return nullptr;
1388 }
1389
1390 inline PropValue lerpValue(const PropValue &a, const PropValue &b, float t)
1391 {
1392 return std::visit([&](const auto &x) -> PropValue
1393 {
1394 using T = std::decay_t<decltype(x)>;
1395 if (const T* y = std::get_if<T>(&b)) return lerpProp(x, *y, t);
1396 return x; }, a);
1397 }
1398
1400}
Centralized standard library includes used throughout ZenitUI.
Easing curves used by transitions and CSS animations.
Small enumerations describing layout strategy and interaction state.
Length units and the compact 8-byte tagged Value expression representation.
Ordered list of font family names to try, first match wins.
Definition CoreTypes.hpp:194
8-byte Copy-on-Write wrapper around std::unordered_map<std::string, std::string>.
Definition Style.hpp:81
8-byte Copy-on-Write wrapper around std::vector<T> for cold style arrays.
Definition Style.hpp:294
TransitionFunction
Timing function applied between two keyframe values.
Definition Easing.hpp:28
Justify
Main-axis distribution for flex containers.
Definition CoreTypes.hpp:462
Align
Cross-axis alignment for flex items and content.
Definition CoreTypes.hpp:452
TextDirection
Inline / layout writing direction for Bidi text and RTL layout mirroring (ยง6.2).
Definition UIEnums.hpp:83
CursorShape
Standard OS cursor shapes requested via ZStyle cursor: and IPlatform::setCursor.
Definition UIEnums.hpp:61
bool clearStyleProp(Style &s, std::string_view name)
Clear the property named name on s.
Definition Style.hpp:997
SelectorCombinator
Relationship between a selector and the preceding selector in a chain.
Definition Style.hpp:621
bool stylesDiffer(const Style &a, const Style &b)
Compare two sparse Style values for "would this change anything".
Definition Style.hpp:1252
TextOverflow
CSS text-overflow modes supported by the text renderer.
Definition Style.hpp:595
ComputedStyle lerpStyleTimed(const ComputedStyle &a, const ComputedStyle &b, float realElapsed)
Field-wise lerp using per-property durations from b's transition list.
Definition Style.hpp:1214
std::ostream & operator<<(std::ostream &os, const FontStack &stack)
std::ostream operator for FontStack, used by debug output.
Definition Style.hpp:504
Overflow
CSS overflow modes for one axis.
Definition Style.hpp:579
bool isInheritedProp(std::string_view name)
true if the named property inherits from parent to child.
Definition Style.hpp:862
ComputedStyle lerpStyle(const ComputedStyle &a, const ComputedStyle &b, float t)
Field-wise lerp of two ComputedStyle.
Definition Style.hpp:1200
WhiteSpace
CSS white-space values relevant to text layout.
Definition Style.hpp:588
Position
CSS-style position modes supported by the layout system.
Definition Style.hpp:552
@ GeneralSibling
A ~ B (any preceding sibling).
Definition Style.hpp:625
@ AdjacentSibling
A + B (immediately preceding sibling).
Definition Style.hpp:624
@ Descendant
A B (any ancestor).
Definition Style.hpp:622
@ Child
A > B (direct parent).
Definition Style.hpp:623
One entry in the animations list of a Style.
Definition Style.hpp:539
CSS box-shadow payload.
Definition Style.hpp:705
8-bit-per-channel RGBA color, non-premultiplied.
Definition CoreTypes.hpp:78
Dense style: every property has a concrete value.
Definition Style.hpp:1036
static ComputedStyle from(const Style &s, const ComputedStyle *parent=nullptr, const Style *root=nullptr)
Build a ComputedStyle from a sparse Style and its context.
Definition Style.hpp:1048
One filter in the filters list of a Style.
Definition Style.hpp:679
Item placement along one grid axis (grid-column or grid-row).
Definition Style.hpp:765
int16_t start
1-based start line (0 = auto-place).
Definition Style.hpp:766
int16_t span
Number of tracks spanned (>= 1).
Definition Style.hpp:767
One track definition in grid-template-columns or grid-template-rows.
Definition Style.hpp:726
Kind
Definition Style.hpp:728
@ Auto
Size to content.
Definition Style.hpp:729
@ Flex
Flexible fraction (fr).
Definition Style.hpp:731
@ Fixed
Explicit length (px, %, vw, vh, calc(...)).
Definition Style.hpp:730
float fr
Used when kind == Kind::Flex.
Definition Style.hpp:736
Value size
Used when kind == Kind::Fixed.
Definition Style.hpp:735
Optional wrapper with value semantics used for all style fields.
Definition Style.hpp:49
Definition Style.hpp:1360
const char * name
camelCase C++ name, e.g. "fontSize".
Definition Style.hpp:1361
const char * defaultExpr
Stringified default expression, e.g. "Value::autoSize()".
Definition Style.hpp:1363
const char * type
Stringified C++ type, e.g. "Value".
Definition Style.hpp:1362
Single compound argument inside a :not(...) pseudo-class.
Definition Style.hpp:643
One :not(a, b, ...) clause; matches when none of items match.
Definition Style.hpp:657
One component of a CSS selector chain.
Definition Style.hpp:632
Kind
Definition Style.hpp:634
@ Any
Universal selector * or implicit base for standalone :not(...) / :hover.
Definition Style.hpp:638
Four-sided Value tuple used for padding, margin and border-width.
Definition Style.hpp:486
Sparse style: every property is Opt<T>, unset by default.
Definition Style.hpp:932
Style & overlay(const Style &o)
Merge o into *this; every set field of o wins.
Definition Style.hpp:943
Reference to a texture asset with optional nine-slice insets.
Definition Style.hpp:604
One entry in the transitions list of a Style.
Definition Style.hpp:525
Definition Unit.hpp:60
8-byte tagged length expression:
Definition Unit.hpp:58
CSS z-index with an explicit "auto" state.
Definition Style.hpp:562