diff --git a/.changeset/thick-boxes-argue.md b/.changeset/thick-boxes-argue.md new file mode 100644 index 0000000000..93cfd2ce02 --- /dev/null +++ b/.changeset/thick-boxes-argue.md @@ -0,0 +1,5 @@ +--- +"@core/elixir-client": patch +--- + +Derive Jason.Encoder for Client.ShapeDefinition diff --git a/.github/workflows/ts_test.yml b/.github/workflows/ts_test.yml index f1e3c87636..b614c0fbc7 100644 --- a/.github/workflows/ts_test.yml +++ b/.github/workflows/ts_test.yml @@ -31,7 +31,7 @@ jobs: example_names: ${{ steps.list_examples.outputs.example_names }} steps: - uses: actions/checkout@v4 - - run: echo "example_names=`find examples/ -mindepth 1 -maxdepth 1 -type d | jq -R -s -c 'split("\n")[:-1]'`" >> $GITHUB_OUTPUT + - run: echo "example_names=$(find examples/ -mindepth 1 -maxdepth 2 -type f -name package.json | xargs dirname | jq -R -s -c 'split("\n")[:-1]')" >> $GITHUB_OUTPUT id: list_examples check_packages: diff --git a/examples/gatekeeper-auth/api/README.md b/examples/gatekeeper-auth/api/README.md index 0c40a1b5d8..4c6b849bdb 100644 --- a/examples/gatekeeper-auth/api/README.md +++ b/examples/gatekeeper-auth/api/README.md @@ -1,4 +1,3 @@ - # API gatekeeper (and proxy) application This is a [Phoenix](https://www.phoenixframework.org) web application written in [Elixir](https://elixir-lang.org). @@ -9,7 +8,7 @@ See the [Implementation](../README.md#implementation) and [How to run](../README Take a look at [`./lib/api_web/router.ex`](./lib/api_web/router.ex) to see what's exposed and read through the [`./lib/api_web/plugs`](./lib/api_web/plugs) and [`./lib/api_web/authenticator.ex`](./lib/api_web/authenticator.ex) to see how auth is implemented and could be extended. -The gatekeeper endpoint is based on an [`Electric.Phoenix.Gateway.Plug`](https://hexdocs.pm/electric_phoenix/Electric.Phoenix.Gateway.Plug.html). +The gatekeeper endpoint is based on an [`Electric.Phoenix.Plug`](https://hexdocs.pm/electric_phoenix/Electric.Phoenix.Plug.html). ## Run/develop locally without Docker diff --git a/examples/gatekeeper-auth/api/config/dev.exs b/examples/gatekeeper-auth/api/config/dev.exs index 782898a6fd..2cbc330e20 100644 --- a/examples/gatekeeper-auth/api/config/dev.exs +++ b/examples/gatekeeper-auth/api/config/dev.exs @@ -27,9 +27,9 @@ config :api, ApiWeb.Endpoint, debug_errors: true, secret_key_base: "pVvBh/U565dk0DteMtnoCjwLcoZnMDU9QeQNVr0gvVtYUrF8KqoJeyn5YJ0EQudX" -# Configure the Electric.Phoenix.Gateway.Plug to route electric client requests +# Configure the Electric.Phoenix.Plug to route electric client requests # via this application's `GET /proxy/v1/shape` endpoint. -config :electric_phoenix, electric_url: "http://localhost:#{port}/proxy" +config :electric_phoenix, Electric.Client, base_url: "http://localhost:#{port}/proxy" # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" diff --git a/examples/gatekeeper-auth/api/config/runtime.exs b/examples/gatekeeper-auth/api/config/runtime.exs index b62a145588..ed41bf7cb0 100644 --- a/examples/gatekeeper-auth/api/config/runtime.exs +++ b/examples/gatekeeper-auth/api/config/runtime.exs @@ -63,11 +63,11 @@ if config_env() == :prod do ], secret_key_base: secret_key_base - # Configure the URL that the Electric.Phoenix.Gateway.Plug uses when returning + # Configure the URL that the Electric.Phoenix.Plug uses when returning # shape config to the client. Defaults to this API, specifically the `/proxy` # endpoint configured in `../lib/api_web/router.ex`. default_proxy_url = URI.parse("https://#{host}:#{port}/proxy") |> URI.to_string() proxy_url = System.get_env("ELECTRIC_PROXY_URL") || default_proxy_url - config :electric_phoenix, electric_url: proxy_url + config :electric_phoenix, Electric.Client, base_url: proxy_url end diff --git a/examples/gatekeeper-auth/api/config/test.exs b/examples/gatekeeper-auth/api/config/test.exs index 4b538ac2eb..91fe8452ad 100644 --- a/examples/gatekeeper-auth/api/config/test.exs +++ b/examples/gatekeeper-auth/api/config/test.exs @@ -25,9 +25,9 @@ config :api, ApiWeb.Endpoint, secret_key_base: "FdsTo+z4sPEhsQNsUtBq26K9qn42nkn1OCH2cLURBZkPCvgJ4F3WiVNFo1NVjojw", server: false -# Configure the Electric.Phoenix.Gateway.Plug to route electric client requests +# Configure the Electric.Phoenix.Plug to route electric client requests # via this application's `GET /proxy/v1/shape` endpoint. -config :electric_phoenix, electric_url: "http://localhost:#{port}/proxy" +config :electric_phoenix, Electric.Client, base_url: "http://localhost:#{port}/proxy" # Print only warnings and errors during test config :logger, level: :warning diff --git a/examples/gatekeeper-auth/api/lib/api_web/authenticator.ex b/examples/gatekeeper-auth/api/lib/api_web/authenticator.ex index a0dacc1ecd..dd97e692e6 100644 --- a/examples/gatekeeper-auth/api/lib/api_web/authenticator.ex +++ b/examples/gatekeeper-auth/api/lib/api_web/authenticator.ex @@ -1,22 +1,18 @@ defmodule ApiWeb.Authenticator do @moduledoc """ - `Electric.Client.Authenticator` implementation that generates - and validates tokens. + Functions for that generating and validating tokens. """ + alias Api.Token - alias Electric.Client - @behaviour Client.Authenticator @header_name "Authorization" - def authenticate_shape(shape, _config) do + # We configure our `Electric.Phoenix.Plug` handler with this function as the + # `authenticator` function in order to return a signed token to the client. + def authentication_headers(_conn, shape) do %{@header_name => "Bearer #{Token.generate(shape)}"} end - def authenticate_request(request, _config) do - request - end - def authorise(shape, request_headers) do header_map = Enum.into(request_headers, %{}) header_key = String.downcase(@header_name) @@ -28,27 +24,4 @@ defmodule ApiWeb.Authenticator do {:error, :missing} end end - - # Provides an `Electric.Client` that uses our `Authenticator` - # implementation to generate signed auth tokens. - # - # This is configured in `./router.ex` to work with the - # `Electric.Phoenix.Gateway.Plug`: - # - # post "/:table", Electric.Phoenix.Gateway.Plug, client: &Authenticator.client/0 - # - # Because `client/0` returns a client that's configured to use our - # `ApiWeb.Authenticator`, then `ApiWeb.Authenticator.authenticate_shape/2` - # will be called to generate an auth header that's included in the - # response data that the Gateway.Plug returns to the client. - # - # I.e.: we basically tie into the `Gateway.Plug` machinery to use our - # `Authenticator` to generate and return a signed token to the client. - def client do - base_url = Application.fetch_env!(:electric_phoenix, :electric_url) - - {:ok, client} = Client.new(base_url: base_url, authenticator: {__MODULE__, []}) - - client - end end diff --git a/examples/gatekeeper-auth/api/lib/api_web/router.ex b/examples/gatekeeper-auth/api/lib/api_web/router.ex index 7aecf1a3f0..e9129021dd 100644 --- a/examples/gatekeeper-auth/api/lib/api_web/router.ex +++ b/examples/gatekeeper-auth/api/lib/api_web/router.ex @@ -28,7 +28,8 @@ defmodule ApiWeb.Router do scope "/gatekeeper" do pipe_through :gatekeeper - post "/:table", Electric.Phoenix.Gateway.Plug, client: &Authenticator.client/0 + post "/:table", Electric.Phoenix.Plug, + authenticator: &Authenticator.authentication_headers/2 end # The proxy endpoint at `GET /proxy/v1/shape` proxies the request to an diff --git a/examples/gatekeeper-auth/api/mix.exs b/examples/gatekeeper-auth/api/mix.exs index 3ad6a18e8e..75a3975a2e 100644 --- a/examples/gatekeeper-auth/api/mix.exs +++ b/examples/gatekeeper-auth/api/mix.exs @@ -26,7 +26,7 @@ defmodule Api.MixProject do defp deps do [ {:bandit, "~> 1.5"}, - {:electric_phoenix, "~> 0.1.2"}, + {:electric_phoenix, ">= 0.2.0-rc-1"}, {:ecto_sql, "~> 3.10"}, {:jason, "~> 1.4"}, {:joken, "~> 2.6"}, diff --git a/examples/gatekeeper-auth/api/mix.lock b/examples/gatekeeper-auth/api/mix.lock index 9cc68e5760..ead03d4738 100644 --- a/examples/gatekeeper-auth/api/mix.lock +++ b/examples/gatekeeper-auth/api/mix.lock @@ -1,13 +1,13 @@ %{ - "bandit": {:hex, :bandit, "1.5.7", "6856b1e1df4f2b0cb3df1377eab7891bec2da6a7fd69dc78594ad3e152363a50", [:mix], [{:hpax, "~> 1.0.0", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.0", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "f2dd92ae87d2cbea2fa9aa1652db157b6cba6c405cb44d4f6dd87abba41371cd"}, - "castore": {:hex, :castore, "1.0.9", "5cc77474afadf02c7c017823f460a17daa7908e991b0cc917febc90e466a375c", [:mix], [], "hexpm", "5ea956504f1ba6f2b4eb707061d8e17870de2bee95fb59d512872c2ef06925e7"}, + "bandit": {:hex, :bandit, "1.6.0", "9cb6c67c27cecab2d0c93968cb957fa8decccb7275193c8bf33f97397b3ac25d", [:mix], [{:hpax, "~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.0", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "fd2491e564a7c5e11ff8496ebf530c342c742452c59de17ac0fb1f814a0ab01a"}, + "castore": {:hex, :castore, "1.0.10", "43bbeeac820f16c89f79721af1b3e092399b3a1ecc8df1a472738fd853574911", [:mix], [], "hexpm", "1b0b7ea14d889d9ea21202c43a4fa015eb913021cb535e8ed91946f4b77a8848"}, "db_connection": {:hex, :db_connection, "2.7.0", "b99faa9291bb09892c7da373bb82cba59aefa9b36300f6145c5f201c7adf48ec", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "dcf08f31b2701f857dfc787fbad78223d61a32204f217f15e881dd93e4bdd3ff"}, - "decimal": {:hex, :decimal, "2.1.1", "5611dca5d4b2c3dd497dec8f68751f1f1a54755e8ed2a966c2633cf885973ad6", [:mix], [], "hexpm", "53cfe5f497ed0e7771ae1a475575603d77425099ba5faef9394932b35020ffcc"}, + "decimal": {:hex, :decimal, "2.2.0", "df3d06bb9517e302b1bd265c1e7f16cda51547ad9d99892049340841f3e15836", [:mix], [], "hexpm", "af8daf87384b51b7e611fb1a1f2c4d4876b65ef968fa8bd3adf44cff401c7f21"}, "dns_cluster": {:hex, :dns_cluster, "0.1.3", "0bc20a2c88ed6cc494f2964075c359f8c2d00e1bf25518a6a6c7fd277c9b0c66", [:mix], [], "hexpm", "46cb7c4a1b3e52c7ad4cbe33ca5079fbde4840dedeafca2baf77996c2da1bc33"}, "ecto": {:hex, :ecto, "3.12.4", "267c94d9f2969e6acc4dd5e3e3af5b05cdae89a4d549925f3008b2b7eb0b93c3", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "ef04e4101688a67d061e1b10d7bc1fbf00d1d13c17eef08b71d070ff9188f747"}, "ecto_sql": {:hex, :ecto_sql, "3.12.1", "c0d0d60e85d9ff4631f12bafa454bc392ce8b9ec83531a412c12a0d415a3a4d0", [:mix], [{:db_connection, "~> 2.4.1 or ~> 2.5", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.12", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.7", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.19 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "aff5b958a899762c5f09028c847569f7dfb9cc9d63bdb8133bff8a5546de6bf5"}, - "electric_client": {:hex, :electric_client, "0.1.2", "1b4b2c3f53a44adaf98a648da21569325338a123ec8f00b7d26c6e3c3583ac94", [:mix], [{:ecto_sql, "~> 3.12", [hex: :ecto_sql, repo: "hexpm", optional: true]}, {:gen_stage, "~> 1.2", [hex: :gen_stage, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:nimble_options, "~> 1.1", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}], "hexpm", "fde191b8ce7c70c44ef12a821210699222ceba1951f73c3c4e7cff8c1d5c0294"}, - "electric_phoenix": {:hex, :electric_phoenix, "0.1.2", "a6228e95e6fa03591307dc34514ba9baf365878efbbfbd78d0312b3b6898bb06", [:mix], [{:ecto_sql, "~> 3.10", [hex: :ecto_sql, repo: "hexpm", optional: true]}, {:electric_client, "~> 0.1.2", [hex: :electric_client, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:nimble_options, "~> 1.1", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 0.20", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "5d88ae053e8035335e6c6d779cc29c3228b71c02d4268e7e959cffff63debd04"}, + "electric_client": {:hex, :electric_client, "0.2.1-rc-2", "3087196645d7cb0e2f7c7b77d84828c363f9069eb1340de5ac8181dc137aaa3f", [:mix], [{:ecto_sql, "~> 3.12", [hex: :ecto_sql, repo: "hexpm", optional: true]}, {:gen_stage, "~> 1.2", [hex: :gen_stage, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:nimble_options, "~> 1.1", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}], "hexpm", "a9dbb5e2ddb6e82e99109f226524e30980f443c6a23295ebb08ae7f675525409"}, + "electric_phoenix": {:hex, :electric_phoenix, "0.2.0-rc-1", "c7f8f7b0db274f22b3189634e1b4e443d4cb1482527ec691ee6a0516f1eefbc2", [:mix], [{:ecto_sql, "~> 3.10", [hex: :ecto_sql, repo: "hexpm", optional: true]}, {:electric_client, "> 0.2.0", [hex: :electric_client, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:nimble_options, "~> 1.1", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 0.20", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "1fca7706043a9559520c44b43b7b81f62748d7513a2a1c7664b65a81919d24fd"}, "finch": {:hex, :finch, "0.19.0", "c644641491ea854fc5c1bbaef36bfc764e3f08e7185e1f084e35e0672241b76d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.6.2 or ~> 1.7", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "fc5324ce209125d1e2fa0fcd2634601c52a787aff1cd33ee833664a5af4ea2b6"}, "hpax": {:hex, :hpax, "1.0.0", "28dcf54509fe2152a3d040e4e3df5b265dcb6cb532029ecbacf4ce52caea3fd2", [:mix], [], "hexpm", "7f1314731d711e2ca5fdc7fd361296593fc2542570b3105595bb0bc6d0fad601"}, "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, @@ -25,12 +25,12 @@ "phoenix_template": {:hex, :phoenix_template, "1.0.4", "e2092c132f3b5e5b2d49c96695342eb36d0ed514c5b252a77048d5969330d639", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "2c0c81f0e5c6753faf5cca2f229c9709919aba34fab866d3bc05060c9c444206"}, "plug": {:hex, :plug, "1.16.1", "40c74619c12f82736d2214557dedec2e9762029b2438d6d175c5074c933edc9d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "a13ff6b9006b03d7e33874945b2755253841b238c34071ed85b0e86057f8cddc"}, "plug_crypto": {:hex, :plug_crypto, "2.1.0", "f44309c2b06d249c27c8d3f65cfe08158ade08418cf540fd4f72d4d6863abb7b", [:mix], [], "hexpm", "131216a4b030b8f8ce0f26038bc4421ae60e4bb95c5cf5395e1421437824c4fa"}, - "postgrex": {:hex, :postgrex, "0.19.2", "34d6884a332c7bf1e367fc8b9a849d23b43f7da5c6e263def92784d03f9da468", [:mix], [{:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "618988886ab7ae8561ebed9a3c7469034bf6a88b8995785a3378746a4b9835ec"}, + "postgrex": {:hex, :postgrex, "0.19.3", "a0bda6e3bc75ec07fca5b0a89bffd242ca209a4822a9533e7d3e84ee80707e19", [:mix], [{:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "d31c28053655b78f47f948c85bb1cf86a9c1f8ead346ba1aa0d0df017fa05b61"}, "req": {:hex, :req, "0.5.7", "b722680e03d531a2947282adff474362a48a02aa54b131196fbf7acaff5e4cee", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.17", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "c6035374615120a8923e8089d0c21a3496cf9eda2d287b806081b8f323ceee29"}, "telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"}, "telemetry_metrics": {:hex, :telemetry_metrics, "1.0.0", "29f5f84991ca98b8eb02fc208b2e6de7c95f8bb2294ef244a176675adc7775df", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f23713b3847286a534e005126d4c959ebcca68ae9582118ce436b521d1d47d5d"}, "telemetry_poller": {:hex, :telemetry_poller, "1.1.0", "58fa7c216257291caaf8d05678c8d01bd45f4bdbc1286838a28c4bb62ef32999", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "9eb9d9cbfd81cbd7cdd24682f8711b6e2b691289a0de6826e58452f28c103c8f"}, - "thousand_island": {:hex, :thousand_island, "1.3.5", "6022b6338f1635b3d32406ff98d68b843ba73b3aa95cfc27154223244f3a6ca5", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "2be6954916fdfe4756af3239fb6b6d75d0b8063b5df03ba76fd8a4c87849e180"}, + "thousand_island": {:hex, :thousand_island, "1.3.6", "835a626a8a6f6a1e681b63e1132a8427e87ce443aaf4888fbf63b2df77539b97", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "0ed8798084c8c49a223840b20598b022e4eb8c9f390fb6701864c307fc9aa2cd"}, "websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"}, - "websock_adapter": {:hex, :websock_adapter, "0.5.7", "65fa74042530064ef0570b75b43f5c49bb8b235d6515671b3d250022cb8a1f9e", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "d0f478ee64deddfec64b800673fd6e0c8888b079d9f3444dd96d2a98383bdbd1"}, + "websock_adapter": {:hex, :websock_adapter, "0.5.8", "3b97dc94e407e2d1fc666b2fb9acf6be81a1798a2602294aac000260a7c4a47d", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "315b9a1865552212b5f35140ad194e67ce31af45bcee443d4ecb96b5fd3f3782"}, } diff --git a/examples/gatekeeper-auth/api/test/api_web/authenticator_test.exs b/examples/gatekeeper-auth/api/test/api_web/authenticator_test.exs index 4f19a2a3dd..ee9504bf84 100644 --- a/examples/gatekeeper-auth/api/test/api_web/authenticator_test.exs +++ b/examples/gatekeeper-auth/api/test/api_web/authenticator_test.exs @@ -9,13 +9,13 @@ defmodule ApiWeb.AuthenticatorTest do {:ok, shape} = Shape.from(%{"table" => "foo"}) assert %{"Authorization" => "Bearer " <> _token} = - Authenticator.authenticate_shape(shape, nil) + Authenticator.authentication_headers(nil, shape) end test "validate token" do {:ok, shape} = Shape.from(%{"table" => "foo"}) - headers = Authenticator.authenticate_shape(shape, nil) + headers = Authenticator.authentication_headers(nil, shape) assert Authenticator.authorise(shape, headers) end @@ -26,7 +26,7 @@ defmodule ApiWeb.AuthenticatorTest do "where" => "value IS NOT NULL" }) - headers = Authenticator.authenticate_shape(shape, nil) + headers = Authenticator.authentication_headers(nil, shape) assert Authenticator.authorise(shape, headers) end end diff --git a/examples/gatekeeper-auth/docker-compose.yaml b/examples/gatekeeper-auth/docker-compose.yaml index d5346baa35..59f85001ca 100644 --- a/examples/gatekeeper-auth/docker-compose.yaml +++ b/examples/gatekeeper-auth/docker-compose.yaml @@ -34,7 +34,7 @@ services: AUTH_SECRET: "NFL5*0Bc#9U6E@tnmC&E7SUN6GwHfLmY" DATABASE_URL: "postgresql://postgres:password@postgres:5432/electric?sslmode=disable" ELECTRIC_URL: "http://electric:3000" - ELECTRIC_PROXY_URL: "${ELECTRIC_PROXY_URL:-http://localhost:3000/proxy}" + ELECTRIC_PROXY_URL: "${ELECTRIC_PROXY_URL:-http://localhost:4000/proxy}" PHX_HOST: "localhost" PHX_PORT: 4000 PHX_SCHEME: "http" diff --git a/examples/phoenix-liveview/.formatter.exs b/examples/phoenix-liveview/.formatter.exs new file mode 100644 index 0000000000..ef8840ce6f --- /dev/null +++ b/examples/phoenix-liveview/.formatter.exs @@ -0,0 +1,6 @@ +[ + import_deps: [:ecto, :ecto_sql, :phoenix], + subdirectories: ["priv/*/migrations"], + plugins: [Phoenix.LiveView.HTMLFormatter], + inputs: ["*.{heex,ex,exs}", "{config,lib,test}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"] +] diff --git a/examples/phoenix-liveview/.gitignore b/examples/phoenix-liveview/.gitignore new file mode 100644 index 0000000000..6a70f2a39d --- /dev/null +++ b/examples/phoenix-liveview/.gitignore @@ -0,0 +1,37 @@ +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where 3rd-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Temporary files, for example, from tests. +/tmp/ + +# Ignore package tarball (built via "mix hex.build"). +electric_phoenix-*.tar + +# Ignore assets that are produced by build tools. +/priv/static/assets/ + +# Ignore digested assets cache. +/priv/static/cache_manifest.json + +# In case you use Node.js/npm, you want to ignore these. +npm-debug.log +/assets/node_modules/ + diff --git a/examples/phoenix-liveview/README.md b/examples/phoenix-liveview/README.md new file mode 100644 index 0000000000..aa1057b9be --- /dev/null +++ b/examples/phoenix-liveview/README.md @@ -0,0 +1,31 @@ +# Elixir Phoenix Example Application + +This is an example Phoenix LiveView application that uses +[`Electric.Phoenix.LiveView.electric_stream/4`](https://hexdocs.pm/electric_phoenix/Electric.Phoenix.LiveView.html#electric_stream/4) +to sync data from Postgres into a LiveView using +[Phoenix Streams](https://fly.io/phoenix-files/phoenix-dev-blog-streams/). +This keeps the LiveView automatically in-sync with Postgres, without having +to re-run queries or trigger any change handling yourself. + +See the +[documentation](https://electric-sql.com/docs/integrations/phoenix#liveview-sync) +for more details. + +## Getting started + +To start your Phoenix server: + +- Run `mix electric.start` to start an Electric instance and associated Postgres DB. +- Run `mix setup` to install and setup dependencies +- Start Phoenix endpoint with `mix phx.server` or inside IEx with `iex -S mix phx.server` + +Now you can visit [`localhost:4000`](http://localhost:4000) from your browser. + +If you open two separate windows, you will see you changes happen +simultaneously in both windows. + +## Implementation + +See the [`Electric.PhoenixExampleWeb.TodoLive.Index` +module](./lib/electric_phoenix_example_web/live/todo_live/index.ex) and the +[`Electric.Phoenix` documentation](https://hexdocs.pm/electric_phoenix/). diff --git a/examples/phoenix-liveview/assets/css/app.css b/examples/phoenix-liveview/assets/css/app.css new file mode 100644 index 0000000000..666b6e3aee --- /dev/null +++ b/examples/phoenix-liveview/assets/css/app.css @@ -0,0 +1,15 @@ +@import "tailwindcss/base"; +@import "tailwindcss/components"; +@import "tailwindcss/utilities"; + +/* This file is for your main application CSS */ + +#blurb p + p { + @apply pt-2; +} +#blurb a { + @apply text-violet-500; +} +#blurb a:hover { + @apply underline; +} diff --git a/examples/phoenix-liveview/assets/js/app.js b/examples/phoenix-liveview/assets/js/app.js new file mode 100644 index 0000000000..d5e278afe5 --- /dev/null +++ b/examples/phoenix-liveview/assets/js/app.js @@ -0,0 +1,44 @@ +// If you want to use Phoenix channels, run `mix help phx.gen.channel` +// to get started and then uncomment the line below. +// import "./user_socket.js" + +// You can include dependencies in two ways. +// +// The simplest option is to put them in assets/vendor and +// import them using relative paths: +// +// import "../vendor/some-package.js" +// +// Alternatively, you can `npm install some-package --prefix assets` and import +// them using a path starting with the package name: +// +// import "some-package" +// + +// Include phoenix_html to handle method=PUT/DELETE in forms and buttons. +import "phoenix_html" +// Establish Phoenix Socket and LiveView configuration. +import {Socket} from "phoenix" +import {LiveSocket} from "phoenix_live_view" +import topbar from "../vendor/topbar" + +let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") +let liveSocket = new LiveSocket("/live", Socket, { + longPollFallbackMs: 2500, + params: {_csrf_token: csrfToken} +}) + +// Show progress bar on live navigation and form submits +topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) +window.addEventListener("phx:page-loading-start", _info => topbar.show(300)) +window.addEventListener("phx:page-loading-stop", _info => topbar.hide()) + +// connect if there are any LiveViews on the page +liveSocket.connect() + +// expose liveSocket on window for web console debug logs and latency simulation: +// >> liveSocket.enableDebug() +// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session +// >> liveSocket.disableLatencySim() +window.liveSocket = liveSocket + diff --git a/examples/phoenix-liveview/assets/tailwind.config.js b/examples/phoenix-liveview/assets/tailwind.config.js new file mode 100644 index 0000000000..ade40e2341 --- /dev/null +++ b/examples/phoenix-liveview/assets/tailwind.config.js @@ -0,0 +1,95 @@ +// See the Tailwind configuration guide for advanced usage +// https://tailwindcss.com/docs/configuration + +const plugin = require("tailwindcss/plugin"); +const fs = require("fs"); +const path = require("path"); + +module.exports = { + content: [ + "./js/**/*.js", + "../lib/electric_phoenix_example_web.ex", + "../lib/electric_phoenix_example_web/**/*.*ex", + ], + theme: { + extend: { + colors: { + brand: "#FD4F00", + }, + }, + }, + plugins: [ + require("@tailwindcss/forms"), + // Allows prefixing tailwind classes with LiveView classes to add rules + // only when LiveView classes are applied, for example: + // + //
+ // + plugin(({ addVariant }) => + addVariant("phx-click-loading", [ + ".phx-click-loading&", + ".phx-click-loading &", + ]), + ), + plugin(({ addVariant }) => + addVariant("phx-submit-loading", [ + ".phx-submit-loading&", + ".phx-submit-loading &", + ]), + ), + plugin(({ addVariant }) => + addVariant("phx-change-loading", [ + ".phx-change-loading&", + ".phx-change-loading &", + ]), + ), + + // Embeds Heroicons (https://heroicons.com) into your app.css bundle + // See your `CoreComponents.icon/1` for more information. + // + plugin(function ({ matchComponents, theme }) { + let iconsDir = path.join(__dirname, "../deps/heroicons/optimized"); + let values = {}; + let icons = [ + ["", "/24/outline"], + ["-solid", "/24/solid"], + ["-mini", "/20/solid"], + ["-micro", "/16/solid"], + ]; + icons.forEach(([suffix, dir]) => { + fs.readdirSync(path.join(iconsDir, dir)).forEach((file) => { + let name = path.basename(file, ".svg") + suffix; + values[name] = { name, fullPath: path.join(iconsDir, dir, file) }; + }); + }); + matchComponents( + { + hero: ({ name, fullPath }) => { + let content = fs + .readFileSync(fullPath) + .toString() + .replace(/\r?\n|\r/g, ""); + let size = theme("spacing.6"); + if (name.endsWith("-mini")) { + size = theme("spacing.5"); + } else if (name.endsWith("-micro")) { + size = theme("spacing.4"); + } + return { + [`--hero-${name}`]: `url('data:image/svg+xml;utf8,${content}')`, + "-webkit-mask": `var(--hero-${name})`, + mask: `var(--hero-${name})`, + "mask-repeat": "no-repeat", + "background-color": "currentColor", + "vertical-align": "middle", + display: "inline-block", + width: size, + height: size, + }; + }, + }, + { values }, + ); + }), + ], +}; diff --git a/examples/phoenix-liveview/assets/vendor/topbar.js b/examples/phoenix-liveview/assets/vendor/topbar.js new file mode 100644 index 0000000000..41957274d7 --- /dev/null +++ b/examples/phoenix-liveview/assets/vendor/topbar.js @@ -0,0 +1,165 @@ +/** + * @license MIT + * topbar 2.0.0, 2023-02-04 + * https://buunguyen.github.io/topbar + * Copyright (c) 2021 Buu Nguyen + */ +(function (window, document) { + "use strict"; + + // https://gist.github.com/paulirish/1579671 + (function () { + var lastTime = 0; + var vendors = ["ms", "moz", "webkit", "o"]; + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + window.requestAnimationFrame = + window[vendors[x] + "RequestAnimationFrame"]; + window.cancelAnimationFrame = + window[vendors[x] + "CancelAnimationFrame"] || + window[vendors[x] + "CancelRequestAnimationFrame"]; + } + if (!window.requestAnimationFrame) + window.requestAnimationFrame = function (callback, element) { + var currTime = new Date().getTime(); + var timeToCall = Math.max(0, 16 - (currTime - lastTime)); + var id = window.setTimeout(function () { + callback(currTime + timeToCall); + }, timeToCall); + lastTime = currTime + timeToCall; + return id; + }; + if (!window.cancelAnimationFrame) + window.cancelAnimationFrame = function (id) { + clearTimeout(id); + }; + })(); + + var canvas, + currentProgress, + showing, + progressTimerId = null, + fadeTimerId = null, + delayTimerId = null, + addEvent = function (elem, type, handler) { + if (elem.addEventListener) elem.addEventListener(type, handler, false); + else if (elem.attachEvent) elem.attachEvent("on" + type, handler); + else elem["on" + type] = handler; + }, + options = { + autoRun: true, + barThickness: 3, + barColors: { + 0: "rgba(26, 188, 156, .9)", + ".25": "rgba(52, 152, 219, .9)", + ".50": "rgba(241, 196, 15, .9)", + ".75": "rgba(230, 126, 34, .9)", + "1.0": "rgba(211, 84, 0, .9)", + }, + shadowBlur: 10, + shadowColor: "rgba(0, 0, 0, .6)", + className: null, + }, + repaint = function () { + canvas.width = window.innerWidth; + canvas.height = options.barThickness * 5; // need space for shadow + + var ctx = canvas.getContext("2d"); + ctx.shadowBlur = options.shadowBlur; + ctx.shadowColor = options.shadowColor; + + var lineGradient = ctx.createLinearGradient(0, 0, canvas.width, 0); + for (var stop in options.barColors) + lineGradient.addColorStop(stop, options.barColors[stop]); + ctx.lineWidth = options.barThickness; + ctx.beginPath(); + ctx.moveTo(0, options.barThickness / 2); + ctx.lineTo( + Math.ceil(currentProgress * canvas.width), + options.barThickness / 2 + ); + ctx.strokeStyle = lineGradient; + ctx.stroke(); + }, + createCanvas = function () { + canvas = document.createElement("canvas"); + var style = canvas.style; + style.position = "fixed"; + style.top = style.left = style.right = style.margin = style.padding = 0; + style.zIndex = 100001; + style.display = "none"; + if (options.className) canvas.classList.add(options.className); + document.body.appendChild(canvas); + addEvent(window, "resize", repaint); + }, + topbar = { + config: function (opts) { + for (var key in opts) + if (options.hasOwnProperty(key)) options[key] = opts[key]; + }, + show: function (delay) { + if (showing) return; + if (delay) { + if (delayTimerId) return; + delayTimerId = setTimeout(() => topbar.show(), delay); + } else { + showing = true; + if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId); + if (!canvas) createCanvas(); + canvas.style.opacity = 1; + canvas.style.display = "block"; + topbar.progress(0); + if (options.autoRun) { + (function loop() { + progressTimerId = window.requestAnimationFrame(loop); + topbar.progress( + "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2) + ); + })(); + } + } + }, + progress: function (to) { + if (typeof to === "undefined") return currentProgress; + if (typeof to === "string") { + to = + (to.indexOf("+") >= 0 || to.indexOf("-") >= 0 + ? currentProgress + : 0) + parseFloat(to); + } + currentProgress = to > 1 ? 1 : to; + repaint(); + return currentProgress; + }, + hide: function () { + clearTimeout(delayTimerId); + delayTimerId = null; + if (!showing) return; + showing = false; + if (progressTimerId != null) { + window.cancelAnimationFrame(progressTimerId); + progressTimerId = null; + } + (function loop() { + if (topbar.progress("+.1") >= 1) { + canvas.style.opacity -= 0.05; + if (canvas.style.opacity <= 0.05) { + canvas.style.display = "none"; + fadeTimerId = null; + return; + } + } + fadeTimerId = window.requestAnimationFrame(loop); + })(); + }, + }; + + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = topbar; + } else if (typeof define === "function" && define.amd) { + define(function () { + return topbar; + }); + } else { + this.topbar = topbar; + } +}.call(this, window, document)); diff --git a/examples/phoenix-liveview/config/config.exs b/examples/phoenix-liveview/config/config.exs new file mode 100644 index 0000000000..dff034bd3c --- /dev/null +++ b/examples/phoenix-liveview/config/config.exs @@ -0,0 +1,61 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Config module. +# +# This configuration file is loaded before any dependency and +# is restricted to this project. + +# General application configuration +import Config + +config :electric_phoenix_example, + namespace: Electric.PhoenixExample, + ecto_repos: [Electric.PhoenixExample.Repo], + generators: [timestamp_type: :utc_datetime] + +# Configures the endpoint +config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, + url: [host: "0,"], + adapter: Bandit.PhoenixAdapter, + render_errors: [ + formats: [ + html: Electric.PhoenixExampleWeb.ErrorHTML, + json: Electric.PhoenixExampleWeb.ErrorJSON + ], + layout: false + ], + pubsub_server: Electric.PhoenixExample.PubSub, + live_view: [signing_salt: "sSaEOlHN"] + +# Configure esbuild (the version is required) +config :esbuild, + version: "0.17.11", + electric_phoenix_example: [ + args: + ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), + cd: Path.expand("../assets", __DIR__), + env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} + ] + +# Configure tailwind (the version is required) +config :tailwind, + version: "3.4.3", + electric_phoenix_example: [ + args: ~w( + --config=tailwind.config.js + --input=css/app.css + --output=../priv/static/assets/app.css + ), + cd: Path.expand("../assets", __DIR__) + ] + +# Configures Elixir's Logger +config :logger, :console, + format: "$time $metadata[$level] $message\n", + metadata: [:request_id] + +# Use Jason for JSON parsing in Phoenix +config :phoenix, :json_library, Jason + +# Import environment specific config. This must remain at the bottom +# of this file so it overrides the configuration defined above. +import_config "#{config_env()}.exs" diff --git a/examples/phoenix-liveview/config/dev.exs b/examples/phoenix-liveview/config/dev.exs new file mode 100644 index 0000000000..574b463020 --- /dev/null +++ b/examples/phoenix-liveview/config/dev.exs @@ -0,0 +1,87 @@ +import Config + +# Configure your database +config :electric_phoenix_example, Electric.PhoenixExample.Repo, + username: "postgres", + password: "password", + hostname: "localhost", + database: "electric", + port: 54321, + stacktrace: true, + show_sensitive_data_on_connection_error: true, + pool_size: 10 + +# For development, we disable any cache and enable +# debugging and code reloading. +# +# The watchers configuration can be used to run external +# watchers to your application. For example, we can use it +# to bundle .js and .css sources. +config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, + # Binding to loopback ipv4 address prevents access from other machines. + # Change to `ip: {0, 0, 0, 0}` to allow access from other machines. + http: [ip: {0, 0, 0, 0}, port: 4000], + check_origin: false, + code_reloader: true, + debug_errors: true, + secret_key_base: "dNSXyPFTrR0O7cN4ZJEdRlDL/NoBisUMHLx2dnJWJjveO9LWiY1f9Jmtkbt5JxvZ", + watchers: [ + esbuild: + {Esbuild, :install_and_run, [:electric_phoenix_example, ~w(--sourcemap=inline --watch)]}, + tailwind: {Tailwind, :install_and_run, [:electric_phoenix_example, ~w(--watch)]} + ] + +# ## SSL Electric.PhoenixExample +# +# In order to use HTTPS in development, a self-signed +# certificate can be generated by running the following +# Mix task: +# +# mix phx.gen.cert +# +# Run `mix help phx.gen.cert` for more information. +# +# The `http:` config above can be replaced with: +# +# https: [ +# port: 4001, +# cipher_suite: :strong, +# keyfile: "priv/cert/selfsigned_key.pem", +# certfile: "priv/cert/selfsigned.pem" +# ], +# +# If desired, both `http:` and `https:` keys can be +# configured to run both http and https servers on +# different ports. + +# Watch static and templates for browser reloading. +config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, + live_reload: [ + patterns: [ + ~r"priv/static/(?!uploads/).*(js|css|png|jpeg|jpg|gif|svg)$", + ~r"priv/gettext/.*(po)$", + ~r"lib/electric_phoenix_example_web/(controllers|live|components)/.*(ex|heex)$" + ] + ] + +# Enable dev routes for dashboard and mailbox +config :electric_phoenix_example, dev_routes: true + +# Do not include metadata nor timestamps in development logs +config :logger, :console, format: "[$level] $message\n" + +# Set a higher stacktrace during development. Avoid configuring such +# in production as building large stacktraces may be expensive. +config :phoenix, :stacktrace_depth, 20 + +# Initialize plugs at runtime for faster development compilation +config :phoenix, :plug_init_mode, :runtime + +config :phoenix_live_view, + # Include HEEx debug annotations as HTML comments in rendered markup + debug_heex_annotations: true, + # Enable helpful, but potentially expensive runtime checks + enable_expensive_runtime_checks: true + +config :electric_phoenix, Electric.Client, + base_url: System.get_env("ELECTRIC_URL", "http://localhost:3000/") diff --git a/examples/phoenix-liveview/config/prod.exs b/examples/phoenix-liveview/config/prod.exs new file mode 100644 index 0000000000..8a33a094b0 --- /dev/null +++ b/examples/phoenix-liveview/config/prod.exs @@ -0,0 +1,15 @@ +import Config + +# Note we also include the path to a cache manifest +# containing the digested version of static files. This +# manifest is generated by the `mix assets.deploy` task, +# which you should run after static files are built and +# before starting your production server. +config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, + cache_static_manifest: "priv/static/cache_manifest.json" + +# Do not print debug messages in production +config :logger, level: :info + +# Runtime production configuration, including reading +# of environment variables, is done on config/runtime.exs. diff --git a/examples/phoenix-liveview/config/runtime.exs b/examples/phoenix-liveview/config/runtime.exs new file mode 100644 index 0000000000..0ba9eb0330 --- /dev/null +++ b/examples/phoenix-liveview/config/runtime.exs @@ -0,0 +1,102 @@ +import Config + +# config/runtime.exs is executed for all environments, including +# during releases. It is executed after compilation and before the +# system starts, so it is typically used to load production configuration +# and secrets from environment variables or elsewhere. Do not define +# any compile-time configuration in here, as it won't be applied. +# The block below contains prod specific runtime configuration. + +# ## Using releases +# +# If you use `mix release`, you need to explicitly enable the server +# by passing the PHX_SERVER=true when you start it: +# +# PHX_SERVER=true bin/electric_phoenix_example start +# +# Alternatively, you can use `mix phx.gen.release` to generate a `bin/server` +# script that automatically sets the env var above. +if System.get_env("PHX_SERVER") do + config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, server: true +end + +if config_env() == :prod do + database_url = + System.get_env("DATABASE_URL") || + raise """ + environment variable DATABASE_URL is missing. + For example: ecto://USER:PASS@HOST/DATABASE + """ + + maybe_ipv6 = if System.get_env("ECTO_IPV6") in ~w(true 1), do: [:inet6], else: [] + + config :electric_phoenix_example, Electric.PhoenixExample.Repo, + # ssl: true, + url: database_url, + pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"), + socket_options: maybe_ipv6 + + # The secret key base is used to sign/encrypt cookies and other secrets. + # A default value is used in config/dev.exs and config/test.exs but you + # want to use a different value for prod and you most likely don't want + # to check this value into version control, so we use an environment + # variable instead. + secret_key_base = + System.get_env("SECRET_KEY_BASE") || + raise """ + environment variable SECRET_KEY_BASE is missing. + You can generate one by calling: mix phx.gen.secret + """ + + host = System.get_env("PHX_HOST") || "example.com" + port = String.to_integer(System.get_env("PORT") || "4000") + + config :electric_phoenix_example, :dns_cluster_query, System.get_env("DNS_CLUSTER_QUERY") + + config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, + url: [host: host, port: 443, scheme: "https"], + http: [ + # Enable IPv6 and bind on all interfaces. + # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. + # See the documentation on https://hexdocs.pm/bandit/Bandit.html#t:options/0 + # for details about using IPv6 vs IPv4 and loopback vs public addresses. + ip: {0, 0, 0, 0, 0, 0, 0, 0}, + port: port + ], + secret_key_base: secret_key_base + + # ## SSL Electric.PhoenixExample + # + # To get SSL working, you will need to add the `https` key + # to your endpoint configuration: + # + # config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, + # https: [ + # ..., + # port: 443, + # cipher_suite: :strong, + # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), + # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") + # ] + # + # The `cipher_suite` is set to `:strong` to support only the + # latest and more secure SSL ciphers. This means old browsers + # and clients may not be supported. You can set it to + # `:compatible` for wider support. + # + # `:keyfile` and `:certfile` expect an absolute path to the key + # and cert in disk or a relative path inside priv, for example + # "priv/ssl/server.key". For all supported SSL configuration + # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 + # + # We also recommend setting `force_ssl` in your config/prod.exs, + # ensuring no data is ever sent via http, always redirecting to https: + # + # config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, + # force_ssl: [hsts: true] + # + # Check `Plug.SSL` for all available options in `force_ssl`. + + config :electric_phoenix, Electric.Client, + base_url: System.get_env("ELECTRIC_URL") || raise("ELECTRIC_URL environment variable not set") +end diff --git a/examples/phoenix-liveview/config/test.exs b/examples/phoenix-liveview/config/test.exs new file mode 100644 index 0000000000..8ca9754449 --- /dev/null +++ b/examples/phoenix-liveview/config/test.exs @@ -0,0 +1,31 @@ +import Config + +# Configure your database +# +# The MIX_TEST_PARTITION environment variable can be used +# to provide built-in test partitioning in CI environment. +# Run `mix help test` for more information. +config :electric_phoenix_example, Electric.PhoenixExample.Repo, + username: "postgres", + password: "postgres", + hostname: "localhost", + database: "electric_phoenix_test#{System.get_env("MIX_TEST_PARTITION")}", + pool: Ecto.Adapters.SQL.Sandbox, + pool_size: System.schedulers_online() * 2 + +# We don't run a server during test. If one is required, +# you can enable the server option below. +config :electric_phoenix_example, Electric.PhoenixExampleWeb.Endpoint, + http: [ip: {127, 0, 0, 1}, port: 4002], + secret_key_base: "UdwZBpb9b+DMjoK82/IpEIqL/DnBiPmDlzljDo6v94eGfPphP5MUNIrAyp3T2OVd", + server: false + +# Print only warnings and errors during test +config :logger, level: :warning + +# Initialize plugs at runtime for faster test compilation +config :phoenix, :plug_init_mode, :runtime + +# Enable helpful, but potentially expensive runtime checks +config :phoenix_live_view, + enable_expensive_runtime_checks: true diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example.ex b/examples/phoenix-liveview/lib/electric_phoenix_example.ex new file mode 100644 index 0000000000..13fb3925a9 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example.ex @@ -0,0 +1,9 @@ +defmodule Electric.PhoenixExample do + @moduledoc """ + Electric.PhoenixExample keeps the contexts that define your domain + and business logic. + + Contexts are also responsible for managing your data, regardless + if it comes from the database, an external API or others. + """ +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example/application.ex b/examples/phoenix-liveview/lib/electric_phoenix_example/application.ex new file mode 100644 index 0000000000..7f55af4689 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example/application.ex @@ -0,0 +1,35 @@ +defmodule Electric.PhoenixExample.Application do + # See https://hexdocs.pm/elixir/Application.html + # for more information on OTP Applications + @moduledoc false + + use Application + + @impl true + def start(_type, _args) do + children = [ + Electric.PhoenixExampleWeb.Telemetry, + Electric.PhoenixExample.Repo, + {DNSCluster, + query: Application.get_env(:electric_phoenix_example, :dns_cluster_query) || :ignore}, + {Phoenix.PubSub, name: Electric.PhoenixExample.PubSub}, + # Start a worker by calling: Electric.PhoenixExample.Worker.start_link(arg) + # {Electric.PhoenixExample.Worker, arg}, + # Start to serve requests, typically the last entry + Electric.PhoenixExampleWeb.Endpoint + ] + + # See https://hexdocs.pm/elixir/Supervisor.html + # for other strategies and supported options + opts = [strategy: :one_for_one, name: Electric.PhoenixExample.Supervisor] + Supervisor.start_link(children, opts) + end + + # Tell Phoenix to update the endpoint configuration + # whenever the application is updated. + @impl true + def config_change(changed, _new, removed) do + Electric.PhoenixExampleWeb.Endpoint.config_change(changed, removed) + :ok + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example/repo.ex b/examples/phoenix-liveview/lib/electric_phoenix_example/repo.ex new file mode 100644 index 0000000000..ec57749d17 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example/repo.ex @@ -0,0 +1,5 @@ +defmodule Electric.PhoenixExample.Repo do + use Ecto.Repo, + otp_app: :electric_phoenix_example, + adapter: Ecto.Adapters.Postgres +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example/todos.ex b/examples/phoenix-liveview/lib/electric_phoenix_example/todos.ex new file mode 100644 index 0000000000..6c465f1784 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example/todos.ex @@ -0,0 +1,109 @@ +defmodule Electric.PhoenixExample.Todos do + @moduledoc """ + The Todos context. + """ + + alias Electric.PhoenixExample.Repo + alias Electric.PhoenixExample.Todos.Todo + + import Ecto.Query, warn: false + + @doc """ + Returns the list of todos. + + ## Examples + + iex> list_todos() + [%Todo{}, ...] + + """ + def list_todos do + Repo.all(Todo) + end + + @doc """ + Gets a single todo. + + Raises `Ecto.NoResultsError` if the Todo does not exist. + + ## Examples + + iex> get_todo!(123) + %Todo{} + + iex> get_todo!(456) + ** (Ecto.NoResultsError) + + """ + def get_todo!(id), do: Repo.get!(Todo, id) + + @doc """ + Creates a todo. + + ## Examples + + iex> create_todo(%{field: value}) + {:ok, %Todo{}} + + iex> create_todo(%{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def create_todo(attrs \\ %{}) do + %Todo{} + |> Todo.changeset(attrs) + |> Repo.insert() + end + + @doc """ + Updates a todo. + + ## Examples + + iex> update_todo(todo, %{field: new_value}) + {:ok, %Todo{}} + + iex> update_todo(todo, %{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def update_todo(%Todo{} = todo, attrs) do + todo + |> Todo.changeset(attrs) + |> Repo.update() + end + + @doc """ + Deletes a todo. + + ## Examples + + iex> delete_todo(todo) + {:ok, %Todo{}} + + iex> delete_todo(todo) + {:error, %Ecto.Changeset{}} + + """ + def delete_todo(%Todo{} = todo) do + Repo.delete(todo) + end + + @doc """ + Returns an `%Ecto.Changeset{}` for tracking todo changes. + + ## Examples + + iex> change_todo(todo) + %Ecto.Changeset{data: %Todo{}} + + """ + def change_todo(%Todo{} = todo, attrs \\ %{}) do + Todo.changeset(todo, attrs) + end + + def toggle_complete(%Todo{} = todo) do + todo + |> update_todo(%{completed: !todo.completed}) + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example/todos/todo.ex b/examples/phoenix-liveview/lib/electric_phoenix_example/todos/todo.ex new file mode 100644 index 0000000000..c9dc3ff704 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example/todos/todo.ex @@ -0,0 +1,19 @@ +defmodule Electric.PhoenixExample.Todos.Todo do + use Ecto.Schema + import Ecto.Changeset + + schema "todos" do + field :text, :string + field :completed, :boolean, default: false + + timestamps(type: :utc_datetime) + end + + @doc false + def changeset(todo, attrs) do + todo + |> cast(attrs, [:text, :completed]) + |> validate_required([:text, :completed]) + |> update_change(:text, &String.trim/1) + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web.ex new file mode 100644 index 0000000000..d33cbe9d46 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web.ex @@ -0,0 +1,114 @@ +defmodule Electric.PhoenixExampleWeb do + @moduledoc """ + The entrypoint for defining your web interface, such + as controllers, components, channels, and so on. + + This can be used in your application as: + + use Electric.PhoenixExampleWeb, :controller + use Electric.PhoenixExampleWeb, :html + + The definitions below will be executed for every controller, + component, etc, so keep them short and clean, focused + on imports, uses and aliases. + + Do NOT define functions inside the quoted expressions + below. Instead, define additional modules and import + those modules here. + """ + + def static_paths, do: ~w(assets fonts images favicon.ico robots.txt) + + def router do + quote do + use Phoenix.Router, helpers: false + + # Import common connection and controller functions to use in pipelines + import Plug.Conn + import Phoenix.Controller + import Phoenix.LiveView.Router + end + end + + def channel do + quote do + use Phoenix.Channel + end + end + + def controller do + quote do + use Phoenix.Controller, + formats: [:html, :json], + layouts: [html: Electric.PhoenixExampleWeb.Layouts] + + use Gettext, backend: Electric.PhoenixExampleWeb.Gettext + + import Plug.Conn + + unquote(verified_routes()) + end + end + + def live_view do + quote do + use Phoenix.LiveView, + layout: {Electric.PhoenixExampleWeb.Layouts, :app} + + unquote(html_helpers()) + end + end + + def live_component do + quote do + use Phoenix.LiveComponent + + unquote(html_helpers()) + end + end + + def html do + quote do + use Phoenix.Component + + # Import convenience functions from controllers + import Phoenix.Controller, + only: [get_csrf_token: 0, view_module: 1, view_template: 1] + + # Include general helpers for rendering HTML + unquote(html_helpers()) + end + end + + defp html_helpers do + quote do + use Gettext, backend: Electric.PhoenixExampleWeb.Gettext + # HTML escaping functionality + import Phoenix.HTML + # Core UI components and translation + import Electric.PhoenixExampleWeb.CoreComponents + + # Shortcut for generating JS commands + alias Phoenix.LiveView.JS + + # Routes generation with the ~p sigil + unquote(verified_routes()) + end + end + + def verified_routes do + quote do + use Phoenix.VerifiedRoutes, + endpoint: Electric.PhoenixExampleWeb.Endpoint, + router: Electric.PhoenixExampleWeb.Router, + statics: Electric.PhoenixExampleWeb.static_paths() + end + end + + @doc """ + When used, dispatch to the appropriate controller/live_view/etc. + """ + defmacro __using__(which) when is_atom(which) do + apply(__MODULE__, which, []) + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/core_components.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/core_components.ex new file mode 100644 index 0000000000..947421305c --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/core_components.ex @@ -0,0 +1,620 @@ +defmodule Electric.PhoenixExampleWeb.CoreComponents do + @moduledoc """ + Provides core UI components. + + At first glance, this module may seem daunting, but its goal is to provide + core building blocks for your application, such as modals, tables, and + forms. The components consist mostly of markup and are well-documented + with doc strings and declarative assigns. You may customize and style + them in any way you want, based on your application growth and needs. + + The default components use Tailwind CSS, a utility-first CSS framework. + See the [Tailwind CSS documentation](https://tailwindcss.com) to learn + how to customize them or feel free to swap in another framework altogether. + + Icons are provided by [heroicons](https://heroicons.com). See `icon/1` for usage. + """ + use Phoenix.Component + + alias Phoenix.LiveView.JS + use Gettext, backend: Electric.PhoenixExampleWeb.Gettext + + @doc """ + Renders a modal. + + ## Examples + + <.modal id="confirm-modal"> + This is a modal. + + + JS commands may be passed to the `:on_cancel` to configure + the closing/cancel event, for example: + + <.modal id="confirm" on_cancel={JS.navigate(~p"/posts")}> + This is another modal. + + + """ + attr :id, :string, required: true + attr :show, :boolean, default: false + attr :on_cancel, JS, default: %JS{} + slot :inner_block, required: true + + def modal(assigns) do + ~H""" + + """ + end + + def input(%{type: "select"} = assigns) do + ~H""" +
+ <.label for={@id}><%= @label %> + + <.error :for={msg <- @errors}><%= msg %> +
+ """ + end + + def input(%{type: "textarea"} = assigns) do + ~H""" +
+ <.label for={@id}><%= @label %> + + <.error :for={msg <- @errors}><%= msg %> +
+ """ + end + + # All other inputs text, datetime-local, url, password, etc. are handled here... + def input(assigns) do + ~H""" +
+ + <.error :for={msg <- @errors}><%= msg %> +
+ """ + end + + @doc """ + Renders a label. + """ + attr :for, :string, default: nil + slot :inner_block, required: true + + def label(assigns) do + ~H""" + + """ + end + + @doc """ + Generates a generic error message. + """ + slot :inner_block, required: true + + def error(assigns) do + ~H""" +

+ <.icon name="hero-exclamation-circle-mini" class="mt-0.5 h-5 w-5 flex-none" /> + <%= render_slot(@inner_block) %> +

+ """ + end + + @doc """ + Renders a header with title. + """ + attr :class, :string, default: nil + + slot :inner_block, required: true + slot :subtitle + slot :actions + + def header(assigns) do + ~H""" +
+
+

+ <%= render_slot(@inner_block) %> +

+

+ <%= render_slot(@subtitle) %> +

+
+
<%= render_slot(@actions) %>
+
+ """ + end + + @doc """ + Renders a data list. + + ## Examples + + <.list> + <:item title="Title"><%= @post.title %> + <:item title="Views"><%= @post.views %> + + """ + slot :item, required: true do + attr :title, :string, required: true + end + + def list(assigns) do + ~H""" +
+
+
+
<%= item.title %>
+
<%= render_slot(item) %>
+
+
+
+ """ + end + + @doc """ + Renders a back navigation link. + + ## Examples + + <.back navigate={~p"/posts"}>Back to posts + """ + attr :navigate, :any, required: true + slot :inner_block, required: true + + def back(assigns) do + ~H""" +
+ <.link + navigate={@navigate} + class="text-sm font-semibold leading-6 text-zinc-900 hover:text-zinc-700" + > + <.icon name="hero-arrow-left-solid" class="h-3 w-3" /> + <%= render_slot(@inner_block) %> + +
+ """ + end + + @doc """ + Renders a [Heroicon](https://heroicons.com). + + Heroicons come in three styles – outline, solid, and mini. + By default, the outline style is used, but solid and mini may + be applied by using the `-solid` and `-mini` suffix. + + You can customize the size and colors of the icons by setting + width, height, and background color classes. + + Icons are extracted from the `deps/heroicons` directory and bundled within + your compiled app.css by the plugin in your `assets/tailwind.config.js`. + + ## Examples + + <.icon name="hero-x-mark-solid" /> + <.icon name="hero-arrow-path" class="ml-1 w-3 h-3 animate-spin" /> + """ + attr :name, :string, required: true + attr :class, :string, default: nil + + def icon(%{name: "hero-" <> _} = assigns) do + ~H""" + + """ + end + + ## JS Commands + + def show(js \\ %JS{}, selector) do + JS.show(js, + to: selector, + time: 300, + transition: + {"transition-all transform ease-out duration-300", + "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95", + "opacity-100 translate-y-0 sm:scale-100"} + ) + end + + def hide(js \\ %JS{}, selector) do + JS.hide(js, + to: selector, + time: 200, + transition: + {"transition-all transform ease-in duration-200", + "opacity-100 translate-y-0 sm:scale-100", + "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"} + ) + end + + def show_modal(js \\ %JS{}, id) when is_binary(id) do + js + |> JS.show(to: "##{id}") + |> JS.show( + to: "##{id}-bg", + time: 300, + transition: {"transition-all transform ease-out duration-300", "opacity-0", "opacity-100"} + ) + |> show("##{id}-container") + |> JS.add_class("overflow-hidden", to: "body") + |> JS.focus_first(to: "##{id}-content") + end + + def hide_modal(js \\ %JS{}, id) do + js + |> JS.hide( + to: "##{id}-bg", + transition: {"transition-all transform ease-in duration-200", "opacity-100", "opacity-0"} + ) + |> hide("##{id}-container") + |> JS.hide(to: "##{id}", transition: {"block", "block", "hidden"}) + |> JS.remove_class("overflow-hidden", to: "body") + |> JS.pop_focus() + end + + @doc """ + Translates an error message using gettext. + """ + def translate_error({msg, opts}) do + # When using gettext, we typically pass the strings we want + # to translate as a static argument: + # + # # Translate the number of files with plural rules + # dngettext("errors", "1 file", "%{count} files", count) + # + # However the error messages in our forms and APIs are generated + # dynamically, so we need to translate them by calling Gettext + # with our gettext backend as first argument. Translations are + # available in the errors.po file (as we use the "errors" domain). + if count = opts[:count] do + Gettext.dngettext(Electric.PhoenixExampleWeb.Gettext, "errors", msg, msg, count, opts) + else + Gettext.dgettext(Electric.PhoenixExampleWeb.Gettext, "errors", msg, opts) + end + end + + @doc """ + Translates the errors for a field from a keyword list of errors. + """ + def translate_errors(errors, field) when is_list(errors) do + for {^field, {msg, opts}} <- errors, do: translate_error({msg, opts}) + end + + attr :todo, :map, required: true + + def todo_description(%{todo: todo} = assigns) do + classes = + if todo.completed do + ~w[font-normal text-slate-400 line-through] + else + [] + end + + assigns = assign(assigns, :classes, classes) + + ~H""" +
+ + <%= @todo.text %> + +
+ """ + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts.ex new file mode 100644 index 0000000000..f5691dfa01 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts.ex @@ -0,0 +1,14 @@ +defmodule Electric.PhoenixExampleWeb.Layouts do + @moduledoc """ + This module holds different layouts used by your application. + + See the `layouts` directory for all templates available. + The "root" layout is a skeleton rendered as part of the + application router. The "app" layout is set as the default + layout on both `use Electric.PhoenixExampleWeb, :controller` and + `use Electric.PhoenixExampleWeb, :live_view`. + """ + use Electric.PhoenixExampleWeb, :html + + embed_templates "layouts/*" +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts/app.html.heex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts/app.html.heex new file mode 100644 index 0000000000..4c306ae146 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts/app.html.heex @@ -0,0 +1,58 @@ +
+
+
+ + + +

+ v<%= Application.spec(:phoenix, :vsn) %> +

+
+ +
+
+
+ + ElectricSQL logo + +
+
+

+ A todo-list powered by Electric.Phoenix. +

+

+ All connected clients will see the same updates, powered by + Electric’s + PostgreSQL replication stream + sending events straight from the database to + the browser via Phoenix + LiveView’s Streams. +

+
+
+
+
+
+ <.flash_group flash={@flash} /> + <%= @inner_content %> +
+
diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts/root.html.heex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts/root.html.heex new file mode 100644 index 0000000000..cb0f243c45 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/components/layouts/root.html.heex @@ -0,0 +1,17 @@ + + + + + + + <.live_title suffix=" · Electric.Phoenix"> + <%= assigns[:page_title] || "TODOs" %> + + + + + + <%= @inner_content %> + + diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/error_html.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/error_html.ex new file mode 100644 index 0000000000..a6795ca198 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/error_html.ex @@ -0,0 +1,24 @@ +defmodule Electric.PhoenixExampleWeb.ErrorHTML do + @moduledoc """ + This module is invoked by your endpoint in case of errors on HTML requests. + + See config/config.exs. + """ + use Electric.PhoenixExampleWeb, :html + + # If you want to customize your error pages, + # uncomment the embed_templates/1 call below + # and add pages to the error directory: + # + # * lib/electric_phoenix_web/controllers/error_html/404.html.heex + # * lib/electric_phoenix_web/controllers/error_html/500.html.heex + # + # embed_templates "error_html/*" + + # The default is to render a plain text page based on + # the template name. For example, "404.html" becomes + # "Not Found". + def render(template, _assigns) do + Phoenix.Controller.status_message_from_template(template) + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/error_json.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/error_json.ex new file mode 100644 index 0000000000..c6d69b4c51 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/error_json.ex @@ -0,0 +1,21 @@ +defmodule Electric.PhoenixExampleWeb.ErrorJSON do + @moduledoc """ + This module is invoked by your endpoint in case of errors on JSON requests. + + See config/config.exs. + """ + + # If you want to customize a particular status code, + # you may add your own clauses, such as: + # + # def render("500.json", _assigns) do + # %{errors: %{detail: "Internal Server Error"}} + # end + + # By default, Phoenix returns the status message from + # the template name. For example, "404.json" becomes + # "Not Found". + def render(template, _assigns) do + %{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}} + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_controller.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_controller.ex new file mode 100644 index 0000000000..17ba1d8843 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_controller.ex @@ -0,0 +1,9 @@ +defmodule Electric.PhoenixExampleWeb.PageController do + use Electric.PhoenixExampleWeb, :controller + + def home(conn, _params) do + # The home page is often custom made, + # so skip the default app layout. + render(conn, :home, layout: false) + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_html.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_html.ex new file mode 100644 index 0000000000..12fc8e70dd --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_html.ex @@ -0,0 +1,10 @@ +defmodule Electric.PhoenixExampleWeb.PageHTML do + @moduledoc """ + This module contains pages rendered by PageController. + + See the `page_html` directory for all templates available. + """ + use Electric.PhoenixExampleWeb, :html + + embed_templates "page_html/*" +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_html/home.html.heex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_html/home.html.heex new file mode 100644 index 0000000000..dc1820b11e --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/controllers/page_html/home.html.heex @@ -0,0 +1,222 @@ +<.flash_group flash={@flash} /> + +
+
+ +

+ Phoenix Framework + + v<%= Application.spec(:phoenix, :vsn) %> + +

+

+ Peace of mind from prototype to production. +

+

+ Build rich, interactive web applications quickly, with less code and fewer moving parts. Join our growing community of developers using Phoenix to craft APIs, HTML5 apps and more, for fun or at scale. +

+ +
+
diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/endpoint.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/endpoint.ex new file mode 100644 index 0000000000..feccf890b1 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/endpoint.ex @@ -0,0 +1,49 @@ +defmodule Electric.PhoenixExampleWeb.Endpoint do + use Phoenix.Endpoint, otp_app: :electric_phoenix_example + + # The session will be stored in the cookie and signed, + # this means its contents can be read but not tampered with. + # Set :encryption_salt if you would also like to encrypt it. + @session_options [ + store: :cookie, + key: "_electric_phoenix_example_key", + signing_salt: "csb9wsGy", + same_site: "Lax" + ] + + socket "/live", Phoenix.LiveView.Socket, + websocket: [connect_info: [session: @session_options]], + longpoll: [connect_info: [session: @session_options]] + + # Serve at "/" the static files from "priv/static" directory. + # + # You should set gzip to true if you are running phx.digest + # when deploying your static files in production. + plug Plug.Static, + at: "/", + from: :electric_phoenix_example, + gzip: false, + only: Electric.PhoenixExampleWeb.static_paths() + + # Code reloading can be explicitly enabled under the + # :code_reloader configuration of your endpoint. + if code_reloading? do + socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket + plug Phoenix.LiveReloader + plug Phoenix.CodeReloader + plug Phoenix.Ecto.CheckRepoStatus, otp_app: :electric_phoenix_example + end + + plug Plug.RequestId + plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] + + plug Plug.Parsers, + parsers: [:urlencoded, :multipart, :json], + pass: ["*/*"], + json_decoder: Phoenix.json_library() + + plug Plug.MethodOverride + plug Plug.Head + plug Plug.Session, @session_options + plug Electric.PhoenixExampleWeb.Router +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/gettext.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/gettext.ex new file mode 100644 index 0000000000..718ee269f0 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/gettext.ex @@ -0,0 +1,24 @@ +defmodule Electric.PhoenixExampleWeb.Gettext do + @moduledoc """ + A module providing Internationalization with a gettext-based API. + + By using [Gettext](https://hexdocs.pm/gettext), + your module gains a set of macros for translations, for example: + + import Electric.PhoenixExampleWeb.Gettext + + # Simple translation + gettext("Here is the string to translate") + + # Plural translation + ngettext("Here is the string to translate", + "Here are the strings to translate", + 3) + + # Domain-based translation + dgettext("errors", "Here is the error message to translate") + + See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. + """ + use Gettext.Backend, otp_app: :electric_phoenix_example +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/form_component.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/form_component.ex new file mode 100644 index 0000000000..662a066fab --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/form_component.ex @@ -0,0 +1,78 @@ +defmodule Electric.PhoenixExampleWeb.TodoLive.FormComponent do + use Electric.PhoenixExampleWeb, :live_component + + alias Electric.PhoenixExample.Todos + alias Electric.PhoenixExample.Todos.Todo + + @impl true + def render(assigns) do + ~H""" +
+ <.form for={@form} id="todo-form" phx-target={@myself} phx-change="validate" phx-submit="save"> +
+
+ <.input + field={@form[:text]} + type="text" + class="inline-flex grow placeholder-slate-300" + placeholder="Thing to do..." + /> + <.button phx-disable-with="Saving..." class="flex-none bg-violet-500 text-white"> + Add Todo + +
+
+ +
+ """ + end + + @impl true + def update(%{todo: todo} = assigns, socket) do + {:ok, + socket + |> assign(assigns) + |> assign_new(:form, fn -> + to_form(Todos.change_todo(todo)) + end)} + end + + @impl true + def handle_event("validate", %{"todo" => todo_params}, socket) do + changeset = Todos.change_todo(socket.assigns.todo, todo_params) + {:noreply, assign(socket, form: to_form(changeset, action: :validate))} + end + + def handle_event("save", %{"todo" => todo_params}, socket) do + save_todo(socket, socket.assigns.action, todo_params) + end + + defp save_todo(socket, :edit, todo_params) do + case Todos.update_todo(socket.assigns.todo, todo_params) do + {:ok, _todo} -> + {:noreply, + socket + |> put_flash(:info, "Todo updated successfully") + |> push_patch(to: socket.assigns.patch)} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, form: to_form(changeset))} + end + end + + defp save_todo(socket, :new, todo_params) do + case Todos.create_todo(todo_params) do + {:ok, _todo} -> + new_todo = %Todo{} + + {:noreply, + socket + |> put_flash(:info, "Todo created successfully") + |> assign(:todo, new_todo) + |> assign(:form, to_form(Todos.change_todo(new_todo)))} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, form: to_form(changeset))} + end + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/index.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/index.ex new file mode 100644 index 0000000000..1c1b0da807 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/index.ex @@ -0,0 +1,63 @@ +defmodule Electric.PhoenixExampleWeb.TodoLive.Index do + use Electric.PhoenixExampleWeb, :live_view + + alias Electric.PhoenixExample.Todos + alias Electric.PhoenixExample.Todos.Todo + + @impl true + def mount(_params, _session, socket) do + {:ok, + socket + |> assign(:electric_live, false) + |> assign(:animate_insert, false) + |> Electric.Phoenix.LiveView.electric_stream(:todos, Todos.Todo)} + end + + @impl true + def handle_params(_params, _url, socket) do + {:noreply, assign(socket, :todo, %Todo{})} + end + + @impl true + # Progress events from the electric client. + # - `:loaded` is sent when the initial fetch has completed + # - `:live` is sent when the client is in `live` mode and waiting for the + # latest updates from the server + def handle_info({:electric, {:todos, :loaded}}, socket) do + {:noreply, socket} + end + + # here we use the `:live` state to turn on animations for new Todos + def handle_info({:electric, {:todos, :live}}, socket) do + {:noreply, socket |> assign(:electric_live, true) |> assign(:animate_insert, true)} + end + + # Forward all events from the Electric sync stream to the component. + # This is **required** for the integration. + def handle_info({:electric, event}, socket) do + {:noreply, Electric.Phoenix.LiveView.electric_stream_update(socket, event, at: 0)} + end + + @impl true + def handle_event("delete", %{"id" => id}, socket) do + {:ok, _todo} = + id + |> Todos.get_todo!() + |> Todos.delete_todo() + + # Deleting is enough -- Electric will stream the update directly from the + # database into the views + {:noreply, socket} + end + + def handle_event("toggle-completed", %{"id" => id}, socket) do + {:ok, _todo} = + id + |> Todos.get_todo!() + |> Todos.toggle_complete() + + # Updating is enough -- Electric will stream the update directly from the + # database into the views + {:noreply, socket} + end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/index.html.heex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/index.html.heex new file mode 100644 index 0000000000..594578f4e7 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/live/todo_live/index.html.heex @@ -0,0 +1,98 @@ +<.live_component + module={Electric.PhoenixExampleWeb.TodoLive.FormComponent} + id={@todo.id || :new} + action={:new} + todo={@todo} +/> + +
+
+
+ + + + + + + Loading… +
+
+
+
+
+
+
+
+ <.input + checked={todo.completed} + value="1" + name={"todo_completed_#{todo.id}"} + type="checkbox" + phx-click={JS.push("toggle-completed", value: %{id: todo.id})} + class=" hover:cursor-pointer" + /> +
+
+ + <%= todo.id |> to_string() |> String.pad_leading(3, " ") %> + +
+
+ <.todo_description todo={todo} /> +
+
+ <.button + phx-click={JS.push("delete", value: %{id: todo.id})} + data-confirm="Delete Todo?" + class="bg-transparent text-zinc-400 hover:text-white hover:bg-violet-400" + > + + + + + + +
+
+
+
+
+
+
diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/router.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/router.ex new file mode 100644 index 0000000000..b1905f6aea --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/router.ex @@ -0,0 +1,27 @@ +defmodule Electric.PhoenixExampleWeb.Router do + use Electric.PhoenixExampleWeb, :router + + pipeline :browser do + plug :accepts, ["html"] + plug :fetch_session + plug :fetch_live_flash + plug :put_root_layout, html: {Electric.PhoenixExampleWeb.Layouts, :root} + plug :protect_from_forgery + plug :put_secure_browser_headers + end + + pipeline :api do + plug :accepts, ["json"] + end + + scope "/", Electric.PhoenixExampleWeb do + pipe_through :browser + + live "/", TodoLive.Index, :index + end + + # Other scopes may use custom stacks. + # scope "/api", Electric.PhoenixExampleWeb do + # pipe_through :api + # end +end diff --git a/examples/phoenix-liveview/lib/electric_phoenix_example_web/telemetry.ex b/examples/phoenix-liveview/lib/electric_phoenix_example_web/telemetry.ex new file mode 100644 index 0000000000..bf68553b60 --- /dev/null +++ b/examples/phoenix-liveview/lib/electric_phoenix_example_web/telemetry.ex @@ -0,0 +1,92 @@ +defmodule Electric.PhoenixExampleWeb.Telemetry do + use Supervisor + import Telemetry.Metrics + + def start_link(arg) do + Supervisor.start_link(__MODULE__, arg, name: __MODULE__) + end + + @impl true + def init(_arg) do + children = [ + # Telemetry poller will execute the given period measurements + # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics + {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} + # Add reporters as children of your supervision tree. + # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} + ] + + Supervisor.init(children, strategy: :one_for_one) + end + + def metrics do + [ + # Phoenix Metrics + summary("phoenix.endpoint.start.system_time", + unit: {:native, :millisecond} + ), + summary("phoenix.endpoint.stop.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.router_dispatch.start.system_time", + tags: [:route], + unit: {:native, :millisecond} + ), + summary("phoenix.router_dispatch.exception.duration", + tags: [:route], + unit: {:native, :millisecond} + ), + summary("phoenix.router_dispatch.stop.duration", + tags: [:route], + unit: {:native, :millisecond} + ), + summary("phoenix.socket_connected.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.channel_joined.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.channel_handled_in.duration", + tags: [:event], + unit: {:native, :millisecond} + ), + + # Database Metrics + summary("electric_phoenix_example.repo.query.total_time", + unit: {:native, :millisecond}, + description: "The sum of the other measurements" + ), + summary("electric_phoenix_example.repo.query.decode_time", + unit: {:native, :millisecond}, + description: "The time spent decoding the data received from the database" + ), + summary("electric_phoenix_example.repo.query.query_time", + unit: {:native, :millisecond}, + description: "The time spent executing the query" + ), + summary("electric_phoenix_example.repo.query.queue_time", + unit: {:native, :millisecond}, + description: "The time spent waiting for a database connection" + ), + summary("electric_phoenix_example.repo.query.idle_time", + unit: {:native, :millisecond}, + description: + "The time the connection spent waiting before being checked out for the query" + ), + + # VM Metrics + summary("vm.memory.total", unit: {:byte, :kilobyte}), + summary("vm.total_run_queue_lengths.total"), + summary("vm.total_run_queue_lengths.cpu"), + summary("vm.total_run_queue_lengths.io") + ] + end + + defp periodic_measurements do + [ + # A module, function and arguments to be invoked periodically. + # This function must call :telemetry.execute/3 and a metric must be added above. + # {Electric.PhoenixExampleWeb, :count_users, []} + ] + end +end diff --git a/examples/phoenix-liveview/mix.exs b/examples/phoenix-liveview/mix.exs new file mode 100644 index 0000000000..e484bcd341 --- /dev/null +++ b/examples/phoenix-liveview/mix.exs @@ -0,0 +1,87 @@ +defmodule Electric.PhoenixExample.MixProject do + use Mix.Project + + def project do + [ + app: :electric_phoenix_example, + version: "0.1.0", + elixir: "~> 1.14", + elixirc_paths: elixirc_paths(Mix.env()), + start_permanent: Mix.env() == :prod, + aliases: aliases(), + deps: deps() + ] + end + + # Configuration for the OTP application. + # + # Type `mix help compile.app` for more information. + def application do + [ + mod: {Electric.PhoenixExample.Application, []}, + extra_applications: [:logger, :runtime_tools] + ] + end + + # Specifies which paths to compile per environment. + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + # Specifies your project dependencies. + # + # Type `mix help deps` for examples and options. + defp deps do + [ + {:phoenix, "~> 1.7.14"}, + {:phoenix_ecto, "~> 4.5"}, + {:ecto_sql, "~> 3.10"}, + {:postgrex, ">= 0.0.0"}, + {:phoenix_html, "~> 4.1"}, + {:phoenix_live_reload, "~> 1.2", only: :dev}, + # TODO bump on release to {:phoenix_live_view, "~> 1.0.0"}, + {:phoenix_live_view, "~> 1.0.0-rc.1", override: true}, + {:floki, ">= 0.30.0", only: :test}, + {:esbuild, "~> 0.8", runtime: Mix.env() == :dev}, + {:tailwind, "~> 0.2", runtime: Mix.env() == :dev}, + {:heroicons, + github: "tailwindlabs/heroicons", + tag: "v2.1.1", + sparse: "optimized", + app: false, + compile: false, + depth: 1}, + {:telemetry_metrics, "~> 1.0"}, + {:telemetry_poller, "~> 1.0"}, + {:gettext, "~> 0.20"}, + {:jason, "~> 1.2"}, + {:dns_cluster, "~> 0.1.1"}, + {:bandit, "~> 1.5"}, + {:electric_phoenix, ">= 0.2.0-rc-1"} + ] + end + + # Aliases are shortcuts or tasks specific to the current project. + # For example, to install project dependencies and perform other setup tasks, run: + # + # $ mix setup + # + # See the documentation for `Mix` for more info on aliases. + defp aliases do + [ + setup: ["deps.get", "ecto.setup", "assets.setup", "assets.build"], + "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], + "ecto.reset": ["ecto.drop", "ecto.setup"], + test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"], + "assets.setup": ["tailwind.install --if-missing", "esbuild.install --if-missing"], + "assets.build": ["tailwind electric_phoenix_example", "esbuild electric_phoenix_example"], + "assets.deploy": [ + "tailwind electric_phoenix_example --minify", + "esbuild electric_phoenix_example --minify", + "phx.digest" + ], + "electric.start": [ + "cmd docker compose -f ../../.support/docker-compose.yml up -d" + ] + ] + end +end diff --git a/examples/phoenix-liveview/mix.lock b/examples/phoenix-liveview/mix.lock new file mode 100644 index 0000000000..a7749c1ca2 --- /dev/null +++ b/examples/phoenix-liveview/mix.lock @@ -0,0 +1,42 @@ +%{ + "bandit": {:hex, :bandit, "1.6.0", "9cb6c67c27cecab2d0c93968cb957fa8decccb7275193c8bf33f97397b3ac25d", [:mix], [{:hpax, "~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.0", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "fd2491e564a7c5e11ff8496ebf530c342c742452c59de17ac0fb1f814a0ab01a"}, + "castore": {:hex, :castore, "1.0.10", "43bbeeac820f16c89f79721af1b3e092399b3a1ecc8df1a472738fd853574911", [:mix], [], "hexpm", "1b0b7ea14d889d9ea21202c43a4fa015eb913021cb535e8ed91946f4b77a8848"}, + "db_connection": {:hex, :db_connection, "2.7.0", "b99faa9291bb09892c7da373bb82cba59aefa9b36300f6145c5f201c7adf48ec", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "dcf08f31b2701f857dfc787fbad78223d61a32204f217f15e881dd93e4bdd3ff"}, + "decimal": {:hex, :decimal, "2.2.0", "df3d06bb9517e302b1bd265c1e7f16cda51547ad9d99892049340841f3e15836", [:mix], [], "hexpm", "af8daf87384b51b7e611fb1a1f2c4d4876b65ef968fa8bd3adf44cff401c7f21"}, + "dns_cluster": {:hex, :dns_cluster, "0.1.3", "0bc20a2c88ed6cc494f2964075c359f8c2d00e1bf25518a6a6c7fd277c9b0c66", [:mix], [], "hexpm", "46cb7c4a1b3e52c7ad4cbe33ca5079fbde4840dedeafca2baf77996c2da1bc33"}, + "ecto": {:hex, :ecto, "3.12.4", "267c94d9f2969e6acc4dd5e3e3af5b05cdae89a4d549925f3008b2b7eb0b93c3", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "ef04e4101688a67d061e1b10d7bc1fbf00d1d13c17eef08b71d070ff9188f747"}, + "ecto_sql": {:hex, :ecto_sql, "3.12.1", "c0d0d60e85d9ff4631f12bafa454bc392ce8b9ec83531a412c12a0d415a3a4d0", [:mix], [{:db_connection, "~> 2.4.1 or ~> 2.5", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.12", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.7", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.19 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "aff5b958a899762c5f09028c847569f7dfb9cc9d63bdb8133bff8a5546de6bf5"}, + "electric_client": {:hex, :electric_client, "0.2.1-rc-2", "3087196645d7cb0e2f7c7b77d84828c363f9069eb1340de5ac8181dc137aaa3f", [:mix], [{:ecto_sql, "~> 3.12", [hex: :ecto_sql, repo: "hexpm", optional: true]}, {:gen_stage, "~> 1.2", [hex: :gen_stage, repo: "hexpm", optional: true]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:nimble_options, "~> 1.1", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}], "hexpm", "a9dbb5e2ddb6e82e99109f226524e30980f443c6a23295ebb08ae7f675525409"}, + "electric_phoenix": {:hex, :electric_phoenix, "0.2.0-rc-1", "c7f8f7b0db274f22b3189634e1b4e443d4cb1482527ec691ee6a0516f1eefbc2", [:mix], [{:ecto_sql, "~> 3.10", [hex: :ecto_sql, repo: "hexpm", optional: true]}, {:electric_client, "> 0.2.0", [hex: :electric_client, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:nimble_options, "~> 1.1", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 0.20", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "1fca7706043a9559520c44b43b7b81f62748d7513a2a1c7664b65a81919d24fd"}, + "esbuild": {:hex, :esbuild, "0.8.1", "0cbf919f0eccb136d2eeef0df49c4acf55336de864e63594adcea3814f3edf41", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "25fc876a67c13cb0a776e7b5d7974851556baeda2085296c14ab48555ea7560f"}, + "expo": {:hex, :expo, "1.1.0", "f7b9ed7fb5745ebe1eeedf3d6f29226c5dd52897ac67c0f8af62a07e661e5c75", [:mix], [], "hexpm", "fbadf93f4700fb44c331362177bdca9eeb8097e8b0ef525c9cc501cb9917c960"}, + "file_system": {:hex, :file_system, "1.0.1", "79e8ceaddb0416f8b8cd02a0127bdbababe7bf4a23d2a395b983c1f8b3f73edd", [:mix], [], "hexpm", "4414d1f38863ddf9120720cd976fce5bdde8e91d8283353f0e31850fa89feb9e"}, + "finch": {:hex, :finch, "0.19.0", "c644641491ea854fc5c1bbaef36bfc764e3f08e7185e1f084e35e0672241b76d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.6.2 or ~> 1.7", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "fc5324ce209125d1e2fa0fcd2634601c52a787aff1cd33ee833664a5af4ea2b6"}, + "floki": {:hex, :floki, "0.36.3", "1102f93b16a55bc5383b85ae3ec470f82dee056eaeff9195e8afdf0ef2a43c30", [:mix], [], "hexpm", "fe0158bff509e407735f6d40b3ee0d7deb47f3f3ee7c6c182ad28599f9f6b27a"}, + "gettext": {:hex, :gettext, "0.26.1", "38e14ea5dcf962d1fc9f361b63ea07c0ce715a8ef1f9e82d3dfb8e67e0416715", [:mix], [{:expo, "~> 0.5.1 or ~> 1.0", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "01ce56f188b9dc28780a52783d6529ad2bc7124f9744e571e1ee4ea88bf08734"}, + "heroicons": {:git, "https://github.com/tailwindlabs/heroicons.git", "88ab3a0d790e6a47404cba02800a6b25d2afae50", [tag: "v2.1.1", sparse: "optimized", depth: 1]}, + "hpax": {:hex, :hpax, "1.0.0", "28dcf54509fe2152a3d040e4e3df5b265dcb6cb532029ecbacf4ce52caea3fd2", [:mix], [], "hexpm", "7f1314731d711e2ca5fdc7fd361296593fc2542570b3105595bb0bc6d0fad601"}, + "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, + "mime": {:hex, :mime, "2.0.6", "8f18486773d9b15f95f4f4f1e39b710045fa1de891fada4516559967276e4dc2", [:mix], [], "hexpm", "c9945363a6b26d747389aac3643f8e0e09d30499a138ad64fe8fd1d13d9b153e"}, + "mint": {:hex, :mint, "1.6.2", "af6d97a4051eee4f05b5500671d47c3a67dac7386045d87a904126fd4bbcea2e", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "5ee441dffc1892f1ae59127f74afe8fd82fda6587794278d924e4d90ea3d63f9"}, + "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"}, + "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"}, + "phoenix": {:hex, :phoenix, "1.7.14", "a7d0b3f1bc95987044ddada111e77bd7f75646a08518942c72a8440278ae7825", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.1", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.7", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:websock_adapter, "~> 0.5.3", [hex: :websock_adapter, repo: "hexpm", optional: false]}], "hexpm", "c7859bc56cc5dfef19ecfc240775dae358cbaa530231118a9e014df392ace61a"}, + "phoenix_ecto": {:hex, :phoenix_ecto, "4.6.2", "3b83b24ab5a2eb071a20372f740d7118767c272db386831b2e77638c4dcc606d", [:mix], [{:ecto, "~> 3.5", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: false]}, {:postgrex, "~> 0.16 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}], "hexpm", "3f94d025f59de86be00f5f8c5dd7b5965a3298458d21ab1c328488be3b5fcd59"}, + "phoenix_html": {:hex, :phoenix_html, "4.1.1", "4c064fd3873d12ebb1388425a8f2a19348cef56e7289e1998e2d2fa758aa982e", [:mix], [], "hexpm", "f2f2df5a72bc9a2f510b21497fd7d2b86d932ec0598f0210fed4114adc546c6f"}, + "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.5.3", "f2161c207fda0e4fb55165f650f7f8db23f02b29e3bff00ff7ef161d6ac1f09d", [:mix], [{:file_system, "~> 0.3 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "b4ec9cd73cb01ff1bd1cac92e045d13e7030330b74164297d1aee3907b54803c"}, + "phoenix_live_view": {:hex, :phoenix_live_view, "1.0.0-rc.7", "d2abca526422adea88896769529addb6443390b1d4f1ff9cbe694312d8875fb2", [:mix], [{:floki, "~> 0.36", [hex: :floki, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.6.15 or ~> 1.7.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.3 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.15", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "b82a4575f6f3eb5b97922ec6874b0c52b3ca0cc5dcb4b14ddc478cbfa135dd01"}, + "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.1.3", "3168d78ba41835aecad272d5e8cd51aa87a7ac9eb836eabc42f6e57538e3731d", [:mix], [], "hexpm", "bba06bc1dcfd8cb086759f0edc94a8ba2bc8896d5331a1e2c2902bf8e36ee502"}, + "phoenix_template": {:hex, :phoenix_template, "1.0.4", "e2092c132f3b5e5b2d49c96695342eb36d0ed514c5b252a77048d5969330d639", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "2c0c81f0e5c6753faf5cca2f229c9709919aba34fab866d3bc05060c9c444206"}, + "plug": {:hex, :plug, "1.16.1", "40c74619c12f82736d2214557dedec2e9762029b2438d6d175c5074c933edc9d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "a13ff6b9006b03d7e33874945b2755253841b238c34071ed85b0e86057f8cddc"}, + "plug_crypto": {:hex, :plug_crypto, "2.1.0", "f44309c2b06d249c27c8d3f65cfe08158ade08418cf540fd4f72d4d6863abb7b", [:mix], [], "hexpm", "131216a4b030b8f8ce0f26038bc4421ae60e4bb95c5cf5395e1421437824c4fa"}, + "postgrex": {:hex, :postgrex, "0.19.3", "a0bda6e3bc75ec07fca5b0a89bffd242ca209a4822a9533e7d3e84ee80707e19", [:mix], [{:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "d31c28053655b78f47f948c85bb1cf86a9c1f8ead346ba1aa0d0df017fa05b61"}, + "req": {:hex, :req, "0.5.7", "b722680e03d531a2947282adff474362a48a02aa54b131196fbf7acaff5e4cee", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.17", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "c6035374615120a8923e8089d0c21a3496cf9eda2d287b806081b8f323ceee29"}, + "tailwind": {:hex, :tailwind, "0.2.3", "277f08145d407de49650d0a4685dc062174bdd1ae7731c5f1da86163a24dfcdb", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}], "hexpm", "8e45e7a34a676a7747d04f7913a96c770c85e6be810a1d7f91e713d3a3655b5d"}, + "telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"}, + "telemetry_metrics": {:hex, :telemetry_metrics, "1.0.0", "29f5f84991ca98b8eb02fc208b2e6de7c95f8bb2294ef244a176675adc7775df", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f23713b3847286a534e005126d4c959ebcca68ae9582118ce436b521d1d47d5d"}, + "telemetry_poller": {:hex, :telemetry_poller, "1.1.0", "58fa7c216257291caaf8d05678c8d01bd45f4bdbc1286838a28c4bb62ef32999", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "9eb9d9cbfd81cbd7cdd24682f8711b6e2b691289a0de6826e58452f28c103c8f"}, + "thousand_island": {:hex, :thousand_island, "1.3.6", "835a626a8a6f6a1e681b63e1132a8427e87ce443aaf4888fbf63b2df77539b97", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "0ed8798084c8c49a223840b20598b022e4eb8c9f390fb6701864c307fc9aa2cd"}, + "websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"}, + "websock_adapter": {:hex, :websock_adapter, "0.5.8", "3b97dc94e407e2d1fc666b2fb9acf6be81a1798a2602294aac000260a7c4a47d", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "315b9a1865552212b5f35140ad194e67ce31af45bcee443d4ecb96b5fd3f3782"}, +} diff --git a/examples/phoenix-liveview/priv/gettext/en/LC_MESSAGES/errors.po b/examples/phoenix-liveview/priv/gettext/en/LC_MESSAGES/errors.po new file mode 100644 index 0000000000..844c4f5cea --- /dev/null +++ b/examples/phoenix-liveview/priv/gettext/en/LC_MESSAGES/errors.po @@ -0,0 +1,112 @@ +## `msgid`s in this file come from POT (.pot) files. +## +## Do not add, change, or remove `msgid`s manually here as +## they're tied to the ones in the corresponding POT file +## (with the same domain). +## +## Use `mix gettext.extract --merge` or `mix gettext.merge` +## to merge POT files into PO files. +msgid "" +msgstr "" +"Language: en\n" + +## From Ecto.Changeset.cast/4 +msgid "can't be blank" +msgstr "" + +## From Ecto.Changeset.unique_constraint/3 +msgid "has already been taken" +msgstr "" + +## From Ecto.Changeset.put_change/3 +msgid "is invalid" +msgstr "" + +## From Ecto.Changeset.validate_acceptance/3 +msgid "must be accepted" +msgstr "" + +## From Ecto.Changeset.validate_format/3 +msgid "has invalid format" +msgstr "" + +## From Ecto.Changeset.validate_subset/3 +msgid "has an invalid entry" +msgstr "" + +## From Ecto.Changeset.validate_exclusion/3 +msgid "is reserved" +msgstr "" + +## From Ecto.Changeset.validate_confirmation/3 +msgid "does not match confirmation" +msgstr "" + +## From Ecto.Changeset.no_assoc_constraint/3 +msgid "is still associated with this entry" +msgstr "" + +msgid "are still associated with this entry" +msgstr "" + +## From Ecto.Changeset.validate_length/3 +msgid "should have %{count} item(s)" +msgid_plural "should have %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be %{count} character(s)" +msgid_plural "should be %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be %{count} byte(s)" +msgid_plural "should be %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at least %{count} item(s)" +msgid_plural "should have at least %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at least %{count} character(s)" +msgid_plural "should be at least %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at least %{count} byte(s)" +msgid_plural "should be at least %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at most %{count} item(s)" +msgid_plural "should have at most %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at most %{count} character(s)" +msgid_plural "should be at most %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at most %{count} byte(s)" +msgid_plural "should be at most %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +## From Ecto.Changeset.validate_number/3 +msgid "must be less than %{number}" +msgstr "" + +msgid "must be greater than %{number}" +msgstr "" + +msgid "must be less than or equal to %{number}" +msgstr "" + +msgid "must be greater than or equal to %{number}" +msgstr "" + +msgid "must be equal to %{number}" +msgstr "" diff --git a/examples/phoenix-liveview/priv/gettext/errors.pot b/examples/phoenix-liveview/priv/gettext/errors.pot new file mode 100644 index 0000000000..eef2de2ba4 --- /dev/null +++ b/examples/phoenix-liveview/priv/gettext/errors.pot @@ -0,0 +1,109 @@ +## This is a PO Template file. +## +## `msgid`s here are often extracted from source code. +## Add new translations manually only if they're dynamic +## translations that can't be statically extracted. +## +## Run `mix gettext.extract` to bring this file up to +## date. Leave `msgstr`s empty as changing them here has no +## effect: edit them in PO (`.po`) files instead. +## From Ecto.Changeset.cast/4 +msgid "can't be blank" +msgstr "" + +## From Ecto.Changeset.unique_constraint/3 +msgid "has already been taken" +msgstr "" + +## From Ecto.Changeset.put_change/3 +msgid "is invalid" +msgstr "" + +## From Ecto.Changeset.validate_acceptance/3 +msgid "must be accepted" +msgstr "" + +## From Ecto.Changeset.validate_format/3 +msgid "has invalid format" +msgstr "" + +## From Ecto.Changeset.validate_subset/3 +msgid "has an invalid entry" +msgstr "" + +## From Ecto.Changeset.validate_exclusion/3 +msgid "is reserved" +msgstr "" + +## From Ecto.Changeset.validate_confirmation/3 +msgid "does not match confirmation" +msgstr "" + +## From Ecto.Changeset.no_assoc_constraint/3 +msgid "is still associated with this entry" +msgstr "" + +msgid "are still associated with this entry" +msgstr "" + +## From Ecto.Changeset.validate_length/3 +msgid "should have %{count} item(s)" +msgid_plural "should have %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be %{count} character(s)" +msgid_plural "should be %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be %{count} byte(s)" +msgid_plural "should be %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at least %{count} item(s)" +msgid_plural "should have at least %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at least %{count} character(s)" +msgid_plural "should be at least %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at least %{count} byte(s)" +msgid_plural "should be at least %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at most %{count} item(s)" +msgid_plural "should have at most %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at most %{count} character(s)" +msgid_plural "should be at most %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at most %{count} byte(s)" +msgid_plural "should be at most %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +## From Ecto.Changeset.validate_number/3 +msgid "must be less than %{number}" +msgstr "" + +msgid "must be greater than %{number}" +msgstr "" + +msgid "must be less than or equal to %{number}" +msgstr "" + +msgid "must be greater than or equal to %{number}" +msgstr "" + +msgid "must be equal to %{number}" +msgstr "" diff --git a/examples/phoenix-liveview/priv/repo/migrations/.formatter.exs b/examples/phoenix-liveview/priv/repo/migrations/.formatter.exs new file mode 100644 index 0000000000..49f9151ed2 --- /dev/null +++ b/examples/phoenix-liveview/priv/repo/migrations/.formatter.exs @@ -0,0 +1,4 @@ +[ + import_deps: [:ecto_sql], + inputs: ["*.exs"] +] diff --git a/examples/phoenix-liveview/priv/repo/migrations/20241008155013_create_todos.exs b/examples/phoenix-liveview/priv/repo/migrations/20241008155013_create_todos.exs new file mode 100644 index 0000000000..ec44a88916 --- /dev/null +++ b/examples/phoenix-liveview/priv/repo/migrations/20241008155013_create_todos.exs @@ -0,0 +1,12 @@ +defmodule Electric.PhoenixExample.Repo.Migrations.CreateTodos do + use Ecto.Migration + + def change do + create table(:todos) do + add :text, :string, null: false + add :completed, :boolean, default: false, null: false + + timestamps(type: :utc_datetime) + end + end +end diff --git a/examples/phoenix-liveview/priv/repo/seeds.exs b/examples/phoenix-liveview/priv/repo/seeds.exs new file mode 100644 index 0000000000..ddb80c7756 --- /dev/null +++ b/examples/phoenix-liveview/priv/repo/seeds.exs @@ -0,0 +1,11 @@ +# Script for populating the database. You can run it as: +# +# mix run priv/repo/seeds.exs +# +# Inside the script, you can read and write to any of your +# repositories directly: +# +# Electric.PhoenixExample.Repo.insert!(%Electric.PhoenixExample.SomeSchema{}) +# +# We recommend using the bang functions (`insert!`, `update!` +# and so on) as they will fail if something goes wrong. diff --git a/examples/phoenix-liveview/priv/static/favicon.ico b/examples/phoenix-liveview/priv/static/favicon.ico new file mode 100644 index 0000000000..7f372bfc21 Binary files /dev/null and b/examples/phoenix-liveview/priv/static/favicon.ico differ diff --git a/examples/phoenix-liveview/priv/static/images/logo.svg b/examples/phoenix-liveview/priv/static/images/logo.svg new file mode 100644 index 0000000000..9f26babac2 --- /dev/null +++ b/examples/phoenix-liveview/priv/static/images/logo.svg @@ -0,0 +1,6 @@ + diff --git a/examples/phoenix-liveview/priv/static/robots.txt b/examples/phoenix-liveview/priv/static/robots.txt new file mode 100644 index 0000000000..26e06b5f19 --- /dev/null +++ b/examples/phoenix-liveview/priv/static/robots.txt @@ -0,0 +1,5 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/examples/phoenix-liveview/test/electric_phoenix_example/todos_test.exs b/examples/phoenix-liveview/test/electric_phoenix_example/todos_test.exs new file mode 100644 index 0000000000..23afb4a356 --- /dev/null +++ b/examples/phoenix-liveview/test/electric_phoenix_example/todos_test.exs @@ -0,0 +1,61 @@ +defmodule Electric.PhoenixExample.TodosTest do + use Electric.PhoenixExample.DataCase + + alias Electric.PhoenixExample.Todos + + describe "todos" do + alias Electric.PhoenixExample.Todos.Todo + + import Electric.PhoenixExample.TodosFixtures + + @invalid_attrs %{text: nil, completed: nil} + + test "list_todos/0 returns all todos" do + todo = todo_fixture() + assert Todos.list_todos() == [todo] + end + + test "get_todo!/1 returns the todo with given id" do + todo = todo_fixture() + assert Todos.get_todo!(todo.id) == todo + end + + test "create_todo/1 with valid data creates a todo" do + valid_attrs = %{text: "some text", completed: true} + + assert {:ok, %Todo{} = todo} = Todos.create_todo(valid_attrs) + assert todo.text == "some text" + assert todo.completed == true + end + + test "create_todo/1 with invalid data returns error changeset" do + assert {:error, %Ecto.Changeset{}} = Todos.create_todo(@invalid_attrs) + end + + test "update_todo/2 with valid data updates the todo" do + todo = todo_fixture() + update_attrs = %{text: "some updated text", completed: false} + + assert {:ok, %Todo{} = todo} = Todos.update_todo(todo, update_attrs) + assert todo.text == "some updated text" + assert todo.completed == false + end + + test "update_todo/2 with invalid data returns error changeset" do + todo = todo_fixture() + assert {:error, %Ecto.Changeset{}} = Todos.update_todo(todo, @invalid_attrs) + assert todo == Todos.get_todo!(todo.id) + end + + test "delete_todo/1 deletes the todo" do + todo = todo_fixture() + assert {:ok, %Todo{}} = Todos.delete_todo(todo) + assert_raise Ecto.NoResultsError, fn -> Todos.get_todo!(todo.id) end + end + + test "change_todo/1 returns a todo changeset" do + todo = todo_fixture() + assert %Ecto.Changeset{} = Todos.change_todo(todo) + end + end +end diff --git a/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/error_html_test.exs b/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/error_html_test.exs new file mode 100644 index 0000000000..79b42519d7 --- /dev/null +++ b/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/error_html_test.exs @@ -0,0 +1,14 @@ +defmodule Electric.PhoenixExampleWeb.ErrorHTMLTest do + use Electric.PhoenixExampleWeb.ConnCase, async: true + + # Bring render_to_string/4 for testing custom views + import Phoenix.Template + + test "renders 404.html" do + assert render_to_string(Electric.PhoenixExampleWeb.ErrorHTML, "404", "html", []) == "Not Found" + end + + test "renders 500.html" do + assert render_to_string(Electric.PhoenixExampleWeb.ErrorHTML, "500", "html", []) == "Internal Server Error" + end +end diff --git a/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/error_json_test.exs b/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/error_json_test.exs new file mode 100644 index 0000000000..ee6cbb9b1b --- /dev/null +++ b/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/error_json_test.exs @@ -0,0 +1,12 @@ +defmodule Electric.PhoenixExampleWeb.ErrorJSONTest do + use Electric.PhoenixExampleWeb.ConnCase, async: true + + test "renders 404" do + assert Electric.PhoenixExampleWeb.ErrorJSON.render("404.json", %{}) == %{errors: %{detail: "Not Found"}} + end + + test "renders 500" do + assert Electric.PhoenixExampleWeb.ErrorJSON.render("500.json", %{}) == + %{errors: %{detail: "Internal Server Error"}} + end +end diff --git a/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/page_controller_test.exs b/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/page_controller_test.exs new file mode 100644 index 0000000000..eddf1fad16 --- /dev/null +++ b/examples/phoenix-liveview/test/electric_phoenix_example_web/controllers/page_controller_test.exs @@ -0,0 +1,8 @@ +defmodule Electric.PhoenixExampleWeb.PageControllerTest do + use Electric.PhoenixExampleWeb.ConnCase + + test "GET /", %{conn: conn} do + conn = get(conn, ~p"/") + assert html_response(conn, 200) =~ "Peace of mind from prototype to production" + end +end diff --git a/examples/phoenix-liveview/test/electric_phoenix_example_web/live/todo_live_test.exs b/examples/phoenix-liveview/test/electric_phoenix_example_web/live/todo_live_test.exs new file mode 100644 index 0000000000..de78c69a0a --- /dev/null +++ b/examples/phoenix-liveview/test/electric_phoenix_example_web/live/todo_live_test.exs @@ -0,0 +1,113 @@ +defmodule Electric.PhoenixExampleWeb.TodoLiveTest do + use Electric.PhoenixExampleWeb.ConnCase + + import Phoenix.LiveViewTest + import Electric.PhoenixExample.TodosFixtures + + @create_attrs %{text: "some text", completed: true} + @update_attrs %{text: "some updated text", completed: false} + @invalid_attrs %{text: nil, completed: false} + + defp create_todo(_) do + todo = todo_fixture() + %{todo: todo} + end + + describe "Index" do + setup [:create_todo] + + test "lists all todos", %{conn: conn, todo: todo} do + {:ok, _index_live, html} = live(conn, ~p"/todos") + + assert html =~ "Listing Todos" + assert html =~ todo.text + end + + test "saves new todo", %{conn: conn} do + {:ok, index_live, _html} = live(conn, ~p"/todos") + + assert index_live |> element("a", "New Todo") |> render_click() =~ + "New Todo" + + assert_patch(index_live, ~p"/todos/new") + + assert index_live + |> form("#todo-form", todo: @invalid_attrs) + |> render_change() =~ "can't be blank" + + assert index_live + |> form("#todo-form", todo: @create_attrs) + |> render_submit() + + assert_patch(index_live, ~p"/todos") + + html = render(index_live) + assert html =~ "Todo created successfully" + assert html =~ "some text" + end + + test "updates todo in listing", %{conn: conn, todo: todo} do + {:ok, index_live, _html} = live(conn, ~p"/todos") + + assert index_live |> element("#todos-#{todo.id} a", "Edit") |> render_click() =~ + "Edit Todo" + + assert_patch(index_live, ~p"/todos/#{todo}/edit") + + assert index_live + |> form("#todo-form", todo: @invalid_attrs) + |> render_change() =~ "can't be blank" + + assert index_live + |> form("#todo-form", todo: @update_attrs) + |> render_submit() + + assert_patch(index_live, ~p"/todos") + + html = render(index_live) + assert html =~ "Todo updated successfully" + assert html =~ "some updated text" + end + + test "deletes todo in listing", %{conn: conn, todo: todo} do + {:ok, index_live, _html} = live(conn, ~p"/todos") + + assert index_live |> element("#todos-#{todo.id} a", "Delete") |> render_click() + refute has_element?(index_live, "#todos-#{todo.id}") + end + end + + describe "Show" do + setup [:create_todo] + + test "displays todo", %{conn: conn, todo: todo} do + {:ok, _show_live, html} = live(conn, ~p"/todos/#{todo}") + + assert html =~ "Show Todo" + assert html =~ todo.text + end + + test "updates todo within modal", %{conn: conn, todo: todo} do + {:ok, show_live, _html} = live(conn, ~p"/todos/#{todo}") + + assert show_live |> element("a", "Edit") |> render_click() =~ + "Edit Todo" + + assert_patch(show_live, ~p"/todos/#{todo}/show/edit") + + assert show_live + |> form("#todo-form", todo: @invalid_attrs) + |> render_change() =~ "can't be blank" + + assert show_live + |> form("#todo-form", todo: @update_attrs) + |> render_submit() + + assert_patch(show_live, ~p"/todos/#{todo}") + + html = render(show_live) + assert html =~ "Todo updated successfully" + assert html =~ "some updated text" + end + end +end diff --git a/examples/phoenix-liveview/test/support/conn_case.ex b/examples/phoenix-liveview/test/support/conn_case.ex new file mode 100644 index 0000000000..f25c315011 --- /dev/null +++ b/examples/phoenix-liveview/test/support/conn_case.ex @@ -0,0 +1,38 @@ +defmodule Electric.PhoenixExampleWeb.ConnCase do + @moduledoc """ + This module defines the test case to be used by + tests that require setting up a connection. + + Such tests rely on `Phoenix.ConnTest` and also + import other functionality to make it easier + to build common data structures and query the data layer. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use Electric.PhoenixExampleWeb.ConnCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + # The default endpoint for testing + @endpoint Electric.PhoenixExampleWeb.Endpoint + + use Electric.PhoenixExampleWeb, :verified_routes + + # Import conveniences for testing with connections + import Plug.Conn + import Phoenix.ConnTest + import Electric.PhoenixExampleWeb.ConnCase + end + end + + setup tags do + Electric.PhoenixExample.DataCase.setup_sandbox(tags) + {:ok, conn: Phoenix.ConnTest.build_conn()} + end +end diff --git a/examples/phoenix-liveview/test/support/data_case.ex b/examples/phoenix-liveview/test/support/data_case.ex new file mode 100644 index 0000000000..1ca6a9bd14 --- /dev/null +++ b/examples/phoenix-liveview/test/support/data_case.ex @@ -0,0 +1,58 @@ +defmodule Electric.PhoenixExample.DataCase do + @moduledoc """ + This module defines the setup for tests requiring + access to the application's data layer. + + You may define functions here to be used as helpers in + your tests. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use Electric.PhoenixExample.DataCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + alias Electric.PhoenixExample.Repo + + import Ecto + import Ecto.Changeset + import Ecto.Query + import Electric.PhoenixExample.DataCase + end + end + + setup tags do + Electric.PhoenixExample.DataCase.setup_sandbox(tags) + :ok + end + + @doc """ + Sets up the sandbox based on the test tags. + """ + def setup_sandbox(tags) do + pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Electric.PhoenixExample.Repo, shared: not tags[:async]) + on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end) + end + + @doc """ + A helper that transforms changeset errors into a map of messages. + + assert {:error, changeset} = Accounts.create_user(%{password: "short"}) + assert "password is too short" in errors_on(changeset).password + assert %{password: ["password is too short"]} = errors_on(changeset) + + """ + def errors_on(changeset) do + Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> + Regex.replace(~r"%{(\w+)}", message, fn _, key -> + opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() + end) + end) + end +end diff --git a/examples/phoenix-liveview/test/support/fixtures/todos_fixtures.ex b/examples/phoenix-liveview/test/support/fixtures/todos_fixtures.ex new file mode 100644 index 0000000000..fc50677bcb --- /dev/null +++ b/examples/phoenix-liveview/test/support/fixtures/todos_fixtures.ex @@ -0,0 +1,21 @@ +defmodule Electric.PhoenixExample.TodosFixtures do + @moduledoc """ + This module defines test helpers for creating + entities via the `Electric.PhoenixExample.Todos` context. + """ + + @doc """ + Generate a todo. + """ + def todo_fixture(attrs \\ %{}) do + {:ok, todo} = + attrs + |> Enum.into(%{ + completed: true, + text: "some text" + }) + |> Electric.PhoenixExample.Todos.create_todo() + + todo + end +end diff --git a/examples/phoenix-liveview/test/test_helper.exs b/examples/phoenix-liveview/test/test_helper.exs new file mode 100644 index 0000000000..a2551d82e8 --- /dev/null +++ b/examples/phoenix-liveview/test/test_helper.exs @@ -0,0 +1,2 @@ +ExUnit.start() +Ecto.Adapters.SQL.Sandbox.mode(Electric.PhoenixExample.Repo, :manual) diff --git a/packages/elixir-client/lib/electric/client/shape_definition.ex b/packages/elixir-client/lib/electric/client/shape_definition.ex index 91fd4282cb..91cb58c9df 100644 --- a/packages/elixir-client/lib/electric/client/shape_definition.ex +++ b/packages/elixir-client/lib/electric/client/shape_definition.ex @@ -10,6 +10,8 @@ defmodule Electric.Client.ShapeDefinition do @enforce_keys [:table] + @derive {Jason.Encoder, except: [:parser]} + defstruct [:namespace, :table, :columns, :where, parser: {Electric.Client.ValueMapper, []}] @schema NimbleOptions.new!( diff --git a/website/docs/integrations/phoenix.md b/website/docs/integrations/phoenix.md index 28f8f0a4e9..ac1b1aea63 100644 --- a/website/docs/integrations/phoenix.md +++ b/website/docs/integrations/phoenix.md @@ -45,13 +45,13 @@ defmodule MyAppWeb.Router do scope "/shapes" do pipe_through :browser - get "/todos", Electric.Phoenix.Gateway.Plug, + get "/todos", Electric.Phoenix.Plug, shape: Electric.Client.shape!(Todo, where: "visible = true") end end ``` -Because the shape is defined in your Router, it can use Plug middleware for authorisation. See [Parameter-based shapes](https://hexdocs.pm/electric_phoenix/0.1.0-dev-2/Electric.Phoenix.Gateway.Plug.html#module-parameter-based-shapes) for more details. +Because the shape is defined in your Router, it can use Plug middleware for authorisation. See [Parameter-based shapes](https://hexdocs.pm/electric_phoenix/Electric.Phoenix.Plug.html#module-parameter-based-shapes) for more details. ### LiveView sync @@ -59,12 +59,12 @@ Because the shape is defined in your Router, it can use Plug middleware for auth LiveView provides a primitive, called [Phoenix.Streams](https://fly.io/phoenix-files/phoenix-dev-blog-streams) that allows you to stream data into a LiveView. `Electric.Phoenix` provides a wrapper around this to automatically stream a [Shape](/docs/guides/shapes) into a LiveView. -The key primitive is a [`live_stream/4`](https://hexdocs.pm/electric_phoenix/Electric.Phoenix.html#live_stream/4) function that wraps [`Phoenix.LiveView.stream/4`](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#stream/4) to provide a live updating collection of items. +The key primitive is an [`electric_stream/4`](https://hexdocs.pm/electric_phoenix/Electric.Phoenix.LiveView.html#electric_stream/4) function that wraps [`Phoenix.LiveView.stream/4`](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#stream/4) to provide a live updating collection of items. ```elixir def mount(_params, _session, socket) do socket = - Electric.Phoenix.live_stream( + Electric.Phoenix.LiveView.electric_stream( socket, :visible_todos, from(t in Todo, where: t.visible == true) @@ -80,6 +80,25 @@ This makes your LiveView applications real-time. In fact, it allows you to build For more details and full documentation see [hexdocs.pm/electric_phoenix](https://hexdocs.pm/electric_phoenix). +## Examples + +### Phoenix LiveView + +See the +[phoenix-liveview example](https://github.com/electric-sql/electric/tree/main/examples/phoenix-liveview) +on GitHub. + +This is an example Phoenix LiveView application that uses +[`Electric.Phoenix.LiveView.electric_stream/4`](https://hexdocs.pm/electric_phoenix/Electric.Phoenix.LiveView.html#electric_stream/4) +to sync data from Postgres into a LiveView using +[Phoenix Streams](https://fly.io/phoenix-files/phoenix-dev-blog-streams/). +This keeps the LiveView automatically in-sync with Postgres, without having +to re-run queries or trigger any change handling yourself. + +See the +[documentation](https://electric-sql.com/docs/integrations/phoenix#liveview-sync) +for more details. + an equivalent integration for other server-side frameworks, such as Rails, Laravel, Django, etc. - \ No newline at end of file +