Skip to content

Instantly share code, notes, and snippets.

@ftes
Created September 5, 2022 07:00
Show Gist options
  • Save ftes/310f4003156aae9e9810672bc0168dc8 to your computer and use it in GitHub Desktop.
Save ftes/310f4003156aae9e9810672bc0168dc8 to your computer and use it in GitHub Desktop.
Phoenix LiveView + HeadlessUI
defmodule PhoenixHeadlessuiWeb.HomeLive do
@options [
%{value: "ck", label: "Clark Kent"}
]
def render(assigns) do
~H"""
<x-combobox
phx-hook="PushEvent"
phx-update="ignore"
id="react-combobox"
options={Jason.encode!(@options)}
value={@selected}
/>
"""
end
def handle_event("select", %{"value" => value}, socket) do
{:noreply, assign(socket, :selected, value)}
end
# ...
end
const PushEventHook = {
mounted() {
const target = this.el.attributes["phx-target"]?.value
this.el.__pushEvent = (event, value, onReply = () => {}) =>
target
? this.pushEventTo(target, event, value, onReply)
: this.pushEvent(event, value, onReply)
}
}
export default class ComboboxWebComponent extends HTMLElement {
connectedCallback() {
// ...
this.render()
}
attributeChangedCallback(attr, value) {
this.render()
}
render() {
const options = JSON.parse(this.getAttribute('options'))
const value = this.getAttribute('value')
const onSelect = ({ value }) => {
this.__pushEvent("select", { value })
}
this.__reactRoot.render(
<Combobox options={options} value={value} onSelect={onSelect} />
)
}
// ...
}
customElements.define('x-combobox', ComboboxWebComponent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment