5#include <portals/detail/model_edit.hpp>
6#include <portals/ui_form_field.hpp>
7#include <portals/ui_model.hpp>
12template <
class Row,
class Value>
class RowField;
13template <
class Row,
class Value>
class EditField;
25 std::function<std::expected<std::string, TreeError>(
const Value &)>
format;
26 std::function<std::expected<Value, TreeError>(std::string_view)>
parse;
32 std::shared_ptr<const Value>
34 std::shared_ptr<const Value>
draft;
40#include <portals/detail/ui_model_edit_core.hpp>
42namespace portals::ui {
48template <
class Row>
class EditSession {
50 EditSession() =
default;
56 template <
class Value> EditField<Row, Value>
field(Value
Row::*member)
const {
57 return makeField({}, member, {});
66 template <
class Value>
67 EditField<Row, Value>
field(std::string_view key, Value
Row::*member,
69 return makeField(key, member, std::move(endpoint),
true);
76 const auto state = state_;
78 auto result = commitChecked();
79 return detail::EditAccess::command(navigation, result, origin);
87 const auto state = state_;
89 auto result = cancelChecked();
90 return detail::EditAccess::command(navigation, result, origin);
94 std::shared_ptr<const EditCommitResult>
lastResult()
const {
95 return state_ && state_->ownerThread == std::this_thread::get_id() ? state_->last :
nullptr;
100 const auto state = state_;
104 if (state->ownerThread != std::this_thread::get_id()) {
107 if (state->accounting) {
110 if (state->endpointClosed) {
113 for (
const auto &entry : state->entries) {
117 auto retained = entry;
118 return retained->reply(receipt);
126 template <
class,
class>
friend class EditField;
128 template <
class,
class>
friend class RowField;
130 std::expected<void, TreeError> commitChecked()
const;
131 std::expected<void, TreeError> cancelChecked()
const;
132 std::shared_ptr<detail::EditState<Row>> state_;
133 template <
class Value>
135 bool persistent =
false)
const;
146 const auto state = state_;
147 const auto definition = definition_;
149 if (!state || !definition) {
152 if (state->ownerThread != std::this_thread::get_id()) {
155 auto position = state->current();
157 return std::unexpected(position.error());
159 auto entry = state->entry(definition, *position);
160 return entry ? inspect(**entry) : std::unexpected(entry.error());
162 }
catch (
const std::bad_alloc &) {
164 }
catch (
const std::length_error &) {
174 auto entry = retained(target);
175 return entry ? inspect(**entry) : std::unexpected(entry.error());
177 }
catch (
const std::bad_alloc &) {
179 }
catch (
const std::length_error &) {
187 std::expected<EditStatus, TreeError>
set(
const Value &value)
const {
188 const auto state = state_;
189 const auto definition = definition_;
191 if (!state || !definition) {
194 if (state->ownerThread != std::this_thread::get_id()) {
197 if (state->accounting) {
200 auto position = state->current();
202 return std::unexpected(position.error());
204 auto entry = state->entry(definition, *position);
206 return std::unexpected(entry.error());
208 if (!(*entry)->endpoint->capabilities().writable) {
211 if (editorValidate_ && !(*editorValidate_)(value)) {
214 if (definition->textCodec || std::same_as<Value, std::string>) {
215 std::optional<std::string> formattedValue;
216 const std::string *formatted =
nullptr;
217 if constexpr (std::same_as<Value, std::string>) {
218 if (!definition->textCodec) {
223 auto converted = (*entry)->format(value);
225 return std::unexpected(converted.error());
227 formattedValue.emplace(*converted);
228 formatted = &*formattedValue;
230 for (
const auto &weak : state->bindings) {
231 auto binding = weak.lock();
232 if (binding && !binding->closed && binding->displayedEntry == entry->get() &&
233 detail::preferredEditBinding(state->bindings, binding)) {
234 auto result = binding->setText(*formatted);
236 return std::unexpected(result.error());
245 if ((*entry)->text) {
246 auto updated = (*entry)->setRetainedText(value, *formatted);
248 return std::unexpected(updated.error());
251 auto result = (*entry)->commit();
252 return result ? std::expected<EditStatus, TreeError>(result->status) : std::unexpected(result.error());
257 if (!(*entry)->endpoint->capabilities().writable) {
260 auto charge = (*entry)->retainedCharge(&value, (*entry)->textCharge,
true);
262 return std::unexpected(charge.error());
264 auto checked = state->checkCredit(**entry, *charge);
266 return std::unexpected(checked.error());
268 auto candidate = std::make_shared<const Value>(value);
269 charge = (*entry)->retainedCharge(candidate.get(), (*entry)->textCharge);
271 return std::unexpected(charge.error());
273 if ((*entry)->discarded || state->endpointClosed) {
276 auto admitted = state->admit(**entry, *charge);
278 return std::unexpected(admitted.error());
280 const auto previousDraft = std::exchange((*entry)->draft, std::move(candidate));
281 ++(*entry)->generation;
284 auto result = (*entry)->commit();
285 return result ? std::expected<EditStatus, TreeError>(result->status) : std::unexpected(result.error());
289 }
catch (
const std::bad_alloc &) {
291 }
catch (
const std::length_error &) {
306 auto entry = retained(target);
308 return std::unexpected(entry.error());
310 if (!(*entry)->text) {
311 return std::expected<std::optional<std::string>,
TreeError>(std::in_place, std::nullopt);
314 return std::expected<std::optional<std::string>,
TreeError>(std::in_place, std::in_place,
315 (*entry)->text->text.bytes());
316 }
catch (
const std::bad_alloc &) {
318 }
catch (
const std::length_error &) {
331 auto entry = retained(target);
332 return entry ? (*entry)->cancel(
true) : std::unexpected(entry.error());
334 }
catch (
const std::bad_alloc &) {
336 }
catch (
const std::length_error &) {
347 if (!state_ || !definition_ || state_->ownerThread != std::this_thread::get_id()) {
350 definition_->
validate = std::move(rule);
355 std::shared_ptr<detail::EditState<Row>> state_;
356 std::shared_ptr<detail::EditDefinition<Row, Value>> definition_;
357 std::shared_ptr<
const std::function<bool(
const Value &)>> editorValidate_;
363 std::expected<std::shared_ptr<detail::EditEntry<Row, Value>>,
TreeError> retained(
const EditTarget &target)
const {
364 if (state_ && state_->ownerThread != std::this_thread::get_id()) {
367 if (!state_ || !definition_ || target.
field != definition_->key) {
370 for (
const auto &base : state_->entries) {
371 if (base->target.resource == target.
resource && base->target.session == target.
session &&
372 base->target.row == target.
row && base->target.field == target.
field &&
373 base->target.sourceSession == target.
sourceSession && !base->discarded) {
374 auto value = std::dynamic_pointer_cast<detail::EditEntry<Row, Value>>(base);
375 return value ? std::expected<std::shared_ptr<detail::EditEntry<Row, Value>>,
TreeError>(std::move(value))
376 : std::unexpected(
TreeError::INVALID_ARGUMENT);
382 static std::expected<EditFieldSnapshot<Value>,
TreeError> inspect(detail::EditEntry<Row, Value> &entry) {
383 auto draft = entry.draft;
384 if (entry.text && entry.text->dirty) {
385 if constexpr (std::same_as<Value, std::string>) {
386 if (!entry.definition->textCodec) {
387 draft = std::make_shared<const Value>(entry.text->text.bytes());
390 if (entry.definition->textCodec) {
391 auto candidate = entry.parse(entry.text->text.bytes());
393 return std::unexpected(candidate.error());
395 draft = candidate ? std::make_shared<const Value>(*candidate) : nullptr;
398 return EditFieldSnapshot<Value>{
399 entry.target, entry.accepted, std::move(draft),
405template <
class Value>
407 std::shared_ptr<EditEndpoint<Value>> endpoint,
408 bool persistent)
const {
409 static_assert(std::copy_constructible<Value> && std::copy_constructible<Row>,
410 "Edit fields require owning copyable values");
411 static_assert(!std::is_pointer_v<Value> && !portals::detail::IS_BORROWED_DERIVED_VALUE<Value> &&
412 !std::ranges::view<Value>,
413 "Edit fields cannot retain borrowed values");
414 if (!state_ || !member || state_->ownerThread != std::this_thread::get_id() || (persistent && key.empty())) {
417 for (
const auto &base : state_->definitions) {
418 auto definition = std::dynamic_pointer_cast<detail::EditDefinition<Row, Value>>(base);
419 if (persistent && base->key.name() == key && (!definition || definition->member != member)) {
422 if (definition && definition->member == member &&
423 (key.empty() ? !definition->key.persistent() : definition->key.name() == key)) {
425 field.state_ = state_;
426 field.definition_ = std::move(definition);
430 auto definition = std::make_shared<detail::EditDefinition<Row, Value>>();
431 definition->member = member;
432 definition->endpoint = std::move(endpoint);
433 definition->prepare =
434 [weakState = std::weak_ptr(state_), weakField = std::weak_ptr(definition)](
435 const NavigationPosition &position,
436 const std::shared_ptr<portals::detail::ManagedModelSource> &source) -> std::expected<void, TreeError> {
437 auto state = weakState.lock();
438 auto field = weakField.lock();
439 if (field && !field->active) {
442 if (field && ((field->endpoint && !field->endpoint->capabilities().writable) ||
443 (!field->endpoint && !detail::EditAccess::sequence(detail::EditAccess::model<Row>(source))))) {
446 if (!state || !field) {
449 auto ready = state->entry(field, position, source);
450 return ready ? std::expected<void, TreeError>{} : std::unexpected(ready.error());
457 definition->key = std::move(*
id);
461 state_->definitions.push_back(definition);
463 field.state_ = state_;
464 field.definition_ = std::move(definition);
473 result.state_ = std::make_shared<detail::EditState<Row>>(std::move(navigation), options);
480std::vector<std::shared_ptr<EditEntryBase>> displayedEntries(
const std::shared_ptr<EditState<Row>> &state) {
481 std::vector<std::shared_ptr<EditEntryBase>> result(0);
482 bool displayed =
false;
483 for (
const auto &weak : state->bindings) {
484 auto binding = weak.lock();
485 if (!binding || binding->closed) {
489 if (!binding->displayedEntry) {
492 for (
const auto &entry : state->entries) {
493 if (entry.get() == binding->displayedEntry && std::ranges::find(result, entry) == result.end()) {
494 result.push_back(entry);
499 for (
const auto &entry : state->entries) {
500 const bool sameRecord = std::ranges::any_of(result, [&](
const auto &visible) {
501 return visible->target.resource == entry->target.resource && visible->target.session == entry->target.session &&
502 visible->target.row == entry->target.row && visible->target.sourceSession == entry->target.sourceSession;
504 if (sameRecord && !entry->discarded && std::ranges::find(result, entry) == result.end()) {
505 result.push_back(entry);
510 auto position = state->current();
514 for (
const auto &entry : state->entries) {
515 if (entry->target.resource == position->resource && position->row == entry->target.row && !entry->discarded) {
516 result.push_back(entry);
527struct EditCommandField {
528 std::shared_ptr<EditEntryBase> entry;
529 std::shared_ptr<portals::detail::EditTextBinding> binding;
532template <
class Row> std::vector<EditCommandField> editCommandPlan(
const std::shared_ptr<EditState<Row>> &state) {
533 const auto entries = displayedEntries(state);
534 std::vector<EditCommandField> plan(0);
535 plan.reserve(entries.size());
536 for (
const auto &entry : entries) {
537 auto chosen = selectEditBinding(state->bindings, entry.get());
538 plan.push_back({entry, std::move(chosen)});
543inline std::expected<EditReceipt, TreeError> commitEditField(
const EditCommandField &field) {
544 if (!field.binding) {
545 return field.entry->commit();
547 if (field.binding->closed || field.binding->displayedEntry != field.entry.get()) {
550 if (!field.entry->hasDraft() && (field.binding->readOnly || !field.binding->writable)) {
553 auto completed = field.binding->complete(
false);
555 return std::unexpected(completed.error());
558 return field.entry->lastReceipt;
561 if (field.entry->lastReceipt.status ==
EditStatus::PENDING && field.entry->lastReceipt.target.sequence) {
562 return field.entry->lastReceipt;
574 if (completed->error) {
575 return std::unexpected(*completed->error);
583template <
class Row> std::expected<void, TreeError> EditSession<Row>::commitChecked()
const {
584 const auto state = state_;
588 if (state->ownerThread != std::this_thread::get_id()) {
591 if (state->endpointClosed) {
594 if (state->accounting) {
598 auto alive = state->current();
600 return std::unexpected(alive.error());
602 auto plan = detail::editCommandPlan(state);
604 auto eligible = state->fixed->origin->tree->inputEligible(state->fixed->origin->node);
606 return std::unexpected(eligible.error());
611 for (
auto &field : plan) {
612 field.binding.reset();
616 auto result = std::make_shared<EditCommitResult>();
617 result->fields.reserve(plan.size());
618 state->last = result;
619 bool rejected =
false;
620 for (
const auto &field : plan) {
621 const auto previousSequence = field.entry->lastReceipt.target.sequence;
622 std::expected<EditReceipt, TreeError> receipt;
624 receipt = detail::commitEditField(field);
625 }
catch (
const std::bad_alloc &) {
631 auto partial = field.entry->lastReceipt.target.sequence != previousSequence
632 ? field.entry->lastReceipt
634 partial.error = receipt.error();
635 result->fields.push_back(std::move(partial));
636 return std::unexpected(receipt.error());
640 result->fields.push_back(std::move(*receipt));
643 }
catch (
const std::bad_alloc &) {
650template <
class Row> std::expected<void, TreeError> EditSession<Row>::cancelChecked()
const {
651 const auto state = state_;
655 if (state->ownerThread != std::this_thread::get_id()) {
658 if (state->endpointClosed) {
661 if (state->accounting) {
665 auto alive = state->current();
667 return std::unexpected(alive.error());
669 auto plan = detail::editCommandPlan(state);
671 auto eligible = state->fixed->origin->tree->inputEligible(state->fixed->origin->node);
673 return std::unexpected(eligible.error());
676 for (
auto &field : plan) {
677 field.binding.reset();
681 for (
const auto &field : plan) {
682 if (field.binding && (field.binding->closed || field.binding->displayedEntry != field.entry.get())) {
685 auto prepared = field.entry->prepareCancel();
694 const std::vector<detail::EditCommandField> &plan;
697 for (
const auto &field : plan) {
698 field.entry->cancelReadPinned =
false;
703 for (
const auto &field : plan) {
704 field.entry->cancelReadPinned =
true;
706 for (
const auto &field : plan) {
708 if (field.binding->closed || field.binding->displayedEntry != field.entry.get()) {
711 auto canceled = field.binding->complete(
true);
713 return std::unexpected(canceled.error());
719 auto canceled = field.entry->cancel(
false);
725 }
catch (
const std::bad_alloc &) {
734template <
class Row,
class Value>
struct EditTextMount {
735 EditField<Row, Value> field;
736 portals::detail::EditTextBinding *binding{};
737 LineEditOptions options;
738 std::unique_ptr<portals::detail::EditTextDraft> empty;
739 std::shared_ptr<const PropertyChange<std::string>> emptySnapshot;
740 std::shared_ptr<const FieldValidation> unchecked;
741 EditEntry<Row, Value> *creditedEntry{};
742 std::size_t preparedCharge{};
743 std::size_t preparedTextCharge{};
744 bool preparedRetention{};
746 std::expected<void, TreeError>
initialize(
const LineEditOptions &value) {
748 binding->readOnly = options.readOnly;
749 auto text = GraphemeText::from(
"", options.widthPolicy, options.limits);
751 return std::unexpected(TreeError::INVALID_ARGUMENT);
753 empty = std::make_unique<portals::detail::EditTextDraft>(std::move(*text), options);
754 empty->initialized =
true;
755 emptySnapshot = std::make_shared<const PropertyChange<std::string>>();
756 unchecked = std::make_shared<const FieldValidation>();
757 binding->displayed = empty.get();
758 binding->prepared = empty.get();
759 auto ready = prepare();
763 binding->displayed = binding->prepared;
764 binding->displayedEntry = binding->preparedEntry;
768 std::expected<void, TreeError> prepareText(
const std::shared_ptr<EditEntry<Row, Value>> &entry) {
770 if (field.state_->nextGeneration == std::numeric_limits<std::uint64_t>::max()) {
771 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
773 std::optional<std::string> formatted;
774 std::string_view initial = entry->textSnapshot->value;
776 auto candidate = entry->format(*entry->draft);
778 return std::unexpected(candidate.error());
780 formatted.emplace(*candidate);
781 initial = *formatted;
783 auto text = GraphemeText::from(initial, options.widthPolicy, options.limits);
785 return std::unexpected(TreeError::INVALID_ARGUMENT);
787 auto draft = std::make_unique<portals::detail::EditTextDraft>(std::move(*text), options);
788 draft->cursor = draft->text.bytes().size();
789 draft->anchor = draft->cursor;
790 draft->revision = entry->target.baseVersion;
791 draft->generation = field.state_->nextGeneration++;
792 draft->initialized =
true;
793 draft->dirty =
static_cast<bool>(entry->draft);
795 draft->history->prepareResetBaseline({std::string(draft->text.bytes()), draft->cursor, draft->anchor});
797 return std::unexpected(TreeError::NO_MEMORY);
799 auto committed = draft->history->commit(std::move(*prepared));
801 return std::unexpected(TreeError::WOULD_BLOCK);
803 if (options.displayMode == LineEditDisplayMode::PASSWORD) {
805 GraphemeText::from(std::string(draft->text.graphemes().size(),
'*'), options.widthPolicy, options.limits);
807 return std::unexpected(TreeError::INVALID_ARGUMENT);
809 draft->mask = std::make_unique<GraphemeText>(std::move(*masked));
812 portals::detail::EditStorageAccess::draftBytes(draft->text, draft->mask.get(), draft->history->retainedBytes());
814 return std::unexpected(textCharge.error());
816 auto charge = entry->retainedCharge(entry->draft.get(), *textCharge);
818 return std::unexpected(charge.error());
820 auto admitted = field.state_->admit(*entry, *charge,
false);
824 entry->textCharge = *textCharge;
825 entry->text = std::move(draft);
830 std::expected<void, TreeError> preflight(
const NavigationPosition &position,
831 const std::shared_ptr<portals::detail::ManagedModelSource> &source) {
832 const auto &definition = field.definition_;
833 if ((definition->endpoint && !definition->endpoint->capabilities().writable) ||
834 (!definition->endpoint && !EditAccess::sequence(EditAccess::model<Row>(source)))) {
837 auto entry = field.state_->entry(definition, position, source);
838 return entry ? prepareText(*entry) : std::unexpected(entry.error());
841 std::expected<void, TreeError> prepare() {
842 auto position = field.state_->current();
844 if (position.error() == TreeError::CLOSED) {
845 binding->writable =
false;
848 return std::unexpected(position.error());
850 if (!position->row || position->resolution != PositionResolution::EXACT) {
851 binding->prepared = empty.get();
852 binding->preparedEntry =
nullptr;
855 auto entry = field.state_->entry(field.definition_, *position);
857 if (entry.error() == TreeError::WOULD_BLOCK) {
858 binding->prepared = empty.get();
859 binding->preparedEntry =
nullptr;
862 return std::unexpected(entry.error());
864 auto ready = prepareText(*entry);
868 if (binding->displayedEntry != entry->get() && binding->validation && binding->displayValidation) {
869 if (binding->displayedEntry && binding->displayedEntry == binding->preparedEntry) {
870 auto retained = preserveValidation();
875 auto shown = binding->displayValidation((*entry)->validation ? (*entry)->validation : unchecked);
880 binding->writable = (*entry)->endpoint->capabilities().writable;
881 binding->prepared = (*entry)->text.get();
882 binding->preparedEntry = entry->get();
886 std::expected<std::shared_ptr<const PropertyChange<std::string>>,
TreeError> snapshot() {
887 auto *entry =
static_cast<EditEntry<Row, Value> *
>(binding->displayedEntry);
889 return emptySnapshot;
891 auto ready = entry->refresh();
892 const bool retainedRefusal =
893 !ready && ready.error() == TreeError::NODE_LIMIT && entry->admissionRefused && entry->textSnapshot;
894 if (!ready && !retainedRefusal && ready.error() != TreeError::WOULD_BLOCK &&
895 ready.error() != TreeError::STALE_NODE && ready.error() != TreeError::CLOSED) {
896 return std::unexpected(ready.error());
898 return entry->textSnapshot;
901 std::expected<std::shared_ptr<const PropertyChange<std::string>>,
TreeError> cancelSnapshot() {
902 binding->retentionRefused =
false;
903 auto *entry =
static_cast<EditEntry<Row, Value> *
>(binding->displayedEntry);
905 return emptySnapshot;
909 if (!entry->cancelReadPinned) {
910 auto ready = entry->prepareCancel();
912 binding->retentionRefused = ready.error() == TreeError::NODE_LIMIT && entry->admissionRefused;
913 return std::unexpected(ready.error());
917 return entry->textSnapshot;
920 std::expected<std::optional<PropertyUpdate<std::string>>,
TreeError> publish(
const std::string &candidate) {
921 auto *entry =
static_cast<EditEntry<Row, Value> *
>(binding->displayedEntry);
922 if (!entry || field.state_->endpointClosed) {
923 return std::unexpected(TreeError::CLOSED);
925 binding->publicationStatus = LineEditStatus::FAILED;
926 binding->retentionRefused =
false;
927 std::optional<Value> parsed;
928 const Value *typedCandidate =
nullptr;
929 if constexpr (std::same_as<Value, std::string>) {
930 if (!field.definition_->textCodec) {
931 typedCandidate = &candidate;
934 if (!typedCandidate) {
935 auto converted = entry->parse(candidate);
937 binding->publicationStatus =
938 converted.error() == TreeError::INVALID_ARGUMENT ? LineEditStatus::VALIDATION_FAILED : LineEditStatus::FAILED;
939 return std::unexpected(converted.error());
941 parsed.emplace(*converted);
942 typedCandidate = &*parsed;
944 auto charge = entry->retainedCharge(typedCandidate, entry->textCharge,
true);
946 binding->retentionRefused = charge.error() == TreeError::NODE_LIMIT;
947 return std::unexpected(charge.error());
949 auto checked = field.state_->checkCredit(*entry, *charge);
951 binding->retentionRefused = checked.error() == TreeError::NODE_LIMIT;
952 return std::unexpected(checked.error());
954 auto retained = std::make_shared<const Value>(*typedCandidate);
955 auto snapshot = std::make_shared<PropertyChange<std::string>>(PropertyChange<std::string>{candidate, 0});
956 const auto snapshotBytes =
sizeof(PropertyChange<std::string>) + snapshot->value.capacity() + 1;
957 charge = entry->retainedCharge(retained.get(), entry->textCharge,
false, {},
nullptr,
958 std::max(entry->snapshotCharge, snapshotBytes));
960 binding->retentionRefused = charge.error() == TreeError::NODE_LIMIT;
961 return std::unexpected(charge.error());
963 auto admitted = field.state_->admit(*entry, *charge);
965 binding->retentionRefused = admitted.error() == TreeError::NODE_LIMIT;
966 return std::unexpected(admitted.error());
968 entry->draft = std::move(retained);
969 entry->status = EditStatus::DIRTY;
970 binding->publicationStatus = LineEditStatus::FAILED;
971 if (binding->validatedByEditor) {
972 entry->validatedGeneration = entry->text->generation;
974 auto receipt = entry->commit();
976 binding->retentionRefused = entry->admissionRefused;
977 return std::unexpected(receipt.error());
979 if (receipt->status == EditStatus::PENDING) {
980 return std::optional<PropertyUpdate<std::string>>{};
982 if (receipt->status != EditStatus::ACCEPTED && receipt->status != EditStatus::CLEAN) {
983 binding->publicationStatus =
984 receipt->status == EditStatus::INVALID ? LineEditStatus::VALIDATION_FAILED : LineEditStatus::CONFLICT;
985 return std::unexpected(TreeError::WOULD_BLOCK);
987 snapshot->revision = receipt->acceptedVersion;
988 if (!entry->discarded) {
989 entry->textSnapshot = snapshot;
990 entry->snapshotCharge = snapshotBytes;
992 return std::optional(
993 PropertyUpdate<std::string>{std::move(snapshot), receipt->acceptedVersion != receipt->target.baseVersion});
996 std::expected<void, TreeError> preserveValidation() {
997 auto *entry =
static_cast<EditEntry<Row, Value> *
>(binding->displayedEntry);
998 if (!entry || !binding->validation) {
1001 auto presentation = binding->validation();
1002 if (!presentation) {
1003 return std::unexpected(presentation.error());
1005 if ((*presentation)->status == FieldStatus::UNCHECKED) {
1006 auto checked = field.state_->admit(*entry, entry->charge - entry->validationCharge,
false);
1010 entry->validation.reset();
1011 entry->validationCharge = 0;
1014 const auto extra =
sizeof(FieldValidation) + (*presentation)->message.capacity() + 1;
1015 const auto limit = field.state_->options.maxRetainedBytes;
1016 const auto oldCharge = entry->charge - entry->validationCharge;
1017 if (oldCharge > limit || extra > limit - oldCharge) {
1018 return std::unexpected(TreeError::NODE_LIMIT);
1020 auto credit = field.state_->admit(*entry, oldCharge + extra);
1024 entry->validation = std::move(*presentation);
1025 entry->validationCharge = extra;
1029 std::expected<void, TreeError> admit(std::size_t textBytes,
bool retain) {
1030 auto *entry =
static_cast<EditEntry<Row, Value> *
>(binding->displayedEntry);
1032 return std::unexpected(TreeError::WOULD_BLOCK);
1034 auto charge = entry->retainedCharge(entry->draft.get(), textBytes);
1036 return std::unexpected(charge.error());
1038 auto checked = field.state_->checkCredit(*entry, *charge, retain);
1042 preparedRetention = retain;
1043 creditedEntry = entry;
1044 preparedCharge = *charge;
1045 preparedTextCharge = textBytes;
1049 void accepted() noexcept {
1050 if (!creditedEntry) {
1053 field.state_->bytes = field.state_->bytes - creditedEntry->charge + preparedCharge;
1054 creditedEntry->charge = preparedCharge;
1055 creditedEntry->textCharge = preparedTextCharge;
1056 if (preparedRetention) {
1057 creditedEntry->status = EditStatus::DIRTY;
1058 creditedEntry->requiresAsyncValidation = binding->asynchronous;
1060 creditedEntry =
nullptr;
1064template <
class Row,
class Value>
1065std::shared_ptr<portals::detail::EditTextBinding> editTextBinding(EditField<Row, Value> field,
1066 bool validateLocal =
true) {
1067 auto binding = std::make_shared<portals::detail::EditTextBinding>();
1068 auto mount = std::make_shared<EditTextMount<Row, Value>>();
1069 mount->field = field;
1070 mount->binding = binding.get();
1071 binding->definition = field.definition_.get();
1072 if (
const auto codec = field.definition_->textCodec) {
1073 binding->checkCandidate = [codec](std::string_view candidate) -> std::expected<bool, TreeError> {
1074 auto parsed = codec->parse(candidate);
1076 return std::unexpected(parsed.error());
1079 return static_cast<bool>(parsed);
1082 if (validateLocal && field.editorValidate_) {
1083 binding->checkCandidate = [field](std::string_view candidate) -> std::expected<bool, TreeError> {
1084 auto parsed = parseEditText(field.definition_->textCodec, candidate);
1087 : std::unexpected(parsed.error());
1090 return (*field.editorValidate_)(*parsed);
1092 binding->validateForCommit = binding->checkCandidate;
1094 binding->initialize = [mount](
const LineEditOptions &options) {
1095 return mount->initialize(options);
1097 binding->prepare = [mount] {
1098 return mount->prepare();
1100 binding->preflight = [mount](
const NavigationPosition &position,
1101 const std::shared_ptr<portals::detail::ManagedModelSource> &source) {
1102 return mount->preflight(position, source);
1104 binding->snapshot = [mount] {
1105 return mount->snapshot();
1107 binding->cancelSnapshot = [mount] {
1108 return mount->cancelSnapshot();
1110 binding->publish = [mount](
const std::string &candidate) {
1111 return mount->publish(candidate);
1113 binding->preserveValidation = [mount] {
1114 return mount->preserveValidation();
1116 binding->admit = [mount](std::size_t bytes,
bool retain) {
1117 return mount->admit(bytes, retain);
1119 binding->accepted = [mount] {
1122 binding->observe = [state = field.state_](Node<LineEdit> receiver,
1123 std::function<void()> callback) -> std::expected<Subscription, TreeError> {
1125 auto live = state->current();
1126 return live ? std::expected<Subscription, TreeError>(Subscription{}) : std::unexpected(
live.error());
1128 auto channel = state->managed.current();
1130 return std::unexpected(channel.error());
1132 return Access::observeEditNavigation(state->managed, receiver, std::move(callback));
1134 std::erase_if(field.state_->bindings, [](
const auto &weak) {
1135 auto value = weak.lock();
1138 field.state_->bindings.push_back(binding);
1147template <
class Row,
class Value>
1148Description<LineEdit> editLineEditRecipe(EditField<Row, Value> field,
1149 std::shared_ptr<portals::detail::EditTextBinding> source,
1150 LineEditConfig config) {
1151 if (!field.state_ || !field.definition_) {
1152 return detail::Access::cold<LineEdit>(
1153 [](ManagedScene &, Node<Widget> parent, detail::MountContext &) -> std::expected<Node<LineEdit>, ManagedError> {
1158 detail::Access::cold<LineEdit>([field, source, options = config.options, policy = config.policy](
1159 ManagedScene &scene, Node<Widget> parent,
1160 detail::MountContext &context) -> std::expected<Node<LineEdit>, ManagedError> {
1161 const ControlSettings empty;
1162 const auto &settings = context.controlSettings ? *context.controlSettings : empty;
1163 auto effective = detail::controlLineEditOptions(settings, options, scene.widthPolicy(), {}, parent);
1165 return std::unexpected(effective.error());
1167 field.definition_->maxTextBytes = effective->limits.max_input_bytes;
1168 auto resolved = field.state_->resolve(scene, context);
1170 return std::unexpected(detail::error(parent, resolved.error()));
1172 effective->editMode = field.state_->options.mode;
1173 auto placeholder = detail::lineEditPlaceholder(*effective, parent);
1175 return std::unexpected(placeholder.error());
1177 return scene.emplace<LineEdit>(parent, *effective, policy, std::move(*placeholder));
1179 config.result = [source,
1180 result = std::move(config.result)](LineEditResult receipt) -> std::expected<void, TreeError> {
1181 auto *entry =
static_cast<EditEntry<Row, Value> *
>(source->displayedEntry);
1185 const auto previousDraft = std::exchange(entry->draft, {});
1186 entry->target.baseVersion = entry->text->revision;
1189 return result ? result(std::move(receipt)) : std::expected<void,
TreeError>{};
1193 [source, config = std::move(config)](ManagedScene &scene, Node<LineEdit> node,
const ControlSettings &)
mutable {
1194 return detail::Access::bindEditText(scene, node, source, std::move(config));
1204template <
class Row> Description<LineEdit> lineEdit(EditField<Row, std::string> field, LineEditConfig config = {}) {
1205 if (!field.state_ || !field.definition_ || field.definition_->textCodec) {
1206 return detail::editLineEditRecipe(EditField<Row, std::string>{}, {}, std::move(config));
1208 auto source = detail::editTextBinding(field);
1209 return detail::editLineEditRecipe(std::move(field), std::move(source), std::move(config));
1216Description<LineEdit> lineEdit(Ref<LineEdit> reference, EditField<Row, std::string> field, LineEditConfig config = {}) {
1217 return lineEdit(std::move(field), std::move(config)).reference(std::move(reference));
1222template <
class Row,
class Value>
1223bool configureEditTextCodec(
const EditField<Row, Value> &field,
1224 const std::shared_ptr<
const EditTextCodec<Value>> &codec) {
1225 if (!field.state_ || !field.definition_ || !codec || !codec->format || !codec->parse ||
1226 field.state_->ownerThread != std::this_thread::get_id()) {
1229 if (field.definition_->textCodec && field.definition_->textCodec != codec) {
1234 if (!field.definition_->textCodec && field.definition_->active) {
1237 field.definition_->textCodec = codec;
1241template <
class Row,
class Value>
1242Description<FormField> boundFormField(std::string_view caption, EditField<Row, Value> field,
1243 FormFieldConfig config = {}) {
1244 if (!field.state_ || !field.definition_) {
1245 return detail::Access::formField(std::string(caption),
1246 detail::Access::erase(detail::editLineEditRecipe(field, {}, {})), {});
1248 auto source = detail::editTextBinding(field,
false);
1249 source->asynchronous =
static_cast<bool>(config.validateAsync);
1250 source->validatedByEditor =
true;
1251 const auto required = config.required;
1252 const auto requiredMessage = config.requiredMessage;
1253 auto semantic = std::make_shared<std::function<FieldValidation(std::string_view)>>(
1254 [required, requiredMessage,
rule = std::move(config.validate),
1255 legacy = std::move(config.editor.validate)](std::string_view candidate) {
1256 if (required && candidate.empty()) {
1259 auto result =
rule ?
rule(candidate) : FieldValidation::valid();
1265 config.editor.validate = {};
1266 const auto definition = field.definition_;
1267 const auto codec = definition->textCodec;
1268 auto typedPolicy = std::make_shared<std::function<std::expected<bool, TreeError>(std::string_view)>>(
1270 localRule = field.editorValidate_](std::string_view candidate) -> std::expected<bool, TreeError> {
1271 auto parsed = parseEditText(codec, candidate);
1274 : std::unexpected(parsed.error());
1276 const auto typedRule = definition->validate;
1278 return (!typedRule || typedRule(*parsed)) && (!localRule || (*localRule)(*parsed));
1280 config.validate = [semantic, typedPolicy](std::string_view candidate) {
1281 auto result = (*semantic)(candidate);
1285 auto typed = (*typedPolicy)(candidate);
1287 throw portals::detail::EditTextFailure{typed.error()};
1292 source->validateBeforeParse = [semantic](std::string_view candidate) -> std::expected<bool, TreeError> {
1295 source->validateForCommit = [typedPolicy](std::string_view candidate) {
1296 return (*typedPolicy)(candidate);
1298 auto canceledPresentation = std::make_shared<const FieldValidation>();
1299 config.editor.result = [source, canceledPresentation, result = std::move(config.editor.result)](
1300 LineEditResult receipt) -> std::expected<void, TreeError> {
1302 auto cleared = source->displayValidation(canceledPresentation);
1307 auto preserved = source->preserveValidation();
1311 return result ? result(std::move(receipt)) : std::expected<void,
TreeError>{};
1313 return detail::Access::formField(
1314 std::string(caption),
1315 [field, source](LineEditConfig editor, ControlSettings settings) {
1316 return detail::Access::erase(
1317 detail::editLineEditRecipe(field, source, std::move(editor)).settings(std::move(settings)));
1320 .setup([source](ManagedScene &scene, Node<FormField> node) {
1321 return detail::Access::connectEditValidation(scene, node, source);
1335template <
class Row,
class Value>
1336Description<LineEdit> lineEdit(EditField<Row, Value> field, std::shared_ptr<
const EditTextCodec<Value>> codec,
1337 LineEditConfig config = {}) {
1338 if (!detail::configureEditTextCodec(field, codec)) {
1339 return detail::editLineEditRecipe(EditField<Row, Value>{}, {}, std::move(config));
1341 auto source = detail::editTextBinding(field);
1343 return detail::editLineEditRecipe(std::move(field), std::move(source), std::move(config));
1352template <
class Row,
class Value>
1353Description<FormField> formField(std::string_view caption, EditField<Row, Value> field,
1354 std::shared_ptr<
const EditTextCodec<Value>> codec, FormFieldConfig config = {}) {
1355 if (!detail::configureEditTextCodec(field, codec)) {
1359 return detail::boundFormField(caption, std::move(field), std::move(config));
1368Description<FormField> formField(std::string_view caption, EditField<Row, std::string> field,
1369 FormFieldConfig config = {}) {
1370 if (field.definition_ && field.definition_->textCodec) {
1374 return detail::boundFormField(caption, std::move(field), std::move(config));
Source capability adapter; calls must return promptly without UI I/O. External work is submitted thro...
Definition model_edit.hpp:124
static std::expected< EditFieldKey, TreeError > create(std::string_view value)
static EditFieldKey local(std::uint64_t identity) noexcept
Owning checked editor command, preserving exactly its collector reporting receipt....
Definition editor_command.hpp:23
Weak UI-affine navigation handle owned by an existing scene/model scope. Removing a view does not rem...
Definition managed_navigation.hpp:119
Lay visible children from left to right.
Definition layout.hpp:250
UI-thread-affine typed field capability with exact-target retained inspection and discard.
Definition ui_model_edit.hpp:139
EditField validate(std::function< bool(const Value &)> rule) const
Definition ui_model_edit.hpp:346
std::expected< void, TreeError > discard(const EditTarget &target) const
Definition ui_model_edit.hpp:329
std::expected< EditFieldSnapshot< Value >, TreeError > snapshot() const
Definition ui_model_edit.hpp:145
std::expected< EditFieldSnapshot< Value >, TreeError > snapshot(const EditTarget &target) const
Definition ui_model_edit.hpp:172
std::expected< EditStatus, TreeError > set(const Value &value) const
Definition ui_model_edit.hpp:187
std::expected< std::optional< std::string >, TreeError > draftText(const EditTarget &target) const
Copy retained editor bytes without parsing, refreshing or changing the displayed target.
Definition ui_model_edit.hpp:304
Owning UI-thread-affine current-record editing descriptor; no runtime is created before mount....
Definition ui_model_edit.hpp:48
EditorCommandResult cancel(std::source_location origin=std::source_location::current()) const
Definition ui_model_edit.hpp:86
std::expected< bool, TreeError > applyReply(const EditReceipt &receipt) const
Definition ui_model_edit.hpp:99
EditorCommandResult commit(std::source_location origin=std::source_location::current()) const
Definition ui_model_edit.hpp:75
std::shared_ptr< const EditCommitResult > lastResult() const
Definition ui_model_edit.hpp:94
EditField< Row, Value > field(std::string_view key, Value Row::*member, std::type_identity_t< std::shared_ptr< EditEndpoint< Value > > > endpoint={}) const
Typed field with an explicit persistent schema key.
Definition ui_model_edit.hpp:67
EditField< Row, Value > field(Value Row::*member) const
Typed field with a process-local member shorthand.
Definition ui_model_edit.hpp:56
Cold explicit shared navigation; ordinary model-source views stay independent.
Definition ui_model.hpp:248
Weak exact-record factory/action context; it never follows a recycled position.
Definition ui_virtual_rows.hpp:554
Weak row-qualified field capability; saved descriptors do not keep UI assignments alive.
Definition ui_virtual_rows.hpp:421
consteval auto rule(S target, D... declarations)
Definition style_static.hpp:1366
auto live(ManagedScene &scene, const S &description)
Definition style_static.hpp:1703
std::expected< void, ProcessContextError > initialize(int argc, const char *const *argv)
Capture argv and the environment once, before any concurrent foreign environment mutation....
@ VALID
The checked candidate satisfied all configured synchronous rules.
Definition form_field.hpp:18
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
@ COMMITTED
Confirmation completed Property::set; inspect its exact receipt.
Definition line_edit.hpp:83
@ VALIDATION_FAILED
The commit validator rejected the complete draft.
Definition line_edit.hpp:89
@ CANCELLED
Escape adopted the latest model snapshot.
Definition line_edit.hpp:84
@ PENDING
The accepted draft awaits asynchronous semantic validation; no model write occurred.
Definition line_edit.hpp:92
@ CONFLICT
The model revision changed since this draft began.
Definition line_edit.hpp:86
EditStatus
Submission and acceptance are separate protocol states.
Definition model_edit.hpp:56
@ READ_ONLY
Source permits reads but does not expose writes.
Definition model_edit.hpp:64
@ DIRTY
Owning unpublished input.
Definition model_edit.hpp:58
@ REJECTED
Backend rejected the request without applying it.
Definition model_edit.hpp:66
@ ACCEPTED
Endpoint applied this exact qualified write.
Definition model_edit.hpp:60
@ CLEAN
Current accepted value, without a draft.
Definition model_edit.hpp:57
@ PENDING
Admitted work; no backend acceptance has been reported.
Definition model_edit.hpp:59
@ INVALID
Validation rejected the retained draft.
Definition model_edit.hpp:61
@ CONFLICT
Expected target version is no longer current.
Definition model_edit.hpp:62
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ CLOSED
The owning tree or source is closed.
Definition widget_types.hpp:31
@ CALLBACK_FAILED
A user extension or callback threw.
Definition widget_types.hpp:37
@ WRONG_THREAD
Operation requires the tree's UI thread.
Definition widget_types.hpp:28
@ STALE_NODE
The observed node or model consumer is absent or retired.
Definition widget_types.hpp:30
@ WOULD_BLOCK
The current frame/reentry boundary or finite queue/work budget rejects this operation.
Definition widget_types.hpp:32
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition widget_types.hpp:33
@ IMMEDIATE
Publish each semantic-valid text change; invalid intermediate text remains visible.
Definition line_edit.hpp:28
Bounded retained editing, independent of collection extent.
Definition model_edit.hpp:93
Owning acknowledgement qualified independently of current navigation.
Definition model_edit.hpp:70
EditTarget target
Original target and expected version.
Definition model_edit.hpp:71
Frozen write destination; ordinal hints and nearest positions are excluded.
Definition model_edit.hpp:42
SourceStamp sourceSession
UI source incarnation; the endpoint also guards its own backend incarnation.
Definition model_edit.hpp:49
RowId row
Complete stable record identity.
Definition model_edit.hpp:45
SourceStamp session
Unique edit request namespace, independent of source delivery.
Definition model_edit.hpp:44
EditFieldKey field
Owning schema key or explicitly local shorthand.
Definition model_edit.hpp:46
ModelResource resource
Source identity and compatible lineage.
Definition model_edit.hpp:43
static FieldValidation invalid(std::string message={})
Owning inspection of one exact retained target, independent of navigation.
Definition ui_model_edit.hpp:30
EditStatus status
Current retained draft, submission or acceptance state.
Definition ui_model_edit.hpp:35
std::shared_ptr< const Value > accepted
Owning last admitted accepted value; a newer read may exceed retention credit.
Definition ui_model_edit.hpp:33
EditTarget target
Exact resource, source incarnation, edit session, record and field qualification.
Definition ui_model_edit.hpp:31
std::shared_ptr< const Value > draft
Nullable owning local draft for this exact target.
Definition ui_model_edit.hpp:34
Owning scalar conversion used by the existing current-record text editor.
Definition ui_model_edit.hpp:21
std::function< std::expected< std::string, TreeError >(const Value &)> format
Complete owning editor text.
Definition ui_model_edit.hpp:25
std::function< std::expected< Value, TreeError >(std::string_view)> parse
Complete typed candidate, or an error.
Definition ui_model_edit.hpp:26
~EditTextCodec()=default
Keep owning callback transfers fallible before the checked mount boundary.
static Description< T > controlSetup(Description< T > description, Callback callback)
Attach binding setup after node creation within the mount transaction.
Definition ui_description.hpp:3460
static Description< T > configuredControl(Description< T > description, std::string_view type, bool inherit=true)
Attach a builtin configuration identity to an owning recipe.
Definition ui_description.hpp:3409