From d7d87978f86b417b62f6416dc9f8f6e9a7748b9a Mon Sep 17 00:00:00 2001 From: Wilson Date: Wed, 25 Sep 2024 21:59:14 +0200 Subject: [PATCH] feat: native image share --- resources/js/poem.js | 87 ++++++++++++++++++++++++++++++--- resources/views/pages/poem.edge | 3 +- 2 files changed, 81 insertions(+), 9 deletions(-) diff --git a/resources/js/poem.js b/resources/js/poem.js index 58525a2..deb452c 100644 --- a/resources/js/poem.js +++ b/resources/js/poem.js @@ -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 @@ -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') diff --git a/resources/views/pages/poem.edge b/resources/views/pages/poem.edge index df6401d..d64b899 100644 --- a/resources/views/pages/poem.edge +++ b/resources/views/pages/poem.edge @@ -10,7 +10,8 @@ window.poem = { title: "{{ poem.title }}", poem: `{{ poem.poem }}`, - url: "{{ request.completeUrl() }}" + url: "{{ request.completeUrl() }}", + imageUrl: "{{ image }}" }; @end