Skip to content
Repos

DevPlaceApp

C++ 6.6 KB188 lines Opens in site

Directory Raw Download

#include "screens/components/DevPlaceTextEditor.hpp"

#include <algorithm>
#include <cmath>

#include "screens/components/Box.hpp"
#include "spec/ComposeSpec.hpp"
#include "ui/Modifiers.hpp"
#include "ui/Palette.hpp"

namespace dp {

using namespace ui;
using spec::ComposeSpec;

float DevPlaceTextEditorMetrics::singleLineHeight() {
  return FontSpec::body().lineHeight() + 2 * ComposeSpec::kEditorMeasureInset;
}

float DevPlaceTextEditorMetrics::initialHeight(const DevPlaceTextEditorOptions& opts) {
  if (opts.initialHeight) return clampHeight(*opts.initialHeight);
  if (opts.initialLineCount > 0) {
    return clampHeight(static_cast<float>(opts.initialLineCount) * FontSpec::body().lineHeight() +
                       2 * ComposeSpec::kEditorMeasureInset);
  }
  return singleLineHeight();
}

float DevPlaceTextEditorMetrics::clampHeight(float height) {
  return std::clamp(height, singleLineHeight(), ComposeSpec::kEditorMaxHeight);
}

namespace {

// Draws the two diagonal grip strokes (INV-social 10) with round caps by stamping 1.5 pt dots.
class ResizeGripView : public View {
 protected:
  Size compute(const Proposal&) override { return {ComposeSpec::kEditorGripSize, ComposeSpec::kEditorGripSize}; }

 public:
  void draw(Canvas& c) override {
    const float step = frame_.w / 3;
    const float r = ComposeSpec::kEditorGripStroke / 2;
    for (int line = 1; line <= 2; ++line) {
      const float offset = step * static_cast<float>(line);
      const Point a{frame_.right(), frame_.y + offset};
      const Point b{frame_.x + offset, frame_.bottom()};
      const float length = std::hypot(b.x - a.x, b.y - a.y);
      const int dots = std::max(2, static_cast<int>(length / 0.4f));
      for (int i = 0; i <= dots; ++i) {
        const float t = static_cast<float>(i) / static_cast<float>(dots);
        const float x = a.x + (b.x - a.x) * t, y = a.y + (b.y - a.y) * t;
        c.fillRRect({x - r, y - r, 2 * r, 2 * r}, Corners::all(r), Palette::fg2(), ComposeSpec::kEditorGripOpacity);
      }
    }
  }
};

// Takes the whole proposal and gives its child the whole rect (an EditView otherwise keeps its one line height).
class FillView : public WrapperView {
 public:
  explicit FillView(ViewPtr child) : WrapperView(std::move(child)) {}

 protected:
  Size compute(const Proposal& p) override {
    const Size own = WrapperView::compute(p);
    return {p.w && *p.w < kInf / 2 ? *p.w : own.w, p.h && *p.h < kInf / 2 ? *p.h : own.h};
  }
};

// Fixed height container whose height lives in the UiState slot of its id. The bottom band is a drag target that
// resizes; a tap in the band falls through to the text input (focus and caret).
class ResizableFrameView : public View {
 public:
  ResizableFrameView(ViewPtr content, float initialHeight, std::shared_ptr<TextInputHandle> handle)
      : initialHeight_(initialHeight), handle_(std::move(handle)) {
    addChild(std::move(content));
  }
  bool acceptsPress() const override { return true; }
  bool wantsDrag() const override { return true; }

  void hits(Point p, std::vector<View*>& out) override {
    if (!frame_.contains(p)) return;
    if (p.y >= frame_.bottom() - ComposeSpec::kEditorResizeBand) out.push_back(this);  // the band wins over the input
    for (auto it = children_.rbegin(); it != children_.rend(); ++it) (*it)->hits(p, out);
  }

  void onDragBegin(Point p) override {
    startY_ = p.y;
    startHeight_ = currentHeight();
    moved_ = 0;
  }
  void onDragMove(Point p, Point) override {
    moved_ = std::max(moved_, std::fabs(p.y - startY_));
    Slot& s = UiState::instance().slot(id_);
    s.anim = DevPlaceTextEditorMetrics::clampHeight(startHeight_ + (p.y - startY_));
    s.flag = true;
  }
  void onDragEnd(Point p) override {
    if (moved_ >= ComposeSpec::kEditorTapSlop) return;
    if (View* input = findInput(this)) {
      if (handle_) handle_->focus();
      input->onDragBegin(p);
    }
  }

  float currentHeight() const {
    Slot& s = UiState::instance().slot(id_);
    if (!s.flag) {
      s.anim = initialHeight_;
      s.flag = true;
    }
    return DevPlaceTextEditorMetrics::clampHeight(s.anim);
  }

 protected:
  Size compute(const Proposal& p) override {
    const float w = p.w ? *p.w : 0.0f;
    const float h = currentHeight();
    children_[0]->measure(Proposal{w, h});
    return {w, h};
  }

 public:
  void place(const Rect& r) override {
    frame_ = r;
    children_[0]->place(r);
  }

 private:
  static View* findInput(View* v) {
    for (const ViewPtr& ch : v->children()) {
      if (ch->isTextInput()) return ch.get();
      if (View* f = findInput(ch.get())) return f;
    }
    return nullptr;
  }
  float initialHeight_;
  std::shared_ptr<TextInputHandle> handle_;
  float startY_ = 0, startHeight_ = 0, moved_ = 0;
};

}  // namespace

ViewPtr DevPlaceTextEditor(Binding text, DevPlaceTextEditorOptions opts) {
  auto handle = opts.handle ? opts.handle : std::make_shared<TextInputHandle>();
  TextInputOptions in;
  in.handle = handle;
  in.minLines = 1;
  in.maxLines = ComposeSpec::kEditorMaxLines;
  in.onChange = opts.onChange;
  in.onCaretChange = opts.onCaretChange;
  in.maxChars = opts.maxChars;
  in.font = FontSpec::body();

  const bool empty = !text.get || text.get().empty();
  ViewPtr input = std::make_shared<FillView>(TextEditor(text, in))->padding(Insets::all(ComposeSpec::kEditorInsetX));
  std::vector<ViewPtr> layers;
  // The placeholder layer always exists so the input keeps its view id (and focus) when the text becomes non-empty.
  if (!empty) {
    layers.push_back(EmptyView());
  } else {
    layers.push_back(Text(opts.placeholder)->foreground(Palette::fg2().opacity(ComposeSpec::kEditorPlaceholderOpacity))
                         ->padding(Insets::symmetric(ComposeSpec::kEditorInsetX, ComposeSpec::kEditorInsetY))
                         ->maxSize(Alignment::topLeading()));
  }
  layers.push_back(input);
  ViewPtr stack = ZStack(std::move(layers), Alignment::topLeading());

  ViewPtr sized;
  if (opts.sizeMode == DevPlaceTextEditorOptions::SizeMode::Fill) {
    sized = stack->maxSize(Alignment::topLeading());
  } else {
    sized = std::make_shared<ResizableFrameView>(stack->maxSize(Alignment::topLeading()),
                                                 DevPlaceTextEditorMetrics::initialHeight(opts), handle)
                ->maxWidth(Alignment::topLeading());
    ViewPtr grip = std::make_shared<ResizeGripView>();
    sized = sized->overlay(grip->padding(ComposeSpec::kEditorGripPadding), Alignment::bottomTrailing());
  }
  BoxStyle style;
  style.background = opts.background.value_or(Palette::bg1());
  style.borderOpacity = 0.5f;
  style.corner = BoxStyle::Corner::Big;
  style.padding = BoxStyle::Pad::None;
  return BoxView(sized, style)->id(opts.stateKey);
}

}  // namespace dp
66.9ms