Skip to content

Commit

Permalink
feat: native image share
Browse files Browse the repository at this point in the history
  • Loading branch information
krthr committed Sep 25, 2024
1 parent 9c458fe commit d7d8797
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 9 deletions.
87 changes: 79 additions & 8 deletions resources/js/poem.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,84 @@ const IOS = /iPad|iPhone|iPod/
const MACOS = /Mac OS X/
const SAFARI = /safari|applewebkit/i

async function createFile() {
try {
const response = await fetch(new URL(poem.imagePath, window.location.origin))
const data = await response.blob()

const metadata = {
type: 'image/jpeg',
}

const file = new File([data], 'poem.jpg', metadata)
return file
} catch (error) {}
}

/**
*
* @param {ShareData} data
*/
async function nativeShare(data) {
console.log('nativeShare', data)

try {
await navigator.share(data)
return true
} catch (error) {
console.error(error)
}

return false
}

/**
*
* @param {ShareData} payload
* @returns
*/
async function shareWithImage(payload) {
console.log('shareWithImage', payload)

if ('canShare' in navigator) {
const image = await createFile()

if (!image) {
return false
}

const payloadWithImage = {
...payload,
files: [image],
}
const canShare = navigator.canShare(payloadWithImage)

if (canShare) {
const result = await nativeShare(payloadWithImage)
return result
}
}

return false
}

async function share() {
const payload = {
title: window.poem.title,
text: window.poem.poem,
url: window.poem.url,
}

console.log('sharing', payload)

const sharedWithImage = await shareWithImage(payload)
if (sharedWithImage) {
return
}

await nativeShare(payload)
}

/**
*
* @param {HTMLElement} node
Expand Down Expand Up @@ -71,14 +149,7 @@ window.onload = () => {
console.log('Can share!')

shareBtn.onclick = async () => {
const payload = {
title: window.poem.title,
text: window.poem.poem,
url: window.poem.url,
}

console.log('Sharing', payload)
await navigator.share(payload)
await share()

window.gtag && window.gtag('event', 'share_native')
window.LogRocket && window.LogRocket.track('share_native')
Expand Down
3 changes: 2 additions & 1 deletion resources/views/pages/poem.edge
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
window.poem = {
title: "{{ poem.title }}",
poem: `{{ poem.poem }}`,
url: "{{ request.completeUrl() }}"
url: "{{ request.completeUrl() }}",
imageUrl: "{{ image }}"
};
</script>
@end
Expand Down

0 comments on commit d7d8797

Please sign in to comment.