### GET /init - Initialize with Default Data Source: https://context7.com/ruilisi/fortune-sheet/llms.txt Clears existing workbook data and inserts a default workbook. ```APIDOC ## GET /init ### Description Initializes the database by deleting all existing workbook data and inserting a default workbook. ### Method GET ### Endpoint /init ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Object** - An object indicating success. #### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Celldata Initialization Example (JavaScript) Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/sheet.md Provides an example of how to format initial cell data for Fortune Sheet. The `celldata` array contains objects, each specifying the row (`r`), column (`c`), and value (`v`) of a cell. The value object includes formatting details like `ct` (cell type) and `m` (formatted value). ```javascript [ { "r": 0, "c": 0, "v": { "ct": {"fa": "General", "t": "g"}, "m":"value1", "v":"value1" } }, { "r": 0, "c": 1, "v": { "ct": {"fa": "General", "t": "g"}, "m":"value2", "v":"value2" } } ] ``` -------------------------------- ### Fortune Sheet Filter Configuration Example Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/sheet.md This JavaScript code snippet demonstrates a complete filter configuration object for Fortune Sheet. It includes settings for multiple columns, specifying filter conditions, hidden row information, and the filter range. The 'key' of the filter object represents the column index (starting from 0). ```javascript { "0": { "caljs": { "value": "cellnull", "text": "Is empty", "type": "0" }, "rowhidden": { "3": 0, "4": 0 }, "optionstate": true, "cindex": 1, "str": 2, "edr": 6, "stc": 1, "edc": 3 }, "1": { "caljs": {}, "rowhidden": { "1": 0}, "optionstate": true, "cindex": 2, "str": 2, "edr": 6, "stc": 1, "edc": 3 } } ``` -------------------------------- ### Basic FortuneSheet Spreadsheet Setup in React Source: https://context7.com/ruilisi/fortune-sheet/llms.txt Renders a basic FortuneSheet spreadsheet component within a React application. It initializes the workbook with sample data and includes a callback function to handle data changes. ```tsx import React, { useState, useCallback } from "react"; import { Workbook } from "@fortune-sheet/react"; import { Sheet } from "@fortune-sheet/core"; import "@fortune-sheet/react/dist/index.css"; function App() { const [data, setData] = useState([ { name: "Sheet1", celldata: [ { r: 0, c: 0, v: { v: "Hello", m: "Hello" } }, { r: 0, c: 1, v: { v: "World", m: "World" } }, { r: 1, c: 0, v: { v: 100, m: "100", ct: { fa: "General", t: "n" } } }, { r: 1, c: 1, v: { v: 200, m: "200", ct: { fa: "General", t: "n" } } }, ], order: 0, row: 36, column: 18, }, ]); const onChange = useCallback((d: Sheet[]) => { setData(d); }, []); return (
); } export default App; ``` -------------------------------- ### Row and Column Height/Width Management Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md APIs for batch operations to get and set row heights and column widths. ```APIDOC ## GET /getRowHeight ### Description Gets row heights in batch for specified row indexes. ### Method GET ### Endpoint /getRowHeight ### Parameters #### Query Parameters - **rows** (number[]) - Required - A list of row indexes, e.g. [1, 4] - **options** ([CommonOptions](#commonoptions)) - Optional - Common options ### Response #### Success Response (200) - **map** (object) - A map of specified row heights, e.g. { "1": 150, "4": 200 } ## GET /getColumnWidth ### Description Gets column widths in batch for specified column indexes. ### Method GET ### Endpoint /getColumnWidth ### Parameters #### Query Parameters - **columns** (number[]) - Required - A list of column indexes, e.g. [1, 4] - **options** ([CommonOptions](#commonoptions)) - Optional - Common options ### Response #### Success Response (200) - **map** (object) - A map of specified column widths, e.g. { "1": 150, "4": 200 } ## POST /setRowHeight ### Description Sets row heights in batch for specified row indexes. ### Method POST ### Endpoint /setRowHeight ### Parameters #### Request Body - **rowInfo** (object) - Required - A map in the form of [row index]: height. Example: { "1": 150, "4": 200 } - **options** ([CommonOptions](#commonoptions)) - Optional - Common options ## POST /setColumnWidth ### Description Sets column widths in batch for specified column indexes. ### Method POST ### Endpoint /setColumnWidth ### Parameters #### Request Body - **columnInfo** (object) - Required - A map in the form of [column index]: width. Example: { "1": 150, "4": 200 } - **options** ([CommonOptions](#commonoptions)) - Optional - Common options ``` -------------------------------- ### GET / - Retrieve Workbook Data Source: https://context7.com/ruilisi/fortune-sheet/llms.txt Fetches all workbook data from the MongoDB database. ```APIDOC ## GET / ### Description Fetches all workbook data stored in the MongoDB database. ### Method GET ### Endpoint / ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Array** - An array of workbook objects. #### Response Example ```json [ { "name": "Sheet1", "id": "some-uuid", "celldata": [ { "r": 0, "c": 0, "v": null } ], "order": 0, "row": 84, "column": 60, "config": {}, "status": 1 } ] ``` ``` -------------------------------- ### Get Custom Functions from Formula Parser Source: https://github.com/ruilisi/fortune-sheet/blob/master/packages/formula-parser/README.md Demonstrates how to retrieve a custom function previously defined using `.setFunction()`. This allows for introspection of the parser's available custom functions. ```javascript parser.setFunction("ADD_5", function (params) { return params[0] + 5; }); parser.getFunction("ADD_5")([1]); // returns `6` ``` -------------------------------- ### Node.js Backend Setup with Express, MongoDB, and WebSockets Source: https://context7.com/ruilisi/fortune-sheet/llms.txt Sets up an Express server for handling HTTP requests and a WebSocket server for real-time communication. It connects to a MongoDB database to store and retrieve workbook data. Dependencies include express, mongodb, ws, uuid, and lodash. ```javascript const express = require("express"); const { MongoClient } = require("mongodb"); const SocketServer = require("ws").Server; const uuid = require("uuid"); const _ = require("lodash"); const dbName = "fortune-sheet"; const collectionName = "workbook"; const uri = "mongodb://localhost:27017"; const client = new MongoClient(uri); const defaultData = { name: "Sheet1", id: uuid.v4(), celldata: [{ r: 0, c: 0, v: null }], order: 0, row: 84, column: 60, config: {}, status: 1, }; async function initMongoDB() { await client.connect(); console.log("Connected to MongoDB"); } initMongoDB(); const app = express(); const port = 8081; async function getData() { const db = client.db(dbName); const data = await db.collection(collectionName).find().toArray(); data.forEach((sheet) => delete sheet._id); return data; } // Get workbook data app.get("/", async (req, res) => { res.json(await getData()); }); // Initialize with default data app.get("/init", async (req, res) => { const db = client.db(dbName); await db.collection(collectionName).deleteMany(); await db.collection(collectionName).insertOne(defaultData); res.json({ ok: true }); }); const server = app.listen(port, () => { console.log(`Server running on port ${port}`); }); // WebSocket for real-time sync const connections = {}; const wss = new SocketServer({ server, path: "/ws" }); wss.on("connection", (ws) => { ws.id = uuid.v4(); connections[ws.id] = ws; ws.on("message", async (data) => { const msg = JSON.parse(data.toString()); if (msg.req === "getData") { ws.send(JSON.stringify({ req: "getData", data: await getData() })); } else if (msg.req === "op") { // Apply operation to database and broadcast to others await applyOpToDb(msg.data); broadcastToOthers(ws.id, data.toString()); } else if (msg.req === "addPresences") { broadcastToOthers(ws.id, data.toString()); } }); ws.on("close", () => { delete connections[ws.id]; }); }); function broadcastToOthers(selfId, data) { Object.values(connections).forEach((ws) => { if (ws.id !== selfId) ws.send(data); }); } async function applyOpToDb(ops) { const db = client.db(dbName); const coll = db.collection(collectionName); for (const op of ops) { if (op.op === "replace") { // Build MongoDB update path from op.path const path = op.path.join("."); await coll.updateOne( { id: op.id }, { $set: { [path]: op.value } } ); } // Handle other op types: add, remove, insertRowCol, deleteRowCol, etc. } } ``` -------------------------------- ### Manage Sheets with Fortune Sheet API Source: https://context7.com/ruilisi/fortune-sheet/llms.txt This snippet demonstrates how to perform various sheet management operations using the Fortune Sheet WorkbookInstance API. It covers getting all sheets, getting a specific sheet, adding, deleting, activating, renaming, and reordering sheets. It also shows how to update multiple sheets at once, including creating new ones. ```tsx import React, { useRef, useState } from "react"; import { Workbook, WorkbookInstance } from "@fortune-sheet/react"; import { Sheet } from "@fortune-sheet/core"; function SheetManagement() { const workbookRef = useRef(null); const [data, setData] = useState([ { id: "sheet1", name: "Sales", celldata: [{ r: 0, c: 0, v: { v: "Sales Data" } }], order: 0, }, { id: "sheet2", name: "Inventory", celldata: [{ r: 0, c: 0, v: { v: "Inventory Data" } }], order: 1, }, ]); const sheetOperations = () => { // Get all sheets data const allSheets = workbookRef.current?.getAllSheets(); console.log("All sheets:", allSheets); // Get specific sheet const sheet = workbookRef.current?.getSheet({ id: "sheet1" }); console.log("Sheet 1:", sheet); // Add new sheet workbookRef.current?.addSheet(); // Delete sheet by ID workbookRef.current?.deleteSheet({ id: "sheet2" }); // Activate/switch to sheet workbookRef.current?.activateSheet({ id: "sheet1" }); // Rename sheet workbookRef.current?.setSheetName("Q1 Sales", { id: "sheet1" }); // Reorder sheets workbookRef.current?.setSheetOrder({ "sheet1": 1, "sheet2": 0, }); }; const updateSheets = () => { // Update multiple sheets at once workbookRef.current?.updateSheet([ { id: "sheet1", name: "Updated Sales", celldata: [ { r: 0, c: 0, v: { v: "New Sales Data" } }, { r: 1, c: 0, v: { v: 1000 } }, ], row: 10, column: 5, order: 0, }, { id: "newSheet", name: "New Sheet", data: [[{ v: "Created via API" }]], order: 2, }, ]); }; return (
); } ``` -------------------------------- ### Collaboration API with WebSocket and React Source: https://context7.com/ruilisi/fortune-sheet/llms.txt Implements real-time collaboration by capturing operations using the `onOp` callback and synchronizing them via WebSocket. This example shows how to connect to a WebSocket server, send user operations, and apply operations received from other clients. Dependencies include React, `@fortune-sheet/react`, and `@fortune-sheet/core`. ```tsx import React, { useRef, useState, useCallback, useEffect } from "react"; import { Workbook, WorkbookInstance } from "@fortune-sheet/react"; import { Sheet, Op } from "@fortune-sheet/core"; function CollaborationExample() { const workbookRef = useRef(null); const wsRef = useRef(null); const [data, setData] = useState(); useEffect(() => { // Connect to WebSocket server const socket = new WebSocket("ws://localhost:8081/ws"); wsRef.current = socket; socket.onopen = () => { socket.send(JSON.stringify({ req: "getData" })); }; socket.onmessage = (e) => { const msg = JSON.parse(e.data); if (msg.req === "getData") { setData(msg.data); } else if (msg.req === "op") { // Apply operations from other users workbookRef.current?.applyOp(msg.data); } }; return () => socket.close(); }, []); // Send operations to server when user makes changes const onOp = useCallback((ops: Op[]) => { if (wsRef.current?.readyState === WebSocket.OPEN) { wsRef.current.send(JSON.stringify({ req: "op", data: ops })); } // Example op structure when user sets cell A2 to bold: // [{ // "op": "replace", // "id": "sheet1", // "path": ["data", 1, 0, "bl"], // "value": 1 // }] }, []); const onChange = useCallback((d: Sheet[]) => { setData(d); }, []); if (!data) return
Loading...
; return (
); } ``` -------------------------------- ### Example Cell Data Structure (JSON) Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/sheet.md Illustrates the structure of cell data within the 'data' array, showing how cell values, formatting, and metadata are represented. This format is used for storing and updating cell content. ```json [ [{ "ct": { "fa": "General", "t": "g" }, "m": "value1", "v": "value1" }, { "ct": { "fa": "General", "t": "g" }, "m": "value2", "v": "value2" }], [{ "ct": { "fa": "General", "t": "g" }, "m": "value3", "v": "value3" }, { "ct": { "fa": "General", "t": "g" }, "m": "value4", "v": "value4" }] ] ``` -------------------------------- ### Get All Sheets Data in Fortune Sheet Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Retrieves the raw data for all sheets within the workbook. The data is returned in a structured format. ```javascript fortuneSheet.getAllSheets(); ``` -------------------------------- ### Manage Cell Selections and Ranges in Fortune Sheet (TypeScript) Source: https://context7.com/ruilisi/fortune-sheet/llms.txt This snippet demonstrates how to get and set cell selections and work with cell ranges using Fortune Sheet's API. It covers retrieving current selections, converting them to text coordinates, setting new selections (including multi-selection), expanding ranges, getting cells within a range, and obtaining an HTML representation of a range for clipboard operations. It requires the '@fortune-sheet/react' and '@fortune-sheet/core' packages. ```tsx import React, { useRef, useState } from "react"; import { Workbook, WorkbookInstance } from "@fortune-sheet/react"; import { Sheet } from "@fortune-sheet/core"; function SelectionExample() { const workbookRef = useRef(null); const [data, setData] = useState([ { name: "Sheet1", celldata: Array.from({ length: 25 }, (_, i) => ({ r: Math.floor(i / 5), c: i % 5, v: { v: `${Math.floor(i / 5)},${i % 5}` }, })), order: 0, row: 5, column: 5, }, ]); const handleSelection = () => { // Get current selection const selection = workbookRef.current?.getSelection(); console.log("Current selection:", selection); // Output: [{ row: [0, 0], column: [0, 0] }] // Get selection as text coordinates const coords = workbookRef.current?.getSelectionCoordinates(); console.log("Selection coordinates:", coords); // Output: ["A1"] or ["A1:C3", "E5"] // Set selection to range B2:D4 workbookRef.current?.setSelection([ { row: [1, 3], column: [1, 3] } ]); // Multi-selection workbookRef.current?.setSelection([ { row: [0, 0], column: [0, 0] }, { row: [2, 4], column: [2, 4] } ]); }; const handleRangeOperations = () => { // Expand range to individual cell coordinates const flatRange = workbookRef.current?.getFlattenRange({ row: [0, 1], column: [0, 2] }); console.log("Flattened range:", flatRange); // Output: [{r:0,c:0}, {r:0,c:1}, {r:0,c:2}, {r:1,c:0}, {r:1,c:1}, {r:1,c:2}] // Get cells by range const cells = workbookRef.current?.getCellsByRange([ { row: [0, 1], column: [0, 1] } ]); console.log("Cells in range:", cells); // Get HTML representation (for clipboard) const html = workbookRef.current?.getHtmlByRange([ { row: [0, 1], column: [0, 2] } ]); console.log("HTML:", html); }; return (
); } ``` -------------------------------- ### Get Fortune Sheet Debug Information (JSON) Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/sheet.md Retrieves the complete internal state of the Fortune Sheet, including all worksheet data, configurations, and operational parameters. This is useful for debugging and analysis. ```json [ { "name": "Cell", "color": "", "id": "0", "status": 1, "order": 0, "hide": 0, "row": 36, "column": 18, "celldata": [], "config": { "merge":{}, "rowlen":{}, "columnlen":{}, "rowhidden":{}, "colhidden":{}, "borderInfo":{}, "authority":{}, }, "scrollLeft": 0, "scrollTop": 315, "luckysheet_select_save": [], "calcChain": [], "isPivotTable":false, "pivotTable":{}, "filter_select": {}, "filter": null, "luckysheet_alternateformat_save": [], "luckysheet_alternateformat_save_modelCustom": [], "luckysheet_conditionformat_save": {}, "frozen": {}, "freezen": {}, "chart": [], "zoomRatio":1, "image":[], "showGridLines": 1, "visibledatarow": [], "visibledatacolumn": [], "ch_width": 2322, "rh_height": 949, "load": "1", "data": [], }, { "name": "Sheet2", "color": "", "id": "1", "status": 0, "order": 1, "celldata": [], "config": {} }, { "name": "Sheet3", "color": "", "id": "2", "status": 0, "order": 2, "celldata": [], "config": {}, } ] ``` -------------------------------- ### Get Single Sheet Data in Fortune Sheet Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Fetches the raw data for a specific sheet. Accepts optional common options for customization. Returns the sheet's data. ```javascript fortuneSheet.getSheet([options]); ``` -------------------------------- ### Get and Set Cell Values with Fortune Sheet API Source: https://context7.com/ruilisi/fortune-sheet/llms.txt Demonstrates how to retrieve and modify cell values using the getCellValue and setCellValue methods from the Fortune Sheet API. It covers fetching raw values, displayed values, and setting simple values, formulas, and formatted cell objects. Requires the '@fortune-sheet/react' and '@fortune-sheet/core' packages. ```tsx import React, { useRef, useState, useCallback, useEffect } from "react"; import { Workbook, WorkbookInstance } from "@fortune-sheet/react"; import { Sheet } from "@fortune-sheet/core"; function CellValueExample() { const workbookRef = useRef(null); const [data, setData] = useState([ { name: "Sheet1", celldata: [ { r: 0, c: 0, v: { v: 10, m: "10", ct: { fa: "General", t: "n" } } }, { r: 0, c: 1, v: { v: 20, m: "20", ct: { fa: "General", t: "n" } } }, { r: 0, c: 2, v: { v: 30, m: "30", ct: { fa: "General", t: "n" } } }, ], order: 0, }, ]); const handleGetValue = () => { // Get raw value (v field) const value = workbookRef.current?.getCellValue(0, 0); console.log("Cell A1 value:", value); // Output: 10 // Get displayed value (m field) const displayedValue = workbookRef.current?.getCellValue(0, 0, { type: "m" }); console.log("Cell A1 displayed:", displayedValue); // Output: "10" // Get background color const bgColor = workbookRef.current?.getCellValue(0, 0, { type: "bg" }); console.log("Cell A1 background:", bgColor); }; const handleSetValues = () => { // Set simple numeric value workbookRef.current?.setCellValue(1, 0, 100); // Set formula workbookRef.current?.setCellValue(1, 1, "=SUM(A1:C1)"); // Set cell object with formatting workbookRef.current?.setCellValue(1, 2, { v: 500, m: "500", bg: "#ffff00", bl: 1, // bold fc: "#ff0000", // font color }); // Set value on specific sheet by index workbookRef.current?.setCellValue(2, 0, "Sheet-specific", { index: 0 }); }; return (
); } ``` -------------------------------- ### Set Font Format for Cells in Range (React Example) Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Demonstrates how to use `setCellFormatByRange` in a React component to set the font family for cells within a specified range. It utilizes `useRef` and `useEffect` to interact with the Workbook instance. ```javascript import { Workbook, WorkbookInstance } from "@fortune-sheet/react"; const ExampleComponent = () => { const ref = useRef < WorkbookInstance > null; useEffect(() => { // Sets A1:C3 to use the Arial font. ref.current?.setCellFormatByRange("ff", "Arial", { column: [0, 2], row: [0, 2], }); }, []); return ( <> ); }; ``` -------------------------------- ### Get Cell Value - TypeScript Example Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Retrieves the value of a specific cell in the worksheet. Supports fetching different cell attributes like 'v' (value) or 'm' (formatted display value). ```typescript workboobRef.current.getCellValue(0, 0) workboobRef.current.getCellValue(1, 1, {type:"m"}) ``` -------------------------------- ### Basic Workbook Configuration and Rendering (JavaScript) Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/config.md Demonstrates the basic structure for configuring a Fortune Sheet workbook and rendering it. It includes settings for sheet data, an onChange event handler, and language. The configuration is passed as props to the Workbook component. ```javascript // Configuration item const settings = { data: [{ name: 'Sheet1', celldata: [{ r: 0, c: 0, v: null }] }], // sheet data onChange: (data) => {}, // onChange event lang:'zh' // set language // More other settings... } // Render the workbook ``` -------------------------------- ### Workbook Operations Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/config.md Callbacks for workbook creation events. ```APIDOC ## workbookCreateBefore ### Description Callback function triggered before the workbook is created. The old hook function was `beforeCreateDom`. ### Method Function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **book** (Object) - Required - Configuration of the entire workbook (options). ### Response #### Success Response (200) None (This is a callback function) ## workbookCreateAfter ### Description Callback function triggered after the workbook is created. ### Method Function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **book** (Object) - Required - Configuration of the entire workbook (options). ### Response #### Success Response (200) None (This is a callback function) ``` -------------------------------- ### Operation Sync (onOp) for Collaboration Source: https://context7.com/ruilisi/fortune-sheet/llms.txt This section explains how to use the `onOp` callback to capture operations for backend synchronization and enable real-time collaboration. It demonstrates setting up a WebSocket connection to broadcast and receive operations. ```APIDOC ## Operation Sync (onOp) for Collaboration ### Description Capture operations for backend synchronization and real-time collaboration. ### Method #### `onOp(ops: Op[])` This callback function is invoked whenever an operation (a change) is made to the sheet. It receives an array of `Op` objects representing the changes. ### Parameters #### Request Body (for WebSocket message) - `req` (string): The type of request. Can be `"getData"` or `"op"`. - `data` (any): The payload of the request. For `"getData"`, it's typically empty. For `"op"`, it's an array of `Op` objects. #### `Op` Object Structure (Example) ```json [ { "op": "replace", "id": "sheet1", "path": ["data", 1, 0, "bl"], "value": 1 } ] ``` - `op` (string): The type of operation (e.g., "replace"). - `id` (string): The ID of the sheet where the operation occurred. - `path` (array): The path within the sheet data structure that was modified. - `value` (any): The new value for the modified path. ### Request Example (WebSocket) ```javascript // Sending data to the server // To get initial data: socket.send(JSON.stringify({ req: "getData" })); // To send an operation: socket.send(JSON.stringify({ req: "op", data: ops })); ``` ### Response (from WebSocket server) #### Success Response (onmessage) - `req` (string): The type of response. Can be `"getData"` or `"op"`. - `data` (any): The payload of the response. For `"getData"`, it's the sheet data. For `"op"`, it's an array of `Op` objects to apply. #### Response Example ```json // Example response for getting data { "req": "getData", "data": [ { "name": "Sheet1", "celldata": [...], "order": 0, "row": 100, "column": 10 } ] } // Example response for applying an operation { "req": "op", "data": [ { "op": "replace", "id": "sheet1", "path": ["data", 1, 0, "bl"], "value": 1 } ] } ``` ``` -------------------------------- ### Configured FortuneSheet Workbook in React Source: https://context7.com/ruilisi/fortune-sheet/llms.txt Demonstrates how to configure a FortuneSheet workbook with various options in a React application. This includes settings for language, toolbar, display elements, and context menus. ```tsx import React, { useState, useCallback } from "react"; import { Workbook } from "@fortune-sheet/react"; import { Sheet } from "@fortune-sheet/core"; function ConfiguredWorkbook() { const [data, setData] = useState([{ name: "Sheet1" }]); return ( setData(d)} lang="en" // "en" | "zh" | "zh_tw" | "es" row={100} // Default rows for empty workbook column={26} // Default columns for empty workbook showToolbar={true} // Show/hide toolbar showFormulaBar={true} // Show/hide formula bar showSheetTabs={true} // Show/hide sheet tabs devicePixelRatio={2} // High DPI support rowHeaderWidth={46} // Row header width (0 to hide) columnHeaderHeight={20} // Column header height (0 to hide) defaultFontSize={11} // Default font size toolbarItems={[ "undo", "redo", "|", "format-painter", "clear-format", "|", "bold", "italic", "underline", "strike-through", "|", "font-color", "background", "border", "|", "merge-cell", "horizontal-align", "vertical-align", "|", "freeze", "filter", "formula", "screenshot" ]} cellContextMenu={[ "copy", "paste", "|", "insert-row", "insert-column", "delete-row", "delete-column", "|", "clear", "sort", "orderAZ", "orderZA" ]} sheetTabContextMenu={[ "delete", "copy", "rename", "color", "hide", "|", "move" ]} /> ); } ``` -------------------------------- ### Cell Data and Range Expansion Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md APIs for expanding ranges into cell coordinates, retrieving cell objects, and getting cell values. ```APIDOC ## POST /getFlattenRange ### Description Expands a given range object into a list of individual cell coordinates. ### Method POST ### Endpoint /getFlattenRange ### Parameters #### Request Body - **range** ({ row: number[], column: number[] }) - Required - A range object specifying the rows and columns to expand. ### Response #### Success Response (200) - **cells** (array) - An array of cell coordinate objects, e.g. [{ "r": 0, "c": 0 }, ...] ### Request Example ```json { "range": {"row": [0, 1], "column": [0, 2]} } ``` ### Response Example ```json [ {"r": 0, "c": 0}, {"r": 0, "c": 1}, {"r": 0, "c": 2}, {"r": 1, "c": 0}, {"r": 1, "c": 1}, {"r": 1, "c": 2} ] ``` ## POST /getCellsByFlattenRange ### Description Retrieves cell objects based on a list of flattened cell coordinates. ### Method POST ### Endpoint /getCellsByFlattenRange ### Parameters #### Request Body - **range** ({ r: number, c: number }[]) - Required - A list of cell coordinates. ### Response #### Success Response (200) - **cells** (array) - A list of cell objects corresponding to the provided coordinates. ## GET /getSelectionCoordinates ### Description Gets a list of text representations for the current selection coordinates. ### Method GET ### Endpoint /getSelectionCoordinates ### Response #### Success Response (200) - **coordinates** (string[]) - An array of strings representing selection coordinates, e.g. ["E10:E14", "A7:B13", ...] ## POST /getCellsByRange ### Description Maps a given range or list of ranges to their corresponding cell objects. ### Method POST ### Endpoint /getCellsByRange ### Parameters #### Request Body - **range** ({ row: number[], column: number[] }[]) - Required - A list of range objects. - **options** ([CommonOptions](#commonoptions)) - Optional - Common options ### Response #### Success Response (200) - **cells** (array) - A list of cell objects within the specified ranges. ## POST /getHtmlByRange ### Description Retrieves an HTML representation of the cells within the specified range(s), useful for pasting into other applications. ### Method POST ### Endpoint /getHtmlByRange ### Parameters #### Request Body - **range** ({ row: number[], column: number[] }[]) - Required - A list of range objects. - **options** ([CommonOptions](#commonoptions)) - Optional - Common options ### Response #### Success Response (200) - **html** (string) - An HTML string representing the specified range. ``` -------------------------------- ### Real-time Collaboration with Presence API in React Source: https://context7.com/ruilisi/fortune-sheet/llms.txt Demonstrates how to use the Presence API in a React component to show collaborator cursors and selections in real-time. It includes functions to add and remove collaborators and tracks the current user's selection changes. ```tsx import React, { useRef, useState, useCallback, useEffect } from "react"; import { Workbook, WorkbookInstance } from "@fortune-sheet/react"; import { Sheet, Selection, colors } from "@fortune-sheet/core"; function PresenceExample() { const workbookRef = useRef(null); const [data, setData] = useState([ { id: "sheet1", name: "Sheet1", order: 0 }, ]); const addCollaborator = () => { // Add a collaborator's presence (cursor position) workbookRef.current?.addPresences([ { sheetId: "sheet1", username: "Alice", userId: "user-123", color: colors[0], // "#5B9BD5" selection: { r: 2, c: 3 }, // Cell D3 }, ]); }; const removeCollaborator = () => { // Remove a collaborator's presence workbookRef.current?.removePresences([ { userId: "user-123" }, ]); }; // Track current user's selection changes const hooks = { afterSelectionChange: (sheetId: string, selection: Selection) => { console.log(`Selection changed to row ${selection.row}, col ${selection.column}`); // Send to server for broadcasting to other users }, }; return (
); } ``` -------------------------------- ### Get Current Selection Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Retrieves the currently selected range or cells within the spreadsheet. This function does not take any arguments and returns an array representing the current selection. ```javascript getSelection() ``` -------------------------------- ### Access Supported Formulas in Formula Parser Source: https://github.com/ruilisi/fortune-sheet/blob/master/packages/formula-parser/README.md Shows how to access the list of all formulas supported by the Formula Parser library. This can be done by importing `SUPPORTED_FORMULAS` from the package. ```javascript require("hot-formula-parser").SUPPORTED_FORMULAS; // An array of formula names ``` -------------------------------- ### Undo/Redo and Scroll API Source: https://context7.com/ruilisi/fortune-sheet/llms.txt This section covers the implementation of undo/redo functionality and programmatic scrolling within the Fortune Sheet component. It provides examples of how to trigger these actions using the `workbookRef`. ```APIDOC ## Undo/Redo and Scroll API ### Description Implement undo/redo functionality and programmatic scrolling. ### Methods #### `handleUndo()` Triggers the undo action, reverting the last change made to the sheet. #### `handleRedo()` Triggers the redo action, reapplying the last undone change. #### `scroll(options)` Programmatically scrolls the sheet view. Accepts an options object: - `targetRow` (number): Scrolls to the specified row. - `targetColumn` (number): Scrolls to the specified column. - `scrollLeft` (number): Scrolls horizontally by the specified pixel amount. - `scrollTop` (number): Scrolls vertically by the specified pixel amount. ### Request Example ```javascript // Example of making changes and then undoing them workbookRef.current?.setCellValue(0, 1, "Change 1"); workbookRef.current?.handleUndo(); // Example of scrolling to a specific row workbookRef.current?.scroll({ targetRow: 50 }); // Example of scrolling to a specific pixel position workbookRef.current?.scroll({ scrollLeft: 100, scrollTop: 500, }); // Example of scrolling to a specific cell workbookRef.current?.scroll({ targetRow: 80, targetColumn: 5, }); ``` ### Response N/A (These are methods that trigger actions, not data retrieval endpoints.) ``` -------------------------------- ### Define and Use Custom Functions in Formula Parser Source: https://github.com/ruilisi/fortune-sheet/blob/master/packages/formula-parser/README.md Shows how to extend the Formula Parser's capabilities by defining custom functions using `.setFunction()`. These functions can then be called within parsed expressions, allowing for specialized calculations. ```javascript parser.setFunction("ADD_5", function (params) { return params[0] + 5; }); parser.setFunction("GET_LETTER", function (params) { var string = params[0]; var index = params[1] - 1; return string.charAt(index); }); parser.parse("SUM(4, ADD_5(1))"); // returns `10` parser.parse('GET_LETTER("Some string", 3)'); // returns `m` ``` -------------------------------- ### Delete Rows or Columns in Fortune Sheet Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Deletes a range of rows or columns from the worksheet. The start and end parameters define the inclusive range of rows or columns to be removed. ```javascript workbookRef.current.deleteRowOrColumn("row", 5, 10); workbookRef.current.deleteRowOrColumn("column", 2, 4); ``` -------------------------------- ### Custom Cell Context Menu Configuration (JSON) Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/config.md Specifies the configuration for the custom context menu that appears when a cell is right-clicked. This JSON array lists the available actions, including copy, paste, row/column operations, and sorting. ```json [ "copy", "paste", "|", "insert-row", "insert-column", "delete-row", "delete-column", "delete-cell", "hide-row", "hide-column", "set-row-height", "set-column-width", "|", "clear", "sort", "orderAZ", // Ascending order sort "orderZA", // Descending order sort ] ``` -------------------------------- ### Get Selection Coordinates as Text Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Retrieves the current selection in a human-readable text format, similar to how ranges are represented in spreadsheet software (e.g., 'A1:C5'). This function does not take any arguments. ```javascript getSelectionCoordinates() ``` -------------------------------- ### Workbook Lifecycle Hooks Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/config.md Functions triggered before and after the workbook is destroyed. They receive the workbook configuration as a parameter. ```javascript workbookDestroyBefore(book) { // Code to execute before workbook destruction } workbookDestroyAfter(book) { // Code to execute after workbook destruction } ``` -------------------------------- ### Custom Toolbar Items Configuration (JSON) Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/config.md Defines the structure for customizing the toolbar items in Fortune Sheet. This JSON array specifies which buttons and separators appear on the toolbar, allowing for a tailored user interface. ```json [ "undo", "redo", "format-painter", "clear-format", "|", "currency-format", "percentage-format", "number-decrease", "number-increase", "format", "|", "font", "|", "font-size", "|", "bold", "italic", "strike-through", "underline", "|", "font-color", "background", "border", "merge-cell", "|", "horizontal-align", "vertical-align", "text-wrap", "text-rotation", "|", "freeze", "conditionFormat", "filter", "link", "image", "comment", "quick-formula", "dataVerification", "splitColumn", "locationCondition", "screenshot", "search", ] ``` -------------------------------- ### Get HTML Representation of Range Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Generates an HTML string for a specified range, suitable for copying and pasting into other applications like Excel. It takes an array of range objects and optional common options. ```javascript getHtmlByRange(range, [options]) ``` -------------------------------- ### Get Column Widths in Batch Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md Retrieves the widths of specified columns in a spreadsheet. It accepts an array of column indexes and optional common options. The function returns a map of column indexes to their respective widths. ```javascript getColumnWidth(columns, [options]) ``` -------------------------------- ### Undo/Redo API Source: https://github.com/ruilisi/fortune-sheet/blob/master/docs/guide/api.md APIs for undoing and redoing actions. ```APIDOC ## POST /api/undo ### Description Reverts the last action performed. ### Method POST ### Endpoint /api/undo ### Response #### Success Response (200) - **success** (boolean) - Indicates if the undo operation was successful. #### Response Example ```json { "success": true } ``` --- ## POST /api/redo ### Description Re-applies the last undone action. ### Method POST ### Endpoint /api/redo ### Response #### Success Response (200) - **success** (boolean) - Indicates if the redo operation was successful. #### Response Example ```json { "success": true } ``` ```