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

AccessKit Disable GIFs: Use content replacement #1708

Draft
wants to merge 19 commits into
base: master
Choose a base branch
from
Draft
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
120 changes: 76 additions & 44 deletions src/features/accesskit/disable_gifs.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { keyToCss } from '../../utils/css_map.js';
import { dom } from '../../utils/dom.js';
import { buildStyle, postSelector } from '../../utils/interface.js';

const canvasClass = 'xkit-paused-gif-placeholder';
const pausedContentVar = '--xkit-paused-gif-content';
const labelClass = 'xkit-paused-gif-label';
const containerClass = 'xkit-paused-gif-container';
const backgroundGifClass = 'xkit-paused-background-gif';
const pausedBackgroundImageVar = '--xkit-paused-gif-background-image';

const hovered = `:is(:hover > *, .${containerClass}:hover *, a:hover + div *)`;

export const styleElement = buildStyle(`
.${labelClass} {
Expand All @@ -33,27 +35,20 @@ export const styleElement = buildStyle(`
font-size: 0.6rem;
}

.${canvasClass} {
position: absolute;
visibility: visible;

background-color: rgb(var(--white));
${keyToCss('background')} > .${labelClass} {
display: none;
}

*:hover > .${canvasClass},
*:hover > .${labelClass},
.${containerClass}:hover .${canvasClass},
.${containerClass}:hover .${labelClass} {
.${labelClass}${hovered} {
display: none;
}

.${backgroundGifClass}:not(:hover) {
background-image: none !important;
background-color: rgb(var(--secondary-accent));
img[style*="${pausedContentVar}"]:not(${hovered}) {
content: var(${pausedContentVar});
}

.${backgroundGifClass}:not(:hover) > div {
color: rgb(var(--black));
[style*="${pausedBackgroundImageVar}"]:not(${hovered}) {
background-image: var(${pausedBackgroundImageVar}) !important;
}
`);

Expand All @@ -68,32 +63,24 @@ const addLabel = (element, inside = false) => {
}
};

const pauseGif = function (gifElement) {
const image = new Image();
image.src = gifElement.currentSrc;
image.onload = () => {
if (gifElement.parentNode && gifElement.parentNode.querySelector(`.${canvasClass}`) === null) {
const canvas = document.createElement('canvas');
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.className = gifElement.className;
canvas.classList.add(canvasClass);
canvas.getContext('2d').drawImage(image, 0, 0);
gifElement.parentNode.append(canvas);
addLabel(gifElement);
}
};
const pauseGif = async function (gifElement) {
gifElement.style.setProperty(pausedContentVar, `url(${await createPausedUrl(gifElement.currentSrc)})`);
addLabel(gifElement);
};

const processGifs = function (gifElements) {
gifElements.forEach(gifElement => {
if (gifElement.closest('.block-editor-writing-flow')) return;
const pausedGifElements = [
...gifElement.parentNode.querySelectorAll(`.${canvasClass}`),
...gifElement.parentNode.querySelectorAll(`.${labelClass}`)
];
if (pausedGifElements.length) {
gifElement.after(...pausedGifElements);
const existingLabelElements = gifElement.parentNode.querySelectorAll(`.${labelClass}`);
if (existingLabelElements.length) {
gifElement.after(...existingLabelElements);
return;
}

const posterElement = gifElement.parentElement.querySelector(keyToCss('poster'));
if (posterElement?.currentSrc) {
gifElement.style.setProperty(pausedContentVar, `url(${posterElement.currentSrc})`);
addLabel(gifElement);
return;
}

Expand All @@ -105,10 +92,43 @@ const processGifs = function (gifElements) {
});
};

const sourceUrlRegex = /(?<=url\(["'])[^)]*?\.gifv?(?=["']\))/g;

const pausedUrlCache = {};
const createPausedUrl = (sourceUrl) => {
pausedUrlCache[sourceUrl] ??= new Promise(resolve => {
fetch(sourceUrl, { headers: { Accept: 'image/webp,*/*' } })
.then(response => response.blob())
.then(blob => createImageBitmap(blob))
.then(imageBitmap => {
const canvas = document.createElement('canvas');
canvas.width = imageBitmap.width;
canvas.height = imageBitmap.height;
canvas.getContext('2d').drawImage(imageBitmap, 0, 0);
canvas.toBlob(blob =>
resolve(URL.createObjectURL(blob))
);
});
});
return pausedUrlCache[sourceUrl];
};

const processBackgroundGifs = function (gifBackgroundElements) {
gifBackgroundElements.forEach(gifBackgroundElement => {
gifBackgroundElement.classList.add(backgroundGifClass);
addLabel(gifBackgroundElement, true);
gifBackgroundElements.forEach(async gifBackgroundElement => {
// "tumblr tv" video cards may be initially rendered with the wrong background
if (!gifBackgroundElement.matches('[style*=".gif"]')) await new Promise(requestAnimationFrame);
if (!gifBackgroundElement.matches('[style*=".gif"]')) return;

const sourceValue = gifBackgroundElement.style.backgroundImage;
const sourceUrl = sourceValue.match(sourceUrlRegex)?.[0];

if (sourceUrl) {
gifBackgroundElement.style.setProperty(
pausedBackgroundImageVar,
sourceValue.replaceAll(sourceUrlRegex, await createPausedUrl(sourceUrl))
);
addLabel(gifBackgroundElement, true);
}
});
};

Expand All @@ -128,17 +148,25 @@ const processRows = function (rowsElements) {
});
};

const processRecommendedBlogCards = cards =>
cards.forEach(card => card.classList.add(containerClass));

export const main = async function () {
const gifImage = `
:is(figure, ${keyToCss('tagImage', 'takeoverBanner')}) img[srcset*=".gif"]:not(${keyToCss('poster')})
:is(figure, main.labs, ${keyToCss('tagImage', 'takeoverBanner', 'videoHubsFeatured', 'headerBanner', 'headerImage', 'typeaheadRow', 'linkCard')}) img:is([srcset*=".gif"], [src*=".gif"]):not(${keyToCss('poster')})
`;
pageModifications.register(gifImage, processGifs);

const gifBackgroundImage = `
${keyToCss('communityHeaderImage', 'bannerImage')}[style*=".gif"]
${keyToCss('communityHeaderImage', 'communityCategoryImage', 'bannerImage', 'videoHubCardWrapper')}
`;
pageModifications.register(gifBackgroundImage, processBackgroundGifs);

pageModifications.register(
`${keyToCss('listTimelineObject')} ${keyToCss('carouselWrapper')} ${keyToCss('postCard')}`,
processRecommendedBlogCards
);

pageModifications.register(
`:is(${postSelector}, ${keyToCss('blockEditorContainer')}) ${keyToCss('rows')}`,
processRows
Expand All @@ -149,11 +177,15 @@ export const clean = async function () {
pageModifications.unregister(processGifs);
pageModifications.unregister(processBackgroundGifs);
pageModifications.unregister(processRows);
pageModifications.unregister(processRecommendedBlogCards);

[...document.querySelectorAll(`.${containerClass}`)].forEach(wrapper =>
wrapper.replaceWith(...wrapper.children)
);

$(`.${canvasClass}, .${labelClass}`).remove();
$(`.${backgroundGifClass}`).removeClass(backgroundGifClass);
$(`.${labelClass}`).remove();
[...document.querySelectorAll(`img[style*="${pausedContentVar}"]`)]
.forEach(element => element.style.removeProperty(pausedContentVar));
[...document.querySelectorAll(`img[style*="${pausedBackgroundImageVar}"]`)]
.forEach(element => element.style.removeProperty(pausedBackgroundImageVar));
};