Skip to content

Commit

Permalink
Add JS-hook for WebShare-API/clipboard-copy
Browse files Browse the repository at this point in the history
QQ: seems like I can only use buttons to do click events, how might I go
about emitting click events from icons?
  • Loading branch information
rtshkmr committed Dec 6, 2023
1 parent fe58e27 commit 714834b
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 19 deletions.
29 changes: 17 additions & 12 deletions assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,31 @@
//

// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
import "phoenix_html"
import "phoenix_html";
// Establish Phoenix Socket and LiveView configuration.
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
import { Socket } from "phoenix";
import { LiveSocket } from "phoenix_live_view";
import topbar from "../vendor/topbar";
import Hooks from "./hooks.js";

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

// 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(300))
window.addEventListener("phx:page-loading-stop", _info => topbar.hide())
topbar.config({ barColors: { 0: "#29d" }, shadowColor: "rgba(0, 0, 0, .3)" });
window.addEventListener("phx:page-loading-start", (_info) => topbar.show(300));
window.addEventListener("phx:page-loading-stop", (_info) => topbar.hide());

// connect if there are any LiveViews on the page
liveSocket.connect()
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

window.liveSocket = liveSocket;
34 changes: 34 additions & 0 deletions assets/js/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Externalised hooks object to be used by app.js.
*/
import { getSharer } from "./web_share.js";

let Hooks = {};

Hooks.ShareQuoteButton = {
mounted() {
let callback = () => console.log("share quote!");
if ("share" in navigator) { // uses webshare api:
callback = () => {
const shareTitle = this.el.getAttribute("data-share-title");
const shareUrl = window.location.href;
const sharer = getSharer("url", shareTitle, shareUrl);
if (!sharer) {
return;
}

window.shareUrl = sharer;
window.shareUrl(shareUrl);
};
} else if ("clipboard" in navigator) {
callback = () => {
const verse = JSON.parse(this.el.getAttribute("data-verse"));
navigator.clipboard.writeText(verse.text);
};
}

this.el.addEventListener("click", callback);
},
};

export default Hooks;
60 changes: 60 additions & 0 deletions assets/js/web_share.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* This file is for helpers to interface with the WebShare API.
*
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Web_Share_API
*/

const sharers = {
"file": shareFile, // to assign to window.shareContent
"url": shareUrl, // to assign to window.shareUrl
};

/**
* Returns a function that can be used to set various webshare api attributes.
*/
export function getSharer(sharingType, ...args) {
if (!checkBrowserSupport()) {
console.warning(`This browser doesn't support shares like that, please copy the url instead.`);
return null;
}
if (!(sharingType in sharers)) {
console.warning(`$Sharing Type of {sharingType} is not supported yet.`);
return null;
}

return () => sharers[sharingType](...args);
}

function shareFile(title, url) {
if (navigator.share) {
navigator.share({
title: title,
url: url,
})
.then(() => console.log("Successful share"))
.catch((error) => console.log("Error sharing", error));
} else {
console.info(`Your system doesn't support sharing files.`);
}
}

function shareUrl(url) {
if (navigator.share) {
navigator.share({
url: url,
})
.then(() => console.log("Successful share"))
.catch((error) => console.log("Error sharing", error));
} else {
console.info(`Your system doesn't support sharing urls.`);
}
}

/**
* Returns true if the browser supports the navigator.share function, false otherwise.
* */
function checkBrowserSupport() {
// TODO: implement this
return true

}
26 changes: 19 additions & 7 deletions lib/vyasa_web/live/gita_live/show_verse.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,27 @@ defmodule VyasaWeb.GitaLive.ShowVerse do
@impl true
def render(assigns) do
~H"""
<.header >
<:subtitle><%= @verse.chapter_number %>:<%= @verse.verse_number %></:subtitle>
<.header>
<:subtitle><%= @verse.chapter_number %>:<%= @verse.verse_number %></:subtitle>
<p class="font-dn text-2xl"><%= @verse.text |> String.split("।।") |> List.first() %></p>
</.header>
<br/>
<p><%= @verse.transliteration %></p>
<br/>
<p><%= @verse.word_meanings %></p>
<br />
<p><%= @verse.transliteration %></p>
<br />
<p><%= @verse.word_meanings %></p>
<br />
<.button
phx-hook="ShareQuoteButton"
id="ShareQuoteButton"
data-verse={Jason.encode!(@verse)}
data-share-title={"Gita Chapter #{@verse.chapter_number} #{@verse.title}"}
>
Share
</.button>
<.back navigate={~p"/gita/#{@verse.chapter_number}"}>Back to Gita Chapter <%= @verse.chapter_number%></.back>
<.back navigate={~p"/gita/#{@verse.chapter_number}"}>
Back to Gita Chapter <%= @verse.chapter_number %>
</.back>
<.back navigate={~p"/gita"}>Back to Gita</.back>
"""
end
Expand All @@ -33,4 +44,5 @@ defmodule VyasaWeb.GitaLive.ShowVerse do
|> stream(:verses, Gita.verses(chapter_no))
|> assign(:verse, Gita.verse(chapter_no, verse_no))}
end

end

0 comments on commit 714834b

Please sign in to comment.