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

embed block #51

Merged
merged 4 commits into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ scripts/jquery-1.11.2.min.js
scripts/jquery.colorbox-min.js
scripts/main-scripts.js
scripts/gcse.js
scripts/v2.js
blocks/embed/lite-yt-embed/lite-yt-embed.js
scripts/v2.js
49 changes: 49 additions & 0 deletions blocks/embed/embed.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 2021 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
.embed {
display: flex;
margin: 0 auto 2rem;
padding: 0;
flex-direction: column;
align-items: stretch;
max-width: 100%;
}

.embed > div,
.embed blockquote,
.embed iframe {
flex: 1;
}

.embed iframe {
border: 1px solid var(--text-color);
border-radius: .5rem;
}

.embed img {
max-width: 100%;
}

.embed.tiktok lite-tiktok {
margin: 0 auto;
width: 518px;
height: 738px;
}

.embed.instagram {
width: 325px;
min-height: 739px;
}

.embed.instagram > div {
display: flex;
}
172 changes: 172 additions & 0 deletions blocks/embed/embed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { loadCSS, loadScript } from '../../scripts/aem.js';

const FALLBACK_PUBLICATION_DATE = '2013-07-18'; // go-live date for the Franklin site, but could be any value

const getDefaultEmbed = (url) => `<iframe src="${url.href}" allowfullscreen allow="encrypted-media" title="Content from ${url.hostname}" loading="lazy"></iframe>`;

const embedYoutubeFacade = async (url) => {
loadCSS('/blocks/embed/lite-yt-embed/lite-yt-embed.css');
loadScript('/blocks/embed/lite-yt-embed/lite-yt-embed.js');

const usp = new URLSearchParams(url.search);
let videoId = usp.get('v');
if (url.origin.includes('youtu.be')) {
videoId = url.pathname.substring(1);
} else {
videoId = url.pathname.split('/').pop();
}
const wrapper = document.createElement('div');
wrapper.setAttribute('itemscope', '');
wrapper.setAttribute('itemtype', 'https://schema.org/VideoObject');
const litePlayer = document.createElement('lite-youtube');
litePlayer.setAttribute('videoid', videoId);
wrapper.append(litePlayer);

try {
const response = await fetch(`https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=${videoId}`);
const json = await response.json();
wrapper.innerHTML = `
<meta itemprop="name" content="${json.title}"/>
<meta itemprop="uploadDate" content="${document.head.querySelector('[name="publication-date"]')?.content || FALLBACK_PUBLICATION_DATE}"/>
<link itemprop="embedUrl" href="https://www.youtube.com/embed/${videoId}"/>
<link itemprop="thumbnailUrl" href="${json.thumbnail_url}"/>

${wrapper.innerHTML}
`;
} catch (err) {
// Nothing to do, metadata just won't be added to the video
}
return wrapper.outerHTML;
};

const embedInstagram = (url) => {
const endingSlash = url.pathname.endsWith('/') ? '' : '/';
const location = window.location.href.endsWith('.html') ? window.location.href : `${window.location.href}.html`;
const src = `${url.origin}${url.pathname}${endingSlash}embed/captioned/?rd=${window.encodeURIComponent(location)}`;
const embedHTML = `
<div itemscope itemtype="https://schema.org/SocialMediaPosting">
<link itemprop="url" href="${url.origin}${url.pathname}${endingSlash}embed/captioned/"/>
<iframe src="${src}" allowfullscreen allowtransparency scrolling="no" frameborder="0" loading="lazy"></iframe>
</div>
`;
return embedHTML;
};

const embedTwitter = (url) => {
loadScript('https://platform.twitter.com/widgets.js');
const embedHTML = `
<blockquote itemscope itemtype="https://schema.org/SocialMediaPosting">
<a itemprop="url" href="${url}"></a>
</blockquote>
`;
return embedHTML;
};

const embedTiktokFacade = async (url) => {
loadScript('/blocks/embed/lite-tiktok/lite-tiktok.js', () => {}, { async: true, type: 'module' });
const videoId = url.pathname.split('/').pop();
try {
const request = await fetch(`https://www.tiktok.com/oembed?url=https://www.tiktok.com/video/${videoId}`);
const json = await request.json();
return `
<div itemscope itemtype="https://schema.org/VideoObject">
<meta itemprop="name" content="${json.title}"/>
<meta itemprop="uploadDate" content="${document.head.querySelector('[name="publication-date"]')?.content || FALLBACK_PUBLICATION_DATE}"/>
<link itemprop="thumbnailUrl" href="${json.thumbnail_url}"/>
<link itemprop="embedUrl" href="https://www.tiktok.com/video/${videoId}"/>
<lite-tiktok videoid="${videoId}"></lite-tiktok>
</div>
`;
} catch (err) {
return `
<div itemscope itemtype="https://schema.org/VideoObject">
<link itemprop="embedUrl" href="https://www.tiktok.com/video/${videoId}"/>
<lite-tiktok videoid="${videoId}"></lite-tiktok>
</div>
`;
}
};

const EMBEDS_CONFIG = {
instagram: embedInstagram,
tiktok: embedTiktokFacade,
twitter: embedTwitter,
youtube: embedYoutubeFacade,
};

function getPlatform(url) {
const [service] = url.hostname.split('.').slice(-2, -1);
if (service === 'youtu') {
return 'youtube';
}
return service;
}

const loadEmbed = async (block, service, url) => {
block.classList.toggle('skeleton', true);

const embed = EMBEDS_CONFIG[service];
if (!embed) {
block.classList.toggle('generic', true);
block.innerHTML = getDefaultEmbed(url);
return;
}

try {
block.classList.toggle(service, true);
try {
block.innerHTML = await embed(url);
} catch (err) {
block.style.display = 'none';
} finally {
block.classList.toggle('skeleton', false);
}
} catch (err) {
block.style.maxHeight = '0px';
}
};

// Listen for messages from instagram embeds to update the embed height.
window.addEventListener('message', (ev) => {
const iframe = [...document.querySelectorAll('iframe')].find((i) => i.contentWindow === ev.source);
if (!iframe) {
return;
}
let data;
try {
data = typeof ev.data === 'string' ? JSON.parse(ev.data) : ev.data;
} catch (e) {
// Nothing to do, the message isn't the one we are looking for
return;
}

if (data.type !== 'MEASURE') {
return;
}

iframe.closest('.block').style.height = `${data.details.height}px`;
});

/**
* @param {HTMLDivElement} block
*/
export default function decorate(block) {
const url = new URL(block.querySelector('a').href.replace(/%5C%5C_/, '_'));

block.textContent = '';
const service = getPlatform(url);
// Both Youtube and TikTok use an optimized lib that already leverages the intersection observer
if (service !== 'tiktok' && service !== 'youtube') {
const observer = new IntersectionObserver((entries) => {
if (!entries.some((e) => e.isIntersecting)) {
return;
}

loadEmbed(block, service, url);
observer.unobserve(block);
});
observer.observe(block);
} else {
loadEmbed(block, service, url);
}
}
86 changes: 86 additions & 0 deletions blocks/embed/lite-yt-embed/lite-yt-embed.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
lite-youtube {
background-color: #000;
position: relative;
display: block;
contain: content;
background-position: center center;
background-size: cover;
cursor: pointer;
max-width: 720px;
}

/* gradient */
lite-youtube::before {
content: '';
display: block;
position: absolute;
top: 0;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAADGCAYAAAAT+OqFAAAAdklEQVQoz42QQQ7AIAgEF/T/D+kbq/RWAlnQyyazA4aoAB4FsBSA/bFjuF1EOL7VbrIrBuusmrt4ZZORfb6ehbWdnRHEIiITaEUKa5EJqUakRSaEYBJSCY2dEstQY7AuxahwXFrvZmWl2rh4JZ07z9dLtesfNj5q0FU3A5ObbwAAAABJRU5ErkJggg==);
background-position: top;
background-repeat: repeat-x;
height: 60px;
padding-bottom: 50px;
width: 100%;
transition: all 0.2s cubic-bezier(0, 0, 0.2, 1);
}

/* responsive iframe with a 16:9 aspect ratio
thanks https://css-tricks.com/responsive-iframes/
*/
lite-youtube::after {
content: "";
display: block;
padding-bottom: calc(100% / (16 / 9));
}
lite-youtube > iframe {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
border: 0;
}

/* play button */
lite-youtube > .lty-playbtn {
display: block;
width: 68px;
height: 48px;
position: absolute;
cursor: pointer;
transform: translate3d(-50%, -50%, 0);
top: 50%;
left: 50%;
z-index: 1;
background-color: transparent;
/* YT's actual play button svg */
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 68 48"><path d="M66.52 7.74c-.78-2.93-2.49-5.41-5.42-6.19C55.79.13 34 0 34 0S12.21.13 6.9 1.55c-2.93.78-4.63 3.26-5.42 6.19C.06 13.05 0 24 0 24s.06 10.95 1.48 16.26c.78 2.93 2.49 5.41 5.42 6.19C12.21 47.87 34 48 34 48s21.79-.13 27.1-1.55c2.93-.78 4.64-3.26 5.42-6.19C67.94 34.95 68 24 68 24s-.06-10.95-1.48-16.26z" fill="red"/><path d="M45 24 27 14v20" fill="white"/></svg>');
filter: grayscale(100%);
transition: filter .1s cubic-bezier(0, 0, 0.2, 1);
border: none;
}

lite-youtube:hover > .lty-playbtn,
lite-youtube .lty-playbtn:focus {
filter: none;
}

/* Post-click styles */
lite-youtube.lyt-activated {
cursor: unset;
}
lite-youtube.lyt-activated::before,
lite-youtube.lyt-activated > .lty-playbtn {
opacity: 0;
pointer-events: none;
}

.lyt-visually-hidden {
clip: rect(0 0 0 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
Loading