Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

docs(facade): supplement notes and example (#4686)

wpxp1234562d4e41921994
diff --git a/packages/sheets-filter/src/facade/f-event.ts b/packages/sheets-filter/src/facade/f-event.ts
index 5bdcd5f391..0fc23770bc 100644
--- a/packages/sheets-filter/src/facade/f-event.ts
+++ b/packages/sheets-filter/src/facade/f-event.ts
@@ -29,53 +29,74 @@ import { FSheetEventName } from '@univerjs/sheets/facade';
export interface IFSheetFilterEventMixin {
/**
* This event will be emitted when the filter criteria on a column is changed.
- * Type of the event is {@link ISheetRangeFilteredParams}.
+ * @see {@link ISheetRangeFilteredParams}
* @example
* ```typescript
* const callbackDisposable = univerAPI.addEvent(univerAPI.Event.SheetRangeFiltered, (params) => {
+ * console.log(params);
* const { workbook, worksheet, col, criteria } = params;
*
* // your custom logic
* });
+ *
+ * // Remove the event listener, use `callbackDisposable.dispose()`
* ```
*/
readonly SheetRangeFiltered: 'SheetRangeFiltered';
+
/**
* This event will be emitted before the filter criteria on a column is changed.
- * Type of the event is {@link ISheetRangeFilteredParams}.
+ * @see {@link ISheetRangeFilteredParams}
* @example
* ```typescript
* const callbackDisposable = univerAPI.addEvent(univerAPI.Event.SheetBeforeRangeFilter, (params) => {
+ * console.log(params);
* const { workbook, worksheet, col, criteria } = params;
*
* // your custom logic
+ *
+ * // Cancel the filter criteria change operation
+ * params.cancel = true;
* });
+ *
+ * // Remove the event listener, use `callbackDisposable.dispose()`
* ```
*/
readonly SheetBeforeRangeFilter: 'SheetBeforeRangeFilter';
+
/**
* This event will be emitted when the filter on a worksheet is cleared.
- * Type of the event is {@link ISheetRangeFilterClearedEventParams}.
+ * @see {@link ISheetRangeFilterClearedEventParams}
* @example
* ```typescript
* const callbackDisposable = univerAPI.addEvent(univerAPI.Event.SheetRangeFilterCleared, (params) => {
+ * console.log(params);
* const { workbook, worksheet } = params;
*
* // your custom logic
* });
+ *
+ * // Remove the event listener, use `callbackDisposable.dispose()`
* ```
*/
readonly SheetRangeFilterCleared: 'SheetRangeFilterCleared';
+
/**
* This event will be emitted after the filter on a worksheet is cleared.
- * Type of the event is {@link ISheetRangeFilterClearedEventParams}.
+ * @see {@link ISheetRangeFilterClearedEventParams}
* @example
* ```typescript
* const callbackDisposable = univerAPI.addEvent(univerAPI.Event.SheetBeforeRangeFilterClear, (params) => {
+ * console.log(params);
* const { workbook, worksheet } = params;
*
* // your custom logic
+ *
+ * // Cancel the filter clear operation
+ * params.cancel = true;
* });
+ *
+ * // Remove the event listener, use `callbackDisposable.dispose()`
* ```
*/
readonly SheetBeforeRangeFilterClear: 'SheetBeforeRangeFilterClear';
@@ -206,9 +227,6 @@ class FUniverSheetsFilterEventMixin extends FUniver {
};
this.fireEvent(this.Event.SheetRangeFiltered, eventParams);
- if (eventParams.cancel) {
- throw new Error('SetSheetsFilterCriteriaCommand canceled.');
- }
}
private _beforeRangeFilterClear(): void {
@@ -236,9 +254,6 @@ class FUniverSheetsFilterEventMixin extends FUniver {
};
this.fireEvent(this.Event.SheetRangeFilterCleared, eventParams);
- if (eventParams.cancel) {
- throw new Error('SetSheetsFilterCriteriaCommand canceled.');
- }
}
}
diff --git a/packages/sheets-filter/src/facade/f-filter.ts b/packages/sheets-filter/src/facade/f-filter.ts
index fd7b1c12ef..ed7f2f1ae0 100644
--- a/packages/sheets-filter/src/facade/f-filter.ts
+++ b/packages/sheets-filter/src/facade/f-filter.ts
@@ -40,6 +40,43 @@ export class FFilter {
/**
* Get the filtered out rows by this filter.
* @returns {number[]} Filtered out rows by this filter.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13],
+ * ]);
+ *
+ * // Create a filter on the range
+ * let fFilter = fRange.createFilter();
+ *
+ * // If the filter already exists, remove it and create a new one
+ * if (!fFilter) {
+ * fRange.getFilter().remove();
+ * fFilter = fRange.createFilter();
+ * }
+ *
+ * // Set the filter criteria of the column A
+ * fFilter?.setColumnFilterCriteria(0, {
+ * colId: 0,
+ * filters: {
+ * filters: ['1', '5', '9'],
+ * },
+ * });
+ *
+ * console.log(fFilter?.getFilteredOutRows()); // [1, 2, 3, 5, 6, 7, 9]
+ * ```
*/
getFilteredOutRows(): number[] {
return Array.from(this._filterModel.filteredOutRows).sort();
@@ -47,23 +84,101 @@ export class FFilter {
/**
* Get the filter criteria of a column.
- * @param {number} col The column number.
+ * @param {number} column - The column index.
* @returns {Nullable<IFilterColumn>} The filter criteria of the column.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13],
+ * ]);
+ *
+ * // Create a filter on the range
+ * let fFilter = fRange.createFilter();
+ *
+ * // If the filter already exists, remove it and create a new one
+ * if (!fFilter) {
+ * fRange.getFilter().remove();
+ * fFilter = fRange.createFilter();
+ * }
+ *
+ * // Set the filter criteria of the column A
+ * fFilter?.setColumnFilterCriteria(0, {
+ * colId: 0,
+ * filters: {
+ * filters: ['1', '5', '9'],
+ * },
+ * });
+ *
+ * console.log(fFilter?.getColumnFilterCriteria(0)); // { colId: 0, filters: { filters: ['1', '5', '9'] } }
+ * console.log(fFilter?.getColumnFilterCriteria(1)); // undefined
+ * ```
*/
- getColumnFilterCriteria(col: number): Nullable<IFilterColumn> {
- return this._filterModel.getFilterColumn(col)?.getColumnData();
+ getColumnFilterCriteria(column: number): Nullable<IFilterColumn> {
+ return this._filterModel.getFilterColumn(column)?.getColumnData();
}
/**
* Clear the filter criteria of a column.
- * @param {number} col The column number.
- * @returns {FFilter} The interface class to handle the filter.
+ * @param {number} column - The column index.
+ * @returns {FFilter} The FFilter instance for chaining.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13],
+ * ]);
+ *
+ * // Create a filter on the range
+ * let fFilter = fRange.createFilter();
+ *
+ * // If the filter already exists, remove it and create a new one
+ * if (!fFilter) {
+ * fRange.getFilter().remove();
+ * fFilter = fRange.createFilter();
+ * }
+ *
+ * // Set the filter criteria of the column A
+ * fFilter?.setColumnFilterCriteria(0, {
+ * colId: 0,
+ * filters: {
+ * filters: ['1', '5', '9'],
+ * },
+ * });
+ *
+ * // Clear the filter criteria of the column A after 3 seconds
+ * setTimeout(() => {
+ * fFilter?.removeColumnFilterCriteria(0);
+ * }, 3000);
+ * ```
*/
- removeColumnFilterCriteria(col: number): FFilter {
+ removeColumnFilterCriteria(column: number): FFilter {
this._commandSrv.syncExecuteCommand(SetSheetsFilterCriteriaCommand.id, {
unitId: this._workbook.getUnitId(),
subUnitId: this._worksheet.getSheetId(),
- col,
+ col: column,
criteria: null,
} as ISetSheetsFilterCriteriaCommandParams);
return this;
@@ -71,15 +186,50 @@ export class FFilter {
/**
* Set the filter criteria of a column.
- * @param {number} col The column number.
- * @param {ISetSheetsFilterCriteriaCommandParams['criteria']} criteria The new filter criteria.
- * @returns {FFilter} The interface class to handle the filter.
+ * @param {number} column - The column index.
+ * @param {ISetSheetsFilterCriteriaCommandParams['criteria']} criteria - The new filter criteria.
+ * @returns {FFilter} The FFilter instance for chaining.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13],
+ * ]);
+ *
+ * // Create a filter on the range
+ * let fFilter = fRange.createFilter();
+ *
+ * // If the filter already exists, remove it and create a new one
+ * if (!fFilter) {
+ * fRange.getFilter().remove();
+ * fFilter = fRange.createFilter();
+ * }
+ *
+ * // Set the filter criteria of the column A
+ * fFilter?.setColumnFilterCriteria(0, {
+ * colId: 0,
+ * filters: {
+ * filters: ['1', '5', '9'],
+ * },
+ * });
+ * ```
*/
- setColumnFilterCriteria(col: number, criteria: ISetSheetsFilterCriteriaCommandParams['criteria']): FFilter {
+ setColumnFilterCriteria(column: number, criteria: ISetSheetsFilterCriteriaCommandParams['criteria']): FFilter {
this._commandSrv.syncExecuteCommand(SetSheetsFilterCriteriaCommand.id, {
unitId: this._workbook.getUnitId(),
subUnitId: this._worksheet.getSheetId(),
- col,
+ col: column,
criteria,
} as ISetSheetsFilterCriteriaCommandParams);
return this;
@@ -88,6 +238,13 @@ export class FFilter {
/**
* Get the range of the filter.
* @returns {FRange} The range of the filter.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fFilter = fWorksheet.getFilter();
+ * console.log(fFilter?.getRange().getA1Notation());
+ * ```
*/
getRange(): FRange {
const range = this._filterModel.getRange();
@@ -96,7 +253,47 @@ export class FFilter {
/**
* Remove the filter criteria of all columns.
- * @returns {Promise<boolean>} If the filter criteria is removed.
+ * @returns {FFilter} The FFilter instance for chaining.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13],
+ * ]);
+ *
+ * // Create a filter on the range
+ * let fFilter = fRange.createFilter();
+ *
+ * // If the filter already exists, remove it and create a new one
+ * if (!fFilter) {
+ * fRange.getFilter().remove();
+ * fFilter = fRange.createFilter();
+ * }
+ *
+ * // Set the filter criteria of the column A
+ * fFilter?.setColumnFilterCriteria(0, {
+ * colId: 0,
+ * filters: {
+ * filters: ['1', '5', '9'],
+ * },
+ * });
+ *
+ * // Clear the filter criteria of all columns after 3 seconds
+ * setTimeout(() => {
+ * fFilter?.removeFilterCriteria();
+ * }, 3000);
+ * ```
*/
removeFilterCriteria(): FFilter {
this._commandSrv.syncExecuteCommand(ClearSheetsFilterCriteriaCommand.id);
@@ -105,7 +302,21 @@ export class FFilter {
/**
* Remove the filter from the worksheet.
- * @returns {boolean} If the filter is removed.
+ * @returns {boolean} True if the filter is removed successfully; otherwise, false.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D14');
+ * let fFilter = fRange.createFilter();
+ *
+ * // If the worksheet already has a filter, remove it and create a new filter.
+ * if (!fFilter) {
+ * fWorksheet.getFilter().remove();
+ * fFilter = fRange.createFilter();
+ * }
+ * console.log(fFilter);
+ * ```
*/
remove(): boolean {
return this._commandSrv.syncExecuteCommand(RemoveSheetFilterCommand.id, {
diff --git a/packages/sheets-filter/src/facade/f-range.ts b/packages/sheets-filter/src/facade/f-range.ts
index 17a5f86e2a..ff73018a82 100644
--- a/packages/sheets-filter/src/facade/f-range.ts
+++ b/packages/sheets-filter/src/facade/f-range.ts
@@ -28,26 +28,41 @@ import { FFilter } from './f-filter';
export interface IFRangeFilter {
/**
* Create a filter for the current range. If the worksheet already has a filter, this method would return `null`.
- * @returns The interface class to handle the filter. If the worksheet already has a filter,
- * this method would return `null`.
+ * @returns {FFilter | null} The FFilter instance to handle the filter.
* @example
* ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const worksheet = workbook.getActiveSheet();
- * const filter = worksheet.getRange('A1:D14').createFilter();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D14');
+ * let fFilter = fRange.createFilter();
+ *
+ * // If the worksheet already has a filter, remove it and create a new filter.
+ * if (!fFilter) {
+ * fWorksheet.getFilter().remove();
+ * fFilter = fRange.createFilter();
+ * }
+ * console.log(fFilter);
* ```
*/
createFilter(this: FRange): FFilter | null;
+
/**
- * Get the filter for the current range's worksheet. Normally, you can directly call `getFilter` on {@link FWorksheet}.
- * @returns {FFilter | null} The interface class to handle the filter. If the worksheet does not have a filter,
- * this method would return `null`.
+ * Get the filter in the worksheet to which the range belongs. If the worksheet does not have a filter, this method would return `null`.
+ * Normally, you can directly call `getFilter` on {@link FWorksheet}.
+ * @returns {FFilter | null} The FFilter instance to handle the filter.
* @example
* ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const worksheet = workbook.getActiveSheet();
- * const filter = worksheet.getRange('A1:D14').getFilter();
- * ````
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D14');
+ * let fFilter = fRange.getFilter();
+ *
+ * // If the worksheet does not have a filter, create a new filter.
+ * if (!fFilter) {
+ * fFilter = fRange.createFilter();
+ * }
+ * console.log(fFilter);
+ * ```
*/
getFilter(): FFilter | null;
}
diff --git a/packages/sheets-filter/src/facade/f-worksheet.ts b/packages/sheets-filter/src/facade/f-worksheet.ts
index 01da1fbdcb..ec5d9844b4 100644
--- a/packages/sheets-filter/src/facade/f-worksheet.ts
+++ b/packages/sheets-filter/src/facade/f-worksheet.ts
@@ -33,9 +33,9 @@ export interface IFWorksheetFilter {
* const workbook = univerAPI.getActiveWorkbook();
* const worksheet = workbook.getActiveSheet();
* const filter = worksheet.getFilter();
- * ````
+ * console.log(filter, filter?.getRange().getA1Notation());
+ * ```
*/
-
getFilter(): FFilter | null;
}
diff --git a/packages/sheets-find-replace/src/facade/f-text-finder.ts b/packages/sheets-find-replace/src/facade/f-text-finder.ts
index 5a50e1ee7c..6c3c5ac2fe 100644
--- a/packages/sheets-find-replace/src/facade/f-text-finder.ts
+++ b/packages/sheets-find-replace/src/facade/f-text-finder.ts
@@ -25,131 +25,323 @@ import { FRange } from '@univerjs/sheets/facade';
*/
export interface IFTextFinder {
/**
- * get all the matched range in the univer
- * @returns all the matched range
- * @throws if the find operation is not completed
+ * Get all the matched cells of the current sheet, the current matched cell is the last matched cell.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @returns {FRange[]} All the matched cells.
+ * @throws If the find operation is not completed.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('hello');
- * const ranges = textFinder.findAll();
- * ranges.forEach((range) => {
- * console.log(range.getA1Notation());
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13]
+ * ]);
+ *
+ * // Create a text-finder to find the text '5'.
+ * const textFinder = await univerAPI.createTextFinderAsync('5');
+ *
+ * // Find all cells that contain the text '5'.
+ * const matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation()); // D2, C3, B4, A5
* });
* ```
*/
findAll(): FRange[];
+
/**
- * find the next matched range in the univer
- * @returns the next matched range
- * @throws if the find operation is not completed
- * @returns null if no more match
+ * Get the next matched cell of the current sheet, if exists return the next matched cell and move the current matched cell to the next matched cell.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @returns {Nullable<FRange>} The next matched cell.
+ * @throws If the find operation is not completed.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('hello');
- * const range = textFinder.findNext();
- * if (range) {
- * console.log(range.getA1Notation());
- * }
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13]
+ * ]);
+ *
+ * // Create a text-finder to find the text '5'.
+ * const textFinder = await univerAPI.createTextFinderAsync('5');
+ * console.log(textFinder.getCurrentMatch().getA1Notation()); // current match cell is A5
+ *
+ * // Find the next matched range
+ * const nextMatch = textFinder.findNext();
+ * console.log(nextMatch.getA1Notation()); // D2
+ * console.log(textFinder.getCurrentMatch().getA1Notation()); // current match cell is D2
* ```
*/
findNext(): Nullable<FRange>;
+
/**
- * find the previous matched range in the univer
- * @returns the previous matched range
- * @throws if the find operation is not completed
- * @returns null if no more match
+ * Get the previous matched cell of the current sheet, if exists return the previous matched cell and move the current matched cell to the previous matched cell.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @returns {Nullable<FRange>} The previous matched cell.
+ * @throws If the find operation is not completed.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('hello');
- * const range = textFinder.findPrevious();
- * if (range) {
- * console.log(range.getA1Notation());
- * }
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13]
+ * ]);
+ *
+ * // Create a text-finder to find the text '5'.
+ * const textFinder = await univerAPI.createTextFinderAsync('5');
+ * console.log(textFinder.getCurrentMatch().getA1Notation()); // current match cell is A5
+ *
+ * // Find the previous matched range.
+ * const previousMatch = textFinder.findPrevious();
+ * console.log(previousMatch.getA1Notation()); // B4
+ * console.log(textFinder.getCurrentMatch().getA1Notation()); // current match cell is B4
* ```
*/
findPrevious(): Nullable<FRange>;
+
/**
- * get the current matched range in the univer
- * @returns the current matched range
- * @throws if the find operation is not completed
+ * Get the current matched cell of the current sheet.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @returns {Nullable<FRange>} The current matched cell.
+ * @throws If the find operation is not completed.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('hello');
- * const range = textFinder.getCurrentMatch();
- * if (range) {
- * console.log(range.getA1Notation());
- * }
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13]
+ * ]);
+ *
+ * // Create a text-finder to find the text '5'.
+ * const textFinder = await univerAPI.createTextFinderAsync('5');
+ *
+ * // Get the current matched range.
+ * const currentMatch = textFinder.getCurrentMatch();
+ * console.log(currentMatch.getA1Notation()); // A5
* ```
*/
getCurrentMatch(): Nullable<FRange>;
/**
- * set the match case option
- * @param {boolean} matchCase whether to match case
- * @returns text-finder instance
+ * Set the match case option, if true, the find operation will match case, otherwise, the find operation will ignore case.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @param {boolean} matchCase - Whether to match case.
+ * @returns {Promise<IFTextFinder>} The text-finder instance.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('hello');
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D1');
+ * fRange.setValues([
+ * ['hello univer', 'hello UNIVER', 'HELLO UNIVER', 'HELLO univer'],
+ * ]);
+ *
+ * // Create a text-finder to find the text 'univer'.
+ * const textFinder = await univerAPI.createTextFinderAsync('univer');
+ * let matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation()); // A1, B1, C1, D1
+ * });
+ *
+ * // Set the match case.
* await textFinder.matchCaseAsync(true);
+ * matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation()); // A1, D1
+ * });
* ```
*/
matchCaseAsync(matchCase: boolean): Promise<IFTextFinder>;
+
/**
- * set the match entire cell option
- * @param {boolean} matchEntireCell whether to match entire cell
- * @returns text-finder instance
+ * Set the match entire cell option, if true, the find operation will match entire cell value, otherwise, the find operation will match part of the cell value.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @param {boolean} matchEntireCell - Whether to match entire cell value.
+ * @returns {Promise<IFTextFinder>} The text-finder instance.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('hello');
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D1');
+ * fRange.setValues([
+ * ['hello univer', 'hello univer 1', 'hello univer 2', 'hello univer 3'],
+ * ]);
+ *
+ * // Create a text-finder to find the text 'hello univer'.
+ * const textFinder = await univerAPI.createTextFinderAsync('hello univer');
+ * let matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation()); // A1, B1, C1, D1
+ * });
+ *
+ * // Set the match entire cell.
* await textFinder.matchEntireCellAsync(true);
+ * matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation()); // A1
+ * });
* ```
*/
matchEntireCellAsync(matchEntireCell: boolean): Promise<IFTextFinder>;
+
/**
- * set the match formula text option
- * @param {boolean} matchFormulaText whether to match formula text
- * @returns text-finder instance
+ * Set the match formula text option, if true, the find operation will match formula text, otherwise, the find operation will match value.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @param {boolean} matchFormulaText - Whether to match formula text.
+ * @returns {Promise<IFTextFinder>} The text-finder instance.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('hello');
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D1');
+ * fRange.setValues([
+ * ['sum', '1', '=SUM(2)', '3'],
+ * ]);
+ *
+ * // Create a text-finder to find the text 'sum'.
+ * const textFinder = await univerAPI.createTextFinderAsync('sum');
+ * let matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation()); // A1
+ * });
+ *
+ * // Set the match entire cell.
* await textFinder.matchFormulaTextAsync(true);
+ * matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation()); // A1, C1
+ * });
* ```
*/
matchFormulaTextAsync(matchFormulaText: boolean): Promise<IFTextFinder>;
+
/**
- * replace all the matched text with the given text
- * @param {string} replaceText the text to replace
- * @returns the number of replaced text
- * @throws if the find operation is not completed
+ * Replace all the matched text with the given text.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @param {string} replaceText - The text to replace.
+ * @returns {Promise<number>} The count of replaced text.
+ * @throws If the find operation is not completed.
* @example
* ```typescript
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D1');
+ * fRange.setValues([
+ * ['hello', 'hello', 'hello', 'hello'],
+ * ]);
+ *
+ * // Create a text-finder to find the text 'hello'.
* const textFinder = await univerAPI.createTextFinderAsync('hello');
- * const replacedCount = await textFinder.replaceAllWithAsync('world');
- * console.log(replacedCount);
+ *
+ * // Replace all the matched text with 'hello univer'.
+ * const count = await textFinder.replaceAllWithAsync('hello univer');
+ * console.log(count); // 4
+ * console.log(fRange.getValues()); // [['hello univer', 'hello univer', 'hello univer', 'hello univer']]
* ```
*/
replaceAllWithAsync(replaceText: string): Promise<number>;
+
/**
- * replace the current matched text with the given text
- * @param {string} replaceText the text to replace
- * @returns whether the replace is successful
- * @throws if the find operation is not completed
+ * Replace the current matched text with the given text.
+ * If current sheet changed, use `await textFinder.ensureCompleteAsync()` to ensure the find operation is completed.
+ * @param {string} replaceText - The text to replace.
+ * @returns {Promise<boolean>} Whether the replace is successful.
+ * @throws If the find operation is not completed.
* @example
* ```typescript
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('B1:E1');
+ * fRange.setValues([
+ * ['hello', 'hello', 'hello', 'hello'],
+ * ]);
+ *
+ * // Create a text-finder to find the text 'hello'.
* const textFinder = await univerAPI.createTextFinderAsync('hello');
- * const replaced = await textFinder.replaceWithAsync('world');
- * console.log(replaced);
+ *
+ * // Replace the current matched text with 'hello univer'.
+ * const replaced = await textFinder.replaceWithAsync('hello univer');
+ * console.log(replaced); // true
+ * console.log(fRange.getValues()); // [['hello', 'hello', 'hello', 'hello univer']]
* ```
*/
replaceWithAsync(replaceText: string): Promise<boolean>;
+
/**
- * ensure the find operation is completed
- * @returns the find complete result
+ * Ensure the find operation is completed. Especially when the current sheet changed use this method to ensure the find operation is completed.
+ * @returns {Promise<Nullable<IFindComplete>>} The find complete result.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('hello');
- * const complete = await textFinder.ensureCompleteAsync();
- * console.log(complete);
+ * // Create a text-finder to find the text '1'.
+ * const textFinder = await univerAPI.createTextFinderAsync('1');
+ *
+ * // Find all cells that contain the text '1'.
+ * const matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation());
+ * });
+ *
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const sheets = fWorkbook.getSheets();
+ *
+ * // Change the current sheet to the second sheet.
+ * sheets[1]?.activate();
+ *
+ * // Ensure the find operation is completed of the current sheet.
+ * await textFinder.ensureCompleteAsync();
+ * const matchCells2 = textFinder.findAll();
+ * matchCells2.forEach((cell) => {
+ * console.log(cell.getA1Notation());
+ * });
* ```
*/
ensureCompleteAsync(): Promise<Nullable<IFindComplete>>;
@@ -219,11 +411,12 @@ export class FTextFinder extends Disposable implements IFTextFinder {
}
async matchCaseAsync(matchCase: boolean): Promise<IFTextFinder> {
- this._state.changeState({ caseSensitive: matchCase });
+ this._state.changeState({ caseSensitive: matchCase, findCompleted: false });
return new Promise((resolve) => {
- const subscribe = this._state.stateUpdates$.subscribe((state) => {
+ const subscribe = this._state.stateUpdates$.subscribe(async (state) => {
if (state.findCompleted === true) {
subscribe.unsubscribe();
+ await this.ensureCompleteAsync();
resolve(this);
}
});
@@ -231,11 +424,12 @@ export class FTextFinder extends Disposable implements IFTextFinder {
}
async matchEntireCellAsync(matchEntireCell: boolean): Promise<IFTextFinder> {
- this._state.changeState({ matchesTheWholeCell: matchEntireCell });
+ this._state.changeState({ matchesTheWholeCell: matchEntireCell, findCompleted: false });
return new Promise((resolve) => {
- const subscribe = this._state.stateUpdates$.subscribe((state) => {
+ const subscribe = this._state.stateUpdates$.subscribe(async (state) => {
if (state.findCompleted === true) {
subscribe.unsubscribe();
+ await this.ensureCompleteAsync();
resolve(this);
}
});
@@ -243,11 +437,12 @@ export class FTextFinder extends Disposable implements IFTextFinder {
}
async matchFormulaTextAsync(matchFormulaText: boolean): Promise<IFTextFinder> {
- this._state.changeState({ findBy: matchFormulaText ? FindBy.FORMULA : FindBy.VALUE });
+ this._state.changeState({ findBy: matchFormulaText ? FindBy.FORMULA : FindBy.VALUE, findCompleted: false });
return new Promise((resolve) => {
- const subscribe = this._state.stateUpdates$.subscribe((state) => {
+ const subscribe = this._state.stateUpdates$.subscribe(async (state) => {
if (state.findCompleted === true) {
subscribe.unsubscribe();
+ await this.ensureCompleteAsync();
resolve(this);
}
});
@@ -269,10 +464,7 @@ export class FTextFinder extends Disposable implements IFTextFinder {
}
async ensureCompleteAsync(): Promise<Nullable<IFindComplete>> {
- if (!this._state.findCompleted || !this._complete) {
- this._complete = await this._model?.start();
- }
- return this._complete;
+ this._complete = await this._model?.start();
};
private _findMatchToFRange(match: IFindMatch): FRange {
diff --git a/packages/sheets-find-replace/src/facade/f-univer.ts b/packages/sheets-find-replace/src/facade/f-univer.ts
index fae16ee509..b328742aed 100644
--- a/packages/sheets-find-replace/src/facade/f-univer.ts
+++ b/packages/sheets-find-replace/src/facade/f-univer.ts
@@ -28,11 +28,34 @@ export interface IFUniverFindReplaceMixin {
* @returns {Promise<FTextFinder | null>} A promise that resolves to the text-finder instance.
* @example
* ```typescript
- * const textFinder = await univerAPI.createTextFinderAsync('Hello');
+ * // Assume the current sheet is empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * fRange.setValues([
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * [6, 7, 8, 9],
+ * [7, 8, 9, 10],
+ * [8, 9, 10, 11],
+ * [9, 10, 11, 12],
+ * [10, 11, 12, 13]
+ * ]);
+ *
+ * // Create a text-finder to find the text '5'.
+ * const textFinder = await univerAPI.createTextFinderAsync('5');
+ *
+ * // Find all cells that contain the text '5'.
+ * const matchCells = textFinder.findAll();
+ * matchCells.forEach((cell) => {
+ * console.log(cell.getA1Notation()); // D2, C3, B4, A5
+ * });
* ```
*/
createTextFinderAsync(text: string): Promise<FTextFinder | null>;
-
}
export class FUniverFindReplaceMixin extends FUniver implements IFUniverFindReplaceMixin {
diff --git a/packages/sheets-formula/src/facade/f-formula.ts b/packages/sheets-formula/src/facade/f-formula.ts
index abd21ef65f..847a18ce7b 100644
--- a/packages/sheets-formula/src/facade/f-formula.ts
+++ b/packages/sheets-formula/src/facade/f-formula.ts
@@ -28,92 +28,145 @@ import { IRegisterFunctionService, PLUGIN_CONFIG_KEY_BASE, RegisterFunctionServi
*/
export interface IFFormulaSheetsMixin {
/**
- * Update the calculation mode of the formula.
- * @param calculationMode
- * @returns
+ * Update the calculation mode of the formula. It will take effect the next time the Univer Sheet is constructed.
+ * The calculation mode only handles formulas data when the workbook initializes data.
+ * @param {CalculationMode} calculationMode - The calculation mode of the formula.
+ * @example
+ * ```ts
+ * const formulaEngine = univerAPI.getFormula();
+ * formulaEngine.setInitialFormulaComputing(0);
+ * ```
*/
setInitialFormulaComputing(calculationMode: CalculationMode): void;
/**
* Register a custom synchronous formula function.
- * @param name - The name of the function to register. This will be used in formulas (e.g., =MYFUNC())
- * @param func - The implementation of the function
- * @param description - A string describing the function's purpose and usage
- * @returns A disposable object that will unregister the function when disposed
+ * @param {string} name - The name of the function to register. This will be used in formulas (e.g., =MYFUNC()).
+ * @param {IRegisterFunction} func - The implementation of the function.
+ * @param {string} [description] - A string describing the function's purpose and usage.
+ * @returns {IDisposable} A disposable object that will unregister the function when disposed.
* @example
- * ```js
- * univerAPI.getFormula().registerFunction('HELLO', (name) => `Hello, ${name}!`, 'A simple greeting function');
+ * ```ts
+ * // Register a simple greeting function
+ * const formulaEngine = univerAPI.getFormula();
+ * formulaEngine.registerFunction(
+ * 'HELLO',
+ * (name) => `Hello, ${name}!`,
+ * 'A simple greeting function'
+ * );
*
* // Use the function in a cell
- * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue('World');
- * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A2').setValue({ f: '=HELLO(A1)' });
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fSheet = fWorkbook.getActiveSheet();
+ * const cellA1 = fSheet.getRange('A1');
+ * cellA1.setValue('World');
+ * const cellA2 = fSheet.getRange('A2');
+ * cellA2.setValue({ f: '=HELLO(A1)' });
+ *
* // A2 will display: "Hello, World!"
+ * formulaEngine.calculationEnd((functionsExecutedState) => {
+ * if (functionsExecutedState === 3) {
+ * console.log(cellA2.getValue()); // Hello, World!
+ * }
+ * })
* ```
* @example
- * ```js
- * univerAPI.getFormula().registerFunction(
+ * ```ts
+ * // Register a discount calculation function
+ * const formulaEngine = univerAPI.getFormula();
+ * formulaEngine.registerFunction(
* 'DISCOUNT',
* (price, discountPercent) => price * (1 - discountPercent / 100),
* 'Calculates final price after discount'
* );
*
- * // Use in cell
- * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue(100);
- * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A2').setValue({ f: '=DISCOUNT(A1, 20)' });
+ * // Use the function in a cell
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fSheet = fWorkbook.getActiveSheet();
+ * const cellA1 = fSheet.getRange('A1');
+ * cellA1.setValue(100);
+ * const cellA2 = fSheet.getRange('A2');
+ * cellA2.setValue({ f: '=DISCOUNT(A1, 20)' });
+ *
* // A2 will display: 80
+ * formulaEngine.calculationEnd((functionsExecutedState) => {
+ * if (functionsExecutedState === 3) {
+ * console.log(cellA2.getValue()); // 80
+ * }
+ * })
* ```
* @example
- * ```typescript
+ * ```ts
* // Registered formulas support lambda functions
- * univerAPI.getFormula().registerFunction('CUSTOMSUM', (...variants) => {
- * let sum = 0;
+ * const formulaEngine = univerAPI.getFormula();
+ * formulaEngine.registerFunction(
+ * 'CUSTOMSUM',
+ * (...variants) => {
+ * let sum = 0;
+ * const last = variants[variants.length - 1];
*
- * const last = variants[variants.length - 1];
- * if (last.isLambda && last.isLambda()) {
- * variants.pop();
+ * if (last.isLambda && last.isLambda()) {
+ * variants.pop();
+ * const variantsList = variants.map((variant) => Array.isArray(variant) ? variant[0][0]: variant);
+ * sum += last.executeCustom(...variantsList).getValue();
+ * }
*
- * const variantsList = variants.map((variant) => Array.isArray(variant) ? variant[0][0]: variant);
+ * for (const variant of variants) {
+ * sum += Number(variant) || 0;
+ * }
*
- * sum += last.executeCustom(...variantsList).getValue();
- * }
+ * return sum;
+ * },
+ * 'Adds its arguments'
+ * );
*
- * for (const variant of variants) {
- * sum += Number(variant) || 0;
- * }
+ * // Use the function in a cell
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fSheet = fWorkbook.getActiveSheet();
+ * const cellA1 = fSheet.getRange('A1');
+ * cellA1.setValue(1);
+ * const cellA2 = fSheet.getRange('A2');
+ * cellA2.setValue(2);
+ * const cellA3 = fSheet.getRange('A3');
+ * cellA3.setValue({ f: '=CUSTOMSUM(A1,A2,LAMBDA(x,y,x*y))' });
*
- * return sum;
- * }, 'Adds its arguments');
+ * // A3 will display: 5
+ * formulaEngine.calculationEnd((functionsExecutedState) => {
+ * if (functionsExecutedState === 3) {
+ * console.log(cellA3.getValue()); // 5
+ * }
+ * })
* ```
*/
registerFunction(name: string, func: IRegisterFunction, description?: string): IDisposable;
-
/**
* Register a custom synchronous formula function with localization support.
- * @param name - The name of the function to register. This will be used in formulas (e.g., =MYFUNC())
- * @param func - The implementation of the function
- * @param options - Object containing locales and description
- * @param options.locales - Object containing locales
- * @param options.description - Object containing description
- * @returns A disposable object that will unregister the function when disposed
+ * @param {string} name - The name of the function to register. This will be used in formulas (e.g., =MYFUNC()).
+ * @param {IRegisterFunction} func - The implementation of the function.
+ * @param {{ locales?: ILocales; description?: string | IFunctionInfo }} [options] - Object containing locales and description.
+ * @param {ILocales} options.locales - Object containing locales.
+ * @param {string | IFunctionInfo} options.description - Object containing description.
+ * @returns {IDisposable} A disposable object that will unregister the function when disposed.
* @example
* ```js
- * univerAPI.getFormula().registerFunction('HELLO',
- * (name) => {
- * return `Hello, ${name}!`;
- * },
+ * // Register a simple greeting function
+ * const formulaEngine = univerAPI.getFormula();
+ * formulaEngine.registerFunction(
+ * 'HELLO',
+ * (name) => `Hello, ${name}!`,
* {
* description: 'customFunction.HELLO.description',
* locales: {
* 'zhCN': {
- * 'customFunction' : {
- * 'HELLO' : {
+ * 'customFunction': {
+ * 'HELLO': {
* 'description': '一个简单的问候函数'
* }
* }
* },
* 'enUS': {
- * 'customFunction' : {
- * 'HELLO' : {
+ * 'customFunction': {
+ * 'HELLO': {
* 'description': 'A simple greeting function'
* }
* }
@@ -122,74 +175,98 @@ export interface IFFormulaSheetsMixin {
* }
* );
*
- * // Use in cell
- * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue({ f: '=HELLO("John")' });
- * // A1 will display: "Hello, John!"
+ * // Use the function in a cell
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fSheet = fWorkbook.getActiveSheet();
+ * const cellA1 = fSheet.getRange('A1');
+ * cellA1.setValue('World');
+ * const cellA2 = fSheet.getRange('A2');
+ * cellA2.setValue({ f: '=HELLO(A1)' });
+ *
+ * // A2 will display: "Hello, World!"
+ * formulaEngine.calculationEnd((functionsExecutedState) => {
+ * if (functionsExecutedState === 3) {
+ * console.log(cellA2.getValue()); // Hello, World!
+ * }
+ * })
* ```
*/
registerFunction(name: string, func: IRegisterFunction, { locales, description }: { locales?: ILocales; description?: string | IFunctionInfo }): IDisposable;
- /**
- * Register a custom asynchronous formula function.
- * @param name - The name of the function to register. This will be used in formulas (e.g., =ASYNCFUNC())
- * @param func - The async implementation of the function
- * @returns A disposable object that will unregister the function when disposed
- * @example
- * ```js
- * univerAPI.getFormula().registerAsyncFunction('RANDOM_DELAYED',
- * async () => {
- * await new Promise(resolve => setTimeout(resolve, 500));
- * return Math.random();
- * },
- * 'Mock a random number generation function'
- * );
- *
- * // Use in cell
- * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue({ f: '=RANDOM_DELAYED()' });
- * // After 0.5 second, A1 will display a random number
- * ```
- */
+ /**
+ * Register a custom asynchronous formula function.
+ * @param {string} name - The name of the function to register. This will be used in formulas (e.g., =ASYNCFUNC()).
+ * @param {IRegisterAsyncFunction} func - The async implementation of the function.
+ * @param {string} [description] - A string describing the function's purpose and usage.
+ * @returns {IDisposable} A disposable object that will unregister the function when disposed.
+ * @example
+ * ```ts
+ * const formulaEngine = univerAPI.getFormula();
+ * formulaEngine.registerAsyncFunction(
+ * 'RANDOM_DELAYED',
+ * async () => {
+ * await new Promise(resolve => setTimeout(resolve, 500));
+ * return Math.random();
+ * },
+ * 'Mock a random number generation function'
+ * );
+ *
+ * // Use the function in a cell
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fSheet = fWorkbook.getActiveSheet();
+ * const cellA1 = fSheet.getRange('A1');
+ * cellA1.setValue({ f: '=RANDOM_DELAYED()' });
+ *
+ * // After 0.5 second, A1 will display a random number
+ * ```
+ */
registerAsyncFunction(name: string, func: IRegisterAsyncFunction, description?: string): IDisposable;
/**
* Register a custom asynchronous formula function with description.
- * @param name - The name of the function to register. This will be used in formulas (e.g., =ASYNCFUNC())
- * @param func - The async implementation of the function
- * @param options - Object containing locales and description
- * @param options.locales - Object containing locales
- * @param options.description - Object containing description
- * @returns A disposable object that will unregister the function when disposed
+ * @param {string} name - The name of the function to register. This will be used in formulas (e.g., =ASYNCFUNC()).
+ * @param {IRegisterAsyncFunction} func - The async implementation of the function.
+ * @param {{ locales?: ILocales; description?: string | IFunctionInfo }} [options] - Object containing locales and description.
+ * @param {ILocales} options.locales - Object containing locales.
+ * @param {string | IFunctionInfo} options.description - Object containing description.
+ * @returns {IDisposable} A disposable object that will unregister the function when disposed.
* @example
- * ```js
+ * ```ts
* // Mock a user score fetching function
- * univerAPI.getFormula().registerAsyncFunction('FETCH_USER_SCORE',
+ * const formulaEngine = univerAPI.getFormula();
+ * formulaEngine.registerAsyncFunction(
+ * 'FETCH_USER_SCORE',
* async (userId) => {
* await new Promise(resolve => setTimeout(resolve, 1000));
* // Mock fetching user score from database
* return userId * 10 + Math.floor(Math.random() * 20);
* },
* {
- * description: 'customFunction.description.FETCH_USER_SCORE',
+ * description: 'customFunction.FETCH_USER_SCORE.description',
* locales: {
* 'zhCN': {
- * 'customFunction': {
- * 'description': {
- * 'FETCH_USER_SCORE': '从数据库中获取用户分数'
- * }
- * }
+ * 'customFunction': {
+ * 'FETCH_USER_SCORE': {
+ * 'description': '从数据库中获取用户分数'
+ * }
+ * }
* },
* 'enUS': {
- * 'customFunction': {
- * 'description': {
- * 'FETCH_USER_SCORE': 'Mock fetching user score from database'
- * }
- * }
+ * 'customFunction': {
+ * 'FETCH_USER_SCORE': {
+ * 'description': 'Mock fetching user score from database'
+ * }
+ * }
* }
* }
* }
* );
*
- * // Use in cell
- * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue({ f: '=FETCH_USER_SCORE(42)' });
+ * // Use the function in a cell
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fSheet = fWorkbook.getActiveSheet();
+ * const cellA1 = fSheet.getRange('A1');
+ * cellA1.setValue({ f: '=FETCH_USER_SCORE(42)' });
+ *
* // After 1 second, A1 will display a score
* ```
*/
diff --git a/packages/sheets-hyper-link-ui/src/facade/f-workbook.ts b/packages/sheets-hyper-link-ui/src/facade/f-workbook.ts
index 8145d5d1cc..1d74dd7ec1 100644
--- a/packages/sheets-hyper-link-ui/src/facade/f-workbook.ts
+++ b/packages/sheets-hyper-link-ui/src/facade/f-workbook.ts
@@ -22,10 +22,26 @@ import { FWorkbook } from '@univerjs/sheets/facade';
interface IFWorkbookHyperlinkUIMixin {
/**
* Navigate to the sheet hyperlink.
- * @param hyperlink the hyperlink string
+ * @param {string} hyperlink - The hyperlink string
* @example
- * ``` ts
- * univerAPI.getActiveWorkbook().navigateToSheetHyperlink('#gid=sheet_Id&range=F6')
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const sheets = fWorkbook.getSheets();
+ *
+ * // Create a hyperlink to the cell F6 in the first sheet
+ * const sheet1 = sheets[0];
+ * const range = sheet1.getRange('F6');
+ * const hyperlink = range.getUrl();
+ *
+ * // Switch to the second sheet
+ * fWorkbook.setActiveSheet(sheets[1]);
+ * console.log(fWorkbook.getActiveSheet().getSheetName());
+ *
+ * // Navigate to the hyperlink after 3 seconds
+ * setTimeout(() => {
+ * fWorkbook.navigateToSheetHyperlink(hyperlink);
+ * console.log(fWorkbook.getActiveSheet().getSheetName());
+ * }, 3000);
* ```
*/
navigateToSheetHyperlink(this: FWorkbook, hyperlink: string): void;
diff --git a/packages/sheets-hyper-link/src/facade/f-event.ts b/packages/sheets-hyper-link/src/facade/f-event.ts
index 0599fe58c9..3413cd6922 100644
--- a/packages/sheets-hyper-link/src/facade/f-event.ts
+++ b/packages/sheets-hyper-link/src/facade/f-event.ts
@@ -25,37 +25,54 @@ import { FEventName } from '@univerjs/core/facade';
interface IFSheetLinkEvent {
/**
* Event triggered before adding a link
- *
+ * @see {@link IBeforeSheetLinkAddEvent}
* @example
* ```ts
- * univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkAdd, (params) => {
- * const { workbook, worksheet, row, col, link } = params;
- * console.log('before sheet link add', params);
+ * const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkAdd, (params) => {
+ * const { workbook, worksheet, row, col, link } = params;
+ * console.log('before sheet link add', params);
+ *
+ * // Cancel the sheet link add operation
+ * params.cancel = true;
* });
+ *
+ * // Remove the event listener, use `disposable.dispose()`
* ```
*/
readonly BeforeSheetLinkAdd: 'BeforeSheetLinkAdd';
+
/**
* Event triggered before canceling a link
- *
+ * @see {@link IBeforeSheetLinkCancelEvent}
* @example
* ```ts
- * univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkCancel, (params) => {
- * const { workbook, worksheet, row, column, id } = params;
- * console.log('before sheet link cancel', params);
+ * const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkCancel, (params) => {
+ * const { workbook, worksheet, row, column, id } = params;
+ * console.log('before sheet link cancel', params);
+ *
+ * // Cancel the sheet link cancel operation
+ * params.cancel = true;
* });
+ *
+ * // Remove the event listener, use `disposable.dispose()`
* ```
*/
readonly BeforeSheetLinkCancel: 'BeforeSheetLinkCancel';
+
/**
* Event triggered before updating a link
- *
+ * @see {@link IBeforeSheetLinkUpdateEvent}
* @example
* ```ts
- * univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkUpdate, (params) => {
- * const { workbook, worksheet, row, column, id, payload } = params;
- * console.log('before sheet link update', params);
+ * const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkUpdate, (params) => {
+ * const { workbook, worksheet, row, column, id, payload } = params;
+ * console.log('before sheet link update', params);
+ *
+ * // Cancel the sheet link update operation
+ * params.cancel = true;
* });
+ *
+ * // Remove the event listener, use `disposable.dispose()`
* ```
*/
readonly BeforeSheetLinkUpdate: 'BeforeSheetLinkUpdate';
diff --git a/packages/sheets-hyper-link/src/facade/f-range.ts b/packages/sheets-hyper-link/src/facade/f-range.ts
index 1a11f6610a..3b03cffc47 100644
--- a/packages/sheets-hyper-link/src/facade/f-range.ts
+++ b/packages/sheets-hyper-link/src/facade/f-range.ts
@@ -33,23 +33,89 @@ export interface ICellHyperLink {
export interface IFRangeHyperlinkMixin {
/**
* @deprecated use `range.setRichTextValueForCell(univerAPI.newRichText().insertLink(label, url))` instead
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1');
+ * const richText = univerAPI.newRichText().insertLink('Univer', 'https://univer.ai/');
+ * fRange.setRichTextValueForCell(richText);
+ * ```
*/
setHyperLink(url: string, label?: string): Promise<boolean>;
+
/**
* @deprecated use `range.setRichTextValueForCell(range.getValue(true).getLinks())` instead
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1');
+ * const richText = univerAPI.newRichText().insertLink('Univer', 'https://univer.ai/');
+ * fRange.setRichTextValueForCell(richText);
+ *
+ * // Get hyperlinks
+ * console.log(fRange.getValue(true).getLinks());
+ * ```
*/
getHyperLinks(): ICellHyperLink[];
+
/**
* @deprecated use `range.setRichTextValueForCell(range.getValue(true).copy().updateLink(id, url))` instead
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1');
+ * const richText = univerAPI.newRichText().insertLink('Univer', 'https://univer.ai/');
+ * fRange.setRichTextValueForCell(richText);
+ *
+ * // Update hyperlink after 3 seconds
+ * setTimeout(() => {
+ * const cellValue = fRange.getValue(true);
+ * const hyperlinks = cellValue.getLinks();
+ * const id = hyperlinks[0].rangeId;
+ * const newUrl = 'https://go.univer.ai/';
+ * const newRichText = cellValue.copy().updateLink(id, newUrl);
+ * fRange.setRichTextValueForCell(newRichText);
+ * }, 3000);
+ * ```
*/
updateHyperLink(id: string, url: string, label?: string): Promise<boolean>;
+
/**
* @deprecated use `range.setRichTextValueForCell(range.getValue(true).copy().cancelLink(id))` instead
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1');
+ * const richText = univerAPI.newRichText().insertLink('Univer', 'https://univer.ai/');
+ * fRange.setRichTextValueForCell(richText);
+ *
+ * // Cancel hyperlink after 3 seconds
+ * setTimeout(() => {
+ * const cellValue = fRange.getValue(true);
+ * const hyperlinks = cellValue.getLinks();
+ * const id = hyperlinks[0].rangeId;
+ * const newRichText = cellValue.copy().cancelLink(id);
+ * fRange.setRichTextValueForCell(newRichText);
+ * }, 3000);
+ * ```
*/
cancelHyperLink(id: string): boolean;
/**
- * Get the url of this range.
+ * Create a hyperlink url to this range
+ * @returns {string} The url of this range
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1');
+ * const url = fRange.getUrl();
+ * console.log(url);
+ * ```
*/
getUrl(): string;
}
diff --git a/packages/sheets-hyper-link/src/facade/f-workbook.ts b/packages/sheets-hyper-link/src/facade/f-workbook.ts
index f1abf92e21..c4f9e0966f 100644
--- a/packages/sheets-hyper-link/src/facade/f-workbook.ts
+++ b/packages/sheets-hyper-link/src/facade/f-workbook.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
+import type { IRange } from '@univerjs/core';
import type { ISheetHyperLinkInfo } from '@univerjs/sheets-hyper-link';
import type { FRange } from '@univerjs/sheets/facade';
-import { Inject, type IRange } from '@univerjs/core';
+import { Inject } from '@univerjs/core';
import { SheetsHyperLinkParserService } from '@univerjs/sheets-hyper-link';
import { FWorkbook } from '@univerjs/sheets/facade';
@@ -46,11 +47,19 @@ export interface IFWorkbookHyperlinkMixin {
/**
* Parse the hyperlink string to get the hyperlink info.
- * @param hyperlink the hyperlink string
- * @returns the hyperlink info
+ * @param {string} hyperlink - The hyperlink string.
+ * @returns {ISheetHyperLinkInfo} The hyperlink info.
* @example
* ``` ts
- * univerAPI.getActiveWorkbook().parseSheetHyperlink('#gid=sheet_Id&range=F6')
+ * // Create a hyperlink to the range A1:D10 of the current sheet
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:D10');
+ * const hyperlink = fRange.getUrl();
+ *
+ * // Parse the hyperlink
+ * const hyperlinkInfo = fWorkbook.parseSheetHyperlink(hyperlink);
+ * console.log(hyperlinkInfo);
* ```
*/
parseSheetHyperlink(this: FWorkbook, hyperlink: string): ISheetHyperLinkInfo;
diff --git a/packages/sheets-hyper-link/src/facade/f-worksheet.ts b/packages/sheets-hyper-link/src/facade/f-worksheet.ts
index e8d6b87d66..c4fe20cd80 100644
--- a/packages/sheets-hyper-link/src/facade/f-worksheet.ts
+++ b/packages/sheets-hyper-link/src/facade/f-worksheet.ts
@@ -22,7 +22,15 @@ import { FWorksheet } from '@univerjs/sheets/facade';
*/
export interface IFWorksheetHyperlinkMixin {
/**
- * Get the url of this sheet
+ * Create a hyperlink url to this sheet
+ * @returns {string} The url of this sheet
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const url = fWorksheet.getUrl();
+ * console.log(url);
+ * ```
*/
getUrl(): string;
}
diff --git a/packages/sheets-numfmt/src/facade/f-range.ts b/packages/sheets-numfmt/src/facade/f-range.ts
index 765b7edcab..6f7564b61d 100644
--- a/packages/sheets-numfmt/src/facade/f-range.ts
+++ b/packages/sheets-numfmt/src/facade/f-range.ts
@@ -26,8 +26,16 @@ export interface IFRangeSheetsNumfmtMixin {
/**
* Set the number format of the range.
- * @param pattern number format pattern.
- * @returns FRange
+ * @param {string} pattern - The number format pattern.
+ * @returns {FRange} The FRange instance for chaining.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1');
+ * fRange.setValue(1234.567).setNumberFormat('#,##0.00');
+ * console.log(fRange.getValue()); // 1,234.57
+ * ```
*/
setNumberFormat(pattern: string): FRange;
}
diff --git a/packages/sheets-numfmt/src/facade/f-workbook.ts b/packages/sheets-numfmt/src/facade/f-workbook.ts
index 50ec43356c..cf22c74852 100644
--- a/packages/sheets-numfmt/src/facade/f-workbook.ts
+++ b/packages/sheets-numfmt/src/facade/f-workbook.ts
@@ -18,19 +18,27 @@ import type { INumfmtLocalTag } from '@univerjs/core';
import { SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';
import { FWorkbook } from '@univerjs/sheets/facade';
-/**
- * @ignore
- */
export interface IFWorkbookNumfmtMixin {
-
/**
- * @example
- * ```ts
- * univerAPI.getActiveWorkbook().setNumfmtLocal('en')
- * ```
+ * Set the locale for number formatting.
* @param {INumfmtLocalTag} local zh_CN,zh_TW,zh_HK,ja,ko,th,cs,da,nl,en,en_AU,en_CA,en_GB,en_IE,fi,fr,fr_CA,fr_CH,de,de_CH,el,hu,is,id,it,it_CH,nb,no,pl,pt,pt_BR,ru,sk,es,es_AR,es_BO,es_CL,es_CO,es_EC,es_MX,es_PY,es_UY,es_VE,sv,tr,cy,az,be,bg,ca,fil,gu,he,hr,hy,ka,kk,kn,lt,lv,ml,mn,mr,my,pa,ro,sl,sr,ta,te,uk,vi,ar,bn,hi
- * @returns {*} {FWorkbook}
+ * @returns {FWorkbook} The FWorkbook instance for chaining.
* @memberof IFWorkbookNumfmtMixin
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1');
+ * fRange.setValue(1234.567).setNumberFormat('#,##0.00');
+ *
+ * // Set the locale en_US for number formatting.
+ * fWorkbook.setNumfmtLocal('en_US');
+ * console.log(fRange.getValue()); // 1,234.57
+ *
+ * // Set the locale de_DE for number formatting.
+ * fWorkbook.setNumfmtLocal('de_DE');
+ * console.log(fRange.getValue()); // 1.234,57
+ * ```
*/
setNumfmtLocal(local: INumfmtLocalTag): FWorkbook;
}
diff --git a/packages/sheets-sort/src/facade/f-event.ts b/packages/sheets-sort/src/facade/f-event.ts
index 988fe1978d..f7bbe22b2f 100644
--- a/packages/sheets-sort/src/facade/f-event.ts
+++ b/packages/sheets-sort/src/facade/f-event.ts
@@ -29,29 +29,33 @@ import { FSheetEventName } from '@univerjs/sheets/facade';
export interface IFSheetSortEventMixin {
/**
* This event will be emitted when a range on a worksheet is sorted.
- * Type of the event is {@link ISheetRangeSortedParams}.
+ * @see {@link ISheetRangeSortParams}
* @example
* ```typescript
* const callbackDisposable = univerAPI.addEvent(univerAPI.Event.SheetRangeSorted, (params) => {
- * const { workbook, worksheet, sortColumn } = params;
- * sortColumn.forEach((col) => {
- * console.log(col.column, col.ascending);
- * });
+ * console.log(params);
+ * const { workbook, worksheet, range, sortColumn } = params;
* });
+ *
+ * // Remove the event listener, use `callbackDisposable.dispose()`
* ```
*/
SheetRangeSorted: 'SheetRangeSorted';
+
/**
* This event will be emitted before sorting a range on a worksheet.
- * Type of the event is {@link ISheetRangeSortParams}.
+ * @see {@link ISheetRangeSortParams}
* @example
* ```typescript
* const callbackDisposable = univerAPI.addEvent(univerAPI.Event.SheetBeforeRangeSort, (params) => {
- * const { workbook, worksheet, sortColumn } = params;
- * sortColumn.forEach((col) => {
- * console.log(col.column, col.ascending);
- * });
+ * console.log(params);
+ * const { workbook, worksheet, range, sortColumn } = params;
+ *
+ * // Cancel the sorting operation.
+ * params.cancel = true;
* });
+ *
+ * // Remove the event listener, use `callbackDisposable.dispose()`
* ```
*/
SheetBeforeRangeSort: 'SheetBeforeRangeSort';
diff --git a/packages/sheets-sort/src/facade/f-worksheet.ts b/packages/sheets-sort/src/facade/f-worksheet.ts
index 4d50da5bdd..14981a0d87 100644
--- a/packages/sheets-sort/src/facade/f-worksheet.ts
+++ b/packages/sheets-sort/src/facade/f-worksheet.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
+import type { IRange } from '@univerjs/core';
import type { IOrderRule } from '@univerjs/sheets-sort';
-import { type IRange, RANGE_TYPE } from '@univerjs/core';
-
+import { RANGE_TYPE } from '@univerjs/core';
import { SortRangeCommand, SortType } from '@univerjs/sheets-sort';
import { FWorksheet } from '@univerjs/sheets/facade';
@@ -26,15 +26,19 @@ import { FWorksheet } from '@univerjs/sheets/facade';
export interface IFWorksheetSort {
/**
* Sort the worksheet by the specified column.
- * @param {number} colIndex The column index to sort by. which starts from 1.
+ * @param {number} colIndex The column index to sort by.
* @param {boolean} [asc=true] The sort order. `true` for ascending, `false` for descending.
- * @returns The worksheet itself for chaining.
+ * @returns {FWorksheet} The worksheet itself for chaining.
* @example
* ```typescript
- * const activeSpreadsheet = univerAPI.getActiveWorkbook();
- * const activeSheet = activeSpreadsheet.getActiveSheet();
- * activeSheet.sort(1); // Sorts the worksheet by the first column in ascending order.
- * activeSheet.sort(1, false); // Sorts the worksheet by the first column in descending order.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ *
+ * // Sorts the worksheet by the column A in ascending order.
+ * fWorksheet.sort(0);
+ *
+ * // Sorts the worksheet by the column A in descending order.
+ * fWorksheet.sort(0, false);
* ```
*/
sort(colIndex: number, asc?: boolean): FWorksheet;