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

feat: Web Share (#286) #341

Merged
merged 19 commits into from
Jan 4, 2022
Merged
Show file tree
Hide file tree
Changes from 11 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
11 changes: 10 additions & 1 deletion components/base/button/BaseButton.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
<template>
<VBtn outlined v-bind="$attrs" class="my-2" @click="$emit('click', $event)">
<VBtn
:outlined="outlined"
v-bind="$attrs"
class="my-2"
@click="$emit('click', $event)"
>
<VIcon v-if="icon" left>{{ mdiIcon }}</VIcon>
<slot>
<span>{{ text }}</span>
Expand Down Expand Up @@ -31,6 +36,10 @@ export default {
icon: {
type: String,
default: null
},
outlined: {
type: Boolean,
default: true
}
},
computed: {
Expand Down
158 changes: 158 additions & 0 deletions components/base/button/BaseButtonShare.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
<template>
<BaseButton
v-if="condition"
icon="mdiShare"
:text="buttonText"
v-bind="$attrs"
@click="share"
/>
</template>

<script>
import 'share-api-polyfill'
import { mapState, mapGetters } from 'vuex'

async function navigatorShare(shareData, polyfillOptions) {
try {
await navigator.share(shareData, polyfillOptions)
} catch (err) {
console.error('navigator.share() failed', err)
}
}

export default {
props: {
buttonText: {
type: String,
default: 'Share'
},
title: {
type: String,
default: ''
},
text: {
type: String,
default: ''
},
files: {
type: Array[File],
default: () => []
},
fileShare: {
type: Boolean,
default: false
}
},
data() {
const condition =
!this.fileShare ||
(navigator.canShare &&
navigator.canShare({
files: [new File(['test'], 'test.txt')]
}))
return {
condition
}
},
computed: {
...mapState(['config']),
...mapGetters(['appName', 'manifest']),
manifestTitle() {
const { title } = this.manifest(this.$route)
return title
},
hashtags() {
const { manifestTitle } = this
const hashtags = [...(this.config.hashtags || ['hestialabs'])]
if (manifestTitle) {
hashtags.push(manifestTitle)
}
return hashtags
},
titleToShare() {
const { title, manifestTitle } = this
if (title) {
// use prop when provided
return title
}
if (manifestTitle) {
return `${this.appName}: ${manifestTitle}`
}
return this.appName
},
quoteToShare() {
const { text, manifestTitle } = this
if (text) {
// use prop when provided
return text
}
let textToShare = 'Analyze the data collected on you'
if (manifestTitle) {
textToShare += ` by ${manifestTitle}`
}
return `${textToShare}.`
},
textToShare() {
return `${this.quoteToShare} ${this.hashtags.map(h => `#${h}`).join(' ')}`
}
},
methods: {
async share() {
const {
hashtags,
titleToShare: title,
quoteToShare,
textToShare,
files
} = this

if (
files.length &&
!(navigator.canShare && navigator.canShare({ files }))
) {
throw new Error('Your system does not support sharing files')
}

let text = quoteToShare
if (navigator.canShare && navigator.canShare({ text })) {
// include hashtags for Web Share API
text = textToShare
}

let url = this.$url()
if (process.env.NODE_ENV === 'development') {
url = `https://experiences.hestialabs.org${this.$route.path}`
}

const webShareData = {
title,
text,
url,
files
}

await navigatorShare(
{
// Web Share Api options
...webShareData,

// share-api-polyfill options
hashtag: 'hestialabs',
hashtags,
via: 'HestiaLabs'
// fbId enables sharing with Facebook Messenger
// fbId: '?'
},
{
// disable text sharing with email, copy, sms, and messenger
// since polyfill does not support text for these types
email: !text,
sms: !text,
copy: !text,
messenger: !text
}
)
}
}
}
</script>
92 changes: 87 additions & 5 deletions components/chart/ChartView.vue
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
<template>
<div>
<component
:is="component"
v-if="isValid && !isEmpty"
v-bind="{ values, headers, ...vizProps }"
/>
<div v-if="isValid && !isEmpty" ref="view">
<component :is="component" v-bind="{ values, headers, ...vizProps }" />
</div>
<i v-else-if="isValid">No data found</i>
<i v-else>Data in this format cannot be displayed by this visualization</i>
<BaseButton icon="mdiExport" text="Export" @click="exportFiles" />
<BaseButtonShare file-share :disabled="!files" :files="files" />
</div>
</template>

<script>
import _ from 'lodash'
import { processError } from '@/utils/utils'

function isDataValid(data) {
return (
_.every(
Expand All @@ -22,9 +24,53 @@ function isDataValid(data) {
_.every(data.items, i => _.every(data.headers, h => _.has(i, h)))
)
}

function isDataEmpty(data) {
return data.items.length === 0
}

// inspired by https://github.com/JuanIrache/d3-svg-to-png
function svgToFile(
svgElement,
filename,
{ scale = 1, format = 'png', quality = 1 }
) {
const svgData = new XMLSerializer().serializeToString(svgElement)
const canvas = document.createElement('canvas')
const svgSize = svgElement.getBoundingClientRect()

// Resize can break shadows
canvas.width = svgSize.width * scale
canvas.height = svgSize.height * scale
canvas.style.width = svgSize.width
canvas.style.height = svgSize.height

const ctx = canvas.getContext('2d')
ctx.scale(scale, scale)

const img = document.createElement('img')
img.setAttribute(
'src',
'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)))
)

const type = `image/${format}`

return new Promise(resolve => {
img.onload = () => {
ctx.drawImage(img, 0, 0)
canvas.toBlob(
blob => {
img.onload = null
resolve(new File([blob], `${filename}.${format}`, { type }))
},
type,
quality
)
}
})
}

export default {
props: {
data: {
Expand All @@ -40,6 +86,14 @@ export default {
default: () => {}
}
},
data() {
return {
files: null,
progress: false,
status: false,
error: false
}
},
computed: {
isValid() {
return isDataValid(this.data)
Expand All @@ -56,6 +110,34 @@ export default {
component() {
return () => import(`@/components/chart/view/${this.graphName}`)
}
},
methods: {
async exportFiles() {
this.progress = true
this.status = false
this.error = false
try {
const format = 'png'

const svgs = [...this.$refs.view.querySelectorAll('svg')].filter(
// avoid including Vuetify icons
el => !el.classList.contains('v-icon__svg')
)
this.files = await Promise.all(
svgs.map((svg, index) => {
const filename = `chart-${index}`
return svgToFile(svg, filename, { format })
})
)
} catch (error) {
console.error(error)
this.error = true
this.message = processError(error)
} finally {
this.progress = false
this.status = true
}
}
}
}
</script>
42 changes: 0 additions & 42 deletions components/share-button/ShareButtonFacebook.vue

This file was deleted.

37 changes: 0 additions & 37 deletions components/share-button/ShareButtonTwitter.vue

This file was deleted.

1 change: 0 additions & 1 deletion components/unit/UnitQuery.vue
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
v-if="vizVega"
:spec-file="vizVega"
:data="result"
:div-id="`viz-${index}`"
class="text-center"
/>
<ChartView
Expand Down
Loading