Skip to content

Commit

Permalink
Update js to latest cascading parent child approach
Browse files Browse the repository at this point in the history
  • Loading branch information
chrismccord committed Feb 13, 2019
1 parent 0f6b763 commit 0f98861
Show file tree
Hide file tree
Showing 10 changed files with 147 additions and 52 deletions.
22 changes: 22 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# MIT License

Copyright (c) 2018 Chris McCord

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
93 changes: 70 additions & 23 deletions assets/js/live_view.js → assets/js/phoenix_live_view.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,12 @@ connection and error class changes. This behavior may be disabled by overriding
import {Socket} from "phoenix"
import morphdom from "morphdom"

const PHX_VIEW_SELECTOR = "[data-phx-view]"
const PHX_VIEW = "data-phx-view"
const PHX_CONNECTED_CLASS = "phx-connected"
const PHX_DISCONNECTED_CLASS = "phx-disconnected"
const PHX_ERROR_CLASS = "phx-error"
const PHX_PARENT_ID = "data-phx-parent-id"
const PHX_VIEW_SELECTOR = `[${PHX_VIEW}]`
const PHX_ERROR_FOR = "data-phx-error-for"
const PHX_HAS_FOCUSED = "data-phx-has-focused"
const PHX_BOUND = "data-phx-bound"
Expand Down Expand Up @@ -150,10 +151,10 @@ export default class LiveSocket {

connect(){
if(["complete", "loaded","interactive"].indexOf(document.readyState) >= 0){
this.joinViewChannels()
this.joinRootView()
} else {
document.addEventListener("DOMContentLoaded", () => {
this.joinViewChannels()
this.joinRootView()
})
}
return this.socket.connect()
Expand All @@ -163,8 +164,9 @@ export default class LiveSocket {

channel(topic, params){ return this.socket.channel(topic, params || {}) }

joinViewChannels(){
document.querySelectorAll(PHX_VIEW_SELECTOR).forEach(el => this.joinView(el))
joinRootView(){
let rootEl = document.querySelector(PHX_VIEW_SELECTOR)
if(rootEl){ this.joinView(rootEl) }
}

joinView(el, parentView){
Expand All @@ -173,11 +175,15 @@ export default class LiveSocket {
view.join()
}

getViewById(id){ return this.views[id] }

destroyViewById(id){
console.log("destroying", id)
let view = this.views[id]
if(!view){ throw `cannot destroy view for id ${id} as it does not exist` }
view.destroy(() => delete this.views[view.id])
if(view){
delete this.views[view.id]
// console.log("destroying", id)
view.destroy()
}
}

getBindingPrefix(){ return this.bindingPrefix }
Expand Down Expand Up @@ -262,8 +268,8 @@ let DOM = {
},
onNodeAdded: function(el){
// nested view handling
if(DOM.isPhxChild(el)){
setTimeout(() => view.liveSocket.joinView(el, view), 1)
if(DOM.isPhxChild(el) && view.ownsElement(el)){
view.onNewChildAdded(el)
return true
}
view.maybeBindAddedNode(el)
Expand All @@ -277,7 +283,10 @@ let DOM = {
},
onBeforeElUpdated: function(fromEl, toEl) {
// nested view handling
if(DOM.isPhxChild(toEl)){ return false }
if(DOM.isPhxChild(toEl)){
DOM.mergeAttrs(fromEl, toEl)
return false
}

// input handling
if(fromEl.getAttribute && fromEl.getAttribute(PHX_HAS_SUBMITTED)){
Expand All @@ -301,11 +310,15 @@ let DOM = {
document.dispatchEvent(new Event("phx:update"))
},

mergeInputs(target, source){
mergeAttrs(target, source){
source.getAttributeNames().forEach(name => {
let value = source.getAttribute(name)
target.setAttribute(name, value)
})
},

mergeInputs(target, source){
DOM.mergeAttrs(target, source)
target.readOnly = source.readOnly
},

Expand All @@ -329,15 +342,18 @@ class View {
this.statics = []
this.dynamics = []
this.parent = parentView
this.newChildrenAdded = false
this.gracefullyClosed = false
this.el = el
this.prevKey = null
this.bindingPrefix = liveSocket.getBindingPrefix()
this.loader = this.el.nextElementSibling
this.id = this.el.id
this.view = this.el.getAttribute("data-view")
this.view = this.el.getAttribute(PHX_VIEW)
this.hasBoundUI = false
this.joinParams = {session: this.getSession()}
this.channel = this.liveSocket.channel(`views:${this.id}`, () => this.joinParams)
this.channel = this.liveSocket.channel(`views:${this.id}`, () => {
return {session: this.getSession()}
})
this.loaderTimer = setTimeout(() => this.showLoader(), LOADER_TIMEOUT)
this.bindChannel()
}
Expand All @@ -346,11 +362,15 @@ class View {
return this.el.getAttribute(PHX_SESSION)|| this.parent.getSession()
}

destroy(callback){
this.channel.leave()
.receive("ok", callback)
.receive("error", callback)
.receive("timeout", callback)
destroy(callback = function(){}){
if(this.hasGracefullyClosed()){
callback()
} else {
this.channel.leave()
.receive("ok", callback)
.receive("error", callback)
.receive("timeout", callback)
}
}

hideLoader(){
Expand All @@ -374,23 +394,48 @@ class View {
DOM.patch(this, this.el, this.id, Rendered.toString(this.rendered))
if(!this.hasBoundUI){ this.bindUI() }
this.hasBoundUI = true
this.joinNewChildren()
}

joinNewChildren(){
let selector = `${PHX_VIEW_SELECTOR}[${PHX_PARENT_ID}="${this.id}"]`
document.querySelectorAll(selector).forEach(childEl => {
let child = this.liveSocket.getViewById(childEl.id)
if(!child){
this.liveSocket.joinView(childEl, this)
}
})
}

update(diff){
if(isEmpty(diff)){ return }
// console.log("update", JSON.stringify(diff))
Rendered.mergeDiff(this.rendered, diff)
let html = Rendered.toString(this.rendered)
this.newChildrenAdded = false
DOM.patch(this, this.el, this.id, html)
if(this.newChildrenAdded){ this.joinNewChildren() }
}

onNewChildAdded(el){
this.newChildrenAdded = true
}

bindChannel(){
this.channel.on("render", (diff) => this.update(diff))
this.channel.on("redirect", ({to, flash}) => Browser.redirect(to, flash) )
this.channel.on("session", ({token}) => this.joinParams.session = token)
this.channel.on("session", ({token}) => this.el.setAttribute(PHX_SESSION, token))
this.channel.onError(() => this.onError())
this.channel.onClose(() => this.onGracefulClose())
}

onGracefulClose(){
this.gracefullyClosed = true
this.liveSocket.destroyViewById(this.id)
}

hasGracefullyClosed(){ return this.gracefullyClosed }

join(){
this.channel.join()
.receive("ok", data => this.onJoin(data))
Expand All @@ -403,6 +448,7 @@ class View {
}

onError(){
// console.log("error", this.view)
document.activeElement.blur()
this.displayError()
}
Expand Down Expand Up @@ -465,7 +511,8 @@ class View {
}

ownsElement(element){
return element.closest(PHX_VIEW_SELECTOR).id === this.id
return element.getAttribute(PHX_PARENT_ID) === this.id ||
element.closest(PHX_VIEW_SELECTOR).id === this.id
}

bindUI(){
Expand Down Expand Up @@ -595,4 +642,4 @@ class View {
return el
}
}
}
}
19 changes: 12 additions & 7 deletions assets/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions assets/package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
{
"repository": {},
"name": "phoenix",
"version": "0.0.1",
"description": "The Phoenix LiveView JavaScript client.",
"license": "MIT",
"main": "./priv/static/phoenix_live_view.js",
"repository": {},
"scripts": {
"deploy": "webpack --mode production",
"build": "webpack --mode production",
"watch": "webpack --mode development --watch"
},
"dependencies": {
Expand All @@ -14,6 +18,7 @@
"babel-core": "^6.26.0",
"babel-loader": "^7.1.3",
"babel-preset-env": "^1.6.1",
"expose-loader": "^0.7.5",
"copy-webpack-plugin": "^4.5.0",
"css-loader": "^0.28.10",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
Expand Down
34 changes: 16 additions & 18 deletions assets/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path')

module.exports = {
entry: './js/app.js',
entry: './js/phoenix_live_view.js',
output: {
filename: 'app.js',
path: path.resolve(__dirname, '../priv/static/js')
filename: 'phoenix_live_view.js',
path: path.resolve(__dirname, '../priv/static'),
library: 'phoenix_live_view',
libraryTarget: 'umd',
globalObject: 'this'
},
module: {
rules: [
{
test: path.resolve(__dirname, './js/phoenix_live_view.js'),
use: [{
loader: 'expose-loader',
options: 'Phoenix.LiveView'
}]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}
]
},
plugins: [
new ExtractTextPlugin('../css/app.css'),
new CopyWebpackPlugin([{ from: 'static/', to: '../' }])
]
};
plugins: []
}
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ defmodule Phoenix.LiveView.MixProject do
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:phoenix, "~> 1.4.1-dev", github: "phoenixframework/phoenix", branch: "v1.4"},
{:phoenix, "~> 1.4.1"},
{:phoenix_html, "~> 2.13"},
{:jason, "~> 1.0", optional: true}
]
Expand Down
2 changes: 1 addition & 1 deletion mix.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
%{
"jason": {:hex, :jason, "1.1.2", "b03dedea67a99223a2eaf9f1264ce37154564de899fd3d8b9a21b1a6fd64afe7", [:mix], [{:decimal, "~> 1.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm"},
"mime": {:hex, :mime, "1.3.0", "5e8d45a39e95c650900d03f897fbf99ae04f60ab1daa4a34c7a20a5151b7a5fe", [:mix], [], "hexpm"},
"phoenix": {:git, "https://github.com/phoenixframework/phoenix.git", "eb3eb71b49de36f778141bdf6b6081a3fcac4d72", [branch: "v1.4"]},
"phoenix": {:hex, :phoenix, "1.4.1", "801f9d632808657f1f7c657c8bbe624caaf2ba91429123ebe3801598aea4c3d9", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 1.1", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 1.0 or ~> 2.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}], "hexpm"},
"phoenix_html": {:hex, :phoenix_html, "2.13.0", "3bad10de5efb6c590f7aa5b316ad0d3faa054715414c9b562c410de4ffb885c5", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"},
"phoenix_pubsub": {:hex, :phoenix_pubsub, "1.1.1", "6668d787e602981f24f17a5fbb69cc98f8ab085114ebfac6cc36e10a90c8e93c", [:mix], [], "hexpm"},
"plug": {:hex, :plug, "1.7.1", "8516d565fb84a6a8b2ca722e74e2cd25ca0fc9d64f364ec9dbec09d33eb78ccd", [:mix], [{:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}], "hexpm"},
Expand Down
Loading

0 comments on commit 0f98861

Please sign in to comment.