TinyMaterialDesign
Loading...
Searching...
No Matches
TextField.h
Go to the documentation of this file.
1#pragma once
2#include <functional>
3#include <string>
4
5#include "TinyGPU/Color/RGB565.h"
6#include "TinyGPU/Color/RGB666.h"
7#include "TinyGPU/Color/RGB888.h"
8#include "TinyMaterialDesign/Core/TextInputTarget.h"
9#include "TinyMaterialDesign/Core/Widget.h"
10
11namespace tinymd {
12
13/**
14 * @brief Single-line text input box.
15 *
16 * TextField only holds and displays text and focus state - it has no idea
17 * how to turn touches into characters. Pair it with a Keyboard (Keyboard.h):
18 *
19 * Keyboard<RGB565> keyboard(Bounds(0, 420, 340, 190));
20 * TextField<RGB565> nameField(Bounds(16, 88, 220, 48), "Name");
21 * keyboard.manage(nameField); // wires nameField's focus to this keyboard
22 * screen.addWidget(nameField);
23 * screen.addWidget(keyboard); // add last so it draws on top when shown
24 *
25 * insertChar()/backspace()/handleEnter() (TextInputTarget, see Core/
26 * TextInputTarget.h) are what let a Keyboard - or any other input source -
27 * drive a focused field without TextField needing to know about it. Enter
28 * submits (see TextArea.h for the multi-line counterpart, where Enter
29 * inserts a newline instead).
30 *
31 * Bounds is split internally into a small label strip (top) and the input
32 * box itself (the rest) - both are part of this widget's own bounds, so a
33 * tap anywhere in either area focuses the field.
34 *
35 * Known limitation: text longer than the box is drawn past its right edge
36 * rather than scrolling/clipping - TinyGPU's fonts have no sub-rect clip,
37 * only surface-edge clipping. Fine for short inputs (names, search terms,
38 * ...); not meant for long free-form text.
39 */
40template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
41class TextField : public Widget<RGB_T>, public TextInputTarget {
42 public:
43 TextField() = default;
44 TextField(Bounds bounds, const char* label = nullptr, const char* placeholder = nullptr) {
45 this->bounds = bounds;
46 if (label != nullptr) {
47 label_ = label;
48 hasLabel_ = true;
49 }
50 if (placeholder != nullptr) placeholder_ = placeholder;
51 }
52
53 /// Fired when the field becomes focused (by tap, or by any other code
54 /// calling focus()) - a Keyboard's manage() wires this to attach itself.
55 std::function<void()> onFocus;
56 /// Fired after every character insertion/deletion.
57 std::function<void(const std::string&)> onChange;
58 /// Fired when a Keyboard's Enter/Done key (or submit()) is pressed.
59 std::function<void()> onSubmit;
60 /// Fired when the field loses the focus (blur(), submit(), or the
61 /// Keyboard switched to another field): editing has ended.
62 std::function<void()> onBlur;
63
64 /// kNumber: only digits (and . - + :) are accepted and a Keyboard shows
65 /// its numeric keypad.
66 void setInputType(InputType type) { inputType_ = type; }
67 InputType inputType() const override { return inputType_; }
68
69 /// Shows the field in the error color with `text` as supporting text below
70 /// the box (it needs 14 px of the bounds); nullptr or "" clears the error.
71 void setError(const char* text) { error_ = text != nullptr ? text : ""; }
72 bool hasError() const { return !error_.empty(); }
73 const std::string& errorText() const { return error_; }
74
75 /// Checks the text after each change: if `valid` returns false the field
76 /// shows `errorText` (see setError()).
77 void setValidator(std::function<bool(const std::string&)> valid, const char* errorText) {
78 validator_ = std::move(valid);
79 validatorError_ = errorText != nullptr ? errorText : "";
80 validate();
81 }
82 /// True if there is no validator or it accepts the text.
83 bool isValid() const { return !validator_ || validator_(text_); }
84
85 /// Shows a '*' for each character (e.g. for a password); text() still
86 /// returns the real text.
87 void setPasswordMode(bool password) { password_ = password; }
88 bool passwordMode() const { return password_; }
89
90 /// The field is directly on a page: the label above the box (and the error
91 /// text below it) are drawn on the theme's background color instead of the
92 /// surface color.
93 void setOnBackground(bool onBackground) { onBackground_ = onBackground; }
94
95 const std::string& text() const { return text_; }
96 void setText(const char* text) {
97 text_ = text != nullptr ? text : "";
98 validate();
99 if (onChange) onChange(text_);
100 }
101 /// 0 (the default) means unlimited.
102 void setMaxLength(size_t maxLength) { maxLength_ = maxLength; }
103
104 bool focused() const { return focused_; }
105 void focus() {
106 focused_ = true;
107 if (onFocus) onFocus();
108 }
109 void blur() override {
110 const bool was = focused_;
111 focused_ = false;
112 if (was && onBlur) onBlur();
113 }
114
115 /// Appends one character - called by whatever is driving text entry
116 /// (typically a Keyboard key tap).
117 void insertChar(char c) override {
118 if (maxLength_ != 0 && text_.size() >= maxLength_) return;
119 if (inputType_ == InputType::kNumber && !((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == ':')) {
120 return;
121 }
122 text_.push_back(c);
123 validate();
124 if (onChange) onChange(text_);
125 }
126 void backspace() override {
127 if (text_.empty()) return;
128 text_.pop_back();
129 validate();
130 if (onChange) onChange(text_);
131 }
132 /// Loses focus and fires onSubmit - called directly, or via a Keyboard's
133 /// Enter/Done key through handleEnter().
134 void submit() {
135 const bool was = focused_;
136 focused_ = false;
137 if (onSubmit) onSubmit();
138 if (was && onBlur) onBlur();
139 }
140
141 /// TextInputTarget: single-line semantics - Enter submits and tells the
142 /// Keyboard to hide itself.
143 bool handleEnter() override {
144 submit();
145 return true;
146 }
147
148 void draw(tinygpu::ISurface<RGB_T>& target) override {
149 const int32_t labelHeight = hasLabel_ ? 14 : 0;
150 const int32_t errorHeight = error_.empty() ? 0 : 14;
151 const Bounds box(this->bounds.x, this->bounds.y + labelHeight, this->bounds.w,
152 this->bounds.h - labelHeight - errorHeight);
153 const RGB_T outside = onBackground_ ? this->theme().colors.background : this->theme().colors.surface;
154 const bool error = !error_.empty();
155
156 if (hasLabel_) {
157 RGB_T labelColor = error ? this->theme().colors.error
158 : focused_ ? this->theme().colors.primary
159 : this->theme().colors.onSurfaceVariant;
160 if (!this->enabled) labelColor = blend(labelColor, this->theme().colors.surface, 0.5f);
161 this->theme().typography.label->drawText(target, static_cast<int16_t>(this->bounds.x),
162 static_cast<int16_t>(this->bounds.y), label_.c_str(),
163 labelColor, outside, false);
164 }
165 if (error) {
166 this->theme().typography.label->drawText(target, static_cast<int16_t>(this->bounds.x + 4),
167 static_cast<int16_t>(box.bottom() + 3), error_.c_str(),
168 this->theme().colors.error, outside, false);
169 }
170
171 RGB_T borderColor = error ? this->theme().colors.error
172 : focused_ ? this->theme().colors.primary
173 : this->theme().colors.outline;
174 if (!this->enabled) borderColor = blend(borderColor, this->theme().colors.surface, 0.5f);
175 const size_t radius = toPx(this->theme().shape.small);
176 target.fillRoundRect(toPx(box.x), toPx(box.y), toPx(box.w), toPx(box.h), radius,
177 this->theme().colors.surface);
178 target.drawRoundRect(toPx(box.x), toPx(box.y), toPx(box.w), toPx(box.h), radius, borderColor);
179
180 const int32_t pad = 8;
181 const int32_t textX = box.x + pad;
182 const int32_t textY = box.centerY() - static_cast<int32_t>(this->theme().typography.body->getHeight(1)) / 2;
183
184 if (text_.empty() && !focused_) {
185 if (!placeholder_.empty()) {
186 this->theme().typography.body->drawText(target, static_cast<int16_t>(textX),
187 static_cast<int16_t>(textY), placeholder_.c_str(),
188 this->theme().colors.onSurfaceVariant, this->theme().colors.surface, false);
189 }
190 return;
191 }
192
193 const std::string shown = password_ ? std::string(text_.size(), '*') : text_;
194 this->theme().typography.body->drawText(target, static_cast<int16_t>(textX),
195 static_cast<int16_t>(textY), shown.c_str(),
196 this->theme().colors.onSurface, this->theme().colors.surface, false);
197
198 if (focused_ && cursorVisible_) {
199 const size_t textWidth = this->theme().typography.body->measureTextWidth(shown.c_str());
200 const int32_t cursorX = textX + static_cast<int32_t>(textWidth) + 1;
201 target.drawLine(toPx(cursorX), toPx(box.y + 6), toPx(cursorX), toPx(box.bottom() - 6),
202 this->theme().colors.primary);
203 }
204 }
205
206 bool onGesture(const tinygpu::GestureEvent& event) override {
207 if (!isTapGesture(event.type)) return false;
208 focus();
209 return true;
210 }
211
212 bool update(uint32_t nowMs) override {
213 const bool wasVisible = cursorVisible_;
214 if (!focused_) {
215 cursorVisible_ = false;
216 return wasVisible != cursorVisible_;
217 }
218 if (nowMs - lastBlinkMs_ >= kBlinkIntervalMs) {
219 cursorVisible_ = !cursorVisible_;
220 lastBlinkMs_ = nowMs;
221 }
222 return wasVisible != cursorVisible_;
223 }
224
225 private:
226 static constexpr uint32_t kBlinkIntervalMs = 500;
227
228 std::string text_;
229 std::string label_;
230 std::string placeholder_;
231 std::string error_;
232 std::string validatorError_;
233 std::function<bool(const std::string&)> validator_;
234 InputType inputType_ = InputType::kText;
235 bool onBackground_ = false;
236 bool password_ = false;
237 bool hasLabel_ = false;
238
239 void validate() {
240 if (validator_) error_ = validator_(text_) ? "" : validatorError_;
241 }
242 size_t maxLength_ = 0;
243 bool focused_ = false;
244 bool cursorVisible_ = true;
245 uint32_t lastBlinkMs_ = 0;
246};
247
251
252} // namespace tinymd
Single-line text input box.
Definition: TextField.h:41
void setMaxLength(size_t maxLength)
0 (the default) means unlimited.
Definition: TextField.h:102
void backspace() override
Definition: TextField.h:126
bool onGesture(const tinygpu::GestureEvent &event) override
Handles one gesture event. Returns true if this widget consumed it.
Definition: TextField.h:206
TextField(Bounds bounds, const char *label=nullptr, const char *placeholder=nullptr)
Definition: TextField.h:44
TextField()=default
void setValidator(std::function< bool(const std::string &)> valid, const char *errorText)
Definition: TextField.h:77
bool isValid() const
True if there is no validator or it accepts the text.
Definition: TextField.h:83
bool handleEnter() override
Definition: TextField.h:143
InputType inputType() const override
The kind of input - Keyboard picks its layout from it. Default: text.
Definition: TextField.h:67
const std::string & errorText() const
Definition: TextField.h:73
bool hasError() const
Definition: TextField.h:72
void blur() override
Definition: TextField.h:109
void setText(const char *text)
Definition: TextField.h:96
bool passwordMode() const
Definition: TextField.h:88
std::function< void(const std::string &)> onChange
Fired after every character insertion/deletion.
Definition: TextField.h:57
void draw(tinygpu::ISurface< RGB_T > &target) override
Definition: TextField.h:148
std::function< void()> onFocus
Definition: TextField.h:55
const std::string & text() const
Definition: TextField.h:95
bool focused() const
Definition: TextField.h:104
void focus()
Definition: TextField.h:105
bool update(uint32_t nowMs) override
Definition: TextField.h:212
void setPasswordMode(bool password)
Definition: TextField.h:87
void setOnBackground(bool onBackground)
Definition: TextField.h:93
void insertChar(char c) override
Definition: TextField.h:117
std::function< void()> onBlur
Definition: TextField.h:62
void setInputType(InputType type)
Definition: TextField.h:66
void submit()
Definition: TextField.h:134
void setError(const char *text)
Definition: TextField.h:71
std::function< void()> onSubmit
Fired when a Keyboard's Enter/Done key (or submit()) is pressed.
Definition: TextField.h:59
Definition: TextInputTarget.h:22
Base class every TinyMaterialDesign widget derives from.
Definition: Widget.h:58
Definition: AnchorLayout.h:4
InputType
Minimal interface a Keyboard drives.
Definition: TextInputTarget.h:20
Axis-aligned pixel rectangle used for widget bounds and hit-testing.
Definition: Bounds.h:21
int32_t centerY() const
Definition: Bounds.h:33
int32_t x
Definition: Bounds.h:22