phoenix-playground / phoenix_playground

Phoenix Playground makes it easy to create single-file Phoenix applications.
154 stars 7 forks source link

How to support hooks #6

Open Munksgaard opened 1 week ago

Munksgaard commented 1 week ago

Thanks for exciting work on Phoenix Playground! This will be great for prototyping simple ideas, showcases and bug reports.

I considered using Phoenix Playground to reproduce an issue in LiveSelect, but that would require me to install LiveSelect, which in turn requires adding some JS hooks. It doesn't seem like Phoenix Playground supports adding any hooks yet, so I was wondering if there are any plans to do so, or if that is outside of the scope of this project.

Thanks again!

wojtekmach commented 1 week ago

Thanks for the report. This is definitely in scope. Any ideas how this could work are appreciated!

wojtekmach commented 1 week ago

At the moment we have two layouts: https://github.com/phoenix-playground/phoenix_playground/blob/main/lib/phoenix_playground/layouts.ex

but we can probably get by with a single one, root.html, and put JS stuff into <head>. And then we could add an option like:

PhoenixPlayground.start(
  live: DemoLive,
  extra_head_markup: """

  """
)

this wouldn't quite be enough to pass hooks to new LiveSocket that playground is doing but something along these lines perhaps?

Munksgaard commented 1 week ago

I think something along those lines might work. I'd be tempted to try something like this

PhoenixPlayground.start(
  live: DemoLive,
  hooks: [
    {"...live_select", import: "live_select from 'live_select'"},
    {"MyHook",
     """
        // ...
     """}
  ]
)

i.e. allow either writing the hook directly or import it. You could of course make the syntax arbitrarily complex.

josecfreittas commented 2 days ago

One idea: a global hooks object that you can freely handle anywhere.

window.hooks = {}
let liveSocket = new window.LiveView.LiveSocket("/live", window.Phoenix.Socket, { hooks })

With this you can declare you hooks on you heex in a simple script tag:

    <div id="test-item" phx-hook="MyHook"></div>
    <script>
        window.hooks.MyHook = {
            mounted() {
                console.log('Hook mounted');
            }
        }
    </script>

It works fine.

joshprice commented 35 minutes ago

One idea: a global hooks object that you can freely handle anywhere.

window.hooks = {}
let liveSocket = new window.LiveView.LiveSocket("/live", window.Phoenix.Socket, { hooks })

With this you can declare you hooks on you heex in a simple script tag:

    <div id="test-item" phx-hook="MyHook"></div>
    <script>
        window.hooks.MyHook = {
            mounted() {
                console.log('Hook mounted');
            }
        }
    </script>

This was how I assumed this would work when I first tried it. Not sure how you'd ensure that the script would be run before the liveSocket is created though...