### live/2 example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Spawns a connected LiveView process. With a path, performs a GET and upgrades to LiveView; without, converts a previously rendered conn. Returns {:ok, view, html} or {:error, {:redirect, ...}}. ```elixir {:ok, view, html} = live(conn, "/path") assert view.module == MyLive assert html =~ "the count is 3" assert {:error, {:redirect, %{to: "/somewhere"}}} = live(conn, "/path") ``` -------------------------------- ### Presign upload function example Source: https://phoenix-live-view.hexdocs.pm/external-uploads.md Example presign_upload/2 function that calls a start_session function and returns the uploader and entrypoint metadata. ```elixir defp presign_upload(entry, socket) do {:ok, %{"Location" => link}} = SomeTube.start_session(%{ "uploadType" => "resumable", "x-upload-content-length" => entry.client_size }) {:ok, %{uploader: "UpChunk", entrypoint: link}, socket} end ``` -------------------------------- ### render examples Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Shows how to get the HTML string of a rendered view or element. ```elixir {:ok, view, _html} = live(conn, "/thermo") assert render(view) =~ ~s| ``` -------------------------------- ### mount/3 Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.md The LiveView entry-point callback. Invoked twice for each LiveView in the root of a template: once for the initial page load and once to establish the live socket. It expects params, session, and socket arguments and must return {:ok, socket} or {:ok, socket, options}. ```APIDOC ## mount/3 ### Description The LiveView entry-point. For each LiveView in the root of a template, mount/3 is invoked twice: once to do the initial page load and again to establish the live socket. ### Callback Signature ```elixir @callback mount( params :: unsigned_params() | :not_mounted_at_router, session :: map(), socket :: Phoenix.LiveView.Socket.t() ) :: {:ok, Phoenix.LiveView.Socket.t()} | {:ok, Phoenix.LiveView.Socket.t(), keyword()} ``` ### Parameters - **params** (unsigned_params() | :not_mounted_at_router) - Required - A map of string keys containing public information set by the user. Contains query params and router path parameters. If the LiveView was not mounted at the router, this argument is the atom :not_mounted_at_router. - **session** (map()) - Required - The connection session. - **socket** (Phoenix.LiveView.Socket.t()) - Required - The LiveView socket. ### Return Values - **{:ok, socket}** - Success. Returns the updated socket. - **{:ok, socket, options}** - Success with options. Options can include: - **:temporary_assigns** (keyword()) - Optional - A keyword list of assigns that are temporary and must be reset to their value after every render. Once reset, the value won't be re-rendered until explicitly assigned. - **:layout** (optional) - Optional - The optional layout to be used by the LiveView. Overrides any layout previously set via Phoenix.LiveView.Router.live_session/2 or on use Phoenix.LiveView. ### Security Note The params argument contains untrusted data from the client. You must authorize and validate this data before using it to fetch or modify resources. See the "Security considerations" guide for more information. ``` -------------------------------- ### Define a function component Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md An example of a simple function component to be used in testing examples. ```elixir def greet(assigns) do ~H"""
Hello, {@name}!
""" end ``` -------------------------------- ### live/2 Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Spawns a connected LiveView process. If a path is given, a regular get(conn, path) is done and the page is upgraded to a LiveView. If no path is given, it assumes a previously rendered %Plug.Conn{} is given, which will be converted to a LiveView immediately. ```APIDOC ## live/2 ### Description Spawns a connected LiveView process. If a path is given, a regular get(conn, path) is done and the page is upgraded to a LiveView. If no path is given, it assumes a previously rendered %Plug.Conn{} is given, which will be converted to a LiveView immediately. ### Parameters - **conn** (connection) - Required - The connection to use. - **path** (string) - Optional - The path to request. ### Options - **:on_error** - Can be either :raise or :warn to control whether detected errors like duplicate IDs or live components fail the test or just log a warning. Defaults to :raise. ### Returns - `{:ok, view, html}` - On success, with the LiveView and its rendered HTML. - `{:error, {:redirect, %{to: path}}}` - If the LiveView redirects. ### Example ```elixir {:ok, view, html} = live(conn, "/path") assert view.module == MyLive assert html =~ "the count is 3" assert {:error, {:redirect, %{to: "/somewhere"}}} = live(conn, "/path") ``` ``` -------------------------------- ### cancel_async usage examples Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.md Examples of how to call cancel_async with different arguments to cancel an async operation. ```elixir cancel_async(socket, :preview) cancel_async(socket, :preview, :my_reason) cancel_async(socket, socket.assigns.preview) ``` -------------------------------- ### Example colocated CSS tag Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.ColocatedCSS.md An example of a style tag using the ColocatedCSS type for scoping. ```heex ``` -------------------------------- ### Using Phoenix.LiveView Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.md Example of using the __using__ macro to configure a LiveView with a custom container, layout, and log level. ```elixir use Phoenix.LiveView, container: {:tr, class: "colorized"}, layout: {MyAppWeb.Layouts, :app}, log: :info ``` -------------------------------- ### Basic allow_upload configurations Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.md Examples of configuring file uploads with specific file types and entry limits. ```elixir allow_upload(socket, :avatar, accept: ~w(.jpg .jpeg), max_entries: 2) allow_upload(socket, :avatar, accept: :any) ``` -------------------------------- ### assert_patched example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Example of using assert_patched to assert a live patch was performed and returns the new path. ```elixir render_click(view, :event_that_triggers_redirect) assert_patched view, "/path" ``` -------------------------------- ### live_redirect example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Shows how to test a live redirect between LiveViews, including a failed redirect to a different live_session. ```elixir assert {:ok, page_live, _html} = live(conn, "/page/1") assert {:ok, page2_live, _html} = live(conn, "/page/2") assert {:error, {:redirect, _}} = live_redirect(page2_live, to: "/admin") ``` -------------------------------- ### assert_patch examples Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Examples of using assert_patch to assert a live patch occurs within a timeout. The first example uses the default timeout, the second specifies 30 ms, and the third captures the returned path and asserts it matches a regex. ```elixir render_click(view, :event_that_triggers_patch) assert_patch view ``` ```elixir render_click(view, :event_that_triggers_patch) assert_patch view, 30 ``` ```elixir render_click(view, :event_that_triggers_patch) path = assert_patch view assert path =~ ~r/path/+/ ``` -------------------------------- ### Render file input with label Source: https://phoenix-live-view.hexdocs.pm/Phoenix.Component.md Example of rendering a file input alongside a descriptive label. ```heex <.live_file_input upload={@uploads.avatar} /> ``` -------------------------------- ### Example: Phone number hook Source: https://phoenix-live-view.hexdocs.pm/js-interop.md Example of defining a hook object for phone number formatting and passing it to the LiveSocket. ```APIDOC ## Example: Phone number hook ### Description Example of defining a hook object for phone number formatting and passing it to the LiveSocket. ### Markup ```heex ``` ### JavaScript ```javascript /** * @type {import("phoenix_live_view").HooksOptions} */ let Hooks = {} Hooks.PhoneNumber = { mounted() { this.el.addEventListener("input", e => { let match = this.el.value.replace(/\D/g, "").match(/^(\d{3})(\d{3})(\d{4})$/) if(match) { this.el.value = `${match[1]}-${match[2]}-${match[3]}` } }) } } let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks, ...}) ``` ``` -------------------------------- ### init/1 Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.UploadWriter.md Callback to initialize the upload writer with options. It receives the writer options and returns an initial state or an error. ```APIDOC ## init/1 ### Description Callback to initialize the upload writer with options. It receives the writer options and returns an initial state or an error. ### Callback `init(opts :: term()) :: {:ok, state :: term()} | {:error, term()}` ### Parameters - **opts** (term) - Required - Options passed to the writer when initializing. ### Returns - `{:ok, state}` - Success with initial state. - `{:error, term()}` - Failure with error reason. ### Example ```elixir @impl true def init(opts) do {:ok, %{total: 0, level: Keyword.fetch!(opts, :level)}} end ``` ``` -------------------------------- ### stream_insert update and move example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.md Example of updating an item and moving it to a new position by combining stream_delete and stream_insert. ```elixir song = get_song!(id) socket |> stream_delete(:songs, song) |> stream_insert(:songs, song, at: -1) ``` -------------------------------- ### stream_delete_by_dom_id usage example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.md Example showing how to render a stream and handle a delete event using the DOM ID. ```elixir def render(assigns) do ~H"""
{song.title}
""" end def handle_event("delete", %{"id" => dom_id}, socket) do {:noreply, stream_delete_by_dom_id(socket, :songs, dom_id)} end ``` -------------------------------- ### Directory listing for embed_templates example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.Component.md Shows the directory structure with components.ex and a cards directory containing two .html.heex template files. ```plain ├── components.ex ├── cards │ ├── pricing_card.html.heex │ └── features_card.html.heex ``` -------------------------------- ### HEEx template script tag example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.HTMLFormatter.TagFormatter.md An example of a script tag in a HEEx template that would trigger the tag formatter. ```heex ``` -------------------------------- ### live_children/1 example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Returns the list of LiveView children for a parent LiveView, in rendered order. The example shows asserting a single child and clicking it. ```elixir {:ok, view, _html} = live(conn, "/thermo") assert [clock_view] = live_children(view) assert render_click(clock_view, :snooze) =~ "snoozing" ``` -------------------------------- ### transition(time, onStart, onDone?) Source: https://phoenix-live-view.hexdocs.pm/js/classes/_internal_.default.html Performs a transition. ```APIDOC ## transition(time, onStart, onDone?) ### Description Performs a transition. ### Parameters - **time** (any) - Required - The time. - **onStart** (any) - Required - Callback on start. - **onDone** (() => void) - Optional - Callback on done. ### Returns void ``` -------------------------------- ### HEEx template example with ~H Source: https://phoenix-live-view.hexdocs.pm/Phoenix.Component.md A basic example of using the ~H sigil to define a template containing HTML, dynamic attributes, and a function component. ```heex ~H"""

Hello {@name}

""" ``` -------------------------------- ### __using__/1 Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveComponent.md Macro that uses LiveComponent in the current module. It accepts options such as :global_prefixes for component prefixes. ```APIDOC ## __using__/1 ### Description Macro that uses LiveComponent in the current module. ### Usage ```elixir use Phoenix.LiveComponent ``` ### Options - **:global_prefixes** (list) - Optional - The global prefixes to use for components. See `Global Attributes` in `Phoenix.Component` for more information. ``` -------------------------------- ### Example payload for Escape key press Source: https://phoenix-live-view.hexdocs.pm/bindings.md When a key is pressed, the value sent to the server contains the "key" that was pressed. This example shows the payload for pressing the Escape key. ```elixir %{"key" => "Escape"} ``` -------------------------------- ### assert_patch with path examples Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Examples of using assert_patch to assert a live patch to a specific path within a timeout. The first uses the default timeout, the second specifies 30 ms. ```elixir render_click(view, :event_that_triggers_patch) assert_patch view, "/path" ``` ```elixir render_click(view, :event_that_triggers_patch) assert_patch view, "/path", 30 ``` -------------------------------- ### Using :for and :let in slots Source: https://phoenix-live-view.hexdocs.pm/Phoenix.Component.md Demonstrates how to use :for and :let attributes together within a slot. ```heex <.table id="my-table" rows={@users}> <:col :for={header <- @headers} :let={user}> {user[header]} <.table> ``` -------------------------------- ### refute_redirected example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Asserts that a redirect to a given path was not performed. ```elixir render_click(view, :event_that_triggers_redirect_to_path) :ok = refute_redirected view, "/wrong_path" ``` -------------------------------- ### Phoenix LiveView HTML template example Source: https://phoenix-live-view.hexdocs.pm/html-attrs.md Demonstrates the use of phx-click to trigger a server-side event with a parameter and a client-side JS command. ```heex ``` -------------------------------- ### Render LiveComponent Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveComponent.md Example of rendering a UserComponent within a template. ```heex <.live_component module={UserComponent} id={user_id} /> ``` -------------------------------- ### LiveView mount and paginate_posts with stream Source: https://phoenix-live-view.hexdocs.pm/bindings.md Sets up the initial socket assigns and defines paginate_posts to fetch a page of posts, prepend or append to the stream based on paging direction, and set end_of_timeline? and page assigns. The stream limit is three times per_page to maintain UI performance. ```elixir def mount(_, _, socket) do {:ok, socket |> assign(page: 1, per_page: 20) |> paginate_posts(1)} end defp paginate_posts(socket, new_page) when new_page >= 1 do %{per_page: per_page, page: cur_page} = socket.assigns posts = Blog.list_posts(offset: (new_page - 1) * per_page, limit: per_page) {posts, at, limit} = if new_page >= cur_page do {posts, -1, per_page * 3 * -1} else {Enum.reverse(posts), 0, per_page * 3} end case posts do [] -> assign(socket, end_of_timeline?: at == -1) [_ | _] = posts -> socket |> assign(end_of_timeline?: false) |> assign(:page, new_page) |> stream(:posts, posts, at: at, limit: limit) end end ``` -------------------------------- ### Define LiveView route Source: https://phoenix-live-view.hexdocs.pm/live-navigation.md Example router definition for a UserTable LiveView. ```elixir live "/users", UserTable ``` -------------------------------- ### render_keyup element example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Sends a keyup event to a specific element. ```elixir {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert view |> element("#inc") |> render_keyup() =~ "The temp is: 31℉" ``` -------------------------------- ### transition(el: HTMLElement, transition: string | string[], opts?: TransitionCommandOpts): void Source: https://phoenix-live-view.hexdocs.pm/js/interfaces/_internal_.HookJSCommands.html Applies a transition to an element. ```APIDOC ## transition ### Description Applies a transition to an element. ### Method transition ### Signature transition(el: HTMLElement, transition: string | string[], opts?: TransitionCommandOpts): void ### Parameters - **el** (HTMLElement) - Required - The element to apply the transition to. - **transition** (string | string[]) - Required - The transition name(s) to apply. - **opts** (TransitionCommandOpts) - Optional - Optional settings. Accepts: `time`, `delay`, and `blocking`. ### Returns void ``` -------------------------------- ### __using__ Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.md Macro that uses LiveView in the current module to mark it as a LiveView. Configures container, layout, logging, and global prefixes. ```APIDOC ## __using__ ### Description Uses LiveView in the current module to mark it a LiveView. This macro sets up the module with LiveView functionality and accepts configuration options. ### Usage ```elixir use Phoenix.LiveView, container: {:tr, class: "colorized"}, layout: {MyAppWeb.Layouts, :app}, log: :info ``` ### Options - **:container** (tuple) - Optional. HTML tag and DOM attributes for the LiveView container. Example: `{:li, style: "color: blue;"}`. - **:global_prefixes** (list) - Optional. Global prefixes to use for components. See `Global Attributes` in `Phoenix.Component`. - **:layout** (tuple) - Optional. Layout the LiveView will be rendered in. Can be overridden by `c:mount/3` or `:layout` option in `Phoenix.LiveView.Router.live_session/2`. - **:log** (atom or false) - Optional. Log level for the LiveView, either `false` or a log level. ``` -------------------------------- ### render_keydown view example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Sends a keydown event directly to the view. ```elixir {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_keydown(view, :inc) =~ "The temp is: 31℉" ``` -------------------------------- ### render_keydown element example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Sends a keydown event to a specific element. ```elixir {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert view |> element("#inc") |> render_keydown() =~ "The temp is: 31℉" ``` -------------------------------- ### render_focus view example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Sends a focus event directly to the view. ```elixir {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_focus(view, :inactive) =~ "Tap to wake" ``` -------------------------------- ### Auto-upload with progress handling Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.md Example of configuring auto-uploads and a progress function to consume files as they complete. ```elixir allow_upload(socket, :avatar, accept: :any, progress: &handle_progress/3, auto_upload: true) defp handle_progress(:avatar, entry, socket) do if entry.done? do uploaded_file = consume_uploaded_entry(socket, entry, fn %{} = meta -> {:ok, ...} end) {:noreply, put_flash(socket, :info, "file #{uploaded_file.name} uploaded")} else {:noreply, socket} end end ``` -------------------------------- ### push_focus examples Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.JS.md Shows two calls to JS.push_focus: one with no arguments and one with the :to option to specify a target selector. ```elixir JS.push_focus() JS.push_focus(to: "#my-button") ``` -------------------------------- ### refute_push_event example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Refutes that an event will be pushed within the default timeout. ```elixir refute_push_event view, "scores", %{points: _, user: "josé"} ``` -------------------------------- ### render_focus element example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Demonstrates using element/3 to target an element with phx-focus and triggering the event. ```elixir {:ok, view, html} = live(conn, "/thermo") assert view |> element("#inactive") |> render_focus() =~ "Tap to wake" ``` -------------------------------- ### refute_patched example Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.md Asserts that a live patch to a given path was not performed. ```elixir render_click(view, :event_that_triggers_patch_to_path) :ok = refute_patched view, "/wrong_path" ``` -------------------------------- ### Combine regular HTTP routes and live routes with same authentication Source: https://phoenix-live-view.hexdocs.pm/Phoenix.LiveView.Router.md Shows how to define a regular HTTP route and live routes with the same authentication rules, using a plug for regular routes and on_mount for live routes. ```elixir scope "/" do # Regular routes pipe_through [MyAppWeb.AdminPlugAuth] get "/admin/health", AdminHealthController, :index # Live routes live_session :admin, on_mount: MyAppWeb.AdminLiveAuth do live "/admin", AdminDashboardLive, :index live "/admin/posts", AdminPostLive, :index end end ```