|
| 1 | +defmodule Plausible.CustomerSupport.Resource do |
| 2 | + @moduledoc """ |
| 3 | + Generic behaviour for CS resources and their components |
| 4 | + """ |
| 5 | + defstruct [:id, :type, :module, :object] |
| 6 | + |
| 7 | + @type schema() :: map() |
| 8 | + |
| 9 | + @type t() :: %__MODULE__{ |
| 10 | + id: pos_integer(), |
| 11 | + module: atom(), |
| 12 | + object: schema(), |
| 13 | + type: String.t() |
| 14 | + } |
| 15 | + |
| 16 | + @callback search(String.t(), pos_integer()) :: list(schema()) |
| 17 | + @callback get(pos_integer()) :: schema() |
| 18 | + @callback component() :: module() |
| 19 | + @callback type() :: String.t() |
| 20 | + @callback dump(schema()) :: t() |
| 21 | + |
| 22 | + defmodule Component do |
| 23 | + @moduledoc false |
| 24 | + @callback render_result(assigns :: Phoenix.LiveView.Socket.assigns()) :: |
| 25 | + Phoenix.LiveView.Rendered.t() |
| 26 | + end |
| 27 | + |
| 28 | + defmacro __using__(:component) do |
| 29 | + quote do |
| 30 | + use PlausibleWeb, :live_component |
| 31 | + alias Plausible.CustomerSupport.Resource |
| 32 | + import PlausibleWeb.CustomerSupport.Live.Shared |
| 33 | + |
| 34 | + @behaviour Plausible.CustomerSupport.Resource.Component |
| 35 | + |
| 36 | + def success(socket, msg) do |
| 37 | + send(socket.root_pid, {:success, msg}) |
| 38 | + socket |
| 39 | + end |
| 40 | + |
| 41 | + def failure(socket, msg) do |
| 42 | + send(socket.root_pid, {:failure, msg}) |
| 43 | + socket |
| 44 | + end |
| 45 | + end |
| 46 | + end |
| 47 | + |
| 48 | + defmacro __using__(component: component) do |
| 49 | + quote do |
| 50 | + @behaviour Plausible.CustomerSupport.Resource |
| 51 | + alias Plausible.CustomerSupport.Resource |
| 52 | + |
| 53 | + import Ecto.Query |
| 54 | + alias Plausible.Repo |
| 55 | + |
| 56 | + @impl true |
| 57 | + def dump(schema) do |
| 58 | + Resource.new(__MODULE__, schema) |
| 59 | + end |
| 60 | + |
| 61 | + defoverridable dump: 1 |
| 62 | + |
| 63 | + @impl true |
| 64 | + def type do |
| 65 | + __MODULE__ |
| 66 | + |> Module.split() |
| 67 | + |> Enum.reverse() |
| 68 | + |> hd() |
| 69 | + |> String.downcase() |
| 70 | + end |
| 71 | + |
| 72 | + defoverridable type: 0 |
| 73 | + |
| 74 | + @impl true |
| 75 | + def component, do: unquote(component) |
| 76 | + |
| 77 | + defoverridable component: 0 |
| 78 | + end |
| 79 | + end |
| 80 | + |
| 81 | + def new(module, schema) do |
| 82 | + %__MODULE__{ |
| 83 | + id: schema.id, |
| 84 | + type: module.type(), |
| 85 | + module: module, |
| 86 | + object: schema |
| 87 | + } |
| 88 | + end |
| 89 | +end |
0 commit comments