FormidableLabs / use-editable

A small React hook to turn elements into fully renderable & editable content surfaces, like code editors, using contenteditable (and magic)
MIT License
483 stars 13 forks source link

Feature Suggestion: Disable line break #10

Closed mauriciosoares closed 3 years ago

mauriciosoares commented 3 years ago

Hey @kitten, thanks for this project, it's been helping me out a lot (dealing with contentEditable was a pain before I found your package :)

So I wanted to suggest that a user could pass an option to prevent the content from breaking lines... This would be particularly useful for my project, since I don't want the users to add break lines, and if you don't mind, I'd like to open a PR to add it to your main package.

My current "fix" for this looks something like this:

useEditable(titleRef, (txt) => {
    setData({
      ...data,
      title: txt.replace(/\n/g, '')
    })
  })

That's not working so great because whenever I hit ENTER, the caret loses the position, and the line break kinda blinks for a milisecond, so I imagine there might be a smarter way to disable that if I dig into your code a little bit, probably an if around here: https://github.com/kitten/use-editable/blob/main/src/useEditable.ts#L406

Thanks :)

kitten commented 3 years ago

This actually isn't well documented yet (due to a lack of examples) but the keydown handler is attached on window and checks for event.defaultPrevented 👀

What that means is that you can try to add an onKeyDown handler to your element and simply detect the enter key and prevent it using event.preventDefault() which will abort that automatic behaviour in useEditable and the browser's default behaviour.

So the idea in having all of these event handlers is that you can still layer your own logic onto event handlers on your own elements on top ✨

mauriciosoares commented 3 years ago

Wow, yeah I didn't figure that, just tried it here and it worked like a charm!

Thanks for the explanation, and also for the prompt response 🤘