### Basic InkPictureProvider Setup
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Demonstrates the fundamental setup of InkPictureProvider to enable image rendering within an Ink application. Ensure you import Image and InkPictureProvider.
```typescript
import React from "react";
import { render } from "ink";
import Image, { InkPictureProvider } from "ink-picture";
function App() {
return (
);
}
render();
```
--------------------------------
### Install ink-picture
Source: https://github.com/endernoke/ink-picture/blob/main/README.md
Install the ink-picture package using npm.
```bash
npm install ink-picture
```
--------------------------------
### Image Source Examples
Source: https://github.com/endernoke/ink-picture/blob/main/README.md
Examples of how to specify the image source for the `` component. It accepts local paths, URLs, and raw image buffers.
```tsx
```
```tsx
```
```tsx
```
--------------------------------
### ImageProtocolHint Example
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/types.md
An example demonstrating how to define an ImageProtocolHint object. This shows assigning specific protocols ('kitty', 'halfBlock', 'ascii') to different visibility states ('full', 'partial', 'hidden').
```typescript
const hint: ImageProtocolHint = {
full: "kitty",
partial: "halfBlock",
hidden: "ascii",
};
```
--------------------------------
### Basic useVisibility Usage Example
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Hooks.md
Demonstrates how to use the useVisibility hook with useStdout and usePosition to conditionally render content based on component visibility.
```typescript
import { useStdout } from "ink";
import { useVisibility, usePosition } from "ink-picture";
function MyComponent() {
const ref = useRef(null);
const { stdout } = useStdout();
const position = usePosition(ref);
const visibility = useVisibility(position, stdout.rows, stdout.columns);
return (
{visibility === "full" && Fully visible}
{visibility === "partial" && Partially visible}
{visibility === "hidden" && Hidden}
);
}
```
--------------------------------
### Custom GetVisibility Example
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/types.md
An example demonstrating how to implement a custom GetVisibility callback. This snippet shows custom logic for partial visibility based on row position and a fallback to default visibility.
```typescript
const customGetVisibility: GetVisibility = ({ position, defaultVisibility }) => {
if (position.row < 5) return "partial"; // Custom logic
return defaultVisibility; // Fall back to default
};
```
--------------------------------
### Quick Start with ink-picture
Source: https://github.com/endernoke/ink-picture/blob/main/README.md
Basic usage of the `` component within an Ink application. Ensure your app is wrapped with `InkPictureProvider`.
```tsx
import React from "react";
import { Box, render } from "ink";
import Image, { InkPictureProvider } from "ink-picture";
function App() {
return (
);
}
render();
```
--------------------------------
### Using ImageCache
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/UtilityFunctions.md
Demonstrates how to use the ImageCache via the useImageCache() hook to get, set, check size, and clear cached images. Ensure the hook is available before use.
```typescript
const cache = useImageCache();
if (cache) {
// Get cached image (cloned)
const image = cache.get("https://example.com/image.png");
// Store new image
cache.set("https://example.com/photo.jpg", loadedImage);
// Check cache size
console.log(`Cached images: ${cache.size}`);
// Clear entire cache
cache.clear();
}
```
--------------------------------
### Customizing Ink-Picture Configuration
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
This example shows how to provide custom configuration options to the InkPictureProvider, such as cache size and polling intervals. It also demonstrates how to use the onTerminalInfoDetection callback to log terminal capabilities.
```typescript
{
console.log("Detected capabilities:", info);
}}
>
```
--------------------------------
### InkPictureProvider with Configuration and Callback
Source: https://github.com/endernoke/ink-picture/blob/main/README.md
Wrap your application with InkPictureProvider to provide terminal capabilities and configuration to all descendant Image components. This example shows how to set a custom cache size and use the onTerminalInfoDetection callback.
```tsx
{
foo(info);
}}>
```
--------------------------------
### Custom Image Visibility Detection
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
This example demonstrates how to implement custom logic for determining image visibility using the getVisibility prop. The provided function allows for conditional visibility based on the image's position on the screen.
```typescript
{
if (position.row < 5) return "partial";
return defaultVisibility;
}}
/>
```
--------------------------------
### Managing Image Cache with useImageCache Hook
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Shows how to use the `useImageCache` hook to get access to the image cache instance, enabling programmatic actions like clearing the cache.
```typescript
import { useImageCache } from "ink-picture";
function CacheClearer() {
const cache = useImageCache();
return (
);
}
```
--------------------------------
### Handling Terminal Info Detection Callback
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Provides an example of using the `onTerminalInfoDetection` prop to receive and log detailed information about the terminal's capabilities after detection.
```typescript
{
console.log(`Terminal supports Kitty: ${info.supportsKittyGraphics}`);
console.log(`Terminal supports Sixel: ${info.supportsSixelGraphics}`);
console.log(`Unicode: ${info.supportsUnicode}, Color: ${info.supportsColor}`);
}}
>
```
--------------------------------
### Usage Example for useImageCache Hook
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Hooks.md
Demonstrates how to use the useImageCache hook to access and manage the image cache within a React component. It shows how to display cache size and clear the cache.
```typescript
function CacheManager() {
const cache = useImageCache();
if (!cache) {
return Caching disabled;
}
return (
Cached images: {cache.size}
);
}
```
--------------------------------
### Override Terminal Info with InkPictureProvider
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Provide a `terminalInfo` object to `InkPictureProvider` to manually set terminal capabilities. This example overrides cell dimensions and graphics support.
```jsx
```
--------------------------------
### Custom Visibility Detection Logic
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Hooks.md
Shows how to override default visibility detection by providing a custom getVisibility callback to the useVisibility hook. This example accounts for a sticky header.
```typescript
const customVisibility = useVisibility(
position,
stdout.rows,
stdout.columns,
({ position, terminalHeight, defaultVisibility }) => {
// Account for sticky header at top of screen
if (position.row < 5) return "partial";
return defaultVisibility;
}
);
```
--------------------------------
### Configuration Priority Example
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Demonstrates how environment variables override prop values for ink-picture configuration. The environment variable INK_PICTURE_POLL_INTERVAL is set to 50, which will be used instead of the prop value of 32.
```typescript
// With INK_PICTURE_POLL_INTERVAL=50 in environment:
{/* pollIntervalMs will be 50, from environment */}
```
--------------------------------
### Get TerminalInfo Hook
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Use this hook to get terminal information, including support for specific graphics protocols. It provides fallback defaults if used outside of InkPictureProvider.
```typescript
function useTerminalInfo(): TerminalInfo
```
```typescript
const info = useTerminalInfo();
if (info.supportsKittyGraphics) {
// Use Kitty graphics protocol
}
```
--------------------------------
### Setting Configuration via Runtime Flags (Node.js)
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Load environment variables for ink-picture configuration from a .env file using Node.js runtime flags.
```bash
node --env-file=.env app.js
```
--------------------------------
### Run All Tests
Source: https://github.com/endernoke/ink-picture/blob/main/DEVELOPMENT.md
Execute a comprehensive test suite including type checking, linting, unit tests, and browser tests.
```bash
pnpm test
```
--------------------------------
### Get ImageCache Hook
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Retrieve the image cache instance using this hook. It returns null if caching is disabled (cacheSize is 0).
```typescript
function useImageCache(): ImageCache | null
```
```typescript
const cache = useImageCache();
if (cache) {
cache.clear(); // Clear all cached images
}
```
--------------------------------
### Setting Configuration via Environment Variables
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Set ink-picture configuration options using environment variables. These take precedence over prop values.
```bash
export INK_PICTURE_POLL_INTERVAL=32
export INK_PICTURE_PAINT_INTERVAL=32
export INK_PICTURE_CACHE_SIZE=20
node app.js
```
--------------------------------
### Get InkPictureConfig Hook
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Use this hook to retrieve the current InkPicture configuration. It combines environment variables, prop overrides, and default values.
```typescript
function useInkPictureConfig(): InkPictureConfig
```
```typescript
const config = useInkPictureConfig();
console.log(config.pollIntervalMs); // 16 or overridden value
```
--------------------------------
### Import Main Component
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/INDEX.md
Import the main Image component and InkPictureProvider for using ink-picture.
```typescript
import Image, { InkPictureProvider } from "ink-picture";
```
--------------------------------
### Render Image with Kitty Protocol and Fallback
Source: https://github.com/endernoke/ink-picture/blob/main/README.md
Use the 'kitty' protocol for full visibility and a text-based fallback for partial or hidden states. This ensures some content is always displayed.
```tsx
import { Image } from "@/components/image";
// Image will be rendered with kitty graphics protocol when fully visible,
// and fall back to a text-based protocol otherwise.
```
--------------------------------
### Use usePosition Hook in a React Component
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Hooks.md
Example of how to use the usePosition hook within a React component. It requires a ref to a Box component and displays its position and dimensions once measured.
```typescript
import { Box } from "ink";
import { usePosition } from "ink-picture";
function PositionDisplay() {
const ref = useRef(null);
const position = usePosition(ref);
return (
{position ? (
Position: ({position.col}, {position.row}) |
Size: {position.width}x{position.height}
) : (
Measuring...
)}
);
}
```
--------------------------------
### makeKittyPlacement
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/RendererFunctions.md
Creates a Kitty graphics placement command to display a transmitted image. This function is used after image data has been sent to position the image on the terminal.
```APIDOC
## makeKittyPlacement
### Description
Creates a Kitty graphics placement command to display a transmitted image.
### Parameters
#### Path Parameters
- `imageId` (number) - Required - Image ID from transmission
- `placementId` (number) - Optional - Placement ID for this display instance (Default: 1)
### Return Value
ANSI escape sequence for image placement (`a=p` action).
### Details
- Must be called after image transmission
- Multiple placements of same image possible with different `placementId`
- Placement position determined by cursor location
- Include cursor positioning commands before this
### Example
```typescript
process.stdout.write("\x1b7"); // Save cursor
process.stdout.write("\x1b[H"); // Move to top-left
process.stdout.write(makeKittyPlacement(imageId, 1));
process.stdout.write("\x1b8"); // Restore cursor
```
```
--------------------------------
### getBestProtocol
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/UtilityFunctions.md
Selects the best rendering protocol based on terminal capabilities. It considers various terminal emulators and their support for different protocols like Kitty, iTerm2, Sixel, and text-based fallbacks.
```APIDOC
## getBestProtocol
### Description
Selects the best rendering protocol based on terminal capabilities.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Method Signature
```typescript
function getBestProtocol(caps: TerminalInfo): "sixel" | "kitty" | "iterm2" | "braille" | "halfBlock" | "ascii"
```
### Parameters
#### `caps` (`TerminalInfo`) - Required
Terminal capabilities from detection.
### Return Value
Protocol name for best available rendering method.
### Selection Logic
1. **iTerm.app (macOS):** Prefer iTerm2 (mature support)
2. **Warp Terminal:** Prefer iTerm2 (incomplete Kitty support)
3. **WezTerm:** Prefer iTerm2 (Kitty has race conditions)
4. **Konsole:** Prefer Kitty (only fully working protocol)
5. **Generic:** Kitty > iTerm2 > Sixel (in order of support)
6. **Text-based fallback:** HalfBlock (color + Unicode) > Braille (Unicode) > ASCII
### Heuristics
- Terminal-specific overrides for known issues with certain protocols
- Environment variables (`TERM_PROGRAM`, `TERM_PROGRAM_VERSION`) used for detection
- Avoids protocols with non-standard implementations or known bugs
### Import
Used by `useProtocol()` hook.
```
--------------------------------
### Import Statement
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/ProtocolComponents.md
Shows how to import the available protocol components from the ink-picture library.
```APIDOC
## Import
```typescript
import {
AsciiImage,
BrailleImage,
HalfBlockImage,
SixelImage,
KittyImage,
ITerm2Image,
} from "ink-picture";
```
```
--------------------------------
### Project File Structure
Source: https://github.com/endernoke/ink-picture/blob/main/DEVELOPMENT.md
The project follows a structured layout with distinct directories for components, hooks, renderers, and utilities. Public exports are located in index.ts.
```tree
src/
├── index.ts # Public exports
├── InkPictureProvider.tsx # Context provider, terminal detection, config
├── components/
│ ├── image/
│ │ ├── index.tsx # Main component with protocol switching
│ │ ├── protocol.ts # ImageProps and ImageProtocol types
│ │ ├── Ascii.tsx # ASCII renderer component
│ │ ├── Braille.tsx # Braille renderer component
│ │ ├── HalfBlock.tsx # Half-block renderer component
│ │ ├── Kitty.tsx # Kitty graphics renderer component
│ │ ├── Sixel.tsx # Sixel renderer component
│ │ └── ITerm2.tsx # iTerm2 renderer component
│ └── ImageBox.tsx # Shared container with loading and error states
├── hooks/
│ ├── useBackgroundColor.ts # Inherited background color detection
│ ├── useDirectRenderer.ts # Interval-based stdout painting for Sixel and iTerm2
│ ├── useImage.ts # Image loading, caching, and resizing
│ ├── useMeasuredSize.ts # Percentage dimension resolution
│ ├── usePosition.ts # Element position tracking with active polling for layout changes
│ ├── useProtocol.ts # Best protocol selection
│ └── useVisibility.ts # Viewport visibility detection
├── renderers/
│ ├── types.ts # PixelData and PngData types
│ ├── ascii.ts # ASCII art generator
│ ├── braille.ts # Braille pattern generator
│ ├── halfBlock.ts # Half-block color generator
│ ├── kitty.ts # Kitty escape sequence generators
│ ├── iterm2.ts # iTerm2 escape sequence generator
│ └── sixel.ts # Sixel escape sequence generator
└── utils/
├── ansiEscapes.ts # Cursor movement helpers
├── bgColorize.ts # Background color ANSI formatting
├── generateKittyId.ts # Kitty image ID singleton
├── getBestProtocol.ts # Terminal-specific protocol heuristic
├── image.ts # Jimp wrappers: load, resize, pixel/PNG output
├── imageCache.ts # LRU image cache
└── queryTerminal.ts # Terminal capability detection via escape queries
```
--------------------------------
### Get InkPicture Configuration
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Hooks.md
Retrieves the resolved InkPicture configuration, which combines environment variables, prop overrides, and default values. This hook is essential for understanding and potentially customizing the behavior of ink-picture components.
```typescript
import { useInkPictureConfig, type InkPictureConfig } from "ink-picture";
function ConfigDisplay() {
const config = useInkPictureConfig();
return (
Poll Interval: {config.pollIntervalMs}msPaint Interval: {config.paintIntervalMs}msCache Size: {config.cacheSize}
);
}
```
--------------------------------
### Configuring InkPictureProvider with Custom Settings
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Shows how to customize InkPictureProvider's behavior by passing a configuration object. This allows tuning cache size and polling intervals.
```typescript
```
--------------------------------
### Run Unit Tests
Source: https://github.com/endernoke/ink-picture/blob/main/DEVELOPMENT.md
Execute unit tests using Vitest. These tests focus on renderers, utilities, and hooks that do not rely on terminal escape sequence interpretation.
```bash
pnpm test:unit
```
--------------------------------
### High-Performance InkPictureProvider Configuration
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Configure for terminals with fast re-renders and minimal flickering by setting lower intervals for polling and painting, and a larger cache size.
```typescript
```
--------------------------------
### Get Terminal Information
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Hooks.md
Fetches terminal capabilities and dimensions. This hook can be used outside of an `InkPictureProvider` and will provide fallback default values. It's useful for adapting rendering based on terminal features like color and graphics support.
```typescript
import { useTerminalInfo, type TerminalInfo } from "ink-picture";
function ProtocolSelector() {
const info = useTerminalInfo();
let protocol = "ascii";
if (info.supportsKittyGraphics) {
protocol = "kitty";
} else if (info.supportsITerm2Graphics) {
protocol = "iterm2";
} else if (info.supportsSixelGraphics) {
protocol = "sixel";
} else if (info.supportsUnicode && info.supportsColor) {
protocol = "halfBlock";
} else if (info.supportsUnicode) {
protocol = "braille";
}
return Using protocol: {protocol};
}
```
--------------------------------
### Import Protocol Components
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/INDEX.md
Import specific image protocol components like AsciiImage, BrailleImage, HalfBlockImage, SixelImage, KittyImage, and ITerm2Image.
```typescript
import {
AsciiImage, BrailleImage, HalfBlockImage,
SixelImage, KittyImage, ITerm2Image
} from "ink-picture";
```
--------------------------------
### Image Dimensions with Percentage Values
Source: https://github.com/endernoke/ink-picture/blob/main/README.md
Use percentage-based width and height for the image component. The parent `` must have a determinable size for this to work correctly.
```tsx
// Image dimensions will be 12W X 8H
```
--------------------------------
### Basic Image Usage
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Image.md
Render a basic image with a remote source, specified dimensions, and an alt text for accessibility. Ensure InkPictureProvider is used.
```typescript
import React from "react";
import { render, Box } from "ink";
import Image, { InkPictureProvider } from "ink-picture";
function App() {
return (
);
}
render();
```
--------------------------------
### Run Formatting and Linting
Source: https://github.com/endernoke/ink-picture/blob/main/DEVELOPMENT.md
Execute code formatting and linting checks. The lint command can optionally attempt to fix issues.
```bash
pnpm format
pnpm lint [--fix]
```
--------------------------------
### Import Types
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
Import various types for defining image properties, protocols, visibility, position, configuration, and terminal information.
```typescript
import type {
ImageProps,
ImageProtocol,
ImageProtocolName,
ImageProtocolHint,
Visibility,
VisibilityInfo,
GetVisibility,
Position,
InkPictureConfig,
TerminalInfo,
} from "ink-picture";
```
--------------------------------
### Visibility Detection
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/ProtocolComponents.md
Explains how visibility is detected for text-based and graphical protocol components.
```APIDOC
## Visibility Detection
Text-based protocol components (ASCII, Braille, HalfBlock) automatically track visibility within the app and terminal viewport.
Graphical protocol components (Sixel, Kitty, iTerm2) only render when images are fully visible to prevent:
- Image dislocation from cursor positioning limitations
- Race conditions during app re-renders
- Visual artifacts from partial rendering
```
--------------------------------
### Load Environment Variables with dotenv/config
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Import 'dotenv/config' to automatically load environment variables from a .env file into process.env.
```typescript
import "dotenv/config";
// Now process.env.INK_PICTURE_POLL_INTERVAL is available
```
--------------------------------
### Local File Paths
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Image.md
Render images from local file paths, supporting relative, absolute, and file:// URL formats.
```typescript
// Relative path
// Absolute path
// file:// URL
```
--------------------------------
### Low-Performance InkPictureProvider Configuration
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Configure for slow terminals or resource-constrained environments by increasing intervals for polling and painting, and reducing the cache size.
```typescript
```
--------------------------------
### Protocol Component Props
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/ProtocolComponents.md
All protocol components accept the same base props for configuring image display.
```APIDOC
## Protocol Component Props
All protocol components accept the same base props:
| Prop | Type | Default | Required | Description |
|------|------|---------|----------|-------------|
| `src` | `string \| ArrayBuffer \| Buffer` | — | Yes | Image source: URL, file path, or raw data |
| `width` | `number \| string` | — | Yes | Width in terminal cells or percentage |
| `height` | `number \| string` | — | Yes | Height in terminal cells or percentage |
| `alt` | `string` | — | No | Alternative text for loading/error states and accessibility |
```
--------------------------------
### Import Types
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/INDEX.md
Import a comprehensive set of types for props, protocols, visibility, position, configuration, terminal information, and image data.
```typescript
import type {
ImageProps, ImageProtocol, ImageProtocolName, ImageProtocolHint,
Visibility, VisibilityInfo, GetVisibility, Position,
InkPictureConfig, TerminalInfo,
PixelData, PngData, TerminalQueryResult
} from "ink-picture";
```
--------------------------------
### Basic Image Rendering with Ink-Picture
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
This snippet demonstrates the fundamental usage of the ink-picture component within a React application. It shows how to import necessary components and render an image with specified dimensions and alt text.
```typescript
import React from "react";
import { render } from "ink";
import Image, { InkPictureProvider } from "ink-picture";
function App() {
return (
);
}
render();
```
--------------------------------
### Setting Configuration via Props
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Configure ink-picture by passing a config object to the InkPictureProvider component.
```typescript
import { InkPictureProvider } from "ink-picture";
```
--------------------------------
### Import renderAscii
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/RendererFunctions.md
Shows the internal import path for the `renderAscii` function, which is not part of the main public API.
```typescript
import { renderAscii } from "ink-picture/renderers/ascii.js";
```
--------------------------------
### Fixed Protocol Selection
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Image.md
Explicitly set the image rendering protocol. 'sixel' is used for direct Sixel support, while { full: 'kitty' } prioritizes Kitty graphics protocol.
```typescript
// Always use Sixel if available, don't fall back
// Use Kitty for fully visible images, fall back to text-based otherwise
```
--------------------------------
### Set Environment Variables in .env File
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Define environment variables in a .env file for ink-picture configuration. Load these variables using Node.js with the --env-file flag.
```bash
# .env
INK_PICTURE_POLL_INTERVAL=32
INK_PICTURE_PAINT_INTERVAL=32
INK_PICTURE_CACHE_SIZE=20
```
```bash
node --env-file=.env app.js
```
--------------------------------
### Import Hooks
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/INDEX.md
Import various hooks provided by ink-picture, including useVisibility, usePosition, useTerminalInfo, useInkPictureConfig, and useImageCache.
```typescript
import {
useVisibility, usePosition,
useTerminalInfo, useInkPictureConfig, useImageCache
} from "ink-picture";
```
--------------------------------
### Component Comparison Table
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/ProtocolComponents.md
A comparison table outlining the features of different image protocol components.
```APIDOC
## Comparison Table
| Component | Protocol | Resolution | Color | Unicode | Requirements |
|-----------|----------|-----------|-------|---------|--------------|
| AsciiImage | ASCII | 1x1 | Optional | No | None |
| BrailleImage | Braille | 2x4 | No | Yes | Unicode |
| HalfBlockImage | Half-Block | 1x2 | Yes | Yes | Unicode + Color |
| SixelImage | Sixel | Full | Yes | No | Terminal support |
| KittyImage | Kitty | Full | Yes | No | Terminal support |
| ITerm2Image | iTerm2 | Full | Yes | No | Terminal support |
```
--------------------------------
### Import Protocol Components
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/ProtocolComponents.md
Import all available protocol components from the 'ink-picture' library. These components are used to render images in different terminal protocols.
```typescript
import {
AsciiImage,
BrailleImage,
HalfBlockImage,
SixelImage,
KittyImage,
ITerm2Image,
} from "ink-picture";
```
--------------------------------
### Import useVisibility Hook
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Hooks.md
Imports necessary types and the useVisibility hook from the ink-picture library.
```typescript
import { useVisibility, type Visibility, type VisibilityInfo, type GetVisibility } from "ink-picture";
```
--------------------------------
### Import Kitty Graphics Functions
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/RendererFunctions.md
Import statement for the Kitty graphics protocol functions from the ink-picture library.
```typescript
import {
makeKittyTransmitChunks,
makeKittyPlacement,
makeKittyDeletion,
} from "ink-picture/renderers/kitty.js";
```
--------------------------------
### Import InkPicture Components
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Import necessary components and hooks from the 'ink-picture' package. Includes an alias for backwards compatibility.
```typescript
import { InkPictureProvider, useInkPictureConfig, useTerminalInfo, useImageCache } from "ink-picture";
// Backwards compatibility alias
import { TerminalInfoProvider } from "ink-picture";
```
--------------------------------
### Choose Protocol Based on Terminal Capabilities
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/ProtocolComponents.md
Dynamically selects an image component based on the terminal's supported graphics protocols. Ensure `useTerminalInfo` is available within a `InkPictureProvider` context.
```typescript
import { useTerminalInfo } from "ink-picture";
function SmartImage({ src, width, height }) {
const info = useTerminalInfo();
if (info.supportsKittyGraphics) {
return ;
} else if (info.supportsITerm2Graphics) {
return ;
} else if (info.supportsSixelGraphics) {
return ;
} else if (info.supportsUnicode && info.supportsColor) {
return ;
} else if (info.supportsUnicode) {
return ;
} else {
return ;
}
}
```
--------------------------------
### Select Best Terminal Rendering Protocol
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/UtilityFunctions.md
Selects the best rendering protocol based on terminal capabilities. It prioritizes protocols like iTerm2, Kitty, and Sixel based on terminal type and known issues, falling back to text-based protocols like HalfBlock, Braille, or ASCII.
```typescript
function getBestProtocol(
caps: TerminalInfo
): "sixel" | "kitty" | "iterm2" | "braille" | "halfBlock" | "ascii"
```
--------------------------------
### Terminal Detection Queries
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
This snippet shows the escape sequences used to query terminal capabilities. These queries help determine cell size, terminal size, and support for specific graphics protocols like Sixel, Kitty, and iTerm2.
```bash
CSI 16 t → Cell size response (CSI 6 ; width ; height t)
CSI 14 t → Terminal size response (CSI 4 ; width ; height t)
CSI ? ... c → Device attributes (checks for 4 = Sixel)
Kitty query → Kitty protocol query (looks for OK response)
iTerm2 query → iTerm2 cell size (ReportCellSize response)
```
--------------------------------
### Module Structure
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
This tree outlines the directory structure of the Ink-Picture project, detailing the location of components, hooks, renderers, and utilities.
```tree
src/
├── components/
│ ├── image/
│ │ ├── index.tsx # Main Image component
│ │ ├── Ascii.tsx # ASCII protocol component
│ │ ├── Braille.tsx # Braille protocol component
│ │ ├── HalfBlock.tsx # Half-block protocol component
│ │ ├── Sixel.tsx # Sixel protocol component
│ │ ├── Kitty.tsx # Kitty protocol component
│ │ ├── ITerm2.tsx # iTerm2 protocol component
│ │ └── protocol.ts # Type definitions
│ ├── ImageBox.tsx # Shared loading/error container
│ └── DirectRenderer.tsx # Direct stdout rendering logic
├── hooks/
│ ├── useImage.ts # Image loading hook
│ ├── usePosition.ts # Position tracking hook
│ ├── useVisibility.ts # Visibility detection hook
│ ├── useProtocol.ts # Protocol selection hook
│ ├── useMeasuredSize.ts # Size measurement hook
│ ├── useDirectRenderer.ts # Direct render scheduling
│ └── useBackgroundColor.ts # Background color detection
├── renderers/
│ ├── ascii.ts # ASCII renderer
│ ├── braille.ts # Braille renderer
│ ├── halfBlock.ts # Half-block renderer
│ ├── sixel.ts # Sixel renderer
│ ├── kitty.ts # Kitty protocol commands
│ ├── iterm2.ts # iTerm2 renderer
│ ├── types.ts # Renderer data types
│ └── index.ts # Renderer exports
├── utils/
│ ├── image.ts # Image loading utilities
│ ├── imageCache.ts # LRU image cache
│ ├── queryTerminal.ts # Terminal capability detection
│ ├── getBestProtocol.ts # Protocol selection logic
│ ├── ansiEscapes.ts # ANSI escape helpers
│ ├── generateKittyId.ts # Kitty ID generator
│ └── bgColorize.ts # Background color utilities
├── InkPictureProvider.tsx # Provider and hooks
└── index.ts # Public API exports
```
--------------------------------
### Main Export
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
The primary way to use ink-picture is by importing the Image component and the InkPictureProvider. This allows for rendering images within your Ink application.
```APIDOC
## Main Export
### Description
Import the `Image` component and `InkPictureProvider` for rendering images in your terminal application using Ink.
### Usage
```typescript
import Image, { InkPictureProvider } from "ink-picture";
```
```
--------------------------------
### Import Image Component
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Image.md
Import the Image component from the ink-picture library.
```typescript
import Image from "ink-picture";
```
--------------------------------
### Forcing a Specific Image Protocol
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
This snippet illustrates how to explicitly set the image rendering protocol to 'kitty' for a specific Image component. This is useful when you need to ensure compatibility with a particular terminal emulator's capabilities.
```typescript
```
--------------------------------
### ImageProtocol Interface
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/types.md
Defines the structure for rendering protocols. Each protocol must have a unique 'name' and a 'render' function that takes ImageProps and returns a JSX.Element or null.
```typescript
interface ImageProtocol {
name: string;
render(props: ImageProps): JSX.Element | null;
}
```
--------------------------------
### Skip Terminal Detection with Overrides
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
To bypass the default terminal detection process and render immediately, provide the `terminalInfo` prop. This ensures no delay while ensuring specific terminal capabilities are set.
```jsx
{/* No detection delay; renders immediately */}
```
--------------------------------
### Create Kitty Graphics Image Placement Command
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/RendererFunctions.md
Generates an ANSI escape sequence to place a previously transmitted image at the current cursor position using the Kitty graphics protocol. This is used to display the image after it has been sent in chunks.
```typescript
process.stdout.write("\x1b7"); // Save cursor
process.stdout.write("\x1b[H"); // Move to top-left
process.stdout.write(makeKittyPlacement(imageId, 1));
process.stdout.write("\x1b8"); // Restore cursor
```
--------------------------------
### Import renderSixel Function
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/RendererFunctions.md
Import statement for the renderSixel function from the ink-picture library.
```typescript
import { renderSixel } from "ink-picture/renderers/sixel.js";
```
--------------------------------
### Import useImageCache Hook
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/Hooks.md
Import the useImageCache hook from the ink-picture library to enable direct cache management in your components.
```typescript
import { useImageCache } from "ink-picture";
```
--------------------------------
### Import Alias for TerminalInfoProvider
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/README.md
Import the TerminalInfoProvider alias, which is an alias for InkPictureProvider.
```typescript
import { TerminalInfoProvider } from "ink-picture"; // Alias for InkPictureProvider
```
--------------------------------
### Test Environment InkPictureProvider Configuration
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/configuration.md
Configure for consistent behavior in testing environments by setting specific terminal dimensions, cell sizes, feature support, and performance intervals.
```typescript
```
--------------------------------
### useImageCache()
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/InkPictureProvider.md
Returns the image cache instance. If caching is disabled (cacheSize: 0), it returns null. This hook allows direct interaction with the image cache, such as clearing it.
```APIDOC
## useImageCache()
### Description
Returns the image cache instance, or `null` if caching is disabled (`cacheSize: 0`).
### Returns
- `ImageCache | null`: The image cache instance or null if caching is disabled.
### Usage Example
```typescript
const cache = useImageCache();
if (cache) {
cache.clear(); // Clear all cached images
}
```
```
--------------------------------
### renderAscii
Source: https://github.com/endernoke/ink-picture/blob/main/_autodocs/api-reference/RendererFunctions.md
Renders pixel data as ASCII art using a 70-character intensity scale. It can optionally output colored characters using ANSI color codes.
```APIDOC
## renderAscii
### Description
Renders pixel data as ASCII art using a 70-character intensity scale. It can optionally output colored characters using ANSI color codes.
### Method
Function
### Parameters
#### Parameters
- **pixels** (PixelData) - Required - Raw RGBA pixel data with width/height metadata
- **options.colored** (boolean) - Optional - If `true`, outputs use ANSI color codes matching pixel colors. Defaults to `true`.
### Return Value
String containing ASCII art (newline-separated lines), with optional color codes if `colored: true`.
### Details
- Maps pixel intensity (0-255) to ASCII character set: `$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. `
- Lowest intensity maps to space ` `, highest to `$`
- Each pixel becomes one character (1x1 resolution)
- Uses RGBA average for intensity calculation
- With `colored: true`, wraps each character with `chalk.rgb(r, g, b)` for colored output
### Usage Example
```typescript
import { renderAscii } from "ink-picture";
import { getRawPixels } from "./image";
import Jimp from "jimp";
const image = await Jimp.read("photo.jpg");
image.resize({ w: 80, h: 40 });
const pixelData = await getRawPixels(image);
const ascii = renderAscii(pixelData, { colored: true });
console.log(ascii);
```
### Import
```typescript
import { renderAscii } from "ink-picture/renderers/ascii.js";
```
```