Merge branch 'feat/youtube-lite'

This commit is contained in:
Sam Carlton 2021-04-27 17:21:19 -05:00
commit 3d580ca0e9
4 changed files with 217 additions and 38 deletions

View file

@ -9,21 +9,75 @@
class="video-canvas w-screen flex flex-col justify-center items-center bg-black" class="video-canvas w-screen flex flex-col justify-center items-center bg-black"
> >
<div class="ratio-wrapper w-full max-w-4xl"> <div class="ratio-wrapper w-full max-w-4xl">
<div class="relative overflow-hidden w-full pb-16/9"> <div
class="relative overflow-hidden w-full pb-16/9"
@pointerover.once="warmConnections()"
>
<div
v-if="playerLoaded === false"
class="player-poster cursor-pointer"
@click="startPlayerLoad()"
>
<picture
class=""
>
<source
v-for="(source, key) in posterSources"
:key="key"
:sizes="source.sizes"
:data-srcset="source.srcset"
:type="`image/${ key }`"
>
<img
:data-src="video.thumbnail.src"
:alt="video.name"
class="absolute inset-0 h-full w-full object-cover lazyload"
>
</picture>
<div
class="video-card-overlay absolute inset-0 flex justify-center items-center bg-gradient-to-tr from-black to-transparent p-4"
style="--gradient-from-color:rgba(0, 0, 0, 1); --gradient-to-color:rgba(0, 0, 0, 0.7);"
>
<div class="play-circle w-16 h-16 bg-white-2 flex justify-center items-center outline-0 rounded-full ease">
<svg
viewBox="0 0 18 18"
style="width:18px;height:18px;margin-left:3px"
>
<path
fill="currentColor"
d="M15.562 8.1L3.87.225c-.818-.562-1.87 0-1.87.9v15.75c0 .9 1.052 1.462 1.87.9L15.563 9.9c.584-.45.584-1.35 0-1.8z"
/>
</svg>
</div>
</div>
</div>
<iframe <iframe
v-else
ref="frame" ref="frame"
:id="frameId" :id="frameId"
:src="`https://www.youtube-nocookie.com/embed/${video.id}?enablejsapi=1&autoplay=1&modestbranding=1&playsinline=1`" :src="`https://www.youtube-nocookie.com/embed/${video.id}?enablejsapi=1&autoplay=1&modestbranding=1&playsinline=1`"
class="absolute h-full w-full" class="absolute inset-0 h-full w-full object-cover"
frameborder="0" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen allowfullscreen
/> />
</div> </div>
<!-- <pre>
hasPlayer: {{ hasPlayer }}
</pre> -->
<!-- <pre>
player: {{ player }}
</pre> -->
<!-- <pre>
timstamps: {{ video.timestamps }}
</pre> -->
</div> </div>
<div <div
v-if="hasTimestamps && hasPlayer" v-if="hasTimestamps"
class="video-timestamps w-full max-w-4xl" class="video-timestamps w-full max-w-4xl"
> >
<div <div
@ -43,7 +97,7 @@
:class-groups="{ :class-groups="{
shadow: 'neumorphic-shadow-inner' shadow: 'neumorphic-shadow-inner'
}" }"
@click.stop="seekTo(timestamp.inSeconds); player.playVideo()" @click.stop="seekTo(timestamp.inSeconds)"
>{{ timestamp.fullText }}</button> >{{ timestamp.fullText }}</button>
</div> </div>
@ -54,6 +108,8 @@
</template> </template>
<script> <script>
import 'lazysizes'
import LinkButton from '~/components/link-button.vue' import LinkButton from '~/components/link-button.vue'
export default { export default {
@ -68,13 +124,27 @@ export default {
}, },
data: function () { data: function () {
return { return {
playerLoaded: false,
player: null, player: null,
playing: false, playing: false,
progressInterval: null, progressInterval: null,
playerTime: 0 playerTime: 0,
preconnected: false
} }
}, },
computed: { computed: {
posterSources () {
const webpSource = {
...this.video.thumbnail,
srcset: this.video.thumbnail.srcset.replaceAll('ytimg.com/vi/', 'ytimg.com/vi_webp/').replace(/.png|.jpg|.jpeg/g, '.webp')
}
return {
webp: webpSource,
jpeg: this.video.thumbnail
}
},
frameId () { frameId () {
return `youtube-player-${this.video.id}-${this._uid}` return `youtube-player-${this.video.id}-${this._uid}`
}, },
@ -149,7 +219,14 @@ export default {
// Set frame ID here so that it's the same when Youtube API looks for it // Set frame ID here so that it's the same when Youtube API looks for it
// this.frameId = `youtube-bg-${this._uid}` // this.frameId = `youtube-bg-${this._uid}`
this.initializePlayer() this.detectAutoplay()
.then( ({ willAutoplay }) => {
// If we're allowed to autoplay
// then start loading the player
if ( willAutoplay === true ) {
this.startPlayerLoad()
}
})
}, },
methods: { methods: {
scrollRow ( timestamp ) { scrollRow ( timestamp ) {
@ -166,21 +243,97 @@ export default {
timestampsScroller.scroll({ left: newScrollPosition, behavior: 'smooth' }) timestampsScroller.scroll({ left: newScrollPosition, behavior: 'smooth' })
}, },
seekTo (timestampInSeconds) {
async detectAutoplay () {
if ( !process.client ) return { willAutoplay: false }
const { default: canAutoPlay } = await import('can-autoplay')
const willAutoplay = await canAutoPlay.video()
// const willAutoplayMuted = await canAutoPlay.video({ muted: true, inline: true })
return {
willAutoplay: willAutoplay.result
}
},
async seekTo (timestampInSeconds) {
if (this.playerLoaded === false) {
await this.startPlayerLoad()
}
this.player.seekTo(timestampInSeconds) this.player.seekTo(timestampInSeconds)
}, },
// async playVideo() {
// if (this.playerLoaded === false) {
// await this.startPlayerLoad()
// }
// this.$nextTick(() => {
// // console.log('this.player', JSON.stringify(this.player))
// this.player.playVideo()
// })
// },
addPrefetch(kind, url, as) {
// console.log('prefetching', url)
const linkEl = document.createElement('link')
linkEl.rel = kind
linkEl.href = url
if (as) {
linkEl.as = as;
}
document.head.append(linkEl)
},
warmConnections() {
if (this.preconnected) return
// The iframe document and most of its subresources come right off youtube.com
this.addPrefetch('preconnect', 'https://www.youtube-nocookie.com')
// The botguard script is fetched off from google.com
this.addPrefetch('preconnect', 'https://www.google.com')
// Not certain if these ad related domains are in the critical path. Could verify with domain-specific throttling.
this.addPrefetch('preconnect', 'https://googleads.g.doubleclick.net')
this.addPrefetch('preconnect', 'https://static.doubleclick.net')
this.preconnected = true
},
async startPlayerLoad () {
this.playerLoaded = true
await this.initializePlayer()
// this.$nextTick(() => {
// this.initializePlayer()
// })
},
async initializePlayer () { async initializePlayer () {
// console.log('Youtube Embed API Ready') // console.log('Youtube Embed API Ready')
// Clear player // Clear player
this.player = null this.player = null
// Clear tprogession interval // Clear progession interval
clearInterval(this.progressInterval) clearInterval(this.progressInterval)
// If there are no timestamps // If there are no timestamps
// then stop // then stop
if (!this.hasTimestamps) return if (!this.hasTimestamps) {
this.playerLoaded = true
return
}
if (typeof YT === 'undefined') { if (typeof YT === 'undefined') {
await this.initializeApi() await this.initializeApi()
@ -204,18 +357,30 @@ export default {
// console.log('frame', this.$refs['frame']) // console.log('frame', this.$refs['frame'])
// console.log('frame id', this.$refs['frame'].id) // console.log('frame id', this.$refs['frame'].id)
this.player = new YT.Player(this.$refs['frame'].id, { const onReady = () => new Promise( resolve => {
events: {
'onReady': this.onPlayerReady,
'onStateChange': event => {
// console.log('state changed', event)
const stateHandler = stateHandlers[String(event.data)] this.player = new YT.Player(this.$refs['frame'].id, {
// console.log('stateHandler', stateHandler) events: {
stateHandler(event) 'onReady': readyEvent => {
this.onPlayerReady( readyEvent )
resolve( readyEvent )
},
'onStateChange': event => {
// console.log('state changed', event)
const stateHandler = stateHandlers[String(event.data)]
// console.log('stateHandler', stateHandler)
stateHandler(event)
}
} }
} })
}) })
await onReady()
// console.log('Youtube Player API ready', JSON.stringify(this.player))
}, },
initializeApi () { initializeApi () {
return new Promise( resolve => { return new Promise( resolve => {
@ -257,7 +422,7 @@ export default {
clearInterval(this.progressInterval) clearInterval(this.progressInterval)
}, },
onPlayerReady (event) { onPlayerReady (event) {
console.log('Player is ready', this.player) console.log('Player is ready', event, this.player )
} }
} }
} }

11
package-lock.json generated
View file

@ -13,6 +13,7 @@
"@open-wc/webpack-import-meta-loader": "^0.4.7", "@open-wc/webpack-import-meta-loader": "^0.4.7",
"@zip.js/zip.js": "^2.2.6", "@zip.js/zip.js": "^2.2.6",
"axios": "^0.21.0", "axios": "^0.21.0",
"can-autoplay": "^3.0.0",
"chance": "^1.1.7", "chance": "^1.1.7",
"cross-env": "^5.2.0", "cross-env": "^5.2.0",
"jsdom": "^16.4.0", "jsdom": "^16.4.0",
@ -4733,6 +4734,11 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/can-autoplay": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/can-autoplay/-/can-autoplay-3.0.0.tgz",
"integrity": "sha512-qQXGGYPWgF8nPjEt305o3TJ/BkN15l6/wG+VU4N93YYXD3OtYkBBx+l5un7ihIk2UU1OLytAVJjW7ZR39j/CAQ=="
},
"node_modules/caniuse-api": { "node_modules/caniuse-api": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-3.0.0.tgz", "resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-3.0.0.tgz",
@ -29125,6 +29131,11 @@
} }
} }
}, },
"can-autoplay": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/can-autoplay/-/can-autoplay-3.0.0.tgz",
"integrity": "sha512-qQXGGYPWgF8nPjEt305o3TJ/BkN15l6/wG+VU4N93YYXD3OtYkBBx+l5un7ihIk2UU1OLytAVJjW7ZR39j/CAQ=="
},
"caniuse-api": { "caniuse-api": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-3.0.0.tgz", "resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-3.0.0.tgz",

View file

@ -26,6 +26,7 @@
"@open-wc/webpack-import-meta-loader": "^0.4.7", "@open-wc/webpack-import-meta-loader": "^0.4.7",
"@zip.js/zip.js": "^2.2.6", "@zip.js/zip.js": "^2.2.6",
"axios": "^0.21.0", "axios": "^0.21.0",
"can-autoplay": "^3.0.0",
"chance": "^1.1.7", "chance": "^1.1.7",
"cross-env": "^5.2.0", "cross-env": "^5.2.0",
"jsdom": "^16.4.0", "jsdom": "^16.4.0",

View file

@ -107,33 +107,35 @@ export default {
VideoPlayer, VideoPlayer,
ChannelCredit ChannelCredit
}, },
asyncData ({ params: { slug }, payload: { app, allVideos, submitVideoCard } }) { async asyncData ( data ) {
// const { allVideoAppsList } = await import('~/helpers/get-list.js') const {
// // const { default: videoList } = await import('~/static/video-list.json') params: { slug },
route
} = data
// const { videosRelatedToApp } = await import('~/helpers/related.js') let {
payload
} = data
// const app = allVideoAppsList.find(app => (app.slug === slug))
// const submitVideoCard = {
// endpoint: `https://docs.google.com/forms/d/e/1FAIpQLSeEVGM9vE7VcfLMy6fJkfU70X2VZ60rHDyhDQLtnAN4nso0WA/viewform?usp=pp_url&entry.1018125313=${app.name}`
// }
// // const featuredApps = [] // Manually get payload as fallback
if ( payload === undefined ) {
// Read back the JSON we just wrote to ensure it exists
const { default: savedList } = await import('~/static/nuxt-endpoints.json')
// const relatedVideos = videosRelatedToApp( app ).map(video => { const endpoint = savedList.find( resource => {
// // console.log('video', video) return resource.route === route.path
// return { } )
// ...video,
// // endpoint: `#${video.id}` payload = endpoint.payload
// } }
// })
return { return {
app, app: payload.app,
allVideos, allVideos: payload.allVideos,
submitVideoCard submitVideoCard: payload.submitVideoCard
} }
}, },
data: function () { data: function () {