Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
Indexed live suggestions

Русская версия · Immutable models · Virtual lists · Document search

Use live suggestions to choose a command, document or instrument while typing. An ordinary LineEdit supplies the query; an ordinary VirtualList<SearchItem> shows bounded ranked results. Unlike FindBar, this composition does not count matches or navigate occurrences inside a document.

Complete native program

Build portals_suggestions_example with examples enabled. Type a command prefix or a small typo, Tab to the results, select with arrows and confirm with Enter. The selection label changes; the query and its Undo history remain independent. F10 closes the application through the standard runner.

Complete source

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
#include <portals/ui_suggestions.hpp>
#include <array>
#include <string>
using namespace portals;
int main() {
return [] {
const std::array<ModelRow<std::string>, 7> commands{{
{{1, 1}, "Open file"},
{{2, 1}, "Open recent document"},
{{3, 1}, "Find in document"},
{{4, 1}, "Show cafe\u0301 notes"},
{{5, 1}, "Show Straße history"},
{{6, 1}, "Открыть справку"},
{{7, 1}, "Show 👩‍💻 workspace"}
}};
config.status = status;
config.activated = [chosen](SearchSelection selection) { chosen.text() = selection.text(); };
config.failed = [status](SearchError) { status.text() = "Search failed; the query is preserved."; };
auto browser = ui::scene(ui::vbox(
ui::label("Search commands | type a prefix or typo | F10 closes"),
ui::lineEdit(query),
ui::label("Tab to results; arrows select; Enter confirms. Ctrl+Z undoes input."),
ui::virtualList(results,
ui::suggestions(query.draftText(), RowCollection<std::string>::from(commands),
[](const std::string &text) -> std::string_view { return text; }),
std::move(config)).height(8),
ui::label(status, "Type to search the reusable index."),
ui::label(chosen, "No command chosen.")));
return std::move(browser)
| ui::onKey(key::F10, ui::quit);
}
| ui::runApp();
}
static std::expected< RowCollection, TreeError > from(std::span< const ModelRow< T > > rows, CollectionLimits limits={})
Copy a checked whole collection into private immutable storage.
Definition collection.hpp:29
Owning bounded selection; display bytes survive source and scene retirement.
Definition ui_suggestions.hpp:15
Typed Widget observation; explicit composite specializations reuse their existing weak facades.
Definition ui_ref.hpp:761
TextProperty text(TextResolver resolver={}, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1968
TextSource draftText() const
Definition ui_ref.hpp:2322
Public Portals API.
Definition action.hpp:8
SearchError
Search/provider errors, separate from scheduler and UI delivery errors.
Definition search.hpp:12
ui::ValueText text(std::format_string< const ui::detail::TextArgumentValue< Args > &... > pattern, Args &&...args)
Declare live formatted text over explicit scalar roots, fields or value properties.
Definition ui_value_text.hpp:567
Ordinary list/editor composition settings; search never commits or replaces editor text.
Definition ui_suggestions.hpp:57
std::function< void(SearchSelection)> activated
UI-only callback after exact-current list-focused activation.
Definition ui_suggestions.hpp:62
Ref< Label > status
Optional weak label; empty means no status label.
Definition ui_suggestions.hpp:61
std::function< void(SearchError)> failed
UI-only newest provider failure; draft is preserved.
Definition ui_suggestions.hpp:63

Include <portals/ui_suggestions.hpp> for this optional model recipe. ui::suggestions(query.draftText(), source, projection) follows visible input. Use committedText() when results should follow accepted model values instead. The source may be a managed model, an immutable owning snapshot or a RowCollection<T> (including its checked construction result). Stable row IDs identify domain rows, rather than positions in a changing result list.

Default match emphasis is bold and underlined, so it remains distinct on a selected row. Set VirtualListOptions::highlight to customize it; an empty style disables the emphasis.

Worker preparation and ownership

The projection returns a std::string_view borrowed from the immutable row. It runs on a worker; captures, snapshot reads and their deleters must be safe there. Never capture UI refs or mutable model storage. The worker builds and queries an index; the UI receives prevalidated display text, whole-grapheme highlight ranges and a bounded top-K result. No UI formatter scans the corpus.

Changing the query reuses the same source index. Its exact key includes source owner/pin identity, revision, projection session, normalization policy and width policy. New source snapshots require a new index. Typing during a build replaces the pending query without restarting the same build. Old completions and old selection commands cannot silently act on a replacement source.

Large index storage belongs to the background executor. UI leases retain only light control state. Retirement and idle eviction release index payload on a worker; final shutdown may release remaining payload after the UI session and worker join. A borrowed executor must provide workerStorage() support; there is no fallback that builds or destroys a large index on the UI thread.

Matching and finite work

The index canonically composes Unicode and applies full case folding, retaining a mapping to complete original graphemes. It does not strip accents or apply compatibility normalization. Full-label and whitespace-token prefixes are ranked deterministically. FUZZY_PREFIX permits one insertion, deletion or substitution for queries of at least three normalized graphemes; transpositions are not treated as a single edit. PREFIX disables that tolerance.

SearchOptions bounds source rows, projected bytes, label/query lengths, resident index storage, build scratch, query scratch, query work and highlights. Defaults allow 100,000 rows, 32 MiB of projected text and 32 results; topK is configurable from 1 to 256. Resident and build-scratch limits are 256 MiB each; the default executor's 512 MiB storage budget is shared across all its indexes, not reserved afresh per control. Query scratch has a separate default limit of 8 MiB per active query (up to 16 MiB with the default two workers). Source owners, bounded result copies and thread stacks are separate; these are not process-RSS limits. Idle entries may be evicted. Exceeding a work or memory budget reports an error rather than presenting an unproven partial ranking as an exact top-K. See the API fields for all byte/grapheme limits.

Selection, status and errors

SuggestionsConfig.status optionally connects an ordinary label to status. activated receives an owning SearchSelection after a current, focused-list activation. Its bounded display text survives source replacement. current() checks whether the selection still refers to the current source/query; it does not rebase an old row or keep the whole source index alive. The application chooses what selection means: navigate, execute a command or change another field.

failed observes the newest SearchError on the UI. Invalid input, unavailable storage, cancellation and capacity failures retain the query. Empty input clears the result list. The existing scheduler handles notification recovery and bounded capacity; no additional polling timer or UI event loop is introduced. Unrelated UI work, source acquisition and application callbacks remain the application's responsibility and must not block the UI thread.