Add support for image output (#380)

This commit is contained in:
Jonatan Kłosko 2021-06-22 18:03:01 +02:00 committed by GitHub
parent 6d0da78370
commit 7024d22253
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 25 additions and 5 deletions

View file

@ -27,6 +27,8 @@ defmodule Livebook.Notebook.Cell.Elixir do
| binary()
# Standalone text block
| {:text, binary()}
# A raw image in the given format.
| {:image, content :: binary(), mime_type :: binary()}
# Vega-Lite graphic
| {:vega_lite_static, spec :: map()}
# Vega-Lite graphic with dynamic data

View file

@ -0,0 +1,15 @@
defmodule LivebookWeb.Output.ImageComponent do
use LivebookWeb, :live_component
@impl true
def render(assigns) do
~L"""
<%= tag :img, src: data_url(@content, @mime_type), alt: "output image" %>
"""
end
defp data_url(content, mime_type) do
image_base64 = Base.encode64(content)
["data:", mime_type, ";base64,", image_base64]
end
end

View file

@ -1,11 +1,6 @@
defmodule LivebookWeb.Output.VegaLiteStaticComponent do
use LivebookWeb, :live_component
@impl true
def mount(socket) do
{:ok, socket}
end
@impl true
def update(assigns, socket) do
socket = assign(socket, id: assigns.id)

View file

@ -309,6 +309,14 @@ defmodule LivebookWeb.SessionLive.CellComponent do
)
end
defp render_output(_socket, {:image, content, mime_type}, id) do
live_component(LivebookWeb.Output.ImageComponent,
id: id,
content: content,
mime_type: mime_type
)
end
defp render_output(_socket, {:error, formatted}, _id) do
render_error_message_output(formatted)
end