### Start Development Environment Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/contributing.en.md Run the development server from the 'dev' directory to start contributing. ```bash # Run from the dev directory npm run dev ``` -------------------------------- ### Install @antv/infographic Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/index.en.md Install the package using npm. ```bash npm install @antv/infographic --save ``` -------------------------------- ### Start the Development Environment Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/contributing.md Run this command from the 'dev' directory to start the local development server. ```bash # 位于 dev 目录下运行 npm run dev ``` -------------------------------- ### Install AntV Infographic Source: https://github.com/antvis/infographic/blob/main/README.md Install the package via npm. ```bash npm install @antv/infographic ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/contributing.md Navigate into the project directory and install the necessary dependencies for the main project and the development environment. ```bash cd infographic npm install cd dev npm install ``` -------------------------------- ### Import Library Modules Source: https://github.com/antvis/infographic/blob/main/skills/infographic-structure-creator/references/structure-prompt.md Example of importing various components and utilities from the library. ```tsx import type { ComponentType, JSXElement } from '../../jsx'; import { getElementBounds, Defs, Ellipse, Group, Path, Polygon, Rect, Text, } from '../../jsx'; import { BtnAdd, BtnRemove, BtnsGroup, Illus, ItemDesc, ItemIcon, ItemIconCircle, ItemLabel, ItemsGroup, ItemValue, Title, } from '../components'; import { LinearGradient } from '../defs'; import { SimpleArrow, Triangle } from '../decorations'; import { FlexLayout } from '../layouts'; import { getColorPrimary, getPaletteColor, getPaletteColors, getThemeColors, getItemComponent, } from '../utils'; import { getDatumByIndexes } from '../../utils'; import { registerStructure } from './registry'; import type { BaseStructureProps } from './types'; ``` -------------------------------- ### Layout - Creating a Layout Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/jsx.en.md Provides instructions and an example for creating custom layout components using `createLayout`. ```APIDOC ## Layout - Creating a Layout Use [createLayout](/reference/create-layout) to build custom layout components. Layout components are special function components marked by a symbol: ```typescript const LAYOUT_SYMBOL = Symbol('layout'); export function createLayout(fn: LayoutFunction): LayoutComponent { const component = (props) => fn(props); component[LAYOUT_SYMBOL] = true; return component; } ``` Example of creating a `VerticalLayout`: ```tsx import {createLayout, getElementBounds} from '@antv/infographic-jsx'; const VerticalLayout = createLayout<{gap: number}>(({children, gap = 10}) => { let currentY = 0; return children.map((child) => { const bounds = getElementBounds(child); const positioned = { ...child, props: {...child.props, y: currentY}, }; currentY += bounds.height + gap; return positioned; }); }); ``` ``` -------------------------------- ### Install Infographic Skills for Codex Source: https://github.com/antvis/infographic/blob/main/README.md Command to install a specific skill using the codex installer. ```codex # Replace with the skill name, e.g. infographic-creator # https://github.com/antvis/Infographic/tree/main/skills/ $skill-installer install https://github.com/antvis/Infographic/tree/main/skills/infographic-creator ``` -------------------------------- ### Install Infographic Skills for Claude Code Source: https://github.com/antvis/infographic/blob/main/README.md Commands to install Infographic skills via the Claude marketplace or manual script. ```bash /plugin marketplace add https://github.com/antvis/Infographic.git /plugin install antv-infographic-skills@antv-infographic ``` ```bash set -e VERSION=0.2.4 # Replace with the latest tag, e.g. 0.2.14 BASE_URL=https://github.com/antvis/Infographic/releases/download mkdir -p .claude/skills curl -L --fail -o skills.zip "$BASE_URL/$VERSION/skills.zip" unzip -q -o skills.zip -d .claude/skills rm -f skills.zip ``` -------------------------------- ### Render infographics programmatically Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/infographic-syntax.md Examples for standard rendering and streaming updates for dynamic content. ```ts import {Infographic} from '@antv/infographic'; const instance = new Infographic({ container: '#container', width: 900, height: 540, padding: 24, }); const syntaxText = ` infographic list-row-horizontal-icon-arrow data title 客户增长引擎 desc 多渠道触达与复购提升 lists - label 线索获取 value 18.6 desc 渠道投放与内容获客 icon company-021_v1_lineal - label 转化提效 value 12.4 desc 线索评分与自动跟进 icon antenna-bars-5_v1_lineal `; instance.render(syntaxText); ``` ```ts import {Infographic} from '@antv/infographic'; const instance = new Infographic({ container: '#container', width: 900, height: 540, padding: 24, }); const chunks = [ 'infographic list-row-horizontal-icon-arrow\n', 'data\n title 客户增长引擎\n desc 多渠道触达与复购提升\n', ' lists\n - label 线索获取\n value 18.6\n', ' desc 渠道投放与内容获客\n icon company-021_v1_lineal\n', ]; let buffer = ''; for (const chunk of chunks) { buffer += chunk; instance.render(buffer); } ``` -------------------------------- ### Configure Sequence Data Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/data.en.md Example of sequence data emphasizing order using the sequences field. ```syntax data title Iteration Flow desc A simple sequence example sequences - label Requirements Review - label Development - label Integration Testing order asc ``` -------------------------------- ### Support Multiple Resource Formats Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.md Adapt resource loading strategies based on the resource type and format. This example handles image base64 encoding and SVG loading, differentiating based on configuration. ```typescript import { registerResourceLoader, loadSVGResource, loadImageBase64Resource, } from '@antv/infographic'; registerResourceLoader(async (config) => { const {data, scene = 'icon', format} = config; if (typeof data === 'string' && data.startsWith('img:')) { const resourceId = data.slice(4); const imageBase64 = await fetchImageAsBase64(resourceId); return loadImageBase64Resource(imageBase64); } // 其它场景按 SVG 处理,可用 scene 做区分 const svg = scene === 'illus' ? await fetchIllustration(data) : await fetchIcon(data, format); return loadSVGResource(svg); }); ``` -------------------------------- ### Configure Plugins and Interactions Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/editor.en.md Instantiate and pass arrays of plugins and interactions to the Infographic constructor to customize editor behavior. This example shows how to configure multiple built-in components. ```javascript import { Infographic, EditBar, ResizeElement, DragCanvas, ClickSelect, BrushSelect, DragElement, DblClickEditText, HotkeyHistory, ZoomWheel, SelectHighlight, } from '@antv/infographic'; const infographic = new Infographic({ container: '#container', editable: true, plugins: [new EditBar(), new ResizeElement()], interactions: [ new DragCanvas({ trigger: ['Space'] }), new DblClickEditText(), new BrushSelect(), new ClickSelect(), new DragElement(), new HotkeyHistory(), new ZoomWheel(), new SelectHighlight(), ], }); ``` -------------------------------- ### Configure List Data Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/data.en.md Example of one-dimensional list data using the infographic syntax. ```syntax data title Infographic Title desc This is the description text of the infographic items - icon https://example.com/icon1.svg label Data Item 1 desc This is the description of data item 1 - icon https://example.com/icon2.svg label Data Item 2 desc This is the description of data item 2 ``` -------------------------------- ### Get Infographic Options Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-api.en.md Retrieves the current configuration object held by the instance. ```typescript getOptions(): Partial ``` -------------------------------- ### Configure Relation Data Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/data.en.md Example of relation data defining nodes and edges between them. ```syntax data title System Relations nodes - id api label API - id db label DB relations - from api to db direction forward ``` -------------------------------- ### Configure Comparison Data Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/data.en.md Example of comparison data using the compares field for side-by-side values. ```syntax data title Plan Comparison compares - label Plan A value 80 - label Plan B value 65 ``` -------------------------------- ### Configure Hierarchical Data Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/data.en.md Example of hierarchical data using root and children nodes. ```syntax data title Infographic Title desc This is the description text of the infographic root label Level 1 Item 1 children - label Level 2 Item 1-1 - label Level 2 Item 1-2 ``` -------------------------------- ### Configure Statistics Data Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/data.en.md Example of statistics data using the values field for numeric entries. ```syntax data title Traffic Sources values - label Search value 62 - label Direct value 38 ``` -------------------------------- ### Define relational data Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/infographic-syntax.md Examples of defining nodes and relations using YAML, Mermaid-style syntax, and shorthand edge definitions. ```infographic infographic relation-dagre-flow-tb-simple-circle-node data title Relation Graph nodes - label Node A - id B label Node B relations - from Node A to B ``` ```infographic infographic relation-dagre-flow-tb-simple-circle-node data nodes - id A label Node A - id B label Node B - id C label Node C relations A -> B A <- C A -> B -> C -> A ``` ```infographic infographic relation-dagre-flow-tb-simple-circle-node data relations A - The Edge Between A and B -> B B -> C[Label of C] C -->|The Edge Between C and D| D ``` -------------------------------- ### Define an infographic with list-row-horizontal-icon-arrow template Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/infographic-syntax.en.md Example of a full infographic definition using the list-row-horizontal-icon-arrow template. ```infographic infographic list-row-horizontal-icon-arrow data title Customer Growth Engine desc Multi-channel reach and repeat purchases lists - label Lead Acquisition value 18.6 desc Channel investment and content marketing icon mdi/rocket-launch - label Conversion Optimization value 12.4 desc Lead scoring and automated follow-ups icon mdi/progress-check - label Loyalty Boost value 9.8 desc Membership programs and benefits icon mdi/account-sync - label Brand Advocacy value 6.2 desc Community rewards and referral loops icon mdi/account-group - label Customer Success value 7.1 desc Training support and activation icon mdi/book-open-page-variant - label Product Growth value 10.2 desc Trial conversion and feature nudges icon mdi/chart-line - label Data Insight value 8.5 desc Key metrics and attribution analysis icon mdi/chart-areaspline - label Ecosystem value 5.4 desc Co-marketing and resource swaps icon mdi/handshake ``` ```infographic infographic list-row-horizontal-icon-arrow data title Customer Growth Engine desc Multi-channel reach and repeat purchases lists - label Lead Acquisition value 18.6 desc Channel investment and content marketing icon company-021_v1_lineal - label Conversion Optimization value 12.4 desc Lead scoring and automated follow-ups icon antenna-bars-5_v1_lineal ``` -------------------------------- ### List All Registered Theme Names Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-exports.en.md Use `getThemes` to get an array of names for all available registered themes. ```typescript function getThemes(): string[]; ``` -------------------------------- ### Example Structure Registration Source: https://github.com/antvis/infographic/blob/main/skills/infographic-structure-creator/references/structure-prompt.md Demonstrates how to register a custom structure component using `registerStructure`. It includes necessary imports for types, components, and utilities, defines a `BaseStructureProps` interface with custom props, and implements the component logic. The `composites` array must accurately list all used components. ```tsx import type { ComponentType, JSXElement } from '../../jsx'; import { getElementBounds, Group } from '../../jsx'; import { BtnAdd, BtnRemove, BtnsGroup, ItemsGroup } from '../components'; import { FlexLayout } from '../layouts'; import { registerStructure } from './registry'; import type { BaseStructureProps } from './types'; export interface ExampleProps extends BaseStructureProps { gap?: number; } export const Example: ComponentType = (props) => { // 组件实现 }; registerStructure('example', { component: Example, composites: ['title', 'item'], // 根据实际使用的组件填写 }); ``` -------------------------------- ### Get a Registered Theme Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-exports.en.md Use `getTheme` to retrieve a theme configuration by its name. Returns `undefined` if the theme is not found. ```typescript function getTheme(name: string): ThemeConfig | undefined; ``` -------------------------------- ### Registering a Single Resource Loader for Multiple Types Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.en.md Handle all resource types within a single `registerResourceLoader` call to prevent previous loaders from being overridden. This example shows how to load icons, illustrations, and base64 encoded images. ```typescript registerResourceLoader(async (config) => { if (config.scene === 'icon') { return await loadIcon(config.data); } if (config.scene === 'illus') { return await loadIllus(config.data); } if (typeof config.data === 'string' && config.data.startsWith('img:')) { return await loadImageBase64Resource(await fetchImageAsBase64(config.data.slice(4))); } return null; }); ``` -------------------------------- ### Customize Infographic Styles Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/theme.en.md Use the `theme` configuration to adjust styles for specific infographic parts. This example sets a dark background, applies a custom font for global text, and changes the fill color for data item labels. ```syntax infographic list-row-horizontal-icon-arrow theme dark colorBg #1F1F1F base text font-family 851tegakizatsu item label fill #FF356A data lists - label Step 1 desc Start icon mdi/rocket-launch - label Step 2 desc In Progress icon mdi/progress-clock - label Step 3 desc Complete icon mdi/trophy ``` -------------------------------- ### Configure theme using dotted paths and blocks Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/infographic-syntax.en.md Demonstrates equivalent ways to set theme properties using dotted keys or nested indentation. ```infographic theme.base.text.fill #fff ``` ```infographic theme base text fill #fff ``` ```infographic theme base shape stroke #654321 base.text.fill #123456 ``` -------------------------------- ### Constructor - Create Infographic Instance Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-api.md Initializes a new Infographic instance using either a syntax string or a configuration object. ```APIDOC ## Constructor ### Description Creates a new instance of the Infographic class. ### Parameters #### Request Body - **options** (string | Partial) - Required - Either an infographic syntax string or a configuration object. ### Request Example ```typescript const infographic = new Infographic({ theme: 'dark' }); ``` ``` -------------------------------- ### List All Registered Palettes Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-exports.en.md Use `getPalettes` to get an array of all registered palettes. ```typescript function getPalettes(): Palette[]; ``` -------------------------------- ### Initialize and Render Infographic Source: https://github.com/antvis/infographic/blob/main/README.md Create an Infographic instance and render a template using the declarative syntax. ```ts import { Infographic } from '@antv/infographic'; const infographic = new Infographic({ container: '#container', width: '100%', height: '100%', editable: true, }); infographic.render(` infographic list-row-simple-horizontal-arrow data lists - label Step 1 desc Start - label Step 2 desc In Progress - label Step 3 desc Complete `); ``` -------------------------------- ### Register a simple custom resource loader Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.en.md Demonstrates fetching icons and illustrations from external URLs based on the scene type. ```javascript import {registerResourceLoader, loadSVGResource} from '@antv/infographic'; // Register the resource loader registerResourceLoader(async (config) => { const {scene = 'icon', data} = config; // scene distinguishes icon / illustration // Parse the resource ID (feel free to design your own protocol; here we assume data is the ID) let url; if (scene === 'icon') { url = `https://api.iconify.design/${data}.svg`; } else { url = `https://raw.githubusercontent.com/balazser/undraw-svg-collection/refs/heads/main/svgs/${data}.svg`; } // Fetch the resource const response = await fetch(url); const svgString = await response.text(); // Convert to a framework-friendly resource object return loadSVGResource(svgString); }); ``` -------------------------------- ### Render Infographic Syntax Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/infographic-syntax.en.md Initialize an Infographic instance and render the provided syntax string. Ensure the container element exists and has dimensions. ```typescript import {Infographic} from '@antv/infographic'; const instance = new Infographic({ container: '#container', width: 900, height: 540, padding: 24, }); const syntaxText = ` infographic list-row-horizontal-icon-arrow data title Customer Growth Engine desc Multi-channel reach and repeat purchases lists - label Lead Acquisition value 18.6 desc Channel investment and content marketing icon company-021_v1_lineal - label Conversion Optimization value 12.4 desc Lead scoring and automated follow-ups icon antenna-bars-5_v1_lineal `; instance.render(syntaxText); ``` -------------------------------- ### Get Theme Colors Source: https://github.com/antvis/infographic/blob/main/skills/infographic-structure-creator/references/structure-prompt.md Retrieves theme configuration colors, optionally with custom overrides. ```tsx const themeColors = getThemeColors(options.themeConfig); // 或自定义配置 const themeColors = getThemeColors( { colorPrimary: '#FF356A', colorBg: '#ffffff', }, options, ); // 返回包含 colorText, colorPrimaryBg 等的主题对象 ``` -------------------------------- ### Apply a Preset Theme Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/infographic-syntax.en.md Switch to a predefined theme by specifying its name. This is the simplest way to apply a consistent style. ```infographic theme ``` -------------------------------- ### Configure themes Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/infographic-syntax.md Apply pre-defined themes or customize colors, palettes, and styles. ```infographic theme ``` ```infographic theme colorBg #0b1220 colorPrimary #ff5a5f palette #ff5a5f #1fb6ff #13ce66 stylize rough roughness 0.3 ``` -------------------------------- ### 配置资源数据结构 Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/resources.md 定义数据项中 icon 和 illus 属性的配置结构。 ```syntax data items - icon illus ``` -------------------------------- ### Register and Use Custom Theme Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-theme.en.md Register a theme for reuse with `registerTheme` and then apply it using `theme my-theme` syntax, allowing for further overrides. ```javascript import {registerTheme} from '@antv/infographic'; registerTheme('my-theme', { // Theme configuration options }); ``` ```syntax infographic list-row-simple-horizontal-arrow theme my-theme colorPrimary #FF356A # Other override configuration options... ``` -------------------------------- ### Implement Uniform Resource Protocol Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.md Adopt a consistent resource protocol format across the project for uniformity. Demonstrates using ID or 'ref' protocols, and an object format with explicit source, format, and data fields. ```typescript // 统一使用 ID 或 ref 协议 icon: 'ref:remote:https://example.com/star.svg' illus: 'chart-1' // 或使用对象格式,source/format 自描述 icon: { source: 'remote', format: 'svg', data: 'https://example.com/star.svg' } illus: { source: 'inline', format: 'svg', data: '...' } ``` -------------------------------- ### Rendering Stage Definition and Example Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/jsx.en.md The render function converts a processed element tree into an SVG string. ```typescript function render(element: ProcessedElement, context: RenderContext): string; ``` ```tsx // Processed element { type: 'Rect', props: { width: 100, height: 50, fill: 'blue' } } // Rendered SVG ``` -------------------------------- ### Using Theme Colors Source: https://github.com/antvis/infographic/blob/main/skills/infographic-item-creator/references/item-prompt.md Illustrates how to apply theme colors to elements for consistent branding and visual appearance. This covers primary color, background, main text, secondary text, and white. ```typescript // 主色调 fill={themeColors.colorPrimary} // 背景色 fill={themeColors.colorPrimaryBg} // 主要文本 fill={themeColors.colorText} // 次要文本 fill={themeColors.colorTextSecondary} // 白色(常用于深色背景上的图标/文字) fill={themeColors.colorWhite} ``` -------------------------------- ### 配置标题样式与数据 Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/design.md 通过 options.design.title 定义标题样式,并通过 options.data 传入具体文案。 ```syntax design title default align-horizontal left desc-line-number 2 # 其他标题设计配置项... # 其他设计配置项... data title 信息图标题 desc 这是信息图的描述文本 # 其他数据... ``` -------------------------------- ### Get Registered Template Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-exports.en.md Retrieve a template configuration by its registered type. Returns undefined if the type is not found. ```typescript function getTemplate(type: string): TemplateOptions | undefined; ``` -------------------------------- ### Create Infographic Instance Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-api.md Import and instantiate the `Infographic` class. The constructor accepts either a syntax string or partial `InfographicOptions`. ```typescript import {Infographic} from '@antv/infographic'; const infographic = new Infographic({ // 信息图配置 }); const syntax = ` infographic data title 标题 items - label 标签1 - label 标签2 `; // 直接渲染信息图语法 infographic.render(syntax); ``` -------------------------------- ### List All Registered Structure Types Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-exports.en.md Use `getStructures` to get an array of all currently registered structure type names. ```typescript function getStructures(): string[]; ``` -------------------------------- ### Infographic Rendering with Asynchronous Loading Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.en.md Initialize an Infographic instance and render content. Resource fetching occurs in parallel and does not block rendering, meaning slow resources might appear with a delay. ```typescript const infographic = new Infographic({ // other configuration... }); infographic.render(` data items - icon 1 label Data 1 - icon 2 label Data 2 - icon 3 label Data 3 `); ``` -------------------------------- ### Get Font Configuration Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-exports.en.md Use `getFont` to retrieve the configuration for a specific font by name. Returns `null` if the font is not registered. ```typescript function getFont(font: string): Font | null; ``` -------------------------------- ### Instantiate Infographic Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-api.en.md Constructor for creating an Infographic instance using either a syntax string or a configuration object. ```ts constructor (options: string | Partial): Infographic; ``` -------------------------------- ### Use in HTML via CDN Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/index.en.md Include the library directly in an HTML file using a script tag. ```html Infographic Demo
``` -------------------------------- ### Retrieve a Registered Item Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-exports.en.md Use `getItem` to get the definition for a specific item type. Returns `undefined` if the item is not registered. ```typescript function getItem(type: string): Item | undefined; ``` -------------------------------- ### Configure Primary and Background Colors Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/theme.en.md Use colorPrimary and colorBg to set the base colors for decorative elements and the infographic background. ```syntax infographic list-row-simple-horizontal-arrow data lists - label Step 1 desc Start - label Step 2 desc In Progress - label Step 3 desc Complete ``` ```syntax infographic list-row-simple-horizontal-arrow theme dark colorPrimary #61DDAA colorBg #1F1F1F data lists - label Step 1 desc Start - label Step 2 desc In Progress - label Step 3 desc Complete ``` -------------------------------- ### SVG Resource Configuration via Data URI Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/resources.en.md Configures SVG resources using the Data URI format, starting with 'data:image/svg+xml,'. ```syntax data items - icon data:image/svg+xml,... ``` -------------------------------- ### Processing Stage Definition and Example Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/jsx.en.md The processElement function converts JSX trees into renderable element trees. It handles component expansion, fragments, and layout execution. ```typescript function processElement( element: JSXElement, context: RenderContext ): ProcessedElement; ``` ```tsx // Input JSX // Processed output { type: 'Group', props: { ... }, children: [ { type: 'Rect', props: { width: 100, height: 50 }, children: [] } ] } ``` -------------------------------- ### Preload Resources Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.en.md Extract and fetch all required resources before initializing the Infographic instance. ```typescript import {Infographic} from '@antv/infographic'; function extractResourceEntries(data: Data): Array<{scene: 'icon' | 'illus'; id: string}> { const entries: Array<{scene: 'icon' | 'illus'; id: string}> = []; data.items.forEach((item) => { if (item.icon) entries.push({scene: 'icon', id: item.icon as string}); if (item.illus) entries.push({scene: 'illus', id: item.illus as string}); }); return entries; } async function preloadResources(data: Data) { const entries = extractResourceEntries(data); await Promise.all(entries.map(({scene, id}) => fetchFromYourServer(scene, id))); } const data = { items: [ {icon: '1', /** ... */}, {icon: '2', /** ... */}, {icon: '3', /** ... */}, ], }; await preloadResources(data); const infographic = new Infographic({ // other configuration... }); infographic.render(` infographic list-row-horizontal-icon-arrow data title Preload Example items - icon 1 label Data 1 - icon 2 label Data 2 - icon 3 label Data 3 `); ``` -------------------------------- ### View Infographic Item Creator Skill Reference Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-items.en.md View the content of the item-prompt.md skill reference file to manually paste into an AI chat. This allows for direct interaction with the skill's definitions and templates. ```bash cat skills/infographic-item-creator/references/item-prompt.md ``` -------------------------------- ### Handling Horizontal and Vertical Positioning Source: https://github.com/antvis/infographic/blob/main/skills/infographic-item-creator/references/item-prompt.md Examples for adapting to 'positionH' and 'positionV' design requirements for alignment. This includes calculating X and Y coordinates for elements and setting text alignment based on positioning. ```typescript // positionH 处理示例 const iconX = positionH === 'flipped' ? width - iconSize // 右对齐 : positionH === 'center' ? (width - iconSize) / 2 // 居中 : 0; // 默认左对齐 // positionV 处理示例 const iconY = positionV === 'middle' ? (height - iconSize) / 2 : positionV === 'flipped' ? height - iconSize : 0; // 文本对齐方式 const textAlign = positionH === 'flipped' ? 'right' : positionH === 'center' ? 'center' : 'left'; ``` -------------------------------- ### Implement a full custom resource loader Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.en.md A complete implementation including a custom fetch function and usage within an Infographic instance. ```typescript import { registerResourceLoader, loadSVGResource, Infographic, } from '@antv/infographic'; // Function that fetches resources from your own server async function fetchFromYourServer(scene: string, id: string): Promise { const response = await fetch( `https://your-api.com/assets?type=${scene}&id=${id}` ); return await response.text(); } // Register the loader registerResourceLoader(async (config) => { const {data, scene = 'icon'} = config; // Parse the resource ID (here data is the ID; you can extend the protocol) const id = data; // Load from your server const svgString = await fetchFromYourServer(scene, id); // Convert to SVG resource object return loadSVGResource(svgString); }); // Usage const infographic = new Infographic({ // other configuration... }); infographic.render(` data items - icon star # Use the custom protocol with scene=icon label Feature 1 desc Using the custom resource loader illus chart-growth # Use the custom protocol with scene=illus `); ``` -------------------------------- ### 配置信息图结构 Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/design.md 通过 options.design.structure 设置信息图的布局骨架。 ```syntax design structure list-row # 其他结构配置项... # 其他配置项... ``` -------------------------------- ### Use Infographic Item Creator Skill via CLI Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-items.en.md Use the infographic-item-creator skill to build a card-style item with icon and value via AI. The AI will generate the item file and update exports. ```bash Please use skill: infographic-item-creator to build a card-style item with icon and value. ``` -------------------------------- ### Sequential Structure with Decorative Arrows Source: https://github.com/antvis/infographic/blob/main/skills/infographic-structure-creator/references/structure-prompt.md Creates a sequential horizontal flow with decorative arrows connecting adjacent items. Arrows are rendered in a separate group before the main items group. Uses `getColorPrimary` for theme color and positions arrows between items. Suitable for process flows or step-by-step guides. ```tsx const colorPrimary = getColorPrimary(options); items.forEach((item, index) => { if (index < items.length - 1) { decorElements.push( , ); } }); return ( {decorElements} {itemElements} {btnElements} ); ``` -------------------------------- ### Clone the AntV Infographic Repository Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/contributing.md Use this command to clone the project repository from GitHub to your local machine. ```bash git clone git@github.com:antvis/infographic.git ``` -------------------------------- ### Layout - Using Layouts Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/jsx.en.md Demonstrates how to use custom layout components within JSX to arrange child elements. ```APIDOC ## Layout - Using Layouts ```tsx // Result: Three rectangles stacked vertically with 20px spacing ``` ### Layout Execution Flow 1. Renderer detects the layout symbol. 2. Collects children. 3. Executes the layout function with `children` and props. 4. Receives the position-adjusted children. 5. Continues rendering the new array. - Layout functions can modify positions, sizes, etc. - Use `getElementBounds` to measure children. - Nested layouts are supported. - Layout runs during the processing stage. ``` -------------------------------- ### ItemOptions Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-types.en.md Optional configuration for items, equivalent to `Partial`. ```APIDOC ## ItemOptions Optional configuration for items, equivalent to `Partial`. ```ts type ItemOptions = Partial; ``` ``` -------------------------------- ### 对象形式资源配置 Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/resources.md 直接提供 ResourceConfig 对象以进行更精细的资源控制。 ```typescript interface ResourceConfig { source: 'inline' | 'remote' | 'search' | 'custom'; format?: 'svg' | 'image' | string; // 兜底格式提示,优先使用真实 Content-Type/内容判定 encoding?: 'raw' | 'data-uri' | 'base64'; data: string; // inline 内容 / URL / 搜索词 / 自定义 payload scene?: 'icon' | 'illus'; // 可选,框架会自动填充当前字段的场景 [key: string]: any; // 自定义扩展 } ``` -------------------------------- ### Use in Vue 3 Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/index.en.md Initialize the infographic within the onMounted lifecycle hook. ```vue ``` -------------------------------- ### Infographic Class Constructor Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-api.en.md Instantiate the Infographic class to create a new infographic instance. The constructor accepts either an infographic syntax string or a partial InfographicOptions object. ```APIDOC ## Constructor Infographic ### Description Creates an instance of the Infographic class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (string | Partial) - Required - Either an infographic syntax string or a JSON object conforming to InfographicOptions. ### Request Example ```json { "options": "infographic MyInfographic\ndata\n title Title\n items\n - label Item 1\n - label Item 2" } ``` ### Response #### Success Response (200) - **Infographic** (object) - An instance of the Infographic class. #### Response Example ```json { "instance": "[Infographic Instance]" } ``` ``` -------------------------------- ### Basic JSX Usage Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/jsx.en.md Demonstrates how to enable the JSX transform and render a simple component to an SVG string. ```APIDOC ## Basic Usage At the top of your file, add the pragma `/** @jsxImportSource @antv/infographic */` to enable the JSX transform. The snippet below defines a simple `Node` component with a rectangle and text, then uses [renderSVG](/reference/jsx-utils#render-svg) to convert it into an SVG string. ```jsx /** @jsxImportSource @antv/infographic */ import {renderSVG, Rect, Text, Group} from '@antv/infographic'; const Node = () => ( Hello World ); const svgString = renderSVG(); console.log(svgString); ``` ``` -------------------------------- ### Support Multiple Resource Formats Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.en.md Branch logic within the loader to handle different resource types like images and illustrations. ```typescript import { registerResourceLoader, loadSVGResource, loadImageBase64Resource, } from '@antv/infographic'; registerResourceLoader(async (config) => { const {data, scene = 'icon', format} = config; if (typeof data === 'string' && data.startsWith('img:')) { const resourceId = data.slice(4); const imageBase64 = await fetchImageAsBase64(resourceId); return loadImageBase64Resource(imageBase64); } const svg = scene === 'illus' ? await fetchIllustration(data) : await fetchIcon(data, format); return loadSVGResource(svg); }); ``` -------------------------------- ### Instantiate and render an infographic Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/index.en.md Basic usage for rendering a list-type infographic in a JavaScript environment. ```js import {Infographic} from '@antv/infographic'; const infographic = new Infographic({ container: '#container', width: '100%', height: '100%', }); const syntax = `infographic list-row-simple-horizontal-arrow data lists - label Step 1 desc Start - label Step 2 desc In Progress - label Step 3 desc Complete`; infographic.render(syntax); ``` -------------------------------- ### Configure Structure and Items Directly Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/template.en.md Use this syntax to directly configure the structure and items of an infographic without registering a template. ```syntax design structure list-row item simple ``` -------------------------------- ### IInteraction Interface Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-types.en.md Interface for interaction handlers like selection and dragging. ```APIDOC ## IInteraction ### Description Interface for interaction handlers (selection, dragging, etc.). ### Interface Definition ```ts interface IInteraction { name: string; init(options: {emitter: any; editor: any; commander: any; interaction: any}): void; destroy(): void; } ``` ``` -------------------------------- ### Implement Unified Resource Protocol Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-resource-loader.en.md Maintain a consistent structure for resource definitions across the application. ```typescript icon: 'ref:remote:https://example.com/star.svg'; illus: 'chart-1'; // Or use object payloads icon: { source: 'remote', format: 'svg', data: 'https://example.com/star.svg' }; illus: { source: 'inline', format: 'svg', data: '...' }; ``` -------------------------------- ### render() Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-api.md Renders the infographic based on the provided configuration or syntax string. ```APIDOC ## render() ### Description Renders the infographic instance. If options are provided, it uses them to render; otherwise, it uses the existing configuration. ### Parameters #### Request Body - **options** (string | Partial) - Optional - The syntax string or configuration object to render. ### Request Example ```typescript infographic.render('infographic template-name...'); ``` ``` -------------------------------- ### Instance Methods Source: https://github.com/antvis/infographic/blob/main/site/src/content/reference/infographic-api.en.md Methods available on an Infographic instance for managing its state and rendering. ```APIDOC ## GET /infographic/options ### Description Retrieves the current configuration of the infographic instance. ### Method GET ### Endpoint /infographic/options ### Parameters None ### Request Example None ### Response #### Success Response (200) - **options** (Partial) - The current configuration object of the infographic. #### Response Example ```json { "options": { "theme": "light", "title": "Example Infographic" } } ``` ``` ```APIDOC ## POST /infographic/render ### Description Renders the infographic using the provided syntax or configuration. ### Method POST ### Endpoint /infographic/render ### Parameters #### Request Body - **options** (string | Partial) - Optional - The infographic syntax string or configuration object to render. ### Request Example ```json { "options": "infographic MyInfographic\n... } ``` ### Response #### Success Response (200) - **void** - This method does not return a value upon success. #### Response Example None ``` ```APIDOC ## PUT /infographic/update ### Description Merges new syntax or options into the current infographic configuration. ### Method PUT ### Endpoint /infographic/update ### Parameters #### Request Body - **options** (string | Partial) - Required - The new syntax string or configuration object to merge. ### Request Example ```json { "options": { "theme": "dark" } } ``` ### Response #### Success Response (200) - **void** - This method does not return a value upon success. #### Response Example None ``` ```APIDOC ## POST /infographic/compose ### Description Creates a pre-rendered template from parsed infographic options. ### Method POST ### Endpoint /infographic/compose ### Parameters #### Request Body - **parsedOptions** (ParsedInfographicOptions) - Required - The parsed infographic options. ### Request Example ```json { "parsedOptions": { "type": "infographic", "data": {}, "title": "Example" } } ``` ### Response #### Success Response (200) - **svgElement** (SVGSVGElement) - The composed SVG element. #### Response Example ```json { "svgElement": "..." } ``` ``` ```APIDOC ## GET /infographic/types ### Description Generates the TypeScript type definitions required for the current infographic. ### Method GET ### Endpoint /infographic/types ### Parameters None ### Request Example None ### Response #### Success Response (200) - **types** (string) - A string containing the TypeScript type definitions. #### Response Example ```json { "types": "export interface MyOptions { ... }" } ``` ``` ```APIDOC ## POST /infographic/toDataURL ### Description Exports the infographic as an image and returns a `data:` URL string. Must be called in the browser after rendering. ### Method POST ### Endpoint /infographic/toDataURL ### Parameters #### Request Body - **options** (ExportOptions) - Optional - Configuration for exporting. Accepts `{type: 'svg'; embedResources?: boolean; removeIds?: boolean}` or `{type: 'png'; dpr?: number}`. Defaults to PNG. ### Request Example ```json { "options": { "type": "svg", "embedResources": true } } ``` ### Response #### Success Response (200) - **dataUrl** (string) - The `data:` URL string of the exported infographic. #### Response Example ```json { "dataUrl": "data:image/png;base64,iVBORw0KGgo..." } ``` ``` ```APIDOC ## POST /infographic/on ### Description Registers an event listener for the infographic instance. ### Method POST ### Endpoint /infographic/on ### Parameters #### Request Body - **event** (string) - Required - The name of the event to listen for (e.g., 'warning', 'error', 'rendered', 'destroyed'). - **listener** ((...args: any[]) => void) - Required - The callback function to execute when the event is triggered. ### Request Example ```json { "event": "rendered", "listener": "() => console.log('Infographic rendered')" } ``` ### Response #### Success Response (200) - **void** - This method does not return a value upon success. #### Response Example None ``` ```APIDOC ## DELETE /infographic/off ### Description Removes an event listener from the infographic instance. ### Method DELETE ### Endpoint /infographic/off ### Parameters #### Request Body - **event** (string) - Required - The name of the event to remove the listener from. - **listener** ((...args: any[]) => void) - Required - The specific listener function to remove. ### Request Example ```json { "event": "rendered", "listener": "() => console.log('Infographic rendered')" } ``` ### Response #### Success Response (200) - **void** - This method does not return a value upon success. #### Response Example None ``` ```APIDOC ## DELETE /infographic/destroy ### Description Destroys the infographic instance, clearing its output and cleaning up resources. ### Method DELETE ### Endpoint /infographic/destroy ### Parameters None ### Request Example None ### Response #### Success Response (200) - **void** - This method does not return a value upon success. #### Response Example None ``` -------------------------------- ### Configure Theme Directly Source: https://github.com/antvis/infographic/blob/main/site/src/content/learn/custom-theme.en.md Pass theme configuration options directly when creating an infographic. Use this for simple, one-off theme adjustments. ```javascript const infographic = new Infographic({ // Other configuration options... }); infographic.render(` theme colorPrimary #FF356A colorBg #FFFFFF # Other theme configuration options... `); ```