feat(site): Add lucide merch ad fallback (#5299)

* feat(site): Show merch from merch.lucide.dev when Carbon Ads are blocked

When an adblocker stops Carbon (failed script request, no window._carbonads
after 3s, or the ad hidden by a cosmetic filter), the ad slot shows a merch
card instead of an empty box. Doc pages and the icons overlay get a 3:4
slider with bullets (10s, crossfade); the home page shows two products.

Products come from the Fourthwall Storefront API at build time
(prebuild:merch, FOURTHWALL_STOREFRONT_TOKEN), in USD, so the token never
reaches the browser. Without a token the card links to the store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G9u8FiGcimashQWZ7MEP1h

* refactor(site): Load merch with a VitePress data loader instead of a prebuild script

Moves the Fourthwall fetch into merch.data.ts, so the products come from
the same .data.ts pattern as the other build-time data. Drops the
prebuild:merch script and the gitignored merchData.json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G9u8FiGcimashQWZ7MEP1h

* Dynamic load merch component

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Eric Fennis
2026-11-26 10:32:25 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 4d55546d15
commit 7af21af580
6 changed files with 514 additions and 17 deletions
@@ -6,9 +6,13 @@ import TeamMemberCard, { TeamMember } from './TeamMemberCard.vue'
import teamData from '../../../data/teamData.json'
import HomeSponsorCard from './HomeSponsorCard.vue';
import VPDocAsideCarbonAds from 'vitepress/dist/client/theme-default/components/VPDocAsideCarbonAds.vue'
import { provide } from 'vue'
import { merchLayoutKey } from '../merch/merch'
const { theme } = useData()
// The wide ad card here shows two merch items side by side when Carbon is blocked.
provide(merchLayoutKey, 'pair')
</script>
<template>
@@ -5,14 +5,14 @@ import Button from '../base/Button.vue';
import VPDocAsideCarbonAds from 'vitepress/dist/client/theme-default/components/VPDocAsideCarbonAds.vue';
import { x } from '../../../data/iconNodes';
import Icon from '@lucide/vue/src/Icon';
import { computed, onMounted, ref } from 'vue';
import { computed } from 'vue';
const { theme } = useData();
const showAd = useSessionStorage('show-carbon-ads', true, {
initOnMounted: true,
});
const carbonLoaded = ref(true);
const shouldHideAd = computed(() => !showAd.value || !carbonLoaded.value);
// When an adblocker stops Carbon, the ad slot shows the merch card instead, so the overlay stays.
const shouldHideAd = computed(() => !showAd.value);
function hideAd() {
showAd.value = false;
@@ -21,14 +21,6 @@ function hideAd() {
defineProps<{
drawerOpen: boolean;
}>();
onMounted(() => {
setTimeout(() => {
if (window?._carbonads == null) {
carbonLoaded.value = false;
}
}, 5000);
});
</script>
<template>
@@ -0,0 +1,322 @@
<script setup lang="ts">
import { computed, inject, onBeforeUnmount, onMounted, ref } from 'vue';
import { usePreferredReducedMotion } from '@vueuse/core';
import { merchLayoutKey, shuffle, type MerchProduct } from './merch';
import { data } from './merch.data';
const { products: merchProducts, storeUrl: merchStoreUrl } = data;
const MAX_SLIDES = 5;
const SLIDE_INTERVAL = 10_000;
const layout = inject(merchLayoutKey, 'slider');
const reducedMotion = usePreferredReducedMotion();
// Server render and first client render use the build order, shuffled once mounted.
const products = ref<MerchProduct[]>(merchProducts.slice(0, MAX_SLIDES));
const current = ref(0);
const paused = ref(false);
const shown = computed(() => (layout === 'pair' ? products.value.slice(0, 2) : products.value));
let timer: ReturnType<typeof setInterval> | undefined;
function stop() {
clearInterval(timer);
timer = undefined;
}
function start() {
stop();
if (layout !== 'slider' || products.value.length < 2 || reducedMotion.value === 'reduce') return;
timer = setInterval(() => {
if (!paused.value) current.value = (current.value + 1) % products.value.length;
}, SLIDE_INTERVAL);
}
/** Picking a slide by hand stops the rotation, like the design. */
function pick(index: number) {
current.value = index;
stop();
}
/** Called by the ad slot on route change, the same moment Carbon refreshes its ad. */
function next() {
if (products.value.length > 1) current.value = (current.value + 1) % products.value.length;
}
defineExpose({ next });
onMounted(() => {
products.value = shuffle(merchProducts).slice(0, MAX_SLIDES);
start();
});
onBeforeUnmount(stop);
</script>
<template>
<div
class="merch-ad"
:class="`merch-ad--${layout}`"
@mouseenter="paused = true"
@mouseleave="paused = false"
@focusin="paused = true"
@focusout="paused = false"
>
<span class="merch-label">Support the project</span>
<a
v-if="shown.length === 0"
class="merch-store"
:href="merchStoreUrl"
target="_blank"
rel="noopener"
>
<span class="merch-name">Lucide merch</span>
<span class="merch-price">Shop merch.lucide.dev</span>
</a>
<div
v-else-if="layout === 'slider'"
class="merch-slides"
>
<a
v-for="(product, index) in shown"
:key="product.slug"
class="merch-item"
:class="{ active: index === current }"
:href="product.url"
:aria-hidden="index !== current"
:tabindex="index === current ? 0 : -1"
target="_blank"
rel="noopener"
>
<img
:src="product.image"
alt=""
width="184"
height="245"
:loading="index === 0 ? 'eager' : 'lazy'"
/>
<span class="merch-info">
<span class="merch-name">{{ product.name }}</span>
<span class="merch-price">{{ product.price }}</span>
</span>
</a>
</div>
<div
v-else
class="merch-pair"
>
<a
v-for="product in shown"
:key="product.slug"
class="merch-item"
:href="product.url"
target="_blank"
rel="noopener"
>
<img
:src="product.image"
alt=""
width="219"
height="292"
loading="lazy"
/>
<span class="merch-info">
<span class="merch-name">{{ product.name }}</span>
<span class="merch-price">{{ product.price }}</span>
</span>
</a>
</div>
<div
v-if="layout === 'slider' && shown.length > 1"
class="merch-dots"
>
<button
v-for="(product, index) in shown"
:key="product.slug"
type="button"
:aria-label="`Show ${product.name}`"
:aria-current="index === current"
@click="pick(index)"
>
<span :class="{ active: index === current }" />
</button>
</div>
</div>
</template>
<style scoped>
.merch-ad {
display: flex;
flex-direction: column;
gap: 12px;
box-sizing: border-box;
width: 100%;
padding: 20px 20px 16px;
border-radius: 12px;
border: 1px solid var(--vp-c-divider);
background-color: var(--vp-carbon-ads-bg-color);
text-align: left;
}
.merch-label {
font-size: 11px;
line-height: 14px;
font-weight: 500;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--vp-carbon-ads-poweredby-color);
}
.merch-slides {
position: relative;
width: 100%;
aspect-ratio: 3 / 4;
border-radius: 10px;
overflow: hidden;
background-color: var(--vp-c-bg-alt);
}
.merch-slides .merch-item {
position: absolute;
inset: 0;
opacity: 0;
pointer-events: none;
transition: opacity 800ms ease;
}
.merch-slides .merch-item.active {
opacity: 1;
pointer-events: auto;
}
.merch-pair {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.merch-pair .merch-item {
position: relative;
aspect-ratio: 3 / 4;
border-radius: 10px;
overflow: hidden;
background-color: var(--vp-c-bg-alt);
}
.merch-item {
display: block;
color: inherit;
text-decoration: none;
}
.merch-item img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 0;
transition: transform 0.4s ease;
}
.merch-item:hover img {
transform: scale(1.03);
}
.merch-info {
position: absolute;
left: 0;
right: 0;
bottom: 0;
display: flex;
flex-direction: column;
gap: 4px;
padding: 20px 14px 12px;
background: color-mix(in srgb, var(--vp-c-bg-alt, #161618), transparent 50%);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
mask-image: linear-gradient(to top, #000 calc(100% - 16px), #0000 100%);
-webkit-mask-image: linear-gradient(to top, #000 calc(100% - 16px), #0000 100%);
}
.merch-name {
font-size: 15px;
line-height: 20px;
font-weight: 600;
color: var(--vp-c-text-1);
}
.merch-price {
font-size: 12px;
line-height: 18px;
font-weight: 600;
color: var(--vp-c-brand-1);
}
.merch-store {
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 4px;
min-height: 160px;
padding: 14px;
border-radius: 10px;
background-color: var(--vp-c-bg-alt);
text-decoration: none;
}
.merch-dots {
display: flex;
justify-content: center;
align-items: center;
gap: 2px;
margin-bottom: -6px;
}
.merch-dots button {
display: flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
padding: 0;
border: 0;
background: transparent;
cursor: pointer;
}
.merch-dots span {
display: block;
width: 6px;
height: 6px;
border-radius: 3px;
background-color: var(--vp-c-gray-1);
transition:
width 300ms ease,
background-color 300ms ease;
}
.merch-dots span.active {
width: 16px;
background-color: var(--vp-c-text-1);
}
.merch-dots button:focus-visible {
outline: 2px solid var(--vp-c-brand-1);
outline-offset: -2px;
border-radius: 6px;
}
@media (prefers-reduced-motion: reduce) {
.merch-slides .merch-item,
.merch-item img,
.merch-dots span {
transition: none;
}
}
</style>
@@ -0,0 +1,125 @@
import { loadEnvFile } from 'node:process';
import type { MerchProduct } from './merch.ts';
/**
* Loads the products of the Lucide merch store (merch.lucide.dev, a Fourthwall shop) at build
* time, so the fallback card for blocked ads never needs the storefront token in the browser.
*
* Needs `FOURTHWALL_STOREFRONT_TOKEN`. Without it the list is empty and the card links to the
* store without a product.
*/
try {
// Load environment variables from docs/.env, if it exists.
loadEnvFile('.env');
} catch {
// No .env file, so rely on the environment as-is.
}
const STORE_URL = 'https://merch.lucide.dev';
const API_URL = 'https://storefront-api.fourthwall.com/v1/collections/all/products';
const CURRENCY = 'USD';
const UTM = 'utm_source=lucide.dev&utm_medium=merch-fallback';
interface FourthwallMoney {
value: number;
currency: string;
}
interface FourthwallProduct {
type?: 'PRODUCT' | 'BUNDLE';
name: string;
slug: string;
state?: { type: 'AVAILABLE' | 'SOLD_OUT' };
access?: { type: 'PUBLIC' | 'HIDDEN' | 'PRIVATE' | 'ARCHIVED' };
images?: { url: string; transformedUrl?: string }[];
variants?: { unitPrice?: FourthwallMoney; images?: { url: string; transformedUrl?: string }[] }[];
}
interface FourthwallPage {
results: FourthwallProduct[];
paging?: { hasNextPage?: boolean };
}
async function fetchAllProducts(token: string) {
const products: FourthwallProduct[] = [];
for (let page = 0; page < 10; page++) {
const params = new URLSearchParams({
storefront_token: token,
currency: CURRENCY,
page: String(page),
size: '50',
});
const response = await fetch(`${API_URL}?${params}`);
if (!response.ok) {
throw new Error(`Fourthwall responded with ${response.status} ${response.statusText}`);
}
const data = (await response.json()) as FourthwallPage;
products.push(...data.results);
if (!data.paging?.hasNextPage) break;
}
return products;
}
function toMerchProduct(product: FourthwallProduct): MerchProduct | null {
if (product.type === 'BUNDLE') return null;
if (product.state?.type !== 'AVAILABLE') return null;
if (product.access && product.access.type !== 'PUBLIC') return null;
const image = product.images?.[0] ?? product.variants?.find((v) => v.images?.length)?.images?.[0];
const prices = (product.variants ?? [])
.map((variant) => variant.unitPrice)
.filter((price): price is FourthwallMoney => price != null);
if (!image || prices.length === 0) return null;
const lowest = prices.reduce((min, price) => (price.value < min.value ? price : min));
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: lowest.currency,
});
const samePrice = prices.every((price) => price.value === lowest.value);
return {
name: product.name,
slug: product.slug,
url: `${STORE_URL}/products/${product.slug}?${UTM}`,
image: image.transformedUrl ?? image.url,
price: `${samePrice ? '' : 'From '}${formatter.format(lowest.value)}`,
};
}
export interface MerchData {
storeUrl: string;
products: MerchProduct[];
}
declare const data: MerchData;
export { data };
export default {
async load(): Promise<MerchData> {
const token = process.env.FOURTHWALL_STOREFRONT_TOKEN;
let products: MerchProduct[] = [];
if (!token) {
console.warn(
'FOURTHWALL_STOREFRONT_TOKEN is not set, the merch card links to the store only.',
);
} else {
try {
const results = await fetchAllProducts(token);
products = results.map(toMerchProduct).filter((product) => product != null);
} catch (error) {
console.warn(`Could not fetch merch, the merch card links to the store only. ${error}`);
}
}
return { storeUrl: `${STORE_URL}/?${UTM}`, products };
},
};
@@ -0,0 +1,26 @@
import type { InjectionKey } from 'vue';
export interface MerchProduct {
name: string;
slug: string;
url: string;
image: string;
/** Lowest variant price, already formatted, e.g. "From $24.00". */
price: string;
}
/**
* How the merch fallback lays itself out in an ad slot.
* `slider` fits the 224px aside and floating overlay, `pair` the wide card on the home page.
*/
export type MerchLayout = 'slider' | 'pair';
export const merchLayoutKey: InjectionKey<MerchLayout> = Symbol('merch-layout');
export function shuffle<T>(items: T[]): T[] {
const copy = [...items];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
@@ -1,8 +1,11 @@
<script setup lang="ts">
import type { DefaultTheme } from 'vitepress/theme'
import { ref, watch, onMounted } from 'vue'
import { ref, watch, onMounted, defineAsyncComponent } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import { useData } from 'vitepress/dist/client/theme-default/composables/data.js'
import type MerchAdComponent from '../merch/MerchAd.vue'
const MerchAd = defineAsyncComponent(() => import('../merch/MerchAd.vue'))
const { page } = useData()
const props = defineProps<{
@@ -13,7 +16,25 @@ const props = defineProps<{
const carbonOptions = props.carbonAds
const isAsideEnabled = useMediaQuery('(min-width: 80rem)')
const container = ref()
const container = ref<HTMLElement>()
const merchAd = ref<InstanceType<typeof MerchAdComponent>>()
/**
* `blocked` when an adblocker stopped Carbon: the script request failed, it never set
* `window._carbonads`, or a cosmetic filter hid the ad. The merch card then takes the slot.
*/
const carbonStatus = ref<'loading' | 'loaded' | 'blocked'>('loading')
const BLOCKED_TIMEOUT = 3000
function carbonAdVisible() {
const ad = container.value?.querySelector<HTMLElement>('#carbonads')
return (window as any)._carbonads != null && ad != null && ad.offsetHeight > 0
}
function checkCarbon(final: boolean) {
if (carbonAdVisible()) carbonStatus.value = 'loaded'
else if (final) carbonStatus.value = 'blocked'
}
let isInitialized = false
@@ -29,13 +50,19 @@ function init() {
s.id = '_carbonads_js'
s.src = `//cdn.carbonads.com/carbon.js?${params.toString()}`
s.async = true
container.value.appendChild(s)
// A network blocker fails the request right away, so show the merch card without waiting.
s.onerror = () => (carbonStatus.value = 'blocked')
// Carbon renders shortly after its script runs; a late ad still replaces the merch card.
s.onload = () => setTimeout(() => checkCarbon(false), 500)
container.value!.appendChild(s)
setTimeout(() => checkCarbon(true), BLOCKED_TIMEOUT)
}
}
watch(() => page.value.relativePath, () => {
if (isInitialized && isAsideEnabled.value) {
;(window as any)._carbonads?.refresh()
if (carbonStatus.value === 'blocked') merchAd.value?.next()
else (window as any)._carbonads?.refresh()
}
})
@@ -56,7 +83,8 @@ if (carbonOptions) {
</script>
<template>
<div class="VPCarbonAds" ref="container" />
<div v-show="carbonStatus !== 'blocked'" class="VPCarbonAds" ref="container" />
<MerchAd v-if="carbonStatus === 'blocked'" ref="merchAd" />
</template>
<style scoped>