or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced.mdcomponents.mdindex.mdtypes.mdutilities.md
tile.json

utilities.mddocs/

Image Utilities

Helper functions for extracting image data from GraphQL nodes, generating image configurations for external services, and processing image metadata.

Capabilities

Image Data Extraction

Functions for extracting image data from various GraphQL node types and structures.

getImage Function

Extracts IGatsbyImageData from various GraphQL node types, handling different field patterns automatically.

/**
 * Extract IGatsbyImageData from various GraphQL node types
 * @param node - GraphQL node that may contain image data
 * @returns Extracted image data or undefined if not found
 */
function getImage(node: ImageDataLike | null): IGatsbyImageData | undefined;

type ImageDataLike =
  | IGatsbyImageData
  | IGatsbyImageDataParent
  | IGatsbyImageParent
  | FileNode
  | null
  | undefined;

interface IGatsbyImageDataParent {
  gatsbyImageData: IGatsbyImageData;
}

interface IGatsbyImageParent {
  gatsbyImage: IGatsbyImageData;
}

interface FileNode {
  childImageSharp?: {
    gatsbyImageData?: IGatsbyImageData;
    gatsbyImage?: IGatsbyImageData;
  };
}

Usage Examples:

import { graphql, useStaticQuery } from "gatsby";
import { getImage, GatsbyImage } from "gatsby-plugin-image";

const ImageExample = () => {
  const data = useStaticQuery(graphql`
    query {
      hero: file(relativePath: { eq: "hero.jpg" }) {
        childImageSharp {
          gatsbyImageData(width: 800)
        }
      }
      profile: contentfulAsset(title: { eq: "Profile Photo" }) {
        gatsbyImageData(width: 200, height: 200)
      }
    }
  `);

  // Extract from different node types
  const heroImage = getImage(data.hero);
  const profileImage = getImage(data.profile);

  return (
    <div>
      {heroImage && <GatsbyImage image={heroImage} alt="Hero" />}
      {profileImage && <GatsbyImage image={profileImage} alt="Profile" />}
    </div>
  );
};

getSrc Function

Extracts the main image source URL from image data.

/**
 * Extract the main image src URL from image data
 * @param node - Image data node
 * @returns Main image source URL or undefined
 */
function getSrc(node: ImageDataLike): string | undefined;

Usage Example:

import { getSrc } from "gatsby-plugin-image";

const ImageMeta = ({ imageData }) => {
  const src = getSrc(imageData);
  
  return (
    <div>
      <p>Image URL: {src}</p>
      <img src={src} alt="Fallback" />
    </div>
  );
};

getSrcSet Function

Extracts the srcSet string for responsive images from image data.

/**
 * Extract the srcSet for responsive images from image data
 * @param node - Image data node
 * @returns Responsive srcSet string or undefined
 */
function getSrcSet(node: ImageDataLike): string | undefined;

Usage Example:

import { getSrcSet } from "gatsby-plugin-image";

const ResponsiveImage = ({ imageData }) => {
  const srcSet = getSrcSet(imageData);
  
  return (
    <img
      srcSet={srcSet}
      sizes="(max-width: 768px) 100vw, 50vw"
      alt="Responsive image"
    />
  );
};

External Image Services

Functions for generating image data for external image services and CDNs.

getImageData Function

Generate gatsby-plugin-image compatible data for external image services using custom URL builders.

/**
 * Generate gatsby-plugin-image data for external image services
 * @param args - Configuration for generating image data
 * @returns Complete IGatsbyImageData structure
 */
function getImageData<OptionsType>(
  args: IGetImageDataArgs<OptionsType>
): IGatsbyImageData;

interface IGetImageDataArgs<OptionsType = Record<string, unknown>> {
  /** Base URL for the image service */
  baseUrl: string;
  /** Function to generate URLs based on dimensions and format */
  urlBuilder: (args: IUrlBuilderArgs<OptionsType>) => string;
  /** Desired image width */
  width?: number;
  /** Desired image height */
  height?: number;
  /** Original image width (for aspect ratio calculation) */
  sourceWidth?: number;
  /** Original image height (for aspect ratio calculation) */
  sourceHeight?: number;
  /** Image layout strategy */
  layout?: Layout;
  /** Output image formats */
  formats?: Array<ImageFormat>;
  /** Custom breakpoints for responsive images */
  breakpoints?: Array<number>;
  /** Additional options passed to urlBuilder */
  options?: OptionsType;
  /** Placeholder image URL */
  placeholderURL?: string;
  /** Background color */
  backgroundColor?: string;
}

interface IUrlBuilderArgs<OptionsType = Record<string, unknown>> {
  /** Target image width */
  width: number;
  /** Target image height */
  height: number;
  /** Base URL for the image */
  baseUrl: string;
  /** Image format */
  format: ImageFormat;
  /** Additional options */
  options: OptionsType;
}

type Layout = "fixed" | "constrained" | "fullWidth";
type ImageFormat = "jpg" | "png" | "webp" | "avif" | "auto" | "";

Usage Examples:

import { getImageData, GatsbyImage } from "gatsby-plugin-image";

// Cloudinary integration
const getCloudinaryImageData = (publicId: string, width = 800, height = 600) => {
  return getImageData({
    baseUrl: `https://res.cloudinary.com/demo/image/upload/${publicId}`,
    urlBuilder: ({ width, height, format }) => {
      const f = format === "jpg" ? "jpg" : format;
      return `https://res.cloudinary.com/demo/image/upload/w_${width},h_${height},f_${f}/${publicId}`;
    },
    width,
    height,
    formats: ["webp", "jpg"],
    layout: "constrained",
  });
};

const CloudinaryImage = ({ publicId }) => {
  const imageData = getCloudinaryImageData(publicId, 800, 600);
  
  return (
    <GatsbyImage
      image={imageData}
      alt="Cloudinary image"
    />
  );
};

// Custom CDN integration
const getCDNImageData = (imageId: string, options = {}) => {
  return getImageData({
    baseUrl: `https://cdn.example.com/images/${imageId}`,
    urlBuilder: ({ width, height, format, options }) => {
      const params = new URLSearchParams({
        w: width.toString(),
        h: height.toString(),
        f: format || "jpg",
        ...options,
      });
      return `https://cdn.example.com/images/${imageId}?${params}`;
    },
    width: 1200,
    height: 800,
    formats: ["webp", "avif", "jpg"],
    breakpoints: [400, 800, 1200, 1600],
    options,
  });
};

Image Processing Utilities

Core utilities for generating image data and processing configurations.

generateImageData Function

Low-level function for generating complete image data structures. Primarily used internally by GraphQL resolvers.

/**
 * Generate complete image data structures for internal use
 * @param args - Image generation configuration
 * @returns Complete IGatsbyImageData structure
 */
function generateImageData(args: IGatsbyImageHelperArgs): IGatsbyImageData;

interface IGatsbyImageHelperArgs {
  /** Plugin name for error reporting */
  pluginName: string;
  /** Function to generate individual image sources */
  generateImageSource: (
    filename: string,
    width: number,
    height: number,
    format: ImageFormat,
    fit?: Fit,
    options?: Record<string, unknown>
  ) => IImage;
  /** Image layout strategy */
  layout?: Layout;
  /** Output image formats */
  formats?: Array<ImageFormat>;
  /** Filename for processing */
  filename: string;
  /** Placeholder image URL */
  placeholderURL?: string;
  /** Target image width */
  width?: number;
  /** Target image height */
  height?: number;
  /** Responsive sizes attribute */
  sizes?: string;
  /** Reporter for warnings */
  reporter?: { warn(message: string): void };
  /** Original image metadata */
  sourceMetadata?: { width: number; height: number; format: ImageFormat };
  /** Image fit strategy */
  fit?: Fit;
  /** Processing options */
  options?: Record<string, unknown>;
  /** Custom breakpoints */
  breakpoints?: Array<number>;
  /** Background color */
  backgroundColor?: string;
  /** Aspect ratio */
  aspectRatio?: number;
}

type Fit = "cover" | "fill" | "inside" | "outside" | "contain";

getLowResolutionImageURL Function

Generate URL for low-resolution placeholder images maintaining the same aspect ratio and processing options as the main image.

/**
 * Generate URL for low-resolution placeholder image
 * @param args - Image generation configuration
 * @param width - Placeholder width (default: 20)
 * @returns Low-resolution image URL
 */
function getLowResolutionImageURL(
  args: IGatsbyImageHelperArgs,
  width?: number
): string;

Usage Example:

import { getLowResolutionImageURL } from "gatsby-plugin-image";

const getCustomPlaceholder = (imageArgs) => {
  const placeholderURL = getLowResolutionImageURL(imageArgs, 40);
  return `url(${placeholderURL})`;
};

Utility Features

GraphQL Integration

The utility functions seamlessly integrate with Gatsby's GraphQL layer:

  • Support for multiple GraphQL field patterns
  • Automatic detection of image data in nested structures
  • Type-safe extraction with duck typing validation
  • Compatibility with various source plugins (Sharp, Contentful, etc.)

External Service Support

Built-in support for external image services:

  • Flexible URL builder pattern for any CDN
  • Automatic responsive image generation
  • Format optimization based on browser support
  • Custom breakpoint configuration

Type Safety

Comprehensive TypeScript support:

  • Generic type parameters for custom options
  • Union types for flexible input handling
  • Complete interface definitions for all configurations
  • Type guards for runtime safety

Performance Optimization

Optimized for performance:

  • Lazy evaluation where possible
  • Efficient image data extraction
  • Minimal runtime overhead
  • Caching-friendly URL generation