@patreon/studio
Version:
Patreon Studio Design System
72 lines • 3.01 kB
JavaScript
import { useTokenModes } from '~/components/TokenModeProvider';
export const normalizeSrc = (src) => (typeof src === 'string' ? { src } : src);
// TODO (legacied consistent-return)
// This failure is legacied in and should be updated. DO NOT COPY.
/* eslint-disable consistent-return */
export function generateSrcSet({ x1, x2 }) {
if (x1 && x2) {
return `${x1} 1x, ${x2} 2x`;
}
if (x1) {
return `${x1} 1x`;
}
return;
}
/* eslint-enable consistent-return */
export function generateSources(tokenColorMode, { src, src2x, darkSrc, darkSrc2x }) {
// since `src` is required, we can safely assert that this image will not be undefined
const lightSrcSet = generateSrcSet({ x1: src, x2: src2x });
const darkSrcSet = generateSrcSet({ x1: darkSrc, x2: darkSrc2x });
// return the light mode srcs if we're in light mode or if there are no dark mode images
if (tokenColorMode === 'light' || !darkSrcSet) {
return [{ media: undefined, srcSet: lightSrcSet }];
}
// in dark mode we return the dark srcs if they exist, otherwise we fallback to the light srcs
if (tokenColorMode === 'dark') {
return [{ media: undefined, srcSet: darkSrcSet }];
}
// in auto mode we return both light and dark srcs using a media query to select the correct one
return [
{ media: '(prefers-color-scheme: dark)', srcSet: darkSrcSet },
{ media: undefined, srcSet: lightSrcSet },
];
}
export function useSources(inputSrc) {
const { currentColorMode } = useTokenModes();
// we need to protect against the case where src is undefined
// because untyped prf code can pass undefined to this hook
if (!inputSrc) {
// TODO: Add a devError here when graduating to studio
return {
src: '',
sources: [],
};
}
const { src, src2x, darkSrc, darkSrc2x } = normalizeSrc(inputSrc);
// since `src` is required, we can safely assert that this image will not be undefined
const lightSrcSet = generateSrcSet({ x1: src, x2: src2x });
const darkSrcSet = generateSrcSet({ x1: darkSrc, x2: darkSrc2x });
// return the light mode srcs if we're in light mode or if there are no dark mode images
if (currentColorMode === 'light' || !darkSrcSet) {
return {
src,
sources: [{ media: undefined, srcSet: lightSrcSet }],
};
}
// in dark mode we return the dark srcs if they exist, otherwise we fallback to the light srcs
if (currentColorMode === 'dark') {
return {
src: darkSrc,
sources: [{ media: undefined, srcSet: darkSrcSet }],
};
}
// in auto mode we return both light and dark srcs using a media query to select the correct one
return {
src,
sources: [
{ media: '(prefers-color-scheme: dark)', srcSet: darkSrcSet },
{ media: undefined, srcSet: lightSrcSet },
],
};
}
//# sourceMappingURL=useSources.js.map