From 04f0ff273c1589e03795a7306227bf5c4e07c384 Mon Sep 17 00:00:00 2001 From: Tjaco Oostdijk Date: Mon, 23 Jan 2023 20:59:51 +0100 Subject: [PATCH 1/2] feat: live_video_preview --- assets/js/phoenix_live_view/hooks.js | 15 +++++ lib/phoenix_component.ex | 40 ++++++++++++++ test/phoenix_component/components_test.exs | 64 ++++++++++++++++++++++ 3 files changed, 119 insertions(+) diff --git a/assets/js/phoenix_live_view/hooks.js b/assets/js/phoenix_live_view/hooks.js index 672f8cea86..1e95244027 100644 --- a/assets/js/phoenix_live_view/hooks.js +++ b/assets/js/phoenix_live_view/hooks.js @@ -43,6 +43,21 @@ let Hooks = { URL.revokeObjectURL(this.url) } }, + // Currently this is exactly the same as the LiveImgPreview, but I wanted to add this + // so possibly this can have functionality specific to videos in the future. + LiveVideoPreview: { + mounted(){ + this.ref = this.el.getAttribute("data-phx-entry-ref") + this.inputEl = document.getElementById(this.el.getAttribute(PHX_UPLOAD_REF)) + LiveUploader.getEntryDataURL(this.inputEl, this.ref, url => { + this.url = url + this.el.src = url + }) + }, + destroyed(){ + URL.revokeObjectURL(this.url) + } + }, FocusWrap: { mounted(){ this.focusStart = this.el.firstElementChild diff --git a/lib/phoenix_component.ex b/lib/phoenix_component.ex index 1e3f7fc918..163d251f73 100644 --- a/lib/phoenix_component.ex +++ b/lib/phoenix_component.ex @@ -2582,6 +2582,46 @@ defmodule Phoenix.Component do raise ArgumentError, "missing required :entry attribute to <.live_img_preview/>" end + @doc """ + Generates a video preview on the client for a selected file. + + ## Examples + + ```heex + <%= for entry <- @uploads.avatar.entries do %> + <.live_video_preview entry={entry} width="400" /> + <% end %> + ``` + """ + @doc type: :component + def live_video_preview(assigns) + + # attr :entry, Phoenix.LiveView.UploadEntry, required: true + # attr :rest, :global + def live_video_preview(%{entry: %Phoenix.LiveView.UploadEntry{ref: ref} = entry} = assigns) do + rest = + assigns + |> assigns_to_attributes([:entry]) + |> Keyword.put_new_lazy(:id, fn -> "phx-preview-#{ref}" end) + + assigns = assign(assigns, entry: entry, ref: ref, rest: rest) + + ~H""" +