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

feature: Embed Block #111

Merged
merged 14 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
2 changes: 1 addition & 1 deletion datocms-environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
* @see docs/getting-started.md on how to use this file
* @see docs/decision-log/2023-10-24-datocms-env-file.md on why file is preferred over env vars
*/
export const datocmsEnvironment = 'redirect-rules';
export const datocmsEnvironment = 'embed-block';
export const datocmsBuildTriggerId = '30535';
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@
"astro": "^4.0.7",
"datocms-listen": "^0.1.15",
"datocms-structured-text-utils": "^2.0.4",
"get-video-id": "^3.6.5",
"globby": "^13.2.2",
"html-validate": "^8.7.4",
"jiti": "^1.20.0",
"nanostores": "^0.9.5",
"oembed-providers": "^1.0.20230906",
"promise-all-props": "^3.0.0",
"rosetta": "^1.1.0",
"typescript": "^5.2.2"
Expand Down
2 changes: 2 additions & 0 deletions src/assets/icons/twitter.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions src/blocks/Blocks.astro
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
import type { AnyBlock } from './Blocks';
import EmbedBlock from './EmbedBlock/EmbedBlock.astro';
import ImageBlock from './ImageBlock/ImageBlock.astro';
import PagePartialBlock from './PagePartialBlock/PagePartialBlock.astro';
import TableBlock from './TableBlock/TableBlock.astro';
Expand All @@ -8,6 +9,7 @@ import TextImageBlock from './TextImageBlock/TextImageBlock.astro';
import VideoEmbedBlock from './VideoEmbedBlock/VideoEmbedBlock.astro';

const blocksByTypename = {
EmbedBlockRecord: EmbedBlock,
ImageBlockRecord: ImageBlock,
PagePartialBlockRecord: PagePartialBlock,
TableBlockRecord: TableBlock,
Expand Down
2 changes: 2 additions & 0 deletions src/blocks/Blocks.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
EmbedBlockFragment,
ImageBlockFragment,
PagePartialBlockFragment,
TableBlockFragment,
Expand All @@ -8,6 +9,7 @@ import {
} from '@lib/types/datocms';

export type AnyBlock =
| EmbedBlockFragment
| ImageBlockFragment
| PagePartialBlockFragment
| TableBlockFragment
Expand Down
58 changes: 58 additions & 0 deletions src/blocks/EmbedBlock/EmbedBlock.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
import type { EmbedBlockFragment } from '@lib/types/datocms';
import { fetchPageTitle, getOEmbedProvider } from './index';
import type { OEmbedAny } from './index';
import DefaultEmbed from './embeds/Default.astro';
import TwitterEmbed from './embeds/Twitter.astro';
import VimeoEmbed from './embeds/Vimeo.astro';
import YouTubeEmbed from './embeds/YouTube.astro';

interface Props {
block: EmbedBlockFragment;
}
const { block } = Astro.props;
const { data, url }: { data: OEmbedAny; url: string } = block;
const fallbackText = data ? null : await fetchPageTitle(block.url);
const providerName = (data || getOEmbedProvider(url))?.provider_name;
const isProvider = (name: string) =>
providerName?.toLowerCase() === name.toLowerCase();
---

<div class='embed-block'>
{
data && data.html ? (
isProvider('Twitter') ? (
<TwitterEmbed {data} {url} />
) : isProvider('Vimeo') ? (
<VimeoEmbed {data} {url} />
) : isProvider('YouTube') ? (
<YouTubeEmbed {data} {url} />
) : (
<DefaultEmbed {data} {url} />
)
) : (
<a
class='embed-fallback'
href={block.url}
target='_blank'
rel='noopener noreferrer'
>
[ unable to load from {providerName} ]<br />
jbmoelker marked this conversation as resolved.
Show resolved Hide resolved
{fallbackText ? fallbackText : `${providerName}: ${block.url}`}
</a>
)
}
</div>

<style>
.embed-block {
margin-block: 20px;
}
.embed-fallback {
display: block;
padding: 10px;
background: #eee;
border: 1px solid black;
word-break: break-word;
}
</style>
5 changes: 5 additions & 0 deletions src/blocks/EmbedBlock/EmbedBlock.fragment.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fragment EmbedBlock on EmbedBlockRecord {
id
url
data
}
16 changes: 16 additions & 0 deletions src/blocks/EmbedBlock/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Embed Block

**Renders external content based on the block's OEmbed data.**

## Features

- Supports [~300 content providers](https://oembed.com/providers.json) (like Twitter, Flickr, YouTube, etc) using the [OEmbed](https://oembed.com/) protocol.
- Renders a noscript embed version which is dynamically enhanced.
- Lazy loads embed scripts and iframes to improve performance.
- Provides a mechanism to define custom renderer per provider.
- If OEmbed data is unavailable, a link is displayed with the page title of the given URL.

## Relevant links

- Embed Block data is preloaded in the CMS using the [DatoCMS OEmbed Plugin](https://github.com/voorhoede/datocms-plugin-oembed/).

77 changes: 77 additions & 0 deletions src/blocks/EmbedBlock/embeds/Default.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
import { extractScripts, isIframeHtml, sanatizeHtml } from '../index';

const { data, url, class: classList, ...props } = Astro.props;
const { noscriptHtml, scripts } = extractScripts(data.html);
const html = sanatizeHtml(noscriptHtml);
const placeholderText = `${data.title} (${data.provider_name})`;
const aspectRatio = data.width && data.height ? data.width / data.height : null;
const maxWidth = data.width ? `${data.width}px` : '100%';
---

<default-embed
data-enhanced="false"
data-provider={data.provider_name}
class:list={[ classList, { 'with-iframe': isIframeHtml(html) } ]}
{ ...props }
>
<slot name="html">
{ isIframeHtml(html)
? (<>
<a href={ url } rel="noreferrer noopener" target="_blank" class="embed-placeholder">
{ data.thumbnail_url
? <img alt={ placeholderText } src={ data.thumbnail_url } loading="lazy" />
: <span>{ data.title } ({ data.pro})</span>
}
</a>
<template set:html={html}></template>
</>)
: <div set:html={html} />
}
</slot>
<slot name="noscript">
{ scripts.map(({ src, ...attributes }) => (
<script data-src={ src } {...attributes} />
)) }
</slot>
</default-embed>

<script src="./Default.client.ts"></script>

<style define:vars={{ aspectRatio, maxWidth }}>
default-embed {
display: block;
aspect-ratio: var(--aspectRatio);
max-width: var(--maxWidth);
overflow: hidden;
background-color: #ebebeb;
}

.embed-placeholder img {
display: block;
width: 100%;
height: 100% !important;
object-fit: cover;
object-position: center;
}
default-embed[data-enhanced="false"] .embed-placeholder {
display: block;
width: 100%;
height: 100%;
}
default-embed[data-enhanced="true"] .embed-placeholder {
display: none;
}

/* only force sizing on embeds with iframe in noscript html */
/* as scripts (like Twitter widget) may load more than just the iframe */
default-embed.with-iframe :global(iframe) {
aspect-ratio: var(--aspectRatio);
max-width: 100% !important;
height: auto !important;
}
default-embed :global(img) {
max-width: 100% !important;
height: auto !important;
}
</style>
67 changes: 67 additions & 0 deletions src/blocks/EmbedBlock/embeds/Default.client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const enhanceIntersectedEmbeds = (entries: IntersectionObserverEntry[]) => {
entries.forEach((entry) => {
if (entry.isIntersecting && entry.target instanceof DefaultEmbed) {
entry.target.enhance();
}
});
};

const observer = new IntersectionObserver(
enhanceIntersectedEmbeds,
{ rootMargin: '100px' }
);

class DefaultEmbed extends HTMLElement {
#isEnhanced = false;
#provider: string;
#template?: HTMLTemplateElement;
#scriptTags: HTMLScriptElement[] = [];

constructor() {
super();
this.#provider = this.dataset.provider || '';
this.#template = this.querySelector('template') || undefined;
this.#scriptTags = Array.from(this.querySelectorAll('script[data-src]'));
}

connectedCallback() {
observer.observe(this);
}

enhance() {
observer.unobserve(this);

if (this.#isEnhanced) {
return;
}
this.#isEnhanced = true;

if (!this.#template && this.#scriptTags.length === 0) {
return;
}

console.log(`Todo: only enhance after consent for "${this.#provider}". See https://github.com/voorhoede/head-start/issues/49`);

if (this.#template) {
const clone = this.#template.content.cloneNode(true);
this.appendChild(clone);
}

if (this.#scriptTags.length === 0) {
this.setAttribute('data-enhanced', 'true');
return;
}

const allScriptsLoaded = Promise.all(this.#scriptTags.map((script) => {
return new Promise((resolve) => script.addEventListener('load', resolve));
}));
allScriptsLoaded.then(() => {
this.setAttribute('data-enhanced', 'true');
});
this.#scriptTags.forEach((script) => {
script.src = script.dataset.src as string;
});
}
}

customElements.define('default-embed', DefaultEmbed);
48 changes: 48 additions & 0 deletions src/blocks/EmbedBlock/embeds/Twitter.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
import Icon from '@components/Icon';
import DefaultEmbed from './Default.astro';
import { extractScripts } from '../index';
import type { OEmbedRich } from '../index';

const data = Astro.props.data as OEmbedRich;
const url = Astro.props.url;
const { noscriptHtml } = extractScripts(data.html);
---

<DefaultEmbed { data } { url } class="twitter-embed">
<div slot="html">
<Icon name="twitter" aria-label={ data.provider_name } />
<div
set:html={noscriptHtml}
style={{
'aspect-ratio': data.width && data.height ? data.width / data.height : null,
'max-width': data.width ? `${data.width}px` : null,
}}
/>
</div>
</DefaultEmbed>

<style>
.twitter-embed {
display: block;
position: relative;
aspect-ratio: unset;
background-color: white;
overflow: auto;
}
.twitter-embed[data-enhanced="false"] {
border: 1px solid black;
border-radius: 5px;
}

.twitter-embed[data-enhanced="true"] [data-icon="twitter"] {
display: none;
}
.twitter-embed[data-enhanced="false"] [data-icon="twitter"] {
position: absolute;
top: 10px;
right: 10px;
width: 15px;
height: 15px;
}
</style>
Loading
Loading