Skip to content

Instantly share code, notes, and snippets.

@davidvanleeuwen
Created October 27, 2022 14:34
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidvanleeuwen/1665f297fe02f8c88aad889f47a90bf1 to your computer and use it in GitHub Desktop.
Save davidvanleeuwen/1665f297fe02f8c88aad889f47a90bf1 to your computer and use it in GitHub Desktop.
Contenteditables in Phoenix Liveview
content_editable: {
mounted() {
this.titleElement = this.el.querySelector("[data-title]")
this.titleElement.addEventListener("focus", this.showText.bind(this))
this.titleElement.addEventListener("keyup", this.keyup.bind(this))
this.el.addEventListener("focusout", this.save.bind(this))
},
showText() {
const title = this.titleElement.getAttribute('data-title')
this.titleElement.innerText = title
},
keyup(e) {
if (e.key == "Enter") {
e.preventDefault()
this.titleElement.innerText = this.titleElement.innerText.replaceAll("\n", "")
this.titleElement.blur()
}
},
save() {
const input = this.el.querySelector('input')
const title = this.titleElement.innerText
if (title.length > 29) {
this.titleElement.innerText = `${title.substr(0, 29)}...`
} else {
this.titleElement.innerText = title
}
if (input.value === title) return
input.value = title
input.dispatchEvent(new Event("input", {bubbles: true}))
}
}
def contenteditable(assigns) do
~H"""
<div class="flex-grow" id="content_editable" phx-hook="content_editable">
<div data-title={@text} class="text-stone-600 text-2xl border-b border-transparent font-medium pt-0.5 mr-4 focus:bg-white focus:outline-none focus:ring-1 focus:ring-white rounded-md hover:cursor-text overflow-hidden flex whitespace-nowrap" contenteditable="true">
<%= @text |> Phoenix.HTML.SimplifiedHelpers.Truncate.truncate(length: 32) %>
</div>
<.form let={f} for={@changeset} phx-target={@target} phx-change={@update}>
<%= hidden_input f, @field %>
</.form>
</div>
"""
end
<.contenteditable text={@title} field={:title} changeset={@changeset} target={@target} update={@myself} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment