bluzky / salad_ui

Phoenix Liveview component library inspired by shadcn UI
https://salad-storybook.fly.dev/welcome
MIT License
363 stars 17 forks source link

Closing a sheet from the backend #28

Open samrat opened 1 month ago

samrat commented 1 month ago

Hi,

Thanks for making this library!

I'm trying to add a button to a sheet that sends an event back to the server and also closes the sheet. I tried this:

      <.sheet_close target="clip-preview-sheet">
        <.button type="button" id="export-video" phx-click="export-video">Export Video</.button>
      </.sheet_close>

This sends the event to the server, but doesn't close the sheet. If I understand correctly, I'll need to push an event from the backend to the frontend(when I'm handling the export-video event). I tried:

     # In the `handle_event`
     push_event(socket, "phx-hide-sheet", %{to: "#clip-preview-sheet"})}

but this didn't work. Is there a way to do this?

ahacking commented 1 month ago

There is a thread here on automatically showing a modal on edit, and automatically closing the modal on a successful submit, which could be adapted to working with the sheet.

Untested code ahead...

An idea which might work is to conditionally show and close the sheet based on the presence of a video form assigns (note the if, phx-mounted and phx-remove attrs).

...
  <.sheet_content id="video_uploader" side="right" :if={@video_form} phx-mounted={JS.exec("phx-show-sheet")} phx-remove={JS.exec("phx-hide-sheet")}>
      ...
  </.sheet_content>
...

Then in your backend you just setup the form on your "edit" event and clear the form on a successful "update" event, whatever you decide to call them.

def handle_event("edit", _params, socket) do
  {:noreply, assign(socket, :video_form, build_video_form())}
end

def handle_event("update", %{"video" => video_params}, socket) do
  # after a successful update
  {:noreply, assign(socket, : video_form, nil)}
end

The above uses Phoenix lifecycle events when adding and removing the sheet content element so that it will both show and hide the sheet using all the transitions that the open and close triggers use.