From bf3ee4b42150680b6190871b334570f6ce85e25f Mon Sep 17 00:00:00 2001 From: Carlos Souza Date: Thu, 22 Jan 2026 12:55:42 -0500 Subject: [PATCH 1/2] Add metrics dashboard --- config/dev.exs | 2 +- config/runtime.exs | 3 +- lib/fester/application.ex | 1 + lib/fester/chain_sync.ex | 23 +- lib/fester/metrics/aggregator.ex | 213 +++++++++++++ lib/fester_web.ex | 39 +++ lib/fester_web/components/layouts.ex | 9 + .../components/layouts/app.html.heex | 9 + .../components/layouts/root.html.heex | 279 ++++++++++++++++++ lib/fester_web/endpoint.ex | 6 +- lib/fester_web/live/dashboard_live.ex | 131 ++++++++ lib/fester_web/router.ex | 17 ++ mix.exs | 1 + mix.lock | 2 + priv/static/assets/app.js | 6 + priv/static/assets/phoenix.js | 2 + priv/static/assets/phoenix_live_view.js | 21 ++ 17 files changed, 755 insertions(+), 9 deletions(-) create mode 100644 lib/fester/metrics/aggregator.ex create mode 100644 lib/fester_web/components/layouts.ex create mode 100644 lib/fester_web/components/layouts/app.html.heex create mode 100644 lib/fester_web/components/layouts/root.html.heex create mode 100644 lib/fester_web/live/dashboard_live.ex create mode 100644 priv/static/assets/app.js create mode 100644 priv/static/assets/phoenix.js create mode 100644 priv/static/assets/phoenix_live_view.js diff --git a/config/dev.exs b/config/dev.exs index 00b6422..5f35bf0 100644 --- a/config/dev.exs +++ b/config/dev.exs @@ -9,7 +9,7 @@ import Config config :fester, FesterWeb.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: {127, 0, 0, 1}, port: 4000], + http: [ip: {0, 0, 0, 0}, port: 4000], check_origin: false, code_reloader: true, debug_errors: true, diff --git a/config/runtime.exs b/config/runtime.exs index 935c492..83deaac 100644 --- a/config/runtime.exs +++ b/config/runtime.exs @@ -115,4 +115,5 @@ config :fester, Fester.Repo, wal_auto_check_point: 8000, custom_pragmas: [ mmap_size: 268_435_456 - ] + ], + busy_timeout: 5000 diff --git a/lib/fester/application.ex b/lib/fester/application.ex index d9f819f..578583f 100644 --- a/lib/fester/application.ex +++ b/lib/fester/application.ex @@ -10,6 +10,7 @@ defmodule Fester.Application do # TODO: Extract these Metrics into a Supervisor Fester.Metrics.ChainSync, Fester.Metrics.Indexer, + Fester.Metrics.Aggregator, Fester.Repo, {DNSCluster, query: Application.get_env(:fester, :dns_cluster_query) || :ignore}, {Phoenix.PubSub, name: Fester.PubSub}, diff --git a/lib/fester/chain_sync.ex b/lib/fester/chain_sync.ex index 2d6e276..99ad8f2 100644 --- a/lib/fester/chain_sync.ex +++ b/lib/fester/chain_sync.ex @@ -7,7 +7,7 @@ defmodule Fester.ChainSync do def start_link(opts) do initial_state = [ is_synced?: false, - sync_from: :origin + sync_from: :conway ## To sync from a specific point in the chain, uncomment the line below ## and set the slot and block hash # sync_from: {slot, block_hash} @@ -46,7 +46,12 @@ defmodule Fester.ChainSync do :telemetry.execute( [:fester, :chain_sync, :block_processed], - %{timestamp: System.system_time(:millisecond), block_height: block_height} + %{ + timestamp: System.system_time(:millisecond), + block_height: block_height, + slot: slot, + tip_slot: slot + } ) {:ok, :next_block, state} @@ -75,7 +80,12 @@ defmodule Fester.ChainSync do :telemetry.execute( [:fester, :chain_sync, :block_processed], - %{timestamp: System.system_time(:millisecond), block_height: block_height} + %{ + timestamp: System.system_time(:millisecond), + block_height: block_height, + slot: slot, + tip_slot: slot + } ) {:ok, :next_block, %{state | is_synced?: true}} @@ -97,7 +107,12 @@ defmodule Fester.ChainSync do :telemetry.execute( [:fester, :chain_sync, :block_processed], - %{timestamp: System.system_time(:millisecond), block_height: block_height} + %{ + timestamp: System.system_time(:millisecond), + block_height: block_height, + slot: slot, + tip_slot: current_tip_slot + } ) {:ok, :next_block, state} diff --git a/lib/fester/metrics/aggregator.ex b/lib/fester/metrics/aggregator.ex new file mode 100644 index 0000000..94c67eb --- /dev/null +++ b/lib/fester/metrics/aggregator.ex @@ -0,0 +1,213 @@ +defmodule Fester.Metrics.Aggregator do + @moduledoc """ + Aggregates telemetry metrics and broadcasts them to subscribed LiveView clients. + """ + + use GenServer + + @pubsub Fester.PubSub + @topic "metrics" + @broadcast_interval 1_000 + + ## Public API + + def start_link(_) do + GenServer.start_link(__MODULE__, %{}, name: __MODULE__) + end + + @doc """ + Returns the current aggregated metrics. + """ + def get_metrics do + GenServer.call(__MODULE__, :get_metrics) + end + + @doc """ + Subscribes the calling process to metrics updates. + """ + def subscribe do + Phoenix.PubSub.subscribe(@pubsub, @topic) + end + + ## Callbacks + + @impl true + def init(_) do + :telemetry.attach_many( + "metrics-aggregator-handler", + [ + [:fester, :chain_sync, :catching_up_started], + [:fester, :chain_sync, :catching_up_finished], + [:fester, :chain_sync, :block_processed], + [:fester, :db_indexer, :tx_start], + [:fester, :db_indexer, :tx_end] + ], + &__MODULE__.handle_telemetry_event/4, + nil + ) + + schedule_broadcast() + + {:ok, + %{ + service_started_at: System.monotonic_time(:millisecond), + sync_start_time: nil, + sync_end_time: nil, + sync_start_block: nil, + current_block_height: 0, + blocks_per_second: 0.0, + tx_count: 0, + tx_total_duration: 0, + tx_avg_duration: 0.0, + tx_start_time: nil, + is_syncing: false, + current_slot: 0, + tip_slot: 0, + sync_percentage: 0.0 + }} + end + + def handle_telemetry_event(event_name, measurements, metadata, _config) do + GenServer.cast(__MODULE__, {:telemetry, event_name, measurements, metadata}) + end + + @impl true + def handle_call(:get_metrics, _from, state) do + {:reply, build_metrics(state), state} + end + + @impl true + def handle_cast( + {:telemetry, [:fester, :chain_sync, :catching_up_started], %{timestamp: timestamp}, _}, + state + ) do + {:noreply, + %{ + state + | sync_start_time: timestamp, + sync_end_time: nil, + sync_start_block: nil, + is_syncing: true + }} + end + + def handle_cast( + {:telemetry, [:fester, :chain_sync, :catching_up_finished], %{timestamp: timestamp}, _}, + state + ) do + {:noreply, %{state | sync_end_time: timestamp, is_syncing: false}} + end + + def handle_cast( + {:telemetry, [:fester, :chain_sync, :block_processed], + %{timestamp: now, block_height: height} = measurements, _}, + state + ) do + sync_start_block = state.sync_start_block || height + blocks_per_second = calculate_throughput(state.sync_start_time, sync_start_block, now, height) + + # Extract slot data if present + current_slot = Map.get(measurements, :slot, state.current_slot) + tip_slot = Map.get(measurements, :tip_slot, state.tip_slot) + + sync_percentage = + if tip_slot > 0 do + min(current_slot / tip_slot * 100, 100.0) + else + 0.0 + end + + {:noreply, + %{ + state + | current_block_height: height, + blocks_per_second: blocks_per_second, + sync_start_block: sync_start_block, + current_slot: current_slot, + tip_slot: tip_slot, + sync_percentage: sync_percentage + }} + end + + def handle_cast( + {:telemetry, [:fester, :db_indexer, :tx_start], %{timestamp: timestamp}, _}, + state + ) do + {:noreply, %{state | tx_start_time: timestamp}} + end + + def handle_cast( + {:telemetry, [:fester, :db_indexer, :tx_end], %{timestamp: timestamp}, _}, + %{tx_start_time: tx_start} = state + ) + when not is_nil(tx_start) do + duration = timestamp - tx_start + tx_count = state.tx_count + 1 + tx_total = state.tx_total_duration + duration + tx_avg = tx_total / tx_count + + {:noreply, + %{ + state + | tx_count: tx_count, + tx_total_duration: tx_total, + tx_avg_duration: tx_avg, + tx_start_time: nil + }} + end + + def handle_cast({:telemetry, _, _, _}, state) do + {:noreply, state} + end + + @impl true + def handle_info(:broadcast, state) do + metrics = build_metrics(state) + Phoenix.PubSub.broadcast(@pubsub, @topic, {:metrics_update, metrics}) + schedule_broadcast() + {:noreply, state} + end + + ## Private + + defp schedule_broadcast do + Process.send_after(self(), :broadcast, @broadcast_interval) + end + + defp build_metrics(state) do + %{ + blocks_per_second: Float.round(state.blocks_per_second, 2), + tx_avg_duration: Float.round(state.tx_avg_duration, 2), + current_block_height: state.current_block_height, + is_syncing: state.is_syncing, + sync_duration: calculate_sync_duration(state), + uptime: System.monotonic_time(:millisecond) - state.service_started_at, + current_slot: state.current_slot, + tip_slot: state.tip_slot, + sync_percentage: Float.round(state.sync_percentage, 2) + } + end + + defp calculate_throughput(nil, _, _, _), do: 0.0 + + defp calculate_throughput(start_time, start_block, now, current_height) do + total_time = now - start_time + total_blocks = current_height - start_block + 1 + + if total_time > 0 do + total_blocks * 1000 / total_time + else + 0.0 + end + end + + defp calculate_sync_duration(%{sync_start_time: nil}), do: nil + + defp calculate_sync_duration(%{sync_start_time: start, sync_end_time: nil}) do + System.system_time(:millisecond) - start + end + + defp calculate_sync_duration(%{sync_start_time: start, sync_end_time: finish}) do + finish - start + end +end diff --git a/lib/fester_web.ex b/lib/fester_web.ex index e88cb02..c96ecfe 100644 --- a/lib/fester_web.ex +++ b/lib/fester_web.ex @@ -19,6 +19,45 @@ defmodule FesterWeb do def static_paths, do: ~w(assets fonts images favicon.ico robots.txt) + def live_view do + quote do + use Phoenix.LiveView, + layout: {FesterWeb.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 Phoenix.Controller, + only: [get_csrf_token: 0, view_module: 1, view_template: 1] + + unquote(html_helpers()) + end + end + + defp html_helpers do + quote do + import Phoenix.HTML + import Phoenix.LiveView.Helpers + + alias Phoenix.LiveView.JS + + unquote(verified_routes()) + end + end + def router do quote do use Phoenix.Router, helpers: false diff --git a/lib/fester_web/components/layouts.ex b/lib/fester_web/components/layouts.ex new file mode 100644 index 0000000..9c27f87 --- /dev/null +++ b/lib/fester_web/components/layouts.ex @@ -0,0 +1,9 @@ +defmodule FesterWeb.Layouts do + @moduledoc """ + Layout templates for FesterWeb. + """ + + use FesterWeb, :html + + embed_templates "layouts/*" +end diff --git a/lib/fester_web/components/layouts/app.html.heex b/lib/fester_web/components/layouts/app.html.heex new file mode 100644 index 0000000..9a533a7 --- /dev/null +++ b/lib/fester_web/components/layouts/app.html.heex @@ -0,0 +1,9 @@ +
+ <%= if info = Phoenix.Flash.get(@flash, :info) do %> +
<%= info %>
+ <% end %> + <%= if error = Phoenix.Flash.get(@flash, :error) do %> +
<%= error %>
+ <% end %> + <%= @inner_content %> +
diff --git a/lib/fester_web/components/layouts/root.html.heex b/lib/fester_web/components/layouts/root.html.heex new file mode 100644 index 0000000..522e0ab --- /dev/null +++ b/lib/fester_web/components/layouts/root.html.heex @@ -0,0 +1,279 @@ + + + + + + + Fester Dashboard + + + + <%= @inner_content %> + + + + + diff --git a/lib/fester_web/endpoint.ex b/lib/fester_web/endpoint.ex index 6eadc76..8e87d3b 100644 --- a/lib/fester_web/endpoint.ex +++ b/lib/fester_web/endpoint.ex @@ -11,9 +11,9 @@ defmodule FesterWeb.Endpoint do same_site: "Lax" ] - # socket "/live", Phoenix.LiveView.Socket, - # websocket: [connect_info: [session: @session_options]], - # longpoll: [connect_info: [session: @session_options]] + 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. # diff --git a/lib/fester_web/live/dashboard_live.ex b/lib/fester_web/live/dashboard_live.ex new file mode 100644 index 0000000..d26936d --- /dev/null +++ b/lib/fester_web/live/dashboard_live.ex @@ -0,0 +1,131 @@ +defmodule FesterWeb.DashboardLive do + @moduledoc """ + Real-time metrics dashboard for Fester. + """ + + use FesterWeb, :live_view + + alias Fester.Metrics.Aggregator + + @impl true + def mount(_params, _session, socket) do + if connected?(socket) do + Aggregator.subscribe() + end + + metrics = Aggregator.get_metrics() + + {:ok, assign(socket, metrics: metrics)} + end + + @impl true + def handle_info({:metrics_update, metrics}, socket) do + {:noreply, assign(socket, metrics: metrics)} + end + + @impl true + def render(assigns) do + ~H""" +
+
+

Fester - Metrics Dashboard

+
+
+ + <%= if @metrics.is_syncing, do: "Syncing", else: "Synced" %> +
+
+ +
+
+ Sync Progress + + <%= Float.round(@metrics.sync_percentage, 1) %>% + +
+
+
+
+
+
+ Slot <%= @metrics.current_slot %> of <%= @metrics.tip_slot %> +
+
+ +
+
+
Chain Sync Throughput
+
+ <%= @metrics.blocks_per_second %> + blocks/sec +
+
+ +
+
Tx Processing Time
+
+ <%= @metrics.tx_avg_duration %> + ms avg +
+
+ +
+
Time to Sync
+
+ <%= format_sync_duration(@metrics.sync_duration, @metrics.is_syncing) %> +
+
+ +
+
Service Uptime
+
+ <%= format_duration(@metrics.uptime) %> +
+
+
+ +
+
+ Current Block Height + <%= @metrics.current_block_height %> +
+
+ Sync Status + <%= if @metrics.is_syncing, do: "Catching up to tip", else: "At chain tip" %> +
+
+ """ + end + + defp status_class(true), do: "syncing" + defp status_class(false), do: "synced" + + defp format_sync_duration(nil, _), do: "--" + defp format_sync_duration(duration, true), do: "#{format_duration(duration)}..." + defp format_sync_duration(duration, false), do: format_duration(duration) + + defp format_duration(ms) when is_nil(ms), do: "--" + + defp format_duration(ms) when ms < 1000, do: "#{ms}ms" + + defp format_duration(ms) do + total_seconds = div(ms, 1000) + days = div(total_seconds, 86400) + hours = div(rem(total_seconds, 86400), 3600) + minutes = div(rem(total_seconds, 3600), 60) + seconds = rem(total_seconds, 60) + + cond do + days > 0 -> "#{days}d #{hours}h #{minutes}m" + hours > 0 -> "#{hours}h #{minutes}m #{seconds}s" + minutes > 0 -> "#{minutes}m #{seconds}s" + true -> "#{seconds}s" + end + end + + defp progress_color_class(percentage) when percentage >= 100, do: "synced" + defp progress_color_class(_), do: "syncing" +end diff --git a/lib/fester_web/router.ex b/lib/fester_web/router.ex index ab6dea1..c66ef22 100644 --- a/lib/fester_web/router.ex +++ b/lib/fester_web/router.ex @@ -1,10 +1,27 @@ defmodule FesterWeb.Router do use FesterWeb, :router + import Phoenix.LiveView.Router + + pipeline :browser do + plug :accepts, ["html"] + plug :fetch_session + plug :fetch_live_flash + plug :put_root_layout, html: {FesterWeb.Layouts, :root} + plug :protect_from_forgery + plug :put_secure_browser_headers + end + pipeline :api do plug :accepts, ["json"] end + scope "/", FesterWeb do + pipe_through :browser + + live "/dashboard", DashboardLive + end + scope "/api", FesterWeb do pipe_through :api diff --git a/mix.exs b/mix.exs index cd16329..135862d 100644 --- a/mix.exs +++ b/mix.exs @@ -41,6 +41,7 @@ defmodule Fester.MixProject do {:jason, "~> 1.2"}, {:phoenix, "~> 1.7.21"}, {:phoenix_ecto, "~> 4.5"}, + {:phoenix_live_view, "~> 1.0"}, {:swoosh, "~> 1.5"}, {:telemetry_metrics, "~> 1.0"}, {:telemetry_poller, "~> 1.0"}, diff --git a/mix.lock b/mix.lock index 9237966..79cb0a3 100644 --- a/mix.lock +++ b/mix.lock @@ -23,6 +23,8 @@ "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"}, "phoenix": {:hex, :phoenix, "1.7.21", "14ca4f1071a5f65121217d6b57ac5712d1857e40a0833aff7a691b7870fc9a3b", [: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", "336dce4f86cba56fed312a7d280bf2282c720abb6074bdb1b61ec8095bdd0bc9"}, "phoenix_ecto": {:hex, :phoenix_ecto, "4.6.3", "f686701b0499a07f2e3b122d84d52ff8a31f5def386e03706c916f6feddf69ef", [: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", "909502956916a657a197f94cc1206d9a65247538de8a5e186f7537c895d95764"}, + "phoenix_html": {:hex, :phoenix_html, "4.3.0", "d3577a5df4b6954cd7890c84d955c470b5310bb49647f0a114a6eeecc850f7ad", [:mix], [], "hexpm", "3eaa290a78bab0f075f791a46a981bbe769d94bc776869f4f3063a14f30497ad"}, + "phoenix_live_view": {:hex, :phoenix_live_view, "1.1.20", "4f20850ee700b309b21906a0e510af1b916b454b4f810fb8581ada016eb42dfc", [:mix], [{:igniter, ">= 0.6.16 and < 1.0.0-0", [hex: :igniter, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:lazy_html, "~> 0.1.0", [hex: :lazy_html, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.6.15 or ~> 1.7.0 or ~> 1.8.0-rc", [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", "c16abd605a21f778165cb0079946351ef20ef84eb1ef467a862fb9a173b1d27d"}, "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.18.1", "5067f26f7745b7e31bc3368bc1a2b818b9779faa959b49c934c17730efc911cf", [: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", "57a57db70df2b422b564437d2d33cf8d33cd16339c1edb190cd11b1a3a546cc2"}, diff --git a/priv/static/assets/app.js b/priv/static/assets/app.js new file mode 100644 index 0000000..a957d32 --- /dev/null +++ b/priv/static/assets/app.js @@ -0,0 +1,6 @@ +let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content"); +let liveSocket = new LiveView.LiveSocket("/live", Phoenix.Socket, { + params: { _csrf_token: csrfToken } +}); +liveSocket.connect(); +window.liveSocket = liveSocket; diff --git a/priv/static/assets/phoenix.js b/priv/static/assets/phoenix.js new file mode 100644 index 0000000..ad4444a --- /dev/null +++ b/priv/static/assets/phoenix.js @@ -0,0 +1,2 @@ +var Phoenix=(()=>{var x=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var D=(a,e)=>{for(var t in e)x(a,t,{get:e[t],enumerable:!0})},U=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of M(e))!P.call(a,s)&&s!==t&&x(a,s,{get:()=>e[s],enumerable:!(i=$(e,s))||i.enumerable});return a};var J=a=>U(x({},"__esModule",{value:!0}),a);var F={};D(F,{Channel:()=>y,LongPoll:()=>m,Presence:()=>g,Serializer:()=>j,Socket:()=>w});var v=a=>typeof a=="function"?a:function(){return a};var z=typeof self!="undefined"?self:null,k=typeof window!="undefined"?window:null,T=z||k||T,H="2.0.0",d={connecting:0,open:1,closing:2,closed:3},N=1e4,O=1e3,u={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},p={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},A={longpoll:"longpoll",websocket:"websocket"},B={complete:4};var b=class{constructor(e,t,i,s){this.channel=e,this.event=t,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:e,response:t,_ref:i}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}};var R=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var y=class{constructor(e,t,i){this.state=u.closed,this.topic=e,this.params=v(t||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new b(this,p.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new R(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=u.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=u.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=u.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=u.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new b(this,p.leave,v({}),this.timeout).send(),this.state=u.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(p.reply,(s,o)=>{this.trigger(this.replyEventName(o),s)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(e){this.on(p.close,e)}onError(e){return this.on(p.error,t=>e(t))}on(e,t){let i=this.bindingRef++;return this.bindings.push({event:e,ref:i,callback:t}),i}off(e,t){this.bindings=this.bindings.filter(i=>!(i.event===e&&(typeof t=="undefined"||t===i.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,i=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new b(this,e,function(){return t},i);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=u.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(p.close,"leave")},i=new b(this,p.leave,v({}),e);return i.receive("ok",()=>t()).receive("timeout",()=>t()),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(e,t,i){return t}isMember(e,t,i,s){return this.topic!==e?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:i,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=u.joining,this.joinPush.resend(e))}trigger(e,t,i,s){let o=this.onMessage(e,t,i,s);if(t&&!o)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(n=>n.event===e);for(let n=0;n{let h=this.parseJSON(e.responseText);n&&n(h)},r&&(e.ontimeout=r),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,i,s,o,r,n,h){return e.open(t,i,!0),e.timeout=r,e.setRequestHeader("Content-Type",s),e.onerror=()=>h&&h(null),e.onreadystatechange=()=>{if(e.readyState===B.complete&&h){let l=this.parseJSON(e.responseText);h(l)}},n&&(e.ontimeout=n),e.send(o),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch(t){return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let i=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let o=t?`${t}[${s}]`:s,r=e[s];typeof r=="object"?i.push(this.serialize(r,o)):i.push(encodeURIComponent(o)+"="+encodeURIComponent(r))}return i.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let i=e.match(/\?/)?"&":"?";return`${e}${i}${this.serialize(t)}`}};var I=a=>{let e="",t=new Uint8Array(a),i=t.byteLength;for(let s=0;sthis.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+A.websocket),"$1/"+A.longpoll)}endpointURL(){return C.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,i){this.close(e,t,i),this.readyState=d.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===d.open||this.readyState===d.connecting}poll(){this.ajax("GET","application/json",null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:i,messages:s}=e;this.token=i}else t=0;switch(t){case 200:s.forEach(o=>{setTimeout(()=>this.onmessage({data:o}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=d.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${t}`)}})}send(e){typeof e!="string"&&(e=I(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST","application/x-ndjson",e.join(` +`),()=>this.onerror("timeout"),t=>{this.awaitingBatchAck=!1,!t||t.status!==200?(this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(e,t,i){for(let o of this.reqs)o.abort();this.readyState=d.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:i});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent!="undefined"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,i,s,o){let r,n=()=>{this.reqs.delete(r),s()};r=C.request(e,this.endpointURL(),t,i,this.timeout,n,h=>{this.reqs.delete(r),this.isActive()&&o(h)}),this.reqs.add(r)}};var g=class{constructor(e,t={}){let i=t.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(i.state,s=>{let{onJoin:o,onLeave:r,onSync:n}=this.caller;this.joinRef=this.channel.joinRef(),this.state=g.syncState(this.state,s,o,r),this.pendingDiffs.forEach(h=>{this.state=g.syncDiff(this.state,h,o,r)}),this.pendingDiffs=[],n()}),this.channel.on(i.diff,s=>{let{onJoin:o,onLeave:r,onSync:n}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=g.syncDiff(this.state,s,o,r),n())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return g.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,i,s){let o=this.clone(e),r={},n={};return this.map(o,(h,l)=>{t[h]||(n[h]=l)}),this.map(t,(h,l)=>{let f=o[h];if(f){let c=l.metas.map(S=>S.phx_ref),E=f.metas.map(S=>S.phx_ref),L=l.metas.filter(S=>E.indexOf(S.phx_ref)<0),_=f.metas.filter(S=>c.indexOf(S.phx_ref)<0);L.length>0&&(r[h]=l,r[h].metas=L),_.length>0&&(n[h]=this.clone(f),n[h].metas=_)}else r[h]=l}),this.syncDiff(o,{joins:r,leaves:n},i,s)}static syncDiff(e,t,i,s){let{joins:o,leaves:r}=this.clone(t);return i||(i=function(){}),s||(s=function(){}),this.map(o,(n,h)=>{let l=e[n];if(e[n]=this.clone(h),l){let f=e[n].metas.map(E=>E.phx_ref),c=l.metas.filter(E=>f.indexOf(E.phx_ref)<0);e[n].metas.unshift(...c)}i(n,l,h)}),this.map(r,(n,h)=>{let l=e[n];if(!l)return;let f=h.metas.map(c=>c.phx_ref);l.metas=l.metas.filter(c=>f.indexOf(c.phx_ref)<0),s(n,l,h),l.metas.length===0&&delete e[n]}),e}static list(e,t){return t||(t=function(i,s){return s}),this.map(e,(i,s)=>t(i,s))}static map(e,t){return Object.getOwnPropertyNames(e).map(i=>t(i,e[i]))}static clone(e){return JSON.parse(JSON.stringify(e))}};var j={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(a,e){if(a.payload.constructor===ArrayBuffer)return e(this.binaryEncode(a));{let t=[a.join_ref,a.ref,a.topic,a.event,a.payload];return e(JSON.stringify(t))}},decode(a,e){if(a.constructor===ArrayBuffer)return e(this.binaryDecode(a));{let[t,i,s,o,r]=JSON.parse(a);return e({join_ref:t,ref:i,topic:s,event:o,payload:r})}},binaryEncode(a){let{join_ref:e,ref:t,event:i,topic:s,payload:o}=a,r=this.META_LENGTH+e.length+t.length+s.length+i.length,n=new ArrayBuffer(this.HEADER_LENGTH+r),h=new DataView(n),l=0;h.setUint8(l++,this.KINDS.push),h.setUint8(l++,e.length),h.setUint8(l++,t.length),h.setUint8(l++,s.length),h.setUint8(l++,i.length),Array.from(e,c=>h.setUint8(l++,c.charCodeAt(0))),Array.from(t,c=>h.setUint8(l++,c.charCodeAt(0))),Array.from(s,c=>h.setUint8(l++,c.charCodeAt(0))),Array.from(i,c=>h.setUint8(l++,c.charCodeAt(0)));var f=new Uint8Array(n.byteLength+o.byteLength);return f.set(new Uint8Array(n),0),f.set(new Uint8Array(o),n.byteLength),f.buffer},binaryDecode(a){let e=new DataView(a),t=e.getUint8(0),i=new TextDecoder;switch(t){case this.KINDS.push:return this.decodePush(a,e,i);case this.KINDS.reply:return this.decodeReply(a,e,i);case this.KINDS.broadcast:return this.decodeBroadcast(a,e,i)}},decodePush(a,e,t){let i=e.getUint8(1),s=e.getUint8(2),o=e.getUint8(3),r=this.HEADER_LENGTH+this.META_LENGTH-1,n=t.decode(a.slice(r,r+i));r=r+i;let h=t.decode(a.slice(r,r+s));r=r+s;let l=t.decode(a.slice(r,r+o));r=r+o;let f=a.slice(r,a.byteLength);return{join_ref:n,ref:null,topic:h,event:l,payload:f}},decodeReply(a,e,t){let i=e.getUint8(1),s=e.getUint8(2),o=e.getUint8(3),r=e.getUint8(4),n=this.HEADER_LENGTH+this.META_LENGTH,h=t.decode(a.slice(n,n+i));n=n+i;let l=t.decode(a.slice(n,n+s));n=n+s;let f=t.decode(a.slice(n,n+o));n=n+o;let c=t.decode(a.slice(n,n+r));n=n+r;let E=a.slice(n,a.byteLength),L={status:c,response:E};return{join_ref:h,ref:l,topic:f,event:p.reply,payload:L}},decodeBroadcast(a,e,t){let i=e.getUint8(1),s=e.getUint8(2),o=this.HEADER_LENGTH+2,r=t.decode(a.slice(o,o+i));o=o+i;let n=t.decode(a.slice(o,o+s));o=o+s;let h=a.slice(o,a.byteLength);return{join_ref:null,ref:null,topic:r,event:n,payload:h}}};var w=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=t.timeout||N,this.transport=t.transport||T.WebSocket||m,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||T&&T.sessionStorage,this.establishedConnections=0,this.defaultEncoder=j.encode.bind(j),this.defaultDecoder=j.decode.bind(j),this.closeWasClean=!1,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.transport!==m?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;k&&k.addEventListener&&(k.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),i=this.connectClock)}),k.addEventListener("pageshow",s=>{i===this.connectClock&&(i=null,this.connect())})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.rejoinAfterMs=s=>t.rejoinAfterMs?t.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>t.reconnectAfterMs?t.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(s,o,r)=>{console.log(`${s}: ${o}`,r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=v(t.params||{}),this.endPoint=`${e}/${A.websocket}`,this.vsn=t.vsn||H,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new R(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return m}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=C.appendParams(C.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,i){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,i)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=v(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==m?this.connectWithFallback(m,this.longPollFallbackMs):this.transportConnect())}log(e,t,i){this.logger&&this.logger(e,t,i)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),i=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(o=>{o.ref===t&&(this.off([s]),e(Date.now()-i))});return!0}transportConnect(){this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let i=!1,s=!0,o,r,n=h=>{this.log("transport",`falling back to ${e.name}...`,h),this.off([o,r]),s=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${e.name}`))return n("memorized");this.fallbackTimer=setTimeout(n,t),r=this.onError(h=>{this.log("transport","error",h),s&&!i&&(clearTimeout(this.fallbackTimer),n(h))}),this.onOpen(()=>{if(i=!0,!s)return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${e.name}`,"true"),this.log("transport",`established ${e.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(n,t),this.ping(h=>{this.log("transport","connected to primary after",h),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,e])=>e())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),O,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,i){if(!this.conn)return e&&e();let s=this.connectClock;this.waitForBufferDone(()=>{s===this.connectClock&&(this.conn&&(t?this.conn.close(t,i||""):this.conn.close()),this.waitForSocketClosed(()=>{s===this.connectClock&&(this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e())}))})}waitForBufferDone(e,t=1){if(t===5||!this.conn||!this.conn.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(e,t+1)},150*t)}waitForSocketClosed(e,t=1){if(t===5||!this.conn||this.conn.readyState===d.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(e,t+1)},150*t)}onConnClose(e){let t=e&&e.code;this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&t!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,i])=>i(e))}onConnError(e){this.hasLogger()&&this.log("transport",e);let t=this.transport,i=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,s])=>{s(e,t,i)}),(t===this.transport||i>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(p.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case d.connecting:return"connecting";case d.open:return"open";case d.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([i])=>e.indexOf(i)===-1)}channel(e,t={}){let i=new y(e,t,this);return this.channels.push(i),i}push(e){if(this.hasLogger()){let{topic:t,event:i,payload:s,ref:o,join_ref:r}=e;this.log("push",`${t} ${i} (${r}, ${o})`,s)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:i,event:s,payload:o,ref:r,join_ref:n}=t;r&&r===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${o.status||""} ${i} ${s} ${r&&"("+r+")"||""}`,o);for(let h=0;hi.topic===e&&(i.isJoined()||i.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};return J(F);})(); diff --git a/priv/static/assets/phoenix_live_view.js b/priv/static/assets/phoenix_live_view.js new file mode 100644 index 0000000..d492266 --- /dev/null +++ b/priv/static/assets/phoenix_live_view.js @@ -0,0 +1,21 @@ +var LiveView=(()=>{var ht=Object.defineProperty,Ni=Object.defineProperties,Fi=Object.getOwnPropertyDescriptor,Ui=Object.getOwnPropertyDescriptors,Xi=Object.getOwnPropertyNames,zt=Object.getOwnPropertySymbols;var Qt=Object.prototype.hasOwnProperty,$i=Object.prototype.propertyIsEnumerable;var Yt=(s,e,t)=>e in s?ht(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,O=(s,e)=>{for(var t in e||(e={}))Qt.call(e,t)&&Yt(s,t,e[t]);if(zt)for(var t of zt(e))$i.call(e,t)&&Yt(s,t,e[t]);return s},ae=(s,e)=>Ni(s,Ui(e));var Vi=(s,e)=>{for(var t in e)ht(s,t,{get:e[t],enumerable:!0})},Bi=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Xi(e))!Qt.call(s,n)&&n!==t&&ht(s,n,{get:()=>e[n],enumerable:!(i=Fi(e,n))||i.enumerable});return s};var ji=s=>Bi(ht({},"__esModule",{value:!0}),s);var An={};Vi(An,{LiveSocket:()=>En,ViewHook:()=>ee,createHook:()=>yn,isUsedInput:()=>Di});var ct="consecutive-reloads";var dt=["phx-click-loading","phx-change-loading","phx-submit-loading","phx-keydown-loading","phx-keyup-loading","phx-blur-loading","phx-focus-loading","phx-hook-loading"],ut="phx-drop-target-active",K="data-phx-component",le="data-phx-view",ft="data-phx-link",Zt="track-static",ei="data-phx-link-state",ge="data-phx-ref-loading",N="data-phx-ref-src",C="data-phx-ref-lock",Ct="phx-pending-refs",pt="track-uploads",G="data-phx-upload-ref",Le="data-phx-preflighted-refs",ti="data-phx-done-refs",qe="drop-target",Ge="data-phx-active-refs",Oe="phx:live-file:updated",mt="data-phx-skip",gt="data-phx-id",xt="data-phx-prune",Rt="phx-connected",ve="phx-loading",Se="phx-error",It="phx-client-error",He="phx-server-error",ne="data-phx-parent-id",De="data-phx-main",Q="data-phx-root-id",ze="viewport-top",Ye="viewport-bottom",ii="viewport-overrun-target",ni="trigger-action",we="phx-has-focused",si=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"],vt=["checkbox","radio"],Pe="phx-has-submitted",q="data-phx-session",he=`[${q}]`,Qe="data-phx-sticky",se="data-phx-static",Ze="data-phx-readonly",be="data-phx-disabled",Lt="disable-with",Me="data-phx-disable-with-restore",Ne="hook",ri="debounce",oi="throttle",Fe="update",Ue="stream",Xe="data-phx-stream",$e="data-phx-portal",re="data-phx-teleported",Ee="data-phx-teleported-src",Ve="data-phx-runtime-hook",ai="data-phx-pid",li="key",te="phxPrivate",Ot="auto-recover",et="phx:live-socket:debug",bt="phx:live-socket:profiling",Et="phx:live-socket:latency-sim",tt="phx:nav-history-position",hi="progress",Ht="mounted",Dt="__phoenix_reload_status__",ci=1,Mt=3,di=200,ui=500,fi="phx-",pi=3e4;var Be="debounce-trigger",je="throttled",Nt="debounce-prev-key",mi={debounce:300,throttle:300},Ft=[ge,N,C],z="s",yt="r",X="c",R="k",ie="kc",Ut="e",Xt="r",$t="t",ce="p",ke="stream";var it=class{constructor(e,t,i){let{chunk_size:n,chunk_timeout:r}=t;this.liveSocket=i,this.entry=e,this.offset=0,this.chunkSize=n,this.chunkTimeout=r,this.chunkTimer=null,this.errored=!1,this.uploadChannel=i.channel(`lvu:${e.ref}`,{token:e.metadata()})}error(e){this.errored||(this.uploadChannel.leave(),this.errored=!0,clearTimeout(this.chunkTimer),this.entry.error(e))}upload(){this.uploadChannel.onError(e=>this.error(e)),this.uploadChannel.join().receive("ok",e=>this.readNextChunk()).receive("error",e=>this.error(e))}isDone(){return this.offset>=this.entry.file.size}readNextChunk(){let e=new window.FileReader,t=this.entry.file.slice(this.offset,this.chunkSize+this.offset);e.onload=i=>{if(i.target.error===null)this.offset+=i.target.result.byteLength,this.pushChunk(i.target.result);else return w("Read error: "+i.target.error)},e.readAsArrayBuffer(t)}pushChunk(e){this.uploadChannel.isJoined()&&this.uploadChannel.push("chunk",e,this.chunkTimeout).receive("ok",()=>{this.entry.progress(this.offset/this.entry.file.size*100),this.isDone()||(this.chunkTimer=setTimeout(()=>this.readNextChunk(),this.liveSocket.getLatencySim()||0))}).receive("error",({reason:t})=>this.error(t))}};var w=(s,e)=>console.error&&console.error(s,e),Z=s=>{let e=typeof s;return e==="number"||e==="string"&&/^(0|[1-9]\d*)$/.test(s)};function gi(){let s=new Set,e=document.querySelectorAll("*[id]");for(let t=0,i=e.length;t{let i=document.getElementById(t);i&&i.parentElement&&i.parentElement.getAttribute("phx-update")!=="stream"&&e.add(`The stream container with id "${i.parentElement.id}" is missing the phx-update="stream" attribute. Ensure it is set for streams to work properly.`)}),e.forEach(t=>console.error(t))}var bi=(s,e,t,i)=>{s.liveSocket.isDebugEnabled()&&console.log(`${s.id} ${e}: ${t} - `,i)},Je=s=>typeof s=="function"?s:function(){return s},We=s=>JSON.parse(JSON.stringify(s)),de=(s,e,t)=>{do{if(s.matches(`[${e}]`)&&!s.disabled)return s;s=s.parentElement||s.parentNode}while(s!==null&&s.nodeType===1&&!(t&&t.isSameNode(s)||s.matches(he)));return null},Te=s=>s!==null&&typeof s=="object"&&!(s instanceof Array),Ei=(s,e)=>JSON.stringify(s)===JSON.stringify(e),Vt=s=>{for(let e in s)return!1;return!0},ue=(s,e)=>s&&e(s),yi=function(s,e,t,i){s.forEach(n=>{new it(n,t.config,i).upload()})},Ai=s=>{if(s.dataTransfer.types){for(let e=0;e{let i=this.getHashTargetEl(window.location.hash);i?i.scrollIntoView():e.type==="redirect"&&window.scroll(0,0)})}}else this.redirect(t)},setCookie(s,e,t){let i=typeof t=="number"?` max-age=${t};`:"";document.cookie=`${s}=${e};${i} path=/`},getCookie(s){return document.cookie.replace(new RegExp(`(?:(?:^|.*;s*)${s}s*=s*([^;]*).*$)|^.*$`),"$1")},deleteCookie(s){document.cookie=`${s}=; max-age=-1; path=/`},redirect(s,e,t=i=>{window.location.href=i}){e&&this.setCookie("__phoenix_flash__",e,60),t(s)},localKey(s,e){return`${s}-${e}`},getHashTargetEl(s){let e=s.toString().substring(1);if(e!=="")return document.getElementById(e)||document.querySelector(`a[name="${e}"]`)}},$=Ji;var Ce={byId(s){return document.getElementById(s)||w(`no id found for ${s}`)},removeClass(s,e){s.classList.remove(e),s.classList.length===0&&s.removeAttribute("class")},all(s,e,t){if(!s)return[];let i=Array.from(s.querySelectorAll(e));return t&&i.forEach(t),i},childNodeLength(s){let e=document.createElement("template");return e.innerHTML=s,e.content.childElementCount},isUploadInput(s){return s.type==="file"&&s.getAttribute(G)!==null},isAutoUpload(s){return s.hasAttribute("data-phx-auto-upload")},findUploadInputs(s){let e=s.id,t=this.all(document,`input[type="file"][${G}][form="${e}"]`);return this.all(s,`input[type="file"][${G}]`).concat(t)},findComponentNodeList(s,e,t=document){return this.all(t,`[${le}="${s}"][${K}="${e}"]`)},isPhxDestroyed(s){return!!(s.id&&Ce.private(s,"destroyed"))},wantsNewTab(s){let e=s.ctrlKey||s.shiftKey||s.metaKey||s.button&&s.button===1,t=s.target instanceof HTMLAnchorElement&&s.target.hasAttribute("download"),i=s.target.hasAttribute("target")&&s.target.getAttribute("target").toLowerCase()==="_blank",n=s.target.hasAttribute("target")&&!s.target.getAttribute("target").startsWith("_");return e||i||t||n},isUnloadableFormSubmit(s){return s.target&&s.target.getAttribute("method")==="dialog"||s.submitter&&s.submitter.getAttribute("formmethod")==="dialog"?!1:!s.defaultPrevented&&!this.wantsNewTab(s)},isNewPageClick(s,e){let t=s.target instanceof HTMLAnchorElement?s.target.getAttribute("href"):null,i;if(s.defaultPrevented||t===null||this.wantsNewTab(s)||t.startsWith("mailto:")||t.startsWith("tel:")||s.target.isContentEditable)return!1;try{i=new URL(t)}catch(n){try{i=new URL(t,e)}catch(r){return!0}}return i.host===e.host&&i.protocol===e.protocol&&i.pathname===e.pathname&&i.search===e.search?i.hash===""&&!i.href.endsWith("#"):i.protocol.startsWith("http")},markPhxChildDestroyed(s){this.isPhxChild(s)&&s.setAttribute(q,""),this.putPrivate(s,"destroyed",!0)},findPhxChildrenInFragment(s,e){let t=document.createElement("template");return t.innerHTML=s,this.findPhxChildren(t.content,e)},isIgnored(s,e){return(s.getAttribute(e)||s.getAttribute("data-phx-update"))==="ignore"},isPhxUpdate(s,e,t){return s.getAttribute&&t.indexOf(s.getAttribute(e))>=0},findPhxSticky(s){return this.all(s,`[${Qe}]`)},findPhxChildren(s,e){return this.all(s,`${he}[${ne}="${e}"]`)},findExistingParentCIDs(s,e){let t=new Set,i=new Set;return e.forEach(n=>{this.all(document,`[${le}="${s}"][${K}="${n}"]`).forEach(r=>{t.add(n),this.all(r,`[${le}="${s}"][${K}]`).map(o=>parseInt(o.getAttribute(K))).forEach(o=>i.add(o))})}),i.forEach(n=>t.delete(n)),t},private(s,e){return s[te]&&s[te][e]},deletePrivate(s,e){s[te]&&delete s[te][e]},putPrivate(s,e,t){s[te]||(s[te]={}),s[te][e]=t},updatePrivate(s,e,t,i){let n=this.private(s,e);n===void 0?this.putPrivate(s,e,i(t)):this.putPrivate(s,e,i(n))},syncPendingAttrs(s,e){s.hasAttribute(N)&&(dt.forEach(t=>{s.classList.contains(t)&&e.classList.add(t)}),Ft.filter(t=>s.hasAttribute(t)).forEach(t=>{e.setAttribute(t,s.getAttribute(t))}))},copyPrivates(s,e){e[te]&&(s[te]=e[te])},putTitle(s){let e=document.querySelector("title");if(e){let{prefix:t,suffix:i,default:n}=e.dataset,r=typeof s!="string"||s.trim()==="";if(r&&typeof n!="string")return;let o=r?n:s;document.title=`${t||""}${o||""}${i||""}`}else document.title=s},debounce(s,e,t,i,n,r,o,a){let l=s.getAttribute(t),c=s.getAttribute(n);l===""&&(l=i),c===""&&(c=r);let d=l||c;switch(d){case null:return a();case"blur":this.incCycle(s,"debounce-blur-cycle",()=>{o()&&a()}),this.once(s,"debounce-blur")&&s.addEventListener("blur",()=>this.triggerCycle(s,"debounce-blur-cycle"));return;default:let p=parseInt(d),m=()=>c?this.deletePrivate(s,je):a(),g=this.incCycle(s,Be,m);if(isNaN(p))return w(`invalid throttle/debounce value: ${d}`);if(c){let v=!1;if(e.type==="keydown"){let E=this.private(s,Nt);this.putPrivate(s,Nt,e.key),v=E!==e.key}if(!v&&this.private(s,je))return!1;{a();let E=setTimeout(()=>{o()&&this.triggerCycle(s,Be)},p);this.putPrivate(s,je,E)}}else setTimeout(()=>{o()&&this.triggerCycle(s,Be,g)},p);let u=s.form;u&&this.once(u,"bind-debounce")&&u.addEventListener("submit",()=>{Array.from(new FormData(u).entries(),([v])=>{let E=u.elements.namedItem(v),M=E instanceof RadioNodeList?E[0]:E;M&&(this.incCycle(M,Be),this.deletePrivate(M,je))})}),this.once(s,"bind-debounce")&&s.addEventListener("blur",()=>{clearTimeout(this.private(s,je)),this.triggerCycle(s,Be)})}},triggerCycle(s,e,t){let[i,n]=this.private(s,e);t||(t=i),t===i&&(this.incCycle(s,e),n())},once(s,e){return this.private(s,e)===!0?!1:(this.putPrivate(s,e,!0),!0)},incCycle(s,e,t=function(){}){let[i]=this.private(s,e)||[0,t];return i++,this.putPrivate(s,e,[i,t]),i},maintainPrivateHooks(s,e,t,i){s.hasAttribute&&s.hasAttribute("data-phx-hook")&&!e.hasAttribute("data-phx-hook")&&e.setAttribute("data-phx-hook",s.getAttribute("data-phx-hook")),e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute(i))&&e.setAttribute("data-phx-hook","Phoenix.InfiniteScroll")},putCustomElHook(s,e){s.isConnected?s.setAttribute("data-phx-hook",""):console.error(` + hook attached to non-connected DOM element + ensure you are calling createHook within your connectedCallback. ${s.outerHTML} + `),this.putPrivate(s,"custom-el-hook",e)},getCustomElHook(s){return this.private(s,"custom-el-hook")},isUsedInput(s){return s.nodeType===Node.ELEMENT_NODE&&(this.private(s,we)||this.private(s,Pe))},resetForm(s){Array.from(s.elements).forEach(e=>{this.deletePrivate(e,we),this.deletePrivate(e,Pe)})},isPhxChild(s){return s.getAttribute&&s.getAttribute(ne)},isPhxSticky(s){return s.getAttribute&&s.getAttribute(Qe)!==null},isChildOfAny(s,e){return!!e.find(t=>t.contains(s))},firstPhxChild(s){return this.isPhxChild(s)?s:this.all(s,`[${ne}]`)[0]},isPortalTemplate(s){return s.tagName==="TEMPLATE"&&s.hasAttribute($e)},closestViewEl(s){let e=s.closest(`[${re}],${he}`);return e?e.hasAttribute(re)?this.byId(e.getAttribute(re)):e.hasAttribute(q)?e:null:null},dispatchEvent(s,e,t={}){let i=!0;s.nodeName==="INPUT"&&s.type==="file"&&e==="click"&&(i=!1);let o={bubbles:t.bubbles===void 0?i:!!t.bubbles,cancelable:!0,detail:t.detail||{}},a=e==="click"?new MouseEvent("click",o):new CustomEvent(e,o);s.dispatchEvent(a)},cloneNode(s,e){if(typeof e=="undefined")return s.cloneNode(!0);{let t=s.cloneNode(!1);return t.innerHTML=e,t}},mergeAttrs(s,e,t={}){var a;let i=new Set(t.exclude||[]),n=t.isIgnored,r=e.attributes;for(let l=r.length-1;l>=0;l--){let c=r[l].name;if(i.has(c)){if(c==="value"){let d=(a=e.value)!=null?a:e.getAttribute(c);s.value===d&&s.setAttribute("value",e.getAttribute(c))}}else{let d=e.getAttribute(c);s.getAttribute(c)!==d&&(!n||n&&c.startsWith("data-"))&&s.setAttribute(c,d)}}let o=s.attributes;for(let l=o.length-1;l>=0;l--){let c=o[l].name;n?c.startsWith("data-")&&!e.hasAttribute(c)&&!Ft.includes(c)&&s.removeAttribute(c):e.hasAttribute(c)||s.removeAttribute(c)}},mergeFocusedInput(s,e){s instanceof HTMLSelectElement||Ce.mergeAttrs(s,e,{exclude:["value"]}),e.readOnly?s.setAttribute("readonly",!0):s.removeAttribute("readonly")},hasSelectionRange(s){return s.setSelectionRange&&(s.type==="text"||s.type==="textarea")},restoreFocus(s,e,t){if(s instanceof HTMLSelectElement&&s.focus(),!Ce.isTextualInput(s))return;s.matches(":focus")||s.focus(),this.hasSelectionRange(s)&&s.setSelectionRange(e,t)},isFormInput(s){return s.localName&&customElements.get(s.localName)?customElements.get(s.localName).formAssociated:/^(?:input|select|textarea)$/i.test(s.tagName)&&s.type!=="button"},syncAttrsToProps(s){s instanceof HTMLInputElement&&vt.indexOf(s.type.toLocaleLowerCase())>=0&&(s.checked=s.getAttribute("checked")!==null)},isTextualInput(s){return si.indexOf(s.type)>=0},isNowTriggerFormExternal(s,e){return s.getAttribute&&s.getAttribute(e)!==null&&document.body.contains(s)},cleanChildNodes(s,e){if(Ce.isPhxUpdate(s,e,["append","prepend",Ue])){let t=[];s.childNodes.forEach(i=>{i.id||(!(i.nodeType===Node.TEXT_NODE&&i.nodeValue.trim()==="")&&i.nodeType!==Node.COMMENT_NODE&&w(`only HTML element tags with an id are allowed inside containers with phx-update. + +removing illegal node: "${(i.outerHTML||i.nodeValue).trim()}" + +`),t.push(i))}),t.forEach(i=>i.remove())}},replaceRootContainer(s,e,t){let i=new Set(["id",q,se,De,Q]);if(s.tagName.toLowerCase()===e.toLowerCase())return Array.from(s.attributes).filter(n=>!i.has(n.name.toLowerCase())).forEach(n=>s.removeAttribute(n.name)),Object.keys(t).filter(n=>!i.has(n.toLowerCase())).forEach(n=>s.setAttribute(n,t[n])),s;{let n=document.createElement(e);return Object.keys(t).forEach(r=>n.setAttribute(r,t[r])),i.forEach(r=>n.setAttribute(r,s.getAttribute(r))),n.innerHTML=s.innerHTML,s.replaceWith(n),n}},getSticky(s,e,t){let i=(Ce.private(s,"sticky")||[]).find(([n])=>e===n);if(i){let[n,r,o]=i;return o}else return typeof t=="function"?t():t},deleteSticky(s,e){this.updatePrivate(s,"sticky",[],t=>t.filter(([i,n])=>i!==e))},putSticky(s,e,t){let i=t(s);this.updatePrivate(s,"sticky",[],n=>{let r=n.findIndex(([o])=>e===o);return r>=0?n[r]=[e,t,i]:n.push([e,t,i]),n})},applyStickyOperations(s){let e=Ce.private(s,"sticky");e&&e.forEach(([t,i,n])=>this.putSticky(s,t,i))},isLocked(s){return s.hasAttribute&&s.hasAttribute(C)},attributeIgnored(s,e){return e.some(t=>s.name==t||t==="*"||t.includes("*")&&s.name.match(t)!=null)}},h=Ce;var fe=class{static isActive(e,t){let i=t._phxRef===void 0,r=e.getAttribute(Ge).split(",").indexOf(x.genFileRef(t))>=0;return t.size>0&&(i||r)}static isPreflighted(e,t){return e.getAttribute(Le).split(",").indexOf(x.genFileRef(t))>=0&&this.isActive(e,t)}static isPreflightInProgress(e){return e._preflightInProgress===!0}static markPreflightInProgress(e){e._preflightInProgress=!0}constructor(e,t,i,n){this.ref=x.genFileRef(t),this.fileEl=e,this.file=t,this.view=i,this.meta=null,this._isCancelled=!1,this._isDone=!1,this._progress=0,this._lastProgressSent=-1,this._onDone=function(){},this._onElUpdated=this.onElUpdated.bind(this),this.fileEl.addEventListener(Oe,this._onElUpdated),this.autoUpload=n}metadata(){return this.meta}progress(e){this._progress=Math.floor(e),this._progress>this._lastProgressSent&&(this._progress>=100?(this._progress=100,this._lastProgressSent=100,this._isDone=!0,this.view.pushFileProgress(this.fileEl,this.ref,100,()=>{x.untrackFile(this.fileEl,this.file),this._onDone()})):(this._lastProgressSent=this._progress,this.view.pushFileProgress(this.fileEl,this.ref,this._progress)))}isCancelled(){return this._isCancelled}cancel(){this.file._preflightInProgress=!1,this._isCancelled=!0,this._isDone=!0,this._onDone()}isDone(){return this._isDone}error(e="failed"){this.fileEl.removeEventListener(Oe,this._onElUpdated),this.view.pushFileProgress(this.fileEl,this.ref,{error:e}),this.isAutoUpload()||x.clearFiles(this.fileEl)}isAutoUpload(){return this.autoUpload}onDone(e){this._onDone=()=>{this.fileEl.removeEventListener(Oe,this._onElUpdated),e()}}onElUpdated(){this.fileEl.getAttribute(Ge).split(",").indexOf(this.ref)===-1&&(x.untrackFile(this.fileEl,this.file),this.cancel())}toPreflightPayload(){return{last_modified:this.file.lastModified,name:this.file.name,relative_path:this.file.webkitRelativePath,size:this.file.size,type:this.file.type,ref:this.ref,meta:typeof this.file.meta=="function"?this.file.meta():void 0}}uploader(e){if(this.meta.uploader){let t=e[this.meta.uploader]||w(`no uploader configured for ${this.meta.uploader}`);return{name:this.meta.uploader,callback:t}}else return{name:"channel",callback:yi}}zipPostFlight(e){this.meta=e.entries[this.ref],this.meta||w(`no preflight upload response returned with ref ${this.ref}`,{input:this.fileEl,response:e})}};var Wi=0,x=class s{static genFileRef(e){let t=e._phxRef;return t!==void 0?t:(e._phxRef=(Wi++).toString(),e._phxRef)}static getEntryDataURL(e,t,i){let n=this.activeFiles(e).find(r=>this.genFileRef(r)===t);i(URL.createObjectURL(n))}static hasUploadsInProgress(e){let t=0;return h.findUploadInputs(e).forEach(i=>{i.getAttribute(Le)!==i.getAttribute(ti)&&t++}),t>0}static serializeUploads(e){let t=this.activeFiles(e),i={};return t.forEach(n=>{let r={path:e.name},o=e.getAttribute(G);i[o]=i[o]||[],r.ref=this.genFileRef(n),r.last_modified=n.lastModified,r.name=n.name||r.ref,r.relative_path=n.webkitRelativePath,r.type=n.type,r.size=n.size,typeof n.meta=="function"&&(r.meta=n.meta()),i[o].push(r)}),i}static clearFiles(e){e.value=null,e.removeAttribute(G),h.putPrivate(e,"files",[])}static untrackFile(e,t){h.putPrivate(e,"files",h.private(e,"files").filter(i=>!Object.is(i,t)))}static trackFiles(e,t,i){if(e.getAttribute("multiple")!==null){let n=t.filter(r=>!this.activeFiles(e).find(o=>Object.is(o,r)));h.updatePrivate(e,"files",[],r=>r.concat(n)),e.value=null}else i&&i.files.length>0&&(e.files=i.files),h.putPrivate(e,"files",t)}static activeFileInputs(e){let t=h.findUploadInputs(e);return Array.from(t).filter(i=>i.files&&this.activeFiles(i).length>0)}static activeFiles(e){return(h.private(e,"files")||[]).filter(t=>fe.isActive(e,t))}static inputsAwaitingPreflight(e){let t=h.findUploadInputs(e);return Array.from(t).filter(i=>this.filesAwaitingPreflight(i).length>0)}static filesAwaitingPreflight(e){return this.activeFiles(e).filter(t=>!fe.isPreflighted(e,t)&&!fe.isPreflightInProgress(t))}static markPreflightInProgress(e){e.forEach(t=>fe.markPreflightInProgress(t.file))}constructor(e,t,i){this.autoUpload=h.isAutoUpload(e),this.view=t,this.onComplete=i,this._entries=Array.from(s.filesAwaitingPreflight(e)||[]).map(n=>new fe(e,n,t,this.autoUpload)),s.markPreflightInProgress(this._entries),this.numEntriesInProgress=this._entries.length}isAutoUpload(){return this.autoUpload}entries(){return this._entries}initAdapterUpload(e,t,i){this._entries=this._entries.map(r=>(r.isCancelled()?(this.numEntriesInProgress--,this.numEntriesInProgress===0&&this.onComplete()):(r.zipPostFlight(e),r.onDone(()=>{this.numEntriesInProgress--,this.numEntriesInProgress===0&&this.onComplete()})),r));let n=this._entries.reduce((r,o)=>{if(!o.meta)return r;let{name:a,callback:l}=o.uploader(i.uploaders);return r[a]=r[a]||{callback:l,entries:[]},r[a].entries.push(o),r},{});for(let r in n){let{callback:o,entries:a}=n[r];o(a,t,e,i)}}};var Ki={anyOf(s,e){return e.find(t=>s instanceof t)},isFocusable(s,e){return s instanceof HTMLAnchorElement&&s.rel!=="ignore"||s instanceof HTMLAreaElement&&s.href!==void 0||!s.disabled&&this.anyOf(s,[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement,HTMLButtonElement])||s instanceof HTMLIFrameElement||s.tabIndex>=0&&s.getAttribute("aria-hidden")!=="true"||!e&&s.getAttribute("tabindex")!==null&&s.getAttribute("aria-hidden")!=="true"},attemptFocus(s,e){if(this.isFocusable(s,e))try{s.focus()}catch(t){}return!!document.activeElement&&document.activeElement.isSameNode(s)},focusFirstInteractive(s){let e=s.firstElementChild;for(;e;){if(this.attemptFocus(e,!0)||this.focusFirstInteractive(e))return!0;e=e.nextElementSibling}},focusFirst(s){let e=s.firstElementChild;for(;e;){if(this.attemptFocus(e)||this.focusFirst(e))return!0;e=e.nextElementSibling}},focusLast(s){let e=s.lastElementChild;for(;e;){if(this.attemptFocus(e)||this.focusLast(e))return!0;e=e.previousElementSibling}}},V=Ki;var wi={LiveFileUpload:{activeRefs(){return this.el.getAttribute(Ge)},preflightedRefs(){return this.el.getAttribute(Le)},mounted(){this.js().ignoreAttributes(this.el,["value"]),this.preflightedWas=this.preflightedRefs()},updated(){let s=this.preflightedRefs();this.preflightedWas!==s&&(this.preflightedWas=s,s===""&&this.__view().cancelSubmit(this.el.form)),this.activeRefs()===""&&(this.el.value=null),this.el.dispatchEvent(new CustomEvent(Oe))}},LiveImgPreview:{mounted(){this.ref=this.el.getAttribute("data-phx-entry-ref"),this.inputEl=document.getElementById(this.el.getAttribute(G)),x.getEntryDataURL(this.inputEl,this.ref,s=>{this.url=s,this.el.src=s})},destroyed(){URL.revokeObjectURL(this.url)}},FocusWrap:{mounted(){this.focusStart=this.el.firstElementChild,this.focusEnd=this.el.lastElementChild,this.focusStart.addEventListener("focus",s=>{if(!s.relatedTarget||!this.el.contains(s.relatedTarget)){let e=s.target.nextElementSibling;V.attemptFocus(e)||V.focusFirst(e)}else V.focusLast(this.el)}),this.focusEnd.addEventListener("focus",s=>{if(!s.relatedTarget||!this.el.contains(s.relatedTarget)){let e=s.target.previousElementSibling;V.attemptFocus(e)||V.focusLast(e)}else V.focusFirst(this.el)}),this.el.contains(document.activeElement)||(this.el.addEventListener("phx:show-end",()=>this.el.focus()),window.getComputedStyle(this.el).display!=="none"&&V.focusFirst(this.el))}}},Pi=s=>["HTML","BODY"].indexOf(s.nodeName.toUpperCase())>=0?null:["scroll","auto"].indexOf(getComputedStyle(s).overflowY)>=0?s:Pi(s.parentElement),_i=s=>s?s.scrollTop:document.documentElement.scrollTop||document.body.scrollTop,Bt=s=>s?s.getBoundingClientRect().bottom:window.innerHeight||document.documentElement.clientHeight,jt=s=>s?s.getBoundingClientRect().top:0,qi=(s,e)=>{let t=s.getBoundingClientRect();return Math.ceil(t.top)>=jt(e)&&Math.ceil(t.left)>=0&&Math.floor(t.top)<=Bt(e)},Gi=(s,e)=>{let t=s.getBoundingClientRect();return Math.ceil(t.bottom)>=jt(e)&&Math.ceil(t.left)>=0&&Math.floor(t.bottom)<=Bt(e)},Si=(s,e)=>{let t=s.getBoundingClientRect();return Math.ceil(t.top)>=jt(e)&&Math.ceil(t.left)>=0&&Math.floor(t.top)<=Bt(e)};wi.InfiniteScroll={mounted(){this.scrollContainer=Pi(this.el);let s=_i(this.scrollContainer),e=!1,t=500,i=null,n=this.throttle(t,(a,l)=>{i=()=>!0,this.liveSocket.js().push(this.el,a,{value:{id:l.id,_overran:!0},callback:()=>{i=null}})}),r=this.throttle(t,(a,l)=>{i=()=>l.scrollIntoView({block:"start"}),this.liveSocket.js().push(this.el,a,{value:{id:l.id},callback:()=>{i=null,window.requestAnimationFrame(()=>{Si(l,this.scrollContainer)||l.scrollIntoView({block:"start"})})}})}),o=this.throttle(t,(a,l)=>{i=()=>l.scrollIntoView({block:"end"}),this.liveSocket.js().push(this.el,a,{value:{id:l.id},callback:()=>{i=null,window.requestAnimationFrame(()=>{Si(l,this.scrollContainer)||l.scrollIntoView({block:"end"})})}})});this.onScroll=a=>{let l=_i(this.scrollContainer);if(i)return s=l,i();let c=this.findOverrunTarget(),d=this.el.getAttribute(this.liveSocket.binding("viewport-top")),p=this.el.getAttribute(this.liveSocket.binding("viewport-bottom")),m=this.el.lastElementChild,g=this.el.firstElementChild,u=ls;u&&d&&!e&&c.top>=0?(e=!0,n(d,g)):v&&e&&c.top<=0&&(e=!1),d&&u&&qi(g,this.scrollContainer)?r(d,g):p&&v&&Gi(m,this.scrollContainer)&&o(p,m),s=l},this.scrollContainer?this.scrollContainer.addEventListener("scroll",this.onScroll):window.addEventListener("scroll",this.onScroll)},destroyed(){this.scrollContainer?this.scrollContainer.removeEventListener("scroll",this.onScroll):window.removeEventListener("scroll",this.onScroll)},throttle(s,e){let t=0,i;return(...n)=>{let r=Date.now(),o=s-(r-t);o<=0||o>s?(i&&(clearTimeout(i),i=null),t=r,e(...n)):i||(i=setTimeout(()=>{t=Date.now(),i=null,e(...n)},o))}},findOverrunTarget(){let s,e=this.el.getAttribute(this.liveSocket.binding(ii));if(e){let t=document.getElementById(e);if(t)s=t.getBoundingClientRect();else throw new Error("did not find element with id "+e)}else s=this.el.getBoundingClientRect();return s}};var ki=wi;var ye=class{static onUnlock(e,t){if(!h.isLocked(e)&&!e.closest(`[${C}]`))return t();let i=e.closest(`[${C}]`),n=i.closest(`[${C}]`).getAttribute(C);i.addEventListener(`phx:undo-lock:${n}`,()=>{t()},{once:!0})}constructor(e){this.el=e,this.loadingRef=e.hasAttribute(ge)?parseInt(e.getAttribute(ge),10):null,this.lockRef=e.hasAttribute(C)?parseInt(e.getAttribute(C),10):null}maybeUndo(e,t,i){if(!this.isWithin(e)){h.updatePrivate(this.el,Ct,[],n=>(n.push(e),n));return}this.undoLocks(e,t,i),this.undoLoading(e,t),h.updatePrivate(this.el,Ct,[],n=>n.filter(r=>{let o={detail:{ref:r,event:t},bubbles:!0,cancelable:!1};return this.loadingRef&&this.loadingRef>r&&this.el.dispatchEvent(new CustomEvent(`phx:undo-loading:${r}`,o)),this.lockRef&&this.lockRef>r&&this.el.dispatchEvent(new CustomEvent(`phx:undo-lock:${r}`,o)),r>e})),this.isFullyResolvedBy(e)&&this.el.removeAttribute(N)}isWithin(e){return!(this.loadingRef!==null&&this.loadingRef>e&&this.lockRef!==null&&this.lockRef>e)}undoLocks(e,t,i){if(!this.isLockUndoneBy(e))return;let n=h.private(this.el,C);n&&(i(n),h.deletePrivate(this.el,C)),this.el.removeAttribute(C);let r={detail:{ref:e,event:t},bubbles:!0,cancelable:!1};this.el.dispatchEvent(new CustomEvent(`phx:undo-lock:${this.lockRef}`,r))}undoLoading(e,t){if(!this.isLoadingUndoneBy(e)){this.canUndoLoading(e)&&this.el.classList.contains("phx-submit-loading")&&this.el.classList.remove("phx-change-loading");return}if(this.canUndoLoading(e)){this.el.removeAttribute(ge);let i=this.el.getAttribute(be),n=this.el.getAttribute(Ze);n!==null&&(this.el.readOnly=n==="true",this.el.removeAttribute(Ze)),i!==null&&(this.el.disabled=i==="true",this.el.removeAttribute(be));let r=this.el.getAttribute(Me);r!==null&&(this.el.textContent=r,this.el.removeAttribute(Me));let o={detail:{ref:e,event:t},bubbles:!0,cancelable:!1};this.el.dispatchEvent(new CustomEvent(`phx:undo-loading:${this.loadingRef}`,o))}dt.forEach(i=>{(i!=="phx-submit-loading"||this.canUndoLoading(e))&&h.removeClass(this.el,i)})}isLoadingUndoneBy(e){return this.loadingRef===null?!1:this.loadingRef<=e}isLockUndoneBy(e){return this.lockRef===null?!1:this.lockRef<=e}isFullyResolvedBy(e){return(this.loadingRef===null||this.loadingRef<=e)&&(this.lockRef===null||this.lockRef<=e)}canUndoLoading(e){return this.lockRef===null||this.lockRef<=e}};var nt=class{constructor(e,t,i){let n=new Set,r=new Set([...t.children].map(a=>a.id)),o=[];Array.from(e.children).forEach(a=>{if(a.id&&(n.add(a.id),r.has(a.id))){let l=a.previousElementSibling&&a.previousElementSibling.id;o.push({elementId:a.id,previousElementId:l})}}),this.containerId=t.id,this.updateType=i,this.elementsToModify=o,this.elementIdsToAdd=[...r].filter(a=>!n.has(a))}perform(){let e=h.byId(this.containerId);e&&(this.elementsToModify.forEach(t=>{t.previousElementId?ue(document.getElementById(t.previousElementId),i=>{ue(document.getElementById(t.elementId),n=>{n.previousElementSibling&&n.previousElementSibling.id==i.id||i.insertAdjacentElement("afterend",n)})}):ue(document.getElementById(t.elementId),i=>{i.previousElementSibling==null||e.insertAdjacentElement("afterbegin",i)})}),this.updateType=="prepend"&&this.elementIdsToAdd.reverse().forEach(t=>{ue(document.getElementById(t),i=>e.insertAdjacentElement("afterbegin",i))}))}};var Ti=11;function zi(s,e){var t=e.attributes,i,n,r,o,a;if(!(e.nodeType===Ti||s.nodeType===Ti)){for(var l=t.length-1;l>=0;l--)i=t[l],n=i.name,r=i.namespaceURI,o=i.value,r?(n=i.localName||n,a=s.getAttributeNS(r,n),a!==o&&(i.prefix==="xmlns"&&(n=i.name),s.setAttributeNS(r,n,o))):(a=s.getAttribute(n),a!==o&&s.setAttribute(n,o));for(var c=s.attributes,d=c.length-1;d>=0;d--)i=c[d],n=i.name,r=i.namespaceURI,r?(n=i.localName||n,e.hasAttributeNS(r,n)||s.removeAttributeNS(r,n)):e.hasAttribute(n)||s.removeAttribute(n)}}var At,Yi="http://www.w3.org/1999/xhtml",B=typeof document=="undefined"?void 0:document,Qi=!!B&&"content"in B.createElement("template"),Zi=!!B&&B.createRange&&"createContextualFragment"in B.createRange();function en(s){var e=B.createElement("template");return e.innerHTML=s,e.content.childNodes[0]}function tn(s){At||(At=B.createRange(),At.selectNode(B.body));var e=At.createContextualFragment(s);return e.childNodes[0]}function nn(s){var e=B.createElement("body");return e.innerHTML=s,e.childNodes[0]}function sn(s){return s=s.trim(),Qi?en(s):Zi?tn(s):nn(s)}function _t(s,e){var t=s.nodeName,i=e.nodeName,n,r;return t===i?!0:(n=t.charCodeAt(0),r=i.charCodeAt(0),n<=90&&r>=97?t===i.toUpperCase():r<=90&&n>=97?i===t.toUpperCase():!1)}function rn(s,e){return!e||e===Yi?B.createElement(s):B.createElementNS(e,s)}function on(s,e){for(var t=s.firstChild;t;){var i=t.nextSibling;e.appendChild(t),t=i}return e}function Jt(s,e,t){s[t]!==e[t]&&(s[t]=e[t],s[t]?s.setAttribute(t,""):s.removeAttribute(t))}var Ci={OPTION:function(s,e){var t=s.parentNode;if(t){var i=t.nodeName.toUpperCase();i==="OPTGROUP"&&(t=t.parentNode,i=t&&t.nodeName.toUpperCase()),i==="SELECT"&&!t.hasAttribute("multiple")&&(s.hasAttribute("selected")&&!e.selected&&(s.setAttribute("selected","selected"),s.removeAttribute("selected")),t.selectedIndex=-1)}Jt(s,e,"selected")},INPUT:function(s,e){Jt(s,e,"checked"),Jt(s,e,"disabled"),s.value!==e.value&&(s.value=e.value),e.hasAttribute("value")||s.removeAttribute("value")},TEXTAREA:function(s,e){var t=e.value;s.value!==t&&(s.value=t);var i=s.firstChild;if(i){var n=i.nodeValue;if(n==t||!t&&n==s.placeholder)return;i.nodeValue=t}},SELECT:function(s,e){if(!e.hasAttribute("multiple")){for(var t=-1,i=0,n=s.firstChild,r,o;n;)if(o=n.nodeName&&n.nodeName.toUpperCase(),o==="OPTGROUP")r=n,n=r.firstChild,n||(n=r.nextSibling,r=null);else{if(o==="OPTION"){if(n.hasAttribute("selected")){t=i;break}i++}n=n.nextSibling,!n&&r&&(n=r.nextSibling,r=null)}s.selectedIndex=t}}},st=1,xi=11,Ri=3,Ii=8;function Ae(){}function an(s){if(s)return s.getAttribute&&s.getAttribute("id")||s.id}function ln(s){return function(t,i,n){if(n||(n={}),typeof i=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"){var r=i;i=B.createElement("html"),i.innerHTML=r}else if(t.nodeName==="BODY"){var o=i;i=B.createElement("html"),i.innerHTML=o;var a=i.querySelector("body");a&&(i=a)}else i=sn(i);else i.nodeType===xi&&(i=i.firstElementChild);var l=n.getNodeKey||an,c=n.onBeforeNodeAdded||Ae,d=n.onNodeAdded||Ae,p=n.onBeforeElUpdated||Ae,m=n.onElUpdated||Ae,g=n.onBeforeNodeDiscarded||Ae,u=n.onNodeDiscarded||Ae,v=n.onBeforeElChildrenUpdated||Ae,E=n.skipFromChildren||Ae,M=n.addChild||function(y,A){return y.appendChild(A)},j=n.childrenOnly===!0,F=Object.create(null),_=[];function k(y){_.push(y)}function I(y,A){if(y.nodeType===st)for(var L=y.firstChild;L;){var P=void 0;A&&(P=l(L))?k(P):(u(L),L.firstChild&&I(L,A)),L=L.nextSibling}}function Y(y,A,L){g(y)!==!1&&(A&&A.removeChild(y),u(y),I(y,L))}function f(y){if(y.nodeType===st||y.nodeType===xi)for(var A=y.firstChild;A;){var L=l(A);L&&(F[L]=A),f(A),A=A.nextSibling}}f(t);function b(y){d(y);for(var A=y.firstChild;A;){var L=A.nextSibling,P=l(A);if(P){var T=F[P];T&&_t(A,T)?(A.parentNode.replaceChild(T,A),J(T,A)):b(A)}else b(A);A=L}}function U(y,A,L){for(;A;){var P=A.nextSibling;(L=l(A))?k(L):Y(A,y,!0),A=P}}function J(y,A,L){var P=l(A);if(P&&delete F[P],!L){var T=p(y,A);if(T===!1||(T instanceof HTMLElement&&(y=T,f(y)),s(y,A),m(y),v(y,A)===!1))return}y.nodeName!=="TEXTAREA"?D(y,A):Ci.TEXTAREA(y,A)}function D(y,A){var L=E(y,A),P=A.firstChild,T=y.firstChild,Re,oe,Ie,at,pe;e:for(;P;){for(at=P.nextSibling,Re=l(P);!L&&T;){if(Ie=T.nextSibling,P.isSameNode&&P.isSameNode(T)){P=at,T=Ie;continue e}oe=l(T);var lt=T.nodeType,me=void 0;if(lt===P.nodeType&&(lt===st?(Re?Re!==oe&&((pe=F[Re])?Ie===pe?me=!1:(y.insertBefore(pe,T),oe?k(oe):Y(T,y,!0),T=pe,oe=l(T)):me=!1):oe&&(me=!1),me=me!==!1&&_t(T,P),me&&J(T,P)):(lt===Ri||lt==Ii)&&(me=!0,T.nodeValue!==P.nodeValue&&(T.nodeValue=P.nodeValue))),me){P=at,T=Ie;continue e}oe?k(oe):Y(T,y,!0),T=Ie}if(Re&&(pe=F[Re])&&_t(pe,P))L||M(y,pe),J(pe,P);else{var Tt=c(P);Tt!==!1&&(Tt&&(P=Tt),P.actualize&&(P=P.actualize(y.ownerDocument||B)),M(y,P),b(P))}P=at,T=Ie}U(y,T,oe);var Gt=Ci[y.nodeName];Gt&&Gt(y,A)}var H=t,W=H.nodeType,qt=i.nodeType;if(!j){if(W===st)qt===st?_t(t,i)||(u(t),H=on(t,rn(i.nodeName,i.namespaceURI))):H=i;else if(W===Ri||W===Ii){if(qt===W)return H.nodeValue!==i.nodeValue&&(H.nodeValue=i.nodeValue),H;H=i}}if(H===i)u(t);else{if(i.isSameNode&&i.isSameNode(H))return;if(J(H,i,j),_)for(var Pt=0,Mi=_.length;Pti(...t))}trackAfter(e,...t){this.callbacks[`after${e}`].forEach(i=>i(...t))}markPrunableContentForRemoval(){let e=this.liveSocket.binding(Fe);h.all(this.container,`[${e}=append] > *, [${e}=prepend] > *`,t=>{t.setAttribute(xt,"")})}perform(e){let{view:t,liveSocket:i,html:n,container:r}=this,o=this.targetContainer;if(this.isCIDPatch()&&!this.targetContainer)return;if(this.isCIDPatch()){let _=o.closest(`[${C}]`);if(_){let k=h.private(_,C);k&&(o=k.querySelector(`[data-phx-component="${this.targetCID}"]`))}}let a=i.getActiveElement(),{selectionStart:l,selectionEnd:c}=a&&h.hasSelectionRange(a)?a:{},d=i.binding(Fe),p=i.binding(ze),m=i.binding(Ye),g=i.binding(ni),u=[],v=[],E=[],M=[],j=null,F=(_,k,I=this.withChildren)=>{let Y={childrenOnly:_.getAttribute(K)===null&&!I,getNodeKey:f=>h.isPhxDestroyed(f)?null:e?f.id:f.id||f.getAttribute&&f.getAttribute(gt),skipFromChildren:f=>f.getAttribute(d)===Ue,addChild:(f,b)=>{let{ref:U,streamAt:J}=this.getStreamInsert(b);if(U===void 0)return f.appendChild(b);if(this.setStreamRef(b,U),J===0)f.insertAdjacentElement("afterbegin",b);else if(J===-1){let D=f.lastElementChild;if(D&&!D.hasAttribute(Xe)){let H=Array.from(f.children).find(W=>!W.hasAttribute(Xe));f.insertBefore(b,H)}else f.appendChild(b)}else if(J>0){let D=Array.from(f.children)[J];f.insertBefore(b,D)}},onBeforeNodeAdded:f=>{var U;if((U=this.getStreamInsert(f))!=null&&U.updateOnly&&!this.streamComponentRestore[f.id])return!1;h.maintainPrivateHooks(f,f,p,m),this.trackBefore("added",f);let b=f;return this.streamComponentRestore[f.id]&&(b=this.streamComponentRestore[f.id],delete this.streamComponentRestore[f.id],F(b,f,!0)),b},onNodeAdded:f=>{f.getAttribute&&this.maybeReOrderStream(f,!0),h.isPortalTemplate(f)&&M.push(()=>this.teleport(f,F)),f instanceof HTMLImageElement&&f.srcset?f.srcset=f.srcset:f instanceof HTMLVideoElement&&f.autoplay&&f.play(),h.isNowTriggerFormExternal(f,g)&&(j=f),(h.isPhxChild(f)&&t.ownsElement(f)||h.isPhxSticky(f)&&t.ownsElement(f.parentNode))&&this.trackAfter("phxChildAdded",f),f.nodeName==="SCRIPT"&&f.hasAttribute(Ve)&&this.handleRuntimeHook(f,k),u.push(f)},onNodeDiscarded:f=>this.onNodeDiscarded(f),onBeforeNodeDiscarded:f=>{if(f.getAttribute&&f.getAttribute(xt)!==null)return!0;if(f.parentElement!==null&&f.id&&h.isPhxUpdate(f.parentElement,d,[Ue,"append","prepend"])||f.getAttribute&&f.getAttribute(re)||this.maybePendingRemove(f)||this.skipCIDSibling(f))return!1;if(h.isPortalTemplate(f)){let b=document.getElementById(f.content.firstElementChild.id);b&&(b.remove(),Y.onNodeDiscarded(b),this.view.dropPortalElementId(b.id))}return!0},onElUpdated:f=>{h.isNowTriggerFormExternal(f,g)&&(j=f),v.push(f),this.maybeReOrderStream(f,!1)},onBeforeElUpdated:(f,b)=>{if(f.id&&f.isSameNode(_)&&f.id!==b.id)return Y.onNodeDiscarded(f),f.replaceWith(b),Y.onNodeAdded(b);if(h.syncPendingAttrs(f,b),h.maintainPrivateHooks(f,b,p,m),h.cleanChildNodes(b,d),this.skipCIDSibling(b))return this.maybeReOrderStream(f),!1;if(h.isPhxSticky(f))return[q,se,Q].map(D=>[D,f.getAttribute(D),b.getAttribute(D)]).forEach(([D,H,W])=>{W&&H!==W&&f.setAttribute(D,W)}),!1;if(h.isIgnored(f,d)||f.form&&f.form.isSameNode(j))return this.trackBefore("updated",f,b),h.mergeAttrs(f,b,{isIgnored:h.isIgnored(f,d)}),v.push(f),h.applyStickyOperations(f),!1;if(f.type==="number"&&f.validity&&f.validity.badInput)return!1;let U=a&&f.isSameNode(a)&&h.isFormInput(f),J=U&&this.isChangedSelect(f,b);if(f.hasAttribute(N)){let D=new ye(f);if(D.lockRef&&(!this.undoRef||!D.isLockUndoneBy(this.undoRef))){h.applyStickyOperations(f);let W=f.hasAttribute(C)?h.private(f,C)||f.cloneNode(!0):null;W&&(h.putPrivate(f,C,W),U||(f=W))}}if(h.isPhxChild(b)){let D=f.getAttribute(q);return h.mergeAttrs(f,b,{exclude:[se]}),D!==""&&f.setAttribute(q,D),f.setAttribute(Q,this.rootID),h.applyStickyOperations(f),!1}return this.undoRef&&h.private(b,C)&&h.putPrivate(f,C,h.private(b,C)),h.copyPrivates(b,f),h.isPortalTemplate(b)?(M.push(()=>this.teleport(b,F)),f.innerHTML=b.innerHTML,!1):U&&f.type!=="hidden"&&!J?(this.trackBefore("updated",f,b),h.mergeFocusedInput(f,b),h.syncAttrsToProps(f),v.push(f),h.applyStickyOperations(f),!1):(J&&f.blur(),h.isPhxUpdate(b,d,["append","prepend"])&&E.push(new nt(f,b,b.getAttribute(d))),h.syncAttrsToProps(b),h.applyStickyOperations(b),this.trackBefore("updated",f,b),f)}};rt(_,k,Y)};if(this.trackBefore("added",r),this.trackBefore("updated",r,r),i.time("morphdom",()=>{this.streams.forEach(([k,I,Y,f])=>{I.forEach(([b,U,J,D])=>{this.streamInserts[b]={ref:k,streamAt:U,limit:J,reset:f,updateOnly:D}}),f!==void 0&&h.all(r,`[${Xe}="${k}"]`,b=>{this.removeStreamChildElement(b)}),Y.forEach(b=>{let U=r.querySelector(`[id="${b}"]`);U&&this.removeStreamChildElement(U)})}),e&&h.all(this.container,`[${d}=${Ue}]`).filter(k=>this.view.ownsElement(k)).forEach(k=>{Array.from(k.children).forEach(I=>{this.removeStreamChildElement(I,!0)})}),F(o,n);let _=0;for(;M.length>0&&_<5;){let k=M.slice();M=[],k.forEach(I=>I()),_++}this.view.portalElementIds.forEach(k=>{let I=document.getElementById(k);I&&(document.getElementById(I.getAttribute(Ee))||(I.remove(),this.onNodeDiscarded(I),this.view.dropPortalElementId(k)))})}),i.isDebugEnabled()&&(gi(),vi(this.streamInserts),Array.from(document.querySelectorAll("input[name=id]")).forEach(_=>{_ instanceof HTMLInputElement&&_.form&&console.error(`Detected an input with name="id" inside a form! This will cause problems when patching the DOM. +`,_)})),E.length>0&&i.time("post-morph append/prepend restoration",()=>{E.forEach(_=>_.perform())}),i.silenceEvents(()=>h.restoreFocus(a,l,c)),h.dispatchEvent(document,"phx:update"),u.forEach(_=>this.trackAfter("added",_)),v.forEach(_=>this.trackAfter("updated",_)),this.transitionPendingRemoves(),j){i.unload();let _=h.private(j,"submitter");if(_&&_.name&&o.contains(_)){let k=document.createElement("input");k.type="hidden";let I=_.getAttribute("form");I&&k.setAttribute("form",I),k.name=_.name,k.value=_.value,_.parentElement.insertBefore(k,_)}Object.getPrototypeOf(j).submit.call(j)}return!0}onNodeDiscarded(e){(h.isPhxChild(e)||h.isPhxSticky(e))&&this.liveSocket.destroyViewByEl(e),this.trackAfter("discarded",e)}maybePendingRemove(e){return e.getAttribute&&e.getAttribute(this.phxRemove)!==null?(this.pendingRemoves.push(e),!0):!1}removeStreamChildElement(e,t=!1){!t&&!this.view.ownsElement(e)||(this.streamInserts[e.id]?(this.streamComponentRestore[e.id]=e,e.remove()):this.maybePendingRemove(e)||(e.remove(),this.onNodeDiscarded(e)))}getStreamInsert(e){return(e.id?this.streamInserts[e.id]:{})||{}}setStreamRef(e,t){h.putSticky(e,Xe,i=>i.setAttribute(Xe,t))}maybeReOrderStream(e,t){let{ref:i,streamAt:n,reset:r}=this.getStreamInsert(e);if(n!==void 0&&(this.setStreamRef(e,i),!(!r&&!t)&&e.parentElement)){if(n===0)e.parentElement.insertBefore(e,e.parentElement.firstElementChild);else if(n>0){let o=Array.from(e.parentElement.children),a=o.indexOf(e);if(n>=o.length-1)e.parentElement.appendChild(e);else{let l=o[n];a>n?e.parentElement.insertBefore(e,l):e.parentElement.insertBefore(e,l.nextElementSibling)}}this.maybeLimitStream(e)}}maybeLimitStream(e){let{limit:t}=this.getStreamInsert(e),i=t!==null&&Array.from(e.parentElement.children);t&&t<0&&i.length>t*-1?i.slice(0,i.length+t).forEach(n=>this.removeStreamChildElement(n)):t&&t>=0&&i.length>t&&i.slice(t).forEach(n=>this.removeStreamChildElement(n))}transitionPendingRemoves(){let{pendingRemoves:e,liveSocket:t}=this;e.length>0&&t.transitionRemoves(e,()=>{e.forEach(i=>{let n=h.firstPhxChild(i);n&&t.destroyViewByEl(n),i.remove()}),this.trackAfter("transitionsDiscarded",e)})}isChangedSelect(e,t){return!(e instanceof HTMLSelectElement)||e.multiple?!1:e.options.length!==t.options.length?!0:(t.value=e.value,!e.isEqualNode(t))}isCIDPatch(){return this.cidPatch}skipCIDSibling(e){return e.nodeType===Node.ELEMENT_NODE&&e.hasAttribute(mt)}targetCIDContainer(e){if(!this.isCIDPatch())return;let[t,...i]=h.findComponentNodeList(this.view.id,this.targetCID);return i.length===0&&h.childNodeLength(e)===1?t:t&&t.parentNode}indexOf(e,t){return Array.from(e.children).indexOf(t)}teleport(e,t){let i=e.getAttribute($e),n=document.querySelector(i);if(!n)throw new Error("portal target with selector "+i+" not found");let r=e.content.firstElementChild;if(this.skipCIDSibling(r))return;if(!(r!=null&&r.id))throw new Error("phx-portal template must have a single root element with ID!");let o=document.getElementById(r.id),a;o?(n.contains(o)||n.appendChild(o),a=o):(a=document.createElement(r.tagName),n.appendChild(a)),r.setAttribute(re,this.view.id),r.setAttribute(Ee,e.id),t(a,r,!0),r.removeAttribute(re),r.removeAttribute(Ee),this.view.pushPortalElementId(r.id)}handleRuntimeHook(e,t){let i=e.getAttribute(Ve),n=e.hasAttribute("nonce")?e.getAttribute("nonce"):null;if(e.hasAttribute("nonce")){let o=document.createElement("template");o.innerHTML=t,n=o.content.querySelector(`script[${Ve}="${CSS.escape(i)}"]`).getAttribute("nonce")}let r=document.createElement("script");r.textContent=e.textContent,h.mergeAttrs(r,e,{isIgnored:!1}),n&&(r.nonce=n),e.replaceWith(r),e=r}};var cn=new Set(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),dn=new Set(["'",'"']),Li=(s,e,t)=>{let i=0,n=!1,r,o,a,l,c,d,p=s.match(/^(\s*(?:\s*)*)<([^\s\/>]+)/);if(p===null)throw new Error(`malformed html ${s}`);for(i=p[0].length,r=p[1],a=p[2],l=i,i;i";i++)if(s.charAt(i)==="="){let u=s.slice(i-3,i)===" id";i++;let v=s.charAt(i);if(dn.has(v)){let E=i;for(i++,i;i=r.length+a.length;){let u=s.charAt(m);if(n)u==="-"&&s.slice(m-3,m)===""&&s.slice(m-2,m)==="--")n=!0,m-=3;else{if(u===">")break;m-=1}}o=s.slice(m+1,s.length);let g=Object.keys(e).map(u=>e[u]===!0?u:`${u}="${e[u]}"`).join(" ");if(t){let u=c?` id="${c}"`:"";cn.has(a)?d=`<${a}${u}${g===""?"":" "}${g}/>`:d=`<${a}${u}${g===""?"":" "}${g}>`}else{let u=s.slice(l,m+1);d=`<${a}${g===""?"":" "}${g}${u}`}return[d,r,o]},Ke=class{static extract(e){let{[Xt]:t,[Ut]:i,[$t]:n}=e;return delete e[Xt],delete e[Ut],delete e[$t],{diff:e,title:n,reply:t||null,events:i||[]}}constructor(e,t){this.viewId=e,this.rendered={},this.magicId=0,this.mergeDiff(t)}parentViewId(){return this.viewId}toString(e){let{buffer:t,streams:i}=this.recursiveToString(this.rendered,this.rendered[X],e,!0,{});return{buffer:t,streams:i}}recursiveToString(e,t=e[X],i,n,r){i=i?new Set(i):null;let o={buffer:"",components:t,onlyCids:i,streams:new Set};return this.toOutputBuffer(e,null,o,n,r),{buffer:o.buffer,streams:o.streams}}componentCIDs(e){return Object.keys(e[X]||{}).map(t=>parseInt(t))}isComponentOnlyDiff(e){return e[X]?Object.keys(e).length===1:!1}getComponent(e,t){return e[X][t]}resetRender(e){this.rendered[X][e]&&(this.rendered[X][e].reset=!0)}mergeDiff(e){let t=e[X],i={};if(delete e[X],this.rendered=this.mutableMerge(this.rendered,e),this.rendered[X]=this.rendered[X]||{},t){let n=this.rendered[X];for(let r in t)t[r]=this.cachedFindComponent(r,t[r],n,t,i);for(let r in t)n[r]=t[r];e[X]=t}}cachedFindComponent(e,t,i,n,r){if(r[e])return r[e];{let o,a,l=t[z];if(Z(l)){let c;l>0?c=this.cachedFindComponent(l,n[l],i,n,r):c=i[-l],a=c[z],o=this.cloneMerge(c,t,!0),o[z]=a}else o=t[z]!==void 0||i[e]===void 0?t:this.cloneMerge(i[e],t,!1);return r[e]=o,o}}mutableMerge(e,t){return t[z]!==void 0?t:(this.doMutableMerge(e,t),e)}doMutableMerge(e,t){if(t[R])this.mergeKeyed(e,t);else for(let i in t){let n=t[i],r=e[i];Te(n)&&n[z]===void 0&&Te(r)?this.doMutableMerge(r,n):e[i]=n}e[yt]&&(e.newRender=!0)}clone(e){return"structuredClone"in window?structuredClone(e):JSON.parse(JSON.stringify(e))}mergeKeyed(e,t){let i=this.clone(e);if(Object.entries(t[R]).forEach(([n,r])=>{if(n!==ie)if(Array.isArray(r)){let[o,a]=r;e[R][n]=i[R][o],this.doMutableMerge(e[R][n],a)}else if(typeof r=="number"){let o=r;e[R][n]=i[R][o]}else typeof r=="object"&&(e[R][n]||(e[R][n]={}),this.doMutableMerge(e[R][n],r))}),t[R][ie]delete this.rendered[X][t])}get(){return this.rendered}isNewFingerprint(e={}){return!!e[z]}templateStatic(e,t){return typeof e=="number"?t[e]:e}nextMagicID(){return this.magicId++,`m${this.magicId}-${this.parentViewId()}`}toOutputBuffer(e,t,i,n,r={}){if(e[R])return this.comprehensionToBuffer(e,t,i,n);e[ce]&&(t=e[ce],delete e[ce]);let{[z]:o}=e;o=this.templateStatic(o,t),e[z]=o;let a=e[yt],l=i.buffer;a&&(i.buffer=""),n&&a&&!e.magicId&&(e.newRender=!0,e.magicId=this.nextMagicID()),i.buffer+=o[0];for(let c=1;c0||d.length>0||p)&&(delete e[ke],e[R]={[ie]:0},i.streams.add(a))}}dynamicToBuffer(e,t,i,n){if(typeof e=="number"){let{buffer:r,streams:o}=this.recursiveCIDToString(i.components,e,i.onlyCids);i.buffer+=r,i.streams=new Set([...i.streams,...o])}else Te(e)?this.toOutputBuffer(e,t,i,n,{}):i.buffer+=e}recursiveCIDToString(e,t,i){let n=e[t]||w(`no component for CID ${t}`,e),r={[K]:t,[le]:this.viewId},o=i&&!i.has(t);n.newRender=!o,n.magicId=`c${t}-${this.parentViewId()}`;let a=!n.reset,{buffer:l,streams:c}=this.recursiveToString(n,e,i,a,r);return delete n.reset,{buffer:l,streams:c}}};var Oi=[],Hi=200,un={exec(s,e,t,i,n,r){let[o,a]=r||[null,{callback:r&&r.callback}];(t.charAt(0)==="["?JSON.parse(t):[[o,a]]).forEach(([c,d])=>{c===o&&(d=O(O({},a),d),d.callback=d.callback||a.callback),this.filterToEls(i.liveSocket,n,d).forEach(p=>{this[`exec_${c}`](s,e,t,i,n,p,d)})})},isVisible(s){return!!(s.offsetWidth||s.offsetHeight||s.getClientRects().length>0)},isInViewport(s){let e=s.getBoundingClientRect(),t=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth;return e.right>0&&e.bottom>0&&e.left{a.done=p});i.liveSocket.asyncTransition(d)}h.dispatchEvent(r,o,{detail:a,bubbles:l})},exec_push(s,e,t,i,n,r,o){let{event:a,data:l,target:c,page_loading:d,loading:p,value:m,dispatcher:g,callback:u}=o,v={loading:p,value:m,target:c,page_loading:!!d,originalEvent:s},E=e==="change"&&g?g:n,M=c||E.getAttribute(i.binding("target"))||E,j=(F,_)=>{if(F.isConnected())if(e==="change"){let{newCid:k,_target:I}=o;I=I||(h.isFormInput(n)?n.name:void 0),I&&(v._target=I),F.pushInput(n,_,k,a||t,v,u)}else if(e==="submit"){let{submitter:k}=o;F.submitForm(n,_,a||t,k,v,u)}else F.pushEvent(e,n,_,a||t,l,v,u)};o.targetView&&o.targetCtx?j(o.targetView,o.targetCtx):i.withinTargets(M,j)},exec_navigate(s,e,t,i,n,r,{href:o,replace:a}){i.liveSocket.historyRedirect(s,o,a?"replace":"push",null,n)},exec_patch(s,e,t,i,n,r,{href:o,replace:a}){i.liveSocket.pushHistoryPatch(s,o,a?"replace":"push",n)},exec_focus(s,e,t,i,n,r){V.attemptFocus(r),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>V.attemptFocus(r))})},exec_focus_first(s,e,t,i,n,r){V.focusFirstInteractive(r)||V.focusFirst(r),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>V.focusFirstInteractive(r)||V.focusFirst(r))})},exec_push_focus(s,e,t,i,n,r){Oi.push(r||n)},exec_pop_focus(s,e,t,i,n,r){let o=Oi.pop();o&&(o.focus(),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>o.focus())}))},exec_add_class(s,e,t,i,n,r,{names:o,transition:a,time:l,blocking:c}){this.addOrRemoveClasses(r,o,[],a,l,i,c)},exec_remove_class(s,e,t,i,n,r,{names:o,transition:a,time:l,blocking:c}){this.addOrRemoveClasses(r,[],o,a,l,i,c)},exec_toggle_class(s,e,t,i,n,r,{names:o,transition:a,time:l,blocking:c}){this.toggleClasses(r,o,a,l,i,c)},exec_toggle_attr(s,e,t,i,n,r,{attr:[o,a,l]}){this.toggleAttr(r,o,a,l)},exec_ignore_attrs(s,e,t,i,n,r,{attrs:o}){this.ignoreAttrs(r,o)},exec_transition(s,e,t,i,n,r,{time:o,transition:a,blocking:l}){this.addOrRemoveClasses(r,[],[],a,o,i,l)},exec_toggle(s,e,t,i,n,r,{display:o,ins:a,outs:l,time:c,blocking:d}){this.toggle(e,i,r,o,a,l,c,d)},exec_show(s,e,t,i,n,r,{display:o,transition:a,time:l,blocking:c}){this.show(e,i,r,o,a,l,c)},exec_hide(s,e,t,i,n,r,{display:o,transition:a,time:l,blocking:c}){this.hide(e,i,r,o,a,l,c)},exec_set_attr(s,e,t,i,n,r,{attr:[o,a]}){this.setOrRemoveAttrs(r,[[o,a]],[])},exec_remove_attr(s,e,t,i,n,r,{attr:o}){this.setOrRemoveAttrs(r,[],[o])},ignoreAttrs(s,e){h.putPrivate(s,"JS:ignore_attrs",{apply:(t,i)=>{let n=Array.from(t.attributes),r=n.map(o=>o.name);Array.from(i.attributes).filter(o=>!r.includes(o.name)).forEach(o=>{h.attributeIgnored(o,e)&&i.removeAttribute(o.name)}),n.forEach(o=>{h.attributeIgnored(o,e)&&i.setAttribute(o.name,o.value)})}})},onBeforeElUpdated(s,e){let t=h.private(s,"JS:ignore_attrs");t&&t.apply(s,e)},show(s,e,t,i,n,r,o){this.isVisible(t)||this.toggle(s,e,t,i,n,null,r,o)},hide(s,e,t,i,n,r,o){this.isVisible(t)&&this.toggle(s,e,t,i,null,n,r,o)},toggle(s,e,t,i,n,r,o,a){o=o||Hi;let[l,c,d]=n||[[],[],[]],[p,m,g]=r||[[],[],[]];if(l.length>0||p.length>0)if(this.isVisible(t)){let u=()=>{this.addOrRemoveClasses(t,m,l.concat(c).concat(d)),window.requestAnimationFrame(()=>{this.addOrRemoveClasses(t,p,[]),window.requestAnimationFrame(()=>this.addOrRemoveClasses(t,g,m))})},v=()=>{this.addOrRemoveClasses(t,[],p.concat(g)),h.putSticky(t,"toggle",E=>E.style.display="none"),t.dispatchEvent(new Event("phx:hide-end"))};t.dispatchEvent(new Event("phx:hide-start")),a===!1?(u(),setTimeout(v,o)):e.transition(o,u,v)}else{if(s==="remove")return;let u=()=>{this.addOrRemoveClasses(t,c,p.concat(m).concat(g));let E=i||this.defaultDisplay(t);window.requestAnimationFrame(()=>{this.addOrRemoveClasses(t,l,[]),window.requestAnimationFrame(()=>{h.putSticky(t,"toggle",M=>M.style.display=E),this.addOrRemoveClasses(t,d,c)})})},v=()=>{this.addOrRemoveClasses(t,[],l.concat(d)),t.dispatchEvent(new Event("phx:show-end"))};t.dispatchEvent(new Event("phx:show-start")),a===!1?(u(),setTimeout(v,o)):e.transition(o,u,v)}else this.isVisible(t)?window.requestAnimationFrame(()=>{t.dispatchEvent(new Event("phx:hide-start")),h.putSticky(t,"toggle",u=>u.style.display="none"),t.dispatchEvent(new Event("phx:hide-end"))}):window.requestAnimationFrame(()=>{t.dispatchEvent(new Event("phx:show-start"));let u=i||this.defaultDisplay(t);h.putSticky(t,"toggle",v=>v.style.display=u),t.dispatchEvent(new Event("phx:show-end"))})},toggleClasses(s,e,t,i,n,r){window.requestAnimationFrame(()=>{let[o,a]=h.getSticky(s,"classes",[[],[]]),l=e.filter(d=>o.indexOf(d)<0&&!s.classList.contains(d)),c=e.filter(d=>a.indexOf(d)<0&&s.classList.contains(d));this.addOrRemoveClasses(s,l,c,t,i,n,r)})},toggleAttr(s,e,t,i){s.hasAttribute(e)?i!==void 0?s.getAttribute(e)===t?this.setOrRemoveAttrs(s,[[e,i]],[]):this.setOrRemoveAttrs(s,[[e,t]],[]):this.setOrRemoveAttrs(s,[],[e]):this.setOrRemoveAttrs(s,[[e,t]],[])},addOrRemoveClasses(s,e,t,i,n,r,o){n=n||Hi;let[a,l,c]=i||[[],[],[]];if(a.length>0){let d=()=>{this.addOrRemoveClasses(s,l,[].concat(a).concat(c)),window.requestAnimationFrame(()=>{this.addOrRemoveClasses(s,a,[]),window.requestAnimationFrame(()=>this.addOrRemoveClasses(s,c,l))})},p=()=>this.addOrRemoveClasses(s,e.concat(c),t.concat(a).concat(l));o===!1?(d(),setTimeout(p,n)):r.transition(n,d,p);return}window.requestAnimationFrame(()=>{let[d,p]=h.getSticky(s,"classes",[[],[]]),m=e.filter(E=>d.indexOf(E)<0&&!s.classList.contains(E)),g=t.filter(E=>p.indexOf(E)<0&&s.classList.contains(E)),u=d.filter(E=>t.indexOf(E)<0).concat(m),v=p.filter(E=>e.indexOf(E)<0).concat(g);h.putSticky(s,"classes",E=>(E.classList.remove(...v),E.classList.add(...u),[u,v]))})},setOrRemoveAttrs(s,e,t){let[i,n]=h.getSticky(s,"attrs",[[],[]]),r=e.map(([l,c])=>l).concat(t),o=i.filter(([l,c])=>!r.includes(l)).concat(e),a=n.filter(l=>!r.includes(l)).concat(t);h.putSticky(s,"attrs",l=>(a.forEach(c=>l.removeAttribute(c)),o.forEach(([c,d])=>l.setAttribute(c,d)),[o,a]))},hasAllClasses(s,e){return e.every(t=>s.classList.contains(t))},isToggledOut(s,e){return!this.isVisible(s)||this.hasAllClasses(s,e)},filterToEls(s,e,{to:t}){let i=()=>{if(typeof t=="string")return document.querySelectorAll(t);if(t.closest){let n=e.closest(t.closest);return n?[n]:[]}else if(t.inner)return e.querySelectorAll(t.inner)};return t?s.jsQuerySelectorAll(e,t,i):[e]},defaultDisplay(s){return{tr:"table-row",td:"table-cell"}[s.tagName.toLowerCase()]||"block"},transitionClasses(s){if(!s)return null;let[e,t,i]=Array.isArray(s)?s:[s.split(" "),[],[]];return e=Array.isArray(e)?e:e.split(" "),t=Array.isArray(t)?t:t.split(" "),i=Array.isArray(i)?i:i.split(" "),[e,t,i]}},S=un;var St=(s,e)=>({exec(t,i){s.execJS(t,i,e)},show(t,i={}){let n=s.owner(t);S.show(e,n,t,i.display,S.transitionClasses(i.transition),i.time,i.blocking)},hide(t,i={}){let n=s.owner(t);S.hide(e,n,t,null,S.transitionClasses(i.transition),i.time,i.blocking)},toggle(t,i={}){let n=s.owner(t),r=S.transitionClasses(i.in),o=S.transitionClasses(i.out);S.toggle(e,n,t,i.display,r,o,i.time,i.blocking)},addClass(t,i,n={}){let r=Array.isArray(i)?i:i.split(" "),o=s.owner(t);S.addOrRemoveClasses(t,r,[],S.transitionClasses(n.transition),n.time,o,n.blocking)},removeClass(t,i,n={}){let r=Array.isArray(i)?i:i.split(" "),o=s.owner(t);S.addOrRemoveClasses(t,[],r,S.transitionClasses(n.transition),n.time,o,n.blocking)},toggleClass(t,i,n={}){let r=Array.isArray(i)?i:i.split(" "),o=s.owner(t);S.toggleClasses(t,r,S.transitionClasses(n.transition),n.time,o,n.blocking)},transition(t,i,n={}){let r=s.owner(t);S.addOrRemoveClasses(t,[],[],S.transitionClasses(i),n.time,r,n.blocking)},setAttribute(t,i,n){S.setOrRemoveAttrs(t,[[i,n]],[])},removeAttribute(t,i){S.setOrRemoveAttrs(t,[],[i])},toggleAttribute(t,i,n,r){S.toggleAttr(t,i,n,r)},push(t,i,n={}){s.withinOwners(t,r=>{let o=n.value||{};delete n.value;let a=new CustomEvent("phx:exec",{detail:{sourceElement:t}});S.exec(a,e,i,r,t,["push",O({data:o},n)])})},navigate(t,i={}){let n=new CustomEvent("phx:exec");s.historyRedirect(n,t,i.replace?"replace":"push",null,null)},patch(t,i={}){let n=new CustomEvent("phx:exec");s.pushHistoryPatch(n,t,i.replace?"replace":"push",null)},ignoreAttributes(t,i){S.ignoreAttrs(t,Array.isArray(i)?i:[i])}});var Wt="hookId",fn=1,ee=class s{get liveSocket(){return this.__liveSocket()}static makeID(){return fn++}static elementID(e){return h.private(e,Wt)}constructor(e,t,i){if(this.el=t,this.__attachView(e),this.__listeners=new Set,this.__isDisconnected=!1,h.putPrivate(this.el,Wt,s.makeID()),i){let n=new Set(["el","liveSocket","__view","__listeners","__isDisconnected","constructor","js","pushEvent","pushEventTo","handleEvent","removeHandleEvent","upload","uploadTo","__mounted","__updated","__beforeUpdate","__destroyed","__reconnected","__disconnected","__cleanup__"]);for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&(this[o]=i[o],n.has(o)&&console.warn(`Hook object for element #${t.id} overwrites core property '${o}'!`));["mounted","beforeUpdate","updated","destroyed","disconnected","reconnected"].forEach(o=>{i[o]&&typeof i[o]=="function"&&(this[o]=i[o])})}}__attachView(e){e?(this.__view=()=>e,this.__liveSocket=()=>e.liveSocket):(this.__view=()=>{throw new Error(`hook not yet attached to a live view: ${this.el.outerHTML}`)},this.__liveSocket=()=>{throw new Error(`hook not yet attached to a live view: ${this.el.outerHTML}`)})}mounted(){}beforeUpdate(){}updated(){}destroyed(){}disconnected(){}reconnected(){}__mounted(){this.mounted()}__updated(){this.updated()}__beforeUpdate(){this.beforeUpdate()}__destroyed(){this.destroyed(),h.deletePrivate(this.el,Wt)}__reconnected(){this.__isDisconnected&&(this.__isDisconnected=!1,this.reconnected())}__disconnected(){this.__isDisconnected=!0,this.disconnected()}js(){return ae(O({},St(this.__view().liveSocket,"hook")),{exec:e=>{this.__view().liveSocket.execJS(this.el,e,"hook")}})}pushEvent(e,t,i){let n=this.__view().pushHookEvent(this.el,null,e,t||{});if(i===void 0)return n.then(({reply:r})=>r);n.then(({reply:r,ref:o})=>i(r,o)).catch(()=>{})}pushEventTo(e,t,i,n){if(n===void 0){let r=[];this.__view().withinTargets(e,(a,l)=>{r.push({view:a,targetCtx:l})});let o=r.map(({view:a,targetCtx:l})=>a.pushHookEvent(this.el,l,t,i||{}));return Promise.allSettled(o)}this.__view().withinTargets(e,(r,o)=>{r.pushHookEvent(this.el,o,t,i||{}).then(({reply:a,ref:l})=>n(a,l)).catch(()=>{})})}handleEvent(e,t){let i={event:e,callback:n=>t(n.detail)};return window.addEventListener(`phx:${e}`,i.callback),this.__listeners.add(i),i}removeHandleEvent(e){window.removeEventListener(`phx:${e.event}`,e.callback),this.__listeners.delete(e)}upload(e,t){return this.__view().dispatchUploads(null,e,t)}uploadTo(e,t,i){return this.__view().withinTargets(e,(n,r)=>{n.dispatchUploads(r,t,i)})}__cleanup__(){this.__listeners.forEach(e=>this.removeHandleEvent(e))}};var pn=(s,e)=>{let t=s.endsWith("[]"),i=t?s.slice(0,-2):s;return i=i.replace(/([^\[\]]+)(\]?$)/,`${e}$1$2`),t&&(i+="[]"),i},wt=(s,e,t=[])=>{let{submitter:i}=e,n;if(i&&i.name){let d=document.createElement("input");d.type="hidden";let p=i.getAttribute("form");p&&d.setAttribute("form",p),d.name=i.name,d.value=i.value,i.parentElement.insertBefore(d,i),n=d}let r=new FormData(s),o=[];r.forEach((d,p,m)=>{d instanceof File&&o.push(p)}),o.forEach(d=>r.delete(d));let a=new URLSearchParams,{inputsUnused:l,onlyHiddenInputs:c}=Array.from(s.elements).reduce((d,p)=>{let{inputsUnused:m,onlyHiddenInputs:g}=d,u=p.name;if(!u)return d;m[u]===void 0&&(m[u]=!0),g[u]===void 0&&(g[u]=!0);let v=h.private(p,we)||h.private(p,Pe),E=p.type==="hidden";return m[u]=m[u]&&!v,g[u]=g[u]&&E,d},{inputsUnused:{},onlyHiddenInputs:{}});for(let[d,p]of r.entries())if(t.length===0||t.indexOf(d)>=0){let m=l[d],g=c[d];m&&!(i&&i.name==d)&&!g&&a.append(pn(d,"_unused_"),""),typeof p=="string"&&a.append(d,p)}return i&&n&&i.parentElement.removeChild(n),a.toString()},xe=class s{static closestView(e){let t=e.closest(he);return t?h.private(t,"view"):null}constructor(e,t,i,n,r){this.isDead=!1,this.liveSocket=t,this.flash=n,this.parent=i,this.root=i?i.root:this,this.el=e;let o=h.private(this.el,"view");if(o!==void 0&&o.isDead!==!0)throw w(`The DOM element for this view has already been bound to a view. + + An element can only ever be associated with a single view! + Please ensure that you are not trying to initialize multiple LiveSockets on the same page. + This could happen if you're accidentally trying to render your root layout more than once. + Ensure that the template set on the LiveView is different than the root layout. + `,{view:o}),new Error("Cannot bind multiple views to the same DOM element.");h.putPrivate(this.el,"view",this),this.id=this.el.id,this.ref=0,this.lastAckRef=null,this.childJoins=0,this.loaderTimer=null,this.disconnectedTimer=null,this.pendingDiffs=[],this.pendingForms=new Set,this.redirect=!1,this.href=null,this.joinCount=this.parent?this.parent.joinCount-1:0,this.joinAttempts=0,this.joinPending=!0,this.destroyed=!1,this.joinCallback=function(a){a&&a()},this.stopCallback=function(){},this.pendingJoinOps=[],this.viewHooks={},this.formSubmits=[],this.children=this.parent?null:{},this.root.children[this.id]={},this.formsForRecovery={},this.channel=this.liveSocket.channel(`lv:${this.id}`,()=>{let a=this.href&&this.expandURL(this.href);return{redirect:this.redirect?a:void 0,url:this.redirect?void 0:a||void 0,params:this.connectParams(r),session:this.getSession(),static:this.getStatic(),flash:this.flash,sticky:this.el.hasAttribute(Qe)}}),this.portalElementIds=new Set}setHref(e){this.href=e}setRedirect(e){this.redirect=!0,this.href=e}isMain(){return this.el.hasAttribute(De)}connectParams(e){let t=this.liveSocket.params(this.el),i=h.all(document,`[${this.binding(Zt)}]`).map(n=>n.src||n.href).filter(n=>typeof n=="string");return i.length>0&&(t._track_static=i),t._mounts=this.joinCount,t._mount_attempts=this.joinAttempts,t._live_referer=e,this.joinAttempts++,t}isConnected(){return this.channel.canPush()}getSession(){return this.el.getAttribute(q)}getStatic(){let e=this.el.getAttribute(se);return e===""?null:e}destroy(e=function(){}){this.destroyAllChildren(),this.destroyPortalElements(),this.destroyed=!0,h.deletePrivate(this.el,"view"),delete this.root.children[this.id],this.parent&&delete this.root.children[this.parent.id][this.id],clearTimeout(this.loaderTimer);let t=()=>{e();for(let i in this.viewHooks)this.destroyHook(this.viewHooks[i])};h.markPhxChildDestroyed(this.el),this.log("destroyed",()=>["the child has been removed from the parent"]),this.channel.leave().receive("ok",t).receive("error",t).receive("timeout",t)}setContainerClasses(...e){this.el.classList.remove(Rt,ve,Se,It,He),this.el.classList.add(...e)}showLoader(e){if(clearTimeout(this.loaderTimer),e)this.loaderTimer=setTimeout(()=>this.showLoader(),e);else{for(let t in this.viewHooks)this.viewHooks[t].__disconnected();this.setContainerClasses(ve)}}execAll(e){h.all(this.el,`[${e}]`,t=>this.liveSocket.execJS(t,t.getAttribute(e)))}hideLoader(){clearTimeout(this.loaderTimer),clearTimeout(this.disconnectedTimer),this.setContainerClasses(Rt),this.execAll(this.binding("connected"))}triggerReconnected(){for(let e in this.viewHooks)this.viewHooks[e].__reconnected()}log(e,t){this.liveSocket.log(this,e,t)}transition(e,t,i=function(){}){this.liveSocket.transition(e,t,i)}withinTargets(e,t,i=document){if(e instanceof HTMLElement||e instanceof SVGElement)return this.liveSocket.owner(e,n=>t(n,e));if(Z(e))h.findComponentNodeList(this.id,e,i).length===0?w(`no component found matching phx-target of ${e}`):t(this,parseInt(e));else{let n=Array.from(i.querySelectorAll(e));n.length===0&&w(`nothing found matching the phx-target selector "${e}"`),n.forEach(r=>this.liveSocket.owner(r,o=>t(o,r)))}}applyDiff(e,t,i){this.log(e,()=>["",We(t)]);let{diff:n,reply:r,events:o,title:a}=Ke.extract(t),l=o.reduce((d,p)=>(p.length===3&&p[2]==!0?d.pre.push(p.slice(0,-1)):d.post.push(p),d),{pre:[],post:[]});this.liveSocket.dispatchEvents(l.pre);let c=()=>{i({diff:n,reply:r,events:l.post}),(typeof a=="string"||e=="mount"&&this.isMain())&&window.requestAnimationFrame(()=>h.putTitle(a))};"onDocumentPatch"in this.liveSocket.domCallbacks?this.liveSocket.triggerDOM("onDocumentPatch",[c]):c()}onJoin(e){let{rendered:t,container:i,liveview_version:n,pid:r}=e;if(i){let[o,a]=i;this.el=h.replaceRootContainer(this.el,o,a)}this.childJoins=0,this.joinPending=!0,this.flash=null,this.root===this&&(this.formsForRecovery=this.getFormsForRecovery()),this.isMain()&&window.history.state===null&&$.pushState("replace",{type:"patch",id:this.id,position:this.liveSocket.currentHistoryPosition}),n!==this.liveSocket.version()&&console.warn(`LiveView asset version mismatch. JavaScript version ${this.liveSocket.version()} vs. server ${n}. To avoid issues, please ensure that your assets use the same version as the server.`),r&&this.el.setAttribute(ai,r),$.dropLocal(this.liveSocket.localStorage,window.location.pathname,ct),this.applyDiff("mount",t,({diff:o,events:a})=>{this.rendered=new Ke(this.id,o);let[l,c]=this.renderContainer(null,"join");this.dropPendingRefs(),this.joinCount++,this.joinAttempts=0,this.maybeRecoverForms(l,()=>{this.onJoinComplete(e,l,c,a)})})}dropPendingRefs(){h.all(document,`[${N}="${this.refSrc()}"]`,e=>{e.removeAttribute(ge),e.removeAttribute(N),e.removeAttribute(C)})}onJoinComplete({live_patch:e},t,i,n){if(this.joinCount>1||this.parent&&!this.parent.isJoinPending())return this.applyJoinPatch(e,t,i,n);h.findPhxChildrenInFragment(t,this.id).filter(o=>{let a=o.id&&this.el.querySelector(`[id="${o.id}"]`),l=a&&a.getAttribute(se);return l&&o.setAttribute(se,l),a&&a.setAttribute(Q,this.root.id),this.joinChild(o)}).length===0?this.parent?(this.root.pendingJoinOps.push([this,()=>this.applyJoinPatch(e,t,i,n)]),this.parent.ackJoin(this)):(this.onAllChildJoinsComplete(),this.applyJoinPatch(e,t,i,n)):this.root.pendingJoinOps.push([this,()=>this.applyJoinPatch(e,t,i,n)])}attachTrueDocEl(){this.el=h.byId(this.id),this.el.setAttribute(Q,this.root.id)}execNewMounted(e=document){let t=this.binding(ze),i=this.binding(Ye);this.all(e,`[${t}], [${i}]`,n=>{h.maintainPrivateHooks(n,n,t,i),this.maybeAddNewHook(n)}),this.all(e,`[${this.binding(Ne)}], [data-phx-${Ne}]`,n=>{this.maybeAddNewHook(n)}),this.all(e,`[${this.binding(Ht)}]`,n=>{this.maybeMounted(n)})}all(e,t,i){h.all(e,t,n=>{this.ownsElement(n)&&i(n)})}applyJoinPatch(e,t,i,n){this.joinCount>1&&this.pendingJoinOps.length&&(this.pendingJoinOps.forEach(o=>typeof o=="function"&&o()),this.pendingJoinOps=[]),this.attachTrueDocEl();let r=new _e(this,this.el,this.id,t,i,null);if(r.markPrunableContentForRemoval(),this.performPatch(r,!1,!0),this.joinNewChildren(),this.execNewMounted(),this.joinPending=!1,this.liveSocket.dispatchEvents(n),this.applyPendingUpdates(),e){let{kind:o,to:a}=e;this.liveSocket.historyPatch(a,o)}this.hideLoader(),this.joinCount>1&&this.triggerReconnected(),this.stopCallback()}triggerBeforeUpdateHook(e,t){this.liveSocket.triggerDOM("onBeforeElUpdated",[e,t]);let i=this.getHook(e),n=i&&h.isIgnored(e,this.binding(Fe));if(i&&!e.isEqualNode(t)&&!(n&&Ei(e.dataset,t.dataset)))return i.__beforeUpdate(),i}maybeMounted(e){let t=e.getAttribute(this.binding(Ht)),i=t&&h.private(e,"mounted");t&&!i&&(this.liveSocket.execJS(e,t),h.putPrivate(e,"mounted",!0))}maybeAddNewHook(e){let t=this.addHook(e);t&&t.__mounted()}performPatch(e,t,i=!1){let n=[],r=!1,o=new Set;return this.liveSocket.triggerDOM("onPatchStart",[e.targetContainer]),e.after("added",a=>{this.liveSocket.triggerDOM("onNodeAdded",[a]);let l=this.binding(ze),c=this.binding(Ye);h.maintainPrivateHooks(a,a,l,c),this.maybeAddNewHook(a),a.getAttribute&&this.maybeMounted(a)}),e.after("phxChildAdded",a=>{h.isPhxSticky(a)?this.liveSocket.joinRootViews():r=!0}),e.before("updated",(a,l)=>{this.triggerBeforeUpdateHook(a,l)&&o.add(a.id),S.onBeforeElUpdated(a,l)}),e.after("updated",a=>{o.has(a.id)&&this.getHook(a).__updated()}),e.after("discarded",a=>{a.nodeType===Node.ELEMENT_NODE&&n.push(a)}),e.after("transitionsDiscarded",a=>this.afterElementsRemoved(a,t)),e.perform(i),this.afterElementsRemoved(n,t),this.liveSocket.triggerDOM("onPatchEnd",[e.targetContainer]),r}afterElementsRemoved(e,t){let i=[];e.forEach(n=>{let r=h.all(n,`[${le}="${this.id}"][${K}]`),o=h.all(n,`[${this.binding(Ne)}], [data-phx-hook]`);r.concat(n).forEach(a=>{let l=this.componentID(a);Z(l)&&i.indexOf(l)===-1&&a.getAttribute(le)===this.id&&i.push(l)}),o.concat(n).forEach(a=>{let l=this.getHook(a);l&&this.destroyHook(l)})}),t&&this.maybePushComponentsDestroyed(i)}joinNewChildren(){h.findPhxChildren(document,this.id).forEach(e=>this.joinChild(e))}maybeRecoverForms(e,t){let i=this.binding("change"),n=this.root.formsForRecovery,r=document.createElement("template");r.innerHTML=e,h.all(r.content,`[${$e}]`).forEach(l=>{r.content.firstElementChild.appendChild(l.content.firstElementChild)});let o=r.content.firstElementChild;o.id=this.id,o.setAttribute(Q,this.root.id),o.setAttribute(q,this.getSession()),o.setAttribute(se,this.getStatic()),o.setAttribute(ne,this.parent?this.parent.id:null);let a=h.all(r.content,"form").filter(l=>l.id&&n[l.id]).filter(l=>!this.pendingForms.has(l.id)).filter(l=>n[l.id].getAttribute(i)===l.getAttribute(i)).map(l=>[n[l.id],l]);if(a.length===0)return t();a.forEach(([l,c],d)=>{this.pendingForms.add(c.id),this.pushFormRecovery(l,c,r.content.firstElementChild,()=>{this.pendingForms.delete(c.id),d===a.length-1&&t()})})}getChildById(e){return this.root.children[this.id][e]}getDescendentByEl(e){var t;return e.id===this.id?this:(t=this.children[e.getAttribute(ne)])==null?void 0:t[e.id]}destroyDescendent(e){for(let t in this.root.children)for(let i in this.root.children[t])if(i===e)return this.root.children[t][i].destroy()}joinChild(e){if(!this.getChildById(e.id)){let i=new s(e,this.liveSocket,this);return this.root.children[this.id][i.id]=i,i.join(),this.childJoins++,!0}}isJoinPending(){return this.joinPending}ackJoin(e){this.childJoins--,this.childJoins===0&&(this.parent?this.parent.ackJoin(this):this.onAllChildJoinsComplete())}onAllChildJoinsComplete(){this.pendingForms.clear(),this.formsForRecovery={},this.joinCallback(()=>{this.pendingJoinOps.forEach(([e,t])=>{e.isDestroyed()||t()}),this.pendingJoinOps=[]})}update(e,t,i=!1){if(this.isJoinPending()||this.liveSocket.hasPendingLink()&&this.root.isMain())return i||this.pendingDiffs.push({diff:e,events:t}),!1;this.rendered.mergeDiff(e);let n=!1;return this.rendered.isComponentOnlyDiff(e)?this.liveSocket.time("component patch complete",()=>{h.findExistingParentCIDs(this.id,this.rendered.componentCIDs(e)).forEach(o=>{this.componentPatch(this.rendered.getComponent(e,o),o)&&(n=!0)})}):Vt(e)||this.liveSocket.time("full patch complete",()=>{let[r,o]=this.renderContainer(e,"update"),a=new _e(this,this.el,this.id,r,o,null);n=this.performPatch(a,!0)}),this.liveSocket.dispatchEvents(t),n&&this.joinNewChildren(),!0}renderContainer(e,t){return this.liveSocket.time(`toString diff (${t})`,()=>{let i=this.el.tagName,n=e?this.rendered.componentCIDs(e):null,{buffer:r,streams:o}=this.rendered.toString(n);return[`<${i}>${r}`,o]})}componentPatch(e,t){if(Vt(e))return!1;let{buffer:i,streams:n}=this.rendered.componentToString(t),r=new _e(this,this.el,this.id,i,n,t);return this.performPatch(r,!0)}getHook(e){return this.viewHooks[ee.elementID(e)]}addHook(e){let t=ee.elementID(e);if(!(e.getAttribute&&!this.ownsElement(e)))if(t&&!this.viewHooks[t]){let i=h.getCustomElHook(e)||w(`no hook found for custom element: ${e.id}`);return this.viewHooks[t]=i,i.__attachView(this),i}else{if(t||!e.getAttribute)return;{let i=e.getAttribute(`data-phx-${Ne}`)||e.getAttribute(this.binding(Ne));if(!i)return;let n=this.liveSocket.getHookDefinition(i);if(n){if(!e.id){w(`no DOM ID for hook "${i}". Hooks require a unique ID on each element.`,e);return}let r;try{if(typeof n=="function"&&n.prototype instanceof ee)r=new n(this,e);else if(typeof n=="object"&&n!==null)r=new ee(this,e,n);else{w(`Invalid hook definition for "${i}". Expected a class extending ViewHook or an object definition.`,e);return}}catch(o){let a=o instanceof Error?o.message:String(o);w(`Failed to create hook "${i}": ${a}`,e);return}return this.viewHooks[ee.elementID(r.el)]=r,r}else i!==null&&w(`unknown hook found for "${i}"`,e)}}}destroyHook(e){let t=ee.elementID(e.el);e.__destroyed(),e.__cleanup__(),delete this.viewHooks[t]}applyPendingUpdates(){this.pendingDiffs=this.pendingDiffs.filter(({diff:e,events:t})=>!this.update(e,t,!0)),this.eachChild(e=>e.applyPendingUpdates())}eachChild(e){let t=this.root.children[this.id]||{};for(let i in t)e(this.getChildById(i))}onChannel(e,t){this.liveSocket.onChannel(this.channel,e,i=>{this.isJoinPending()?this.joinCount>1?this.pendingJoinOps.push(()=>t(i)):this.root.pendingJoinOps.push([this,()=>t(i)]):this.liveSocket.requestDOMUpdate(()=>t(i))})}bindChannel(){this.liveSocket.onChannel(this.channel,"diff",e=>{this.liveSocket.requestDOMUpdate(()=>{this.applyDiff("update",e,({diff:t,events:i})=>this.update(t,i))})}),this.onChannel("redirect",({to:e,flash:t})=>this.onRedirect({to:e,flash:t})),this.onChannel("live_patch",e=>this.onLivePatch(e)),this.onChannel("live_redirect",e=>this.onLiveRedirect(e)),this.channel.onError(e=>this.onError(e)),this.channel.onClose(e=>this.onClose(e))}destroyAllChildren(){this.eachChild(e=>e.destroy())}onLiveRedirect(e){let{to:t,kind:i,flash:n}=e,r=this.expandURL(t),o=new CustomEvent("phx:server-navigate",{detail:{to:t,kind:i,flash:n}});this.liveSocket.historyRedirect(o,r,i,n)}onLivePatch(e){let{to:t,kind:i}=e;this.href=this.expandURL(t),this.liveSocket.historyPatch(t,i)}expandURL(e){return e.startsWith("/")?`${window.location.protocol}//${window.location.host}${e}`:e}onRedirect({to:e,flash:t,reloadToken:i}){this.liveSocket.redirect(e,t,i)}isDestroyed(){return this.destroyed}joinDead(){this.isDead=!0}joinPush(){return this.joinPush=this.joinPush||this.channel.join(),this.joinPush}join(e){this.showLoader(this.liveSocket.loaderTimeout),this.bindChannel(),this.isMain()&&(this.stopCallback=this.liveSocket.withPageLoading({to:this.href,kind:"initial"})),this.joinCallback=t=>{t=t||function(){},e?e(this.joinCount,t):t()},this.wrapPush(()=>this.channel.join(),{ok:t=>this.liveSocket.requestDOMUpdate(()=>this.onJoin(t)),error:t=>this.onJoinError(t),timeout:()=>this.onJoinError({reason:"timeout"})})}onJoinError(e){if(e.reason==="reload"){this.log("error",()=>[`failed mount with ${e.status}. Falling back to page reload`,e]),this.onRedirect({to:this.liveSocket.main.href,reloadToken:e.token});return}else if(e.reason==="unauthorized"||e.reason==="stale"){this.log("error",()=>["unauthorized live_redirect. Falling back to page request",e]),this.onRedirect({to:this.liveSocket.main.href,flash:this.flash});return}if((e.redirect||e.live_redirect)&&(this.joinPending=!1,this.channel.leave()),e.redirect)return this.onRedirect(e.redirect);if(e.live_redirect)return this.onLiveRedirect(e.live_redirect);if(this.log("error",()=>["unable to join",e]),this.isMain())this.displayError([ve,Se,He],{unstructuredError:e,errorKind:"server"}),this.liveSocket.isConnected()&&this.liveSocket.reloadWithJitter(this);else{this.joinAttempts>=Mt&&(this.root.displayError([ve,Se,He],{unstructuredError:e,errorKind:"server"}),this.log("error",()=>[`giving up trying to mount after ${Mt} tries`,e]),this.destroy());let t=h.byId(this.el.id);t?(h.mergeAttrs(t,this.el),this.displayError([ve,Se,He],{unstructuredError:e,errorKind:"server"}),this.el=t):this.destroy()}}onClose(e){if(!this.isDestroyed()){if(this.isMain()&&this.liveSocket.hasPendingLink()&&e!=="leave")return this.liveSocket.reloadWithJitter(this);this.destroyAllChildren(),this.liveSocket.dropActiveElement(this),this.liveSocket.isUnloaded()&&this.showLoader(di)}}onError(e){this.onClose(e),this.liveSocket.isConnected()&&this.log("error",()=>["view crashed",e]),this.liveSocket.isUnloaded()||(this.liveSocket.isConnected()?this.displayError([ve,Se,He],{unstructuredError:e,errorKind:"server"}):this.displayError([ve,Se,It],{unstructuredError:e,errorKind:"client"}))}displayError(e,t={}){this.isMain()&&h.dispatchEvent(window,"phx:page-loading-start",{detail:O({to:this.href,kind:"error"},t)}),this.showLoader(),this.setContainerClasses(...e),this.delayedDisconnected()}delayedDisconnected(){this.disconnectedTimer=setTimeout(()=>{this.execAll(this.binding("disconnected"))},this.liveSocket.disconnectedTimeout)}wrapPush(e,t){let i=this.liveSocket.getLatencySim(),n=i?r=>setTimeout(()=>!this.isDestroyed()&&r(),i):r=>!this.isDestroyed()&&r();n(()=>{e().receive("ok",r=>n(()=>t.ok&&t.ok(r))).receive("error",r=>n(()=>t.error&&t.error(r))).receive("timeout",()=>n(()=>t.timeout&&t.timeout()))})}pushWithReply(e,t,i){if(!this.isConnected())return Promise.reject(new Error("no connection"));let[n,[r],o]=e?e({payload:i}):[null,[],{}],a=this.joinCount,l=function(){};return o.page_loading&&(l=this.liveSocket.withPageLoading({kind:"element",target:r})),typeof i.cid!="number"&&delete i.cid,new Promise((c,d)=>{this.wrapPush(()=>this.channel.push(t,i,pi),{ok:p=>{n!==null&&(this.lastAckRef=n);let m=g=>{p.redirect&&this.onRedirect(p.redirect),p.live_patch&&this.onLivePatch(p.live_patch),p.live_redirect&&this.onLiveRedirect(p.live_redirect),l(),c({resp:p,reply:g,ref:n})};p.diff?this.liveSocket.requestDOMUpdate(()=>{this.applyDiff("update",p.diff,({diff:g,reply:u,events:v})=>{n!==null&&this.undoRefs(n,i.event),this.update(g,v),m(u)})}):(n!==null&&this.undoRefs(n,i.event),m(null))},error:p=>d(new Error(`failed with reason: ${JSON.stringify(p)}`)),timeout:()=>{d(new Error("timeout")),this.joinCount===a&&this.liveSocket.reloadWithJitter(this,()=>{this.log("timeout",()=>["received timeout while communicating with server. Falling back to hard refresh for recovery"])})}})})}undoRefs(e,t,i){if(!this.isConnected())return;let n=`[${N}="${this.refSrc()}"]`;i?(i=new Set(i),h.all(document,n,r=>{i&&!i.has(r)||(h.all(r,n,o=>this.undoElRef(o,e,t)),this.undoElRef(r,e,t))})):h.all(document,n,r=>this.undoElRef(r,e,t))}undoElRef(e,t,i){new ye(e).maybeUndo(t,i,r=>{let o=new _e(this,e,this.id,r,[],null,{undoRef:t}),a=this.performPatch(o,!0);h.all(e,`[${N}="${this.refSrc()}"]`,l=>this.undoElRef(l,t,i)),a&&this.joinNewChildren()})}refSrc(){return this.el.id}putRef(e,t,i,n={}){let r=this.ref++,o=this.binding(Lt);if(n.loading){let a=h.all(document,n.loading).map(l=>({el:l,lock:!0,loading:!0}));e=e.concat(a)}for(let{el:a,lock:l,loading:c}of e){if(!l&&!c)throw new Error("putRef requires lock or loading");if(a.setAttribute(N,this.refSrc()),c&&a.setAttribute(ge,r),l&&a.setAttribute(C,r),!c||n.submitter&&!(a===n.submitter||a===n.form))continue;let d=new Promise(u=>{a.addEventListener(`phx:undo-lock:${r}`,()=>u(g),{once:!0})}),p=new Promise(u=>{a.addEventListener(`phx:undo-loading:${r}`,()=>u(g),{once:!0})});a.classList.add(`phx-${i}-loading`);let m=a.getAttribute(o);m!==null&&(a.getAttribute(Me)||a.setAttribute(Me,a.textContent),m!==""&&(a.textContent=m),a.setAttribute(be,a.getAttribute(be)||a.disabled),a.setAttribute("disabled",""));let g={event:t,eventType:i,ref:r,isLoading:c,isLocked:l,lockElements:e.filter(({lock:u})=>u).map(({el:u})=>u),loadingElements:e.filter(({loading:u})=>u).map(({el:u})=>u),unlock:u=>{u=Array.isArray(u)?u:[u],this.undoRefs(r,t,u)},lockComplete:d,loadingComplete:p,lock:u=>new Promise(v=>{if(this.isAcked(r))return v(g);u.setAttribute(C,r),u.setAttribute(N,this.refSrc()),u.addEventListener(`phx:lock-stop:${r}`,()=>v(g),{once:!0})})};n.payload&&(g.payload=n.payload),n.target&&(g.target=n.target),n.originalEvent&&(g.originalEvent=n.originalEvent),a.dispatchEvent(new CustomEvent("phx:push",{detail:g,bubbles:!0,cancelable:!1})),t&&a.dispatchEvent(new CustomEvent(`phx:push:${t}`,{detail:g,bubbles:!0,cancelable:!1}))}return[r,e.map(({el:a})=>a),n]}isAcked(e){return this.lastAckRef!==null&&this.lastAckRef>=e}componentID(e){let t=e.getAttribute&&e.getAttribute(K);return t?parseInt(t):null}targetComponentID(e,t,i={}){if(Z(t))return t;let n=i.target||e.getAttribute(this.binding("target"));return Z(n)?parseInt(n):t&&(n!==null||i.target)?this.closestComponentID(t):null}closestComponentID(e){return Z(e)?e:e?ue(e.closest(`[${K}],[${Ee}]`),t=>{if(t.hasAttribute(K))return this.ownsElement(t)&&this.componentID(t);if(t.hasAttribute(Ee)){let i=h.byId(t.getAttribute(Ee));return this.closestComponentID(i)}}):null}pushHookEvent(e,t,i,n){if(!this.isConnected())return this.log("hook",()=>["unable to push hook event. LiveView not connected",i,n]),Promise.reject(new Error("unable to push hook event. LiveView not connected"));let r=()=>this.putRef([{el:e,loading:!0,lock:!0}],i,"hook",{payload:n,target:t});return this.pushWithReply(r,"event",{type:"hook",event:i,value:n,cid:this.closestComponentID(t)}).then(({resp:o,reply:a,ref:l})=>({reply:a,ref:l}))}extractMeta(e,t,i){let n=this.binding("value-");for(let r=0;r=0&&!e.checked&&delete t.value),i){t||(t={});for(let r in i)t[r]=i[r]}return t}pushEvent(e,t,i,n,r,o={},a){this.pushWithReply(l=>this.putRef([{el:t,loading:!0,lock:!0}],n,e,ae(O({},o),{payload:l==null?void 0:l.payload})),"event",{type:e,event:n,value:this.extractMeta(t,r,o.value),cid:this.targetComponentID(t,i,o)}).then(({reply:l})=>a&&a(l)).catch(l=>w("Failed to push event",l))}pushFileProgress(e,t,i,n=function(){}){this.liveSocket.withinOwners(e.form,(r,o)=>{r.pushWithReply(null,"progress",{event:e.getAttribute(r.binding(hi)),ref:e.getAttribute(G),entry_ref:t,progress:i,cid:r.targetComponentID(e.form,o)}).then(()=>n()).catch(a=>w("Failed to push file progress",a))})}pushInput(e,t,i,n,r,o){if(!e.form)throw new Error("form events require the input to be inside a form");let a,l=Z(i)?i:this.targetComponentID(e.form,t,r),c=u=>this.putRef([{el:e,loading:!0,lock:!0},{el:e.form,loading:!0,lock:!0}],n,"change",ae(O({},r),{payload:u==null?void 0:u.payload})),d,p=this.extractMeta(e.form,{},r.value),m={};e instanceof HTMLButtonElement&&(m.submitter=e),e.getAttribute(this.binding("change"))?d=wt(e.form,m,[e.name]):d=wt(e.form,m),h.isUploadInput(e)&&e.files&&e.files.length>0&&x.trackFiles(e,Array.from(e.files)),a=x.serializeUploads(e);let g={type:"form",event:n,value:d,meta:O({_target:r._target||"undefined"},p),uploads:a,cid:l};this.pushWithReply(c,"event",g).then(({resp:u})=>{h.isUploadInput(e)&&h.isAutoUpload(e)?ye.onUnlock(e,()=>{if(x.filesAwaitingPreflight(e).length>0){let[v,E]=c();this.undoRefs(v,n,[e.form]),this.uploadFiles(e.form,n,t,v,l,M=>{o&&o(u),this.triggerAwaitingSubmit(e.form,n),this.undoRefs(v,n)})}}):o&&o(u)}).catch(u=>w("Failed to push input event",u))}triggerAwaitingSubmit(e,t){let i=this.getScheduledSubmit(e);if(i){let[n,r,o,a]=i;this.cancelSubmit(e,t),a()}}getScheduledSubmit(e){return this.formSubmits.find(([t,i,n,r])=>t.isSameNode(e))}scheduleSubmit(e,t,i,n){if(this.getScheduledSubmit(e))return!0;this.formSubmits.push([e,t,i,n])}cancelSubmit(e,t){this.formSubmits=this.formSubmits.filter(([i,n,r,o])=>i.isSameNode(e)?(this.undoRefs(n,t),!1):!0)}disableForm(e,t,i={}){let n=u=>!(de(u,`${this.binding(Fe)}=ignore`,u.form)||de(u,"data-phx-update=ignore",u.form)),r=u=>u.hasAttribute(this.binding(Lt)),o=u=>u.tagName=="BUTTON",a=u=>["INPUT","TEXTAREA","SELECT"].includes(u.tagName),l=Array.from(e.elements),c=l.filter(r),d=l.filter(o).filter(n),p=l.filter(a).filter(n);d.forEach(u=>{u.setAttribute(be,u.disabled),u.disabled=!0}),p.forEach(u=>{u.setAttribute(Ze,u.readOnly),u.readOnly=!0,u.files&&(u.setAttribute(be,u.disabled),u.disabled=!0)});let m=c.concat(d).concat(p).map(u=>({el:u,loading:!0,lock:!0})),g=[{el:e,loading:!0,lock:!1}].concat(m).reverse();return this.putRef(g,t,"submit",i)}pushFormSubmit(e,t,i,n,r,o){let a=c=>this.disableForm(e,i,ae(O({},r),{form:e,payload:c==null?void 0:c.payload,submitter:n}));h.putPrivate(e,"submitter",n);let l=this.targetComponentID(e,t);if(x.hasUploadsInProgress(e)){let[c,d]=a(),p=()=>this.pushFormSubmit(e,t,i,n,r,o);return this.scheduleSubmit(e,c,r,p)}else if(x.inputsAwaitingPreflight(e).length>0){let[c,d]=a(),p=()=>[c,d,r];this.uploadFiles(e,i,t,c,l,m=>{if(x.inputsAwaitingPreflight(e).length>0)return this.undoRefs(c,i);let g=this.extractMeta(e,{},r.value),u=wt(e,{submitter:n});this.pushWithReply(p,"event",{type:"form",event:i,value:u,meta:g,cid:l}).then(({resp:v})=>o(v)).catch(v=>w("Failed to push form submit",v))})}else if(!(e.hasAttribute(N)&&e.classList.contains("phx-submit-loading"))){let c=this.extractMeta(e,{},r.value),d=wt(e,{submitter:n});this.pushWithReply(a,"event",{type:"form",event:i,value:d,meta:c,cid:l}).then(({resp:p})=>o(p)).catch(p=>w("Failed to push form submit",p))}}uploadFiles(e,t,i,n,r,o){let a=this.joinCount,l=x.activeFileInputs(e),c=l.length;l.forEach(d=>{let p=new x(d,this,()=>{c--,c===0&&o()}),m=p.entries().map(u=>u.toPreflightPayload());if(m.length===0){c--;return}let g={ref:d.getAttribute(G),entries:m,cid:this.targetComponentID(d.form,i)};this.log("upload",()=>["sending preflight request",g]),this.pushWithReply(null,"allow_upload",g).then(({resp:u})=>{if(this.log("upload",()=>["got preflight response",u]),p.entries().forEach(v=>{u.entries&&!u.entries[v.ref]&&this.handleFailedEntryPreflight(v.ref,"failed preflight",p)}),u.error||Object.keys(u.entries).length===0)this.undoRefs(n,t),(u.error||[]).map(([E,M])=>{this.handleFailedEntryPreflight(E,M,p)});else{let v=E=>{this.channel.onError(()=>{this.joinCount===a&&E()})};p.initAdapterUpload(u,v,this.liveSocket)}}).catch(u=>w("Failed to push upload",u))})}handleFailedEntryPreflight(e,t,i){if(i.isAutoUpload()){let n=i.entries().find(r=>r.ref===e.toString());n&&n.cancel()}else i.entries().map(n=>n.cancel());this.log("upload",()=>[`error for entry ${e}`,t])}dispatchUploads(e,t,i){let n=this.targetCtxElement(e)||this.el,r=h.findUploadInputs(n).filter(o=>o.name===t);r.length===0?w(`no live file inputs found matching the name "${t}"`):r.length>1?w(`duplicate live file inputs found matching the name "${t}"`):h.dispatchEvent(r[0],pt,{detail:{files:i}})}targetCtxElement(e){if(Z(e)){let[t]=h.findComponentNodeList(this.id,e);return t}else return e||null}pushFormRecovery(e,t,i,n){let r=this.binding("change"),o=t.getAttribute(this.binding("target"))||t,a=t.getAttribute(this.binding(Ot))||t.getAttribute(this.binding("change")),l=Array.from(e.elements).filter(p=>h.isFormInput(p)&&p.name&&!p.hasAttribute(r));if(l.length===0){n();return}l.forEach(p=>p.hasAttribute(G)&&x.clearFiles(p));let c=l.find(p=>p.type!=="hidden")||l[0],d=0;this.withinTargets(o,(p,m)=>{let g=this.targetComponentID(t,m);d++;let u=new CustomEvent("phx:form-recovery",{detail:{sourceElement:e}});S.exec(u,"change",a,this,c,["push",{_target:c.name,targetView:p,targetCtx:m,newCid:g,callback:()=>{d--,d===0&&n()}}])},i)}pushLinkPatch(e,t,i,n){let r=this.liveSocket.setPendingLink(t),o=e.isTrusted&&e.type!=="popstate",a=i?()=>this.putRef([{el:i,loading:o,lock:!0}],null,"click"):null,l=()=>this.liveSocket.redirect(window.location.href),c=t.startsWith("/")?`${location.protocol}//${location.host}${t}`:t;this.pushWithReply(a,"live_patch",{url:c}).then(({resp:d})=>{this.liveSocket.requestDOMUpdate(()=>{if(d.link_redirect)this.liveSocket.replaceMain(t,null,n,r);else{if(d.redirect)return;this.liveSocket.commitPendingLink(r)&&(this.href=t),this.applyPendingUpdates(),n&&n(r)}})},({error:d,timeout:p})=>l())}getFormsForRecovery(){if(this.joinCount===0)return{};let e=this.binding("change");return h.all(document,`#${CSS.escape(this.id)} form[${e}], [${re}="${CSS.escape(this.id)}"] form[${e}]`).filter(t=>t.id).filter(t=>t.elements.length>0).filter(t=>t.getAttribute(this.binding(Ot))!=="ignore").map(t=>{let i=t.cloneNode(!0);rt(i,t,{onBeforeElUpdated:(r,o)=>(h.copyPrivates(r,o),r.getAttribute("form")===t.id?(r.parentNode.removeChild(r),!1):!0)});let n=document.querySelectorAll(`[form="${CSS.escape(t.id)}"]`);return Array.from(n).forEach(r=>{let o=r.cloneNode(!0);rt(o,r),h.copyPrivates(o,r),o.removeAttribute("form"),i.appendChild(o)}),i}).reduce((t,i)=>(t[i.id]=i,t),{})}maybePushComponentsDestroyed(e){let t=e.filter(n=>h.findComponentNodeList(this.id,n).length===0),i=n=>{this.isDestroyed()||w("Failed to push components destroyed",n)};t.length>0&&(t.forEach(n=>this.rendered.resetRender(n)),this.pushWithReply(null,"cids_will_destroy",{cids:t}).then(()=>{this.liveSocket.requestDOMUpdate(()=>{let n=t.filter(r=>h.findComponentNodeList(this.id,r).length===0);n.length>0&&this.pushWithReply(null,"cids_destroyed",{cids:n}).then(({resp:r})=>{this.rendered.pruneCIDs(r.cids)}).catch(i)})}).catch(i))}ownsElement(e){let t=h.closestViewEl(e);return e.getAttribute(ne)===this.id||t&&t.id===this.id||!t&&this.isDead}submitForm(e,t,i,n,r={}){h.putPrivate(e,Pe,!0),Array.from(e.elements).forEach(a=>h.putPrivate(a,Pe,!0)),this.liveSocket.blurActiveElement(this),this.pushFormSubmit(e,t,i,n,r,()=>{this.liveSocket.restorePreviouslyActiveFocus()})}binding(e){return this.liveSocket.binding(e)}pushPortalElementId(e){this.portalElementIds.add(e)}dropPortalElementId(e){this.portalElementIds.delete(e)}destroyPortalElements(){this.liveSocket.unloaded||this.portalElementIds.forEach(e=>{let t=document.getElementById(e);t&&t.remove()})}};var Di=s=>h.isUsedInput(s),ot=class{constructor(e,t,i={}){if(this.unloaded=!1,!t||t.constructor.name==="Object")throw new Error(` + a phoenix Socket must be provided as the second argument to the LiveSocket constructor. For example: + + import {Socket} from "phoenix" + import {LiveSocket} from "phoenix_live_view" + let liveSocket = new LiveSocket("/live", Socket, {...}) + `);this.socket=new t(e,i),this.bindingPrefix=i.bindingPrefix||fi,this.opts=i,this.params=Je(i.params||{}),this.viewLogger=i.viewLogger,this.metadataCallbacks=i.metadata||{},this.defaults=Object.assign(We(mi),i.defaults||{}),this.prevActive=null,this.silenced=!1,this.main=null,this.outgoingMainEl=null,this.clickStartedAtTarget=null,this.linkRef=1,this.roots={},this.href=window.location.href,this.pendingLink=null,this.currentLocation=We(window.location),this.hooks=i.hooks||{},this.uploaders=i.uploaders||{},this.loaderTimeout=i.loaderTimeout||ci,this.disconnectedTimeout=i.disconnectedTimeout||ui,this.reloadWithJitterTimer=null,this.maxReloads=i.maxReloads||10,this.reloadJitterMin=i.reloadJitterMin||5e3,this.reloadJitterMax=i.reloadJitterMax||1e4,this.failsafeJitter=i.failsafeJitter||3e4,this.localStorage=i.localStorage||window.localStorage,this.sessionStorage=i.sessionStorage||window.sessionStorage,this.boundTopLevelEvents=!1,this.boundEventNames=new Set,this.blockPhxChangeWhileComposing=i.blockPhxChangeWhileComposing||!1,this.serverCloseRef=null,this.domCallbacks=Object.assign({jsQuerySelectorAll:null,onPatchStart:Je(),onPatchEnd:Je(),onNodeAdded:Je(),onBeforeElUpdated:Je()},i.dom||{}),this.transitions=new Kt,this.currentHistoryPosition=parseInt(this.sessionStorage.getItem(tt))||0,window.addEventListener("pagehide",n=>{this.unloaded=!0}),this.socket.onOpen(()=>{this.isUnloaded()&&window.location.reload()})}version(){return"1.1.20"}isProfileEnabled(){return this.sessionStorage.getItem(bt)==="true"}isDebugEnabled(){return this.sessionStorage.getItem(et)==="true"}isDebugDisabled(){return this.sessionStorage.getItem(et)==="false"}enableDebug(){this.sessionStorage.setItem(et,"true")}enableProfiling(){this.sessionStorage.setItem(bt,"true")}disableDebug(){this.sessionStorage.setItem(et,"false")}disableProfiling(){this.sessionStorage.removeItem(bt)}enableLatencySim(e){this.enableDebug(),console.log("latency simulator enabled for the duration of this browser session. Call disableLatencySim() to disable"),this.sessionStorage.setItem(Et,e)}disableLatencySim(){this.sessionStorage.removeItem(Et)}getLatencySim(){let e=this.sessionStorage.getItem(Et);return e?parseInt(e):null}getSocket(){return this.socket}connect(){window.location.hostname==="localhost"&&!this.isDebugDisabled()&&this.enableDebug();let e=()=>{this.resetReloadStatus(),this.joinRootViews()?(this.bindTopLevelEvents(),this.socket.connect()):this.main?this.socket.connect():this.bindTopLevelEvents({dead:!0}),this.joinDeadView()};["complete","loaded","interactive"].indexOf(document.readyState)>=0?e():document.addEventListener("DOMContentLoaded",()=>e())}disconnect(e){clearTimeout(this.reloadWithJitterTimer),this.serverCloseRef&&(this.socket.off(this.serverCloseRef),this.serverCloseRef=null),this.socket.disconnect(e)}replaceTransport(e){clearTimeout(this.reloadWithJitterTimer),this.socket.replaceTransport(e),this.connect()}execJS(e,t,i=null){let n=new CustomEvent("phx:exec",{detail:{sourceElement:e}});this.owner(e,r=>S.exec(n,i,t,r,e))}js(){return St(this,"js")}unload(){this.unloaded||(this.main&&this.isConnected()&&this.log(this.main,"socket",()=>["disconnect for page nav"]),this.unloaded=!0,this.destroyAllViews(),this.disconnect())}triggerDOM(e,t){this.domCallbacks[e](...t)}time(e,t){if(!this.isProfileEnabled()||!console.time)return t();console.time(e);let i=t();return console.timeEnd(e),i}log(e,t,i){if(this.viewLogger){let[n,r]=i();this.viewLogger(e,t,n,r)}else if(this.isDebugEnabled()){let[n,r]=i();bi(e,t,n,r)}}requestDOMUpdate(e){this.transitions.after(e)}asyncTransition(e){this.transitions.addAsyncTransition(e)}transition(e,t,i=function(){}){this.transitions.addTransition(e,t,i)}onChannel(e,t,i){e.on(t,n=>{let r=this.getLatencySim();r?setTimeout(()=>i(n),r):i(n)})}reloadWithJitter(e,t){clearTimeout(this.reloadWithJitterTimer),this.disconnect();let i=this.reloadJitterMin,n=this.reloadJitterMax,r=Math.floor(Math.random()*(n-i+1))+i,o=$.updateLocal(this.localStorage,window.location.pathname,ct,0,a=>a+1);o>=this.maxReloads&&(r=this.failsafeJitter),this.reloadWithJitterTimer=setTimeout(()=>{e.isDestroyed()||e.isConnected()||(e.destroy(),t?t():this.log(e,"join",()=>[`encountered ${o} consecutive reloads`]),o>=this.maxReloads&&this.log(e,"join",()=>[`exceeded ${this.maxReloads} consecutive reloads. Entering failsafe mode`]),this.hasPendingLink()?window.location=this.pendingLink:window.location.reload())},r)}getHookDefinition(e){if(e)return this.maybeInternalHook(e)||this.hooks[e]||this.maybeRuntimeHook(e)}maybeInternalHook(e){return e&&e.startsWith("Phoenix.")&&ki[e.split(".")[1]]}maybeRuntimeHook(e){let t=document.querySelector(`script[${Ve}="${CSS.escape(e)}"]`);if(!t)return;let i=window[`phx_hook_${e}`];if(!i||typeof i!="function"){w("a runtime hook must be a function",t);return}let n=i();if(n&&(typeof n=="object"||typeof n=="function"))return n;w("runtime hook must return an object with hook callbacks or an instance of ViewHook",t)}isUnloaded(){return this.unloaded}isConnected(){return this.socket.isConnected()}getBindingPrefix(){return this.bindingPrefix}binding(e){return`${this.getBindingPrefix()}${e}`}channel(e,t){return this.socket.channel(e,t)}joinDeadView(){let e=document.body;if(e&&!this.isPhxView(e)&&!this.isPhxView(document.firstElementChild)){let t=this.newRootView(e);t.setHref(this.getHref()),t.joinDead(),this.main||(this.main=t),window.requestAnimationFrame(()=>{var i;t.execNewMounted(),this.maybeScroll((i=history.state)==null?void 0:i.scroll)})}}joinRootViews(){let e=!1;return h.all(document,`${he}:not([${ne}])`,t=>{if(!this.getRootById(t.id)){let i=this.newRootView(t);h.isPhxSticky(t)||i.setHref(this.getHref()),i.join(),t.hasAttribute(De)&&(this.main=i)}e=!0}),e}redirect(e,t,i){i&&$.setCookie(Dt,i,60),this.unload(),$.redirect(e,t)}replaceMain(e,t,i=null,n=this.setPendingLink(e)){let r=this.currentLocation.href;this.outgoingMainEl=this.outgoingMainEl||this.main.el;let o=h.findPhxSticky(document)||[],a=h.all(this.outgoingMainEl,`[${this.binding("remove")}]`).filter(c=>!h.isChildOfAny(c,o)),l=h.cloneNode(this.outgoingMainEl,"");this.main.showLoader(this.loaderTimeout),this.main.destroy(),this.main=this.newRootView(l,t,r),this.main.setRedirect(e),this.transitionRemoves(a),this.main.join((c,d)=>{c===1&&this.commitPendingLink(n)&&this.requestDOMUpdate(()=>{a.forEach(p=>p.remove()),o.forEach(p=>l.appendChild(p)),this.outgoingMainEl.replaceWith(l),this.outgoingMainEl=null,i&&i(n),d()})})}transitionRemoves(e,t){let i=this.binding("remove"),n=r=>{r.preventDefault(),r.stopImmediatePropagation()};e.forEach(r=>{for(let o of this.boundEventNames)r.addEventListener(o,n,!0);this.execJS(r,r.getAttribute(i),"remove")}),this.requestDOMUpdate(()=>{e.forEach(r=>{for(let o of this.boundEventNames)r.removeEventListener(o,n,!0)}),t&&t()})}isPhxView(e){return e.getAttribute&&e.getAttribute(q)!==null}newRootView(e,t,i){let n=new xe(e,this,null,t,i);return this.roots[n.id]=n,n}owner(e,t){let i,n=h.closestViewEl(e);if(n)i=this.getViewByEl(n);else{if(!e.isConnected)return null;i=this.main}return i&&t?t(i):i}withinOwners(e,t){this.owner(e,i=>t(i,e))}getViewByEl(e){let t=e.getAttribute(Q);return ue(this.getRootById(t),i=>i.getDescendentByEl(e))}getRootById(e){return this.roots[e]}destroyAllViews(){for(let e in this.roots)this.roots[e].destroy(),delete this.roots[e];this.main=null}destroyViewByEl(e){let t=this.getRootById(e.getAttribute(Q));t&&t.id===e.id?(t.destroy(),delete this.roots[t.id]):t&&t.destroyDescendent(e.id)}getActiveElement(){return document.activeElement}dropActiveElement(e){this.prevActive&&e.ownsElement(this.prevActive)&&(this.prevActive=null)}restorePreviouslyActiveFocus(){this.prevActive&&this.prevActive!==document.body&&this.prevActive instanceof HTMLElement&&this.prevActive.focus()}blurActiveElement(){this.prevActive=this.getActiveElement(),this.prevActive!==document.body&&this.prevActive instanceof HTMLElement&&this.prevActive.blur()}bindTopLevelEvents({dead:e}={}){this.boundTopLevelEvents||(this.boundTopLevelEvents=!0,this.serverCloseRef=this.socket.onClose(t=>{if(t&&t.code===1e3&&this.main)return this.reloadWithJitter(this.main)}),document.body.addEventListener("click",function(){}),window.addEventListener("pageshow",t=>{t.persisted&&(this.getSocket().disconnect(),this.withPageLoading({to:window.location.href,kind:"redirect"}),window.location.reload())},!0),e||this.bindNav(),this.bindClicks(),e||this.bindForms(),this.bind({keyup:"keyup",keydown:"keydown"},(t,i,n,r,o,a)=>{let l=r.getAttribute(this.binding(li)),c=t.key&&t.key.toLowerCase();if(l&&l.toLowerCase()!==c)return;let d=O({key:t.key},this.eventMeta(i,t,r));S.exec(t,i,o,n,r,["push",{data:d}])}),this.bind({blur:"focusout",focus:"focusin"},(t,i,n,r,o,a)=>{if(!a){let l=O({key:t.key},this.eventMeta(i,t,r));S.exec(t,i,o,n,r,["push",{data:l}])}}),this.bind({blur:"blur",focus:"focus"},(t,i,n,r,o,a)=>{if(a==="window"){let l=this.eventMeta(i,t,r);S.exec(t,i,o,n,r,["push",{data:l}])}}),this.on("dragover",t=>t.preventDefault()),this.on("dragenter",t=>{let i=de(t.target,this.binding(qe));!i||!(i instanceof HTMLElement)||Ai(t)&&this.js().addClass(i,ut)}),this.on("dragleave",t=>{let i=de(t.target,this.binding(qe));if(!i||!(i instanceof HTMLElement))return;let n=i.getBoundingClientRect();(t.clientX<=n.left||t.clientX>=n.right||t.clientY<=n.top||t.clientY>=n.bottom)&&this.js().removeClass(i,ut)}),this.on("drop",t=>{t.preventDefault();let i=de(t.target,this.binding(qe));if(!i||!(i instanceof HTMLElement))return;this.js().removeClass(i,ut);let n=i.getAttribute(this.binding(qe)),r=n&&document.getElementById(n),o=Array.from(t.dataTransfer.files||[]);!r||!(r instanceof HTMLInputElement)||r.disabled||o.length===0||!(r.files instanceof FileList)||(x.trackFiles(r,o,t.dataTransfer),r.dispatchEvent(new Event("input",{bubbles:!0})))}),this.on(pt,t=>{let i=t.target;if(!h.isUploadInput(i))return;let n=Array.from(t.detail.files||[]).filter(r=>r instanceof File||r instanceof Blob);x.trackFiles(i,n),i.dispatchEvent(new Event("input",{bubbles:!0}))}))}eventMeta(e,t,i){let n=this.metadataCallbacks[e];return n?n(t,i):{}}setPendingLink(e){return this.linkRef++,this.pendingLink=e,this.resetReloadStatus(),this.linkRef}resetReloadStatus(){$.deleteCookie(Dt)}commitPendingLink(e){return this.linkRef!==e?!1:(this.href=this.pendingLink,this.pendingLink=null,!0)}getHref(){return this.href}hasPendingLink(){return!!this.pendingLink}bind(e,t){for(let i in e){let n=e[i];this.on(n,r=>{let o=this.binding(i),a=this.binding(`window-${i}`),l=r.target.getAttribute&&r.target.getAttribute(o);l?this.debounce(r.target,r,n,()=>{this.withinOwners(r.target,c=>{t(r,i,c,r.target,l,null)})}):h.all(document,`[${a}]`,c=>{let d=c.getAttribute(a);this.debounce(c,r,n,()=>{this.withinOwners(c,p=>{t(r,i,p,c,d,"window")})})})})}}bindClicks(){this.on("mousedown",e=>this.clickStartedAtTarget=e.target),this.bindClick("click","click")}bindClick(e,t){let i=this.binding(t);window.addEventListener(e,n=>{let r=null;n.detail===0&&(this.clickStartedAtTarget=n.target);let o=this.clickStartedAtTarget||n.target;r=de(n.target,i),this.dispatchClickAway(n,o),this.clickStartedAtTarget=null;let a=r&&r.getAttribute(i);if(!a){h.isNewPageClick(n,window.location)&&this.unload();return}r.getAttribute("href")==="#"&&n.preventDefault(),!r.hasAttribute(N)&&this.debounce(r,n,"click",()=>{this.withinOwners(r,l=>{S.exec(n,"click",a,l,r,["push",{data:this.eventMeta("click",n,r)}])})})},!1)}dispatchClickAway(e,t){let i=this.binding("click-away");h.all(document,`[${i}]`,n=>{n.isSameNode(t)||n.contains(t)||!S.isVisible(t)||this.withinOwners(n,r=>{let o=n.getAttribute(i);S.isVisible(n)&&S.isInViewport(n)&&S.exec(e,"click",o,r,n,["push",{data:this.eventMeta("click",e,e.target)}])})})}bindNav(){if(!$.canPushState())return;history.scrollRestoration&&(history.scrollRestoration="manual");let e=null;window.addEventListener("scroll",t=>{clearTimeout(e),e=setTimeout(()=>{$.updateCurrentState(i=>Object.assign(i,{scroll:window.scrollY}))},100)}),window.addEventListener("popstate",t=>{if(!this.registerNewLocation(window.location))return;let{type:i,backType:n,id:r,scroll:o,position:a}=t.state||{},l=window.location.href,c=a>this.currentHistoryPosition,d=c?i:n||i;this.currentHistoryPosition=a||0,this.sessionStorage.setItem(tt,this.currentHistoryPosition.toString()),h.dispatchEvent(window,"phx:navigate",{detail:{href:l,patch:d==="patch",pop:!0,direction:c?"forward":"backward"}}),this.requestDOMUpdate(()=>{let p=()=>{this.maybeScroll(o)};this.main.isConnected()&&d==="patch"&&r===this.main.id?this.main.pushLinkPatch(t,l,null,p):this.replaceMain(l,null,p)})},!1),window.addEventListener("click",t=>{let i=de(t.target,ft),n=i&&i.getAttribute(ft);if(!n||!this.isConnected()||!this.main||h.wantsNewTab(t))return;let r=i.href instanceof SVGAnimatedString?i.href.baseVal:i.href,o=i.getAttribute(ei);t.preventDefault(),t.stopImmediatePropagation(),this.pendingLink!==r&&this.requestDOMUpdate(()=>{if(n==="patch")this.pushHistoryPatch(t,r,o,i);else if(n==="redirect")this.historyRedirect(t,r,o,null,i);else throw new Error(`expected ${ft} to be "patch" or "redirect", got: ${n}`);let a=i.getAttribute(this.binding("click"));a&&this.requestDOMUpdate(()=>this.execJS(i,a,"click"))})},!1)}maybeScroll(e){typeof e=="number"&&requestAnimationFrame(()=>{window.scrollTo(0,e)})}dispatchEvent(e,t={}){h.dispatchEvent(window,`phx:${e}`,{detail:t})}dispatchEvents(e){e.forEach(([t,i])=>this.dispatchEvent(t,i))}withPageLoading(e,t){h.dispatchEvent(window,"phx:page-loading-start",{detail:e});let i=()=>h.dispatchEvent(window,"phx:page-loading-stop",{detail:e});return t?t(i):i}pushHistoryPatch(e,t,i,n){if(!this.isConnected()||!this.main.isMain())return $.redirect(t);this.withPageLoading({to:t,kind:"patch"},r=>{this.main.pushLinkPatch(e,t,n,o=>{this.historyPatch(t,i,o),r()})})}historyPatch(e,t,i=this.setPendingLink(e)){this.commitPendingLink(i)&&(this.currentHistoryPosition++,this.sessionStorage.setItem(tt,this.currentHistoryPosition.toString()),$.updateCurrentState(n=>ae(O({},n),{backType:"patch"})),$.pushState(t,{type:"patch",id:this.main.id,position:this.currentHistoryPosition},e),h.dispatchEvent(window,"phx:navigate",{detail:{patch:!0,href:e,pop:!1,direction:"forward"}}),this.registerNewLocation(window.location))}historyRedirect(e,t,i,n,r){let o=r&&e.isTrusted&&e.type!=="popstate";if(o&&r.classList.add("phx-click-loading"),!this.isConnected()||!this.main.isMain())return $.redirect(t,n);if(/^\/$|^\/[^\/]+.*$/.test(t)){let{protocol:l,host:c}=window.location;t=`${l}//${c}${t}`}let a=window.scrollY;this.withPageLoading({to:t,kind:"redirect"},l=>{this.replaceMain(t,n,c=>{c===this.linkRef&&(this.currentHistoryPosition++,this.sessionStorage.setItem(tt,this.currentHistoryPosition.toString()),$.updateCurrentState(d=>ae(O({},d),{backType:"redirect"})),$.pushState(i,{type:"redirect",id:this.main.id,scroll:a,position:this.currentHistoryPosition},t),h.dispatchEvent(window,"phx:navigate",{detail:{href:t,patch:!1,pop:!1,direction:"forward"}}),this.registerNewLocation(window.location)),o&&r.classList.remove("phx-click-loading"),l()})})}registerNewLocation(e){let{pathname:t,search:i}=this.currentLocation;return t+i===e.pathname+e.search?!1:(this.currentLocation=We(e),!0)}bindForms(){let e=0,t=!1;this.on("submit",i=>{let n=i.target.getAttribute(this.binding("submit")),r=i.target.getAttribute(this.binding("change"));!t&&r&&!n&&(t=!0,i.preventDefault(),this.withinOwners(i.target,o=>{o.disableForm(i.target),window.requestAnimationFrame(()=>{h.isUnloadableFormSubmit(i)&&this.unload(),i.target.submit()})}))}),this.on("submit",i=>{let n=i.target.getAttribute(this.binding("submit"));if(!n){h.isUnloadableFormSubmit(i)&&this.unload();return}i.preventDefault(),i.target.disabled=!0,this.withinOwners(i.target,r=>{S.exec(i,"submit",n,r,i.target,["push",{submitter:i.submitter}])})});for(let i of["change","input"])this.on(i,n=>{if(n instanceof CustomEvent&&(n.target instanceof HTMLInputElement||n.target instanceof HTMLSelectElement||n.target instanceof HTMLTextAreaElement)&&n.target.form===void 0){if(n.detail&&n.detail.dispatcher)throw new Error(`dispatching a custom ${i} event is only supported on input elements inside a form`);return}let r=this.binding("change"),o=n.target;if(this.blockPhxChangeWhileComposing&&n.isComposing){let u=`composition-listener-${i}`;h.private(o,u)||(h.putPrivate(o,u,!0),o.addEventListener("compositionend",()=>{o.dispatchEvent(new Event(i,{bubbles:!0})),h.deletePrivate(o,u)},{once:!0}));return}let a=o.getAttribute(r),l=o.form&&o.form.getAttribute(r),c=a||l;if(!c||o.type==="number"&&o.validity&&o.validity.badInput)return;let d=a?o:o.form,p=e;e++;let{at:m,type:g}=h.private(o,"prev-iteration")||{};m===p-1&&i==="change"&&g==="input"||(h.putPrivate(o,"prev-iteration",{at:p,type:i}),this.debounce(o,n,i,()=>{this.withinOwners(d,u=>{h.putPrivate(o,we,!0),S.exec(n,"change",c,u,o,["push",{_target:n.target.name,dispatcher:d}])})}))});this.on("reset",i=>{let n=i.target;h.resetForm(n);let r=Array.from(n.elements).find(o=>o.type==="reset");r&&window.requestAnimationFrame(()=>{r.dispatchEvent(new Event("input",{bubbles:!0,cancelable:!1}))})})}debounce(e,t,i,n){if(i==="blur"||i==="focusout")return n();let r=this.binding(ri),o=this.binding(oi),a=this.defaults.debounce.toString(),l=this.defaults.throttle.toString();this.withinOwners(e,c=>{let d=()=>!c.isDestroyed()&&document.body.contains(e);h.debounce(e,t,r,a,o,l,d,()=>{n()})})}silenceEvents(e){this.silenced=!0,e(),this.silenced=!1}on(e,t){this.boundEventNames.add(e),window.addEventListener(e,i=>{this.silenced||t(i)})}jsQuerySelectorAll(e,t,i){let n=this.domCallbacks.jsQuerySelectorAll;return n?n(e,t,i):i()}},Kt=class{constructor(){this.transitions=new Set,this.promises=new Set,this.pendingOps=[]}reset(){this.transitions.forEach(e=>{clearTimeout(e),this.transitions.delete(e)}),this.promises.clear(),this.flushPendingOps()}after(e){this.size()===0?e():this.pushPendingOp(e)}addTransition(e,t,i){t();let n=setTimeout(()=>{this.transitions.delete(n),i(),this.flushPendingOps()},e);this.transitions.add(n)}addAsyncTransition(e){this.promises.add(e),e.then(()=>{this.promises.delete(e),this.flushPendingOps()})}pushPendingOp(e){this.pendingOps.push(e)}size(){return this.transitions.size+this.promises.size}flushPendingOps(){if(this.size()>0)return;let e=this.pendingOps.shift();e&&(e(),this.flushPendingOps())}};var En=ot;function yn(s,e){let t=h.getCustomElHook(s);if(t)return t;s.hasAttribute("id")||w("Elements passed to createHook need to have a unique id attribute",s);let i=new ee(xe.closestView(s),s,e);return h.putCustomElHook(s,i),i}return ji(An);})(); From 20c1f6764b95c8d19104a7a04baf59fb51278c2d Mon Sep 17 00:00:00 2001 From: Carlos Souza Date: Thu, 22 Jan 2026 16:54:24 -0500 Subject: [PATCH 2/2] Nit --- lib/fester/chain_sync.ex | 2 +- lib/fester_web/live/dashboard_live.ex | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/fester/chain_sync.ex b/lib/fester/chain_sync.ex index 99ad8f2..1122e39 100644 --- a/lib/fester/chain_sync.ex +++ b/lib/fester/chain_sync.ex @@ -7,7 +7,7 @@ defmodule Fester.ChainSync do def start_link(opts) do initial_state = [ is_synced?: false, - sync_from: :conway + sync_from: :origin ## To sync from a specific point in the chain, uncomment the line below ## and set the slot and block hash # sync_from: {slot, block_hash} diff --git a/lib/fester_web/live/dashboard_live.ex b/lib/fester_web/live/dashboard_live.ex index d26936d..fec1661 100644 --- a/lib/fester_web/live/dashboard_live.ex +++ b/lib/fester_web/live/dashboard_live.ex @@ -9,9 +9,7 @@ defmodule FesterWeb.DashboardLive do @impl true def mount(_params, _session, socket) do - if connected?(socket) do - Aggregator.subscribe() - end + if connected?(socket), do: Aggregator.subscribe() metrics = Aggregator.get_metrics()