### Clone and Install S2 Project Source: https://github.com/antvis/s2/blob/next/packages/s2-core/README.en-US.md Clone the S2 repository and install dependencies using pnpm. This is the initial setup step for development. ```bash git clone git@github.com:antvis/S2.git cd S2 pnpm install # or pnpm bootstrap ``` -------------------------------- ### Start S2 Website Source: https://github.com/antvis/s2/blob/next/packages/s2-core/README.en-US.md Command to start the S2 project website. This is useful for previewing documentation and examples. ```bash # start the website pnpm site:start ``` -------------------------------- ### Run Examples Source: https://github.com/antvis/s2/blob/next/packages/s2-ssr/README.md Execute the example Node.js script to test the s2-ssr functionality. ```bash node examples/grid-english.js ``` -------------------------------- ### Install @antv/s2-react-components Source: https://github.com/antvis/s2/blob/next/packages/s2-react-components/README.md Install the library using pnpm, npm, or yarn. ```bash $ pnpm add @antv/s2-react-components # npm install @antv/s2-react-components --save # yarn add @antv/s2-react-components ``` -------------------------------- ### Install @antv/s2-react Source: https://github.com/antvis/s2/blob/next/packages/s2-react/README.md Install the library using pnpm, npm, or yarn. ```bash $ pnpm add @antv/s2-react # npm install @antv/s2-react --save # yarn add @antv/s2-react ``` -------------------------------- ### Start Local S2 Website Source: https://github.com/antvis/s2/blob/next/CONTRIBUTING.en-US.md Starts the local development server for the AntV S2 website. Useful for previewing documentation and examples. ```bash pnpm site:start ``` -------------------------------- ### Clone and Install S2 Dependencies Source: https://github.com/antvis/s2/blob/next/s2-site/common/development.en.md Clone the S2 repository, checkout the 2.x branch, and install dependencies using pnpm. Use `pnpm install` for a standard install or `pnpm bootstrap` for a full bootstrap. ```bash git clone git@github.com:antvis/S2.git cd S2 # 切换到 2.x 分支 git checkout next # 安装依赖 pnpm install # 或者 pnpm bootstrap ``` -------------------------------- ### Install @antv/s2-react Source: https://github.com/antvis/s2/blob/next/s2-site/common/install.en.md Install both the core @antv/s2 library and the @antv/s2-react package for React integration. ```bash npm install @antv/s2 @antv/s2-react --save ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/antvis/s2/blob/next/CONTRIBUTING.en-US.md Installs all necessary dependencies for the project using pnpm. This command should be run after cloning the repository. ```bash pnpm install ``` -------------------------------- ### Install Core @antv/s2 Source: https://github.com/antvis/s2/blob/next/s2-site/common/install.en.md Install the basic @antv/s2 library using your preferred package manager. ```bash # npm $ npm install @antv/s2 --save ``` ```bash # yarn $ yarn add @antv/s2 ``` ```bash # pnpm $ pnpm add @antv/s2 ``` -------------------------------- ### S2 Development Commands Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/contribution.en.md Commands for managing the S2 project locally, including installing dependencies, starting the website, debugging, building, testing, and linting. ```bash pnpm install ``` ```bash pnpm site:start ``` ```bash pnpm core:start ``` ```bash pnpm react:start ``` ```bash pnpm react:playground ``` ```bash pnpm vue:playground ``` ```bash pnpm build ``` ```bash pnpm test ``` ```bash pnpm lint ``` -------------------------------- ### Install @antv/s2-vue Source: https://github.com/antvis/s2/blob/next/packages/s2-vue/README.md Install the package using your preferred package manager. ```bash pnpm add @antv/s2-vue # yarn add @antv/s2-vue # npm install @antv/s2-vue --save ``` -------------------------------- ### Install @antv/s2 and @antv/s2-react-components Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/analysis/introduction.en.md Install the necessary packages for using S2 and its React components. ```bash npm install @antv/s2 @antv/s2-react-components --save # yarn add @antv/s2 @antv/s2-react-components ``` -------------------------------- ### Install @antv/s2-react-components Source: https://github.com/antvis/s2/blob/next/s2-site/common/install.en.md Install @antv/s2, @antv/s2-react-components, antd, and @ant-design/icons for React analysis components. ```bash npm install @antv/s2 @antv/s2-react-components antd @-design/icons --save ``` -------------------------------- ### Install @antv/s2-ssr Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/ssr.en.md Install the @antv/s2-ssr package using npm, pnpm, or yarn. ```bash npm install @antv/s2-ssr # or pnpm add @antv/s2-ssr # or yarn add @antv/s2-ssr ``` -------------------------------- ### Install node-canvas Prerequisites Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/ssr.en.md Install the necessary graphics libraries for node-canvas on macOS or Ubuntu/Debian. ```bash # macOS: brew install pkg-config cairo pango libpng jpeg giflib librsvg # Ubuntu/Debian: sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev ``` -------------------------------- ### List Table Link Jump Configuration and Handler Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/cell-render/link-jump.en.md For list tables, `linkFields` can be applied to `columns`. This example demonstrates the setup for list views, including data, options, event handling, and rendering. ```typescript import { S2Event } from '@antv/s2'; const s2DataConfig = { fields: { columns: ['type', 'price', 'province', 'city'], }, }; const s2Options = { width: 600, height: 600, interaction: { linkFields: ['type', 'price', 'province'], } }; const s2 = new TableSheet(container, s2DataConfig, s2Options); s2.on(S2Event.GLOBAL_LINK_FIELD_JUMP, (data) => { const { key, record } = data; const value = record[key] // Construct your own jump URL location.href = `https://path/to/${key}=${value}}`; }); s2.render(); ``` -------------------------------- ### Start @antv/s2-react Playground Source: https://github.com/antvis/s2/blob/next/CONTRIBUTING.en-US.md Starts the local playground for `@antv/s2-react` using Vite. This allows for interactive testing of the React component. ```bash pnpm react:playground ``` -------------------------------- ### Install G2 Dependency Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/cell-render/chart-with-g2.en.md This command installs version 5.x of G2, which is required for this feature. ```bash pnpm add @antv/g2 ``` -------------------------------- ### Store Get and Set Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/basic-class/store.en.md Demonstrates how to retrieve and store data using the store's get and set methods. ```APIDOC ## Store Operations ### Description Provides methods to manage data within the S2 instance. ### Methods #### `get(key: string): unknown` Retrieves a value associated with the given key from the store. #### `set(key: string, value: unknown): void` Stores a value associated with the given key in the store. ### Usage Examples ```ts // Get a value const value = s2.store.get('someKey'); // Set a value s2.store.set('anotherKey', 'someValue'); ``` ### Available Store Keys and Types | key | illustrate | type | | -------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------- | | scrollX | horizontal scroll offset | `number` | | scrollY | vertical scroll offset | `number` | | rowHeaderScrollX | vertical header scroll offset | `number` | | sortParam | Column header sorting configuration | [SortParam](/en/api/components/sheet-component/#sortparams) | | drillDownIdPathMap | Drill down node id and corresponding generated path addressing path | `Map` | | drillDownNode | current drill-down node | [node](/en/api/basic-class/node) | | drillItemsNum | Control the number of drill-down data | `number` | | interactionStateInfo | Current Interaction Status Information | `number` | | drillDownFieldInLevel| Drill down to node level information | [PartDrillDownInfo[]](#partdrilldowninfo) | | originalDataCfg | Raw Data Configuration | [S2DataConfig](/en/api/general/s2-data-config) | | panelBBox | Visual area wrapping box model | [BBox](/en/api/basic-class/spreadsheet/#bbox) | | activeResizeArea | current resizing region group | [Group](https://g.antv.antgroup.com/api/basic/group) | | valueRanges | conditional format value range | [ValueRanges](#valueranges) | | initColLeafNodes | The column header leaf node when it is first rendered | [Node[]](/en/api/basic-class/node) | | hiddenColumnsDetail | Hidden column header details | [HiddenColumnsInfo[]](#hiddencolumnsinfo) | | lastRenderedColumnFields | The column header configuration of the last render | `string[]` | | resized | Whether to manually adjust the width and height | `boolean` | | visibleActionIcons | The icon cache displayed by hover | `GuiIcon[]` | | lastClickedCell | last clicked cell | `S2CellType` | | initOverscrollBehavior | initial scroll chain state | `'auto' | 'none' | 'contain'` | | sortMethodMap | sort by | `Record` | | [key: string] | Any other field | `unknown` | ## HiddenColumnsInfo ```ts interface HiddenColumnsInfo { // Hidden nodes before the currently displayed sibling node hideColumnNodes: Node[]; // Sibling node corresponding to the expand button of the currently hidden column displaySiblingNode: Node; } ``` ## PartDrillDownInfo ```ts interface PartDrillDownInfo { // Drill down data drillData: RawData[]; // Drill down field drillField: string; } ``` ## ValueRanges ```ts export interface ValueRange { minValue?: number; maxValue?: number; } export type ValueRanges = Record; ``` ``` -------------------------------- ### Install @antv/s2-vue (Discontinued) Source: https://github.com/antvis/s2/blob/next/s2-site/common/install.en.md Install @antv/s2, @antv/s2-vue, and ant-design-vue@3.x. Note that @antv/s2-vue has been discontinued. ```bash npm install @antv/s2 @antv/s2-vue ant-design-vue@3.x --save ``` -------------------------------- ### Install S2 using npm or yarn Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/introduction.en.md Use npm or yarn to install the S2 library in your project. ```bash npm install @antv/s2 # yarn add @antv/s2 ``` -------------------------------- ### Install antd and @ant-design/icons Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/analysis/introduction.en.md Install antd and its icons, which are required as a dependency for React-based analysis components. ```bash npm install antd @ant-design/icons --save # yarn add antd @ant-design/icons --save ``` -------------------------------- ### Install AntV S2 Source: https://github.com/antvis/s2/blob/next/packages/s2-core/README.en-US.md Install the core S2 package using your preferred package manager. ```bash pnpm add @antv/s2 # yarn add @antv/s2 # npm install @antv/s2 --save ``` -------------------------------- ### S2 Options Configuration Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/general/s2-options.en.md An example of how to configure S2 options. ```APIDOC ## S2 Options ### Description Configuration options for S2 tables. ### Parameters #### General Options - **width** (number) - Optional - Default: 600 - Table width. - **height** (number) - Optional - Default: 480 - Table height. - **debug** (boolean) - Optional - Default: false - Whether to enable debug mode. - **hierarchyType** (string) - Optional - Default: "grid" - The display method of row headers. Options: "grid", "tree", "grid-tree". Supports [custom structure](/en/manual/advanced/custom/custom-header). - **showDefaultHeaderActionIcon** (boolean) - Optional - Default: true - Whether to display the default row and column header operation icons. #### Advanced Options - **conditions** ([Conditions](#conditions)) - Optional - Conditional Mode Configuration. - **totals** ([Totals](#totals)) - Optional - Subtotal Total Configuration. - **tooltip** ([Tooltip](#tooltip)) - Optional - Tooltip configuration. - **interaction** ([Interaction](#interaction)) - Optional - Table interaction configuration. - **pagination** ([Pagination](#pagination)) - Optional - Paging configuration. - **frozen** ([Frozen](#frozen)) - Optional - Row and Column Header Freezing Configuration. - **seriesNumber** ([SeriesNumber](#seriesnumber)) - Optional - Series number column configuration. ### Request Example ```ts const s2Options = { width: 600, height: 400, hierarchyType: 'grid' } ``` ``` -------------------------------- ### Start @antv/s2-vue Playground Source: https://github.com/antvis/s2/blob/next/CONTRIBUTING.en-US.md Starts the local playground for `@antv/s2-vue` using Vite. This allows for interactive testing of the Vue component. ```bash pnpm vue:playground ``` -------------------------------- ### Pivot Table Link Jump Configuration and Handler Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/cell-render/link-jump.en.md For pivot tables, `linkFields` can be applied to `rows`. This example shows the full setup including data configuration, options, event listener, and rendering. ```typescript import { S2Event } from '@antv/s2' const s2DataConfig = { fields: { rows: ['province', 'city'], columns: ['type'], values: ['price'], }, }; const s2Options = { width: 600, height: 600, interaction: { linkFields: ['province', 'city'], } }; const s2 = new PivotSheet(container, s2DataConfig, s2Options); s2.on(S2Event.GLOBAL_LINK_FIELD_JUMP, (data) => { const { key, record } = data; const value = record[key] // Construct your own jump URL location.href = `https://path/to/${key}=${value}}`; }); s2.render(); ``` -------------------------------- ### Install @antv/s2-ssr Source: https://github.com/antvis/s2/blob/next/packages/s2-ssr/README.md Install the package using npm or pnpm. Note the dependency on node-canvas and its system requirements. ```bash npm install @antv/s2-ssr # or pnpm add @antv/s2-ssr ``` -------------------------------- ### Filtered and Sorted Data Example Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/extended-reading/data-process/table.en.md Example of data after being filtered by 'city' and then sorted by 'price' in descending order. ```json [ { "price": 3, "province": "Zhejiang", "city": "Hangzhou", "type": "Furniture", "sub_type": "Sofa" }, { "price": 1, "province": "Zhejiang", "city": "Hangzhou", "type": "Furniture", "sub_type": "Table" }, ] ``` -------------------------------- ### Install React or Vue3 versions of AntV S2 Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/getting-started.en.md Install the core @antv/s2 package along with the specific framework package for React or Vue3. ```bash # React $ yarn add @antv/s2 @antv/s2-react # Vue3 $ yarn add @antv/s2 @antv/s2-vue ``` -------------------------------- ### Install AntV S2 with npm Source: https://github.com/antvis/s2/blob/next/README.md Use npm to install the AntV S2 library. This is the standard package manager for Node.js. ```bash npm install @antv/s2 --save ``` -------------------------------- ### Install ant-design-vue for Vue3 Analysis Components Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/getting-started.en.md Install the 'ant-design-vue' library if you plan to use Vue3-based analysis components. Also, import the necessary CSS. ```bash yarn add ant-design-vue ``` -------------------------------- ### S2 Data Configuration Example Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/introduction.en.md This is an example of the data configuration object used by S2. It defines the structure and values for the chart. ```json { "fields": { "rows": ["province", "city"], "columns": ["type"], "values": ["cost"] }, "data": [ { "province": "Zhejiang", "city": "Zhoushan", "type": "Paper", "cost": "20" }, { "province": "Zhejiang", "city": "Zhoushan", "type": "Pen", "cost": "1.7" }, { "province": "Zhejiang", "city": "Zhoushan", "type": "Paper", "cost": "0.12" }, { "province": "Jilin", "city": "Changchun", "type": "Pen", "cost": "10" }, { "province": "Jilin", "city": "Baishan", "type": "Pen", "cost": "9" }, { "province": "Jilin", "city": "Changchun", "type": "Paper", "cost": "3" }, { "province": "Jilin", "city": "Baishan", "type": "Paper", "cost": "1" } ] } ``` -------------------------------- ### Install pnpm Package Manager Source: https://github.com/antvis/s2/blob/next/CONTRIBUTING.en-US.md Installs the pnpm package manager globally. This is a prerequisite for managing project dependencies. ```bash npm i -g pnpm ``` -------------------------------- ### Install antd for React Analysis Components Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/getting-started.en.md Install the 'antd' library and '@ant-design/icons' if you plan to use React-based analysis components like Advanced Sort or Export. ```bash yarn add antd @ant-design/icons ``` -------------------------------- ### Install AntV S2 with yarn Source: https://github.com/antvis/s2/blob/next/README.md Use yarn to install the AntV S2 library. Yarn is another popular JavaScript package manager. ```bash yarn add @antv/s2 ``` -------------------------------- ### Instantiate PivotSheet Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/basic-class/spreadsheet.en.md Demonstrates how to create a new PivotSheet instance. This is the starting point for interacting with pivot table functionalities. ```typescript const s2 = new PivotSheet() s2.isPivotMode() ``` -------------------------------- ### Install AntV S2 with npm or yarn Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/getting-started.en.md Use npm or yarn to add the @antv/s2 package to your project. ```bash # npm $ npm install @antv/s2 # yarn $ yarn add @antv/s2 ``` -------------------------------- ### Example Data Configuration for Mini Charts Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/cell-render/chart-in-cell.en.md Demonstrates how to structure the data configuration to include mini charts, specifying chart type and data points. ```diff const s2DataConfig = { data: [ { - number: 123, + number: { + values: { + type: 'line', + data: [ + { + year: '2017', + value: -368, + }, + ], + encode: { x: 'year', y: 'value' }, + } + }, } ] } ``` -------------------------------- ### Getting the Corresponding Cell by Listening to a Click Event Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/get-cell-data.en.md An example demonstrating how to get cell information by listening to a row header cell click event. ```APIDOC ## Getting the Corresponding Cell by Listening to a Click Event Example with a row header cell click: ```ts import { S2Event } from '@antv/s2' s2.on(S2Event.ROW_CELL_CLICK, (event) => { // Get the cell at the current coordinates from the event target const cell = s2.getCell(event.target) // Get the information for the current cell const meta = cell.getMeta() }) ``` preview Of course, you can get data this way anywhere you have access to an `event`. ``` -------------------------------- ### Vue Drilldown Component Usage Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/components/drill-down.en.md Example of integrating the drill-down component in a Vue application. This snippet illustrates the setup for the SheetComponent with drill-down enabled, suitable for table and perspective modes. ```APIDOC ## Vue drilldown component The drill-down component can only be used in table and perspective mode. ```vue const s2Options = { width: 600, height: 480, hierarchyType: 'tree', }; ``` ​📊 Check out [the Vue version of the drilldown demo](https://codesandbox.io/s/vue-drilldown-demo-8p1lmv?file=/src/App.vue:6385-6396) ``` -------------------------------- ### Import S2 UMD Build in Browser Source: https://github.com/antvis/s2/blob/next/s2-site/common/browser.zh.md Include the S2 UMD build script and initialize a PivotSheet. Access the S2 library via the global `window.S2` variable. ```html ``` -------------------------------- ### Basic Pivot Table Setup Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/basic/sheet-type/pivot-mode.en.md Prepare and render a basic pivot table using PivotSheet. Ensure the container element exists and the data configuration is correctly set. ```html
``` ```typescript import { PivotSheet } from "@antv/s2"; // Prepare the data const data = [ { province: "Zhejiang", city: "Hangzhou", type: "Furniture", sub_type: "Table", price: "1", }, { province: "Zhejiang", city: "Hangzhou", type: "Furniture", sub_type: "Sofa", price: "2", }, { province: "Zhejiang", city: "Hangzhou", type: "Office Supplies", sub_type: "Pen", price: "3", }, { province: "Zhejiang", city: "Hangzhou", type: "Office Supplies", sub_type: "Paper", price: "4", }, ]; // Configure the data const s2DataConfig = { fields: { rows: ["province", "city"], columns: ["type", "sub_type"], values: ["price"] }, data, }; // Add configuration const s2Options = { width: 600, height: 600, }; // Render async function bootstrap() { const container = document.getElementById('container'); const s2 = new PivotSheet(container, s2DataConfig, s2Options); await s2.render(); } bootstrap() ``` -------------------------------- ### Configuration Priority Example Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/custom/custom-collapse-nodes.en.md Demonstrates how to set `collapseFields` and `expandDepth` to null to ensure `collapseAll` takes effect, illustrating the configuration priority: `collapseFields` > `expandDepth` > `collapseAll`. ```typescript const s2Options = { style: { rowCell: { collapseFields: null, // Invalid collapseAll: true, // Effective expandDepth: null, // Invalid }, }, } ``` -------------------------------- ### Basic SSR Spreadsheet Creation and Export Source: https://github.com/antvis/s2/blob/next/packages/s2-ssr/README.md Demonstrates creating a spreadsheet instance with specified options, exporting it to a file, and retrieving it as a buffer or data URL. Remember to clean up the instance after use. ```javascript require.extensions['.css'] = () => {}; require.extensions['.less'] = () => {}; require.extensions['.svg'] = () => {}; const { createSpreadsheet } = require('@antv/s2-ssr'); const options = { sheetType: 'pivot', // or 'table' width: 800, height: 600, dataCfg: { fields: { rows: ['province', 'city'], columns: ['type'], values: ['price'], }, data: [ { province: 'Province A', city: 'City 1', type: 'Type A', price: 100 }, { province: 'Province A', city: 'City 2', type: 'Type B', price: 200 }, ], }, options: { // S2 options }, }; (async () => { const spreadsheet = await createSpreadsheet(options); // Export to file spreadsheet.exportToFile('./output.png'); // Or get as buffer const buffer = spreadsheet.toBuffer(); // Or get as data URL const dataURL = spreadsheet.toDataURL(); // Clean up spreadsheet.destroy(); })(); ``` -------------------------------- ### Build s2-ssr Source: https://github.com/antvis/s2/blob/next/packages/s2-ssr/README.md Navigate to the `s2-ssr` package directory and build the package. ```bash cd packages/s2-ssr pnpm build ``` -------------------------------- ### Build and Run S2 Development Servers Source: https://github.com/antvis/s2/blob/next/s2-site/common/development.en.md Build the S2 project and run specific development servers for core, react, or vue components. Use `pnpm build` to package the project. ```bash # 打包 pnpm build # 调试 s2-core pnpm core:start # 调试 s2-react pnpm react:Playground # 调试 s2-vue pnpm vue:Playground # 本地启动官网 pnpm site:start ``` -------------------------------- ### DataItem Example JSON Source: https://github.com/antvis/s2/blob/next/s2-site/common/view-meta.zh.md Example JSON object representing a DataItem, including numerical and string properties. ```json { "number": 7789, "province": "浙江省", "city": "杭州市", "type": "家具", "sub_type": "桌子" } ``` -------------------------------- ### Configuration Preprocessing API Renaming Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/migration-v2.zh.md In v2, the import paths for configuration preprocessing utilities have changed from `getSafetyOptions` and `getSafetyDataConfig` to `setupOptions` and `setupDataConfig`. ```diff - import { getSafetyOptions, getSafetyDataConfig } from '@antv/s2' + import { setupOptions, setupDataConfig } from '@antv/s2' ``` -------------------------------- ### Filtered Data Example Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/extended-reading/data-process/table.en.md Example of raw data after being filtered by the 'city' field to include only records where the city is 'Hangzhou'. ```json [ { "price": 1, "province": "Zhejiang", "city": "Hangzhou", "type": "Furniture", "sub_type": "Table" }, { "price": 3, "province": "Zhejiang", "city": "Hangzhou", "type": "Furniture", "sub_type": "Sofa" }, ] ``` -------------------------------- ### Build S2 Packages Source: https://github.com/antvis/s2/blob/next/CONTRIBUTING.en-US.md Builds the `@antv/s2`, `@antv/s2-react`, and `@antv/s2-vue` packages. Outputs are generated in `umd`, `esm`, and `lib` directories. ```bash pnpm build ``` -------------------------------- ### ViewMetaData Data Example JSON Source: https://github.com/antvis/s2/blob/next/s2-site/common/view-meta.zh.md Example JSON object for ViewMetaData when it represents basic data, showing city information. ```json { "city": "杭州市" } ``` -------------------------------- ### ExtraData Example JSON Source: https://github.com/antvis/s2/blob/next/s2-site/common/view-meta.zh.md Example JSON object for ExtraData, showing the structure with special keys for extra and value fields. ```json { "$$extra$$": "number", "$$value$$": 7789, } ``` -------------------------------- ### Configure Global Empty Data Placeholder Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/migration-v2.en.md Configure the placeholder for globally empty data states, including an icon and description. ```diff const s2Options = { + placeholder: { + empty: { + icon: 'Empty', + description: 'No Data' + } + } } ``` -------------------------------- ### Install AntV S2 with pnpm Source: https://github.com/antvis/s2/blob/next/README.md Use pnpm to install the AntV S2 library. pnpm is a performant package manager for Node.js. ```bash pnpm add @antv/s2 ``` -------------------------------- ### Window Adaptive with ResizeObserver Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/adaptive.en.md Implement window adaptation by listening to the 'resize' event using ResizeObserver. This updates the table size dynamically when the window resizes. It uses a debounced function to limit render calls. ```typescript import { PivotSheet } from '@antv/s2' import { debounce } from 'lodash' const s2 = new PivotSheet(...) const debounceRender = debounce((width, height) => { s2.changeSheetSize(width, height) s2.render(false) // Do not reload data }, 200) new ResizeObserver(([entry] = []) => { const [size] = entry.borderBoxSize || []; debounceRender(size.inlineSize, size.blockSize) }).observe(document.body); // Monitor window size changes by observing document.body ``` -------------------------------- ### CellData Example JSON Source: https://github.com/antvis/s2/blob/next/s2-site/common/view-meta.zh.md Example JSON object for CellData, illustrating its structure including extraField, raw data, and origin data. ```json { "extraField": "number", "raw": { "number": 7789, "province": "浙江省", "city": "杭州市", "type": "家具", "sub_type": "桌子" }, "$$extra$$": "number", "$$value$$": 7789, "$$origin$$": { "number": 7789, "province": "浙江省", "city": "杭州市", "type": "家具", "sub_type": "桌子" } } ``` -------------------------------- ### Full Copy with @antv/s2 Source: https://github.com/antvis/s2/blob/next/s2-site/common/copy-export.en.md Demonstrates how to get all table data and copy it to the clipboard using `asyncGetAllData` and `copyToClipboard`. Supports synchronous copy. ```typescript import { asyncGetAllData, copyToClipboard } from '@antv/s2' // 1. Get the table data const data = await asyncGetAllData({ sheetInstance: s2, split: '\t', formatOptions: true, // formatOptions: { // formatHeader: true, // formatData: true // }, // Synchronous copy // async: false }); // 2. Write to the clipboard (including both `text/html` and `text/plain`) // Synchronous copy: copyToClipboard(data, false) copyToClipboard(data) .then(() => { console.log('Copy successful') }) .catch(() => { console.log('Copy failed') }) ``` -------------------------------- ### Example Data Configuration for Mini Charts Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/cell-render/chart-in-cell.zh.md Demonstrates how to structure the s2DataConfig to include mini chart specifications for different chart types like line, bar, multi-column text, and bullet charts. ```typescript const s2DataConfig = { fields: { rows: ['province', 'city'], columns: ['type', 'sub_type'], values: ['number'], }, data: [ // 用于绘制 mini 图的数据 { province: '海南省', city: '三亚市', type: '家具', sub_type: '桌子', number: { // 折线图 values: { type: 'line', data: [ { year: '2017', value: -368, }, { year: '2018', value: 368, }, { year: '2019', value: 368, }, { year: '2020', value: 368, }, { year: '2021', value: 268, }, { year: '2022', value: 168, }, ], encode: { x: 'year', y: 'value' }, }, }, }, { province: '海南省', city: '三亚市', type: '家具', sub_type: '沙发', number: { // 柱状图 values: { type: 'bar', data: [ { year: '2017', value: -368, }, { year: '2018', value: 328, }, { year: '2019', value: 38, }, { year: '2020', value: 168, }, { year: '2021', value: 268, }, { year: '2022', value: 368, }, ], encode: { x: 'year', y: 'value' }, }, }, }, { province: '海南省', city: '三亚市', type: '办公用品', sub_type: '笔', number: { // 多列文本 values: [ [3877, -4324, '42%'], [3877, 4324, '-42%'], ], }, }, { province: '海南省', city: '三亚市', type: '办公用品', sub_type: '纸张', number: { // 子弹图 values: { type: 'bullet', measure: 0.3, target: 0.76, }, }, }, ], }; ``` -------------------------------- ### Export CSV Source: https://github.com/antvis/s2/blob/next/s2-site/common/copy-export.zh.md Demonstrates how to export data in CSV format using `asyncGetAllPlainData` and `download`. ```APIDOC ## Export CSV This section details how to export data in CSV format. ### Method `asyncGetAllPlainData` and `download` ### Usage ```ts import { asyncGetAllPlainData, download } from '@antv/s2'; // Get plain text data for export const data = await asyncGetAllPlainData({ sheetInstance: s2, split: ',', formatOptions: true, }); // Download the data as a CSV file download(data, 'filename'); // filename.csv ``` ### API Details #### asyncGetAllPlainData Gets `text/plain` type data for export. **Parameters:** | Parameter | Description | Type | Default Value | Required | |---|---|---|---|---| | sheetInstance | S2 instance | `SpreadSheet` | | ✓ | | split | Delimiter | `string` | | ✓ | | formatOptions | Whether to use `S2DataConfig.Meta` for formatting. Can be a boolean or an object to specify formatting for header and data separately. | `boolean | { formatHeader?: boolean, formatData?: boolean }` | `true` | | | customTransformer | Custom transformer function for data export formatting. | `(transformer: Transformer) => Partial` | | | | async | Whether to perform the operation asynchronously. Falls back to synchronous if `requestIdleCallback` is not supported. | `boolean` | `true` | | #### download Downloads the provided data as a file. **Parameters:** | Parameter | Description | Type | Default Value | Required | |---|---|---|---|---| | data | The data source string. | `string` | | ✓ | | filename | The name of the file to download. | `string` | | ✓ | ### Special Character Handling Rules According to CSV specifications and Excel's handling rules, S2 processes special characters as follows: 1. **Field Wrapping Rule**: Fields containing `,`, ` ``` -------------------------------- ### S2 Rendering with PivotSheet Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/introduction.en.md Demonstrates how to initialize and render a PivotSheet instance. Ensure the container element exists and the S2 library is imported. ```typescript import { PivotSheet } from '@antv/s2'; async function run() { const container = document.getElementById('container'); const s2 = new PivotSheet(container, s2DataConfig, s2Options); await s2.render(); // return Promise } run(); ``` -------------------------------- ### Vue Drill-Down Component Setup Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/components/drill-down.zh.md Basic setup for using the drill-down feature in a Vue SheetComponent. This configuration is for pivot sheet types with tree hierarchy. ```vue const s2Options = { width: 600, height: 480, hierarchyType: 'tree' }; ``` -------------------------------- ### Enable Canvas Build Script Source: https://github.com/antvis/s2/blob/next/packages/s2-ssr/README.md Ensure the 'canvas' package is listed in `onlyBuiltDependencies` in `pnpm-workspace.yaml` to enable its install script. Reinstall dependencies afterwards. ```yaml onlyBuiltDependencies: - canvas ``` -------------------------------- ### MultiData Example JSON Source: https://github.com/antvis/s2/blob/next/s2-site/common/view-meta.zh.md Example JSON structure for MultiData, which supports multi-metric custom cell rendering. It includes formatted values, original values, and a label. ```json { "number": { "originalValues": [1, 2, 3], "values": ["1", "2", "3"] } } ``` -------------------------------- ### LayoutCellMeta Source: https://github.com/antvis/s2/blob/next/s2-site/common/custom/layoutCellMeta.en.md A function that allows for custom cell metadata retrieval. It takes the spreadsheet instance and a function to get cell data, returning a function to get cell meta information. ```APIDOC ## LayoutCellMeta ### Description Custom data function for cell meta. ### Parameters #### Path Parameters - **spreadsheet** (SpreadSheet) - Required - Table class instance, which can access any configuration information - **getCellData** (GetCellMeta) - Required - Get information such as cell data and position ### Type Definition ```ts type GetCellMeta = (rowIndex?: number, colIndex?: number) => ViewMeta; ``` ``` -------------------------------- ### showTooltipWithInfo Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/basic-class/spreadsheet.en.md Displays the tooltip with default information and custom options. ```APIDOC ## showTooltipWithInfo ### Description Display tooltip, and display some default information. ### Signature `(event: CanvasEvent | MouseEvent , data: [TooltipData[]](/en/api/basic-class/base-tooltip#tooltipshowoptions) , options?: [TooltipOptions](/en/api/basic-class/base-tooltip#tooltipshowoptions) ) => void` ``` -------------------------------- ### Getting Merged Cells Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/get-cell-data.en.md Retrieve all merged cells. ```APIDOC ## Getting Merged Cells ```ts s2.facet.getMergedCells() ``` ``` -------------------------------- ### measureTextHeight Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/basic-class/spreadsheet.en.md Gets the measured height of the text in the canvas. ```APIDOC ## measureTextHeight ### Description Get the measured height of the text in the canvas. ### Method `measureTextHeight(text: string, font: TextTheme)` ### Parameters #### Path Parameters - **text** (string) - Required - The text to measure. - **font** (TextTheme) - Required - The font theme to use for measurement. ### Response #### Success Response - **number | null** - The measured height of the text or null if measurement fails. ``` -------------------------------- ### Build and Debug S2 Core Source: https://github.com/antvis/s2/blob/next/packages/s2-core/README.en-US.md Commands to build the entire project or specifically debug the s2-core module. Use these for development and testing. ```bash # build all pnpm build # debug s2-core pnpm core:start ``` -------------------------------- ### measureTextWidth Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/basic-class/spreadsheet.en.md Gets the measured width of the text in the canvas. ```APIDOC ## measureTextWidth ### Description Get the measured width of the text in the canvas. ### Method `measureTextWidth(text: string, font: TextTheme)` ### Parameters #### Path Parameters - **text** (string) - Required - The text to measure. - **font** (TextTheme) - Required - The font theme to use for measurement. ### Response #### Success Response - **number | null** - The measured width of the text or null if measurement fails. ``` -------------------------------- ### measureText Source: https://github.com/antvis/s2/blob/next/s2-site/docs/api/basic-class/spreadsheet.en.md Gets the measurement information of the text in the canvas. ```APIDOC ## measureText ### Description Get the measurement information of the text in the canvas. ### Method `measureText(text: string, font: TextTheme)` ### Parameters #### Path Parameters - **text** (string) - Required - The text to measure. - **font** (TextTheme) - Required - The font theme to use for measurement. ### Response #### Success Response - **TextMetrics | null** - The TextMetrics object or null if measurement fails. ``` -------------------------------- ### Get Row Data on Row Cell Click Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/get-cell-data.en.md On a row cell click event, retrieve all data for the current row using `getCellMultiData` with the row's query. Also demonstrates getting the specific row cell data and dimension values. ```typescript s2.on(S2Event.ROW_CELL_CLICK, (event) => { // First, get the current cell's information const cell = s2.getCell(event.target) const meta = cell.getMeta() // Get the data for the current row const rowData = s2.dataSet.getCellMultiData({ query: meta.query }) // Get the data for the current row header cell const rowCellData = s2.dataSet.getCellData({ query: meta.query }) // Get the dimension values for the current row header const dimensionValues = s2.dataSet.getDimensionValues(meta.field) console.log('Current row data:', rowData) console.log('Current row header cell data:', rowCellData) console.log('Current row header dimension values:', dimensionValues) }) ``` -------------------------------- ### Tooltip Configuration Options Source: https://github.com/antvis/s2/blob/next/s2-site/common/tooltip.en.md Configuration object for tooltips. This object is optional and defaults to null. It allows for extensive customization of tooltip behavior and appearance. ```APIDOC ## Tooltip Configuration An optional object that configures the tooltip behavior and appearance. Defaults to `null`. ### Parameters - **showTooltip** (boolean) - Optional - Whether to display the tooltip. Defaults to `true`. - **operation** - Optional - Configuration for tooltip operations. See [Tooltip Operation](#tooltipoperation) for details. - **rowCell** - Optional - Configuration for row header cells. See [BaseTooltipConfig](#basetooltipconfig) for details. - **colCell** - Optional - Configuration for column header cells. See [BaseTooltipConfig](#basetooltipconfig) for details. - **dataCell** - Optional - Configuration for data cells. See [BaseTooltipConfig](#basetooltipconfig) for details. - **cornerCell** - Optional - Configuration for corner cells. See [BaseTooltipConfig](#basetooltipconfig) for details. - **render** - Optional - Allows for complete customization of the tooltip by inheriting `BaseTooltip` and rewriting methods. See [RenderTooltip](#rendertooltip) for details. - **content** - Optional - Customizes the tooltip content. Can be a `ReactNode`, `Element`, `string`, or a function that returns one of these based on cell data and default options. `(cell, defaultTooltipShowOptions) => ReactNode | Element | string`. - **autoAdjustBoundary** - Optional - Automatically adjusts the tooltip position when it exceeds the boundary. Options are `container` (chart area) or `body` (entire browser window). Set to `null` to disable. Defaults to `body`. - **adjustPosition** - Optional - A function to customize the tooltip's position. It receives `positionInfo` and should return an object with `x` and `y` coordinates. `(positionInfo: [TooltipPositionInfo](#tooltippositioninfo) ) => {x: number, y: number}`. - **getContainer** - Optional - A function that returns the HTML element where the tooltip should be mounted. Defaults to `document.body`. - **className** - Optional - Additional CSS class names for the tooltip container. `string`. ``` -------------------------------- ### Update Tooltip Configuration from v1.x to v2.x Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/migration-v2.en.md Tooltip configuration keys have been updated from `row`, `col`, `data`, `corner` to `rowCell`, `colCell`, `dataCell`, `cornerCell`. `showTooltip` is now `enable`, and `renderTooltip` is now `render`. ```diff const s2Options = { tooltip: { - row: {}, - col: {}, - data: {}, - corner: {}, + rowCell: {}, + colCell: {}, + dataCell: {}, + cornerCell: {}, } } ``` ```diff const s2Options = { tooltip: { - showTooltip: true, - renderTooltip: () => new CustomTooltip(), + enable: true, + render: () => new CustomTooltip(), } } ``` ```diff s2.showTooltip({ options: { - enterable: true, - showSingleTips: true, + onlyShowCellText: true, - onlyMenu: true, + onlyShowOperator: true }, }); ``` -------------------------------- ### Getting All Cells Source: https://github.com/antvis/s2/blob/next/s2-site/docs/manual/advanced/get-cell-data.en.md Retrieve all cells within the S2 table. ```APIDOC ## Getting All Cells ```ts s2.facet.getCells() ``` ```