-
-
Save davidvanleeuwen/1665f297fe02f8c88aad889f47a90bf1 to your computer and use it in GitHub Desktop.
Contenteditables in Phoenix Liveview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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})) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<.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