Skip to content

Commit

Permalink
Submit chat comment with enter
Browse files Browse the repository at this point in the history
  • Loading branch information
axelclark committed Apr 20, 2024
1 parent 34e7367 commit e0cd185
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 4 deletions.
5 changes: 5 additions & 0 deletions assets/js/app.js
Expand Up @@ -61,6 +61,11 @@ window.addEventListener(`phx:animate`, (e) => {
}
})

window.addEventListener(`phx:clear-textarea`, (e) => {
let el = document.getElementById(e.detail.id)
el.value = ""
})

// connect if there are any LiveViews on the page
liveSocket.connect()

Expand Down
14 changes: 14 additions & 0 deletions assets/js/hooks/enter-submit-hook.js
@@ -0,0 +1,14 @@
const EnterSubmitHook = {
mounted() {
this.el.addEventListener("keydown", (e) => {
if (e.key == "Enter" && e.shiftKey == false) {
this.el.form.dispatchEvent(
new Event("submit", { bubbles: true, cancelable: true })
)
this.el.value = ""
}
})
},
}

export default EnterSubmitHook
6 changes: 4 additions & 2 deletions assets/js/hooks/index.js
@@ -1,9 +1,11 @@
import SortableInputsFor from "./sortable-hooks"
import ChatScrollToBottom from "./chat-hooks"
import EnterSubmitHook from "./enter-submit-hook"
import LocalTimeHook from "./local-time-hooks"
import SortableInputsFor from "./sortable-hooks"

export default {
SortableInputsFor,
ChatScrollToBottom,
EnterSubmitHook,
LocalTimeHook,
SortableInputsFor,
}
7 changes: 5 additions & 2 deletions lib/ex338_web/live/championship_live/chat_component.ex
Expand Up @@ -36,7 +36,10 @@ defmodule Ex338Web.ChampionshipLive.ChatComponent do

case Chats.create_message(message_params) do
{:ok, _message} ->
{:noreply, push_patch(socket, to: socket.assigns.patch)}
{:noreply,
socket
|> push_event("clear-textarea", %{id: "message_content"})
|> push_patch(to: socket.assigns.patch)}

{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
Expand Down Expand Up @@ -66,11 +69,11 @@ defmodule Ex338Web.ChampionshipLive.ChatComponent do
<label for="comment" class="sr-only">Add your comment</label>
<.input
field={@form[:content]}
phx-debounce="blur"
type="commenttextarea"
rows="2"
class="block w-full resize-none border-0 bg-transparent py-1.5 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="Add your comment..."
phx-hook="EnterSubmitHook"
/>
</div>
Expand Down

0 comments on commit e0cd185

Please sign in to comment.