Migrate from channel to phoenix live view.

Move phoenix config to ui project.
Sync progress on page load.
This commit is contained in:
Pim Kunis 2019-10-23 14:38:11 +02:00
parent e888f1330b
commit ad24ec96ac
26 changed files with 120 additions and 164 deletions

View file

@ -11,7 +11,8 @@ import css from "../css/app.css"
//
import "phoenix_html"
// Import local files
//
// Local files can be imported directly using relative paths, for example:
import socket from "./socket"
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"
let liveSocket = new LiveSocket("/live", Socket)
liveSocket.connect()

View file

@ -1,19 +0,0 @@
import {Socket} from "phoenix"
let socket = new Socket("/socket", {params: {token: window.userToken}})
socket.connect()
let channel = socket.channel("morse:progress", {})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
let progressBar = document.getElementById("morse-progress")
channel.on("update", (content) => {
progressBar.value = content["value"]
progressBar.innerHTML = content["value"]
});
export default socket

View file

@ -4515,6 +4515,9 @@
"phoenix_html": {
"version": "file:../deps/phoenix_html"
},
"phoenix_live_view": {
"version": "file:../deps/phoenix_live_view"
},
"pify": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz",

View file

@ -7,7 +7,8 @@
},
"dependencies": {
"phoenix": "file:../deps/phoenix",
"phoenix_html": "file:../deps/phoenix_html"
"phoenix_html": "file:../deps/phoenix_html",
"phoenix_live_view": "file:../deps/phoenix_live_view"
},
"devDependencies": {
"@babel/core": "^7.0.0",

19
ui/config/config.exs Normal file
View file

@ -0,0 +1,19 @@
use Mix.Config
config :ui, target: Mix.target()
config :ui, UiWeb.Endpoint,
live_view: [signing_salt: "h4niP0Ovx/wDHjKRBJelcKHsbBUzptcagimD/iSDHMg5r535/A1ad5uAKJjY9ktI"],
pubsub: [name: Ui.PubSub, adapter: Phoenix.PubSub.PG2]
config :phoenix, :json_library, Jason
config :phoenix, template_engines: [leex: Phoenix.LiveView.Engine]
config :morse, :pubsub, Phoenix.PubSub
if Mix.target() != :host do
"target.exs"
else
"host.exs"
end
|> import_config()

36
ui/config/host.exs Normal file
View file

@ -0,0 +1,36 @@
use Mix.Config
config :ui, UiWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "FkfuB09FEncz4aAi6hS6w5bsNast+D1P12MckXr5dlRdhtFJrKqgEhvhpTU3qzgh",
render_errors: [view: UiWeb.ErrorView, accepts: ~w(html json)],
http: [port: 4000],
server: true,
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch-stdin",
cd: Path.expand("../assets", __DIR__)
]
],
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/ui_web/{live,views}/.*(ex)$",
~r"lib/ui_web/templates/.*(eex)$",
~r{lib/ui_web/live/.*(ex)$}
]
]
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime

12
ui/config/target.exs Normal file
View file

@ -0,0 +1,12 @@
use Mix.Config
config :ui, UiWeb.Endpoint,
url: [host: "www.geokunis2.nl"],
http: [port: 80],
secret_key_base: "HEY05EB1dFVSu6KykKHuS4rQPQzSHv4F7mGVB/gnDLrIu75wE/ytBXy2TaL3A6RA",
root: Path.dirname(__DIR__),
server: true,
render_errors: [view: UiWeb.ErrorView, accepts: ~w(html json)],
code_reloader: false
config :morse, :relay_pin, 17

View file

@ -12,7 +12,7 @@ defmodule Ui.Application do
UiWeb.Endpoint
# Starts a worker by calling: Ui.Worker.start_link(arg)
# {Ui.Worker, arg},
]
] ++ children(target())
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
@ -20,10 +20,23 @@ defmodule Ui.Application do
Supervisor.start_link(children, opts)
end
def children(:host) do
{:ok, _} = Node.start(:"host@0.0.0.0")
Node.set_cookie(:tastycookie)
true = Node.connect(:"esrom@esrom.lan")
[]
end
def children(_target), do: []
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
UiWeb.Endpoint.config_change(changed, removed)
:ok
end
def target() do
Application.get_env(:ui, :target)
end
end

View file

@ -42,6 +42,8 @@ defmodule UiWeb do
import UiWeb.ErrorHelpers
import UiWeb.Gettext
alias UiWeb.Router.Helpers, as: Routes
import Phoenix.LiveView, only: [live_render: 2, live_render: 3]
end
end
@ -50,6 +52,7 @@ defmodule UiWeb do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
import Phoenix.LiveView.Router
end
end

View file

@ -1,7 +0,0 @@
defmodule UiWeb.MorseProgressChannel do
use UiWeb, :channel
def join(channel_name, _params, socket) do
{:ok, %{channel: channel_name}, socket}
end
end

View file

@ -1,37 +0,0 @@
defmodule UiWeb.UserSocket do
use Phoenix.Socket
## Channels
channel "morse:progress", UiWeb.MorseProgressChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket, _connect_info) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# UiWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
def broadcast_progress(progress) do
UiWeb.Endpoint.broadcast("morse:progress", "update", %{value: progress})
end
end

View file

@ -1,25 +1,17 @@
defmodule UiWeb.PageController do
use UiWeb, :controller
alias Phoenix.LiveView
def index(conn, _params) do
conn |> send_resp(204, "")
send_resp(conn, 204, "")
end
def instructions(conn, _params) do
conn |> render(:instructions)
render(conn, :instructions)
end
def morse(conn, _params) do
conn |> render(:morse)
LiveView.Controller.live_render(conn, UiWeb.MorseLive, session: %{})
end
def start(conn, _params) do
response =
case Morse.Server.start_morse() do
:ok -> "Started."
{:error, :already_started} -> "The process is still in progress..."
end
conn |> text(response)
end
end

View file

@ -1,9 +1,7 @@
defmodule UiWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :ui
socket "/socket", UiWeb.UserSocket,
websocket: true,
longpoll: false
socket "/live", Phoenix.LiveView.Socket
# Serve at "/" the static files from "priv/static" directory.
#
@ -17,7 +15,6 @@ defmodule UiWeb.Endpoint do
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
IO.inspect code_reloading?
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader

View file

@ -0,0 +1,23 @@
defmodule UiWeb.MorseLive do
use Phoenix.LiveView
@topic "morse_progress"
def render(assigns) do
UiWeb.PageView.render("morse.html", assigns)
end
def mount(_session, socket) do
UiWeb.Endpoint.subscribe(@topic)
{:ok, assign(socket, progress: Morse.Server.progress())}
end
def handle_event("start_morse", _value, socket) do
Morse.Server.start_morse()
{:noreply, socket}
end
def handle_info(progress, socket) do
{:noreply, assign(socket, progress: progress)}
end
end

View file

@ -5,6 +5,7 @@ defmodule UiWeb.Router do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug Phoenix.LiveView.Flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
@ -26,6 +27,6 @@ defmodule UiWeb.Router do
get "/OB13", PageController, :morse
get "/seinlamp", PageController, :morse
get "/start", PageController, :start
# get "/start", PageController, :start
end
end

View file

@ -3,12 +3,12 @@
<h2>nl:<br>Druk op de Start knop hieronder om <span style="color:red">UVW</span><span style="color:blue">XYZ</span> te vinden. Je kunt dan de geocache vinden op N 52&deg; 40.<span style="color:red">UVW</span>' E 004&deg; 53.<span style="color:blue">XYZ</span>'</h2>
<div id="buttonwrap">
<input onclick="start()" value="Start" type="button" class="button">
<div id="response-block" style="visibility:hidden">
<button phx-click="start_morse" class="button">Start</button>
<div id="response-block">
<h2>Response status:</h2>
<p id="response"></p>
<h2>Progress:</h2>
<progress id="morse-progress" max="100" value="0">0%</progress>
<progress max="100" value="<%= @progress %>"><%= @progress %>%</progress>
</div>
</div>
@ -24,22 +24,6 @@
</div>
<script>
var responseP = document.getElementById("response");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
responseP.innerHTML = this.responseText;
}
};
function start() {
responseP.innerHTML = "Starting...";
document.getElementById("response-block").style.visibility = "visible";
xhttp.open("GET", "/start", true);
xhttp.send();
}
function givehint() {
document.getElementById("givehint").style.visibility = "visible";
}

View file

@ -36,6 +36,7 @@ defmodule Ui.MixProject do
{:phoenix_pubsub, "~> 1.1"},
{:phoenix_html, "~> 2.11"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:phoenix_live_view, "~> 0.3.1"},
{:gettext, "~> 0.11"},
{:jason, "~> 1.0"},
{:plug_cowboy, "~> 2.0"},

View file

@ -10,6 +10,7 @@
"phoenix": {:hex, :phoenix, "1.4.9", "746d098e10741c334d88143d3c94cab1756435f94387a63441792e66ec0ee974", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 1.1", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:plug, "~> 1.8.1 or ~> 1.9", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 1.0 or ~> 2.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm"},
"phoenix_html": {:hex, :phoenix_html, "2.13.3", "850e292ff6e204257f5f9c4c54a8cb1f6fbc16ed53d360c2b780a3d0ba333867", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"},
"phoenix_live_reload": {:hex, :phoenix_live_reload, "1.2.1", "274a4b07c4adbdd7785d45a8b0bb57634d0b4f45b18d2c508b26c0344bd59b8f", [:mix], [{:file_system, "~> 0.2.1 or ~> 0.3", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm"},
"phoenix_live_view": {:hex, :phoenix_live_view, "0.3.1", "5474c9e70db4e5bb23c1d1200d9a119ee76b927f3352554d31f5f31eaa1ea568", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.4.9", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.13.2", [hex: :phoenix_html, repo: "hexpm", optional: false]}], "hexpm"},
"phoenix_pubsub": {:hex, :phoenix_pubsub, "1.1.2", "496c303bdf1b2e98a9d26e89af5bba3ab487ba3a3735f74bf1f4064d2a845a3e", [:mix], [], "hexpm"},
"plug": {:hex, :plug, "1.8.2", "0bcce1daa420f189a6491f3940cc77ea7fb1919761175c9c3b59800d897440fc", [:mix], [{:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: true]}], "hexpm"},
"plug_cowboy": {:hex, :plug_cowboy, "2.1.0", "b75768153c3a8a9e8039d4b25bb9b14efbc58e9c4a6e6a270abff1cd30cbe320", [:mix], [{:cowboy, "~> 2.5", [hex: :cowboy, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"},