General API
The Facade APIs available in Univer depend on the document type. This page covers the general APIs, which behave the same way in every document type.
Importing
import { FUniver } from '@univerjs/core/facade'const univerAPI = FUniver.newAPI(univer)Concepts
Commands
Most operations in Univer are registered with the command system and run through it. Because every operation follows the same path, Univer can support undo, redo, and collaboration.
Commands
Nearly every operation in Univer is registered with the command system and triggered through it. Centralizing all operations in one place is what makes features such as undo, redo, and collaboration practical.
A command can be understood as a unique "event" inside Univer. For the design details, see command-system.
Listening commands
Univer provides two points at which to listen to a command: before it executes and after it executes.
Event.BeforeCommandExecuteruns custom logic before the command executes.Event.CommandExecutedruns custom logic after the command executes.
Listening commands before execution
Pass Event.BeforeCommandExecute to FUniver.addEvent to register a preprocessing listener. The listener's code runs before the command executes.
const univerAPI = FUniver.newAPI(univer)univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, ({ id, type, params }) => { // Custom logic executed before the command is executed})To prevent the command from executing, set event.cancel to true in the callback.
const univerAPI = FUniver.newAPI(univer)univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, (event) => { event.cancel = true})Listening commands after execution
Pass Event.CommandExecuted to FUniver.addEvent to register a post-processing listener. Its code runs after the command has executed.
const univerAPI = FUniver.newAPI(univer)univerAPI.addEvent(univerAPI.Event.CommandExecuted, ({ id, type, params }) => { // Custom logic executed after the command is executed})Cancel listening
Registering a command listener returns an IDisposable object. Call IDisposable.dispose to destroy it.
Destroy listeners that are no longer in use. Releasing them helps keep the program stable.
const univerAPI = FUniver.newAPI(univer)// Register a listenerconst disposable = univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, () => { // custom preprocessing logic before the command is executed})// Example: Destroy the listener after 1 secondsetTimeout(() => { // Destroy the listener disposable.dispose()}, 1000)Execute commands
If you already know the command ID and its parameters, you can execute the command directly with FUniver.executeCommand.
For example, the following code sets the value of cell A1 with the sheet.command.set-range-values command:
const univerAPI = FUniver.newAPI(univer)// Execute the commanduniverAPI.executeCommand('sheet.command.set-range-values', { value: { v: 'Hello, Univer!' }, range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },})Events API
Univer dispatches events for changes that occur inside a spreadsheet, so an application can listen for them and respond. The events fall into groups such as clipboard operations, selection changes, cell interactions, sheet modifications, and a few others.
Event categories
Full event list: /reference/facade/events
-
Clipboard Events
BeforeClipboardChange: fires before the clipboard content changes; setparams.cancel = trueto block the changeBeforeClipboardPaste: fires before content is pasted; setparams.cancel = trueto block the pasteClipboardChanged: fires after the clipboard content changes, with the new contentClipboardPasted: fires after content is pasted, with the pasted content
-
Selection Events
SelectionChanged: fires when the selection changes, with the new selection rangeSelectionMoveStart: fires when the selection starts moving, which allows custom selection effectsSelectionMoveEnd: fires when the selection stops moving, with the final rangeSelectionMoving: fires while the selection moves, which supports live UI updatesDragOver: fires while content is dragged over cellsDrop: fires when the dragged content is dropped
-
Cell Events
CellClicked: fires when a cell is clicked, with its position and contentCellHover: fires when the pointer hovers over a cell, which supports tooltipsCellPointerDown: fires when the pointer is pressed on a cell; used to start a drag or a selectionCellPointerUp: fires when the pointer is released on a cell; used to finish an operationCellPointerMove: fires when the pointer moves over cells
-
Sheet Events
SheetValueChanged: fires when sheet values change, with the changed range and the new valuesSheetZoomChanged: fires when the zoom level changes, with the new zoom ratioSheetSkeletonChanged: fires when the sheet structure changes, for example when rows or columns are inserted or deletedBeforeSheetEditStart: fires before cell editing starts; used to control whether editing is allowedSheetEditStarted: fires when cell editing begins; used for custom editor behaviorBeforeSheetEditEnd: fires before cell editing ends; used to validate the contentSheetEditEnded: fires when cell editing ends, with the edited valueSheetEditChanging: fires during cell editing; used for live validation or formattingScroll: fires when the sheet scrolls, with the scroll positionCrosshairHighlightEnabledChanged: fires when crosshair highlight is enabled or disabled
-
Header Events
RowHeaderClick: fires when a row header is clickedRowHeaderHover: fires when the pointer hovers over a row headerColumnHeaderClick: fires when a column header is clickedColumnHeaderHover: fires when the pointer hovers over a column header
-
Data Validation Events
BeforeSheetDataValidationAdd: fires before a data validation rule is addedSheetDataValidationChanged: fires when data validation rules changeSheetDataValidatorStatusChanged: fires when the data validation status changes
-
Comment Events
BeforeCommentAdd: fires before a comment is addedCommentAdded: fires after a comment is addedBeforeCommentUpdate: fires before a comment is updatedCommentUpdated: fires after a comment is updatedBeforeCommentDeleted: fires before a comment is deletedCommentDeleted: fires after a comment is deleted
-
Data Processing Events
SheetBeforeRangeSort: fires before a range is sortedSheetRangeSorted: fires after a range is sortedSheetBeforeRangeFilter: fires before a range is filteredSheetRangeFiltered: fires after a range is filteredBeforePivotTableAdd: fires before a pivot table is addedPivotTableAdded: fires after a pivot table is added
Using events
Call addEvent on univerAPI to register a listener. The pattern is the same for every event:
univerAPI.addEvent(univerAPI.Event.EventName, (params) => { // Handle event parameters})Example: listening to cell clicks
univerAPI.addEvent(univerAPI.Event.CellClicked, (params) => { const { worksheet, workbook, row, column } = params console.log(`Cell clicked at row ${row}, column ${column}`)})Example: monitoring clipboard operations
univerAPI.addEvent(univerAPI.Event.BeforeClipboardPaste, (params) => { const { text, html } = params // If you want to cancel the clipboard paste params.cancel = true})Example: tracking selection changes
univerAPI.addEvent(univerAPI.Event.SelectionChanged, (params) => { const { worksheet, workbook, selections } = params console.log('Selection changed:', selections)})Canceling event listeners
Event listeners return an IDisposable object; use it to remove the listener when it is no longer needed:
const disposable = univerAPI.addEvent(univerAPI.Event.SheetValueChanged, (params) => { // Handle value changes})// Later, when you want to remove the listener:disposable.dispose()Best practices
- Dispose of event listeners that are no longer needed; otherwise they leak memory.
- Choose the event that matches the use case, and prefer a specific event over a general one.
- Keep event handlers lightweight, because they run every time the event fires.
- To block the default behavior, use
BeforeClipboardChangeor another "before" event.
Undo and redo
Undo
await univerAPI.undo()Redo
await univerAPI.redo()System clipboard
FUniver.copy() and FUniver.paste() read from and write to the system clipboard.
Copy and paste rely on the browser's native API. If the environment or its permissions do not permit them, neither operation works. See the MDN documentation.
The following example copies and pastes a sheet range.
// Prevent failure due to loss of focus when executing copy and paste code in the console,// this example listens for the cell click event and executes the copy and paste code.univerAPI.addEvent(univerAPI.Event.CellClicked, async (params) => { const fWorkbook = univerAPI.getActiveWorkbook() const fWorksheet = fWorkbook.getActiveSheet() // Copy the range A1:B2 to the clipboard const fRange = fWorksheet.getRange('A1:B2') fRange.activate().setValues([ [1, 2], [3, 4], ]) await univerAPI.copy() // Paste the copied content to the range C1:D2 const fRange2 = fWorksheet.getRange('C1') fRange2.activate() await univerAPI.paste() // Check the pasted content console.log(fWorksheet.getRange('C1:D2').getValues()) // [[1, 2], [3, 4]]})The clipboard commands can also be executed through the command system:
import { CopyCommand, PasteCommand } from '@univerjs/ui'// CopyuniverAPI.executeCommand(CopyCommand.id)// PasteuniverAPI.executeCommand(PasteCommand.id)UI
To extend the Univer UI, see the following page:
WebSocket
The Facade API provides createSocket. Given a URL, it opens a WebSocket connection. The connection exposes the open, message, close, and error events; messages are sent with the send method, and the connection is closed with the close method.
In a Presets installation, univerAPI.createSocket(url) can be called directly. In a piecemeal installation, install the @univerjs/network package and register UniverNetworkPlugin.
// ... Omits other plugin importsimport { UniverNetworkPlugin } from '@univerjs/network'// ... Omits other facade importsimport '@univerjs/network/facade'// ... Omits other plugin registrationsuniver.registerPlugin(UniverNetworkPlugin)The following is a minimal example:
// Replace the URL with the address of your own WebSocket serviceconst ws = univerAPI.createSocket('ws://47.100.177.253:8449/ws')ws.open$.subscribe(() => { console.log('websocket opened') ws.send('hello')})ws.message$.subscribe((message) => { console.log('websocket message', message) const content = JSON.parse(message.data).content if (!content.includes('command')) { return } const commandInfo = JSON.parse(content) const { command, options } = commandInfo const { id, params } = command // Upon receiving collaborative data, it is locally saved univerAPI.executeCommand(id, params, options)})ws.close$.subscribe(() => { console.log('websocket closed')})ws.error$.subscribe((error) => { console.log('websocket error', error)})univerAPI.addEvent(univerAPI.Event.CommandExecuted, ({ id, type, params, options }) => { // Only synchronize local mutations if ( type !== univerAPI.Enum.CommandType.MUTATION || options?.fromCollab || options?.onlyLocal || id === 'doc.mutation.rich-text-editing' ) { return } const commandInfo = JSON.stringify({ command: { id, type, params }, options: { fromCollab: true } }) ws.send(commandInfo)})Univer must start with a unitID; collaboration does not work without one.
Register formula
Custom formulas can be registered on the current Univer instance through the Facade API.
The following example calls registerFunction once to register the algorithm, name, and description that a CUSTOMSUM formula requires into the formula plugin. The formula is then available: typing =CUSTOMSUM in any blank cell displays the prompt.
// Registered formulas support lambda functionsconst formulaEngine = univerAPI.getFormula()formulaEngine.registerFunction( 'CUSTOMSUM', (...variants) => { let sum = 0 const last = variants[variants.length - 1] if (last.isLambda && last.isLambda()) { variants.pop() const variantsList = variants.map((variant) => (Array.isArray(variant) ? variant[0][0] : variant)) sum += last.executeCustom(...variantsList).getValue() } for (const variant of variants) { sum += Number(variant) || 0 } return sum }, 'Adds its arguments',)// Use the function in a cellconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const cellA1 = fWorksheet.getRange('A1')cellA1.setValue(1)const cellA2 = fWorksheet.getRange('A2')cellA2.setValue(2)const cellA3 = fWorksheet.getRange('A3')cellA3.setValue({ f: '=CUSTOMSUM(A1,A2,LAMBDA(x,y,x*y))' })// A3 will display: 5formulaEngine.calculationEnd((functionsExecutedState) => { if (functionsExecutedState === 3) { console.log(cellA3.getValue()) // 5 }})Call dispose to unregister the formula.
const functionDisposable = formulaEngine.registerFunction({ // calculate})// Unregister the functionfunctionDisposable.dispose()To provide more complete internationalized content and descriptions, set the locales and description fields as well:
formulaEngine.registerFunction( 'CUSTOMSUM', (...variants) => { let sum = 0 const last = variants[variants.length - 1] if (last.isLambda && last.isLambda()) { variants.pop() const variantsList = variants.map((variant) => (Array.isArray(variant) ? variant[0][0] : variant)) sum += last.executeCustom(...variantsList).getValue() } for (const variant of variants) { sum += Number(variant) || 0 } return sum }, { description: { functionName: 'CUSTOMSUM', description: 'formulaCustom.CUSTOMSUM.description', abstract: 'formulaCustom.CUSTOMSUM.abstract', functionParameter: [ { name: 'formulaCustom.CUSTOMSUM.functionParameter.number1.name', detail: 'formulaCustom.CUSTOMSUM.functionParameter.number1.detail', example: 'A1:A20', require: 1, repeat: 0, }, { name: 'formulaCustom.CUSTOMSUM.functionParameter.number2.name', detail: 'formulaCustom.CUSTOMSUM.functionParameter.number2.detail', example: 'B2:B10', require: 0, repeat: 1, }, ], }, locales: { zhCN: { formulaCustom: { CUSTOMSUM: { description: '将单个值、单元格引用或是区域相加,或者将三者的组合相加。', abstract: '求参数的和', functionParameter: { number1: { name: '数值1', detail: '要相加的第一个数字。 该数字可以是 4 之类的数字,B6 之类的单元格引用或 B2:B8 之类的单元格范围。', }, number2: { name: '数值2', detail: '这是要相加的第二个数字。 可以按照这种方式最多指定 255 个数字。', }, }, }, }, }, enUS: { formulaCustom: { CUSTOMSUM: { description: `You can add individual values, cell references or ranges or a mix of all three.`, abstract: `Adds its arguments`, functionParameter: { number1: { name: 'number1', detail: 'The first number you want to add. The number can be like 4, a cell reference like B6, or a cell range like B2:B8.', }, number2: { name: 'number2', detail: 'This is the second number you want to add. You can specify up to 255 numbers in this way.', }, }, }, }, }, }, },)The options are described below.
funcholds the algorithm and the name mapping for the formula. Its input is what the user enters when using the formula, which can be a number, a string, a Boolean value, or an array.descriptionsets the description of the custom formula.localescan hold several languages; the naming rules are described in LocaleType.functionListcan hold translations for more than one formula. For field details, see the How to add formulas in Formula Engine section.
To reuse the algorithm that the formula system already provides and extend it, register a custom formula through plugin configuration. See Custom Formula for the walkthrough.
Enum API
The Facade API includes the enum types used during development, for example:
console.log(univerAPI.Enum)console.log(univerAPI.Enum.UniverInstanceType.UNIVER_SHEET)console.log(univerAPI.Enum.LifecycleStages.Rendered)Utility method API
The Facade API also includes a set of utility methods, for example:
console.log(univerAPI.Util)console.log(univerAPI.Util.tools.chatAtABC(10))console.log(univerAPI.Util.tools.ABCatNum('K'))How is this guide?