2023-08-22 19:21:22 +08:00
|
|
|
defmodule LivebookWeb.Output.PlainTextComponent do
|
|
|
|
use LivebookWeb, :live_component
|
|
|
|
|
|
|
|
@impl true
|
|
|
|
def mount(socket) do
|
2024-01-26 16:17:46 +08:00
|
|
|
{:ok,
|
|
|
|
socket
|
|
|
|
|> assign(initialized: false)
|
|
|
|
|> stream(:chunks, [])}
|
2023-08-22 19:21:22 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
@impl true
|
2024-01-26 16:17:46 +08:00
|
|
|
def update(%{event: {:append, text}}, socket) do
|
|
|
|
{:ok, append_text(socket, text)}
|
|
|
|
end
|
|
|
|
|
2023-08-22 19:21:22 +08:00
|
|
|
def update(assigns, socket) do
|
|
|
|
{text, assigns} = Map.pop(assigns, :text)
|
|
|
|
socket = assign(socket, assigns)
|
|
|
|
|
2024-01-26 16:17:46 +08:00
|
|
|
if socket.assigns.initialized do
|
2023-08-22 19:21:22 +08:00
|
|
|
{:ok, socket}
|
2024-01-26 16:17:46 +08:00
|
|
|
else
|
|
|
|
{:ok,
|
|
|
|
socket
|
|
|
|
|> append_text(text)
|
|
|
|
|> assign(:initialized, true)}
|
2023-08-22 19:21:22 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-01-26 16:17:46 +08:00
|
|
|
defp append_text(socket, text) do
|
|
|
|
chunk = %{id: Livebook.Utils.random_long_id(), text: text}
|
|
|
|
stream_insert(socket, :chunks, chunk)
|
|
|
|
end
|
|
|
|
|
2023-08-22 19:21:22 +08:00
|
|
|
@impl true
|
|
|
|
def render(assigns) do
|
|
|
|
~H"""
|
2023-10-28 03:36:19 +08:00
|
|
|
<div
|
|
|
|
id={@id}
|
|
|
|
class="text-gray-700 whitespace-pre-wrap break-words"
|
|
|
|
phx-update="stream"
|
|
|
|
phx-no-format
|
|
|
|
><span
|
2023-10-28 02:49:46 +08:00
|
|
|
:for={{dom_id, chunk}<- @streams.chunks} id={dom_id}><%= chunk.text %></span></div>
|
2023-08-22 19:21:22 +08:00
|
|
|
"""
|
|
|
|
end
|
|
|
|
end
|