### Initial Cells Configuration Examples Source: https://gridsheet.walkframe.com/api-reference/props Examples demonstrating how to configure the `initialCells` prop, including setting default styles, column/row dimensions, and individual cell data. ```APIDOC ## Initial Cells Configuration ### Default Configuration The `default` key applies a base configuration to all cells in the spreadsheet, which is useful for setting global shared styles. However, **`width` and `height` cannot be set via `default`**. To set a global default width or height that applies to all headers, use the `defaultCol` and `defaultRow` keys instead: ```javascript const initialCells = { // Applies to all cells in the sheet default: { style: { fontSize: '14px' } }, // Base configuration for all column headers defaultCol: { width: 100 }, // Base configuration for all row headers defaultRow: { height: 30 }, 'A1': { value: 'Hello World' }, 'B2': { value: 100 }, }; ``` ### Header Configuration Header dimensions are configured using the `0` key for the corner cell (sets default header height/width): ```javascript const initialCells = { // Corner cell: default header row height and column header width '0': { height: 60, // Header row height width: 80, // Row header width }, 'A1': { value: 'Hello World' }, }; ``` ### Header Cell Addressing (`ch()`, `rh()`, `A0:G0`) To configure individual column or row header cells, you should use the `ch()` and `rh()` utility functions provided by `@gridsheet/react-core`. While internally GridSheet appends a `0` (e.g., `A0`, `01`), Using the `ch` and `rh` functions is strongly recommended. * **`ch('A')`** (evaluates to `A0`) — Column A's header cell only (width, label, style, etc.) * **`rh(1)`** (evaluates to `01`) — Row 1's header cell only (height, style, etc.) * **`A0:G0`** — Range of column header cells (A through G) ```javascript import { ch, rh } from '@gridsheet/react-core'; const initialCells = { // Column A header: set width and label [ch('A')]: { width: 150, label: 'Product' }, // Row 1 header: set height [rh(1)]: { height: 50 }, // Style column headers F and G blue 'F0:G0': { style: { color: 'blue' } }, // All data cells in column A (does NOT affect the header) A: { style: { backgroundColor: '#eef' } }, }; ``` **Note**: `A: { ... }` applies to **all data cells** in column A (rows 1 and below). Use `ch('A')` to target the column A header cell. Similarly, `1: { ... }` applies to all data cells in row 1; use `rh(1)` for the row 1 header. ### Column and Row Specifications For columns and rows, you can specify using only one side of the address: * **Columns**: Use just the column letter (e.g., `D` for column D) * **Rows**: Use just the row number (e.g., `3` for row 3) ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://gridsheet.walkframe.com/development/development-guide Clone the GridSheet repository and install project dependencies using pnpm. ```bash git clone https://github.com/your-org/gridsheet.git cd gridsheet pnpm install ``` -------------------------------- ### Start Storybook Server Source: https://gridsheet.walkframe.com/development/development-guide Launch the Storybook development server with `pnpm dev` to view and interact with UI components. ```bash # Start Storybook development server pnpm dev ``` -------------------------------- ### Install GridSheet React Core and Functions Source: https://gridsheet.walkframe.com/getting-started/react Install the core GridSheet React component and the functions package using npm, yarn, or pnpm. It's recommended to install `@gridsheet/functions` for built-in spreadsheet functions. ```bash npm install @gridsheet/react-core @gridsheet/functions ``` ```bash yarn add @gridsheet/react-core @gridsheet/functions ``` ```bash pnpm add @gridsheet/react-core @gridsheet/functions ``` -------------------------------- ### Svelte App.svelte Example Source: https://gridsheet.walkframe.com/getting-started/svelte A basic example of how to import and use Gridsheet components within a Svelte component. ```svelte ``` -------------------------------- ### Install Gridsheet Svelte Core and Functions Source: https://gridsheet.walkframe.com/getting-started/svelte Install the necessary Gridsheet packages for Svelte integration using npm or yarn. ```bash npm install @gridsheet/svelte-core @gridsheet/functions ``` -------------------------------- ### Package JSON Example for Core Packages Source: https://gridsheet.walkframe.com/development/package-structure Shows the versioning format for core GridSheet packages like @gridsheet/react-core and @gridsheet/preact-core. ```json { "name": "@gridsheet/react-core", "version": "2.0.0-rc.2" } ``` ```json { "name": "@gridsheet/preact-core", "version": "2.0.0-rc.2" } ``` -------------------------------- ### Install GridSheet Svelte Core and Functions Source: https://gridsheet.walkframe.com/getting-started/svelte Install the necessary packages for GridSheet's Svelte component and built-in functions using npm, yarn, or pnpm. ```bash npm install @gridsheet/svelte-core @gridsheet/functions ``` ```bash yarn add @gridsheet/svelte-core @gridsheet/functions ``` ```bash pnpm add @gridsheet/svelte-core @gridsheet/functions ``` -------------------------------- ### Install GridSheet Preact Core and Functions Source: https://gridsheet.walkframe.com/getting-started/vanilla Install the necessary packages for GridSheet's Preact integration and built-in spreadsheet functions using npm, yarn, or pnpm. ```bash npm install @gridsheet/preact-core @gridsheet/functions # or yarn add @gridsheet/preact-core @gridsheet/functions # or pnpm add @gridsheet/preact-core @gridsheet/functions ``` -------------------------------- ### Git Tagging Strategy Example Source: https://gridsheet.walkframe.com/development/package-structure Demonstrates the standard git tag format used for releasing GridSheet packages. ```git @gridsheet/react-core/2.0.0-rc.2 ``` ```git @gridsheet/vue-core/2.0.0-rc.2-0 ``` -------------------------------- ### Package JSON Example for Wrapper Packages Source: https://gridsheet.walkframe.com/development/package-structure Illustrates the versioning format for wrapper packages like @gridsheet/vue-core, which includes a wrapper-specific increment. ```json { "name": "@gridsheet/vue-core", "version": "2.0.0-rc.2-0" } ``` -------------------------------- ### Run Documentation Server Source: https://gridsheet.walkframe.com/development/development-guide Start the documentation development server using the `pnpm doc` command. This is essential for viewing and testing documentation changes locally. ```bash # Start documentation development server pnpm doc ``` -------------------------------- ### Policy Registration Example Source: https://gridsheet.walkframe.com/api-reference/props Register custom policies like 'currency' and 'status' using the useBook hook for use in cell configurations. ```javascript import { useBook } from '@gridsheet/react-core'; const book = useBook({ policies: { currency: new Policy({ mixins: [CurrencyPolicyMixin] }), status: new Policy({ mixins: [StatusPolicyMixin] }), }, }); // In initialCells configuration { 'A1': { value: 1000, policy: 'currency', style: { backgroundColor: '#f0f9ff' }, }, 'B1': { value: 'Active', policy: 'status', }, } ``` -------------------------------- ### Initial Cell Configuration Example Source: https://gridsheet.walkframe.com/api-reference/props Demonstrates how to configure default cell styles, column/row dimensions, individual cell values, policies, and header labels using the initialCells prop. ```javascript import { ch, rh } from '@gridsheet/react-core'; const initialCells = { // Default configuration for all cells default: { style: { fontSize: '14px' } }, defaultCol: { width: 100 }, defaultRow: { height: 30 }, // Header configuration '0': { height: 60, // Header row height width: 80, // Header column width }, // Individual cell configuration 'A1': { value: 'Hello World', style: { color: '#FF0000' } }, 'B2': { value: 100, policy: 'currency' }, 'C3': { value: 'Active', policy: 'status' }, // Column header configuration (width, label only affect headers) [ch('A')]: { width: 150, label: 'Name' }, // A0 [ch(2)]: { width: 200, label: 'Value' }, // B0 // Style for all data cells in column A 'A': { style: { backgroundColor: '#f9f9f9' } }, // Row header configuration [rh(1)]: { height: 40 }, // 01 [rh(2)]: { height: 50 }, // 02 }; ``` -------------------------------- ### Dynamic Cell Generation Example Source: https://gridsheet.walkframe.com/api-reference/utility-functions Shows how to dynamically generate cells for a multiplication table using `buildInitialCells` and address conversion utilities. This is useful for populating grids with calculated data. ```typescript import { buildInitialCells, p2a } from '@gridsheet/react-core'; // Generate a multiplication table const generateMultiplicationTable = (size: number) => { const cells: any = {}; // Headers for (let i = 0; i <= size; i++) { cells[p2a({ y: 1, x: i + 1 })] = { value: i || '', style: { fontWeight: 'bold' } }; cells[p2a({ y: i + 1, x: 1 })] = { value: i || '', style: { fontWeight: 'bold' } }; } // Multiplication values for (let row = 1; row <= size; row++) { for (let col = 1; col <= size; col++) { cells[p2a({ y: row + 1, x: col + 1 })] = { value: row * col }; } } return buildInitialCells({ cells, ensured: { numRows: size + 1, numCols: size + 1 }, }); }; const multiplicationTable = generateMultiplicationTable(10); ``` -------------------------------- ### Install GridSheet Vue Core and Functions Source: https://gridsheet.walkframe.com/getting-started/vue Install the necessary GridSheet packages for Vue.js using npm, yarn, or pnpm. It's recommended to include `@gridsheet/functions` for built-in spreadsheet functions. ```bash npm install @gridsheet/vue-core @gridsheet/functions # or yarn add @gridsheet/vue-core @gridsheet/functions # or pnpm add @gridsheet/vue-core @gridsheet/functions ``` -------------------------------- ### Example Cell and Registry Implementation Source: https://gridsheet.walkframe.com/development/architecture Demonstrates how cells store serializable identifiers and how the registry holds actual object instances. This design supports data integrity and flexibility. ```javascript // Cell stores only serializable data const cell = { value: "user123", policy: "userPolicy", // Identifier, not the actual policy instance custom: { userId: 123 } // Serializable custom data } // Registry (book.registry) stores the actual instances const book = useBook({ policies: { userPolicy: new UserPolicy(), // Actual policy instance (handles parsing + rendering) }, additionalFunctions: { MY_FUNC: MyFunction, // Formula function class }, onChange: ({ sheet }) => { /* event handler */ }, }); ``` -------------------------------- ### E2E Test Example with Playwright Source: https://gridsheet.walkframe.com/development/development-guide An example of an end-to-end test using Playwright to verify time and delta calculations in GridSheet. ```typescript import { test, expect } from '@playwright/test'; import { ctrl, drag, paste } from './utils'; test('time + delta, time + number(days)', async ({ page }) => { await page.goto('http://localhost:5233/iframe.html?id=basic-simple--sheet&viewMode=story'); const a4 = page.locator("[data-address='A4']"); const b4 = page.locator("[data-address='B4']"); const c4 = page.locator("[data-address='C4']"); const a5 = page.locator("[data-address='A5']"); expect(await a4.locator('.gs-cell-rendered').textContent()).toBe('2022-03-05 12:34:56'); expect(await b4.locator('.gs-cell-rendered').textContent()).toBe('11:11:11'); expect(await c4.locator('.gs-cell-rendered').textContent()).toBe('2022-03-05 23:46:07'); expect(await a5.locator('.gs-cell-rendered').textContent()).toBe('2022-03-04 23:34:56'); }); ``` -------------------------------- ### Publish Package with pnpm Source: https://gridsheet.walkframe.com/development/development-guide Manually publish packages using `pnpm publish`. This command correctly handles `workspace:*` references, preventing installation issues. ```bash pnpm publish ``` -------------------------------- ### Async Cache Key Generation Example Source: https://gridsheet.walkframe.com/development/architecture Illustrates how a cache key is generated for an asynchronous formula, combining the function name, argument length, and a hash of the serialized arguments. ```javascript // Example: GH_REPO("facebook/react", "stars") // Cache key: "GH_REPO:45:2gosa7pa2gv" // funcName:length:base36-hash(up to 11 chars) ``` -------------------------------- ### Gridsheet Component Structure (1.x) Source: https://gridsheet.walkframe.com/history/migration-guide/1to2 Example of how Gridsheet components were structured and initialized in version 1.x, using constructInitialCells and SheetProvider. ```jsx import * as React from "react"; import { GridSheet, constructInitialCells, BaseFunction, prevention, SheetProvider, } from "@gridsheet/react-core"; const ScoreColorRendererMixin: RendererMixinType = { number(value: number) { if (value < 60) { return { style: { backgroundColor: "#ffcccc" } }; } else if (value < 80) { return { style: { backgroundColor: "#ffffcc" } }; } else { return { style: { backgroundColor: "#ccffcc" } }; } } } function App() { return ( ); } ``` -------------------------------- ### Loading Overlay Until Initialization Completes Source: https://gridsheet.walkframe.com/examples/case8 Use a MutationObserver to watch for the 'gs-initialized' class and display a loading spinner until the grid is fully interactive. This ensures a smooth user experience during grid setup. ```javascript const containerRef = React.useRef(null); const [ready, setReady] = React.useState(false); React.useEffect(() => { const el = containerRef.current; if (!el) return; const observer = new MutationObserver(() => { if (el.querySelector('.gs-initialized')) { setReady(true); observer.disconnect(); } }); observer.observe(el, { attributes: true, subtree: true, attributeFilter: ['class'] }); if (el.querySelector('.gs-initialized')) { setReady(true); } return () => observer.disconnect(); }, []); return (
{!ready && (
)}
); ``` -------------------------------- ### Registering a Currency Policy with useBook Source: https://gridsheet.walkframe.com/api-reference/policy Register a custom policy named 'currency' using `useBook` and apply it to cells. This example uses `ThousandSeparatorPolicyMixin` for formatting. ```typescript import { GridSheet, Policy, useBook, ThousandSeparatorPolicyMixin } from '@gridsheet/react-core'; function MySheet() { const book = useBook({ policies: { currency: new Policy({ mixins: [ThousandSeparatorPolicyMixin] }), }, }); return ( ); } ``` -------------------------------- ### Gridsheet Component Structure (2.x) Source: https://gridsheet.walkframe.com/history/migration-guide/1to2 Example of Gridsheet component initialization in version 2.x, utilizing buildInitialCells, useHub, and Renderer for custom renderers. ```jsx import * as React from "react"; import { GridSheet, buildInitialCells, useHub, Renderer, RendererMixinType, RenderProps, makeBorder, } from "@gridsheet/react-core"; // Updated renderer with new method signature const ScoreColorRendererMixin: RendererMixinType = { number({ value }: RenderProps) { if (value < 60) { return { style: { backgroundColor: "#ffcccc" } }; } else if (value < 80) { return { style: { backgroundColor: "#ffffcc" } }; } else { return { style: { backgroundColor: "#ccffcc" } }; } } } function App() { const hub = useHub({ renderers: { scoreColor: new Renderer({ mixins: [ScoreColorRendererMixin] }), }, }); return ( <> ); } ``` -------------------------------- ### Create a Custom Policy with Dropdown and Validation Source: https://gridsheet.walkframe.com/api-reference/policy Example of creating a custom policy mixin that provides dropdown options and validates user input for a color selection. ```typescript import { Policy, PolicyMixinType, AutocompleteOption, SelectProps } from '@gridsheet/react-core'; const ColorPolicyMixin: PolicyMixinType = { getSelectOptions(): AutocompleteOption[] { return [ { value: 'red', label: Red }, { value: 'green', label: Green }, { value: 'blue', label: Blue }, ]; }, select({ next, current }: SelectProps) { const allowed = ['red', 'green', 'blue']; if (allowed.includes(next?.value)) { return { value: next!.value, style: { backgroundColor: next!.value } }; } // Preserve current value if input is invalid return current ?? { value: null }; }, }; const colorPolicy = new Policy({ mixins: [ColorPolicyMixin], priority: 2 }); ``` -------------------------------- ### Load Dynamic Data into GridSheet Source: https://gridsheet.walkframe.com/examples/case2 Populate the grid starting from cell A1 using `buildInitialCellsFromOrigin` with fetched data. GridSheet initializes with this data only once, so use a loading flag for dynamic updates. ```javascript ``` -------------------------------- ### Registering a Policy with useSpellbook Source: https://gridsheet.walkframe.com/api-reference/policy Register a custom policy using `useSpellbook`, which pre-loads extended formula functions. This example demonstrates registering a 'currency' policy with `ThousandSeparatorPolicyMixin`. ```typescript import { GridSheet, Policy, ThousandSeparatorPolicyMixin } from '@gridsheet/react-core'; import { useSpellbook } from '@gridsheet/react-core/spellbook'; function MySheet() { const book = useSpellbook({ policies: { currency: new Policy({ mixins: [ThousandSeparatorPolicyMixin] }), }, }); return ( ); } ``` -------------------------------- ### Creating a Policy by Subclassing Source: https://gridsheet.walkframe.com/api-reference/policy Define a custom policy by extending the base `Policy` class and overriding methods like `renderString` to modify behavior. This example creates a policy that converts cell values to uppercase. ```typescript import { Policy, RenderProps } from '@gridsheet/react-core'; class UpperCasePolicy extends Policy { override renderString({ value }: RenderProps) { return value?.toUpperCase() ?? ''; } } const upperCasePolicy = new UpperCasePolicy(); ``` -------------------------------- ### Coordinate and Address Conversion Example Source: https://gridsheet.walkframe.com/api-reference/utility-functions Demonstrates converting between programmatic coordinates (x, y) and cell addresses (e.g., 'F10') using various utility functions. Includes column and row number conversions. ```tsx import { x2c, c2x, y2r, r2y, p2a, a2p } from '@gridsheet/react-core'; // Working with programmatic coordinates const colIndex = 5; const rowIndex = 10; // Convert to address const address = p2a({ y: rowIndex, x: colIndex }); console.log(address); // 'F10' // Convert back to coordinates const point = a2p(address); console.log(point); // `{ y: 10, x: 5 }` // Column operations const colLetter = x2c(colIndex); console.log(colLetter); // 'F' const backToIndex = c2x(colLetter); console.log(backToIndex); // 5 // Row operations const rowNumber = y2r(rowIndex); console.log(rowNumber); // 10 const backToRowIndex = r2y(rowNumber); console.log(backToRowIndex); // 10 ``` -------------------------------- ### Formula-based Calculations and Summary Rows Source: https://gridsheet.walkframe.com/examples/case10 Illustrates how to define matrices with formulas for calculations and summary rows using functions like SUM, COUNTA, and COUNTIF. This setup allows for dynamic data aggregation and analysis within the sheet. ```javascript matrices: { A1: [ [null, 'Laptop Pro X1', 'Electronics', 15, 1299.99, '=D1*E1'], // ... ], B22: [['TOTAL', '', '=SUM(D1:D21)', '', '=SUM(F1:F21)']], B23: [['Items', '', '=COUNTA(B1:B21)']], B24: [['Low Stock', '', '=COUNTIF(D1:D21,"<=10")']], }, ``` -------------------------------- ### Build Documentation Source: https://gridsheet.walkframe.com/development/development-guide Build the project documentation for deployment using the `pnpm build:docs` command. ```bash # Build documentation pnpm build:docs ``` -------------------------------- ### Main Entry Point for Preact App Source: https://gridsheet.walkframe.com/getting-started/vanilla Renders the main App component into the DOM, setting up the Preact application's entry point. ```javascript import { render } from 'preact' import './index.css' import { App } from './app.jsx' render(, document.getElementById('app')) ``` -------------------------------- ### Internal Formula Storage Example Source: https://gridsheet.walkframe.com/development/architecture Formulas in GridSheet use internal IDs for cell references, ensuring stability when rows or columns are modified. This example shows the internal storage format. ```javascript // Internal formula storage "=SUM(#2!#0:#4)" // Uses internal IDs (sheet ID + cell IDs) ``` -------------------------------- ### Usage Example: GetProps refEvaluation (1.x vs 2.x) Source: https://gridsheet.walkframe.com/history/migration-guide/1to2 Shows how to use the 'evaluates' property in Gridsheet 1.x and its equivalent 'refEvaluation' property in Gridsheet 2.x when calling table.getCell. The examples illustrate the mapping between the old boolean values and the new string enum values for reference evaluation. ```typescript // Before (1.x) table.getCell({ y: 1, x: 1 }, { evaluates: true }); table.getCell({ y: 1, x: 1 }, { evaluates: false }); table.getCell({ y: 1, x: 1 }, { evaluates: null }); ``` ```typescript // After (2.x) table.getCell({ y: 1, x: 1 }, { refEvaluation: 'COMPLETE' }); table.getCell({ y: 1, x: 1 }, { refEvaluation: 'RAW' }); table.getCell({ y: 1, x: 1 }, { refEvaluation: 'SYSTEM' }); ``` -------------------------------- ### removeCols Source: https://gridsheet.walkframe.com/api-reference/sheet Removes a specified number of columns starting from a given position `x`. ```APIDOC ## removeCols ### Description Removes columns starting at position `x`. ### Method `removeCols(args: { x: number; numCols: number; reflection?: StorePatchType }): UserSheet` ### Parameters #### Path Parameters - **x** (number) - Required - The starting column index for removal. - **numCols** (number) - Required - The number of columns to remove. - **reflection** (StorePatchType) - Optional - A patch to apply for reflection. ### Request Example ```javascript if (!sheetRef.current) return; const { sheet, apply } = sheetRef.current; const newSheet = sheet.removeCols({ x: 2, numCols: 3 }); apply(newSheet); // Required to apply changes ``` ``` -------------------------------- ### Remove Columns Source: https://gridsheet.walkframe.com/api-reference/sheet Removes a specified number of columns starting from a given position. ```typescript if (!sheetRef.current) return; const { sheet, apply } = sheetRef.current; const newSheet = sheet.removeCols({ x: 2, numCols: 3 }); apply(newSheet); // Required to apply changes ``` -------------------------------- ### buildInitialCellsFromOrigin Source: https://gridsheet.walkframe.com/api-reference/utility-functions Creates initial cells configuration from matrix data, automatically generating column names. ```APIDOC ## buildInitialCellsFromOrigin(config: InitialCellsOriginConfig) ### Description Creates initial cells configuration from matrix data, automatically generating column names. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **config** (InitialCellsOriginConfig) - Required - Configuration with matrix data and options - **matrix** (MatrixType) - Required - 2D array of data - **origin** (Address) - Required - Starting address for the matrix - **cells** (CellsByAddressType) - Optional - Individual cell data and configuration - **ensured** ({ numRows?: number; numCols?: number }) - Optional - Minimum table dimensions - **flattenAs** (keyof CellType) - Optional - Property to flatten matrix into ### Request Example ```javascript import { buildInitialCellsFromOrigin } from '@gridsheet/react-core'; const data = [ ['Name', 'Age', 'City'], ['John', 25, 'New York'], ['Jane', 30, 'Los Angeles'], ['Bob', 35, 'Chicago'], ]; const initialCells = buildInitialCellsFromOrigin({ matrix: data, origin: 'A1', ensured: { numRows: 20, numCols: 10, }, }); ``` ### Response #### Success Response (200) - **initialCells** (object) - The formatted initial cells configuration. #### Response Example ```json { "example": "// GridSheet component usage\n" } ``` ``` -------------------------------- ### Get Cell Policy Source: https://gridsheet.walkframe.com/api-reference/sheet Retrieve the Policy instance applied to a specific cell using its coordinates. ```typescript const policy = sheet.getPolicy({ y: 1, x: 1 }); ``` -------------------------------- ### Migrate Header Configuration: Global Options to Table Settings (v1.x to v2.x) Source: https://gridsheet.walkframe.com/history/migration-guide/1to2 Before: Setting header height and width via global options. After: Configuring header dimensions using initialCells or table methods. ```javascript ``` ```javascript ``` ```javascript table.setHeaderHeight(100); table.setHeaderWidth(100); ``` -------------------------------- ### historyIndex Source: https://gridsheet.walkframe.com/api-reference/sheet Gets the current position within the history stack, indicating how many operations have been undone or redone. ```APIDOC ## historyIndex() ### Description Returns the current position in the history stack. ### Method N/A (This is a method call, not an HTTP endpoint) ### Endpoint N/A ### Parameters None ### Response #### Success Response - **return value** (number) - The index representing the current position in the history stack. ### Request Example ```javascript const currentIndex = sheet.historyIndex(); ``` ``` -------------------------------- ### Build Storybook Source: https://gridsheet.walkframe.com/development/development-guide Generate a static build of the Storybook for deployment using `pnpm build:storybook`. ```bash # Build Storybook pnpm build:storybook ``` -------------------------------- ### Get Last Changed Cell Addresses Source: https://gridsheet.walkframe.com/api-reference/sheet Retrieve an array of cell addresses that were modified during the most recent operation. ```typescript const changed = sheet.getLastChangedAddresses(); console.log(changed); // e.g. ['A1', 'B2'] ``` -------------------------------- ### v3 Sheet and Store Handle Initialization and Usage Source: https://gridsheet.walkframe.com/history/migration-guide/2to3 This snippet demonstrates the v3 approach using `useSheetRef` and `useStoreRef` hooks for accessing sheet data and UI state, respectively. It also shows how to apply updates to the store and pass the refs to the GridSheet component. ```javascript import { GridSheet, useSheetRef, useStoreRef, } from '@gridsheet/react-core'; const sheetRef = useSheetRef(); const storeRef = useStoreRef(); // read sheet data const sheet = sheetRef.current?.sheet; // programmatically move the cursor const store = storeRef.current?.store; storeRef.current?.apply({ ...store, choosing: { y: 2, x: 3 } }); return ( ); ``` -------------------------------- ### BaseFunction Type Definition Source: https://gridsheet.walkframe.com/api-reference/formula Defines the structure for custom Gridsheet formulas, including properties for examples, descriptions, argument definitions, and caching. ```typescript class BaseFunction { // Formula example shown in autocomplete example?: string; // Short description of the function description?: string; // Function category for grouping in autocomplete category: FunctionCategory = 'other'; // Argument definitions (drives arg-count and type validation) defs: FunctionArgumentDefinition[] = []; // Cache TTL in milliseconds (async only). undefined = never expires. protected ttlMilliseconds?: number; // Hash segments in cache key. Higher = lower collision risk. Default: 1 protected hashPrecision: number; // If true, reuse the same in-flight Promise for matching cache keys. Default: true protected useInflight: boolean; // If true, broadcasting is unconditionally disabled for this function. Default: false protected broadcastDisabled: boolean; // If true, wraps return value in a Spilling sentinel for spill behaviour. Default: false protected autoSpilling: boolean; // Main function implementation protected main(...args: any[]): any; // Optional: override to customise argument coercion before main() is called protected validate(args: any[]): any[]; } type FunctionCategory = | 'math' | 'statistics' | 'text' | 'time' | 'lookup' | 'information' | 'finance' | 'engineering' | 'logical' | 'other'; type FunctionArgumentDefinition = { name: string; description: string; optional?: boolean; // allows fewer args than defs.length variadic?: boolean; // last matching def receives all remaining args nullable?: boolean; // blank treated as 0 / "" etc. (default: true) errorTolerant?: boolean; // forward FormulaError values instead of throwing acceptedTypes?: FunctionArgumentType[]; // runtime type check takesMatrix?: boolean; // suppresses broadcasting for this arg }; type FunctionArgumentType = | 'number' | 'string' | 'boolean' | 'date' | 'time' | 'matrix' | 'reference' | 'any'; ``` -------------------------------- ### Create a Custom Formula Source: https://gridsheet.walkframe.com/api-reference/formula Extend BaseFunction to create custom formula functions. Define example usage, descriptions, and argument documentation. ```typescript import { BaseFunction, FunctionArgumentDefinition } from '@gridsheet/react-core'; class MyCustomFunction extends BaseFunction { // Display name and example usage example = 'MY_FUNC(arg1, arg2)'; // Optional: description of what this function does description = 'Description of what this function does'; // Argument documentation (also drives arg-count validation) defs: FunctionArgumentDefinition[] = [ { name: 'arg1', description: 'Description of first argument', acceptedTypes: ['string'] }, { name: 'arg2', description: 'Description of second argument', acceptedTypes: ['number'] } ]; // The main function logic protected main(stringArg: string, numberArg: number) { // Your logic here return result; } } ``` -------------------------------- ### Migrate Utility Function Names: constructInitialCells to buildInitialCells (v1.x to v2.x) Source: https://gridsheet.walkframe.com/history/migration-guide/1to2 Before: Using constructInitialCells and constructInitialCellsOrigin. After: Using the renamed buildInitialCells and buildInitialCellsFromOrigin. ```javascript import { constructInitialCells, constructInitialCellsOrigin } from "@gridsheet/react-core"; ``` ```javascript import { buildInitialCells, buildInitialCellsFromOrigin } from "@gridsheet/react-core"; ``` -------------------------------- ### Registering Custom Formulas with useSpellbook Source: https://gridsheet.walkframe.com/api-reference/formula Registers custom formulas using `useSpellbook`, which includes all built-in extended functions. Requires `@gridsheet/functions` to be installed. ```typescript import { useSpellbook } from '@gridsheet/react-core/spellbook'; const book = useSpellbook({ additionalFunctions: { my_func: MyCustomFunction, fetch_weather: FetchWeather, }, }); ``` -------------------------------- ### Creating Refs Source: https://gridsheet.walkframe.com/api-reference/props Demonstrates how to create `sheetRef` and `storeRef` using hooks within components or factory functions outside of components. ```APIDOC ## Creating refs Use the provided hooks (inside a component) or factory functions (outside): ```javascript import { useSheetRef, useStoreRef, createSheetRef, createStoreRef } from '@gridsheet/react-core'; // Inside a component const sheetRef = useSheetRef(); const storeRef = useStoreRef(); // Outside a component (e.g. in a class or module) const sheetRef = createSheetRef(); const storeRef = createStoreRef(); ``` ``` -------------------------------- ### Migrate TableRef and StoreRef to Connector (v1.x to v2.x) Source: https://gridsheet.walkframe.com/history/migration-guide/1to2 Before: Using separate useTableRef and useStoreRef hooks. After: Using the unified useConnector hook for both table and store managers. ```javascript import { useTableRef, useStoreRef } from '@gridsheet/react-core'; const tableRef = useTableRef(); const storeRef = useStoreRef(); // Access table const { table, apply } = tableRef.current; // Access store const { store, apply } = storeRef.current; ``` ```javascript import { useConnector } from '@gridsheet/react-core'; const connector = useConnector(); // Access table manager const { tableManager } = connector.current; const { table, apply } = tableManager; // Access store manager const { storeManager } = connector.current; const { store, apply } = storeManager; ``` -------------------------------- ### Policy Mixin with `EVALUATED` Resolution Source: https://gridsheet.walkframe.com/api-reference/sheet Example of using `'EVALUATED'` resolution within a `renderSheet` policy mixin to receive range formulas as `Sheet` objects. ```javascript const ChartPolicyMixin: PolicyMixinType = { renderSheet({ value }: RenderProps) { // value is the Sheet spanning the referenced range (e.g. C1:F1) const matrix = toValueMatrix(value); // ... render chart from matrix data }, }; ``` -------------------------------- ### Using `getCell` with Resolution Options Source: https://gridsheet.walkframe.com/api-reference/sheet Demonstrates how to use the `getCell` method with different `resolution` options to control formula evaluation. ```javascript // Default: =C1:F1 → scalar value of C1 sheet.getCell({ y: 1, x: 2 }); // EVALUATED: =C1:F1 → Sheet object spanning C1:F1 sheet.getCell({ y: 1, x: 2 }, { resolution: 'EVALUATED' }); // RAW: =C1:F1 → '=C1:F1' string sheet.getCell({ y: 1, x: 2 }, { resolution: 'RAW' }); ``` -------------------------------- ### Development Scripts Source: https://gridsheet.walkframe.com/development/development-guide Common scripts for running development servers, tests, and linters. ```bash pnpm dev pnpm doc pnpm test pnpm e2e pnpm lint:fix ``` -------------------------------- ### Reading Sheet Data as a Value Object Source: https://gridsheet.walkframe.com/api-reference/sheet Get cell values as an object keyed by address using `toValueObject`. Allows filtering by specific addresses. ```javascript const values = toValueObject(sheet); console.log(values['A1']); // value of A1 // Only specific addresses const partial = toValueObject(sheet, { addresses: ['A1', 'B2', 'C3'] }); ``` -------------------------------- ### Run Tests Source: https://gridsheet.walkframe.com/development/development-guide Execute all project tests to ensure code quality and stability before submitting changes. Use `pnpm test` for this purpose. ```bash pnpm test ``` -------------------------------- ### Log Cell Changes with onChange Source: https://gridsheet.walkframe.com/examples/case10 Fires after any cell mutation. Use `getLastChangedAddresses()` to get the exact addresses of modified cells, which is more precise than tracking `points`. ```typescript onChange: ({ sheet }: { sheet: UserSheet }) => { const addresses = sheet.getLastChangedAddresses(); if (addresses.length > 0) { addActivityLog(`✏️ Cells changed: ${addresses.join(', ')}`); } setTsv(convertToTSV(sheet)); }, ``` -------------------------------- ### buildInitialCells(config: InitialCellsConfig): any Source: https://gridsheet.walkframe.com/api-reference/utility-functions Initializes cells with provided configurations, including direct cell data, matrices, and ensuring a minimum number of rows/columns. ```APIDOC ## buildInitialCells(config: InitialCellsConfig): any ### Description Initializes cells with provided configurations. This can include direct cell data, matrices, and ensuring a minimum number of rows and columns. ### Parameters #### Path Parameters - **config** (InitialCellsConfig) - Required - Configuration object for initializing cells. - **matrices** (MatricesByAddress) - Optional - Matrix data. - **cells** (CellsByAddressType) - Optional - Direct cell data keyed by address. - **ensured** (object) - Optional - Ensures a minimum number of rows and columns. - **numRows** (number) - Optional - Minimum number of rows. - **numCols** (number) - Optional - Minimum number of columns. - **flattenAs** (keyof CellType) - Optional - Specifies how to flatten cell data. ### Response #### Success Response - **any** - The result of building initial cells. ### Response Example ```json { // ... structure representing initialized cells ... } ``` ### Usage Example ```javascript import { buildInitialCells, rh, ch } from '@gridsheet/react-core'; buildInitialCells({ cells: { [rh(6)]: { sortFixed: true, filterFixed: true }, [ch('A')]: { width: 150, label: 'Product' }, }, ensured: { numRows: 10, numCols: 5 }, }); ``` ``` -------------------------------- ### Ensuring Grid Size with `ensured` Option Source: https://gridsheet.walkframe.com/examples/case3 Use the `ensured` option within `buildInitialCells` to pre-allocate a minimum number of rows and columns. This is vital for creating a blank canvas where all cells should be accessible. ```javascript buildInitialCells({ cells: { defaultRow: { height: 25 }, defaultCol: { width: 25 }, ...getSavedData(), }, ensured: { numRows: 50, numCols: 50, }, }) ``` -------------------------------- ### Formula Display Conversion Example Source: https://gridsheet.walkframe.com/development/architecture Internal cell IDs are converted to human-readable addresses (e.g., 'A1') for display purposes. This ensures a familiar user experience. ```javascript // Display conversion "=SUM('Sheet2'!A1:A5)" // Converted to addresses for display ``` -------------------------------- ### Update Hub Configuration with Event Handlers Source: https://gridsheet.walkframe.com/history/migration-guide/1to2 Configure the hub with renderers and move event handlers from options to the hub configuration. ```javascript const hub = useHub({ renderers: { myRenderer: new Renderer({ mixins: [MyRenderer] }), }, // Move event handlers from options to hub onChange: ({ table, points }) => { console.log('Data changed:', points); }, onSave: ({ table, points }) => { console.log('Data saved:', points); }, onSelect: ({ table, points }) => { console.log('Selection changed:', points); }, onRemoveRows: ({ table, ys }) => { console.log('Rows removed:', ys); }, onRemoveCols: ({ table, xs }) => { console.log('Columns removed:', xs); }, onInsertRows: ({ table, y, numRows }) => { console.log('Rows inserted at position', y, 'count:', numRows); }, onInsertCols: ({ table, x, numCols }) => { console.log('Columns inserted at position', x, 'count:', numCols); }, onKeyUp: ({ e, points }) => { console.log('Key pressed:', e.key, 'at position:', points); }, onInit: (table) => { console.log('Table initialized:', table.sheetName); }, }); ``` -------------------------------- ### Cell Policy Configuration Source: https://gridsheet.walkframe.com/examples/case11 Defines the policy for a cell, specifying how its value is interpreted or handled. This example sets the policy to 'repo' for cell A1 in the 'GithubRepos' sheet. ```json 1{ 2 "policy": "repo", 3 "value": "facebook/react" 4} ```