Skip to content

Declared by <huxerui/text.h>, <huxerui/text_input.h>, <huxerui/validation.h>, and <huxerui/clipboard.h>.

  • FontFamilyKind: System, Monospace, Named, or Custom.
  • FontWeight: Thin, ExtraLight, Light, Regular, Medium, SemiBold, Bold, ExtraBold, or Black.
  • FontSlant: Normal or Italic.
  • Font: System(size), named/fallback family construction, and fluent size/weight/slant updates; equality compares descriptor values.
  • TextDecoration: None, Underline, StrikeThrough flags; bitwise |, &, and HasTextDecoration support combinations.
  • TextStyle: font, foreground, and decoration.

FontFamily describes an immutable family independently of size/weight/slant. System, Monospace and Named request platform families; FromResources, FromFiles and FromBytes construct validated custom static OpenType/TrueType families. Resource loading uses the application thread; file/byte construction can run on a worker.

Font::FromFamily, FromResource, FromFile and FromBytes construct a request. WithFamily changes the family while preserving size, weight and slant. TypographyScheme::family applies a family to theme-derived text. See Fonts and typography for ownership, supported data and complete examples.

SoftwareKeyboardPolicy is Automatic or Manual in TextInputConfiguration::keyboard_policy. Automatic requests keyboard display on session start and a confirmed editor tap; Manual leaves display requests to the application. WindowHandle::ShowKeyboard and HideKeyboard act on the focused session without ending focus or selection. They are separate from text selection, secure-input policy and input action.

  • TextDirection: Auto, LeftToRight, or RightToLeft.
  • TextShapingOptions: locale/language and direction inputs.
  • TextAlign: Leading, Center, or Trailing.
  • TextWrap: NoWrap or Word.
  • TextLayoutOptions holds shaping, alignment, and wrapping options. Measurement and layout take width as a separate argument.
  • FontMetrics, TextRunMetrics, and TextLayoutMetrics: ascent/descent/leading, run geometry, overall size, baselines, and line data.
  • TextMeasurer platform interface and UseTextMeasurer() extension hook.

TextMeasurer::CreateTextLayout(attributed_text, style, width, options) returns an immutable, copyable TextLayout. Width must be finite and positive. Borrow the measurer during composition or geometry preparation, then retain the layout on its creating UI thread. Rebuild the layout when its content, width, style, shaping options, or effective font metrics change. Pass an explicit shaping locale when the layout should use the inherited locale.

Query Result
Metrics(), Lines() Measured size, baselines, and the visual lines in top-to-bottom order. Each TextLineMetrics contains a half-open source range excluding the hard break, logical bounds, and a paragraph-relative baseline. The span borrows the layout snapshot.
HitTest(Point) The nearest caret position with visual affinity, including for points outside the paragraph.
CaretRect(TextPosition), LineIndex(TextPosition) Unclipped caret geometry and visual line index. Affinity selects the appropriate side of a soft wrap.
RangeRects(TextRange) Unclipped selection fragments. A range across lines or directional runs can produce multiple rectangles.
PreviousCaretOffset(offset), NextCaretOffset(offset) The adjacent caret boundary in logical text order.
InlineObjectRect(offset) Baseline-positioned bounds for an annotated replacement character, or an empty optional at an unannotated position.

Queries use UTF-16 offsets and paragraph-local logical coordinates from the top-left origin. Invalid offsets and positions that split a surrogate pair throw std::invalid_argument. A collapsed range has no selection fragments. Empty text and a trailing hard break produce an empty visual line. See custom text editing and paragraph drawing.

  • TextOffset is signed 64-bit; TextInputSessionId is unsigned 64-bit.
  • TextAffinity: Upstream or Downstream; TextPosition, TextRange, and TextSelection model caret/range state.
  • TextEditingValue contains UTF-8 text, selection, and composition range with validation/equality helpers.

TextInputCommandKind values are SetSelection, BeginComposition, UpdateComposition, CommitText, FinishComposition, CancelComposition, and DeleteSurrounding. TextInputCoordinateSpace is Text or Composition; TextInputUnit is Utf16CodeUnit or UnicodeCodePoint. TextInputCommand and TextInputCommandBatch carry revisioned platform edits.

  • TextInputType: Text, Email, Number, Decimal, Phone, or Url.

  • TextCapitalization: None, Characters, Words, or Sentences.

  • TextInputAction: Default, Done, Go, Next, Search, Send, or Newline.

  • TextInputConfiguration: type, capitalization, action, multiline, secure, autocorrect, and read-only flags.

  • TextInputResultCode: Ok, SessionMismatch, Rejected, or ReadOnly.

  • TextInputSyncAction: None, Update, or Restart.

  • TextInputEndReason: FocusLost, ClientRemoved, Disabled, ReadOnly, or RuntimeDestroyed.

  • TextInputKeyResult: Unhandled or Handled.

  • State/result structures: TextInputState, TextInputApplyResult, TextInputContext, TextInputGeometry, and TextInputPositionResult.

TextInputClient and TextSelectionClient are mounted extension interfaces. PlatformTextInput is the adapter interface for begin/update/end session, keyboard, geometry queries, selection menus, and platform synchronization.

ValidationStatus is None, Valid, Invalid, or Pending. ValidationResult has named factories and IsInvalid. Required and EmailAddress accept optional localized messages. Validate(value, rules...) evaluates until a rule is non-valid.

Obtain the application-owned Clipboard with UseApplication().Clipboard(). Start operations on the application thread in response to a user action. SupportsSynchronousText() describes whether ReadText() and WriteText(text) are available. An individual operation can still fail.

A ClipboardItem can carry UTF-8 plain text, HTML, an encoded ImageAsset, and custom MIME representations of the same content. ClipboardItem::FromAttributedText produces HTML and a plain-text fallback, which also satisfies Android’s requirement for HTML publication.

Operation Contract
WriteItem(item), WriteItemAsync(item) Publish all representations as one item. Rejection returns false. An empty item, conflicting MIME names, invalid UTF-8, embedded nulls in text or HTML, or an empty image throws std::invalid_argument.
ReadItemAsync(ClipboardReadOptions) Returns Task<IoResult<ClipboardItem>> for one system item. The defaults request text and HTML. Set image or specify custom_mime_types when needed. Use ToAttributedText() on a successful item to parse supported styles and links or fall back to plain text.
ReadTextAsync(), ReadImageAsync() Read a single representation. An empty stored string counts as successful text. An image file in a file list remains a file.
WriteFiles(files), ReadFilesAsync() Publish or read a nonempty file list separately from a multi-format item. Reads return the complete ordered list as read-only FileReference values or fail the entire operation. The system can revoke provider access when clipboard contents change.

File and format capabilities vary by platform. On Web, invoke the asynchronous method inside the click or key handler, before handing off its returned task. A secure browser context can provide text, HTML and PNG, subject to user activation, permissions and supported formats. Web does not expose file-list clipboard access. Browser-managed TextField shortcuts use the browser’s editing path. Canceling the returned task suppresses delivery of the result and may leave an already-started publication intact.

#include <huxerui/huxerui.h>
#include <utility>
using namespace huxerui;
Task<void> ReportClipboardWrite(Task<bool> write, State<std::string> status) {
const bool accepted = co_await std::move(write);
status = accepted ? "Copied" : "Clipboard write unavailable";
}
[[huxerui::composable]]
View CopyHeading() {
auto clipboard = UseApplication().Clipboard();
auto tasks = UseTaskScope();
auto status = UseState(std::string{"Ready to copy"});
return Column {
Button("Copy heading").OnClick([clipboard, tasks, status] {
const AttributedText heading{
TextSpan("Build ready").Style({.font_weight = FontWeight::Bold}),
};
tasks.Launch(ReportClipboardWrite(clipboard->WriteItemAsync(ClipboardItem::FromAttributedText(heading)), status));
}),
Text(status),
}.With(Spacing(8.0F));
}

A custom TextInputClient can override GetTextEditingActionStatus(action, clipboard) to determine whether Cut, Copy, Paste, or SelectAll is available. Keep that query side-effect free. Handle the action in PerformTextEditingAction(action, clipboard). Start clipboard reads or writes inside the call when browser user activation is needed. For deferred paste, keep owned data and check that the original edit session and selection are still valid before applying the result. Respect read-only and secure input when exposing actions.

TextSelectionMenuLabels overrides localized labels through the environment without changing which actions are available.

#include <huxerui/huxerui.h>
using namespace huxerui;
[[huxerui::composable]]
View AccountEmail() {
auto email = UseState(TextEditingValue::FromText(""));
return TextField(email)
.Label("Email")
.Placeholder("name@example.com")
.Variant(TextFieldVariant::Outlined)
.InputConfiguration({
.type = TextInputType::Email,
.action = TextInputAction::Done,
})
.Validation(Validate(email->text, Required(), EmailAddress()))
.OnChanged([email](const TextEditingValue& next) {
email = next;
});
}

Writing the complete event value preserves selection, affinity, and composition. Validation reports domain state and does not rewrite the edit.

TextSpan(text).Style(TextSpanStyle).Link(Uri) builds character runs. AttributedText accepts text, an initializer list of spans, or a span range. It owns shared immutable text/styles/links; copying it is suitable for State and component arguments.

AttributedText::FromRanges(text, styles, links = {}) accepts UTF-16 ranges. Each style/link list must be ordered and non-overlapping within itself. Endpoints must not split surrogate pairs. Style and link ranges are independent and may cross one another. WithStyles(...) replaces styles while preserving the shared body, links, and inline objects. PlainText(), Length(), StyleRanges(), LinkRanges(), and TextInRange() inspect content.

WithInlineObjects(vector<TextInlineObject>) replaces object annotations. Each annotation names a U+FFFC replacement character by UTF-16 offset and supplies a positive width with nonnegative ascent and descent. Offsets must be strictly increasing, dimensions finite, and total height positive. An empty list clears the annotations. InlineObjects() borrows the ordered annotation list. Text drawing leaves the reserved boxes blank so the caller can fill them using the layout’s object rectangles.

TextSpanStyle partially overrides font, size, weight, slant, foreground, background, and decoration. An unset field inherits; TextDecoration::None explicitly clears decoration. It is not a complete TextStyle replacement.

TextEvents::LinkActivated provides a TextLinkActivation. Links do not open themselves: decide whether to navigate internally, invoke application policy, or open an allowed external target. See Text for a complete example.

TextSelectionSource is an immutable logical snapshot with Count(), IdAt(), IndexOf(), and BlockAt(). Each TextSelectionBlock contains attributed text and a separator (newline by default). IDs are TextBlockId, stable across reorder rather than derived from current positions.

Attach a source with SelectionArea::Source(snapshot) and identify each rendered Text using SelectionBlock(id). This lets copying traverse offscreen logical blocks. A rendered Text must match its entire source block. Source methods must return synchronously and without I/O; publish a new snapshot when content changes.

TextSelection{anchor, active, affinity} preserves selection direction. Range() orders the endpoints into a half-open TextRange; it does not validate them against text or preserve which end is active. IsCollapsed() only compares endpoints. Endpoints must be in bounds in UTF-16 units and cannot split a surrogate pair.

TextEditingValue::FromText validates UTF-8, places a downstream caret at the UTF-16 end, and clears composition. That is appropriate for loading/resetting a document, not for accepting a user’s normal edit. Copy the complete OnChanged proposal for ordinary typing so selection direction and provisional IME composition survive.

composition = std::nullopt means no composition. A collapsed composition range is still an active composition; do not test its length to decide whether IME work exists. Input session IDs and synchronization revisions belong to the input client/adapter, not application TextEditingValue.

ValidationResult::None() means no validation presentation, Valid() means checked and valid, Invalid(message) supplies an error, and Pending(message = {}) reports unfinished validation. IsInvalid() tests only the Invalid status. Validate starts at Valid and stops at the first rule returning anything other than Valid, including None or Pending.

The built-in Required and EmailAddress rules are synchronous. For remote validation, publish an application-owned Pending result, launch a scoped request, and replace it only if the result still corresponds to the current input. Cancel obsolete tasks or track request identity. Do not make the rule itself block or launch a request on every render.

Decide whether to show errors immediately, after editing, or after submission in application state. For example, choose between None and Validate based on a submitted flag. Validation does not reject keyboard input, change selection, or rewrite text; use the editor’s length/line policies for input mechanics.

Applications normally use TextField, TextEditingValue, input hints, and ValidationResult. A custom input extension implements TextInputClient only when it truly owns an editor; a platform backend implements PlatformTextInput to connect IME operations. These interfaces are not necessary for changing a field’s keyboard type or adding an action.

At that boundary, keep the captured nonzero session ID and current revision with every delayed edit. A stale session must not target the next focused field. Commands use the declared TextInputCoordinateSpace and TextInputUnit, validate the batch against the current value, and preserve the distinction between text UTF-8 bytes, UTF-16 offsets, Unicode scalars, and grapheme limits. See the TextField component for the application-facing configuration surface.