S2 Documentation

repository·next·Indexed 23 days ago

https://github.com/antvis/s2

S2 is a data-driven multi-dimensional cross-analysis table visualization library designed for high-performance rendering of large datasets. It provides official support for React and Vue 3, as well as server-side rendering (SSR) capabilities via @antv/s2-ssr for exporting sheets to PNG, JPEG, SVG, or PDF. The library includes components like SheetComponent and configuration panels such as ThemePanel, TextAlignPanel, and FrozenPanel.

Tokens
215.4K
Snippets
558
Records
1.1K
Agent score
80%

What's inside S2

  1. What is S2?

    next
    S2 is a data-driven table visualization engine designed for visual analytics. It specializes in multidimensional pivot tables, providing high-performance rendering (supporting millions of data points) and rich interactions like single/circle/row/column selection, frozen headers, and drag-and-drop resizing. It is highly extensible, allowing for custom layouts, styles, and interactions.
  2. S2 performance optimization techniques

    next

    S2 employs several optimization techniques to maintain smooth performance:

    • On-demand Rendering: Only renders cells in the visible area.
    • Caching: Uses memoization for frequent operations, such as getFieldMeta (caching field information) and caching font width calculations.
    • Scrolling Frame: Implemented to prevent 'white screen' issues during fast scrolling.
    • Lazy Rendering: Used to prevent repeated rendering of the same elements.
    • Future Plans: Migration of complex layout and data calculations to web worker to prevent blocking the main thread.
  3. What is a Custom Hook in S2

    next
    A custom Hook is a powerful extension mechanism that allows developers to rewrite or customize almost every element of an S2 pivot table. It provides hooks into the layout engine, cell rendering, and structural hierarchy. You can use it to customize corner headers, column/row headers, cell positioning, icon sets, and even the overall table framework (dividing lines, shadows, etc.). This allows for complete control over the table's visual and structural representation to meet specific product requirements.
  4. Define custom row and column header structures

    next

    By default, S2 generates hierarchy structures from grouped data. You can override this by providing a custom tree structure to the rows or columns fields in s2DataConfig. This allows you to define a custom directory structure that works with both grid (flat) and tree layouts.

    Data Structure

    A custom tree node should follow this structure:

    • field: Unique identifier for the node.
    • title: Display name for the node.
    • description: Optional description.
    • children: An array of child nodes (empty array if leaf node).

    Limitations

    • The default sorting icon (showDefaultHeaderActionIcon) is disabled when using custom headers.
    • Custom row headers do not support row subtotals/totals.
    • Custom column headers do not support column subtotals/totals.
  5. How multipleMap is applied via adjustTotalNodesCoordinate

    next

    The adjustTotalNodesCoordinate function uses the multipleMap to apply cell merging to summary nodes.

    Handling Zero Multiples in Subtotals

    If a subtotal node's calculated multiple is 0, it is adjusted to the nearest non-zero parent's multiple minus the level difference. This ensures the subtotal node correctly spans the appropriate number of cells relative to its hierarchy.

    // Subtotal root node if 0, change to nearest upper level multiple - level difference
    if (!multiple && isSubTotal) {
        let lowerLevelIndex = 1;
    
        while (multiple < 1) {
            multiple =
            multipleMap[node.level - lowerLevelIndex] - lowerLevelIndex;
            lowerLevelIndex++;
        }
    }

    Example of Adjustment

    If multipleMap = [3, 0, 0, 1] and a subtotal node appears at the second dimension:

    1. The calculation finds the nearest non-zero value (which is 3 at index 0).
    2. It calculates the multiple as: 3 - 1 = 2.
    3. The resulting effective multipleMap for that node becomes [1, 2, 0, 1].
    // 小计根节点若为 0,则改为最近上级倍数 - level 差
    if (!multiple && isSubTotal) {
        let lowerLevelIndex = 1;
    
        while (multiple < 1) {
            multiple =
            multipleMap[node.level - lowerLevelIndex] - lowerLevelIndex;
            lowerLevelIndex++;
        }
    }
  6. Use Single Audience Proportion Tables (单人群占比表)

    next

    A Single Audience Proportion Table (also referred to as an Audience Proportion Heatmap) is a pivot table showing the proportion of a single audience across different dimensions.

    When to use: Use this to compare how a specific group is distributed across the same dimensions. For example, analyzing the scale and distribution of an audience across different age groups and job titles to identify factors that influence large or small audience sizes.

    Core Concept: It focuses on the distribution of a single target group across multiple attributes to find influencing factors for audience scale.

  7. Understand SheetComponentOptions in Vue

    next

    The options prop for the Vue SheetComponent is based on S2Options, but with a specific modification for pagination. The paging configuration is designed to be compatible with ant-design-vue's paging component, allowing for transparent API transmission.

    import type { Pagination, S2Options } from '@antv/s2';
    import type { PaginationProps } from 'ant-design-vue';
    
    type SheetComponentOptions = S2Options<
       Element | string,
       Pagination & PaginationProps
    >;
  8. Understand Dimension Drill Down

    next

    Dimension drill-down allows users to explore hierarchical data by digging into more detailed information across different dimensions. It is primarily used with data sources that have hierarchical relationships (e.g., moving from a Region view to a Province view, or from a Province view to a City view).

    Key concepts:

    • Drill Down: Moving from summary data to more granular details layer by layer.
    • Drill Up: Moving from detailed data back to a higher-level summary (e.g., from Zhejiang Province back to East China).

    Currently, S2 supports dimension drill-down in the perspective mode tree structure and row header dimension drill-down.

  9. Sort by measure values (sortByMeasure)

    next

    Use sortByMeasure to sort row or column headers based on numeric values in the intersection cells.

    Sorting Detail Data

    To sort by specific cell values, set sortFieldId to the last field of the dimension (e.g., city) and use query to specify the exact column dimensions (e.g., type and sub_type). Use a specific measure name for sortByMeasure.

    Sorting Aggregated Data (Subtotals/Totals)

    To sort by subtotals or totals:

    1. Set sortByMeasure to TOTAL_VALUE.
    2. For non-leaf dimensions (e.g., province), use query to define which column dimensions are included in the calculation.
    3. For leaf dimensions (e.g., city), use query to define which row dimensions are included.
    // Example: Sorting by detail data
    {
      sortFieldId: 'city',
      sortByMeasure: 'number',
      sortMethod: 'asc',
      query: {
        type: '办公用品',
        sub_type: '纸张',
        [EXTRA_FIELD]: 'number'
      }
    }
    
    // Example: Sorting by subtotal (TOTAL_VALUE)
    {
      sortFieldId: 'province',
      sortByMeasure: 'TOTAL_VALUE',
      sortMethod: 'asc',
      query: {
        type: '家具',
        [EXTRA_FIELD]: 'number'
      }
    }
  10. Difference between Cell, Node, and Facet

    next

    When working with the low-level rendering and data model, distinguish between these three terms:

    • Cell: Represents the instantiated information of a specific cell within the current visible range.
    • Node: Represents the metadata of a cell. This includes cells that are currently outside the visible range.
    • Facet: Refers to the current visible rendering area.

    Cells (including those in the Corner, Row, and Column headers) can be customized using S2's customization hooks.

  11. Control header icon visibility and color

    next

    Icon Visibility

    • defaultHide: If set, the icon is hidden by default and only appears when hovering over the corresponding cell.
    • displayCondition: Allows for dynamic logic to determine if an icon should be rendered.

    Icon Color

    Icons follow the theme's text color by default. You can override this using the fill property. To use the original colors of a multi-colored SVG (especially for online links), set fill: null.

    const s2Options = {
      headerActionIcons: [
        {
          // Set position to left and color to red
          icons: [{ name: 'SortDown', position: 'left', fill: 'red' }],
          belongsCell: 'colCell',
        },
      ],
    };