### Visualizing Application Trees with Kino.Process.app_tree in Elixir Source: https://context7_llms This set of examples shows how to visualize Elixir application trees using `Kino.Process.app_tree`. It starts by showing how to list running applications, then demonstrates rendering a specific application's tree, and finally how to customize the rendering direction. ```Elixir :application_controller.which_applications() ``` ```Elixir Kino.Process.app_tree(:logger) ``` ```Elixir Kino.Process.app_tree(:logger, direction: :left_right) ``` -------------------------------- ### Setting up Supervisors for Kino.Process.sup_tree - Elixir Source: https://context7_llms This snippet initializes a `Supervisor` and a `DynamicSupervisor` with a one-for-one strategy. It then starts three child `Agent` processes under the `DynamicSupervisor` to create a sample supervision tree for visualization. ```Elixir {:ok, supervisor_pid} = Supervisor.start_link( [ {DynamicSupervisor, strategy: :one_for_one, name: MyApp.DynamicSupervisor}, {Agent, fn -> [] end} ], strategy: :one_for_one, name: MyApp.Supervisor ) Enum.each(1..3, fn _ -> DynamicSupervisor.start_child(MyApp.DynamicSupervisor, {Agent, fn -> %{} end}) end) ``` -------------------------------- ### Starting a Smart Cell and Retrieving Kino and Source in Elixir Source: https://context7_llms This function starts a smart cell defined by a given module (`Kino.SmartCell.Custom`) with initial attributes (`%{"key" => "value"}`). It returns the `Kino.JS.Live` kino instance and the initial source code, enabling interaction and testing. ```Elixir {kino, source} = start_smart_cell!(Kino.SmartCell.Custom, %{"key" => "value"}) ``` -------------------------------- ### Creating Select Inputs with Kino.Input.select/3 in Elixir Source: https://context7_llms These examples illustrate how to create a new select input using `Kino.Input.select/3`. The first example uses a keyword list for options, while the second uses a list of tuples, demonstrating flexibility in defining value-label pairs. ```Elixir Kino.Input.select("Language", [en: "English", fr: "Français"]) ``` ```Elixir Kino.Input.select("Language", [{1, "One"}, {2, "Two"}, {3, "Three"}]) ``` -------------------------------- ### Rendering an Autoplaying, Looping Video with Kino.Video in Elixir Source: https://context7_llms This example expands on basic video rendering by demonstrating how to use options like `autoplay: true` and `loop: true` with `Kino.Video.new/3`. It reads the video content and then configures the video to start playing automatically and loop continuously once rendered. ```Elixir content = File.read!("/path/to/video.mp4") Kino.Video.new(content, :mp4, autoplay: true, loop: true) ``` -------------------------------- ### Creating Audio Kino - Kino.Audio.new/3 (Elixir) Source: https://context7_llms Demonstrates how to create a new Kino for displaying binary audio using Kino.Audio.new/3. The first example shows basic audio rendering, while the second includes autoplay and loop options. ```Elixir content = File.read!("/path/to/audio.wav") Kino.Audio.new(content, :wav) ``` ```Elixir content = File.read!("/path/to/audio.wav") Kino.Audio.new(content, :wav, autoplay: true, loop: true) ``` -------------------------------- ### Rendering Supervision Tree by PID with Kino.Process.sup_tree - Elixir Source: https://context7_llms This example demonstrates how to render a supervision tree using `Kino.Process.sup_tree/1` by passing the process ID (PID) of the supervisor. This visualizes the hierarchy of supervised processes. ```Elixir Kino.Process.sup_tree(supervisor_pid) ``` -------------------------------- ### Creating a Data Table with Specific Keys - Kino.DataTable - Elixir Source: https://context7_llms This example shows how to create a `Kino.DataTable` from process information, explicitly selecting and ordering specific keys (`:registered_name`, `:initial_call`, `:reductions`, `:stack_size`) to be displayed in the table. ```Elixir data = for pid <- Process.list() do pid |> Process.info() |> Keyword.merge(registered_name: nil) end Kino.DataTable.new( data, keys: [:registered_name, :initial_call, :reductions, :stack_size] ) ``` -------------------------------- ### Creating a Basic Text Download Button - Kino.Download - Elixir Source: https://context7_llms This example creates a download button using `Kino.Download.new/1` that, when clicked, generates and downloads a simple text string. The content is produced by the provided anonymous function. ```Elixir Kino.Download.new(fn -> "Example text" end) ``` -------------------------------- ### Creating a Binary File Download Button - Kino.Download - Elixir Source: https://context7_llms This example shows how to create a download button for binary data. It specifies a `filename` of 'data.bin' and customizes the button's display text using the `label` option. ```Elixir Kino.Download.new( fn -> <<0, 1>> end, filename: "data.bin", label: "Binary data" ) ``` -------------------------------- ### Using a Custom Module Plug with Kino.Proxy.listen - Elixir Source: https://context7_llms This example demonstrates how to register a custom module plug, `MyPlug`, with `Kino.Proxy.listen/1`. The module implements the `init/1` and `call/2` functions required by Plug, sending a simple 'hello world!' response for all requests. ```Elixir defmodule MyPlug do def init([]), do: false def call(conn, _opts) do Plug.Conn.send_resp(conn, 200, "hello world!") end end Kino.Proxy.listen(MyPlug) ``` -------------------------------- ### Configuring Livebook Bridge for Kino Tests (Elixir) Source: https://context7_llms This snippet shows the necessary setup for testing custom `Kino` components, specifically `Kino.JS.Live` kinos, by mimicking Livebook's communication. It imports `Kino.Test` and configures the `livebook_bridge` in a test module's setup. This allows `Kino.JS.Live` interactions to be simulated during tests. ```Elixir import Kino.Test setup :configure_livebook_bridge ``` -------------------------------- ### Tracing All Process Messages with Kino.Process.seq_trace - Elixir Source: https://context7_llms This example demonstrates how to use Kino.Process.seq_trace/3 to generate a sequence diagram of all messages occurring during the execution of a provided function. It starts an Agent, monitors it, performs asynchronous tasks that interact with the agent, and then stops the agent, capturing all process communications in the trace. The function takes a 0-arity function as its first argument. ```Elixir Kino.Process.seq_trace(fn -> {:ok, agent_pid} = Agent.start_link(fn -> [] end) Process.monitor(agent_pid) 1..2 |> Task.async_stream( fn value -> Agent.get(agent_pid, fn value -> value end) 100 * value end, max_concurrency: 3 ) |> Stream.run() Agent.stop(agent_pid) end) ``` -------------------------------- ### Implementing a Multi-Step Wizard with Kino.Screen in Elixir Source: https://context7_llms This comprehensive example demonstrates how to build a multi-step wizard using the `Kino.Screen` behaviour in Elixir. It covers state management, rendering different pages based on state, handling form submissions, input validation, and navigation between steps, including a shared layout for all pages. ```Elixir defmodule MyScreen do @behaviour Kino.Screen # Import Kino.Control for forms, Kino.Input for inputs, and Screen for control/2 import Kino.{Control, Input, Screen} # Our screen will guide the user to provide its name and address. # We also have a field keeping the current page and if there is an error. def new do state = %{page: 1, name: nil, address: nil, error: nil} Kino.Screen.new(__MODULE__, state) end # The first screen gets the name. # # The `control/2` function comes from `Kino.Screen` and it specifies # which function to be invoked on form submission. def render(%{page: 1} = state) do form( [name: text("Name", default: state.name)], submit: "Step one" ) |> control(&step_one/2) |> add_layout(state) end # The next screen gets the address. def render(%{page: 2} = state) do form( [address: text("Address", default: state.address)], submit: "Step two" ) |> control(&step_two/2) |> add_layout(state) end # The final screen shows a success message. def render(%{page: 3} = state) do Kino.Text.new("Well done, #{state.name}. You live in #{state.address}.") |> add_layout(state) end # This is the layout shared across all pages. defp add_layout(element, state) do prefix = if state.error do Kino.Text.new("Error: #{state.error}!") end suffix = if state.page > 1 do button("Go back") |> control(&go_back/2) end [prefix, element, suffix] |> Enum.reject(&is_nil/1) |> Kino.Layout.grid() end defp step_one(%{data: %{name: name}}, state) do if name == "" do %{state | name: name, error: "name can't be blank"} else %{state | name: name, error: nil, page: 2} end end defp step_two(%{data: %{address: address}}, state) do if address == "" do %{state | address: address, error: "address can't be blank"} else %{state | address: address, error: nil, page: 3} end end defp go_back(_, state) do %{state | page: state.page - 1} end end MyScreen.new() ``` -------------------------------- ### Rendering Supervision Tree by Name with Kino.Process.sup_tree - Elixir Source: https://context7_llms This snippet shows how to render a supervision tree using `Kino.Process.sup_tree/1` by providing the registered name of the supervisor. This is useful when the supervisor has been started with a global name. ```Elixir Kino.Process.sup_tree(MyApp.Supervisor) ``` -------------------------------- ### Rendering Static HTML with Kino.Shorts (Elixir) Source: https://context7_llms This example demonstrates how to display arbitrary static HTML content directly within a Kino notebook using `Kino.Shorts.html/1`. It takes a multi-line HTML string as input and renders it as-is. ```Elixir html(""" Look! I wrote this HTML from Kino ! "\"") ``` -------------------------------- ### Listening to Kino.Control Events with Kino.listen/2 in Elixir Source: https://context7_llms This example shows how `Kino.listen/2` can be used to consume events from a `Kino.Control` component, specifically a button. It starts a process that inspects each event triggered by the "Greet" button without blocking the main execution. ```Elixir Kino.Control.button("Greet") |> Kino.listen(fn event -> IO.inspect(event) end) ``` -------------------------------- ### Connecting to Kino.JS.Live and Asserting Initial Data in Elixir Source: https://context7_llms This function connects to a `Kino.JS.Live` kino and returns its initial data. The example demonstrates asserting that the returned data matches an expected map (`%{count: 1}`). ```Elixir data = connect(kino) assert data == %{count: 1} ``` -------------------------------- ### Inspecting Process Information with Kino.Tree in Elixir Source: https://context7_llms This example showcases `Kino.Tree.new/1` for inspecting the detailed information of the current Elixir process. `Process.info(self())` retrieves a map containing various process attributes, which `Kino.Tree` then renders as an interactive tree, making it easy to explore. ```Elixir data = Process.info(self()) Kino.Tree.new(data) ``` -------------------------------- ### Viewing an Existing ETS Table - Kino.ETS - Elixir Source: https://context7_llms This example shows how to display an existing ETS table, specifically `:elixir_config`, using `Kino.ETS.new/1`. This is useful for inspecting the contents of running ETS tables. ```Elixir Kino.ETS.new(:elixir_config) ``` -------------------------------- ### Rendering Markdown Content with Kino.Shorts (Elixir) Source: https://context7_llms This example shows how to render multi-line Markdown content, including headings, paragraphs, and tables, using `Kino.Shorts.markdown/1`. It allows for richer text formatting within the Kino output. ```Elixir markdown(""" # Example A regular Markdown file. ### Code - Kino.Shorts.markdown/1 (function) ```elixir \"Elixir\" |> String.graphemes() |> Enum.frequencies() ``` ### Table - Kino.Shorts.markdown/1 (function) | ID | Name | Website | | -- | ------ | ----------------------- | | 1 | Elixir | https://elixir-lang.org | | 2 | Erlang | https://www.erlang.org | "") ``` -------------------------------- ### Building a Data Export API with Kino.Proxy.listen - Elixir Source: https://context7_llms This example shows how to create a data export API endpoint using `Kino.Proxy.listen/1`. It checks the `path_info` to serve 'some data' as a CSV for `/export/data` and a default message for other paths, demonstrating conditional request handling. ```Elixir Kino.Proxy.listen(fn %{path_info: ["export", "data"]} = conn -> data = "some data" conn |> Plug.Conn.put_resp_header("content-type", "application/csv") |> Plug.Conn.send_resp(200, data) conn -> conn |> Plug.Conn.put_resp_header("content-type", "application/text") |> Plug.Conn.send_resp(200, "use /export/data to get extract the report data") end) ``` -------------------------------- ### Custom Labeling Process Messages with Kino.Process.seq_trace - Elixir Source: https://context7_llms This example demonstrates how to apply custom labels to messages within the sequence diagram using the :message_label option in Kino.Process.seq_trace/3. It traces interactions with an Agent and provides a function that inspects message content to assign a custom label "GET: value" for specific :get calls, otherwise using the default label. This allows for more descriptive diagrams. ```Elixir {:ok, agent_pid} = Agent.start_link(fn -> [] end) Process.monitor(agent_pid) Kino.Process.seq_trace(agent_pid, fn -> 1..2 |> Task.async_stream( fn value -> Agent.get(agent_pid, fn value -> value end) 100 * value end, max_concurrency: 3 ) |> Stream.run() Agent.stop(agent_pid) end, message_label: fn(msg) -> case msg do {:":$gen_call", _ref, {:get, _}} -> {:ok, "GET: value"} _ -> :continue end end) ``` -------------------------------- ### Listening to Generic Streams with Kino.listen/2 in Elixir Source: https://context7_llms This example illustrates `Kino.listen/2` consuming events from a generic Elixir `Stream`. It creates a stream that emits values every 100 milliseconds, takes the first 10 values, and then uses `Kino.listen/2` to print a "Ping" message for each received value. ```Elixir Stream.interval(100) |> Stream.take(10) |> Kino.listen(fn i -> IO.puts("Ping #{i}") end) ``` -------------------------------- ### Handling Multiple Endpoints with Plug.Router and Kino.Proxy.listen - Elixir Source: https://context7_llms This snippet shows how to integrate `Plug.Router` with `Kino.Proxy.listen/1` to define multiple API endpoints. It uses `get` macros to handle `/hello` and `/echo/:message` paths, demonstrating routing capabilities within a Livebook app. ```Elixir defmodule ApiRouter do use Plug.Router plug :match plug :dispatch get "/hello" do send_resp(conn, 200, "hello from router") end get "/echo/:message" do send_resp(conn, 200, String.upcase(message)) end match _ do send_resp(conn, 404, "oops, not found") end end Kino.Proxy.listen(ApiRouter) ``` -------------------------------- ### Creating Download Buttons with Kino.Shorts.download/2 in Elixir Source: https://context7_llms This snippet provides multiple examples of using `Kino.Shorts.download/2` to create interactive download buttons. It shows how to generate file content dynamically, specify filenames, and customize button labels for various data types like plain text, JSON, and binary data. ```Elixir download(fn -> "Example text" end) download( fn -> Jason.encode!(%{"foo" => "bar"}) end, filename: "data.json" ) download( fn -> <<0, 1>> end, filename: "data.bin", label: "Binary data" ) ``` -------------------------------- ### Streaming Markdown Chunks with Kino.Frame in Elixir Source: https://context7_llms This example illustrates streaming Markdown content in chunks using Kino.Markdown.new/2 with the :chunk option and Kino.Frame. Each word is rendered as a separate chunk and appended to a Kino.Frame, simulating a real-time display. ```Elixir frame = Kino.Frame.new() |> Kino.render() for word <- ["who", " *let*", " `the`", " **dogs**", " out"] do text = Kino.Markdown.new(word, chunk: true) Kino.Frame.append(frame, text) Process.sleep(250) end ``` -------------------------------- ### Rendering Mermaid Diagram with Kino.Mermaid in Elixir Source: https://context7_llms This example demonstrates how to render a Mermaid diagram using Kino.Mermaid.new/1. It takes a Mermaid diagram definition string as input and displays it as a visual graph. ```Elixir Kino.Mermaid.new(""" graph TD; A-->B; A-->C; B-->D; C-->D; """) ``` -------------------------------- ### Updating a Dynamic Frame in Kino.Shorts (Elixir) Source: https://context7_llms This example demonstrates how to create a dynamic frame using `Kino.Shorts.frame/1` and then update its content iteratively using `Kino.Frame.render/2`. It simulates a simple animation by rendering numbers from 1 to 100 with a short delay between updates. ```Elixir frame = frame() |> Kino.render() for i <- 1..100 do Kino.Frame.render(frame, i) Process.sleep(50) end ``` -------------------------------- ### Arranging Images in a Grid with Kino.Layout.grid in Elixir Source: https://context7_llms This example shows how to create a grid layout of multiple images using Kino.Layout.grid/2. It first iterates through a list of paths to read and create Kino.Image instances, then arranges them into a grid with 3 columns. ```Elixir images = for path <- paths do path |> File.read!() |> Kino.Image.new(:jpeg) end Kino.Layout.grid(images, columns: 3) ``` -------------------------------- ### Shorthand Animation with Kino.animate/2 (Elixir) Source: https://context7_llms This example shows a shorthand usage of Kino.animate/2 where an integer (e.g., 100ms) is directly passed as the first argument, implicitly creating an interval stream. The callback function then renders a new Markdown frame every specified interval, displaying the current iteration count. ```Elixir # Render new Markdown every 100ms Kino.animate(100, fn i -> Kino.Markdown.new("**Iteration: `#{i}`**") end) ``` -------------------------------- ### Rendering Markdown Content with Kino.Markdown in Elixir Source: https://context7_llms This example shows how to render multi-line Markdown content, including headings, code blocks, and tables, using Kino.Markdown.new/1. The entire Markdown string is passed as an argument to the function. ```Elixir Kino.Markdown.new(""" # Example A regular Markdown file. ### Code - Kino.Markdown (module) ```elixir \"Elixir\" |> String.graphemes() |> Enum.frequencies() ``` ### Table - Kino.Markdown (module) | ID | Name | Website | | -- | ------ | ----------------------- | | 1 | Elixir | https://elixir-lang.org | | 2 | Erlang | https://www.erlang.org | """) ``` -------------------------------- ### Rendering Supervision Tree with Custom Direction using Kino.Process.sup_tree - Elixir Source: https://context7_llms This example illustrates how to customize the rendering direction of the supervision tree using `Kino.Process.sup_tree/2` by passing the `:direction` option, such as `:left_right`, to change the layout of the visualization. ```Elixir Kino.Process.sup_tree(MyApp.Supervisor, direction: :left_right) ``` -------------------------------- ### Asynchronous Event Handler Registration with Async/Await in JavaScript Source: https://context7_llms This JavaScript `init` function shows an alternative way to register an event handler asynchronously using `async/await`. Similar to the `fetch.then` approach, events are buffered until the handler is registered, allowing for setup operations before event processing begins. ```JavaScript export async function init(ctx, data) { const response = await fetch(data.someUrl); ctx.handleEvent("update", (payload) => { // ... }); } ``` -------------------------------- ### Reading Select Input - Kino.Shorts.read_select/3 (Elixir) Source: https://context7_llms Demonstrates how to use Kino.Shorts.read_select/3 to render a select input. The first example uses atom keys with string labels, while the second uses integer values with string labels. This function expects a list of {value, label} tuples. ```Elixir read_select("Language", [en: "English", fr: "Français"]) ``` ```Elixir read_select("Language", [{1, "One"}, {2, "Two"}, {3, "Three"}]) ``` -------------------------------- ### Stateful Event Listening with Kino.listen/3 in Elixir Source: https://context7_llms This example demonstrates the stateful `Kino.listen/3` function. It initializes a counter to 0 and increments it each time a button is clicked, printing the updated count. The callback returns `{:cont, new_counter}` to continue listening with the updated state. ```Elixir button = Kino.Control.button("Click") Kino.listen(button, 0, fn _event, counter -> new_counter = counter + 1 IO.puts("Clicks: #{new_counter}") {:cont, new_counter} end) ``` -------------------------------- ### Displaying Tabular Data with Kino.Shorts.data_table/2 in Elixir Source: https://context7_llms This example demonstrates how to render tabular data using `Kino.Shorts.data_table/2`. It takes a list of maps, where each map represents a row, and displays it as an interactive data table, simplifying the visualization of structured information. ```Elixir import Kino.Shorts data = [ %{id: 1, name: "Elixir", website: "https://elixir-lang.org"}, %{id: 2, name: "Erlang", website: "https://www.erlang.org"} ] data_table(data) ``` -------------------------------- ### Handling Asynchronous File Form Submissions with Kino.Control.form - Elixir Source: https://context7_llms This example illustrates how to create a form with a file input and process its asynchronous submissions. It sets up a form with a file upload and a submit button, then listens for form submission events to extract the uploaded file's path and inspect its content. ```Elixir form = Kino.Control.form([file: Kino.Input.file("File")], submit: "Send") ``` ```Elixir form |> Kino.Control.stream() |> Kino.listen(fn event -> path = Kino.Input.file_path(event.data.file.file_ref) content = File.read!(path) IO.inspect(content) end) ``` -------------------------------- ### Broadcasting Events to All Clients in Kino.JS.Live (Elixir) Source: https://context7_llms This example illustrates broadcasting an event to all connected clients using `Kino.JS.Live.Context.broadcast_event/3`. The event, identified by a string name (e.g., 'new_point') and a map of data, will be dispatched to the registered JavaScript callback on every client. This is ideal for real-time updates affecting all users. ```Elixir broadcast_event(ctx, "new_point", %{x: 10, y: 10}) ``` -------------------------------- ### Rendering Custom Structs with Tabs in Livebook (Elixir) Source: https://context7_llms This example shows how to render a custom `Graph` struct using tabs, combining a visual Mermaid representation with the default inspect output. It creates a `Kino.Mermaid` instance for the graph and a `Kino.Inspect` instance for the raw data, then uses `Kino.Layout.tabs` to present them side-by-side. This provides both a visual and a detailed textual view of the data. ```Elixir defimpl Kino.Render, for: Graph do def to_livebook(graph) do source = Graph.to_mermaid(graph) mermaid_kino = Kino.Mermaid.new(source) inspect_kino = Kino.Inspect.new(graph) kino = Kino.Layout.tabs(Graph: mermaid_kino, Raw: inspect_kino) Kino.Render.to_livebook(kino) end end ``` -------------------------------- ### Rendering HTML with Embedded JavaScript - Kino.HTML - Elixir Source: https://context7_llms This example shows how to render HTML content that includes an embedded