diff --git a/.formatter.exs b/.formatter.exs new file mode 100644 index 0000000..5b550b5 --- /dev/null +++ b/.formatter.exs @@ -0,0 +1,6 @@ +[ + plugins: [Phoenix.LiveView.HTMLFormatter], + inputs: ["*.{heex,ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{heex,ex,exs}"], + import_deps: [:ecto, :phoenix], + subdirectories: ["priv/*/migrations"] +] diff --git a/.gitignore b/.gitignore index 6704566..5992bbc 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,40 @@ dist # TernJS port file .tern-port + +package-lock.json + +# Phoenix gitignore values +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where 3rd-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Ignore package tarball (built via "mix hex.build"). +app-*.tar + +# Ignore assets that are produced by build tools. +/priv/static/assets/ + +# Ignore digested assets cache. +/priv/static/cache_manifest.json + +# In case you use Node.js/npm, you want to ignore these. +npm-debug.log +/assets/node_modules/ diff --git a/README.md b/README.md index d3c4261..3feb7f7 100644 --- a/README.md +++ b/README.md @@ -88,4 +88,12 @@ Once you have a basic understanding of how Alpine.js's directives work. checkout our Stopwatch example: https://dwyl.github.io/learn-alpine.js/stopwatch.html -Code: [**`stopwatch.html`**](https://github.com/dwyl/learn-alpine.js/blob/main/stopwatch.html) \ No newline at end of file +Code: [**`stopwatch.html`**](https://github.com/dwyl/learn-alpine.js/blob/main/stopwatch.html) + +### Drag and drop + +Along the nodejs application used for the sotopwatch example, +we have created a Phoenix application to test see how drag-and-drop +can be implemented using Alpinejs. + +See [drag-and-drop.md](drag-and-drop.md) diff --git a/assets/css/app.css b/assets/css/app.css new file mode 100644 index 0000000..f2098fa --- /dev/null +++ b/assets/css/app.css @@ -0,0 +1,132 @@ +/* This file is for your main application CSS */ +@import "./phoenix.css"; + +/* Alerts and form errors used by phx.new */ +.alert { + padding: 15px; + margin-bottom: 20px; + border: 1px solid transparent; + border-radius: 4px; +} +.alert-info { + color: #31708f; + background-color: #d9edf7; + border-color: #bce8f1; +} +.alert-warning { + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #faebcc; +} +.alert-danger { + color: #a94442; + background-color: #f2dede; + border-color: #ebccd1; +} +.alert p { + margin-bottom: 0; +} +.alert:empty { + display: none; +} +.invalid-feedback { + color: #a94442; + display: block; + margin: -1rem 0 2rem; +} + +/* LiveView specific classes for your customization */ +.phx-no-feedback.invalid-feedback, +.phx-no-feedback .invalid-feedback { + display: none; +} + +.phx-click-loading { + opacity: 0.5; + transition: opacity 1s ease-out; +} + +.phx-loading{ + cursor: wait; +} + +.phx-modal { + opacity: 1!important; + position: fixed; + z-index: 1; + left: 0; + top: 0; + width: 100%; + height: 100%; + overflow: auto; + background-color: rgba(0,0,0,0.4); +} + +.phx-modal-content { + background-color: #fefefe; + margin: 15vh auto; + padding: 20px; + border: 1px solid #888; + width: 80%; +} + +.phx-modal-close { + color: #aaa; + float: right; + font-size: 28px; + font-weight: bold; +} + +.phx-modal-close:hover, +.phx-modal-close:focus { + color: black; + text-decoration: none; + cursor: pointer; +} + +.fade-in-scale { + animation: 0.2s ease-in 0s normal forwards 1 fade-in-scale-keys; +} + +.fade-out-scale { + animation: 0.2s ease-out 0s normal forwards 1 fade-out-scale-keys; +} + +.fade-in { + animation: 0.2s ease-out 0s normal forwards 1 fade-in-keys; +} +.fade-out { + animation: 0.2s ease-out 0s normal forwards 1 fade-out-keys; +} + +@keyframes fade-in-scale-keys{ + 0% { scale: 0.95; opacity: 0; } + 100% { scale: 1.0; opacity: 1; } +} + +@keyframes fade-out-scale-keys{ + 0% { scale: 1.0; opacity: 1; } + 100% { scale: 0.95; opacity: 0; } +} + +@keyframes fade-in-keys{ + 0% { opacity: 0; } + 100% { opacity: 1; } +} + +@keyframes fade-out-keys{ + 0% { opacity: 1; } + 100% { opacity: 0; } +} + +.cursor-grab{ + cursor: grab; +} + +.cursor-grabbing{ + cursor: grabbing; +} + +.bg-yellow-300{ + background-color: rgb(253 224 71); +} diff --git a/assets/css/phoenix.css b/assets/css/phoenix.css new file mode 100644 index 0000000..0d59050 --- /dev/null +++ b/assets/css/phoenix.css @@ -0,0 +1,101 @@ +/* Includes some default style for the starter application. + * This can be safely deleted to start fresh. + */ + +/* Milligram v1.4.1 https://milligram.github.io + * Copyright (c) 2020 CJ Patoilo Licensed under the MIT license + */ + +*,*:after,*:before{box-sizing:inherit}html{box-sizing:border-box;font-size:62.5%}body{color:#000000;font-family:'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;font-size:1.6em;font-weight:300;letter-spacing:.01em;line-height:1.6}blockquote{border-left:0.3rem solid #d1d1d1;margin-left:0;margin-right:0;padding:1rem 1.5rem}blockquote *:last-child{margin-bottom:0}.button,button,input[type='button'],input[type='reset'],input[type='submit']{background-color:#0069d9;border:0.1rem solid #0069d9;border-radius:.4rem;color:#fff;cursor:pointer;display:inline-block;font-size:1.1rem;font-weight:700;height:3.8rem;letter-spacing:.1rem;line-height:3.8rem;padding:0 3.0rem;text-align:center;text-decoration:none;text-transform:uppercase;white-space:nowrap}.button:focus,.button:hover,button:focus,button:hover,input[type='button']:focus,input[type='button']:hover,input[type='reset']:focus,input[type='reset']:hover,input[type='submit']:focus,input[type='submit']:hover{background-color:#606c76;border-color:#606c76;color:#fff;outline:0}.button[disabled],button[disabled],input[type='button'][disabled],input[type='reset'][disabled],input[type='submit'][disabled]{cursor:default;opacity:.5}.button[disabled]:focus,.button[disabled]:hover,button[disabled]:focus,button[disabled]:hover,input[type='button'][disabled]:focus,input[type='button'][disabled]:hover,input[type='reset'][disabled]:focus,input[type='reset'][disabled]:hover,input[type='submit'][disabled]:focus,input[type='submit'][disabled]:hover{background-color:#0069d9;border-color:#0069d9}.button.button-outline,button.button-outline,input[type='button'].button-outline,input[type='reset'].button-outline,input[type='submit'].button-outline{background-color:transparent;color:#0069d9}.button.button-outline:focus,.button.button-outline:hover,button.button-outline:focus,button.button-outline:hover,input[type='button'].button-outline:focus,input[type='button'].button-outline:hover,input[type='reset'].button-outline:focus,input[type='reset'].button-outline:hover,input[type='submit'].button-outline:focus,input[type='submit'].button-outline:hover{background-color:transparent;border-color:#606c76;color:#606c76}.button.button-outline[disabled]:focus,.button.button-outline[disabled]:hover,button.button-outline[disabled]:focus,button.button-outline[disabled]:hover,input[type='button'].button-outline[disabled]:focus,input[type='button'].button-outline[disabled]:hover,input[type='reset'].button-outline[disabled]:focus,input[type='reset'].button-outline[disabled]:hover,input[type='submit'].button-outline[disabled]:focus,input[type='submit'].button-outline[disabled]:hover{border-color:inherit;color:#0069d9}.button.button-clear,button.button-clear,input[type='button'].button-clear,input[type='reset'].button-clear,input[type='submit'].button-clear{background-color:transparent;border-color:transparent;color:#0069d9}.button.button-clear:focus,.button.button-clear:hover,button.button-clear:focus,button.button-clear:hover,input[type='button'].button-clear:focus,input[type='button'].button-clear:hover,input[type='reset'].button-clear:focus,input[type='reset'].button-clear:hover,input[type='submit'].button-clear:focus,input[type='submit'].button-clear:hover{background-color:transparent;border-color:transparent;color:#606c76}.button.button-clear[disabled]:focus,.button.button-clear[disabled]:hover,button.button-clear[disabled]:focus,button.button-clear[disabled]:hover,input[type='button'].button-clear[disabled]:focus,input[type='button'].button-clear[disabled]:hover,input[type='reset'].button-clear[disabled]:focus,input[type='reset'].button-clear[disabled]:hover,input[type='submit'].button-clear[disabled]:focus,input[type='submit'].button-clear[disabled]:hover{color:#0069d9}code{background:#f4f5f6;border-radius:.4rem;font-size:86%;margin:0 .2rem;padding:.2rem .5rem;white-space:nowrap}pre{background:#f4f5f6;border-left:0.3rem solid #0069d9;overflow-y:hidden}pre>code{border-radius:0;display:block;padding:1rem 1.5rem;white-space:pre}hr{border:0;border-top:0.1rem solid #f4f5f6;margin:3.0rem 0}input[type='color'],input[type='date'],input[type='datetime'],input[type='datetime-local'],input[type='email'],input[type='month'],input[type='number'],input[type='password'],input[type='search'],input[type='tel'],input[type='text'],input[type='url'],input[type='week'],input:not([type]),textarea,select{-webkit-appearance:none;background-color:transparent;border:0.1rem solid #d1d1d1;border-radius:.4rem;box-shadow:none;box-sizing:inherit;height:3.8rem;padding:.6rem 1.0rem .7rem;width:100%}input[type='color']:focus,input[type='date']:focus,input[type='datetime']:focus,input[type='datetime-local']:focus,input[type='email']:focus,input[type='month']:focus,input[type='number']:focus,input[type='password']:focus,input[type='search']:focus,input[type='tel']:focus,input[type='text']:focus,input[type='url']:focus,input[type='week']:focus,input:not([type]):focus,textarea:focus,select:focus{border-color:#0069d9;outline:0}select{background:url('data:image/svg+xml;utf8,') center right no-repeat;padding-right:3.0rem}select:focus{background-image:url('data:image/svg+xml;utf8,')}select[multiple]{background:none;height:auto}textarea{min-height:6.5rem}label,legend{display:block;font-size:1.6rem;font-weight:700;margin-bottom:.5rem}fieldset{border-width:0;padding:0}input[type='checkbox'],input[type='radio']{display:inline}.label-inline{display:inline-block;font-weight:normal;margin-left:.5rem}.container{margin:0 auto;max-width:112.0rem;padding:0 2.0rem;position:relative;width:100%}.row{display:flex;flex-direction:column;padding:0;width:100%}.row.row-no-padding{padding:0}.row.row-no-padding>.column{padding:0}.row.row-wrap{flex-wrap:wrap}.row.row-top{align-items:flex-start}.row.row-bottom{align-items:flex-end}.row.row-center{align-items:center}.row.row-stretch{align-items:stretch}.row.row-baseline{align-items:baseline}.row .column{display:block;flex:1 1 auto;margin-left:0;max-width:100%;width:100%}.row .column.column-offset-10{margin-left:10%}.row .column.column-offset-20{margin-left:20%}.row .column.column-offset-25{margin-left:25%}.row .column.column-offset-33,.row .column.column-offset-34{margin-left:33.3333%}.row .column.column-offset-40{margin-left:40%}.row .column.column-offset-50{margin-left:50%}.row .column.column-offset-60{margin-left:60%}.row .column.column-offset-66,.row .column.column-offset-67{margin-left:66.6666%}.row .column.column-offset-75{margin-left:75%}.row .column.column-offset-80{margin-left:80%}.row .column.column-offset-90{margin-left:90%}.row .column.column-10{flex:0 0 10%;max-width:10%}.row .column.column-20{flex:0 0 20%;max-width:20%}.row .column.column-25{flex:0 0 25%;max-width:25%}.row .column.column-33,.row .column.column-34{flex:0 0 33.3333%;max-width:33.3333%}.row .column.column-40{flex:0 0 40%;max-width:40%}.row .column.column-50{flex:0 0 50%;max-width:50%}.row .column.column-60{flex:0 0 60%;max-width:60%}.row .column.column-66,.row .column.column-67{flex:0 0 66.6666%;max-width:66.6666%}.row .column.column-75{flex:0 0 75%;max-width:75%}.row .column.column-80{flex:0 0 80%;max-width:80%}.row .column.column-90{flex:0 0 90%;max-width:90%}.row .column .column-top{align-self:flex-start}.row .column .column-bottom{align-self:flex-end}.row .column .column-center{align-self:center}@media (min-width: 40rem){.row{flex-direction:row;margin-left:-1.0rem;width:calc(100% + 2.0rem)}.row .column{margin-bottom:inherit;padding:0 1.0rem}}a{color:#0069d9;text-decoration:none}a:focus,a:hover{color:#606c76}dl,ol,ul{list-style:none;margin-top:0;padding-left:0}dl dl,dl ol,dl ul,ol dl,ol ol,ol ul,ul dl,ul ol,ul ul{font-size:90%;margin:1.5rem 0 1.5rem 3.0rem}ol{list-style:decimal inside}ul{list-style:circle inside}.button,button,dd,dt,li{margin-bottom:1.0rem}fieldset,input,select,textarea{margin-bottom:1.5rem}blockquote,dl,figure,form,ol,p,pre,table,ul{margin-bottom:2.5rem}table{border-spacing:0;display:block;overflow-x:auto;text-align:left;width:100%}td,th{border-bottom:0.1rem solid #e1e1e1;padding:1.2rem 1.5rem}td:first-child,th:first-child{padding-left:0}td:last-child,th:last-child{padding-right:0}@media (min-width: 40rem){table{display:table;overflow-x:initial}}b,strong{font-weight:bold}p{margin-top:0}h1,h2,h3,h4,h5,h6{font-weight:300;letter-spacing:-.1rem;margin-bottom:2.0rem;margin-top:0}h1{font-size:4.6rem;line-height:1.2}h2{font-size:3.6rem;line-height:1.25}h3{font-size:2.8rem;line-height:1.3}h4{font-size:2.2rem;letter-spacing:-.08rem;line-height:1.35}h5{font-size:1.8rem;letter-spacing:-.05rem;line-height:1.5}h6{font-size:1.6rem;letter-spacing:0;line-height:1.4}img{max-width:100%}.clearfix:after{clear:both;content:' ';display:table}.float-left{float:left}.float-right{float:right} + +/* General style */ +h1{font-size: 3.6rem; line-height: 1.25} +h2{font-size: 2.8rem; line-height: 1.3} +h3{font-size: 2.2rem; letter-spacing: -.08rem; line-height: 1.35} +h4{font-size: 1.8rem; letter-spacing: -.05rem; line-height: 1.5} +h5{font-size: 1.6rem; letter-spacing: 0; line-height: 1.4} +h6{font-size: 1.4rem; letter-spacing: 0; line-height: 1.2} +pre{padding: 1em;} + +.container{ + margin: 0 auto; + max-width: 80.0rem; + padding: 0 2.0rem; + position: relative; + width: 100% +} +select { + width: auto; +} + +/* Phoenix promo and logo */ +.phx-hero { + text-align: center; + border-bottom: 1px solid #e3e3e3; + background: #eee; + border-radius: 6px; + padding: 3em 3em 1em; + margin-bottom: 3rem; + font-weight: 200; + font-size: 120%; +} +.phx-hero input { + background: #ffffff; +} +.phx-logo { + min-width: 300px; + margin: 1rem; + display: block; +} +.phx-logo img { + width: auto; + display: block; +} + +/* Headers */ +header { + width: 100%; + background: #fdfdfd; + border-bottom: 1px solid #eaeaea; + margin-bottom: 2rem; +} +header section { + align-items: center; + display: flex; + flex-direction: column; + justify-content: space-between; +} +header section :first-child { + order: 2; +} +header section :last-child { + order: 1; +} +header nav ul, +header nav li { + margin: 0; + padding: 0; + display: block; + text-align: right; + white-space: nowrap; +} +header nav ul { + margin: 1rem; + margin-top: 0; +} +header nav a { + display: block; +} + +@media (min-width: 40.0rem) { /* Small devices (landscape phones, 576px and up) */ + header section { + flex-direction: row; + } + header nav ul { + margin: 1rem; + } + .phx-logo { + flex-basis: 527px; + margin: 2rem 1rem; + } +} diff --git a/assets/js/app.js b/assets/js/app.js new file mode 100644 index 0000000..a1f4390 --- /dev/null +++ b/assets/js/app.js @@ -0,0 +1,117 @@ +// We import the CSS which is extracted to its own file by esbuild. +// Remove this line if you add a your own CSS build pipeline (e.g postcss). +import "../css/app.css" + +// If you want to use Phoenix channels, run `mix help phx.gen.channel` +// to get started and then uncomment the line below. +// import "./user_socket.js" + +// You can include dependencies in two ways. +// +// The simplest option is to put them in assets/vendor and +// import them using relative paths: +// +// import "../vendor/some-package.js" +// +// Alternatively, you can `npm install some-package --prefix assets` and import +// them using a path starting with the package name: +// +// import "some-package" +// + +// Include phoenix_html to handle method=PUT/DELETE in forms and buttons. +import "phoenix_html" +// Establish Phoenix Socket and LiveView configuration. +import {Socket} from "phoenix" +import {LiveSocket} from "phoenix_live_view" +import topbar from "../vendor/topbar" + +let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") + +let Hooks = {}; +Hooks.Items = { + mounted() { + const hook = this + + this.el.addEventListener("highlight", e => { + hook.pushEventTo("#items", "highlight", {id: e.detail.id}) + }) + + this.el.addEventListener("remove-highlight", e => { + hook.pushEventTo("#items", "remove-highlight", {id: e.detail.id}) + }) + + this.el.addEventListener("dragoverItem", e => { + const currentItemId = e.detail.currentItemId + const selectedItemId = e.detail.selectedItemId + if( currentItemId != selectedItemId) { + hook.pushEventTo("#items", "dragoverItem", {currentItemId: currentItemId, selectedItemId: selectedItemId}) + } + }) + + this.el.addEventListener("update-indexes", e => { + console.log('yyyyy') + const ids = [...document.querySelectorAll(".item")].map( i => i.dataset.id) + hook.pushEventTo("#items", "updateIndexes", {ids: ids}) + }) + } +} +let liveSocket = new LiveSocket("/live", Socket, { + hooks: Hooks, + dom:{ + onBeforeElUpdated(from, to) { + if (from._x_dataStack) { + window.Alpine.clone(from, to) + } + } + }, + params: {_csrf_token: csrfToken} +}) + +// Show progress bar on live navigation and form submits +topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) +window.addEventListener("phx:page-loading-start", info => topbar.show()) +window.addEventListener("phx:page-loading-stop", info => topbar.hide()) + +window.addEventListener("phx:highlight", (e) => { + document.querySelectorAll("[data-highlight]").forEach(el => { + if(el.id == e.detail.id) { + liveSocket.execJS(el, el.getAttribute("data-highlight")) + } + }) +}) + +window.addEventListener("phx:remove-highlight", (e) => { + document.querySelectorAll("[data-highlight]").forEach(el => { + if(el.id == e.detail.id) { + liveSocket.execJS(el, el.getAttribute("data-remove-highlight")) + } + }) +}) + +window.addEventListener("phx:dragover-item", (e) => { + const selectedItem = document.querySelector(`#${e.detail.selected_item_id}`) + const currentItem = document.querySelector(`#${e.detail.current_item_id}`) + + const items = document.querySelector('#items') + const listItems = [...document.querySelectorAll('.item')] + + console.log(selectedItem, currentItem) + + if(listItems.indexOf(selectedItem) < listItems.indexOf(currentItem)){ + items.insertBefore(selectedItem, currentItem.nextSibling) + } + + if(listItems.indexOf(selectedItem) > listItems.indexOf(currentItem)){ + items.insertBefore(selectedItem, currentItem) + } +}) + +// connect if there are any LiveViews on the page +liveSocket.connect() + +// expose liveSocket on window for web console debug logs and latency simulation: +// >> liveSocket.enableDebug() +// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session +// >> liveSocket.disableLatencySim() +window.liveSocket = liveSocket diff --git a/assets/vendor/topbar.js b/assets/vendor/topbar.js new file mode 100644 index 0000000..1f62209 --- /dev/null +++ b/assets/vendor/topbar.js @@ -0,0 +1,157 @@ +/** + * @license MIT + * topbar 1.0.0, 2021-01-06 + * https://buunguyen.github.io/topbar + * Copyright (c) 2021 Buu Nguyen + */ +(function (window, document) { + "use strict"; + + // https://gist.github.com/paulirish/1579671 + (function () { + var lastTime = 0; + var vendors = ["ms", "moz", "webkit", "o"]; + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + window.requestAnimationFrame = + window[vendors[x] + "RequestAnimationFrame"]; + window.cancelAnimationFrame = + window[vendors[x] + "CancelAnimationFrame"] || + window[vendors[x] + "CancelRequestAnimationFrame"]; + } + if (!window.requestAnimationFrame) + window.requestAnimationFrame = function (callback, element) { + var currTime = new Date().getTime(); + var timeToCall = Math.max(0, 16 - (currTime - lastTime)); + var id = window.setTimeout(function () { + callback(currTime + timeToCall); + }, timeToCall); + lastTime = currTime + timeToCall; + return id; + }; + if (!window.cancelAnimationFrame) + window.cancelAnimationFrame = function (id) { + clearTimeout(id); + }; + })(); + + var canvas, + progressTimerId, + fadeTimerId, + currentProgress, + showing, + addEvent = function (elem, type, handler) { + if (elem.addEventListener) elem.addEventListener(type, handler, false); + else if (elem.attachEvent) elem.attachEvent("on" + type, handler); + else elem["on" + type] = handler; + }, + options = { + autoRun: true, + barThickness: 3, + barColors: { + 0: "rgba(26, 188, 156, .9)", + ".25": "rgba(52, 152, 219, .9)", + ".50": "rgba(241, 196, 15, .9)", + ".75": "rgba(230, 126, 34, .9)", + "1.0": "rgba(211, 84, 0, .9)", + }, + shadowBlur: 10, + shadowColor: "rgba(0, 0, 0, .6)", + className: null, + }, + repaint = function () { + canvas.width = window.innerWidth; + canvas.height = options.barThickness * 5; // need space for shadow + + var ctx = canvas.getContext("2d"); + ctx.shadowBlur = options.shadowBlur; + ctx.shadowColor = options.shadowColor; + + var lineGradient = ctx.createLinearGradient(0, 0, canvas.width, 0); + for (var stop in options.barColors) + lineGradient.addColorStop(stop, options.barColors[stop]); + ctx.lineWidth = options.barThickness; + ctx.beginPath(); + ctx.moveTo(0, options.barThickness / 2); + ctx.lineTo( + Math.ceil(currentProgress * canvas.width), + options.barThickness / 2 + ); + ctx.strokeStyle = lineGradient; + ctx.stroke(); + }, + createCanvas = function () { + canvas = document.createElement("canvas"); + var style = canvas.style; + style.position = "fixed"; + style.top = style.left = style.right = style.margin = style.padding = 0; + style.zIndex = 100001; + style.display = "none"; + if (options.className) canvas.classList.add(options.className); + document.body.appendChild(canvas); + addEvent(window, "resize", repaint); + }, + topbar = { + config: function (opts) { + for (var key in opts) + if (options.hasOwnProperty(key)) options[key] = opts[key]; + }, + show: function () { + if (showing) return; + showing = true; + if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId); + if (!canvas) createCanvas(); + canvas.style.opacity = 1; + canvas.style.display = "block"; + topbar.progress(0); + if (options.autoRun) { + (function loop() { + progressTimerId = window.requestAnimationFrame(loop); + topbar.progress( + "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2) + ); + })(); + } + }, + progress: function (to) { + if (typeof to === "undefined") return currentProgress; + if (typeof to === "string") { + to = + (to.indexOf("+") >= 0 || to.indexOf("-") >= 0 + ? currentProgress + : 0) + parseFloat(to); + } + currentProgress = to > 1 ? 1 : to; + repaint(); + return currentProgress; + }, + hide: function () { + if (!showing) return; + showing = false; + if (progressTimerId != null) { + window.cancelAnimationFrame(progressTimerId); + progressTimerId = null; + } + (function loop() { + if (topbar.progress("+.1") >= 1) { + canvas.style.opacity -= 0.05; + if (canvas.style.opacity <= 0.05) { + canvas.style.display = "none"; + fadeTimerId = null; + return; + } + } + fadeTimerId = window.requestAnimationFrame(loop); + })(); + }, + }; + + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = topbar; + } else if (typeof define === "function" && define.amd) { + define(function () { + return topbar; + }); + } else { + this.topbar = topbar; + } +}.call(this, window, document)); diff --git a/config/config.exs b/config/config.exs new file mode 100644 index 0000000..1402ed4 --- /dev/null +++ b/config/config.exs @@ -0,0 +1,40 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Config module. +# +# This configuration file is loaded before any dependency and +# is restricted to this project. + +# General application configuration +import Config + +config :app, + ecto_repos: [App.Repo] + +# Configures the endpoint +config :app, AppWeb.Endpoint, + url: [host: "localhost"], + render_errors: [view: AppWeb.ErrorView, accepts: ~w(html json), layout: false], + pubsub_server: App.PubSub, + live_view: [signing_salt: "RmlS3YZ/"] + +# Configure esbuild (the version is required) +config :esbuild, + version: "0.14.29", + default: [ + args: + ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), + cd: Path.expand("../assets", __DIR__), + env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} + ] + +# Configures Elixir's Logger +config :logger, :console, + format: "$time $metadata[$level] $message\n", + metadata: [:request_id] + +# Use Jason for JSON parsing in Phoenix +config :phoenix, :json_library, Jason + +# Import environment specific config. This must remain at the bottom +# of this file so it overrides the configuration defined above. +import_config "#{config_env()}.exs" diff --git a/config/dev.exs b/config/dev.exs new file mode 100644 index 0000000..b6917a0 --- /dev/null +++ b/config/dev.exs @@ -0,0 +1,74 @@ +import Config + +# Configure your database +config :app, App.Repo, + username: "postgres", + password: "postgres", + hostname: "localhost", + database: "app_dev", + stacktrace: true, + show_sensitive_data_on_connection_error: true, + pool_size: 10 + +# For development, we disable any cache and enable +# debugging and code reloading. +# +# The watchers configuration can be used to run external +# watchers to your application. For example, we use it +# with esbuild to bundle .js and .css sources. +config :app, AppWeb.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], + check_origin: false, + code_reloader: true, + debug_errors: true, + secret_key_base: "aMh0TI5FqAjFd9Xa+kRAlNfq1OzVb6NmiciLcpgiuU9mpCYjc78L+5cPte+Bqo0m", + watchers: [ + # Start the esbuild watcher by calling Esbuild.install_and_run(:default, args) + esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]} + ] + +# ## SSL Support +# +# In order to use HTTPS in development, a self-signed +# certificate can be generated by running the following +# Mix task: +# +# mix phx.gen.cert +# +# Note that this task requires Erlang/OTP 20 or later. +# Run `mix help phx.gen.cert` for more information. +# +# The `http:` config above can be replaced with: +# +# https: [ +# port: 4001, +# cipher_suite: :strong, +# keyfile: "priv/cert/selfsigned_key.pem", +# certfile: "priv/cert/selfsigned.pem" +# ], +# +# If desired, both `http:` and `https:` keys can be +# configured to run both http and https servers on +# different ports. + +# Watch static and templates for browser reloading. +config :app, AppWeb.Endpoint, + live_reload: [ + patterns: [ + ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", + ~r"lib/app_web/(live|views)/.*(ex)$", + ~r"lib/app_web/templates/.*(eex)$" + ] + ] + +# Do not include metadata nor timestamps in development logs +config :logger, :console, format: "[$level] $message\n" + +# Set a higher stacktrace during development. Avoid configuring such +# in production as building large stacktraces may be expensive. +config :phoenix, :stacktrace_depth, 20 + +# Initialize plugs at runtime for faster development compilation +config :phoenix, :plug_init_mode, :runtime diff --git a/config/prod.exs b/config/prod.exs new file mode 100644 index 0000000..d5f74e9 --- /dev/null +++ b/config/prod.exs @@ -0,0 +1,49 @@ +import Config + +# For production, don't forget to configure the url host +# to something meaningful, Phoenix uses this information +# when generating URLs. +# +# Note we also include the path to a cache manifest +# containing the digested version of static files. This +# manifest is generated by the `mix phx.digest` task, +# which you should run after static files are built and +# before starting your production server. +config :app, AppWeb.Endpoint, cache_static_manifest: "priv/static/cache_manifest.json" + +# Do not print debug messages in production +config :logger, level: :info + +# ## SSL Support +# +# To get SSL working, you will need to add the `https` key +# to the previous section and set your `:url` port to 443: +# +# config :app, AppWeb.Endpoint, +# ..., +# url: [host: "example.com", port: 443], +# https: [ +# ..., +# port: 443, +# cipher_suite: :strong, +# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), +# certfile: System.get_env("SOME_APP_SSL_CERT_PATH") +# ] +# +# The `cipher_suite` is set to `:strong` to support only the +# latest and more secure SSL ciphers. This means old browsers +# and clients may not be supported. You can set it to +# `:compatible` for wider support. +# +# `:keyfile` and `:certfile` expect an absolute path to the key +# and cert in disk or a relative path inside priv, for example +# "priv/ssl/server.key". For all supported SSL configuration +# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 +# +# We also recommend setting `force_ssl` in your endpoint, ensuring +# no data is ever sent via http, always redirecting to https: +# +# config :app, AppWeb.Endpoint, +# force_ssl: [hsts: true] +# +# Check `Plug.SSL` for all available options in `force_ssl`. diff --git a/config/runtime.exs b/config/runtime.exs new file mode 100644 index 0000000..f930961 --- /dev/null +++ b/config/runtime.exs @@ -0,0 +1,65 @@ +import Config + +# config/runtime.exs is executed for all environments, including +# during releases. It is executed after compilation and before the +# system starts, so it is typically used to load production configuration +# and secrets from environment variables or elsewhere. Do not define +# any compile-time configuration in here, as it won't be applied. +# The block below contains prod specific runtime configuration. + +# ## Using releases +# +# If you use `mix release`, you need to explicitly enable the server +# by passing the PHX_SERVER=true when you start it: +# +# PHX_SERVER=true bin/app start +# +# Alternatively, you can use `mix phx.gen.release` to generate a `bin/server` +# script that automatically sets the env var above. +if System.get_env("PHX_SERVER") do + config :app, AppWeb.Endpoint, server: true +end + +if config_env() == :prod do + database_url = + System.get_env("DATABASE_URL") || + raise """ + environment variable DATABASE_URL is missing. + For example: ecto://USER:PASS@HOST/DATABASE + """ + + maybe_ipv6 = if System.get_env("ECTO_IPV6"), do: [:inet6], else: [] + + config :app, App.Repo, + # ssl: true, + url: database_url, + pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"), + socket_options: maybe_ipv6 + + # The secret key base is used to sign/encrypt cookies and other secrets. + # A default value is used in config/dev.exs and config/test.exs but you + # want to use a different value for prod and you most likely don't want + # to check this value into version control, so we use an environment + # variable instead. + secret_key_base = + System.get_env("SECRET_KEY_BASE") || + raise """ + environment variable SECRET_KEY_BASE is missing. + You can generate one by calling: mix phx.gen.secret + """ + + host = System.get_env("PHX_HOST") || "example.com" + port = String.to_integer(System.get_env("PORT") || "4000") + + config :app, AppWeb.Endpoint, + url: [host: host, port: 443, scheme: "https"], + http: [ + # Enable IPv6 and bind on all interfaces. + # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. + # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html + # for details about using IPv6 vs IPv4 and loopback vs public addresses. + ip: {0, 0, 0, 0, 0, 0, 0, 0}, + port: port + ], + secret_key_base: secret_key_base +end diff --git a/config/test.exs b/config/test.exs new file mode 100644 index 0000000..0b59e37 --- /dev/null +++ b/config/test.exs @@ -0,0 +1,27 @@ +import Config + +# Configure your database +# +# The MIX_TEST_PARTITION environment variable can be used +# to provide built-in test partitioning in CI environment. +# Run `mix help test` for more information. +config :app, App.Repo, + username: "postgres", + password: "postgres", + hostname: "localhost", + database: "app_test#{System.get_env("MIX_TEST_PARTITION")}", + pool: Ecto.Adapters.SQL.Sandbox, + pool_size: 10 + +# We don't run a server during test. If one is required, +# you can enable the server option below. +config :app, AppWeb.Endpoint, + http: [ip: {127, 0, 0, 1}, port: 4002], + secret_key_base: "9ww3quhVNS/QGlR90nuvRsp4mo0iUNeQe8BNwsu7hL54c58IhSe3KDgQfU50WJvS", + server: false + +# Print only warnings and errors during test +config :logger, level: :warn + +# Initialize plugs at runtime for faster test compilation +config :phoenix, :plug_init_mode, :runtime diff --git a/drag-and-drop.md b/drag-and-drop.md new file mode 100644 index 0000000..d373fdb --- /dev/null +++ b/drag-and-drop.md @@ -0,0 +1,870 @@ +
+ +# Drag and drop + +A drag and drop implementation +using `Alpine.js` +and +`Phoenix LiveView` +to sort a list of items. + +
+ +The drag and drop actions +are _visible_ in real time across any browsers connected +to the `Phoenix LiveView` app. + + +- [Drag and drop](#drag-and-drop) + - [0. Technical Info](#0-technical-info) + - [1. Initialisation](#1-initialisation) + - [2. Create items](#2-create-items) + - [3. Make it Real Time](#3-make-it-real-time) + - [4. Drag and Drop](#4-drag-and-drop) + + +## 0. Technical Info + +The following versions were used: + +- `Phoenix`: 1.6.15 +- `LiveView`: 0.17.12 +- `Alpine.js`: 3.x.x + +> **Note**: If your versions are different from these +> and anything is not working, +> please +> [open an issue](https://github.com/dwyl/learn-alpine.js/issues) + +## 1. Initialisation + +Start by creating a new `Phoenix` application: + +```sh +mix phx.new app --no-dashboard --no-gettext --no-mailer +``` +Install the dependencies when asked: + +```sh +Fetch and install dependencies? [Yn] y +``` + +Then follow the last instructions to make sure the Phoenix application +is running correctly: + +```sh +cd app +mix ecto.create +mix phx.server +``` + +Open the your web browser +to the the following URL: +[localhost:4000/](http://localhost:4000) +You should be able to see: + +![Phoenix App](https://user-images.githubusercontent.com/6057298/199209631-b3c084e0-62f4-43f2-a4bc-ccb57f101443.png) + + +We can now update the generated html +in `lib/app_web/templates/layout/root.html.heex` file: + +- Add Alpine.js CDN script tag, see [Alpine.js documentation](https://alpinejs.dev/essentials/installation) + `` +- Remove the `header` tag containing the Phoenix logo: + +```html + + + + + + + + + <%= live_title_tag(assigns[:page_title] || "App", suffix: " · Phoenix Framework") %> + + + + + <%= @inner_content %> + + +``` + +You can now run +`mix deps.get` +to make sure all dependencies are installed +followed by +`mix phx.server` + +## 2. Create items + +We can use the +[mix phx.gen.live](https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Live.html) +command to let `Phoenix` create the `LiveView` files: + +```sh +mix phx.gen.live Tasks Item items text:string index:integer` +``` + +This will create the: + +- [Tasks context](https://hexdocs.pm/phoenix/contexts.html) +- [Item schema](https://hexdocs.pm/ecto/Ecto.Schema.html) +- `items` table with the `text` and `index` fields + +`.heex` Template files and `LiveView` controllers will also be created. + +Update `lib/app_web/router.ex` to add the new endpoints: + +```elixir + scope "/", AppWeb do + pipe_through :browser + live "/", ItemLive.Index, :index + live "/items/new", ItemLive.Index, :new + live "/items/:id/edit", ItemLive.Index, :edit + + live "/items/:id", ItemLive.Show, :show + live "/items/:id/show/edit", ItemLive.Show, :edit + end +``` + + +in the `lib/app_web/live/item_live/index.html.heex` file, +remove the `edit` and `delete` +links as we won't use them: + +```heex +

Listing Items

+ +<%= if @live_action in [:new, :edit] do %> + <.modal return_to={Routes.item_index_path(@socket, :index)}> + <.live_component + module={AppWeb.ItemLive.FormComponent} + id={@item.id || :new} + title={@page_title} + action={@live_action} + item={@item} + return_to={Routes.item_index_path(@socket, :index)} + /> + +<% end %> + + + + + + + + + + <%= for item <- @items do %> + + + + + <% end %> + +
TextIndex
<%= item.text %><%= item.index %>
+ +<%= live_patch "New Item", to: Routes.item_index_path(@socket, :new) %> +``` + +> **Note**: the `<.modal>` component is created by **`phx.gen.live`**. +> It is not a UI/UX best-practice and should not be used in a _real_ App. + + +Then in +`lib/app_web/live/item_live/form_component.html.heex` +remove the +`label`, `number_input` and `error_tag` +linked to the `index` as we want our +server to set this value +when the `item` is created: + +```heex +
+

<%= @title %>

+ + <.form + let={f} + for={@changeset} + id="item-form" + phx-target={@myself} + phx-change="validate" + phx-submit="save"> + + <%= label f, :text %> + <%= text_input f, :text %> + <%= error_tag f, :text %> + +
+ <%= submit "Save", phx_disable_with: "Saving..." %> +
+ +
+``` + +Then we need to update our `Item` schema to be able to save a new item. +We want to remove the `:index` value from the `validate_required` function in the changeset. +Update `lib/app/tasks/item.ex`: + +```elixir +def changeset(item, attrs) do + item + |> cast(attrs, [:text, :index]) + |> validate_required([:text]) # index is removed +end +``` +Let's update the `create_item` function in `lib/app/tasks.ex` to make +sure Phoenix set the `index` value. +The item's index is equal to the number of existing items + 1: + +```elixir +def create_item(attrs \\ %{}) do + items = list_items() + index = length(items) + 1 + + %Item{} + |> Item.changeset(Map.put(attrs, "index", index)) + |> Repo.insert() +end +``` + +Finally we want to update the `list_items` function in the same file to get the +items order by their indexes: + +```elixir +def list_items do + Repo.all(from i in Item, order_by: i.index) +end +``` + +Running the application, you should see a UI similar to: + +![create-items](https://user-images.githubusercontent.com/6057298/199272881-0581b3f8-1e15-408b-9711-05747714a92a.png) +![list-items](https://user-images.githubusercontent.com/6057298/199272939-1343c915-df0b-4b52-a003-47d047e2c6a3.png) + +## 3. Make it Real Time + +[`PubSub`](https://hexdocs.pm/phoenix_pubsub/Phoenix.PubSub.html) is used +to send and listen to `messages`. Any clients connected to a `topic` can +listen for new messages on this topic. + +In this section we are using `PubSub` +to notify clients when new items are created. + +The first step is to connect the client +when the `LiveView` page is requested. +Add helper functions in +`lib/app/tasks.ex` +to manages the `PubSub` feature. +The first function is `subscribe`: + +```elixir +# Make sure to add the alias +alias Phoenix.PubSub + +# subscribe to the `liveview_items` topic +def subscribe() do + PubSub.subscribe(App.PubSub, "liveview_items") +end +``` + +Then in `lib/app_web/live/item_live/index.ex`, update the `mount` function to: + +```elixir +def mount(_params, _session, socket) do + if connected?(socket), do: Tasks.subscribe() + {:ok, assign(socket, :items, list_items())} +end +``` + +We are checking if the socket is properly connected to the client before calling +the new `subscribe` function. + + +We are going to write now the `notify` function which uses the +[PubSub.broadcast](https://hexdocs.pm/phoenix_pubsub/Phoenix.PubSub.html#broadcast/4) +function to dispatch messages to clients + +In `lib/app/tasks.ex`: + +```elixir +def notify({:ok, item}, event) do + PubSub.broadcast(App.PubSub, "liveview_items", {event, item}) + {:ok, item} +end + +def notify({:error, reason}, _event), do: {:error, reason} +``` + +Then call this function inside the `create_item` function: + +```elixir +def create_item(attrs \\ %{}) do + items = list_items() + index = length(items) + 1 + + %Item{} + |> Item.changeset(Map.put(attrs, "index", index)) + |> Repo.insert() + |> notify(:item_created) +end +``` + +The `notify` function will send the `:item_created` message to all clients. + +Finally we need to listen to this new messages and update our liveview. +In `lib/app_web/live/item_live/index.ex`, add: + +```elixir +@impl true +def handle_info({:item_created, _item}, socket) do + items = list_items() + {:noreply, assign(socket, items: items)} +end +``` + +When the client receive the `:item_created` we are getting the list of items +from the database and assigning the list to the socket. This will update the +liveview template with the new created item. + + +## 4. Drag and Drop + +Now that we can create `items`, +we can _finally_ start to implement our +drag and drop feature. + +To be able to use `Alpine.js` +with `Phoenix LiveView` +we need to update `asset/js/app.js`: + +```js +let liveSocket = new LiveSocket("/live", Socket, { + dom: { + onBeforeElUpdated(from, to) { + if (from._x_dataStack) { + window.Alpine.clone(from, to) + } + } + }, + params: {_csrf_token: csrfToken} +}) +``` + +This is to make sure `Alpine.js` keeps track +of the `DOM` changes created by `LiveView`. + +See the +[Phoenix LiveView JavaScript interoperability documentation](https://hexdocs.pm/phoenix_live_view/js-interop.html): + +![Alpine.js docs](https://user-images.githubusercontent.com/6057298/199215481-489e71fb-9a95-4d24-9484-e90b6257211c.png) + +Add the following content at the end of the `assets/css/app.css` file: + +```css +.cursor-grab{ + cursor: grab; +} + +.cursor-grabbing{ + cursor: grabbing; +} + +.bg-yellow-300{ + background-color: rgb(253 224 71); +} +``` + +These CSS classes will be used +to make our `items` +more visible when moved. + + +We are going to define an `Alpine.js` component using the +[`x-data`](https://alpinejs.dev/directives/data) +directive: + +> Everything in `Alpine` starts with the `x-data` directive. +`x-data` defines a chunk of `HTML` +as an `Alpine` component and +provides the reactive data for that component to reference. + +in `lib/app_web/live/item_live/index.html.heex`: + +```heex + + <%= for item <- @items do %> + + <%= item.text %> + <%= item.index %> + + <% end %> + +``` + +We have also added the +[`draggable` html attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable) +to the `tr` tags. + +To add an event listener to your html tag `Alpine.js` +provides the +[x-on](https://alpinejs.dev/directives/on) +attribute. +Listen for the +[**`dragstart`**](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragstart_event) +and +[**`dragend`**](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragend_event) +events: + + +```heex + + <%= for item <- @items do %> + + <%= item.text %> + <%= item.index %> + + <% end %> + +``` + +When the **`dragstart` event** is triggered +(i.e. an `item` is moved) +we update the newly +`selected` value define in `x-data` to **`true`**. +When the **`dragend` event** +is triggered we set `selected` to **`false`**. + +Finally we are using `x-bind:class` +to add a CSS class depending on the _value_ of +`selected`. +In this case we have customized the display of the cursor. + +To make the moved `item` a bit more obvious, +we also change the **background color**. + +In this step we also make sure that all connected clients can see +the new background color of the moved `item`! + +Update the `tr` tag with the following: + +```html + +``` + +The +[dispatch](https://alpinejs.dev/magics/dispatch) +`Alpine.js` function +sends a new custom `JS` event. +We use +[**`hooks`**](https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks-via-phx-hook) +to listen for this event +and then notify `LiveView`. + +In `assets/js/app.js`, +add above the `liveSocket` variable: + + +```javascript +let Hooks = {}; +Hooks.Items = { + mounted() { + const hook = this + + this.el.addEventListener("highlight", e => { + hook.pushEventTo("#items", "highlight", {id: e.detail.id}) + }) + + this.el.addEventListener("remove-highlight", e => { + hook.pushEventTo("#items", "remove-highlight", {id: e.detail.id}) + }) + } +} +``` + +Then add the Hooks `JS` object +to the `socket`: + +```javascript +let liveSocket = new LiveSocket("/live", Socket, { + hooks: Hooks, //Add hooks + dom: { + onBeforeElUpdated(from, to) { + if (from._x_dataStack) { + window.Alpine.clone(from, to) + } + } + }, + params: {_csrf_token: csrfToken} +}) +``` + +The last step for the hooks to initialized +is to add `phx-hook` attribute +in our +`lib/app_web/live/item_live/index.html.heex`: + +```heex + +``` + +Note that the value of `phx-hook` +must be the same as `Hooks.Items = ...` +defined in `app.js`, i.e. `Items`. + +We now have the `hooks` listening +to the `highlight` and `remove-highlight` events, +and we use the +[pushEventTo](https://hexdocs.pm/phoenix_live_view/js-interop.html#client-hooks-via-phx-hook) +function to send a message to the `LiveView` server. + +Let's add the following code to handle the new messages in +`lib/app_web/live/item_live/index.ex`. +Note that `Elixir` requires +the `handle_event` function definitions +to be grouped. + +```elixir +@impl true +def handle_event("highlight", %{"id" => id}, socket) do + Tasks.drag_item(id) + {:noreply, socket} +end + +@impl true +def handle_event("remove-highlight", %{"id" => id}, socket) do + Tasks.drop_item(id) + {:noreply, socket} +end +``` + +The `Tasks` functions `drag_item` and `drop_item` +are using `PubSub` to send +a message to all clients +to let them know which `item` is being moved: + +In `lib/app/tasks.ex`: + +```elixir +def drag_item(item_id) do + PubSub.broadcast(App.PubSub, "liveview_items", {:drag_item, item_id}) +end + +def drop_item(item_id) do + PubSub.broadcast(App.PubSub, "liveview_items", {:drop_item, item_id}) +end +``` + +Then back in +`lib/app_web/live/item_live/index.ex` +we handle these events with: + +```elixir +@impl true +def handle_info({:drag_item, item_id}, socket) do + {:noreply, push_event(socket, "highlight", %{id: item_id})} +end + +@impl true +def handle_info({:drop_item, item_id}, socket) do + {:noreply, push_event(socket, "remove-highlight", %{id: item_id})} +end +``` + +The LiveView will send the `highlight` +and `remove-highlight` to the client. +The final step is to handle these Phoenix events with +[Phoenix.LiveView.JS](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.JS.html) +to add and remove the background color. + +In `assets/js/app.js` add +(for example above `liveSocket.connect()`) +the event listeners: + +```javascript +window.addEventListener("phx:highlight", (e) => { + document.querySelectorAll("[data-highlight]").forEach(el => { + if(el.id == e.detail.id) { + liveSocket.execJS(el, el.getAttribute("data-highlight")) + } + }) +}) + +window.addEventListener("phx:remove-highlight", (e) => { + document.querySelectorAll("[data-highlight]").forEach(el => { + if(el.id == e.detail.id) { + liveSocket.execJS(el, el.getAttribute("data-remove-highlight")) + } + }) +}) +``` + +For each item we are checking if the id match the id linked to the drag/drop event, +then execute the Phoenix.LiveView.JS function that we now have to define back to our +`lib/app_web/live/item_live/index.html.heex` file. + +```heex + +``` + +To the call to `add_class` and `remove_class`, +you need to add +`alias Phoenix.LiveView.JS` +at the top of the file +`lib/app_web/live/item_live/index.ex` +This alias will make sure +the two functions +are accessible in the `LiveView` template. + + +Again there are a few steps to make sure the highlight for the selected item +is properly displayed. However all the clients should now be able to see +the drag/drop action! + + +So far we have added the code to be able to drag an item, however we haven't yet +implemented the code to sort the items. + +We want to switch the positions of the items when the selected item is hovering +over another item. +We are going to use the [dragover](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragover_event) +event for this: + + +```heex + + <%= for item <- @items do %> + +``` + +We have added `x-data="{selectedItem: null}` to the `tbody` html tag. +This value represents which element is currently being moved. + +We have also added the `class="item"`. This will be used later on in `app.js` +to get the list of items using `querySelectorAll`. + +Then we have +`x-on:dragover.throttle="$dispatch('dragoverItem', {selectedItemId: selectedItem.id, currentItemId: $el.id})"` + +The [throttle](https://alpinejs.dev/directives/on#throttle) Alpine.js modifier +will only send the event `dragoverItem` once every 250ms max. +Similar to how we manage the highlights events, we need to update the `app.js` file +and add to the Hooks: + + +```javascript +this.el.addEventListener("dragoverItem", e => { + const currentItemId = e.detail.currentItemId + const selectedItemId = e.detail.selectedItemId + if( currentItemId != selectedItemId) { + hook.pushEventTo("#items", "dragoverItem", {currentItemId: currentItemId, selectedItemId: selectedItemId}) + } +}) +``` + +We only want to push the `dragoverItem` +event to the server if the item is over +an item which is different than itself. + + +On the server side we now add + +- in `lib/app_web/live/item_live/index.ex`: + + +```elixir +@impl true +def handle_event( + "dragoverItem", + %{"currentItemId" => current_item_id, "selectedItemId" => selected_item_id}, + socket + ) do + Tasks.dragover_item(current_item_id, selected_item_id) + {:noreply, socket} +end +``` +and + +```elixir +@impl true +def handle_info({:dragover_item, {current_item_id, selected_item_id}}, socket) do + {:noreply, + push_event(socket, "dragover-item", %{ + current_item_id: current_item_id, + selected_item_id: selected_item_id + })} +end +``` + +Where `Tasks.dragover_item\2` is defined as: + +```elixir +def dragover_item(current_item_id, selected_item_id) do + PubSub.broadcast(App.PubSub, "liveview_items", {:dragover_item, {current_item_id,selected_item_id }}) +end +``` + +Finally we in `app.js`: + +```javascript +window.addEventListener("phx:dragover-item", (e) => { + const selectedItem = document.querySelector(`#${e.detail.selected_item_id}`) + const currentItem = document.querySelector(`#${e.detail.current_item_id}`) + + const items = document.querySelector('#items') + const listItems = [...document.querySelectorAll('.item')] + + if(listItems.indexOf(selectedItem) < listItems.indexOf(currentItem)){ + items.insertBefore(selectedItem, currentItem.nextSibling) + } + + if(listItems.indexOf(selectedItem) > listItems.indexOf(currentItem)){ + items.insertBefore(selectedItem, currentItem) + } +}) +``` + +We compare the selected item position +in the list with the "over" `item` +and use `insertBefore` `JS` function to add our `item` at the correct DOM place. + + +You should now be able to see on different clients the selected item +moved into the list during the drag and drop. +However we haven't updated the +indexes of the items yet. + +We want to send a new event when the **`dragend`** event is emitted: + +```heex + +``` + +We have added the `data-id` attribute to store the +`item.id` and created the +`$dispatch('update-indexes')` event. + +In `app.js` we listen to the event in the Hook: + +```javascript +this.el.addEventListener("update-indexes", e => { + const ids = [...document.querySelectorAll(".item")].map( i => i.dataset.id) + hook.pushEventTo("#items", "updateIndexes", {ids: ids}) +}) +``` + +We are creating a list of the items' id that we push to the LiveView server with the +event `updateIndexes` + +In `lib/app_web/live/item_live/index.ex` we add a new `handle_event` + +```elixir +@impl true +def handle_event("updateIndexes", %{"ids" => ids}, socket) do + Tasks.update_items_index(ids) + {:noreply, socket} +end +``` + +And in `tasks.ex`: + +```elixir +def update_items_index(ids) do + ids + |> Enum.with_index(fn id, index -> + item = get_item!(id) + update_item(item, %{index: index + 1}) + end) + + PubSub.broadcast(App.PubSub, "liveview_items", :indexes_updated) +end +``` + +For each id a new index is created using `Enum.with_index` and the item is updated. +(This might not be the best implementation for updating a list of items, so +if you think there is a better way to do this don't hesitate to open an issue, thanks!) + +Finally similar to the way we tell clients a new item has been created, we +broadcast a new message, `indexes_updated`: + +```elixir +@impl true +def handle_info(:indexes_updated, socket) do + items = list_items() + {:noreply, assign(socket, items: items)} +end +``` + +We fetch the `list` of `items` from the database +and let `LiveView` update the UI automatically. + +You should now have a complete drag-and-drop +feature shared with _multiple_ +clients! + +Connect a few browsers to the app URL: +[localhost:4000/](http://localhost:4000) + +You should see something similar to the following when you drag-and-drop `items`: + +![drag-and-drop-demo](https://user-images.githubusercontent.com/194400/199440271-dee75a14-f699-4e36-8ab6-d19a504b295e.gif) + + +Thanks for reading and again don't hesitate to open issues for questions, +enhancement, bug fixes... diff --git a/lib/app.ex b/lib/app.ex new file mode 100644 index 0000000..a10dc06 --- /dev/null +++ b/lib/app.ex @@ -0,0 +1,9 @@ +defmodule App do + @moduledoc """ + App keeps the contexts that define your domain + and business logic. + + Contexts are also responsible for managing your data, regardless + if it comes from the database, an external API or others. + """ +end diff --git a/lib/app/application.ex b/lib/app/application.ex new file mode 100644 index 0000000..7b9240f --- /dev/null +++ b/lib/app/application.ex @@ -0,0 +1,36 @@ +defmodule App.Application do + # See https://hexdocs.pm/elixir/Application.html + # for more information on OTP Applications + @moduledoc false + + use Application + + @impl true + def start(_type, _args) do + children = [ + # Start the Ecto repository + App.Repo, + # Start the Telemetry supervisor + AppWeb.Telemetry, + # Start the PubSub system + {Phoenix.PubSub, name: App.PubSub}, + # Start the Endpoint (http/https) + AppWeb.Endpoint + # Start a worker by calling: App.Worker.start_link(arg) + # {App.Worker, arg} + ] + + # See https://hexdocs.pm/elixir/Supervisor.html + # for other strategies and supported options + opts = [strategy: :one_for_one, name: App.Supervisor] + Supervisor.start_link(children, opts) + end + + # Tell Phoenix to update the endpoint configuration + # whenever the application is updated. + @impl true + def config_change(changed, _new, removed) do + AppWeb.Endpoint.config_change(changed, removed) + :ok + end +end diff --git a/lib/app/repo.ex b/lib/app/repo.ex new file mode 100644 index 0000000..857bd3f --- /dev/null +++ b/lib/app/repo.ex @@ -0,0 +1,5 @@ +defmodule App.Repo do + use Ecto.Repo, + otp_app: :app, + adapter: Ecto.Adapters.Postgres +end diff --git a/lib/app/tasks.ex b/lib/app/tasks.ex new file mode 100644 index 0000000..194978f --- /dev/null +++ b/lib/app/tasks.ex @@ -0,0 +1,146 @@ +defmodule App.Tasks do + @moduledoc """ + The Tasks context. + """ + + import Ecto.Query, warn: false + alias App.Repo + + alias App.Tasks.Item + alias Phoenix.PubSub + + def subscribe() do + PubSub.subscribe(App.PubSub, "liveview_items") + end + + def notify({:ok, item}, event) do + PubSub.broadcast(App.PubSub, "liveview_items", {event, item}) + {:ok, item} + end + + def notify({:error, reason}, _event), do: {:error, reason} + + @doc """ + Returns the list of items. + + ## Examples + + iex> list_items() + [%Item{}, ...] + + """ + def list_items do + Repo.all(from i in Item, order_by: i.index) + end + + @doc """ + Gets a single item. + + Raises `Ecto.NoResultsError` if the Item does not exist. + + ## Examples + + iex> get_item!(123) + %Item{} + + iex> get_item!(456) + ** (Ecto.NoResultsError) + + """ + def get_item!(id), do: Repo.get!(Item, id) + + @doc """ + Creates a item. + + ## Examples + + iex> create_item(%{field: value}) + {:ok, %Item{}} + + iex> create_item(%{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def create_item(attrs \\ %{}) do + items = list_items() + index = length(items) + 1 + + %Item{} + |> Item.changeset(Map.put(attrs, "index", index)) + |> Repo.insert() + |> notify(:item_created) + end + + @doc """ + Updates a item. + + ## Examples + + iex> update_item(item, %{field: new_value}) + {:ok, %Item{}} + + iex> update_item(item, %{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def update_item(%Item{} = item, attrs) do + item + |> Item.changeset(attrs) + |> Repo.update() + end + + @doc """ + Deletes a item. + + ## Examples + + iex> delete_item(item) + {:ok, %Item{}} + + iex> delete_item(item) + {:error, %Ecto.Changeset{}} + + """ + def delete_item(%Item{} = item) do + Repo.delete(item) + end + + @doc """ + Returns an `%Ecto.Changeset{}` for tracking item changes. + + ## Examples + + iex> change_item(item) + %Ecto.Changeset{data: %Item{}} + + """ + def change_item(%Item{} = item, attrs \\ %{}) do + Item.changeset(item, attrs) + end + + def drag_item(item_id) do + PubSub.broadcast(App.PubSub, "liveview_items", {:drag_item, item_id}) + end + + def drop_item(item_id) do + PubSub.broadcast(App.PubSub, "liveview_items", {:drop_item, item_id}) + end + + def dragover_item(current_item_id, selected_item_id) do + PubSub.broadcast( + App.PubSub, + "liveview_items", + {:dragover_item, {current_item_id, selected_item_id}} + ) + end + + def update_items_index(ids) do + ids + |> Enum.with_index(fn id, index -> + item = get_item!(id) + update_item(item, %{index: index + 1}) + end) + + PubSub.broadcast(App.PubSub, "liveview_items", :indexes_updated) + end +end diff --git a/lib/app/tasks/item.ex b/lib/app/tasks/item.ex new file mode 100644 index 0000000..b905997 --- /dev/null +++ b/lib/app/tasks/item.ex @@ -0,0 +1,18 @@ +defmodule App.Tasks.Item do + use Ecto.Schema + import Ecto.Changeset + + schema "items" do + field :index, :integer + field :text, :string + + timestamps() + end + + @doc false + def changeset(item, attrs) do + item + |> cast(attrs, [:text, :index]) + |> validate_required([:text]) + end +end diff --git a/lib/app_web.ex b/lib/app_web.ex new file mode 100644 index 0000000..e801cec --- /dev/null +++ b/lib/app_web.ex @@ -0,0 +1,110 @@ +defmodule AppWeb do + @moduledoc """ + The entrypoint for defining your web interface, such + as controllers, views, channels and so on. + + This can be used in your application as: + + use AppWeb, :controller + use AppWeb, :view + + The definitions below will be executed for every view, + controller, etc, so keep them short and clean, focused + on imports, uses and aliases. + + Do NOT define functions inside the quoted expressions + below. Instead, define any helper function in modules + and import those modules here. + """ + + def controller do + quote do + use Phoenix.Controller, namespace: AppWeb + + import Plug.Conn + alias AppWeb.Router.Helpers, as: Routes + end + end + + def view do + quote do + use Phoenix.View, + root: "lib/app_web/templates", + namespace: AppWeb + + import Phoenix.Component + # Import convenience functions from controllers + import Phoenix.Controller, + only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1] + + # Include shared imports and aliases for views + unquote(view_helpers()) + end + end + + def live_view do + quote do + use Phoenix.LiveView, + layout: {AppWeb.LayoutView, "live.html"} + + unquote(view_helpers()) + end + end + + def live_component do + quote do + use Phoenix.LiveComponent + + unquote(view_helpers()) + end + end + + def component do + quote do + use Phoenix.Component + + unquote(view_helpers()) + end + end + + def router do + quote do + use Phoenix.Router + + import Plug.Conn + import Phoenix.Controller + import Phoenix.LiveView.Router + end + end + + def channel do + quote do + use Phoenix.Channel + end + end + + defp view_helpers do + quote do + # Use all HTML functionality (forms, tags, etc) + use Phoenix.HTML + + # Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc) + import Phoenix.LiveView.Helpers + import AppWeb.LiveHelpers + + # Import basic rendering functionality (render, render_layout, etc) + import Phoenix.View + import Phoenix.Component + + import AppWeb.ErrorHelpers + alias AppWeb.Router.Helpers, as: Routes + end + end + + @doc """ + When used, dispatch to the appropriate controller/view/etc. + """ + defmacro __using__(which) when is_atom(which) do + apply(__MODULE__, which, []) + end +end diff --git a/lib/app_web/controllers/page_controller.ex b/lib/app_web/controllers/page_controller.ex new file mode 100644 index 0000000..2941548 --- /dev/null +++ b/lib/app_web/controllers/page_controller.ex @@ -0,0 +1,7 @@ +defmodule AppWeb.PageController do + use AppWeb, :controller + + def index(conn, _params) do + render(conn, "index.html") + end +end diff --git a/lib/app_web/endpoint.ex b/lib/app_web/endpoint.ex new file mode 100644 index 0000000..147d14d --- /dev/null +++ b/lib/app_web/endpoint.ex @@ -0,0 +1,46 @@ +defmodule AppWeb.Endpoint do + use Phoenix.Endpoint, otp_app: :app + + # The session will be stored in the cookie and signed, + # this means its contents can be read but not tampered with. + # Set :encryption_salt if you would also like to encrypt it. + @session_options [ + store: :cookie, + key: "_app_key", + signing_salt: "V0P9A9Ds" + ] + + socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] + + # Serve at "/" the static files from "priv/static" directory. + # + # You should set gzip to true if you are running phx.digest + # when deploying your static files in production. + plug Plug.Static, + at: "/", + from: :app, + gzip: false, + only: ~w(assets fonts images favicon.ico robots.txt) + + # Code reloading can be explicitly enabled under the + # :code_reloader configuration of your endpoint. + if code_reloading? do + socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket + plug Phoenix.LiveReloader + plug Phoenix.CodeReloader + plug Phoenix.Ecto.CheckRepoStatus, otp_app: :app + end + + plug Plug.RequestId + plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] + + plug Plug.Parsers, + parsers: [:urlencoded, :multipart, :json], + pass: ["*/*"], + json_decoder: Phoenix.json_library() + + plug Plug.MethodOverride + plug Plug.Head + plug Plug.Session, @session_options + plug AppWeb.Router +end diff --git a/lib/app_web/live/item_live/form_component.ex b/lib/app_web/live/item_live/form_component.ex new file mode 100644 index 0000000..379f721 --- /dev/null +++ b/lib/app_web/live/item_live/form_component.ex @@ -0,0 +1,55 @@ +defmodule AppWeb.ItemLive.FormComponent do + use AppWeb, :live_component + + alias App.Tasks + + @impl true + def update(%{item: item} = assigns, socket) do + changeset = Tasks.change_item(item) + + {:ok, + socket + |> assign(assigns) + |> assign(:changeset, changeset)} + end + + @impl true + def handle_event("validate", %{"item" => item_params}, socket) do + changeset = + socket.assigns.item + |> Tasks.change_item(item_params) + |> Map.put(:action, :validate) + + {:noreply, assign(socket, :changeset, changeset)} + end + + def handle_event("save", %{"item" => item_params}, socket) do + save_item(socket, socket.assigns.action, item_params) + end + + defp save_item(socket, :edit, item_params) do + case Tasks.update_item(socket.assigns.item, item_params) do + {:ok, _item} -> + {:noreply, + socket + |> put_flash(:info, "Item updated successfully") + |> push_redirect(to: socket.assigns.return_to)} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, :changeset, changeset)} + end + end + + defp save_item(socket, :new, item_params) do + case Tasks.create_item(item_params) do + {:ok, _item} -> + {:noreply, + socket + |> put_flash(:info, "Item created successfully") + |> push_redirect(to: socket.assigns.return_to)} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, changeset: changeset)} + end + end +end diff --git a/lib/app_web/live/item_live/form_component.html.heex b/lib/app_web/live/item_live/form_component.html.heex new file mode 100644 index 0000000..c38166d --- /dev/null +++ b/lib/app_web/live/item_live/form_component.html.heex @@ -0,0 +1,20 @@ +
+

<%= @title %>

+ + <.form + let={f} + for={@changeset} + id="item-form" + phx-target={@myself} + phx-change="validate" + phx-submit="save" + > + <%= label(f, :text) %> + <%= text_input(f, :text) %> + <%= error_tag(f, :text) %> + +
+ <%= submit("Save", phx_disable_with: "Saving...") %> +
+ +
diff --git a/lib/app_web/live/item_live/index.ex b/lib/app_web/live/item_live/index.ex new file mode 100644 index 0000000..6f3c2d7 --- /dev/null +++ b/lib/app_web/live/item_live/index.ex @@ -0,0 +1,107 @@ +defmodule AppWeb.ItemLive.Index do + use AppWeb, :live_view + + alias App.Tasks + alias App.Tasks.Item + alias Phoenix.LiveView.JS + + @impl true + def mount(_params, _session, socket) do + if connected?(socket), do: Tasks.subscribe() + {:ok, assign(socket, :items, list_items())} + end + + @impl true + def handle_params(params, _url, socket) do + {:noreply, apply_action(socket, socket.assigns.live_action, params)} + end + + defp apply_action(socket, :edit, %{"id" => id}) do + socket + |> assign(:page_title, "Edit Item") + |> assign(:item, Tasks.get_item!(id)) + end + + defp apply_action(socket, :new, _params) do + socket + |> assign(:page_title, "New Item") + |> assign(:item, %Item{}) + end + + defp apply_action(socket, :index, _params) do + socket + |> assign(:page_title, "Listing Items") + |> assign(:item, nil) + end + + @impl true + def handle_event("delete", %{"id" => id}, socket) do + item = Tasks.get_item!(id) + {:ok, _} = Tasks.delete_item(item) + + {:noreply, assign(socket, :items, list_items())} + end + + @impl true + def handle_event("highlight", %{"id" => id}, socket) do + Tasks.drag_item(id) + {:noreply, socket} + end + + @impl true + def handle_event("remove-highlight", %{"id" => id}, socket) do + Tasks.drop_item(id) + {:noreply, socket} + end + + @impl true + def handle_event( + "dragoverItem", + %{"currentItemId" => current_item_id, "selectedItemId" => selected_item_id}, + socket + ) do + Tasks.dragover_item(current_item_id, selected_item_id) + {:noreply, socket} + end + + @impl true + def handle_event("updateIndexes", %{"ids" => ids}, socket) do + Tasks.update_items_index(ids) + {:noreply, socket} + end + + @impl true + def handle_info(:indexes_updated, socket) do + items = list_items() + {:noreply, assign(socket, items: items)} + end + + @impl true + def handle_info({:dragover_item, {current_item_id, selected_item_id}}, socket) do + {:noreply, + push_event(socket, "dragover-item", %{ + current_item_id: current_item_id, + selected_item_id: selected_item_id + })} + end + + @impl true + def handle_info({:item_created, _item}, socket) do + items = list_items() + {:noreply, assign(socket, items: items)} + end + + @impl true + def handle_info({:drag_item, item_id}, socket) do + {:noreply, push_event(socket, "highlight", %{id: item_id})} + end + + @impl true + def handle_info({:drop_item, item_id}, socket) do + {:noreply, push_event(socket, "remove-highlight", %{id: item_id})} + end + + defp list_items do + Tasks.list_items() + end +end diff --git a/lib/app_web/live/item_live/index.html.heex b/lib/app_web/live/item_live/index.html.heex new file mode 100644 index 0000000..a6178ec --- /dev/null +++ b/lib/app_web/live/item_live/index.html.heex @@ -0,0 +1,45 @@ +

Listing Items

+ +<%= if @live_action in [:new, :edit] do %> + <.modal return_to={Routes.item_index_path(@socket, :index)}> + <.live_component + module={AppWeb.ItemLive.FormComponent} + id={@item.id || :new} + title={@page_title} + action={@live_action} + item={@item} + return_to={Routes.item_index_path(@socket, :index)} + /> + +<% end %> + + + + + + + + + + <%= for item <- @items do %> + + + + + <% end %> + +
TextIndex
<%= item.text %><%= item.index %>
+ +<%= live_patch("New Item", to: Routes.item_index_path(@socket, :new)) %> diff --git a/lib/app_web/live/item_live/show.ex b/lib/app_web/live/item_live/show.ex new file mode 100644 index 0000000..1b5e175 --- /dev/null +++ b/lib/app_web/live/item_live/show.ex @@ -0,0 +1,21 @@ +defmodule AppWeb.ItemLive.Show do + use AppWeb, :live_view + + alias App.Tasks + + @impl true + def mount(_params, _session, socket) do + {:ok, socket} + end + + @impl true + def handle_params(%{"id" => id}, _, socket) do + {:noreply, + socket + |> assign(:page_title, page_title(socket.assigns.live_action)) + |> assign(:item, Tasks.get_item!(id))} + end + + defp page_title(:show), do: "Show Item" + defp page_title(:edit), do: "Edit Item" +end diff --git a/lib/app_web/live/item_live/show.html.heex b/lib/app_web/live/item_live/show.html.heex new file mode 100644 index 0000000..256a07b --- /dev/null +++ b/lib/app_web/live/item_live/show.html.heex @@ -0,0 +1,31 @@ +

Show Item

+ +<%= if @live_action in [:edit] do %> + <.modal return_to={Routes.item_show_path(@socket, :show, @item)}> + <.live_component + module={AppWeb.ItemLive.FormComponent} + id={@item.id} + title={@page_title} + action={@live_action} + item={@item} + return_to={Routes.item_show_path(@socket, :show, @item)} + /> + +<% end %> + + + + + <%= live_patch("Edit", to: Routes.item_show_path(@socket, :edit, @item), class: "button") %> + +| <%= live_redirect("Back", to: Routes.item_index_path(@socket, :index)) %> diff --git a/lib/app_web/live/live_helpers.ex b/lib/app_web/live/live_helpers.ex new file mode 100644 index 0000000..f33dcc5 --- /dev/null +++ b/lib/app_web/live/live_helpers.ex @@ -0,0 +1,60 @@ +defmodule AppWeb.LiveHelpers do + import Phoenix.LiveView + import Phoenix.LiveView.Helpers + + alias Phoenix.LiveView.JS + + @doc """ + Renders a live component inside a modal. + + The rendered modal receives a `:return_to` option to properly update + the URL when the modal is closed. + + ## Examples + + <.modal return_to={Routes.item_index_path(@socket, :index)}> + <.live_component + module={AppWeb.ItemLive.FormComponent} + id={@item.id || :new} + title={@page_title} + action={@live_action} + return_to={Routes.item_index_path(@socket, :index)} + item: @item + /> + + """ + def modal(assigns) do + assigns = assign_new(assigns, :return_to, fn -> nil end) + + ~H""" + + """ + end + + defp hide_modal(js \\ %JS{}) do + js + |> JS.hide(to: "#modal", transition: "fade-out") + |> JS.hide(to: "#modal-content", transition: "fade-out-scale") + end +end diff --git a/lib/app_web/router.ex b/lib/app_web/router.ex new file mode 100644 index 0000000..3690187 --- /dev/null +++ b/lib/app_web/router.ex @@ -0,0 +1,32 @@ +defmodule AppWeb.Router do + use AppWeb, :router + + pipeline :browser do + plug :accepts, ["html"] + plug :fetch_session + plug :fetch_live_flash + plug :put_root_layout, {AppWeb.LayoutView, :root} + plug :protect_from_forgery + plug :put_secure_browser_headers + end + + pipeline :api do + plug :accepts, ["json"] + end + + scope "/", AppWeb do + pipe_through :browser + live "/", ItemLive.Index, :index + live "/items", ItemLive.Index, :index + live "/items/new", ItemLive.Index, :new + live "/items/:id/edit", ItemLive.Index, :edit + + live "/items/:id", ItemLive.Show, :show + live "/items/:id/show/edit", ItemLive.Show, :edit + end + + # Other scopes may use custom stacks. + # scope "/api", AppWeb do + # pipe_through :api + # end +end diff --git a/lib/app_web/telemetry.ex b/lib/app_web/telemetry.ex new file mode 100644 index 0000000..516863e --- /dev/null +++ b/lib/app_web/telemetry.ex @@ -0,0 +1,71 @@ +defmodule AppWeb.Telemetry do + use Supervisor + import Telemetry.Metrics + + def start_link(arg) do + Supervisor.start_link(__MODULE__, arg, name: __MODULE__) + end + + @impl true + def init(_arg) do + children = [ + # Telemetry poller will execute the given period measurements + # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics + {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} + # Add reporters as children of your supervision tree. + # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} + ] + + Supervisor.init(children, strategy: :one_for_one) + end + + def metrics do + [ + # Phoenix Metrics + summary("phoenix.endpoint.stop.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.router_dispatch.stop.duration", + tags: [:route], + unit: {:native, :millisecond} + ), + + # Database Metrics + summary("app.repo.query.total_time", + unit: {:native, :millisecond}, + description: "The sum of the other measurements" + ), + summary("app.repo.query.decode_time", + unit: {:native, :millisecond}, + description: "The time spent decoding the data received from the database" + ), + summary("app.repo.query.query_time", + unit: {:native, :millisecond}, + description: "The time spent executing the query" + ), + summary("app.repo.query.queue_time", + unit: {:native, :millisecond}, + description: "The time spent waiting for a database connection" + ), + summary("app.repo.query.idle_time", + unit: {:native, :millisecond}, + description: + "The time the connection spent waiting before being checked out for the query" + ), + + # VM Metrics + summary("vm.memory.total", unit: {:byte, :kilobyte}), + summary("vm.total_run_queue_lengths.total"), + summary("vm.total_run_queue_lengths.cpu"), + summary("vm.total_run_queue_lengths.io") + ] + end + + defp periodic_measurements do + [ + # A module, function and arguments to be invoked periodically. + # This function must call :telemetry.execute/3 and a metric must be added above. + # {AppWeb, :count_users, []} + ] + end +end diff --git a/lib/app_web/templates/layout/app.html.heex b/lib/app_web/templates/layout/app.html.heex new file mode 100644 index 0000000..365b597 --- /dev/null +++ b/lib/app_web/templates/layout/app.html.heex @@ -0,0 +1,3 @@ +
+ <%= @inner_content %> +
diff --git a/lib/app_web/templates/layout/live.html.heex b/lib/app_web/templates/layout/live.html.heex new file mode 100644 index 0000000..a29d604 --- /dev/null +++ b/lib/app_web/templates/layout/live.html.heex @@ -0,0 +1,11 @@ +
+ + + + + <%= @inner_content %> +
diff --git a/lib/app_web/templates/layout/root.html.heex b/lib/app_web/templates/layout/root.html.heex new file mode 100644 index 0000000..3e4553b --- /dev/null +++ b/lib/app_web/templates/layout/root.html.heex @@ -0,0 +1,22 @@ + + + + + + + + <%= live_title_tag(assigns[:page_title] || "App", suffix: " · Phoenix Framework") %> + + + + + <%= @inner_content %> + + diff --git a/lib/app_web/templates/page/index.html.heex b/lib/app_web/templates/page/index.html.heex new file mode 100644 index 0000000..37847db --- /dev/null +++ b/lib/app_web/templates/page/index.html.heex @@ -0,0 +1 @@ +

Alpine.js

diff --git a/lib/app_web/views/error_helpers.ex b/lib/app_web/views/error_helpers.ex new file mode 100644 index 0000000..b3a7c1b --- /dev/null +++ b/lib/app_web/views/error_helpers.ex @@ -0,0 +1,30 @@ +defmodule AppWeb.ErrorHelpers do + @moduledoc """ + Conveniences for translating and building error messages. + """ + + use Phoenix.HTML + + @doc """ + Generates tag for inlined form input errors. + """ + def error_tag(form, field) do + Enum.map(Keyword.get_values(form.errors, field), fn error -> + content_tag(:span, translate_error(error), + class: "invalid-feedback", + phx_feedback_for: input_name(form, field) + ) + end) + end + + @doc """ + Translates an error message. + """ + def translate_error({msg, opts}) do + # Because the error messages we show in our forms and APIs + # are defined inside Ecto, we need to translate them dynamically. + Enum.reduce(opts, msg, fn {key, value}, acc -> + String.replace(acc, "%{#{key}}", fn _ -> to_string(value) end) + end) + end +end diff --git a/lib/app_web/views/error_view.ex b/lib/app_web/views/error_view.ex new file mode 100644 index 0000000..a6651a5 --- /dev/null +++ b/lib/app_web/views/error_view.ex @@ -0,0 +1,16 @@ +defmodule AppWeb.ErrorView do + use AppWeb, :view + + # If you want to customize a particular status code + # for a certain format, you may uncomment below. + # def render("500.html", _assigns) do + # "Internal Server Error" + # end + + # By default, Phoenix returns the status message from + # the template name. For example, "404.html" becomes + # "Not Found". + def template_not_found(template, _assigns) do + Phoenix.Controller.status_message_from_template(template) + end +end diff --git a/lib/app_web/views/layout_view.ex b/lib/app_web/views/layout_view.ex new file mode 100644 index 0000000..69e85d2 --- /dev/null +++ b/lib/app_web/views/layout_view.ex @@ -0,0 +1,7 @@ +defmodule AppWeb.LayoutView do + use AppWeb, :view + + # Phoenix LiveDashboard is available only in development by default, + # so we instruct Elixir to not warn if the dashboard route is missing. + @compile {:no_warn_undefined, {Routes, :live_dashboard_path, 2}} +end diff --git a/lib/app_web/views/page_view.ex b/lib/app_web/views/page_view.ex new file mode 100644 index 0000000..8ba34d2 --- /dev/null +++ b/lib/app_web/views/page_view.ex @@ -0,0 +1,3 @@ +defmodule AppWeb.PageView do + use AppWeb, :view +end diff --git a/mix.exs b/mix.exs new file mode 100644 index 0000000..b41b708 --- /dev/null +++ b/mix.exs @@ -0,0 +1,80 @@ +defmodule App.MixProject do + use Mix.Project + + def project do + [ + app: :app, + version: "0.1.0", + elixir: "~> 1.14", + elixirc_paths: elixirc_paths(Mix.env()), + compilers: Mix.compilers(), + start_permanent: Mix.env() == :prod, + aliases: aliases(), + deps: deps(), + test_coverage: [tool: ExCoveralls], + preferred_cli_env: [ + c: :test, + coveralls: :test, + "coveralls.json": :test, + "coveralls.html": :test, + t: :test + ] + ] + end + + # Configuration for the OTP application. + # + # Type `mix help compile.app` for more information. + def application do + [ + mod: {App.Application, []}, + extra_applications: [:logger, :runtime_tools] + ] + end + + # Specifies which paths to compile per environment. + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + # Specifies your project dependencies. + # + # Type `mix help deps` for examples and options. + defp deps do + [ + {:phoenix, "~> 1.6.14"}, + {:phoenix_ecto, "~> 4.4"}, + {:ecto_sql, "~> 3.6"}, + {:postgrex, ">= 0.0.0"}, + {:phoenix_html, "~> 3.0"}, + {:phoenix_live_reload, "~> 1.2", only: :dev}, + {:phoenix_live_view, "~> 0.17.5"}, + {:floki, ">= 0.30.0", only: :test}, + {:esbuild, "~> 0.4", runtime: Mix.env() == :dev}, + {:telemetry_metrics, "~> 0.6"}, + {:telemetry_poller, "~> 1.0"}, + {:jason, "~> 1.2"}, + {:plug_cowboy, "~> 2.5"}, + + # Track test coverage: + {:excoveralls, "~> 0.14.5", only: [:test, :dev]}, + ] + end + + # Aliases are shortcuts or tasks specific to the current project. + # For example, to install project dependencies and perform other setup tasks, run: + # + # $ mix setup + # + # See the documentation for `Mix` for more info on aliases. + defp aliases do + [ + "assets.deploy": ["esbuild default --minify", "phx.digest"], + "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], + "ecto.reset": ["ecto.drop", "ecto.setup"], + c: ["coveralls.html"], + setup: ["deps.get", "ecto.setup"], + s: ["phx.server"], + test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"] + ] + end +end diff --git a/mix.lock b/mix.lock new file mode 100644 index 0000000..853a512 --- /dev/null +++ b/mix.lock @@ -0,0 +1,42 @@ +%{ + "castore": {:hex, :castore, "0.1.18", "deb5b9ab02400561b6f5708f3e7660fc35ca2d51bfc6a940d2f513f89c2975fc", [:mix], [], "hexpm", "61bbaf6452b782ef80b33cdb45701afbcf0a918a45ebe7e73f1130d661e66a06"}, + "certifi": {:hex, :certifi, "2.9.0", "6f2a475689dd47f19fb74334859d460a2dc4e3252a3324bd2111b8f0429e7e21", [:rebar3], [], "hexpm", "266da46bdb06d6c6d35fde799bcb28d36d985d424ad7c08b5bb48f5b5cdd4641"}, + "connection": {:hex, :connection, "1.1.0", "ff2a49c4b75b6fb3e674bfc5536451607270aac754ffd1bdfe175abe4a6d7a68", [:mix], [], "hexpm", "722c1eb0a418fbe91ba7bd59a47e28008a189d47e37e0e7bb85585a016b2869c"}, + "cowboy": {:hex, :cowboy, "2.9.0", "865dd8b6607e14cf03282e10e934023a1bd8be6f6bacf921a7e2a96d800cd452", [:make, :rebar3], [{:cowlib, "2.11.0", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "2c729f934b4e1aa149aff882f57c6372c15399a20d54f65c8d67bef583021bde"}, + "cowboy_telemetry": {:hex, :cowboy_telemetry, "0.4.0", "f239f68b588efa7707abce16a84d0d2acf3a0f50571f8bb7f56a15865aae820c", [:rebar3], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7d98bac1ee4565d31b62d59f8823dfd8356a169e7fcbb83831b8a5397404c9de"}, + "cowlib": {:hex, :cowlib, "2.11.0", "0b9ff9c346629256c42ebe1eeb769a83c6cb771a6ee5960bd110ab0b9b872063", [:make, :rebar3], [], "hexpm", "2b3e9da0b21c4565751a6d4901c20d1b4cc25cbb7fd50d91d2ab6dd287bc86a9"}, + "db_connection": {:hex, :db_connection, "2.4.2", "f92e79aff2375299a16bcb069a14ee8615c3414863a6fef93156aee8e86c2ff3", [:mix], [{:connection, "~> 1.0", [hex: :connection, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "4fe53ca91b99f55ea249693a0229356a08f4d1a7931d8ffa79289b145fe83668"}, + "decimal": {:hex, :decimal, "2.0.0", "a78296e617b0f5dd4c6caf57c714431347912ffb1d0842e998e9792b5642d697", [:mix], [], "hexpm", "34666e9c55dea81013e77d9d87370fe6cb6291d1ef32f46a1600230b1d44f577"}, + "ecto": {:hex, :ecto, "3.9.1", "67173b1687afeb68ce805ee7420b4261649d5e2deed8fe5550df23bab0bc4396", [:mix], [{:decimal, "~> 1.6 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "c80bb3d736648df790f7f92f81b36c922d9dd3203ca65be4ff01d067f54eb304"}, + "ecto_sql": {:hex, :ecto_sql, "3.9.0", "2bb21210a2a13317e098a420a8c1cc58b0c3421ab8e3acfa96417dab7817918c", [:mix], [{:db_connection, "~> 2.5 or ~> 2.4.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.9.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.6.0", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.16.0 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "a8f3f720073b8b1ac4c978be25fa7960ed7fd44997420c304a4a2e200b596453"}, + "esbuild": {:hex, :esbuild, "0.5.0", "d5bb08ff049d7880ee3609ed5c4b864bd2f46445ea40b16b4acead724fb4c4a3", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}], "hexpm", "f183a0b332d963c4cfaf585477695ea59eef9a6f2204fdd0efa00e099694ffe5"}, + "excoveralls": {:hex, :excoveralls, "0.14.6", "610e921e25b180a8538229ef547957f7e04bd3d3e9a55c7c5b7d24354abbba70", [:mix], [{:hackney, "~> 1.16", [hex: :hackney, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "0eceddaa9785cfcefbf3cd37812705f9d8ad34a758e513bb975b081dce4eb11e"}, + "file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"}, + "floki": {:hex, :floki, "0.33.1", "f20f1eb471e726342b45ccb68edb9486729e7df94da403936ea94a794f072781", [:mix], [{:html_entities, "~> 0.5.0", [hex: :html_entities, repo: "hexpm", optional: false]}], "hexpm", "461035fd125f13fdf30f243c85a0b1e50afbec876cbf1ceefe6fddd2e6d712c6"}, + "hackney": {:hex, :hackney, "1.18.1", "f48bf88f521f2a229fc7bae88cf4f85adc9cd9bcf23b5dc8eb6a1788c662c4f6", [:rebar3], [{:certifi, "~>2.9.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "~>6.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "~>1.0.0", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "~>1.1", [hex: :mimerl, repo: "hexpm", optional: false]}, {:parse_trans, "3.3.1", [hex: :parse_trans, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "~>1.1.0", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}, {:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "a4ecdaff44297e9b5894ae499e9a070ea1888c84afdd1fd9b7b2bc384950128e"}, + "html_entities": {:hex, :html_entities, "0.5.2", "9e47e70598da7de2a9ff6af8758399251db6dbb7eebe2b013f2bbd2515895c3c", [:mix], [], "hexpm", "c53ba390403485615623b9531e97696f076ed415e8d8058b1dbaa28181f4fdcc"}, + "idna": {:hex, :idna, "6.1.1", "8a63070e9f7d0c62eb9d9fcb360a7de382448200fbbd1b106cc96d3d8099df8d", [:rebar3], [{:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "92376eb7894412ed19ac475e4a86f7b413c1b9fbb5bd16dccd57934157944cea"}, + "jason": {:hex, :jason, "1.4.0", "e855647bc964a44e2f67df589ccf49105ae039d4179db7f6271dfd3843dc27e6", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "79a3791085b2a0f743ca04cec0f7be26443738779d09302e01318f97bdb82121"}, + "metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], [], "hexpm", "69b09adddc4f74a40716ae54d140f93beb0fb8978d8636eaded0c31b6f099f16"}, + "mime": {:hex, :mime, "2.0.3", "3676436d3d1f7b81b5a2d2bd8405f412c677558c81b1c92be58c00562bb59095", [:mix], [], "hexpm", "27a30bf0db44d25eecba73755acf4068cbfe26a4372f9eb3e4ea3a45956bff6b"}, + "mimerl": {:hex, :mimerl, "1.2.0", "67e2d3f571088d5cfd3e550c383094b47159f3eee8ffa08e64106cdf5e981be3", [:rebar3], [], "hexpm", "f278585650aa581986264638ebf698f8bb19df297f66ad91b18910dfc6e19323"}, + "parse_trans": {:hex, :parse_trans, "3.3.1", "16328ab840cc09919bd10dab29e431da3af9e9e7e7e6f0089dd5a2d2820011d8", [:rebar3], [], "hexpm", "07cd9577885f56362d414e8c4c4e6bdf10d43a8767abb92d24cbe8b24c54888b"}, + "phoenix": {:hex, :phoenix, "1.6.15", "0a1d96bbc10747fd83525370d691953cdb6f3ccbac61aa01b4acb012474b047d", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 1.0 or ~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: false]}, {:plug, "~> 1.10", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.2", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "d70ab9fbf6b394755ea88b644d34d79d8b146e490973151f248cacd122d20672"}, + "phoenix_ecto": {:hex, :phoenix_ecto, "4.4.0", "0672ed4e4808b3fbed494dded89958e22fb882de47a97634c0b13e7b0b5f7720", [:mix], [{:ecto, "~> 3.3", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "09864e558ed31ee00bd48fcc1d4fc58ae9678c9e81649075431e69dbabb43cc1"}, + "phoenix_html": {:hex, :phoenix_html, "3.2.0", "1c1219d4b6cb22ac72f12f73dc5fad6c7563104d083f711c3fcd8551a1f4ae11", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "36ec97ba56d25c0136ef1992c37957e4246b649d620958a1f9fa86165f8bc54f"}, + "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.4.0", "4fe222c0be55fdc3f9c711e24955fc42a7cd9b7a2f5f406f2580a567c335a573", [: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", "bebf0fc2d2113b61cb5968f585367234b7b4c21d963d691de7b4b2dc6cdaae6f"}, + "phoenix_live_view": {:hex, :phoenix_live_view, "0.17.12", "74f4c0ad02d7deac2d04f50b52827a5efdc5c6e7fac5cede145f5f0e4183aedc", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.6.0 or ~> 1.7.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.1", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "af6dd5e0aac16ff43571f527a8e0616d62cb80b10eb87aac82170243e50d99c8"}, + "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.1.1", "ba04e489ef03763bf28a17eb2eaddc2c20c6d217e2150a61e3298b0f4c2012b5", [:mix], [], "hexpm", "81367c6d1eea5878ad726be80808eb5a787a23dee699f96e72b1109c57cdd8d9"}, + "phoenix_template": {:hex, :phoenix_template, "1.0.0", "c57bc5044f25f007dc86ab21895688c098a9f846a8dda6bc40e2d0ddc146e38f", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "1b066f99a26fd22064c12b2600a9a6e56700f591bf7b20b418054ea38b4d4357"}, + "phoenix_view": {:hex, :phoenix_view, "2.0.1", "a653e3d9d944aace0a064e4a13ad473ffa68f7bc4ca42dbf83cc1d464f1fb295", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}], "hexpm", "6c358e2cefc5f341c728914b867c556bbfd239fed9e881bac257d70cb2b8a6f6"}, + "plug": {:hex, :plug, "1.14.0", "ba4f558468f69cbd9f6b356d25443d0b796fbdc887e03fa89001384a9cac638f", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "bf020432c7d4feb7b3af16a0c2701455cbbbb95e5b6866132cb09eb0c29adc14"}, + "plug_cowboy": {:hex, :plug_cowboy, "2.6.0", "d1cf12ff96a1ca4f52207c5271a6c351a4733f413803488d75b70ccf44aebec2", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:cowboy_telemetry, "~> 0.3", [hex: :cowboy_telemetry, repo: "hexpm", optional: false]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "073cf20b753ce6682ed72905cd62a2d4bd9bad1bf9f7feb02a1b8e525bd94fa6"}, + "plug_crypto": {:hex, :plug_crypto, "1.2.3", "8f77d13aeb32bfd9e654cb68f0af517b371fb34c56c9f2b58fe3df1235c1251a", [:mix], [], "hexpm", "b5672099c6ad5c202c45f5a403f21a3411247f164e4a8fab056e5cd8a290f4a2"}, + "postgrex": {:hex, :postgrex, "0.16.5", "fcc4035cc90e23933c5d69a9cd686e329469446ef7abba2cf70f08e2c4b69810", [:mix], [{:connection, "~> 1.1", [hex: :connection, repo: "hexpm", optional: false]}, {:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "edead639dc6e882618c01d8fc891214c481ab9a3788dfe38dd5e37fd1d5fb2e8"}, + "ranch": {:hex, :ranch, "1.8.0", "8c7a100a139fd57f17327b6413e4167ac559fbc04ca7448e9be9057311597a1d", [:make, :rebar3], [], "hexpm", "49fbcfd3682fab1f5d109351b61257676da1a2fdbe295904176d5e521a2ddfe5"}, + "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.6", "cf344f5692c82d2cd7554f5ec8fd961548d4fd09e7d22f5b62482e5aeaebd4b0", [:make, :mix, :rebar3], [], "hexpm", "bdb0d2471f453c88ff3908e7686f86f9be327d065cc1ec16fa4540197ea04680"}, + "telemetry": {:hex, :telemetry, "1.1.0", "a589817034a27eab11144ad24d5c0f9fab1f58173274b1e9bae7074af9cbee51", [:rebar3], [], "hexpm", "b727b2a1f75614774cff2d7565b64d0dfa5bd52ba517f16543e6fc7efcc0df48"}, + "telemetry_metrics": {:hex, :telemetry_metrics, "0.6.1", "315d9163a1d4660aedc3fee73f33f1d355dcc76c5c3ab3d59e76e3edf80eef1f", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7be9e0871c41732c233be71e4be11b96e56177bf15dde64a8ac9ce72ac9834c6"}, + "telemetry_poller": {:hex, :telemetry_poller, "1.0.0", "db91bb424e07f2bb6e73926fcafbfcbcb295f0193e0a00e825e589a0a47e8453", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "b3a24eafd66c3f42da30fc3ca7dda1e9d546c12250a2d60d7b81d264fbec4f6e"}, + "unicode_util_compat": {:hex, :unicode_util_compat, "0.7.0", "bc84380c9ab48177092f43ac89e4dfa2c6d62b40b8bd132b1059ecc7232f9a78", [:rebar3], [], "hexpm", "25eee6d67df61960cf6a794239566599b09e17e668d3700247bc498638152521"}, +} diff --git a/playground.html b/playground.html new file mode 100644 index 0000000..9c9b8b0 --- /dev/null +++ b/playground.html @@ -0,0 +1,118 @@ + + + + + + Alpine Stopwatch + + + + + + + + +
+ 1657807647000 + + + +
+ + +
+ + + + + + + +
+
+ + Hello 👋 + + + + + diff --git a/priv/repo/migrations/.formatter.exs b/priv/repo/migrations/.formatter.exs new file mode 100644 index 0000000..49f9151 --- /dev/null +++ b/priv/repo/migrations/.formatter.exs @@ -0,0 +1,4 @@ +[ + import_deps: [:ecto_sql], + inputs: ["*.exs"] +] diff --git a/priv/repo/migrations/20221022131733_create_items.exs b/priv/repo/migrations/20221022131733_create_items.exs new file mode 100644 index 0000000..27bb5c4 --- /dev/null +++ b/priv/repo/migrations/20221022131733_create_items.exs @@ -0,0 +1,12 @@ +defmodule App.Repo.Migrations.CreateItems do + use Ecto.Migration + + def change do + create table(:items) do + add :text, :string + add :index, :integer + + timestamps() + end + end +end diff --git a/priv/repo/seeds.exs b/priv/repo/seeds.exs new file mode 100644 index 0000000..fe3037b --- /dev/null +++ b/priv/repo/seeds.exs @@ -0,0 +1,11 @@ +# Script for populating the database. You can run it as: +# +# mix run priv/repo/seeds.exs +# +# Inside the script, you can read and write to any of your +# repositories directly: +# +# App.Repo.insert!(%App.SomeSchema{}) +# +# We recommend using the bang functions (`insert!`, `update!` +# and so on) as they will fail if something goes wrong. diff --git a/priv/static/favicon-a8ca4e3a2bb8fea46a9ee9e102e7d3eb.ico b/priv/static/favicon-a8ca4e3a2bb8fea46a9ee9e102e7d3eb.ico new file mode 100644 index 0000000..73de524 Binary files /dev/null and b/priv/static/favicon-a8ca4e3a2bb8fea46a9ee9e102e7d3eb.ico differ diff --git a/priv/static/favicon.ico b/priv/static/favicon.ico new file mode 100644 index 0000000..73de524 Binary files /dev/null and b/priv/static/favicon.ico differ diff --git a/priv/static/images/phoenix-5bd99a0d17dd41bc9d9bf6840abcc089.png b/priv/static/images/phoenix-5bd99a0d17dd41bc9d9bf6840abcc089.png new file mode 100644 index 0000000..9c81075 Binary files /dev/null and b/priv/static/images/phoenix-5bd99a0d17dd41bc9d9bf6840abcc089.png differ diff --git a/priv/static/images/phoenix.png b/priv/static/images/phoenix.png new file mode 100644 index 0000000..9c81075 Binary files /dev/null and b/priv/static/images/phoenix.png differ diff --git a/priv/static/robots-9e2c81b0855bbff2baa8371bc4a78186.txt b/priv/static/robots-9e2c81b0855bbff2baa8371bc4a78186.txt new file mode 100644 index 0000000..26e06b5 --- /dev/null +++ b/priv/static/robots-9e2c81b0855bbff2baa8371bc4a78186.txt @@ -0,0 +1,5 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/priv/static/robots-9e2c81b0855bbff2baa8371bc4a78186.txt.gz b/priv/static/robots-9e2c81b0855bbff2baa8371bc4a78186.txt.gz new file mode 100644 index 0000000..043be33 Binary files /dev/null and b/priv/static/robots-9e2c81b0855bbff2baa8371bc4a78186.txt.gz differ diff --git a/priv/static/robots.txt b/priv/static/robots.txt new file mode 100644 index 0000000..26e06b5 --- /dev/null +++ b/priv/static/robots.txt @@ -0,0 +1,5 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/priv/static/robots.txt.gz b/priv/static/robots.txt.gz new file mode 100644 index 0000000..043be33 Binary files /dev/null and b/priv/static/robots.txt.gz differ diff --git a/test/app/tasks_test.exs b/test/app/tasks_test.exs new file mode 100644 index 0000000..a8d9cb2 --- /dev/null +++ b/test/app/tasks_test.exs @@ -0,0 +1,59 @@ +defmodule App.TasksTest do + use App.DataCase + + alias App.Tasks + + describe "items" do + alias App.Tasks.Item + + import App.TasksFixtures + + @invalid_attrs %{"text" => nil} + + test "list_items/0 returns all items" do + item = item_fixture() + assert Tasks.list_items() == [item] + end + + test "get_item!/1 returns the item with given id" do + item = item_fixture() + assert Tasks.get_item!(item.id) == item + end + + test "create_item/1 with valid data creates a item" do + valid_attrs = %{"text" => "some text"} + + assert {:ok, %Item{} = item} = Tasks.create_item(valid_attrs) + assert item.text == "some text" + end + + test "create_item/1 with invalid data returns error changeset" do + assert {:error, %Ecto.Changeset{}} = Tasks.create_item(@invalid_attrs) + end + + test "update_item/2 with valid data updates the item" do + item = item_fixture() + update_attrs = %{"text" => "some updated text"} + + assert {:ok, %Item{} = item} = Tasks.update_item(item, update_attrs) + assert item.text == "some updated text" + end + + test "update_item/2 with invalid data returns error changeset" do + item = item_fixture() + assert {:error, %Ecto.Changeset{}} = Tasks.update_item(item, @invalid_attrs) + assert item == Tasks.get_item!(item.id) + end + + test "delete_item/1 deletes the item" do + item = item_fixture() + assert {:ok, %Item{}} = Tasks.delete_item(item) + assert_raise Ecto.NoResultsError, fn -> Tasks.get_item!(item.id) end + end + + test "change_item/1 returns a item changeset" do + item = item_fixture() + assert %Ecto.Changeset{} = Tasks.change_item(item) + end + end +end diff --git a/test/app_web/controllers/page_controller_test.exs b/test/app_web/controllers/page_controller_test.exs new file mode 100644 index 0000000..9a7a758 --- /dev/null +++ b/test/app_web/controllers/page_controller_test.exs @@ -0,0 +1,8 @@ +defmodule AppWeb.PageControllerTest do + use AppWeb.ConnCase + + test "GET /", %{conn: conn} do + conn = get(conn, "/") + assert html_response(conn, 200) + end +end diff --git a/test/app_web/live/item_live_test.exs b/test/app_web/live/item_live_test.exs new file mode 100644 index 0000000..76f8dad --- /dev/null +++ b/test/app_web/live/item_live_test.exs @@ -0,0 +1,42 @@ +defmodule AppWeb.ItemLiveTest do + use AppWeb.ConnCase + + import Phoenix.LiveViewTest + import App.TasksFixtures + + @create_attrs %{"text" => "some text"} + + defp create_item(_) do + item = item_fixture() + %{item: item} + end + + describe "Index" do + setup [:create_item] + + test "lists all items", %{conn: conn, item: item} do + {:ok, _index_live, html} = live(conn, Routes.item_index_path(conn, :index)) + + assert html =~ "Listing Items" + assert html =~ item.text + end + + test "saves new item", %{conn: conn} do + {:ok, index_live, _html} = live(conn, Routes.item_index_path(conn, :index)) + + assert index_live |> element("a", "New Item") |> render_click() =~ + "New Item" + + assert_patch(index_live, Routes.item_index_path(conn, :new)) + + {:ok, _, html} = + index_live + |> form("#item-form", item: @create_attrs) + |> render_submit() + |> follow_redirect(conn, Routes.item_index_path(conn, :index)) + + assert html =~ "Item created successfully" + assert html =~ "some text" + end + end +end diff --git a/test/app_web/views/error_view_test.exs b/test/app_web/views/error_view_test.exs new file mode 100644 index 0000000..85a326c --- /dev/null +++ b/test/app_web/views/error_view_test.exs @@ -0,0 +1,14 @@ +defmodule AppWeb.ErrorViewTest do + use AppWeb.ConnCase, async: true + + # Bring render/3 and render_to_string/3 for testing custom views + import Phoenix.View + + test "renders 404.html" do + assert render_to_string(AppWeb.ErrorView, "404.html", []) == "Not Found" + end + + test "renders 500.html" do + assert render_to_string(AppWeb.ErrorView, "500.html", []) == "Internal Server Error" + end +end diff --git a/test/app_web/views/layout_view_test.exs b/test/app_web/views/layout_view_test.exs new file mode 100644 index 0000000..1ba98bc --- /dev/null +++ b/test/app_web/views/layout_view_test.exs @@ -0,0 +1,8 @@ +defmodule AppWeb.LayoutViewTest do + use AppWeb.ConnCase, async: true + + # When testing helpers, you may want to import Phoenix.HTML and + # use functions such as safe_to_string() to convert the helper + # result into an HTML string. + # import Phoenix.HTML +end diff --git a/test/app_web/views/page_view_test.exs b/test/app_web/views/page_view_test.exs new file mode 100644 index 0000000..75067ce --- /dev/null +++ b/test/app_web/views/page_view_test.exs @@ -0,0 +1,3 @@ +defmodule AppWeb.PageViewTest do + use AppWeb.ConnCase, async: true +end diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex new file mode 100644 index 0000000..ec9556c --- /dev/null +++ b/test/support/conn_case.ex @@ -0,0 +1,38 @@ +defmodule AppWeb.ConnCase do + @moduledoc """ + This module defines the test case to be used by + tests that require setting up a connection. + + Such tests rely on `Phoenix.ConnTest` and also + import other functionality to make it easier + to build common data structures and query the data layer. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use AppWeb.ConnCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + # Import conveniences for testing with connections + import Plug.Conn + import Phoenix.ConnTest + import AppWeb.ConnCase + + alias AppWeb.Router.Helpers, as: Routes + + # The default endpoint for testing + @endpoint AppWeb.Endpoint + end + end + + setup tags do + App.DataCase.setup_sandbox(tags) + {:ok, conn: Phoenix.ConnTest.build_conn()} + end +end diff --git a/test/support/data_case.ex b/test/support/data_case.ex new file mode 100644 index 0000000..4a83f5a --- /dev/null +++ b/test/support/data_case.ex @@ -0,0 +1,58 @@ +defmodule App.DataCase do + @moduledoc """ + This module defines the setup for tests requiring + access to the application's data layer. + + You may define functions here to be used as helpers in + your tests. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use App.DataCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + alias App.Repo + + import Ecto + import Ecto.Changeset + import Ecto.Query + import App.DataCase + end + end + + setup tags do + App.DataCase.setup_sandbox(tags) + :ok + end + + @doc """ + Sets up the sandbox based on the test tags. + """ + def setup_sandbox(tags) do + pid = Ecto.Adapters.SQL.Sandbox.start_owner!(App.Repo, shared: not tags[:async]) + on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end) + end + + @doc """ + A helper that transforms changeset errors into a map of messages. + + assert {:error, changeset} = Accounts.create_user(%{password: "short"}) + assert "password is too short" in errors_on(changeset).password + assert %{password: ["password is too short"]} = errors_on(changeset) + + """ + def errors_on(changeset) do + Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> + Regex.replace(~r"%{(\w+)}", message, fn _, key -> + opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() + end) + end) + end +end diff --git a/test/support/fixtures/tasks_fixtures.ex b/test/support/fixtures/tasks_fixtures.ex new file mode 100644 index 0000000..04639ed --- /dev/null +++ b/test/support/fixtures/tasks_fixtures.ex @@ -0,0 +1,20 @@ +defmodule App.TasksFixtures do + @moduledoc """ + This module defines test helpers for creating + entities via the `App.Tasks` context. + """ + + @doc """ + Generate a item. + """ + def item_fixture(attrs \\ %{}) do + {:ok, item} = + attrs + |> Enum.into(%{ + "text" => "some text" + }) + |> App.Tasks.create_item() + + item + end +end diff --git a/test/test_helper.exs b/test/test_helper.exs new file mode 100644 index 0000000..4fe7a40 --- /dev/null +++ b/test/test_helper.exs @@ -0,0 +1,2 @@ +ExUnit.start() +Ecto.Adapters.SQL.Sandbox.mode(App.Repo, :manual)