livebook/lib/livebook_web/live/open_live/source_component.ex

75 lines
1.8 KiB
Elixir
Raw Normal View History

defmodule LivebookWeb.OpenLive.SourceComponent do
use LivebookWeb, :live_component
2023-07-19 06:38:26 +08:00
import Ecto.Changeset
@impl true
def mount(socket) do
2023-07-19 06:38:26 +08:00
{:ok, assign(socket, changeset: changeset())}
end
defp changeset(attrs \\ %{}) do
data = %{source: nil}
types = %{source: :string}
cast({data, types}, attrs, [:source])
|> validate_required([:source])
end
@impl true
def render(assigns) do
~H"""
<div class="flex-col space-y-5">
<p class="text-gray-700" id="import-from-source">
2022-08-02 21:51:02 +08:00
Import notebook by directly pasting the <span class="font-semibold">live markdown</span>
source.
</p>
2022-08-02 21:51:02 +08:00
<.form
2022-10-04 14:46:55 +08:00
:let={f}
2023-07-19 06:38:26 +08:00
for={@changeset}
2023-02-21 03:51:17 +08:00
as={:data}
id="import-source"
phx-submit="import"
phx-change="validate"
phx-target={@myself}
2022-08-02 21:51:02 +08:00
autocomplete="off"
>
2023-02-23 02:34:54 +08:00
<.textarea_field
field={f[:source]}
label="Notebook source"
2023-02-23 02:34:54 +08:00
autofocus
aria-labelledby="import-from-source"
2023-02-23 02:34:54 +08:00
spellcheck="false"
rows="5"
/>
<div class="mt-5">
<.button type="submit" disabled={not @changeset.valid?}>
Import
</.button>
</div>
</.form>
</div>
"""
end
@impl true
2023-07-19 06:38:26 +08:00
def handle_event("validate", %{"data" => data}, socket) do
changeset = data |> changeset() |> Map.replace!(:action, :validate)
{:noreply, assign(socket, changeset: changeset)}
end
2023-07-19 06:38:26 +08:00
def handle_event("import", %{"data" => data}, socket) do
data
|> changeset()
|> apply_action(:insert)
|> case do
{:ok, data} ->
send(self(), {:import_source, data.source, []})
{:noreply, socket}
2023-07-19 06:38:26 +08:00
{:error, changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
end