From e6f8dd1d9944d9c4df5dce2cb15967ddcd001fb4 Mon Sep 17 00:00:00 2001 From: Vincent Boutour Date: Sun, 31 Jul 2022 18:06:35 +0200 Subject: [PATCH] feat(webp): Making webp works for story mode Signed-off-by: Vincent Boutour --- cmd/fibr/templates/async-image.html | 11 ++++++--- cmd/fibr/templates/story.html | 35 ++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/cmd/fibr/templates/async-image.html b/cmd/fibr/templates/async-image.html index da3e5041..6a07f744 100644 --- a/cmd/fibr/templates/async-image.html +++ b/cmd/fibr/templates/async-image.html @@ -137,14 +137,19 @@ try { await isWebPCompatible(); - window.dispatchEvent(new Event('thumbnail-done')); } catch (e) { - resolveScript( + await resolveScript( 'https://unpkg.com/webp-hero@0.0.2/dist-cjs/webp-hero.bundle.js', 'sha512-DA6h9H5Sqn55/uVn4JI4aSPFnAWoCQYYDXUnvjOAMNVx11///hX4QaFbQt5yWsrIm9hSI5fLJYfRWt3KXneSXQ==', 'anonymous', - ).then(() => new webpHero.WebpMachine().polyfillDocument()); + ); + + const webpMachine = new webpHero.WebpMachine(); + webpMachine.polyfillDocument(); + webpMachine.clearCache(); } + + window.dispatchEvent(new Event('thumbnail-done')); }, false, ); diff --git a/cmd/fibr/templates/story.html b/cmd/fibr/templates/story.html index d80caa2c..d5c7ab01 100644 --- a/cmd/fibr/templates/story.html +++ b/cmd/fibr/templates/story.html @@ -238,17 +238,30 @@ }); window.addEventListener('thumbnail-done', () => { - const lazyImageObserver = new IntersectionObserver((entries, observer) => { - entries.forEach((entry) => { - if (!entry.isIntersecting) { - return; - } - - const lazyImage = entry.target; - lazyImage.src = lazyImage.dataset.src; - lazyImageObserver.unobserve(lazyImage); - }); - }); + const lazyImageObserver = new IntersectionObserver( + async (entries, observer) => { + entries.forEach(async (entry) => { + if (!entry.isIntersecting) { + return; + } + + const lazyImage = entry.target; + if (window.webpHero) { + const content = await fetch(lazyImage.dataset.src, { + credentials: 'same-origin', + }).arrayBuffer(); + + const webpMachine = new webpHero.WebpMachine(); + lazyImage.src = await webpMachine.decode(new Uint8Array(content)); + webpMachine.clearCache(); + } else { + lazyImage.src = lazyImage.dataset.src; + } + + lazyImageObserver.unobserve(lazyImage); + }); + }, + ); document .querySelectorAll('img.thumbnail')