#include "screens/create/CreatePostScreen.hpp"
#include "api/DevPlaceError.hpp"
#include "core/Log.hpp"
#include "core/TextCount.hpp"
#include "screens/AppContext.hpp"
#include "screens/components/AccessibleLabel.hpp"
#include "screens/components/AlertPresenter.hpp"
#include "screens/components/Box.hpp"
#include "screens/components/DevPlaceTextEditor.hpp"
#include "spec/ComposeSpec.hpp"
#include "spec/ModelLimits.hpp"
#include "store/AppState.hpp"
#include "store/SettingsStore.hpp"
#include "ui/Controls.hpp"
#include "ui/Overlays.hpp"
#include "ui/Palette.hpp"
namespace dp {
using namespace ui;
using spec::ComposeSpec;
using spec::ModelLimits;
namespace {
std::string trimmed(const std::string& s) {
std::size_t a = 0, b = s.size();
while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;
while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;
return s.substr(a, b - a);
}
struct PickerEntry {
std::string title;
bool checked;
std::function<void()> action;
};
// "<label> <value> v": tapping the value opens a menu (SwiftUI Picker, menu style).
ViewPtr pickerRow(const std::string& label, const std::string& value, std::vector<PickerEntry> entries, const std::string& key) {
ViewPtr chip = OnTapRect(HStack({Text(value)->foreground(Palette::accent())->lineLimit(1),
Icon("chevron.up.chevron.down", 13)->foreground(Palette::accent())}, 4)
->paddingV(6)->paddingH(2)->contentShape(),
[entries](Rect anchor) {
std::vector<MenuItem> items;
for (const auto& e : entries) items.push_back({e.title, "", false, e.checked, e.action});
Overlays::instance().menu(anchor, std::move(items));
});
return HStack({Text(label), chip->id(key), Spacer()}, 8);
}
} // namespace
CreatePostScreen::CreatePostScreen(std::optional<PostDetail> editing)
: editing_(std::move(editing)),
uploader_(AttachmentUploader::Options{false, {}, nullptr}) {
if (editing_) {
topic_ = PostTopic::fromRaw(editing_->post.topic.value_or("")).value_or(PostTopic::Random);
title_ = editing_->post.title.value_or("");
message_ = editing_->post.content;
} else {
title_ = SettingsStore::instance().draftPostTitle();
message_ = SettingsStore::instance().draftPostMessage();
}
}
CreatePostScreen::~CreatePostScreen() {
*alive_ = false;
cleanup();
}
std::string CreatePostScreen::title() const { return isEditing() ? ComposeSpec::kTitleEdit : ComposeSpec::kTitleCreate; }
bool CreatePostScreen::canSubmit() const {
const auto titleLength = static_cast<std::size_t>(TextCount::utf16(title_));
const auto messageLength = static_cast<std::size_t>(TextCount::utf16(message_));
return titleLength <= ModelLimits::kMaxPostTitleLength && messageLength <= ModelLimits::kMaxPostContentLength &&
messageLength >= ModelLimits::kMinPostContentLength;
}
void CreatePostScreen::setTitle(const std::string& value) {
title_ = value;
if (!isEditing()) SettingsStore::instance().setDraftPostTitle(title_);
}
void CreatePostScreen::setMessage(const std::string& value) {
message_ = value;
if (!isEditing()) SettingsStore::instance().setDraftPostMessage(message_);
}
void CreatePostScreen::addPoll() {
poll_.ensureMinimumOptions();
isPollAdded_ = true;
}
void CreatePostScreen::removePoll() { isPollAdded_ = false; }
void CreatePostScreen::onAppear() {
if (!projectsRequested_) loadProjects();
}
void CreatePostScreen::onDisappear() { cleanup(); }
void CreatePostScreen::cleanup() {
if (!uploader_.attachments().empty()) uploader_.deleteUnsubmittedAttachments();
}
void CreatePostScreen::loadProjects() {
projectsRequested_ = true;
projectsLoading_ = true;
auto alive = alive_;
AppContext::api().profile(std::nullopt, [this, alive](Result<Profile> r) {
if (!*alive) return;
projectsLoading_ = false;
if (!r.ok()) {
Log::warn("Failed to load projects: " + r.error().message);
return;
}
projects_ = r.value().projects;
if (projects_.size() > ComposeSpec::kMaxProjects) projects_.resize(ComposeSpec::kMaxProjects);
});
}
void CreatePostScreen::resetFields() {
setTitle("");
setMessage("");
uploader_.forget();
isPollAdded_ = false;
poll_.reset();
selectedProjectId_.reset();
}
void CreatePostScreen::dismiss() { Overlays::instance().dismissSheetContaining(this); }
void CreatePostScreen::submit() {
if (isLoading_ || !canSubmit()) return;
isLoading_ = true;
std::optional<std::string> cleanTitle = trimmed(title_);
if (cleanTitle->empty()) cleanTitle.reset();
auto alive = alive_;
auto finished = [this, alive](Result<Unit> r) {
if (!*alive) return;
if (!r.ok()) {
isLoading_ = false;
AlertPresenter::showError(r.error());
return;
}
// try? loadFeed: errors are ignored, the flow continues either way.
AppState::instance().loadFeed(AppContext::api(), [this, alive](Result<Unit>) {
if (!*alive) return;
isLoading_ = false;
resetFields();
auto complete = onComplete_;
dismiss();
if (complete) complete();
});
};
DevPlaceApi& api = AppContext::api();
if (editing_) {
if (!editing_->post.slug) {
isLoading_ = false;
AlertPresenter::showError(DevPlaceError::postNotEditable());
return;
}
api.editPost(*editing_->post.slug, cleanTitle.value_or(""), topic_, message_, selectedProjectId_.value_or(""), finished);
} else {
std::optional<std::string> question;
std::vector<std::string> options;
if (isPollAdded_) {
question = poll_.question;
options = poll_.options;
}
api.createPost(cleanTitle, topic_, message_, uploader_.attachments(), question, options, selectedProjectId_, finished);
}
}
ViewPtr CreatePostScreen::toolbarLeading() {
return WithAccessibleLabel(ToolbarIconButton("xmark", [this] { dismiss(); })->id("close"), ComposeSpec::kClose);
}
ViewPtr CreatePostScreen::toolbarTrailing() {
if (isLoading_) return ProgressSpinner(20);
return WithAccessibleLabel(ToolbarIconButton(isEditing() ? "checkmark" : "paperplane.fill", [this] { submit(); })
->disabled(!canSubmit())->id("submit"),
isEditing() ? ComposeSpec::kSave : ComposeSpec::kCreate);
}
ViewPtr CreatePostScreen::topicArea() {
std::vector<PickerEntry> entries;
for (const PostTopic& t : PostTopic::all()) {
entries.push_back({t.name(), t == topic_, [this, t] { topic_ = t; }});
}
return pickerRow(ComposeSpec::kTopic, topic_.name(), std::move(entries), "topic-picker");
}
ViewPtr CreatePostScreen::titleArea() {
TextInputOptions o;
o.placeholder = ComposeSpec::kTitlePlaceholder;
o.handle = titleHandle_;
auto message = messageHandle_;
o.onSubmit = [message] { message->focus(); };
ViewPtr field = DevPlaceField(TextField(Binding{[this] { return title_; }, [this](const std::string& v) { setTitle(v); }}, o));
ViewPtr counter = CharacterCounter(TextCount::utf16(title_), static_cast<int>(ModelLimits::kMaxPostTitleLength))
->paddingH(ComposeSpec::kCreateCounterPadH)->maxWidth(Alignment::leading());
return VStack({field, counter}, ComposeSpec::kCreateFieldGap, HAlign::Leading);
}
ViewPtr CreatePostScreen::messageArea() {
DevPlaceTextEditorOptions o;
o.placeholder = ComposeSpec::kMessagePlaceholder;
o.initialLineCount = ComposeSpec::kEditorInitialLines;
o.handle = messageHandle_;
o.stateKey = "create-post-message";
ViewPtr editor = DevPlaceTextEditor(Binding{[this] { return message_; }, [this](const std::string& v) { setMessage(v); }}, o);
ViewPtr counter = CharacterCounter(TextCount::utf16(message_), static_cast<int>(ModelLimits::kMaxPostContentLength),
static_cast<int>(ModelLimits::kMinPostContentLength))
->paddingH(ComposeSpec::kCreateCounterPadH)->maxWidth(Alignment::leading());
return VStack({editor, counter}, ComposeSpec::kCreateFieldGap, HAlign::Leading);
}
ViewPtr CreatePostScreen::attachmentsArea() { return uploader_.view(); }
ViewPtr CreatePostScreen::pollArea() {
const std::string label = isPollAdded_ ? ComposeSpec::kRemovePoll : ComposeSpec::kAddPoll;
ViewPtr toggle = Button(BoxView(HStack({Icon("chart.bar.yaxis", 16), Text(label)}, 6)->maxWidth(Alignment::leading())),
[this] { if (isPollAdded_) removePoll(); else addPoll(); }, ButtonStyles::automatic())
->id("poll-toggle");
std::vector<ViewPtr> col{toggle};
if (isPollAdded_) col.push_back(poll_.view());
return VStack(col, ComposeSpec::kPollSpacing, HAlign::Leading)->maxWidth(Alignment::leading());
}
ViewPtr CreatePostScreen::projectArea() {
if (projects_.empty()) return EmptyView();
std::vector<PickerEntry> entries;
entries.push_back({ComposeSpec::kNone, !selectedProjectId_, [this] { selectedProjectId_.reset(); }});
std::string current = ComposeSpec::kNone;
for (const Project::Data& p : projects_) {
const bool checked = selectedProjectId_ && *selectedProjectId_ == p.id;
if (checked) current = p.title;
const std::string id = p.id;
entries.push_back({p.title, checked, [this, id] { selectedProjectId_ = id; }});
}
return pickerRow(ComposeSpec::kLinkToProject, current, std::move(entries), "project-picker");
}
ViewPtr CreatePostScreen::body() {
std::vector<ViewPtr> col{topicArea(), titleArea(), messageArea()};
if (!isEditing()) {
col.push_back(attachmentsArea());
col.push_back(pollArea());
}
col.push_back(projectArea());
ViewPtr content = VStack(col, ComposeSpec::kCreateSpacing, HAlign::Leading)->maxWidth(Alignment::leading())->padding(16)->disabled(isLoading_);
return ScrollView(ContentColumn(content));
}
} // namespace dp