defmodule FrenzyWeb.EditPipelineLive do use FrenzyWeb, :live_view use Phoenix.HTML alias Frenzy.{Repo, Pipeline} @impl true def mount(%{"id" => pipeline_id}, _session, socket) do pipeline = Repo.get(Pipeline, pipeline_id) {:ok, assign(socket, pipeline: pipeline, stages: [ {"Filter Stage", "Frenzy.Pipeline.FilterStage"}, {"Scrape Stage", "Frenzy.Pipeline.ScrapeStage"}, {"Conditional Stage", "Frenzy.Pipeline.ConditionalStage"} ] )} end @impl true def handle_event("add_stage", %{"stage" => %{"module_name" => module}}, socket) do pipeline = socket.assigns[:pipeline] default_options = apply(String.to_existing_atom("Elixir." <> module), :default_opts, []) changeset = Pipeline.changeset(pipeline, %{ stages: pipeline.stages ++ [%{"module_name" => module, "options" => default_options}] }) {:ok, pipeline} = Repo.update(changeset) {:noreply, assign(socket, pipeline: pipeline)} end def handle_event("delete_stage", %{"index" => index}, socket) do pipeline = socket.assigns.pipeline index = String.to_integer(index) changeset = Pipeline.changeset(pipeline, %{ stages: List.delete_at(pipeline.stages, index) }) {:ok, pipeline} = Repo.update(changeset) {:noreply, assign(socket, pipeline: pipeline)} end @impl true def handle_info({:update_stage_opts, index, new_opts}, socket) do pipeline = socket.assigns.pipeline stages = pipeline.stages stage = Enum.at(stages, index) new_stage = Map.put(stage, "options", new_opts) new_stages = List.replace_at(stages, index, new_stage) changeset = Pipeline.changeset(pipeline, %{stages: new_stages}) {:ok, pipeline} = Repo.update(changeset) {:noreply, assign(socket, pipeline: pipeline)} end def component_for(socket, %{"module_name" => module, "options" => opts}, index) do component = case module do "Frenzy.Pipeline.ScrapeStage" -> FrenzyWeb.ConfigureStage.ScrapeStageLive _ -> nil end case component do nil -> nil component -> live_component(socket, component, index: index, id: "stage-#{index}", opts: opts) end end end