Created
September 5, 2022 07:00
-
-
Save ftes/310f4003156aae9e9810672bc0168dc8 to your computer and use it in GitHub Desktop.
Phoenix LiveView + HeadlessUI
This file contains 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
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 |
This file contains 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
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) | |
} | |
} |
This file contains 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
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