Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with rails hotwire trix textarea resize #1167

Open
dcalixto opened this issue Jul 9, 2024 · 0 comments
Open

Issue with rails hotwire trix textarea resize #1167

dcalixto opened this issue Jul 9, 2024 · 0 comments

Comments

@dcalixto
Copy link

dcalixto commented Jul 9, 2024

Hello, im trying to create a textarea resize grippie more or less like the SO for a trix textarea with rais stimulus so i set this controller below

the issue is when i pull down the textarea the textarea blow all the page, and i have any idea why, someone that know hotwire better can point my mistake please?

<%= form.rich_text_area :body, required: true, data: { target: 'textarea-resizer.textarea' } %>
// app/javascript/controllers/textarea_resizer_controller.js

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["textarea", "grippie"];

  connect() {
    this.textareaTarget.classList.add("processed");
    this.setupGrippie();
  }

  setupGrippie() {
    this.grippieTarget.addEventListener("mousedown", this.startDrag.bind(this));
  }

  startDrag(event) {
    event.preventDefault();
    this.lastMousePos = this.mousePosition(event).y;
    this.staticOffset = this.textareaTarget.offsetHeight - this.lastMousePos;
    this.textareaTarget.style.opacity = 0.25;

    document.addEventListener("mousemove", this.performDrag.bind(this));
    document.addEventListener("mouseup", this.endDrag.bind(this));
  }

  performDrag(event) {
    const currentMousePos = this.mousePosition(event).y;
    let newHeight = this.staticOffset + currentMousePos;

    if (this.lastMousePos >= currentMousePos) {
      newHeight -= 5;
    }
    this.lastMousePos = currentMousePos;
    newHeight = Math.max(32, newHeight);

    this.textareaTarget.style.height = `${newHeight}px`;

    if (newHeight < 32) {
      this.endDrag(event);
    }
  }

  endDrag() {
    document.removeEventListener("mousemove", this.performDrag.bind(this));
    document.removeEventListener("mouseup", this.endDrag.bind(this));

    this.textareaTarget.style.opacity = 1;
    this.lastMousePos = 0;
    this.staticOffset = null;
  }

  mousePosition(event) {
    return {
      x: event.clientX + document.documentElement.scrollLeft,
      y: event.clientY + document.documentElement.scrollTop,
    };
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant