Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazy Load Artwork example #41

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions assets/css/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ pre{
animation: slide-up 0.4s ease;
}

.user-artwork {
border-radius: 50%;
}

@keyframes slide-up {
0% {
opacity: 0;
Expand Down
108 changes: 107 additions & 1 deletion assets/js/app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import css from "../css/app.css"
import "phoenix_html"
import {Socket} from "phoenix"
import IntersectionObserverAdmin from 'intersection-observer-admin';
import {LiveSocket, debug} from "phoenix_live_view"

let Hooks = {}
Expand All @@ -27,7 +28,112 @@ Hooks.InfiniteScroll = {
updated(){ this.pending = this.page() }
}

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
// TODO: make IE11 compat with rAF
const observerAdmin = new IntersectionObserverAdmin();
const sentinelOptions = { rootMargin: '0px 0px 90px 0px', threshold: 0 };
const observerOptions = { rootMargin: '0px 0px 0px 0px', threshold: 0 };

Hooks.ObserverInfiniteScroll = {
observerAdmin,
page() { return this.el.dataset.page },
mounted(){
this.pending = this.page()
let enterCallback = ({ target }) => {
if (this.pending == this.page()) {
this.pending = this.page() + 1
this.pushEvent("load-more", {})
}
}

let exitCallback = ({ isIntersecting, target }) => {
if (isIntersecting) {
this.observerAdmin.unobserve(target, sentinelOptions);
}
}

this.observerAdmin.addEnterCallback(
this.el,
enterCallback.bind(this)
)
this.observerAdmin.addExitCallback(
this.el,
exitCallback.bind(this)
)

this.observerAdmin.observe(
this.el,
sentinelOptions
)
},

// after DOM Patch
updated(){ this.pending = this.page() }
}

Hooks.LazyArtwork = {
observerAdmin,
artwork() { return this.el.querySelector('img') },

mounted() {
window.requestIdleCallback(() => {
let enterCallback = ({ target: img }) => {
if (img) {
if (img && img.dataset) {
img.src = img.dataset.src;
}
}
}

let exitCallback = ({ isIntersecting, target: img }) => {
if (isIntersecting) {
this.observerAdmin.unobserve(img, observerOptions);
}
}

const artwork = this.artwork();
this.observerAdmin.addEnterCallback(
artwork,
enterCallback
)
this.observerAdmin.addExitCallback(
artwork,
exitCallback
)

this.observerAdmin.observe(
artwork,
observerOptions
)
});
}
}

let serializeForm = (form) => {
let formData = new FormData(form)
let params = new URLSearchParams()
for(let [key, val] of formData.entries()){ params.append(key, val) }

return params.toString()
}

let Params = {
data: {},
set(namespace, key, val){
if(!this.data[namespace]){ this.data[namespace] = {}}
this.data[namespace][key] = val
},
get(namespace){ return this.data[namespace] || {} }
}

Hooks.SavedForm = {
mounted(){
this.el.addEventListener("input", e => {
Params.set(this.viewName, "stashed_form", serializeForm(this.el))
})
}
}

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks, params: {_csrf_token: csrfToken}})

liveSocket.connect()
47 changes: 36 additions & 11 deletions assets/package-lock.json

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

1 change: 1 addition & 0 deletions assets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"copy-webpack-plugin": "^4.5.0",
"css-loader": "^0.28.10",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"intersection-observer-admin": "^0.2.10",
"morphdom": "^2.5.12",
"style-loader": "^0.20.2",
"webpack": "4.0.0",
Expand Down
Binary file added assets/static/images/1x1.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion lib/demo/accounts/user.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ defmodule Demo.Accounts.User do
import Ecto.Changeset

schema "users" do
field :artwork, :map
field :username, :string
field :email, :string
field :phone_number, :string
Expand All @@ -17,7 +18,7 @@ defmodule Demo.Accounts.User do
@doc false
def changeset(user, attrs) do
user
|> cast(attrs, [:username, :email, :phone_number, :password])
|> cast(attrs, [:username, :artwork, :email, :phone_number, :password])
|> validate_required([:username, :email, :phone_number])
|> validate_confirmation(:password)
|> validate_format(:username, ~r/^[a-zA-Z0-9_]*$/,
Expand Down
25 changes: 19 additions & 6 deletions lib/demo_web/live/user_live/index_auto_scroll.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ defmodule DemoWeb.UserLive.Row do

def render(assigns) do
~L"""
<span id="<%= @id %>" phx-click="click" phx-target="#<%= @id %>" phx-hook="Test">
<span id="<%= @id %>" phx-click="click" phx-target="#<%= @id %>">
Email: <%= @email %> <%= @count %>
</span>
"""
Expand All @@ -28,6 +28,20 @@ defmodule DemoWeb.UserLive.Row do
def render(assigns) do
~L"""
<tr class="user-row" id="<%= @id %>" phx-click="click" phx-target="#<%= @id %>">
<td phx-hook="LazyArtwork">
<img
class="user-artwork"
src=<%= DemoWeb.Router.Helpers.static_url(DemoWeb.Endpoint, "/images/1x1.gif") %> ;
data-src=<%= Map.get(@user.artwork, "url") %>
alt=<%= @user.username %>
height=<%= Map.get(@user.artwork, "height") %>
width=<%= Map.get(@user.artwork, "width") %>
style="background-color: lightgray"
role="presentation"
phx-update="ignore"
data-lazy-artwork
/>
</td>
<td><%= @user.username %> <%= @count %></td>
<td>
<%= live_component @socket, Email, id: "email-#{@id}", email: @user.email %>
Expand All @@ -49,22 +63,21 @@ defmodule DemoWeb.UserLive.IndexAutoScroll do
def render(assigns) do
~L"""
<table>
<tbody id="users"
phx-update="append"
phx-hook="InfiniteScroll"
data-page="<%= @page %>">
<tbody id="users" phx-update="append">
<%= for user <- @users do %>
<%= live_component @socket, Row, id: "user-#{user.id}", user: user %>
<% end %>
</tbody>
</table>

<div phx-hook="ObserverInfiniteScroll" data-page="<%= @page %>"></div>
"""
end

def mount(_session, socket) do
{:ok,
socket
|> assign(page: 1, per_page: 10)
|> assign(page: 1, per_page: 20)
|> fetch(), temporary_assigns: [users: []]}
end

Expand Down
Loading