hotwired-laravel / turbo-laravel

This package gives you a set of conventions to make the most out of Hotwire in Laravel.
https://turbo-laravel.com
MIT License
795 stars 48 forks source link

Select contents of input after clicking on edit #67

Closed bilogic closed 2 years ago

bilogic commented 2 years ago

Hi!

Not sure where to ask this, appreciate if you can help.

Supposed I have a button to edit, is it possible (to run some javascript) to select all text in the input box via TurboStream after clicking to edit? Or is Stimulus the only way? Thank you!

tonysm commented 2 years ago

Not sure I follow. Can you clarify the use case? Feel free to ask here, but I'll close the issue for now as this is not related to package.

bilogic commented 2 years ago

Ok

  1. Let's say I have some text in a turbo frame that can be clicked on to edit, i.e. clicking turns it into a form with an <input> that is filled with the text
  2. When it turns into a form, the <input> is not focused
  3. How can I get it to focus?
  4. To go even further, how can I get the text in the <input> to be selected? i.e. the effect of pressing ctrl+a while in the <input>
  5. Is Stimulus the only way? My issue with Stimulus is the need for npm i && npm run dev, and my initial impression was it would be a thing of the past after I'm fully in on Turbo. (unfortunately not... haha)

Just like to add that I already managed to get infinite scrolling to work using a Stimulus controller

Thanks!

tonysm commented 2 years ago

So, if you have an autofocus attribute in your input, Turbo will find the first one with that attribute and focus it for you (here). Something like <input autofocus ... />.

If you want to select the content, you're gonna need JavaScript, since that's a browser thing. Hotwire is really about using the rule of least power to do the job, but sometimes we need JavaScript. I would add a Stimulus controller for that like:

// resources/js/controllers/select_all_controller.js
import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  connect() {
    this.element.select();
  }
}

So your input would be like:

<input autofocus data-controller="select-all" />

Something like that (I haven't tested this, it's just what I would try).

About needing NPM, yeah, I feel the pain. That's why I built the Importmap Laravel package. Here's an intro if you're interesting. The idea is to stay in PHP as much as I can

bilogic commented 2 years ago

Yes, I have seen your importmap, it will be the next thing once I reach my milestones with the Turbo integration.

I have tried autofocus a few days ago, it only works on the 1st turbo stream, the browser doesn't respect subsequent ones and I did not pursue further.

Do you mean that with importmap, I can still write controllers for Stimulus? That would be an acceptable trade off.

tonysm commented 2 years ago

@bilogic Yep. The demo app uses Importmap and makes use of Alpine, Stimulus, and other JS libs.