Skip to content

Commit

Permalink
feat: add reading time to content
Browse files Browse the repository at this point in the history
  • Loading branch information
abehidek committed Dec 11, 2023
1 parent 5b4dc4f commit 090dd70
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
16 changes: 15 additions & 1 deletion assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,22 @@ window.addEventListener("phx:page-loading-stop", _ => {
})
})

let Hooks = {
"CalculateReadingTime": {
mounted() {
const content = document.getElementById("article").innerText;
const wpm = 225;

const words = content.trim().split(/\s+/).length;
console.log("article words:", words)
const time = Math.round(words / wpm);
document.getElementById("time").innerText = `${time} ${time > 0 ? "minutes" : "minute"}`;
}
}
}

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

// Show progress bar on live navigation and form submits
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
Expand Down
6 changes: 5 additions & 1 deletion lib/hidek_xyz_web/live/content/show_live.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,15 @@ defmodule HidekXyzWeb.Content.ShowLive do
<div class="flex justify-between">
<p class="mb-2"><%= @article.frontmatter.publish_date %></p>
<div class="flex gap-2">
<p>
<span id="time" phx-hook="CalculateReadingTime"></span> read -
</p>
<%= live_render(@socket, HidekXyzWeb.ContentUsersLive,
sticky: true,
id: "content_users_live",
session: %{"id" => @article.slug}
) %>
<p>-</p>
<%= live_render(@socket, HidekXyzWeb.ContentViewsLive,
sticky: true,
id: "content_views_live",
Expand Down Expand Up @@ -71,7 +75,7 @@ defmodule HidekXyzWeb.Content.ShowLive do
<hr />
<div class="article-body"><%= raw(@article.body) %></div>
<div id="article" class="article-body"><%= raw(@article.body) %></div>
</article>
"""
end
Expand Down

0 comments on commit 090dd70

Please sign in to comment.