TinyMaterialDesign
Loading...
Searching...
No Matches
Carousel.h
Go to the documentation of this file.
1#pragma once
2#include <algorithm>
3#include <cmath>
4#include <functional>
5#include <utility>
6#include <vector>
7
8#include "TinyGPU/Color/RGB565.h"
9#include "TinyGPU/Color/RGB666.h"
10#include "TinyGPU/Color/RGB888.h"
11#include "TinyMaterialDesign/Core/Widget.h"
12
13namespace tinymd {
14
15/**
16 * @brief Horizontally paged, drag-to-swipe row of items (typically
17 * `MediaCard`), with a snap-to-item animation and a page-dot indicator -
18 * Material's "carousel", e.g. a row of featured stations/genres.
19 *
20 * Items are not owned by Carousel - same non-owning `addItem()` convention
21 * as Drawer/BottomSheet. Each item's `bounds` is authored in the carousel's
22 * own *content* space (see `itemRect()`, stacked left-to-right by
23 * `itemWidth + gap`, starting at x=0) rather than screen space - `draw()`
24 * temporarily shifts each item's `bounds.x` by the carousel's own position
25 * and current scroll offset before drawing it, then restores it, the same
26 * pattern `Screen::draw()` uses for its own vertically-scrolled content.
27 * `onGesture()` translates a tap's point the same way before forwarding it
28 * to whichever item it landed on.
29 *
30 * Reports `isDraggable() == true` (like `Slider`) so a horizontal drag
31 * starting on the carousel is classified as `GestureType::kDrag` and
32 * latched to it for the drag's whole lifetime - see `Screen::
33 * isDraggableAt()`. Releasing mid-drag snaps to the nearest item,
34 * animated over a few frames via `update()`.
35 *
36 * An item scrolled partway past the carousel's left/right edge is cropped
37 * to it (see ISurface::pushClipRect()), not drawn in full or skipped.
38 *
39 * Alternative to addItem(): setItemProvider(count, at) switches to
40 * callback-driven items, for a station/genre list too large to keep every
41 * MediaCard resident at once - see Container.h's class comment for the same
42 * pattern. `at(index)`'s returned Widget has its bounds overwritten with
43 * itemRect(index) on every fetch (addItem() only does this once, since a
44 * vector-mode item's position never needs to change again).
45 */
46template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
47class Carousel : public Widget<RGB_T> {
48 public:
49 using ItemCountFn = std::function<int()>;
50 using ItemAtFn = std::function<Widget<RGB_T>&(int index)>;
51
52 Carousel() = default;
53 explicit Carousel(Bounds bounds, int32_t itemWidth = 140, int32_t gap = 12)
54 : itemWidth_(itemWidth), gap_(gap) {
55 this->bounds = bounds;
56 }
57
58 /// Fired whenever the settled current page changes - by drag-release snap
59 /// or by setCurrentIndex().
60 std::function<void(int)> onPageChange;
61
62 /// Positions `item`'s own bounds (see class comment) and appends it.
63 /// Ignored while an item provider is active - see setItemProvider().
64 void addItem(Widget<RGB_T>& item) {
65 item.bounds = itemRect(static_cast<int>(items_.size()));
66 items_.push_back(&item);
67 if (this->theme_ != nullptr) item.setTheme(*this->theme_);
68 }
69
70 /// Switches to callback-driven items - see the class comment.
71 void setItemProvider(ItemCountFn count, ItemAtFn at) {
72 itemCountFn_ = std::move(count);
73 itemAtFn_ = std::move(at);
74 }
75
76 void setTheme(const MaterialTheme<RGB_T>& theme) override {
77 Widget<RGB_T>::setTheme(theme);
78 for (Widget<RGB_T>* item : items_) {
79 if (item != nullptr) item->setTheme(theme);
80 }
81 }
82
83 /// Suggested content-space rect for the `index`-th item - see class
84 /// comment. Leaves room at the bottom for the page-dot indicator.
85 Bounds itemRect(int index) const {
86 return Bounds(index * (itemWidth_ + gap_), 0, itemWidth_, this->bounds.h - kIndicatorHeight);
87 }
88
89 int currentIndex() const { return currentIndex_; }
90 int pageCount() const { return itemCount(); }
91
92 /// Pages to `index`, clamped to a valid item - animated (the same
93 /// snap-glide update() uses after a drag release) unless `animate` is
94 /// false.
95 void setCurrentIndex(int index, bool animate = true) {
96 const int count = itemCount();
97 if (count == 0) return;
98 index = std::min(std::max(index, 0), count - 1);
99 const bool changed = index != currentIndex_;
100 currentIndex_ = index;
101 targetOffsetX_ = static_cast<float>(index * (itemWidth_ + gap_));
102 if (!animate) offsetX_ = targetOffsetX_;
103 animating_ = animate && offsetX_ != targetOffsetX_;
104 if (changed && onPageChange) onPageChange(currentIndex_);
105 }
106
107 bool isDraggable() const override { return true; }
108
109 void draw(tinygpu::ISurface<RGB_T>& target) override {
110 target.pushClipRect(toPx(this->bounds.x), toPx(this->bounds.y), toPx(this->bounds.w),
111 toPx(this->bounds.h));
112 const int count = itemCount();
113 for (int i = 0; i < count; ++i) {
114 Widget<RGB_T>* item = itemAt(i);
115 if (!item->visible) continue;
116 const int32_t contentX = item->bounds.x;
117 item->bounds.x = this->bounds.x + contentX - static_cast<int32_t>(offsetX_);
118 if (item->bounds.right() > this->bounds.x && item->bounds.x < this->bounds.right()) {
119 item->draw(target);
120 }
121 item->bounds.x = contentX;
122 }
123 target.popClipRect();
124 drawIndicator(target);
125 }
126
127 bool onGesture(const tinygpu::GestureEvent& event) override {
128 if (event.type == tinygpu::GestureType::kDrag) {
129 if (event.phase == tinygpu::GesturePhase::kBegan) animating_ = false;
130 offsetX_ -= event.stepDeltaX;
131 clampOffset();
132 if (event.phase == tinygpu::GesturePhase::kEnded) snapToNearest();
133 return true;
134 }
135 if (!isTapGesture(event.type)) return false;
136
137 const int32_t contentX = event.point.x - this->bounds.x + static_cast<int32_t>(offsetX_);
138 const int count = itemCount();
139 for (int i = 0; i < count; ++i) {
140 Widget<RGB_T>* item = itemAt(i);
141 if (item->enabled && item->bounds.contains(contentX, event.point.y)) {
142 tinygpu::GestureEvent shifted = event;
143 shifted.point.x = static_cast<int16_t>(contentX);
144 return item->onGesture(shifted);
145 }
146 }
147 return true;
148 }
149
150 bool update(uint32_t nowMs) override {
151 bool changed = false;
152 if (animating_) {
153 const float diff = targetOffsetX_ - offsetX_;
154 if (std::fabs(diff) < 1.0f) {
155 offsetX_ = targetOffsetX_;
156 animating_ = false;
157 } else {
158 offsetX_ += diff * 0.3f;
159 }
160 changed = true;
161 }
162 const int count = itemCount();
163 for (int i = 0; i < count; ++i) changed |= itemAt(i)->update(nowMs);
164 return changed;
165 }
166
167 private:
168 static constexpr int32_t kIndicatorHeight = 16;
169
170 int32_t itemWidth_ = 140;
171 int32_t gap_ = 12;
172 std::vector<Widget<RGB_T>*> items_;
173 ItemCountFn itemCountFn_;
174 ItemAtFn itemAtFn_;
175
176 float offsetX_ = 0.0f;
177 float targetOffsetX_ = 0.0f;
178 bool animating_ = false;
179 int currentIndex_ = 0;
180
181 int itemCount() const { return itemCountFn_ ? itemCountFn_() : static_cast<int>(items_.size()); }
182
183 /// The item at `index` right now - from the provider if active (bounds
184 /// reset to itemRect(index) and themed on every fetch, since a pooled
185 /// provider Widget may have just served a different index - see the class
186 /// comment), else from the addItem()'d vector (bounds set once, at add
187 /// time).
188 Widget<RGB_T>* itemAt(int index) const {
189 if (itemAtFn_) {
190 Widget<RGB_T>& item = itemAtFn_(index);
191 item.bounds = itemRect(index);
192 if (this->theme_ != nullptr) item.setTheme(*this->theme_);
193 return &item;
194 }
195 return items_[static_cast<size_t>(index)];
196 }
197
198 int32_t maxOffsetX() const {
199 const int count = itemCount();
200 return count > 0 ? std::max(int32_t{0}, (count - 1) * (itemWidth_ + gap_)) : 0;
201 }
202
203 void clampOffset() {
204 offsetX_ = std::min(static_cast<float>(maxOffsetX()), std::max(0.0f, offsetX_));
205 }
206
207 /// Rounds the current (mid-drag) offset to the nearest item and starts
208 /// the snap-glide animation toward it - see update().
209 void snapToNearest() {
210 if (itemCount() == 0) return;
211 const int32_t step = itemWidth_ + gap_;
212 const int index = step > 0 ? static_cast<int>(std::round(offsetX_ / step)) : 0;
213 setCurrentIndex(index, /*animate=*/true);
214 }
215
216 void drawIndicator(tinygpu::ISurface<RGB_T>& target) {
217 const int count = itemCount();
218 if (count <= 1) return;
219 constexpr int32_t kDotDiameter = 6;
220 constexpr int32_t kDotGap = 8;
221 const int32_t totalWidth = count * kDotDiameter + (count - 1) * kDotGap;
222 int32_t x = this->bounds.centerX() - totalWidth / 2;
223 const int32_t y = this->bounds.bottom() - kIndicatorHeight / 2;
224
225 for (int i = 0; i < count; ++i) {
226 const RGB_T color =
227 i == currentIndex_ ? this->theme().colors.primary : this->theme().colors.surfaceVariant;
228 target.fillCircle(toPx(x + kDotDiameter / 2), toPx(y), toPx(kDotDiameter / 2), color);
229 x += kDotDiameter + kDotGap;
230 }
231 }
232};
233
237
238} // namespace tinymd
Horizontally paged, drag-to-swipe row of items (typically MediaCard), with a snap-to-item animation a...
Definition: Carousel.h:47
bool isDraggable() const override
Definition: Carousel.h:107
bool onGesture(const tinygpu::GestureEvent &event) override
Handles one gesture event. Returns true if this widget consumed it.
Definition: Carousel.h:127
Carousel()=default
int currentIndex() const
Definition: Carousel.h:89
void setItemProvider(ItemCountFn count, ItemAtFn at)
Switches to callback-driven items - see the class comment.
Definition: Carousel.h:71
void addItem(Widget< RGB_T > &item)
Definition: Carousel.h:64
Carousel(Bounds bounds, int32_t itemWidth=140, int32_t gap=12)
Definition: Carousel.h:53
void draw(tinygpu::ISurface< RGB_T > &target) override
Definition: Carousel.h:109
bool update(uint32_t nowMs) override
Definition: Carousel.h:150
int pageCount() const
Definition: Carousel.h:90
std::function< void(int)> onPageChange
Definition: Carousel.h:60
void setCurrentIndex(int index, bool animate=true)
Definition: Carousel.h:95
void setTheme(const MaterialTheme< RGB_T > &theme) override
Definition: Carousel.h:76
Bounds itemRect(int index) const
Definition: Carousel.h:85
Base class every TinyMaterialDesign widget derives from.
Definition: Widget.h:58
Definition: AnchorLayout.h:4
Axis-aligned pixel rectangle used for widget bounds and hit-testing.
Definition: Bounds.h:21
Bundles a color scheme, shape tokens, typography, and spacing into one theme, passed to widgets so th...
Definition: MaterialTheme.h:50