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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(formula): input hightlight (#447)
Univer8e7fe27c01ed
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.tsindex 2457e2bd7a..a60ee75b84 100644--- a/packages/base-docs/src/index.ts+++ b/packages/base-docs/src/index.ts@@ -1,4 +1,4 @@-export * from './basics/component-tools';+export { getDocObject } from './basics/component-tools';export * from './basics/docs-view-key';export { MemoryCursor } from './basics/memory-cursor';export {diff --git a/packages/base-formula-engine/src/analysis/lexer.ts b/packages/base-formula-engine/src/analysis/lexer.tsindex 2c969b12f5..29cff504d0 100644--- a/packages/base-formula-engine/src/analysis/lexer.ts+++ b/packages/base-formula-engine/src/analysis/lexer.ts@@ -1,13 +1,17 @@-import { Disposable, Nullable } from '@univerjs/core';+import { Disposable, Nullable, Tools } from '@univerjs/core';import { ErrorType } from '../basics/error-type';+import { isReferenceString, REFERENCE_SINGLE_RANGE_REGEX } from '../basics/regex';+import { ISequenceArray, ISequenceNode, sequenceNodeType } from '../basics/sequence';import {+ compareToken,matchToken,OPERATOR_TOKEN_PRIORITY,OPERATOR_TOKEN_SET,operatorToken,prefixToken,SUFFIX_TOKEN_SET,+ suffixToken,} from '../basics/token';import {DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER,@@ -42,8 +46,8 @@ export class LexerTreeBuilder extends Disposable {private _colonState = false; // :override dispose(): void {+ this.resetTemp();this._currentLexerNode.dispose();- this._bracketState = [];}getUpLevel() {@@ -86,6 +90,213 @@ export class LexerTreeBuilder extends Disposable {return this._currentLexerNode;}+ getCurrentParamIndex(formulaString: string, index: number) {+ return this._nodeMaker(formulaString, undefined, index);+ }++ sequenceNodesBuilder(formulaString: string) {+ const sequenceArray = this._getSequenceArray(formulaString);+ if (sequenceArray.length === 0) {+ return;+ }++ const sequenceNodes: Array<ISequenceNode | string> = [];++ let maybeString = false;++ for (let i = 0, len = sequenceArray.length; i < len; i++) {+ const item = sequenceArray[i];+ console.log('item', item);+ const preItem = sequenceArray[i - 1];++ const { segment, currentString, cur } = item;++ if (currentString === matchToken.DOUBLE_QUOTATION) {+ maybeString = true;+ }++ if ((segment !== '' || i === 0) && i !== len - 1) {+ sequenceNodes.push(currentString);+ continue;+ }++ let preSegment = preItem?.segment || '';++ const startIndex = i - preSegment.length;++ let endIndex = i - 1;++ const deleteEndIndex = i - 1;++ if (i === len - 1 && this._isLastMergeString(currentString)) {+ preSegment += currentString;++ endIndex += 1;+ }++ if (preSegment === '' || OPERATOR_TOKEN_PRIORITY.has(preSegment)) {+ sequenceNodes.push(currentString);+ continue;+ }++ const preSegmentTrim = preSegment.trim();++ const preSegmentNotPrefixToken = this._replacePrefixString(preSegmentTrim);++ if (maybeString === true && preSegmentTrim[preSegmentTrim.length - 1] === matchToken.DOUBLE_QUOTATION) {+ maybeString = false;+ this._pushSequenceNode(+ sequenceNodes,+ {+ nodeType: sequenceNodeType.STRING,+ token: preSegment,+ startIndex,+ endIndex,+ },+ deleteEndIndex+ );+ } else if (new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test(preSegmentNotPrefixToken)) {+ this._pushSequenceNode(+ sequenceNodes,+ {+ nodeType: sequenceNodeType.REFERENCE,+ token: preSegment,+ startIndex,+ endIndex,+ },+ deleteEndIndex+ );+ } else if (Tools.isStringNumber(preSegmentTrim)) {+ this._pushSequenceNode(+ sequenceNodes,+ {+ nodeType: sequenceNodeType.NUMBER,+ token: preSegment,+ startIndex,+ endIndex,+ },+ deleteEndIndex+ );+ } else if (preSegmentTrim.length > 0) {+ this._pushSequenceNode(+ sequenceNodes,+ {+ nodeType: sequenceNodeType.FUNCTION,+ token: preSegment,+ startIndex,+ endIndex,+ },+ deleteEndIndex+ );+ }++ if (i !== len - 1 || !this._isLastMergeString(currentString)) {+ sequenceNodes.push(currentString);+ }+ }++ const newSequenceNodes = this._mergeSequenceNodeReference(sequenceNodes);++ let sequenceString = '';+ for (const node of newSequenceNodes) {+ if (typeof node === 'string') {+ sequenceString += node;+ } else {+ sequenceString += node.token;+ }+ }+ console.log('sequenceString', sequenceString);++ return newSequenceNodes;+ }++ private _isLastMergeString(str: string) {+ return (+ str === matchToken.DOUBLE_QUOTATION ||+ Tools.isStringNumber(str) ||+ (!Object.values(compareToken).includes(str as compareToken) &&+ !Object.values(operatorToken).includes(str as operatorToken) &&+ !Object.values(matchToken).includes(str as matchToken) &&+ !Object.values(suffixToken).includes(str as suffixToken) &&+ !Object.values(prefixToken).includes(str as prefixToken))+ );+ }++ /**+ * Merge array and handle ref operations+ *+ */+ private _mergeSequenceNodeReference(sequenceNodes: Array<string | ISequenceNode>) {+ const newSequenceNodes: Array<string | ISequenceNode> = [];++ const sequenceNodesCount = sequenceNodes.length;++ let i = 0;+ while (i < sequenceNodesCount) {+ const node = sequenceNodes[i];++ if (typeof node === 'string') {+ const preNode = sequenceNodes[i - 1];+ if (+ node.trim() === matchToken.CLOSE_BRACES &&+ preNode != null &&+ typeof preNode !== 'string' &&+ preNode.nodeType === sequenceNodeType.FUNCTION+ ) {+ /**+ * Solving the merging issue of ['{1,2,3;4,5,6;7,8,10', '}']+ */+ const firstChar = preNode.token.trim().substring(0, 1);++ if (firstChar === matchToken.OPEN_BRACES) {+ preNode.nodeType = sequenceNodeType.ARRAY;+ preNode.token += node;+ preNode.endIndex += node.length;+ i++;+ continue;+ }+ }+ newSequenceNodes.push(node);+ } else {+ const nextOneNode = sequenceNodes[i + 1];++ const nextTwoNode = sequenceNodes[i + 2];++ if (+ nextOneNode === matchToken.COLON &&+ typeof node !== 'string' &&+ nextTwoNode != null &&+ typeof nextTwoNode !== 'string' &&+ isReferenceString((node.token + nextOneNode + nextTwoNode.token).trim())+ ) {+ node.nodeType = sequenceNodeType.REFERENCE;+ node.token += nextOneNode + nextTwoNode.token;+ node.endIndex = nextTwoNode.endIndex;+ i += 2;+ }++ newSequenceNodes.push(node);+ }++ i++;+ }++ return newSequenceNodes;+ }++ private _pushSequenceNode(+ sequenceNodes: Array<ISequenceNode | string>,+ node: ISequenceNode,+ deleteEndIndex: number+ ) {+ const segmentCount = deleteEndIndex - node.startIndex + 1;+ sequenceNodes.splice(sequenceNodes.length - segmentCount, segmentCount, node);+ }++ private _replacePrefixString(token: string) {+ return token.replace(new RegExp(prefixToken.AT, 'g'), '').replace(new RegExp(prefixToken.MINUS, 'g'), '');+ }+treeBuilder(formulaString: string, transformSuffix = true) {this._resetCurrentLexerNode();@@ -93,7 +304,9 @@ export class LexerTreeBuilder extends Disposable {const state = this._nodeMaker(formulaString);- console.log('error', state);+ if (state === ErrorType.VALUE) {+ return state;+ }const node = this._getTopNode(this._currentLexerNode);if (node) {@@ -183,29 +396,6 @@ export class LexerTreeBuilder extends Disposable {this._segment = '';}- private _pushNodeToChildren(value: LexerNode | string, isUnshift = false) {- if (value !== '') {- const children = this._currentLexerNode.getChildren();- if (!(value instanceof LexerNode) && this.isColonOpen()) {- const subLexerNode_ref = new LexerNode();- subLexerNode_ref.setToken(value);- subLexerNode_ref.setParent(this._currentLexerNode);-- value = subLexerNode_ref;- }- if (isUnshift) {- children.unshift(value);- } else {- children.push(value);- }- }-- if (this.isColonOpen()) {- this._setAncestorCurrentLexerNode();- this._closeColon(); /* */- }- }-private _openBracket(type: bracketType = bracketType.NORMAL) {this._bracketState.push(type);}@@ -336,6 +526,29 @@ export class LexerTreeBuilder extends Disposable {this._segment += value;}+ private _pushNodeToChildren(value: LexerNode | string, isUnshift = false) {+ if (value !== '') {+ const children = this._currentLexerNode.getChildren();+ if (!(value instanceof LexerNode) && this.isColonOpen()) {+ const subLexerNode_ref = new LexerNode();+ subLexerNode_ref.setToken(value);+ subLexerNode_ref.setParent(this._currentLexerNode);++ value = subLexerNode_ref;+ }+ if (isUnshift) {+ children.unshift(value);+ } else {+ children.push(value);+ }+ }++ if (this.isColonOpen()) {+ this._setAncestorCurrentLexerNode();+ this._closeColon(); /* */+ }+ }+private _setCurrentLexerNode(subLexerNode: LexerNode, isUnshift = false) {this._pushNodeToChildren(subLexerNode, isUnshift);subLexerNode.setParent(this._currentLexerNode);@@ -345,7 +558,7 @@ export class LexerTreeBuilder extends Disposable {private _newAndPushCurrentLexerNode(token: string, current: number, isUnshift = false) {const subLexerNode = new LexerNode();subLexerNode.setToken(token);- subLexerNode.setIndex(current - token.length + 1, current);+ subLexerNode.setIndex(current - token.length, current - 1);this._setCurrentLexerNode(subLexerNode, isUnshift);}@@ -383,17 +596,50 @@ export class LexerTreeBuilder extends Disposable {return false;}+ private _getSequenceArray(formulaString: string) {+ const sequenceArray: ISequenceArray[] = [];++ this._nodeMaker(formulaString, sequenceArray);++ return sequenceArray;+ }++ private resetTemp() {+ this._currentLexerNode = new LexerNode();++ this._upLevel = 0;++ this._segment = '';++ this._bracketState = []; // ()++ this._bracesState = 0; // {}++ this._singleQuotationState = 0; // ''++ this._doubleQuotationState = 0; // ""++ this._lambdaState = false; // Lambda++ this._colonState = false; // :+ }+// eslint-disable-next-line max-lines-per-function- private _nodeMaker(formulaString: string) {+ private _nodeMaker(formulaString: string, sequenceArray?: ISequenceArray[], matchCurrentNodeIndex?: number) {if (formulaString.substring(0, 1) === operatorToken.EQUALS) {formulaString = formulaString.substring(1);}const formulaStringArray = formulaString.split('');const formulaStringArrayCount = formulaStringArray.length;let cur = 0;- this._resetSegment();+ this.resetTemp();while (cur < formulaStringArrayCount) {const currentString = formulaStringArray[cur];++ if (matchCurrentNodeIndex === cur) {+ return [this._currentLexerNode, currentString];+ }+if (currentString === matchToken.OPEN_BRACKET &&this.isSingleQuotationClose() &&@@ -423,6 +669,8 @@ export class LexerTreeBuilder extends Disposable {// subLexerNode.token = DEFAULT_TOKEN_TYPE_PARAMETER;// this.setCurrentLexerNode(subLexerNode);this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER, cur);++ // this._pushNodeToChildren(matchToken.OPEN_BRACKET);}} else {this._pushNodeToChildren(currentString);@@ -513,10 +761,19 @@ export class LexerTreeBuilder extends Disposable {this.isBracesClose()) {const currentBracket = this._getCurrentBracket();- if (currentBracket === bracketType.FUNCTION) {+ /**+ * Handle the occurrence of commas, where in the formula,+ * the comma represents the parameters of the function+ * [currentBracket == null] is for the situation where [=A1:B1, B5:A10] occurs+ */+ if (currentBracket === bracketType.FUNCTION || currentBracket == null) {this._pushNodeToChildren(this._segment);this._resetSegment();- if (!this._setParentCurrentLexerNode() && cur !== formulaStringArrayCount - 1) {+ if (+ !this._setParentCurrentLexerNode() &&+ cur !== formulaStringArrayCount - 1 &&+ currentBracket != null+ ) {return ErrorType.VALUE;}// const subLexerNode = new LexerNode();@@ -653,6 +910,13 @@ export class LexerTreeBuilder extends Disposable {const prevString = this._findPreviousToken(formulaStringArray, cur - 1) || '';if (this._negativeCondition(prevString)) {this._pushSegment(operatorToken.MINUS);++ sequenceArray?.push({+ segment: this._segment,+ currentString,+ cur,+ currentLexerNode: this._currentLexerNode,+ });cur++;continue;}@@ -678,7 +942,13 @@ export class LexerTreeBuilder extends Disposable {} else {this._pushSegment(currentString);}- // console.log('func', { segment: this._segment, currentString, cur, currentLexerNode: this._currentLexerNode });++ sequenceArray?.push({+ segment: this._segment,+ currentString,+ cur,+ currentLexerNode: this._currentLexerNode,+ });cur++;}diff --git a/packages/base-formula-engine/src/basics/regex.ts b/packages/base-formula-engine/src/basics/regex.tsindex 87c31a60f1..6e33f16094 100644--- a/packages/base-formula-engine/src/basics/regex.ts+++ b/packages/base-formula-engine/src/basics/regex.ts@@ -41,3 +41,12 @@ export const REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX = `^(${UNIT_NAME_REGEX})?${TAexport const $SUPER_TABLE_COLUMN_REGEX = /[.*?]/g;export const $ARRAY_VALUE_REGEX = /{.*?}/g;++export function isReferenceString(refString: string) {+ return (+ new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test(refString) ||+ new RegExp(REFERENCE_MULTIPLE_RANGE_REGEX).test(refString) ||+ new RegExp(REFERENCE_REGEX_ROW).test(refString) ||+ new RegExp(REFERENCE_REGEX_COLUMN).test(refString)+ );+}diff --git a/packages/base-formula-engine/src/basics/sequence.ts b/packages/base-formula-engine/src/basics/sequence.tsnew file mode 100644index 0000000000..c1c14e8469--- /dev/null+++ b/packages/base-formula-engine/src/basics/sequence.ts@@ -0,0 +1,24 @@+import { LexerNode } from '../analysis/lexer-node';++export enum sequenceNodeType {+ NORMAL,+ NUMBER,+ STRING,+ FUNCTION,+ REFERENCE,+ ARRAY,+}++export interface ISequenceNode {+ nodeType: sequenceNodeType;+ token: string;+ startIndex: number;+ endIndex: number;+}++export interface ISequenceArray {+ segment: string;+ currentString: string;+ cur: number;+ currentLexerNode: LexerNode;+}diff --git a/packages/base-formula-engine/src/dependency/formula-dependency.ts b/packages/base-formula-engine/src/dependency/formula-dependency.tsindex ad2c05bbac..a5fa950ce2 100644--- a/packages/base-formula-engine/src/dependency/formula-dependency.ts+++ b/packages/base-formula-engine/src/dependency/formula-dependency.ts@@ -2,11 +2,13 @@ import { Disposable, IRange, IUnitRange, LifecycleStages, Nullable, ObjectMatriximport { Inject } from '@wendellhu/redi';import { LexerTreeBuilder } from '../analysis/lexer';+import { LexerNode } from '../analysis/lexer-node';import { AstTreeBuilder } from '../analysis/parser';import { AstRootNode, FunctionNode, PrefixNode, SuffixNode } from '../ast-node';-import { BaseAstNode } from '../ast-node/base-ast-node';+import { BaseAstNode, ErrorNode } from '../ast-node/base-ast-node';import { FormulaASTCache } from '../ast-node/cache-lru';import { NodeType } from '../ast-node/node-type';+import { ErrorType } from '../basics/error-type';import { PreCalculateNodeType } from '../basics/node-type';import { prefixToken, suffixToken } from '../basics/token';import { Interpreter } from '../interpreter/interpreter';@@ -117,9 +119,14 @@ export class FormulaDependencyGenerator extends Disposable {}const lexerNode = this._lexerTreeBuilder.treeBuilder(formulaString);++ if ((lexerNode as ErrorType) in ErrorType) {+ return ErrorNode.create(lexerNode as ErrorType);+ }+// suffix Express, 1+(3*4=4)*5+1 convert to 134*4=5*1++- astNode = this._astTreeBuilder.parse(lexerNode);+ astNode = this._astTreeBuilder.parse(lexerNode as LexerNode);if (astNode == null) {throw new Error('astNode is null');diff --git a/packages/base-formula-engine/src/index.ts b/packages/base-formula-engine/src/index.tsindex c6fc0e75d7..1440f6369e 100644--- a/packages/base-formula-engine/src/index.ts+++ b/packages/base-formula-engine/src/index.ts@@ -1,3 +1,4 @@+export { LexerNode } from './analysis/lexer-node';export type {ArrayFormulaDataType,IFormulaData,@@ -8,6 +9,7 @@ export type {IUnitSheetNameMap,} from './basics/common';export { FUNCTION_NAMES, FunctionType, type IFunctionInfo, type IFunctionParam } from './basics/function';+export { type ISequenceNode, sequenceNodeType } from './basics/sequence';export { RangeReferenceObject } from './reference-object/range-reference-object';export { FormulaEngineService } from './services/formula-engine.service';export { IFunctionService } from './services/function.service';diff --git a/packages/base-formula-engine/src/services/formula-engine.service.ts b/packages/base-formula-engine/src/services/formula-engine.service.tsindex e2e9e9296a..6449c5dbec 100644--- a/packages/base-formula-engine/src/services/formula-engine.service.ts+++ b/packages/base-formula-engine/src/services/formula-engine.service.ts@@ -2,8 +2,10 @@ import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';import { Ctor, Dependency, Inject, Injector } from '@wendellhu/redi';import { LexerTreeBuilder } from '../analysis/lexer';+import { LexerNode } from '../analysis/lexer-node';import { AstTreeBuilder } from '../analysis/parser';import { AstRootNodeFactory } from '../ast-node/ast-root-node';+import { ErrorNode } from '../ast-node/base-ast-node';import { FunctionNodeFactory } from '../ast-node/function-node';import { LambdaNodeFactory } from '../ast-node/lambda-node';import { LambdaParameterNodeFactory } from '../ast-node/lambda-parameter-node';@@ -14,6 +16,7 @@ import { SuffixNodeFactory } from '../ast-node/suffix-node';import { UnionNodeFactory } from '../ast-node/union-node';import { ValueNodeFactory } from '../ast-node/value-node';import { IFormulaDatasetConfig } from '../basics/common';+import { ErrorType } from '../basics/error-type';import { FUNCTION_NAMES } from '../basics/function';import { FormulaDependencyGenerator } from '../dependency/formula-dependency';import {@@ -118,6 +121,30 @@ export class FormulaEngineService extends Disposable {return this.functionService.getDescriptions();}+ getRunTimeData(unitId: string) {+ return {+ sheetData: this.runtimeService.getSheetData(unitId),+ arrayFormulaData: this.runtimeService.getSheetArrayFormula(unitId),+ };+ }++ builderLexerTree(formulaString: string) {+ const lexerNode = this.lexerTreeBuilder.treeBuilder(formulaString, false);++ if (Object.values(ErrorType).includes(lexerNode as ErrorType)) {+ return ErrorNode.create(lexerNode as ErrorType);+ }+ return lexerNode as LexerNode;+ }++ buildSequenceNodes(formulaString: string) {+ return this.lexerTreeBuilder.sequenceNodesBuilder(formulaString);+ }++ getCurrentParamIndex(formulaString: string, index: number) {+ return this.lexerTreeBuilder.getCurrentParamIndex(formulaString, index);+ }+/**** @param unitId@@ -163,18 +190,27 @@ export class FormulaEngineService extends Disposable {};}- calculate(formulaString: string) {+ calculate(formulaString: string, transformSuffix: boolean = true) {// TODO how to observe @alex// this.getObserver('onBeforeFormulaCalculateObservable')?.notifyObservers(formulaString);- const lexerNode = this.lexerTreeBuilder.treeBuilder(formulaString);+ const lexerNode = this.lexerTreeBuilder.treeBuilder(formulaString, transformSuffix);++ if (Object.values(ErrorType).includes(lexerNode as ErrorType)) {+ return ErrorNode.create(lexerNode as ErrorType);+ }+// this.lexerTreeBuilder.suffixExpressionHandler(lexerNode); // suffix Express, 1+(3*4=4)*5+1 convert to 134*4=5*1++- console.log('lexerNode', lexerNode.serialize());+ console.log('lexerNode', (lexerNode as LexerNode).serialize());++ console.log('sequence', this.lexerTreeBuilder.sequenceNodesBuilder(formulaString));++ console.log('index', this.lexerTreeBuilder.getCurrentParamIndex(formulaString, 73));// this.getObserver('onAfterFormulaLexerObservable')?.notifyObservers(lexerNode);// const astTreeBuilder = new AstTreeBuilder();- const astNode = this.astTreeBuilder.parse(lexerNode);+ const astNode = this.astTreeBuilder.parse(lexerNode as LexerNode);console.log('astNode', astNode?.serialize());diff --git a/packages/base-render/src/basics/cell-data.ts b/packages/base-render/src/basics/cell-data.tsnew file mode 100644index 0000000000..a0472ee430--- /dev/null+++ b/packages/base-render/src/basics/cell-data.ts@@ -0,0 +1,6 @@+import { ICellData, IStyleData } from '@univerjs/core';++export interface ITempCellData extends ICellData {+ style: IStyleData;+ prefix: string[];+}diff --git a/packages/base-render/src/basics/index.ts b/packages/base-render/src/basics/index.tsindex 2208f59200..23f5819320 100644--- a/packages/base-render/src/basics/index.ts+++ b/packages/base-render/src/basics/index.ts@@ -1,3 +1,4 @@+export * from './cell-data';export * from './const';export * from './document-node-tools';export * from './draw';diff --git a/packages/base-render/src/components/sheets/sheet-skeleton.ts b/packages/base-render/src/components/sheets/sheet-skeleton.tsindex 2842dcdc99..16a83fc441 100644--- a/packages/base-render/src/components/sheets/sheet-skeleton.ts+++ b/packages/base-render/src/components/sheets/sheet-skeleton.ts@@ -28,7 +28,6 @@ import {searchArray,Styles,TextDirection,- TextDirectionType,Tools,VerticalAlign,Worksheet,@@ -118,13 +117,6 @@ export function getDocsSkeletonPageSize(documentSkeleton: DocumentSkeleton, angl};}-interface ISetCellCache {- cache: IStylesCache;- skipBackgroundAndBorder: boolean;- styles?: Styles;- cellData?: ObjectMatrix<ICellData>;-}-export interface IRowAutoHeightInfo {row: number;autoHeight?: number;@@ -594,7 +586,7 @@ export class SpreadsheetSkeleton extends Skeleton {column: number,columnCount: number) {- const { width: contentWidth, height: contentHeight } = contentSize;+ const { width: contentWidth } = contentSize;let startColumn = column;let endColumn = column;@@ -1555,7 +1547,6 @@ export class SpreadsheetSkeleton extends Skeleton {const contentLength = content.length;const {textRotation = { a: 0, v: BooleanNumber.FALSE },- textDirection = TextDirection.UNSPECIFIED,paddingData = {t: 0,r: 2,@@ -1569,13 +1560,12 @@ export class SpreadsheetSkeleton extends Skeleton {const { a: angle = 0, v: isVertical = BooleanNumber.FALSE } = textRotation;const { t: marginTop, r: marginRight, b: marginBottom, l: marginLeft } = paddingData;- let textDirectionDocument = TextDirectionType.NORMAL;+let centerAngle = 0;let vertexAngle = angle;if (isVertical === BooleanNumber.TRUE) {centerAngle = DEFAULT_ROTATE_ANGLE;vertexAngle = DEFAULT_ROTATE_ANGLE;- textDirectionDocument = TextDirectionType.TBRL;}const documentData: IDocumentData = {id: 'd',@@ -1646,7 +1636,7 @@ export class SpreadsheetSkeleton extends Skeleton {if (!format) {return {};}- const { ff, fs, it, bl, ul, st, ol, cl, bg, bd } = format;+ const { ff, fs, it, bl, ul, st, ol, cl } = format;const style: IStyleBase = {};ff && (style.ff = ff);fs && (style.fs = fs);diff --git a/packages/base-render/src/shape/scroll-bar.ts b/packages/base-render/src/shape/scroll-bar.tsindex 6f58cd60d7..592d5fe3bc 100644--- a/packages/base-render/src/shape/scroll-bar.ts+++ b/packages/base-render/src/shape/scroll-bar.ts@@ -40,6 +40,9 @@ export class ScrollBar extends BaseScrollBar {thumbLengthRatio = 1;+ /**+ * todo: @DR-univer。 Mainly inject themeService in order to obtain colors.+ */thumbBackgroundColor = '#cccccc';thumbHoverBackgroundColor = '#b2b2b2';diff --git a/packages/core/src/shared/reference.ts b/packages/core/src/shared/reference.tsindex ef059db162..34008990b7 100644--- a/packages/core/src/shared/reference.ts+++ b/packages/core/src/shared/reference.ts@@ -8,6 +8,7 @@ const $ROW_REGEX = /[^0-9]/g;const $COLUMN_REGEX = /[^A-Za-z]/g;export interface IGridRangeName {+ unitId: string;sheetName: string;range: IRange;}@@ -43,6 +44,14 @@ export function serializeRangeWithSheet(sheetName: string, range: IRange): strin}export function deserializeRangeWithSheet(refString: string): IGridRangeName {+ const unitIdMatch = new RegExp('\'?\\[((?![\\/?:"<>|*\\\\]).)*\\]').exec(refString);+ let unitId = '';++ if (unitIdMatch != null) {+ unitId = unitIdMatch[0];+ refString = refString.replace(new RegExp('\'?\\[((?![\\/?:"<>|*\\\\]).)*\\]', 'g'), '');+ }+const sheetNameIndex = refString.indexOf('!');let sheetName: string = '';let refBody: string = '';@@ -67,6 +76,7 @@ export function deserializeRangeWithSheet(refString: string): IGridRangeName {};return {+ unitId,sheetName,range,};@@ -82,6 +92,7 @@ export function deserializeRangeWithSheet(refString: string): IGridRangeName {const endColumn = endGrid.column;return {+ unitId,sheetName,range: {startRow,diff --git a/packages/core/src/types/interfaces/i-cell-data.ts b/packages/core/src/types/interfaces/i-cell-data.tsindex 93ddfe89b8..e0745717ea 100644--- a/packages/core/src/types/interfaces/i-cell-data.ts+++ b/packages/core/src/types/interfaces/i-cell-data.ts@@ -1,5 +1,4 @@import { Nullable } from '../../shared/types';-import { FormatType } from '../enum/format-type';import { CellValueType } from '../enum/text-style';import { IDocumentData } from './i-document-data';import { IStyleData } from './i-style-data';@@ -63,32 +62,3 @@ export function isICellData(value: any): value is ICellData {(value as ICellData).f !== undefined);}--/**- * Format of cell data- */-export interface IFormatData {- /**- * format- */- f: string;- /**- * 数字 n- * 字符串 g- * 时间 d- * 富文本 r- */- t: FormatType;-}--/**- * Cell data type- */-export type ICellDataType = Nullable<ICellData> | Nullable<IStyleData> | string | number | boolean;--// WTF: other matrix are number indexed objects, but this is an array?--/**- * Cell data matrix type- */-export type ICellDataMatrix = ICellDataType[][];diff --git a/packages/core/src/types/interfaces/i-style-data.ts b/packages/core/src/types/interfaces/i-style-data.tsindex d8d41a73a1..2f63d76aef 100644--- a/packages/core/src/types/interfaces/i-style-data.ts+++ b/packages/core/src/types/interfaces/i-style-data.ts@@ -57,20 +57,6 @@ export interface IBorderData {l?: Nullable<IBorderStyleData>;}-// export interface IFormatData {-// /**-// * format-// */-// f: string;-// /**-// * 数字 n-// * 字符串 g-// * 时间 d-// * 富文本 r-// */-// t: string;-// }-export interface ITextRotation {/*** anglediff --git a/packages/sheets-plugin-formula-ui/package.json b/packages/sheets-plugin-formula-ui/package.jsonindex 71594b62ea..ef0f3627a7 100644--- a/packages/sheets-plugin-formula-ui/package.json+++ b/packages/sheets-plugin-formula-ui/package.json@@ -41,7 +41,8 @@"@wendellhu/redi": "^0.12.11","react": "^18.2.0","react-dom": "^18.2.0",- "rxjs": "^7.8.1"+ "rxjs": "^7.8.1",+ "@ctrl/tinycolor": "^4.0.2"},"devDependencies": {"@types/node": "^20.9.0",diff --git a/packages/sheets-plugin-formula-ui/src/common/selection.ts b/packages/sheets-plugin-formula-ui/src/common/selection.tsnew file mode 100644index 0000000000..372c7f555d--- /dev/null+++ b/packages/sheets-plugin-formula-ui/src/common/selection.ts@@ -0,0 +1,27 @@+import { TinyColor } from '@ctrl/tinycolor';+import { ISelectionStyle } from '@univerjs/base-sheets';+import { ThemeService } from '@univerjs/core';++export const FORMULA_REF_SELECTION_PLUGIN_NAME = 'formula_reference_selection_plugin_name';++export function getFormulaRefSelectionStyle(themeService: ThemeService, refColor: string): ISelectionStyle {+ const style = themeService.getCurrentTheme();+ const fill = new TinyColor(refColor).setAlpha(0.05).toString();+ return {+ strokeWidth: 2,+ stroke: refColor,+ // strokeDash: 10,+ fill,++ widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },+ widgetSize: 6,+ widgetStrokeWidth: 1,+ widgetStroke: style.colorWhite,++ hasAutoFill: false,++ hasRowHeader: false,++ hasColumnHeader: false,+ };+}diff --git a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.tsindex 2fc9c837b4..c5fd89f9df 100644--- a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts+++ b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts@@ -1,88 +1,196 @@import { TextSelectionManagerService } from '@univerjs/base-docs';+import { FormulaEngineService, IFunctionInfo, ISequenceNode, sequenceNodeType } from '@univerjs/base-formula-engine';import {+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ IRenderManagerService,+} from '@univerjs/base-render';+import { ISelectionWithStyle, NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '@univerjs/base-sheets';+import {+ deserializeRangeWithSheet,Disposable,+ DisposableCollection,FOCUSING_EDITOR_INPUT_FORMULA,ICommandService,IContextService,+ IDocumentBody,isFormulaString,+ ITextRun,+ IUniverInstanceService,LifecycleStages,LocaleService,+ Nullable,OnLifecycle,+ ThemeService,+ toDisposable,} from '@univerjs/core';-import { EditorBridgeService, IEditorBridgeService } from '@univerjs/ui-plugin-sheets';+import {+ EditorBridgeService,+ getEditorObject,+ IEditorBridgeService,+ ISelectionRenderService,+ SheetSkeletonManagerService,+} from '@univerjs/ui-plugin-sheets';import { Inject } from '@wendellhu/redi';import { HelpFunctionOperation } from '../commands/operations/help-function.operation';import { SearchFunctionOperation } from '../commands/operations/search-function.operation';+import { FORMULA_REF_SELECTION_PLUGIN_NAME, getFormulaRefSelectionStyle } from '../common/selection';import { FUNCTION_LIST } from '../services/function-list';import { IFormulaPromptService, ISearchItem } from '../services/prompt.service';import { getFunctionName } from './util';+interface IFunctionPanelParam {+ visibleSearch: boolean;+ visibleHelp: boolean;+ searchText: string;+ paramIndex: number;+ functionInfo?: IFunctionInfo;+ searchList?: ISearchItem[];+}++interface IRefSelection {+ refIndex: number;+ themeColor: string;+ token: string;+}+@OnLifecycle(LifecycleStages.Starting, PromptController)export class PromptController extends Disposable {+ private _formulaRefColors: string[] = [];++ private _currentRefIndex: number = -1;++ private _stringColor = '';++ private _numberColor = '';+constructor(@ICommandService private readonly _commandService: ICommandService,@Inject(LocaleService) private readonly _localeService: LocaleService,@IContextService private readonly _contextService: IContextService,@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,@Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,- @Inject(IFormulaPromptService) private readonly _formulaPromptService: IFormulaPromptService+ @Inject(IFormulaPromptService) private readonly _formulaPromptService: IFormulaPromptService,+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @Inject(ThemeService) private readonly _themeService: ThemeService,+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,+ @Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService) {super();this._initialize();}+ override dispose(): void {+ this._formulaRefColors = [];+ }+private _initialize(): void {this._initialCursorSync();this._initAcceptFormula();++ this._initialFormulaTheme();++ this._initialRefSelectionEvent();++ this._initialExitEditor();+ }++ private _initialFormulaTheme() {+ const style = this._themeService.getCurrentTheme();++ this._formulaRefColors = [+ style.loopColor1,+ style.loopColor2,+ style.loopColor3,+ style.loopColor4,+ style.loopColor5,+ style.loopColor6,+ style.loopColor7,+ style.loopColor8,+ style.loopColor9,+ style.loopColor10,+ style.loopColor11,+ style.loopColor12,+ ];++ this._numberColor = style.hyacinth700;++ this._stringColor = style.verdancy800;}private _initialCursorSync() {- this._textSelectionManagerService.textSelectionInfo$.subscribe(() => {- const currentInputValue = this._getCurrentCellValue();+ this.disposeWithMe(+ toDisposable(+ this._textSelectionManagerService.textSelectionInfo$.subscribe(() => {+ if (this._editorBridgeService.isVisible().visible === false) {+ return;+ }- // TODO@Dushusir: use real text info- const input = this._getCellEditInput(currentInputValue || '');- if (!input) return;+ const currentBody = this._getCurrentBody();- const { visibleSearch, visibleHelp, searchText, paramIndex, searchList, functionInfo } = input;+ const dataStream = currentBody?.dataStream || '';- if (visibleSearch) {- this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);- } else if (visibleHelp) {- this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);- } else {- this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);- }+ this._contextSwitch(dataStream);- this._commandService.executeCommand(SearchFunctionOperation.id, {- visible: visibleSearch,- searchText,- searchList,- });- this._commandService.executeCommand(HelpFunctionOperation.id, {- visible: visibleHelp,- paramIndex,- functionInfo,- });- });+ // TODO@Dushusir: use real text info+ this._setFunctionPanel(dataStream);++ this._highlightFormula(currentBody);+ })+ )+ );+ }++ private _initialExitEditor() {+ this.disposeWithMe(+ toDisposable(+ this._editorBridgeService.visible$.subscribe((visibleParam) => {+ if (visibleParam.visible === true) {+ return;+ }++ this._switchSelectionPlugin(NORMAL_SELECTION_PLUGIN_NAME);+ })+ )+ );}- private _getCurrentCellValue() {+ private _getCurrentBody() {const state = this._editorBridgeService.getState();- let currentInputValue = state?.documentLayoutObject?.documentModel?.snapshot?.body?.dataStream;+ return state?.documentLayoutObject?.documentModel?.snapshot?.body;+ }- if (currentInputValue) {- currentInputValue = currentInputValue.split('\r\n')[0].toLocaleUpperCase();+ private _contextSwitch(currentInputValue: string) {+ if (isFormulaString(currentInputValue)) {+ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);+ } else {+ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);}+ }- return currentInputValue;+ private _getContextState() {+ return this._contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA);}// TODO@Dushusir: remove after use real text info- private _getCellEditInput(currentInputValue: string) {- if (isFormulaString(currentInputValue)) {+ private _setFunctionPanel(currentInputValue: string) {+ let param: IFunctionPanelParam = {+ visibleSearch: false,+ visibleHelp: false,+ searchText: '',+ paramIndex: 0,+ functionInfo: {} as IFunctionInfo,+ searchList: [],+ };++ if (this._getContextState()) {+ currentInputValue = currentInputValue.split('\r\n')[0].toLocaleUpperCase();+const searchText = currentInputValue.substring(1);// TODO@Dushusir: remove after use real text info@@ -94,7 +202,7 @@ export class PromptController extends Disposable {const functionInfo = this._getFunctionInfo(searchText);- return {+ param = {visibleSearch: false,visibleHelp: !!functionInfo,searchText,@@ -104,7 +212,7 @@ export class PromptController extends Disposable {}const searchList = this._getSearchList(searchText);- return {+ param = {visibleSearch: searchList.length > 0,visibleHelp: false,searchText,@@ -113,12 +221,16 @@ export class PromptController extends Disposable {};}- return {- visibleSearch: false,- visibleHelp: false,- searchText: '',- paramIndex: 0,- };+ this._commandService.executeCommand(SearchFunctionOperation.id, {+ visible: param.visibleSearch,+ searchText: param.searchText,+ searchList: param.searchList,+ });+ this._commandService.executeCommand(HelpFunctionOperation.id, {+ visible: param.visibleHelp,+ paramIndex: param.paramIndex,+ functionInfo: param.functionInfo,+ });}private _initAcceptFormula() {@@ -142,4 +254,229 @@ export class PromptController extends Disposable {private _getFunctionInfo(searchText: string) {return FUNCTION_LIST.find((item) => getFunctionName(item, this._localeService) === searchText);}++ /**+ *+ * @param body the body object of the current input box+ * @returns+ */+ private _highlightFormula(body: Nullable<IDocumentBody>) {+ if (body == null || this._getContextState() === false) {+ return;+ }++ const dataStream = body.dataStream;++ const sequenceNodes = this._formulaEngineService.buildSequenceNodes(+ dataStream.replace(/\r/g, '').replace(/\n/g, '')+ );++ this._switchSelectionPlugin(FORMULA_REF_SELECTION_PLUGIN_NAME);++ this._selectionManagerService.clear();++ if (sequenceNodes == null || sequenceNodes.length === 0) {+ body.textRuns = [];+ } else {+ const textRuns: ITextRun[] = this._buildTextRuns(sequenceNodes);+ body.textRuns = textRuns;+ }++ this._refreshEditorObject();+ }++ /**+ * :+ * #+ *+ * @returns+ */+ private _buildTextRuns(sequenceNodes: Array<ISequenceNode | string>) {+ const textRuns: ITextRun[] = [];+ const refSelections: IRefSelection[] = [];+ let refIndex = 0;++ for (const node of sequenceNodes) {+ if (typeof node === 'string') {+ continue;+ }++ const { startIndex, endIndex, nodeType, token } = node;+ let themeColor = '';+ if (nodeType === sequenceNodeType.REFERENCE) {+ const colorIndex = refIndex % this._formulaRefColors.length;+ themeColor = this._formulaRefColors[colorIndex];++ refSelections.push({+ refIndex,+ themeColor,+ token,+ });++ refIndex++;+ } else if (nodeType === sequenceNodeType.NUMBER) {+ themeColor = this._numberColor;+ } else if (nodeType === sequenceNodeType.STRING) {+ themeColor = this._stringColor;+ } else if (nodeType === sequenceNodeType.ARRAY) {+ themeColor = this._stringColor;+ }++ if (themeColor.length > 0) {+ textRuns.push({+ st: startIndex + 1,+ ed: endIndex + 2,+ ts: {+ cl: {+ rgb: themeColor,+ },+ },+ });+ }+ }++ this._refreshSelectionForReference(refSelections);++ console.log('sequenceNodes', sequenceNodes, textRuns);++ return textRuns;+ }++ private _refreshSelectionForReference(refSelections: IRefSelection[]) {+ const current = this._sheetSkeletonManagerService.getCurrent();++ if (current == null) {+ return;+ }++ const { unitId, sheetId } = current;++ const selectionWithStyle: ISelectionWithStyle[] = [];++ for (const refSelection of refSelections) {+ const { refIndex, themeColor, token } = refSelection;++ const gridRange = deserializeRangeWithSheet(token);++ const { unitId: refUnitId, sheetName, range } = gridRange;++ if (refUnitId != null && refUnitId.length > 0 && unitId !== refUnitId) {+ continue;+ }++ const refSheetId = this._getSheetIdByName(unitId, sheetName.trim());++ if (refSheetId != null && refSheetId !== sheetId) {+ continue;+ }++ selectionWithStyle.push({+ range,+ primary: null,+ style: getFormulaRefSelectionStyle(this._themeService, themeColor),+ });+ }++ if (selectionWithStyle.length === 0) {+ return;+ }++ this._selectionManagerService.add(selectionWithStyle);+ }++ private _switchSelectionPlugin(pluginName: string) {+ const current = this._sheetSkeletonManagerService.getCurrent();++ if (current == null) {+ return;+ }++ const { unitId, sheetId } = current;++ this._selectionManagerService.setCurrentSelection({+ pluginName,+ unitId,+ sheetId,+ });+ }++ private _getSheetIdByName(unitId: string, sheetName: string) {+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);++ return workbook?.getSheetBySheetName(sheetName)?.getSheetId();+ }++ private _initialRefSelectionEvent() {+ const disposableCollection = new DisposableCollection();++ this.disposeWithMe(+ toDisposable(+ this._selectionManagerService.selectionInfo$.subscribe(() => {+ // Each range change requires re-listening+ disposableCollection.dispose();++ const current = this._selectionManagerService.getCurrent();++ if (current?.pluginName !== FORMULA_REF_SELECTION_PLUGIN_NAME) {+ return;+ }++ const selectionControls = this._selectionRenderService.getCurrentControls();+ selectionControls.forEach((controlSelection) => {+ disposableCollection.add(+ toDisposable(+ controlSelection.selectionMoving$.subscribe((toRange) => {+ if (!toRange) {+ return;+ }++ console.log('formulaRefSelections', toRange);+ })+ )+ );++ disposableCollection.add(+ toDisposable(+ controlSelection.selectionScaling$.subscribe((toRange) => {+ if (!toRange) {+ return;+ }++ console.log('formulaRefSelections', toRange);+ })+ )+ );+ });+ })+ )+ );+ }++ private _refreshEditorObject() {+ const editorObject = this._getEditorObject();++ const documentComponent = editorObject?.document;++ documentComponent?.getSkeleton()?.calculate();++ documentComponent?.makeDirty();+ }++ private _refreshFormulaBarEditorObject() {+ const editorObject = this._getEditorObject();++ const documentComponent = editorObject?.document;++ documentComponent?.getSkeleton()?.calculate();++ documentComponent?.makeDirty();+ }++ private _getEditorObject() {+ return getEditorObject(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, this._renderManagerService);+ }++ private _getFormulaBarEditorObject() {+ return getEditorObject(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, this._renderManagerService);+ }}diff --git a/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.tsindex c43b649b25..33cecec86b 100644--- a/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts+++ b/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts@@ -112,7 +112,10 @@ export class EditingController extends Disposable {// console.log(res.sheetData, res.arrayFormulaData);// });- console.log('calculate', this._formulaEngineService.calculate('=sum(, A1:B1)'));+ console.log(+ 'calculate',+ this._formulaEngineService.calculate('=REDUCE(1, [2sjasdfjdadsf]sheet1!A:B1, LAMBDA(a,b,a+b^2))', false)+ );}private _commandExecutedListener() {}diff --git a/packages/ui-plugin-sheets/src/controllers/move-range.controller.ts b/packages/ui-plugin-sheets/src/controllers/move-range.controller.tsindex 1c9503768c..0067acdcdc 100644--- a/packages/ui-plugin-sheets/src/controllers/move-range.controller.ts+++ b/packages/ui-plugin-sheets/src/controllers/move-range.controller.ts@@ -1,4 +1,9 @@-import { IMoveRangeCommandParams, MoveRangeCommand, SelectionManagerService } from '@univerjs/base-sheets';+import {+ IMoveRangeCommandParams,+ MoveRangeCommand,+ NORMAL_SELECTION_PLUGIN_NAME,+ SelectionManagerService,+} from '@univerjs/base-sheets';import {Disposable,DisposableCollection,@@ -31,6 +36,12 @@ export class MoveRangeController extends Disposable {// Each range change requires re-listeningdisposableCollection.dispose();+ const current = this._selectionManagerService.getCurrent();++ if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {+ return;+ }+const selectionControls = this._selectionRenderService.getCurrentControls();selectionControls.forEach((controlSelection) => {disposableCollection.add(diff --git a/packages/ui-plugin-sheets/src/index.ts b/packages/ui-plugin-sheets/src/index.tsindex be037aa962..cb9b8d7cf0 100644--- a/packages/ui-plugin-sheets/src/index.ts+++ b/packages/ui-plugin-sheets/src/index.ts@@ -1,4 +1,5 @@export * from './basics';+export { getEditorObject } from './basics/editor/get-editor-object';export { SetCellEditVisibleArrowOperation } from './commands/operations/cell-edit.operation';export { whenEditorInputFormulaActivated } from './controllers/shortcuts/utils';export {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ce9a0cbd7c..a552212dfe 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -934,6 +934,9 @@ importers:packages/sheets-plugin-formula-ui:dependencies:+ '@ctrl/tinycolor':+ specifier: ^4.0.2+ version: 4.0.2'@univerjs/base-docs':specifier: '*'version: link:../base-docs