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
fix: resolve lint and type errors (#7277)
白熱08b9b20f32a7
diff --git a/packages/design/src/components/color-picker/ColorPicker.tsx b/packages/design/src/components/color-picker/ColorPicker.tsxindex 4fc2f24d8c..d6d6373850 100644--- a/packages/design/src/components/color-picker/ColorPicker.tsx+++ b/packages/design/src/components/color-picker/ColorPicker.tsx@@ -39,8 +39,6 @@ export interface IColorPickerProps {}export function ColorPicker({ format = 'hex', value, onChange }: IColorPickerProps) {- if (!isBrowser) return null;-const { direction, locale } = useContext(ConfigContext);const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);@@ -69,6 +67,8 @@ export function ColorPicker({ format = 'hex', value, onChange }: IColorPickerPro}}, [value, format]);+ if (!isBrowser) return null;+function handleColorChange(h: number, s: number, v: number) {setHsv([h, s, v]);}diff --git a/packages/design/src/components/gallery/Gallery.tsx b/packages/design/src/components/gallery/Gallery.tsxindex 7bffac1c79..3c7b9b550c 100644--- a/packages/design/src/components/gallery/Gallery.tsx+++ b/packages/design/src/components/gallery/Gallery.tsx@@ -15,7 +15,7 @@*/import { OneToOneIcon, ZoomInIcon, ZoomOutIcon } from '@univerjs/icons';-import { useContext, useEffect, useMemo, useRef, useState } from 'react';+import { useContext, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { clsx } from '../../helper/clsx';import { ConfigContext } from '../config-provider/ConfigProvider';@@ -43,7 +43,7 @@ export function Gallery(props: IGalleryProps) {const dialogRef = useRef<HTMLDivElement>(null);- const activeImage = useMemo(() => images[activeImageIndex], [activeImageIndex, images]);+ const activeImage = images[activeImageIndex];const hasPagination = images.length > 1;// Focus managementdiff --git a/packages/design/src/components/input-number/InputNumber.tsx b/packages/design/src/components/input-number/InputNumber.tsxindex e1d919658a..f567f0ebc6 100644--- a/packages/design/src/components/input-number/InputNumber.tsx+++ b/packages/design/src/components/input-number/InputNumber.tsx@@ -73,7 +73,7 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(value !== undefined ? value : defaultValue !== undefined ? defaultValue : null);const lastValidValueRef = useRef<number | null>(internalValue);- const [inputValue, setInputValue] = useState<string>(formatValue(internalValue));+ const [inputValue, setInputValue] = useState<string>(() => formatValue(internalValue));const inputRef = useRef<HTMLInputElement>(null);const longPressTimerRef = useRef<NodeJS.Timeout | null>(null);const longPressIntervalRef = useRef<NodeJS.Timeout | null>(null);diff --git a/packages/design/src/components/pager/Pager.tsx b/packages/design/src/components/pager/Pager.tsxindex 8f30dd3c34..28c43c565d 100644--- a/packages/design/src/components/pager/Pager.tsx+++ b/packages/design/src/components/pager/Pager.tsx@@ -15,7 +15,6 @@*/import { MoreLeftIcon, MoreRightIcon } from '@univerjs/icons';-import { useMemo } from 'react';import { clsx } from '../../helper/clsx';export interface IPagerProps {@@ -30,7 +29,7 @@ export interface IPagerProps {export function Pager(props: IPagerProps) {const { className, value: current = 0, total: count = 0, loop, text: propText, onChange } = props;- const text = useMemo(() => propText ?? `${current}/${count}`, [current, count, propText]);+ const text = propText ?? `${current}/${count}`;const hasValue = count > 0;const onClickLeftArrow = () => {diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsxindex e542a43089..125b6503dc 100644--- a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx@@ -45,6 +45,14 @@ export interface IDocDrawingPositionProps {}export const DocDrawingPosition = (props: IDocDrawingPositionProps) => {+ const renderManagerService = useDependency(IRenderManagerService);+ const drawingParam = props.drawings[0];+ const scene = drawingParam ? renderManagerService.getRenderById(drawingParam.unitId)?.scene : undefined;++ return drawingParam && scene ? <DocDrawingPositionContent {...props} /> : null;+};++function DocDrawingPositionContent(props: IDocDrawingPositionProps) {const commandService = useDependency(ICommandService);const localeService = useDependency(LocaleService);const drawingManagerService = useDependency(IDrawingManagerService);@@ -55,10 +63,6 @@ export const DocDrawingPosition = (props: IDocDrawingPositionProps) => {const drawingParam = drawings[0] as IDocDrawing;- if (drawingParam == null) {- return;- }-const { unitId } = drawingParam;const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);@@ -66,10 +70,7 @@ export const DocDrawingPosition = (props: IDocDrawingPositionProps) => {const documentFlavor = documentDataModel?.getSnapshot().documentStyle.documentFlavor;const renderObject = renderManagerService.getRenderById(unitId);- const scene = renderObject?.scene;- if (scene == null) {- return;- }+ const scene = renderObject!.scene!;const transformer = scene.getTransformerByCreate();const HORIZONTAL_RELATIVE_FROM = [{@@ -487,4 +488,4 @@ export const DocDrawingPosition = (props: IDocDrawingPositionProps) => {</div></div>);-};+}diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsxindex 206854aeb4..67c57cab28 100644--- a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx@@ -53,30 +53,27 @@ interface IDistToText {}export const DocDrawingTextWrap = (props: IDocDrawingTextWrapProps) => {+ const renderManagerService = useDependency(IRenderManagerService);+ const drawingParam = props.drawings[0];+ const scene = drawingParam ? renderManagerService.getRenderUnitById(drawingParam.unitId)?.scene : undefined;++ return drawingParam && scene ? <DocDrawingTextWrapContent {...props} /> : null;+};++function DocDrawingTextWrapContent(props: IDocDrawingTextWrapProps) {const commandService = useDependency(ICommandService);const localeService = useDependency(LocaleService);const drawingManagerService = useDependency(IDrawingManagerService);- const renderManagerService = useDependency(IRenderManagerService);const univerInstanceService = useDependency(IUniverInstanceService);const { drawings } = props;const drawingParam = drawings[0] as IDocDrawing;- if (drawingParam == null) {- return null;- }-const { unitId } = drawingParam;const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);- const renderObject = renderManagerService.getRenderUnitById(unitId);- const scene = renderObject?.scene;- if (scene == null) {- return null;- }-const [disableWrapText, setDisableWrapText] = useState(true);const [disableDistTB, setDisableDistTB] = useState(true);const [disableDistLR, setDisableDistLR] = useState(true);@@ -395,4 +392,4 @@ export const DocDrawingTextWrap = (props: IDocDrawingTextWrapProps) => {</div></div>);-};+}diff --git a/packages/docs-mention-ui/src/views/MentionEditPopup.tsx b/packages/docs-mention-ui/src/views/MentionEditPopup.tsxindex a38f46198d..3dfed19cd8 100644--- a/packages/docs-mention-ui/src/views/MentionEditPopup.tsx+++ b/packages/docs-mention-ui/src/views/MentionEditPopup.tsx@@ -44,13 +44,21 @@ export const MentionEditPopup = () => {const search = editPopup ? documentDataModel?.getBody()?.dataStream.slice(editPopup.anchor, textSelection?.textRanges[0].startOffset) : '';useEffect(() => {- (async () => {- if (editPopup) {- const res = await mentionIOService.list({ unitId: editPopup.unitId, search });- setMentions(res.list);- }- })();+ let cancelled = false;++ if (editPopup) {+ mentionIOService.list({ unitId: editPopup.unitId, search }).then(({ list }) => {+ if (!cancelled) {+ setMentions(list);+ }+ });+ }++ return () => {+ cancelled = true;+ };}, [mentionIOService, editPopup, search]);+if (!editPopup) {return null;}diff --git a/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsx b/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsxindex a23fa76b6f..fd8690eac0 100644--- a/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsx+++ b/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsx@@ -95,10 +95,16 @@ class TestMentionState {class TestMentionIOService {readonly requests: IListMentionParam[] = [];+ readonly pending: Array<(response: IListMentionResponse) => void> = [];+ deferResponses = false;async list(params: IListMentionParam): Promise<IListMentionResponse> {this.requests.push(params);+ if (this.deferResponses) {+ return new Promise((resolve) => this.pending.push(resolve));+ }+return {list: peopleMentions,total: peopleMentions[0].mentions.length,@@ -353,6 +359,57 @@ describe('mention views', () => {expect(testBed.editorService.focusedUnitIds).toEqual([unitId, unitId]);});+ it('keeps the latest mention response when an older request resolves last', async () => {+ const testBed = createViewsTestBed();+ univer = testBed.univer;+ testBed.mentionIOService.deferResponses = true;+ testBed.popupService.showEditPopup(unitId, 6);+ const rendered = renderIntoDocument(<MentionEditPopup />, testBed.injector);+ disposable = disposeRender(rendered.root, rendered.container);++ await act(async () => {+ testBed.selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 9,+ endOffset: 9,+ collapsed: true,+ isActive: true,+ segmentId: '',+ style: null as never,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ isEditing: true,+ style: null as never,+ }, {+ unitId,+ subUnitId: unitId,+ });+ await Promise.resolve();+ });++ const response = (label: string): IListMentionResponse => ({+ list: [{+ ...peopleMentions[0],+ mentions: [{ ...peopleMentions[0].mentions[0], label }],+ }],+ total: 1,+ });++ await act(async () => {+ testBed.mentionIOService.pending[1](response('Latest'));+ await Promise.resolve();+ });+ await act(async () => {+ testBed.mentionIOService.pending[0](response('Stale'));+ await Promise.resolve();+ });++ expect(rendered.container.textContent).toContain('Latest');+ expect(rendered.container.textContent).not.toContain('Stale');+ });+it('dismisses the edit popup from the empty list area without inserting a mention', async () => {const testBed = createViewsTestBed();univer = testBed.univer;diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/editor-undo-redo-keyboard.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/editor-undo-redo-keyboard.tsindex 70edc5bcb8..80678ef913 100644--- a/packages/docs-ui/src/views/rich-text-editor/hooks/editor-undo-redo-keyboard.ts+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/editor-undo-redo-keyboard.ts@@ -60,7 +60,7 @@ export function executeEditorUndoRedoCommand(options: IExecuteEditorUndoRedoCommuniverInstanceService.focusUnit(editorUnitId);}- void commandService.executeCommand(commandId).finally(() => {+ commandService.executeCommand(commandId).finally(() => {if (shouldRestoreFocus) {univerInstanceService.focusUnit(previousFocusedUnitId);}diff --git a/packages/drawing-ui/src/controllers/image-update.controller.ts b/packages/drawing-ui/src/controllers/image-update.controller.tsindex b5a368fdf6..9b886febd9 100644--- a/packages/drawing-ui/src/controllers/image-update.controller.ts+++ b/packages/drawing-ui/src/controllers/image-update.controller.ts@@ -177,7 +177,7 @@ export class ImageUpdateController extends Disposable {filter((items) => items.length > 0)).subscribe((uniqueParams) => {- void this._insertImages(uniqueParams);+ this._insertImages(uniqueParams);}));}diff --git a/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsxindex b8fbcda819..c889496cb4 100644--- a/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx+++ b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx@@ -67,6 +67,10 @@ export function ImagePopupMenu(props: IImagePopupMenuProps) {const { popup } = props;const menuItems = popup?.extraProps?.menuItems;+ const commandService = useDependency(ICommandService);+ const localeService = useDependency(LocaleService);+ const [visible, setVisible] = useState(false);+ const [isHovered, setIsHovered] = useState(false);if (!menuItems) return null;@@ -90,18 +94,12 @@ export function ImagePopupMenu(props: IImagePopupMenuProps) {return <DocChartFloatingToolbar menuItems={menuItems} />;}- const commandService = useDependency(ICommandService);- const localeService = useDependency(LocaleService);-- const [visible, setVisible] = useState(false);- const [isHovered, setHovered] = useState(false);-const handleMouseEnter = () => {- setHovered(true);+ setIsHovered(true);};const handleMouseLeave = () => {- setHovered(false);+ setIsHovered(false);};const onVisibleChange = (visible: boolean) => {diff --git a/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx b/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsxindex b549971de0..07f55dc2d5 100644--- a/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx+++ b/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx@@ -76,19 +76,9 @@ export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {const { drawings, hasArrange = true, hasTransform = true, hasAlign = true, hasCropper = true, hasGroup = true } = props;const drawingParam = drawings[0];-- if (drawingParam == null) {- return;- }-- const { unitId } = drawingParam;-- const renderObject = renderManagerService.getRenderById(unitId);+ const renderObject = drawingParam ? renderManagerService.getRenderById(drawingParam.unitId) : undefined;const scene = renderObject?.scene;- if (scene == null) {- return;- }- const transformer = scene.getTransformerByCreate();+ const transformer = scene?.getTransformerByCreate();const initialShowState = getPanelShowState(drawings);@@ -100,6 +90,7 @@ export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {// const [groupShow, setGroupShow] = useState(false);useEffect(() => {+ if (!transformer) return;const clearControlSub = transformer.clearControl$.subscribe((changeSelf) => {if (changeSelf === true) {setArrangeShow(false);@@ -162,7 +153,11 @@ export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {clearControlSub.unsubscribe();focusSub.unsubscribe();};- }, []);+ }, [drawingManagerService, transformer]);++ if (!drawingParam || !scene || !transformer) {+ return null;+ }return (<>diff --git a/packages/drawing-ui/src/views/panel/DrawingTransform.tsx b/packages/drawing-ui/src/views/panel/DrawingTransform.tsxindex 26f7f8eb3c..a7ad1dffa3 100644--- a/packages/drawing-ui/src/views/panel/DrawingTransform.tsx+++ b/packages/drawing-ui/src/views/panel/DrawingTransform.tsx@@ -36,35 +36,33 @@ export interface IDrawingTransformProps {const INPUT_DEBOUNCE_TIME = 300;export const DrawingTransform = (props: IDrawingTransformProps) => {+ const renderManagerService = useDependency(IRenderManagerService);+ const drawingParam = props.drawings[0];+ const scene = drawingParam ? renderManagerService.getRenderById(drawingParam.unitId)?.scene : undefined;+ const topScene = scene?.getEngine()?.activeScene as Nullable<Scene>;++ if (!drawingParam?.transform || !scene || !topScene) {+ return null;+ }++ return <DrawingTransformContent {...props} />;+};++function DrawingTransformContent(props: IDrawingTransformProps) {const localeService = useDependency(LocaleService);const drawingManagerService = useDependency(IDrawingManagerService);const renderManagerService = useDependency(IRenderManagerService);const { drawings, transformShow } = props;- const drawingParam = drawings[0];-- if (drawingParam == null) {- return;- }-- const transform = drawingParam.transform;- if (transform == null) {- return;- }+ const drawingParam = drawings[0]!;+ const transform = drawingParam.transform!;const { unitId, subUnitId, drawingId, drawingType } = drawingParam;const renderObject = renderManagerService.getRenderById(unitId);- const scene = renderObject?.scene;- if (scene == null) {- return;- }-- const topScene = scene.getEngine()?.activeScene as Nullable<Scene>;- if (topScene == null) {- return;- }+ const scene = renderObject!.scene!;+ const topScene = scene.getEngine()!.activeScene as Scene;const transformer = scene.getTransformerByCreate();@@ -424,4 +422,4 @@ export const DrawingTransform = (props: IDrawingTransformProps) => {</div></div>);-};+}diff --git a/packages/drawing-ui/src/views/panel/ImageCropper.tsx b/packages/drawing-ui/src/views/panel/ImageCropper.tsxindex ad0ee7a871..11f25287d6 100644--- a/packages/drawing-ui/src/views/panel/ImageCropper.tsx+++ b/packages/drawing-ui/src/views/panel/ImageCropper.tsx@@ -43,13 +43,7 @@ export const ImageCropper = (props: IImageCropperProps) => {const { drawings, cropperShow } = props;const drawingParam = drawings[0];-- if (drawingParam == null) {- return;- }-const [cropValue, setCropValue] = useState<string>(CropType.FREE as string);-const cropStateRef = useRef(false);const cropOptions = [@@ -110,6 +104,10 @@ export const ImageCropper = (props: IImageCropperProps) => {};}, []);+ if (drawingParam == null) {+ return null;+ }+function handleCropChange(value: string | number | boolean) {setCropValue((value as string));if (cropStateRef.current) {diff --git a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts b/packages/engine-formula/src/services/formula-calculation-trigger.service.tsindex 11be6d633f..39ab9b3c3f 100644--- a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts+++ b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts@@ -116,7 +116,7 @@ export class FormulaCalculationTriggerService extends Disposable {this._executingDirtyData = mergeDirtyData(this._executingDirtyData, dirtyData);if (this._executionInProgress) {this._restartCalculation = true;- void this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {}, LOCAL_ONLY);+ this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {}, LOCAL_ONLY);return;}@@ -125,7 +125,7 @@ export class FormulaCalculationTriggerService extends Disposable {private _startCalculation(): void {this._executionInProgress = true;- void this._commandService.executeCommand(+ this._commandService.executeCommand(SetFormulaCalculationStartMutation.id,{ ...this._executingDirtyData },LOCAL_ONLYdiff --git a/packages/engine-render/src/shape/__tests__/image.spec.ts b/packages/engine-render/src/shape/__tests__/image.spec.tsindex 7e626bb18c..8c0d0a80c9 100644--- a/packages/engine-render/src/shape/__tests__/image.spec.ts+++ b/packages/engine-render/src/shape/__tests__/image.spec.ts@@ -40,6 +40,22 @@ function createCtxMock() {}describe('image extra', () => {+ it('preserves the request mode of an already-loaded native image', () => {+ const native = createNativeImage();+ native.crossOrigin = 'use-credentials';++ const image = new Image('decoded-image', {+ image: native,+ left: 0,+ top: 0,+ width: 120,+ height: 80,+ });++ expect(image.getNative()).toBe(native);+ expect(native.crossOrigin).toBe('use-credentials');+ });+it('handles srcRect transform and render branches', () => {const image = new Image('img1', {image: createNativeImage(100, 60),diff --git a/packages/engine-render/src/shape/image.ts b/packages/engine-render/src/shape/image.tsindex 23447861e5..5722f8e506 100644--- a/packages/engine-render/src/shape/image.ts+++ b/packages/engine-render/src/shape/image.ts@@ -91,7 +91,6 @@ export class Image extends Shape<IImageProps> {if (config.image) {this._native = config.image;- this._native.crossOrigin = 'anonymous';this.makeDirty(true);} else if (config.url) {this._native = document.createElement('img');diff --git a/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts b/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.tsindex 125ecd33da..b8d3e6237b 100644--- a/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts+++ b/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts@@ -151,7 +151,7 @@ describe('rpc.service edge cases', () => {})).toThrow('[ChannelClient]: unknown response type!');callPending.delete(getSeq(unknownCallRequest) as number);- void unknownCallPromise.catch(() => undefined);+ unknownCallPromise.catch(() => undefined);const values: number[] = [];const stream = channel.subscribe<number>('stream$').subscribe((value) => values.push(value));diff --git a/packages/sheets-conditional-formatting-ui/src/views/Preview.tsx b/packages/sheets-conditional-formatting-ui/src/views/Preview.tsxindex 0498905dff..af60194e51 100644--- a/packages/sheets-conditional-formatting-ui/src/views/Preview.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/Preview.tsx@@ -18,16 +18,22 @@ import type { IConditionalFormattingRuleConfig } from '@univerjs/sheets-conditioimport { BooleanNumber, ColorKit } from '@univerjs/core';import { clsx } from '@univerjs/design';import { SlashDoubleIcon } from '@univerjs/icons';-import { CFRuleType, DEFAULT_BG_COLOR, DEFAULT_FONT_COLOR, defaultDataBarNativeColor, defaultDataBarPositiveColor, getColorScaleFromValue, iconMap } from '@univerjs/sheets-conditional-formatting';+import {+ CFRuleType,+ DEFAULT_BG_COLOR,+ DEFAULT_FONT_COLOR,+ defaultDataBarNativeColor,+ defaultDataBarPositiveColor,+ getColorScaleFromValue,+ iconMap,+} from '@univerjs/sheets-conditional-formatting';import { useMemo } from 'react';-export const Preview = (props: { rule?: IConditionalFormattingRuleConfig }) => {- const rule = props.rule;-- if (!rule) return null;+export function Preview(props: { rule?: IConditionalFormattingRuleConfig }) {+ const { rule } = props;const colorList = useMemo(() => {- if (rule.type === CFRuleType.colorScale) {+ if (rule?.type === CFRuleType.colorScale) {const config = rule.config.map((c, index) => ({ color: new ColorKit(c.color), value: index }));const maxValue = config.length - 1;const valueList = new Array(5).fill('').map((_v, index, arr) => index * maxValue / (arr.length - 1));@@ -37,7 +43,7 @@ export const Preview = (props: { rule?: IConditionalFormattingRuleConfig }) => {}, [rule]);const iconSet = useMemo(() => {- if (rule.type === CFRuleType.iconSet) {+ if (rule?.type === CFRuleType.iconSet) {return rule.config.map((item) => {const iconList = iconMap[item.iconType];return iconList && iconList[Number(item.iconId)];@@ -45,6 +51,8 @@ export const Preview = (props: { rule?: IConditionalFormattingRuleConfig }) => {}}, [rule]);+ if (!rule) return null;+const previewClassName = 'univer-pointer-events-none univer-flex univer-h-5 univer-min-w-[72px] univer-items-center univer-justify-center univer-text-xs';switch (rule.type) {@@ -124,4 +132,4 @@ export const Preview = (props: { rule?: IConditionalFormattingRuleConfig }) => {);}}-};+}diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsxindex 6f1baa4ffb..3b27102f13 100644--- a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx@@ -121,7 +121,7 @@ const getRuleDescribe = (rule: IConditionFormattingRule, localeService: LocaleSe}};-export const RuleList = (props: IRuleListProps) => {+export function RuleList(props: IRuleListProps) {const { onClick } = props;const conditionalFormattingRuleModel = useDependency(ConditionalFormattingRuleModel);const univerInstanceService = useDependency(IUniverInstanceService);@@ -132,12 +132,14 @@ export const RuleList = (props: IRuleListProps) => {const conditionalFormattingI18nController = useDependency(ConditionalFormattingI18nController);- const workbook = useObservable(() => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET), undefined, undefined, [])!;+ const workbook = useObservable(+ () => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET),+ undefined,+ undefined,+ []+ )!;const unitId = workbook.getUnitId();const worksheet = workbook.getActiveSheet();- if (!worksheet) {- throw new Error('No active sheet found');- }const subUnitId = worksheet.getSheetId();@@ -422,4 +424,4 @@ export const RuleList = (props: IRuleListProps) => {</div></div>);-};+}diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsxindex 989a50f1f1..efe15e1db6 100644--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx@@ -15,7 +15,7 @@*/import type { Workbook } from '@univerjs/core';-import type { IColorScale, IConditionalFormattingRuleConfig } from '@univerjs/sheets-conditional-formatting';+import type { IColorScale } from '@univerjs/sheets-conditional-formatting';import type { IFormulaEditorRef } from '@univerjs/sheets-formula-ui';import type { LocaleKey } from '../../../locale/types';import type { IStyleEditorProps } from './type';@@ -194,7 +194,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {minColor: string;medianColor: string;maxColor: string;- }) => {+ }): IColorScale => {const { minType, medianType, maxType, minValue, medianValue, maxValue, minColor, medianColor, maxColor } = option;const list = [];list.push({ color: minColor, value: { type: minType, value: minValue } });@@ -237,7 +237,19 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.styleRule')}</div><div className={previewClassName}>- <Preview rule={getResult({ minType, medianType, maxType, minValue, medianValue, maxValue, minColor, medianColor, maxColor }) as IConditionalFormattingRuleConfig} />+ <Preview+ rule={getResult({+ minType,+ medianType,+ maxType,+ minValue,+ medianValue,+ maxValue,+ minColor,+ medianColor,+ maxColor,+ })}+ /></div><divclassName={`diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsxindex 6ca1f47020..ca05a75f22 100644--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx@@ -15,7 +15,7 @@*/import type { Workbook } from '@univerjs/core';-import type { IConditionalFormattingRuleConfig, IValueConfig } from '@univerjs/sheets-conditional-formatting';+import type { IDataBar, IValueConfig } from '@univerjs/sheets-conditional-formatting';import type { IFormulaEditorRef } from '@univerjs/sheets-formula-ui';import type { LocaleKey } from '../../../locale/types';import type { IStyleEditorProps } from './type';@@ -193,7 +193,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {positiveColor: string;isShowValue: boolean;nativeColor: string;- }) => {+ }): IDataBar => {const config: {min: IValueConfig;max: IValueConfig;@@ -284,7 +284,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {positiveColor,nativeColor,isShowValue,- }) as IConditionalFormattingRuleConfig}+ })}/></div><div>diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsxindex 656ddc2c09..b1365ed4f1 100644--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx@@ -16,10 +16,8 @@import type { Workbook } from '@univerjs/core';import type {- IAverageHighlightCell,- IConditionalFormattingRuleConfig,+ IFormulaHighlightCell,IHighlightCell,- IRankHighlightCell,} from '@univerjs/sheets-conditional-formatting';import type { IFormulaEditorRef } from '@univerjs/sheets-formula-ui';import type { LocaleKey } from '../../../locale/types';@@ -43,7 +41,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const worksheet = workbook.getActiveSheet();- const rule = props.rule?.type === CFRuleType.highlightCell ? props.rule : undefined as IRankHighlightCell | IAverageHighlightCell | undefined;+ const rule = props.rule?.type === CFRuleType.highlightCell ? props.rule : undefined;const divEleRef = useRef<HTMLDivElement>(null);const [isFocusFormulaEditor, setIsFocusFormulaEditor] = useState(false);@@ -60,7 +58,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {const getResult = (config: {style: IHighlightCell['style'];formula: string;- }) => {+ }): IFormulaHighlightCell => {return {style: config.style,value: formula,@@ -155,7 +153,12 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {</div><div className={previewClassName}>- <Preview rule={getResult({ style, formula }) as IConditionalFormattingRuleConfig} />+ <Preview+ rule={getResult({+ style,+ formula,+ })}+ /></div><ConditionalStyleEditorstyle={rule?.style}diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsxindex fbb69dbe64..39e0bdd977 100644--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx@@ -15,11 +15,12 @@*/import type {- IConditionalFormattingRuleConfig,+ IDuplicateValuesHighlightCell,IHighlightCell,INumberHighlightCell,ITextHighlightCell,ITimePeriodHighlightCell,+ IUniqueValuesHighlightCell,} from '@univerjs/sheets-conditional-formatting';import type { LocaleKey } from '../../../locale/types';import type { IStyleEditorProps } from './type';@@ -40,16 +41,27 @@ import { Preview } from '../../Preview';import { WrapperError } from '../../wrapper-error/WrapperError';import { previewClassName } from './styles';-const createOptionItem = (text: CFTextOperator | CFNumberOperator | CFTimePeriodOperator): { label: LocaleKey; value: string } => ({+type IEditableHighlightCell = ITextHighlightCell | INumberHighlightCell | ITimePeriodHighlightCell | IDuplicateValuesHighlightCell | IUniqueValuesHighlightCell;+type IEditableSubType = IEditableHighlightCell['subType'];+type IEditableOperator = ITextHighlightCell['operator'] | INumberHighlightCell['operator'] | ITimePeriodHighlightCell['operator'];++const textOperators = new Set<string>(Object.values(CFTextOperator));+const numberOperators = new Set<string>(Object.values(CFNumberOperator));+const timePeriodOperators = new Set<string>(Object.values(CFTimePeriodOperator));++const isTextOperator = (value: unknown): value is CFTextOperator => typeof value === 'string' && textOperators.has(value);+const isNumberOperator = (value: unknown): value is CFNumberOperator => typeof value === 'string' && numberOperators.has(value);+const isTimePeriodOperator = (value: unknown): value is CFTimePeriodOperator => typeof value === 'string' && timePeriodOperators.has(value);++const createOptionItem = <T extends IEditableOperator>(text: T): { label: LocaleKey; value: T } => ({label: `sheets-conditional-formatting-ui.operator.${text}`,value: text,});type IValue = number | string | [number, number];-type IResult = (Pick<ITextHighlightCell | INumberHighlightCell | ITimePeriodHighlightCell, 'operator' | 'subType'>) & { value?: IValue };function HighlightCellInput(props: {- type: IResult['subType'] | CFSubRuleType.duplicateValues | CFSubRuleType.uniqueValues;- operator?: IResult['operator'];+ type: IEditableSubType;+ operator?: IEditableOperator;interceptorManager: IStyleEditorProps['interceptorManager'];rule?: IHighlightCell;value: IValue;@@ -190,7 +202,7 @@ function HighlightCellInput(props: {}return null;};-const getOperatorOptions = (type: CFSubRuleType.duplicateValues | CFSubRuleType.uniqueValues | CFSubRuleType.number | CFSubRuleType.text | CFSubRuleType.timePeriod | CFSubRuleType.formula) => {+const getOperatorOptions = (type: IEditableSubType) => {switch (type) {case CFSubRuleType.text: {return [@@ -236,12 +248,12 @@ const getOperatorOptions = (type: CFSubRuleType.duplicateValues | CFSubRuleType.return [];}};-export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHighlightCell | INumberHighlightCell | ITimePeriodHighlightCell>) => {+export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, IEditableHighlightCell>) => {const { interceptorManager, onChange } = props;const localeService = useDependency(LocaleService);const rule = props.rule?.type === CFRuleType.highlightCell ? props.rule : undefined;- const [subType, setSubType] = useState<CFSubRuleType.number | CFSubRuleType.text | CFSubRuleType.timePeriod | CFSubRuleType.duplicateValues | CFSubRuleType.uniqueValues>(() => {+ const [subType, setSubType] = useState<IEditableSubType>(() => {const defaultV = CFSubRuleType.text;if (!rule) {return defaultV;@@ -249,7 +261,7 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHighreturn rule.subType || defaultV;});- const typeOptions = [{+ const typeOptions: Array<{ value: IEditableSubType; label: string }> = [{value: CFSubRuleType.text,label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.subRuleType.text'),}, {@@ -268,12 +280,12 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHighconst operatorOptions = useMemo(() => getOperatorOptions(subType).map((option) => ({ ...option, label: localeService.t(option.label) })), [localeService, subType]);- const [operator, setOperator] = useState<IResult['operator'] | undefined>(() => {- const defaultV = operatorOptions[0]?.value as IResult['operator'] | undefined;+ const [operator, setOperator] = useState<IEditableOperator | undefined>(() => {+ const defaultV = operatorOptions[0]?.value;if (!rule) {return defaultV;}- return rule.operator || defaultV;+ return 'operator' in rule ? rule.operator : defaultV;});const [value, setValue] = useState<IValue>(() => {@@ -281,62 +293,72 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHighif (!rule) {return defaultV;}- const v = (rule as ITextHighlightCell | INumberHighlightCell).value ?? createDefaultValue(rule.subType, rule.operator);- return v;+ if ('value' in rule && rule.value !== undefined) {+ return rule.value;+ }+ return 'operator' in rule ? createDefaultValue(rule.subType, rule.operator) : defaultV;});const [style, setStyle] = useState<IHighlightCell['style']>({});- const getResult = useMemo(() => (option: { subType?: string; operator?: string; value?: IValue; style?: IHighlightCell['style'] }) => {- switch (option.subType || subType) {- case CFSubRuleType.duplicateValues:- case CFSubRuleType.uniqueValues: {+ const getResult = useMemo(() => (option: { subType?: IEditableSubType; operator?: IEditableOperator; value?: IValue; style?: IHighlightCell['style'] }): IEditableHighlightCell => {+ const nextSubType = option.subType ?? subType;+ const nextOperator = option.operator ?? operator;+ const nextValue = option.value ?? value;+ const nextStyle = option.style ?? style;++ switch (nextSubType) {+ case CFSubRuleType.duplicateValues: {return {type: CFRuleType.highlightCell,- subType: option.subType ?? subType,- style: option.style ?? style,+ subType: CFSubRuleType.duplicateValues,+ style: nextStyle,};}+ case CFSubRuleType.uniqueValues:+ return {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.uniqueValues,+ style: nextStyle,+ };case CFSubRuleType.text: {- if ([CFTextOperator.beginsWith, CFTextOperator.endsWith, CFTextOperator.containsText, CFTextOperator.notContainsText, CFTextOperator.equal, CFTextOperator.notEqual].includes(operator as CFTextOperator)) {- return {- type: CFRuleType.highlightCell,- subType: option.subType ?? subType,- operator: option.operator ?? operator,- style: option.style ?? style,- value: option.value ?? value,- };- }- break;+ return {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.text,+ operator: isTextOperator(nextOperator) ? nextOperator : CFTextOperator.containsText,+ style: nextStyle,+ value: typeof nextValue === 'string' ? nextValue : undefined,+ };+ }+ case CFSubRuleType.timePeriod: {+ return {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.timePeriod,+ operator: isTimePeriodOperator(nextOperator) ? nextOperator : CFTimePeriodOperator.today,+ style: nextStyle,+ };}case CFSubRuleType.number: {- if ([CFNumberOperator.equal, CFNumberOperator.notEqual, CFNumberOperator.greaterThan, CFNumberOperator.greaterThanOrEqual, CFNumberOperator.lessThan, CFNumberOperator.lessThanOrEqual].includes(operator as CFNumberOperator)) {- return {- type: CFRuleType.highlightCell,- subType: option.subType ?? subType,- operator: option.operator ?? operator,- style: option.style ?? style,- value: option.value ?? value,- };- }- if ([CFNumberOperator.between, CFNumberOperator.notBetween].includes(operator as CFNumberOperator)) {+ const numberOperator = isNumberOperator(nextOperator) ? nextOperator : CFNumberOperator.equal;+ if (numberOperator === CFNumberOperator.between || numberOperator === CFNumberOperator.notBetween) {+ const range: [number, number] = Array.isArray(nextValue) ? nextValue : [0, 100];return {type: CFRuleType.highlightCell,- subType: option.subType ?? subType,- operator: option.operator ?? operator,- style: option.style ?? style,- value: option.value ?? value,+ subType: CFSubRuleType.number,+ operator: numberOperator,+ style: nextStyle,+ value: range,};}- break;+ return {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.number,+ operator: numberOperator,+ style: nextStyle,+ value: typeof nextValue === 'number' ? nextValue : undefined,+ };}}- return {- type: CFRuleType.highlightCell,- subType: option.subType ?? subType,- operator: option.operator ?? operator,- style: option.style ?? style,- };}, [subType, operator, value, style]);useEffect(() => {@@ -355,9 +377,12 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHigh}, [typeOptions]);const onTypeChange = (v: string) => {- const _subType = v as typeof subType;+ const _subType = typeOptions.find((item) => item.value === v)?.value;+ if (!_subType) {+ return;+ }const operatorList = getOperatorOptions(_subType).map((option) => ({ ...option, label: localeService.t(option.label) }));- const _operator = operatorList[0]?.value as typeof operator;+ const _operator = operatorList[0]?.value;setSubType(_subType);setOperator(_operator);_operator && setValue(createDefaultValue(_subType, _operator));@@ -365,7 +390,10 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHigh};const onOperatorChange = (v: string) => {- const _operator = v as typeof operator;+ const _operator = operatorOptions.find((item) => item.value === v)?.value;+ if (!_operator) {+ return;+ }setOperator(_operator);onChange(getResult({ operator: _operator }));};@@ -375,10 +403,6 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHighonChange(getResult({ value }));};- const inputRenderKey = useMemo(() => {- return `${subType}_${operator}_${Math.random()}`;- }, [subType, operator]);-return (<div><div@@ -406,7 +430,7 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHigh)}</div><HighlightCellInput- key={inputRenderKey}+ key={`${subType}_${operator}`}value={value}interceptorManager={interceptorManager}type={subType}@@ -415,7 +439,7 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, ITextHighonChange={onInputChange}/><div className={previewClassName}>- <Preview rule={getResult({}) as IConditionalFormattingRuleConfig} />+ <Preview rule={getResult({})} /></div><ConditionalStyleEditorstyle={rule?.style}diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Rank.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Rank.tsxindex 62159ce285..be0268ff17 100644--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Rank.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Rank.tsx@@ -16,7 +16,6 @@import type {IAverageHighlightCell,- IConditionalFormattingRuleConfig,IHighlightCell,IRankHighlightCell,} from '@univerjs/sheets-conditional-formatting';@@ -31,14 +30,16 @@ import { ConditionalStyleEditor } from '../../ConditionalStyleEditor';import { Preview } from '../../Preview';import { previewClassName } from './styles';+type IRankRuleType = 'isNotBottom' | 'isBottom' | 'greaterThanAverage' | 'lessThanAverage';+export const RankStyleEditor = (props: IStyleEditorProps) => {const { onChange, interceptorManager } = props;const localeService = useDependency(LocaleService);- const rule = props.rule?.type === CFRuleType.highlightCell ? props.rule : undefined as IRankHighlightCell | IAverageHighlightCell | undefined;- const options = [{ label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.isNotBottom'), value: 'isNotBottom' }, { label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.isBottom'), value: 'isBottom' }, { label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.greaterThanAverage'), value: 'greaterThanAverage' }, { label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.lessThanAverage'), value: 'lessThanAverage' }];+ const rule = props.rule?.type === CFRuleType.highlightCell ? props.rule : undefined;+ const options: Array<{ label: string; value: IRankRuleType }> = [{ label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.isNotBottom'), value: 'isNotBottom' }, { label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.isBottom'), value: 'isBottom' }, { label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.greaterThanAverage'), value: 'greaterThanAverage' }, { label: localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.lessThanAverage'), value: 'lessThanAverage' }];- const [type, setType] = useState(() => {+ const [type, setType] = useState<IRankRuleType>(() => {const defaultV = options[0].value;const type = rule?.type;if (!rule) {@@ -109,25 +110,25 @@ export const RankStyleEditor = (props: IStyleEditorProps) => {const [style, setStyle] = useState<IHighlightCell['style']>({});const getResult = (config: {- type: string;+ type: IRankRuleType;isPercent: boolean;value: number;style: IHighlightCell['style'];- }) => {+ }): IRankHighlightCell | IAverageHighlightCell => {const { type, isPercent, value, style } = config;- if (type === 'isNotBottom') {- return { type: CFRuleType.highlightCell, subType: CFSubRuleType.rank, isPercent, isBottom: false, value, style };- }- if (type === 'isBottom') {- return { type: CFRuleType.highlightCell, subType: CFSubRuleType.rank, isPercent, isBottom: true, value, style };- }- if (type === 'greaterThanAverage') {- return { type: CFRuleType.highlightCell, subType: CFSubRuleType.average, operator: CFNumberOperator.greaterThan, style };- }- if (type === 'lessThanAverage') {- return { type: CFRuleType.highlightCell, subType: CFSubRuleType.average, operator: CFNumberOperator.lessThan, style };++ switch (type) {+ case 'isNotBottom':+ return { type: CFRuleType.highlightCell, subType: CFSubRuleType.rank, isPercent, isBottom: false, value, style };+ case 'isBottom':+ return { type: CFRuleType.highlightCell, subType: CFSubRuleType.rank, isPercent, isBottom: true, value, style };+ case 'greaterThanAverage':+ return { type: CFRuleType.highlightCell, subType: CFSubRuleType.average, operator: CFNumberOperator.greaterThan, style };+ case 'lessThanAverage':+ return { type: CFRuleType.highlightCell, subType: CFSubRuleType.average, operator: CFNumberOperator.lessThan, style };}};+useEffect(() => {const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().submit, {handler() {@@ -138,7 +139,7 @@ export const RankStyleEditor = (props: IStyleEditorProps) => {}, [type, isPercent, value, style, interceptorManager]);const _onChange = (config: {- type: string;+ type: IRankRuleType;isPercent: boolean;value: number;style: IHighlightCell['style'];@@ -160,8 +161,11 @@ export const RankStyleEditor = (props: IStyleEditorProps) => {value={type}options={options}onChange={(v) => {- setType(v);- _onChange({ type: v, isPercent, value, style });+ const nextType = options.find((option) => option.value === v)?.value;+ if (nextType) {+ setType(nextType);+ _onChange({ type: nextType, isPercent, value, style });+ }}}/>{['isNotBottom', 'isBottom'].includes(type) && (@@ -192,7 +196,14 @@ export const RankStyleEditor = (props: IStyleEditorProps) => {</div>)}<div className={previewClassName}>- <Preview rule={getResult({ type, isPercent, value, style }) as IConditionalFormattingRuleConfig} />+ <Preview+ rule={getResult({+ type,+ isPercent,+ value,+ style,+ })}+ /></div><ConditionalStyleEditorstyle={rule?.style}diff --git a/packages/sheets-data-validation-ui/src/views/components/DataValidationDetail.tsx b/packages/sheets-data-validation-ui/src/views/components/DataValidationDetail.tsxindex 03a9485582..232085ded6 100644--- a/packages/sheets-data-validation-ui/src/views/components/DataValidationDetail.tsx+++ b/packages/sheets-data-validation-ui/src/views/components/DataValidationDetail.tsx@@ -127,9 +127,13 @@ function DataValidationDetailInner(props: { activeRuleInfo: { unitId: string; su}, [sheetSelectionService]);useEffect(() => {- commandService.onCommandExecuted((commandInfo) => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const disposable = commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === UndoCommand.id || commandInfo.id === RedoCommand.id) {- setTimeout(() => {+ if (timer !== undefined) {+ clearTimeout(timer);+ }+ timer = setTimeout(() => {const activeRule = dataValidationModel.getRuleById(unitId, subUnitId, ruleId) as ISheetDataValidationRule;setKey((k) => k + 1);if (activeRule) {@@ -139,41 +143,14 @@ function DataValidationDetailInner(props: { activeRuleInfo: { unitId: string; su}, 20);}});- }, [commandService, dataValidationModel, ruleId, subUnitId, unitId]);-- if (!validator) {- return null;- }- const operators = validator.operators;- const operatorNames = validator.operatorNames;- const isTwoFormula = localRule.operator ? TWO_FORMULA_OPERATOR_COUNT.includes(localRule.operator) : false;-- const goBackActiveRuleSheet = () => {- if (worksheet?.getSheetId() !== subUnitId) {- commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {- unitId,- subUnitId,- });- }- };-- const handleOk = () => {- if (rangeSelectorInstance.current?.editor?.isFocus()) {- handleUpdateRuleRanges(rangeSelectorInstance.current?.getValue());- }- if (!localRule.ranges.length || isRangeError) {- return;- }-- if (validator.validatorFormula(localRule, unitId, subUnitId).success) {- dataValidationPanelService.setActiveRule(null);- } else {- setShowError(true);- }-- goBackActiveRuleSheet();- };+ return () => {+ disposable.dispose();+ if (timer !== undefined) {+ clearTimeout(timer);+ }+ };+ }, [commandService, dataValidationModel, ruleId, subUnitId, unitId]);const handleUpdateRuleRanges = useEvent((rangeText: string) => {const unitRanges = rangeText.split(',').filter(Boolean).map(deserializeRangeWithSheet).map((unitRange) => {@@ -210,6 +187,41 @@ function DataValidationDetailInner(props: { activeRuleInfo: { unitId: string; sudebounceExecute(UpdateSheetDataValidationRangeCommand.id, params);});+ const rangeStr = useMemo(() => localRanges.map((i) => serializeRange(i.range)).join(','), []);++ if (!validator) {+ return null;+ }++ const operators = validator.operators;+ const operatorNames = validator.operatorNames;+ const isTwoFormula = localRule.operator ? TWO_FORMULA_OPERATOR_COUNT.includes(localRule.operator) : false;++ const goBackActiveRuleSheet = () => {+ if (worksheet?.getSheetId() !== subUnitId) {+ commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {+ unitId,+ subUnitId,+ });+ }+ };++ const handleOk = () => {+ if (rangeSelectorInstance.current?.editor?.isFocus()) {+ handleUpdateRuleRanges(rangeSelectorInstance.current?.getValue());+ }+ if (!localRule.ranges.length || isRangeError) {+ return;+ }++ if (validator.validatorFormula(localRule, unitId, subUnitId).success) {+ dataValidationPanelService.setActiveRule(null);+ } else {+ setShowError(true);+ }++ goBackActiveRuleSheet();+ };const handleUpdateRuleSetting = (setting: IDataValidationRuleBase) => {if (shallowEqual(setting, getRuleSetting(localRule))) {@@ -283,7 +295,6 @@ function DataValidationDetailInner(props: { activeRuleInfo: { unitId: string; su};const FormulaInput = componentManager.get(validator.formulaInput!);- const rangeStr = useMemo(() => localRanges.map((i) => serializeRange(i.range)).join(','), []);const options: IDataValidationRuleOptions = getRuleOptions(localRule);diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsxindex b4317238b0..5e74064fab 100644--- a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx@@ -623,6 +623,24 @@ describe('DataValidationDetail rule editing', () => {currentTestBed = undefined;});+ it('disposes command listeners when unmounted', async () => {+ currentTestBed = createDetailTestBed(createDateRule());+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ const commandListeners = () => (currentTestBed!.commandService as unknown as { _commandExecutedListeners: unknown[] })._commandExecutedListeners.length;+ const initialListenerCount = commandListeners();++ await renderDetail(root, currentTestBed);+ expect(commandListeners()).toBeGreaterThan(initialListenerCount);++ act(() => root?.unmount());+ root = undefined;++ expect(commandListeners()).toBe(initialListenerCount);+ });+it('persists the allow-blank checkbox into the active rule setting command', async () => {currentTestBed = createDetailTestBed(createDateRule('rule-date-allow-blank'));container = document.createElement('div');diff --git a/packages/sheets-data-validation-ui/src/views/components/formula-input/ListFormulaInput.tsx b/packages/sheets-data-validation-ui/src/views/components/formula-input/ListFormulaInput.tsxindex 81940d878a..3d801e6dbd 100644--- a/packages/sheets-data-validation-ui/src/views/components/formula-input/ListFormulaInput.tsx+++ b/packages/sheets-data-validation-ui/src/views/components/formula-input/ListFormulaInput.tsx@@ -18,7 +18,7 @@ import type { ListValidator } from '@univerjs/sheets-data-validation';import type { IFormulaEditorRef } from '@univerjs/sheets-formula-ui';import type { LocaleKey } from '../../../locale/types';import type { IFormulaInputProps } from './interface';-import { awaitTime, DataValidationType, generateRandomId, isFormulaString, LocaleService } from '@univerjs/core';+import { DataValidationType, generateRandomId, isFormulaString, LocaleService } from '@univerjs/core';import { DataValidationModel, DataValidatorRegistryService } from '@univerjs/data-validation';import { borderClassName, clsx, DraggableList, Dropdown, FormLayout, Input, Radio, RadioGroup } from '@univerjs/design';import { DeleteIcon, GripVerticalIcon, IncreaseIcon, MoreDownIcon } from '@univerjs/icons';@@ -189,22 +189,29 @@ export function ListFormulaInput(props: IFormulaInputProps) {const onChange = useEvent(_onChange);useEffect(() => {- (async () => {- await awaitTime(100);-+ let cancelled = false;+ const timer = setTimeout(() => {const rule = dataValidationModel.getRuleById(unitId, subUnitId, ruleId);const formula1 = rule?.formula1;if (isFormulaString(formula1) && listValidator && rule) {- const res = await listValidator.getListAsync(rule, unitId, subUnitId);- setRefOptions(res);+ listValidator.getListAsync(rule, unitId, subUnitId).then((options) => {+ if (!cancelled) {+ setRefOptions(options);+ }+ });}- })();+ }, 100);++ return () => {+ cancelled = true;+ clearTimeout(timer);+ };}, [dataValidationModel, ruleChange, listValidator, ruleId, subUnitId, unitId]);useEffect(() => {if (isFormulaString(formula1) && formula1 !== formulaStrCopy) {setFormulaStr(formula1);- setFormulaStrCopy(formulaStrCopy);+ setFormulaStrCopy(formula1);}}, [formulaStrCopy, formula1]);diff --git a/packages/sheets-drawing-ui/src/embed/floating-host/register-sheets-drawing-floating-host.ts b/packages/sheets-drawing-ui/src/embed/floating-host/register-sheets-drawing-floating-host.tsindex 1961766933..5ca4e26cbf 100644--- a/packages/sheets-drawing-ui/src/embed/floating-host/register-sheets-drawing-floating-host.ts+++ b/packages/sheets-drawing-ui/src/embed/floating-host/register-sheets-drawing-floating-host.ts@@ -45,7 +45,7 @@ export function touchSheetsDrawingFloatingHostCapabilityWhenReady(injector: Injereturn;}- void lifecycleService.onStage(LifecycleStages.Ready).then(() => {+ lifecycleService.onStage(LifecycleStages.Ready).then(() => {touchSheetsDrawingFloatingHostCapability(injector);});}diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsxindex 020958d7ff..3e286ab7fa 100644--- a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx@@ -38,24 +38,14 @@ export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {const { drawings } = props;- const drawingParam = drawings[0] as ISheetDrawing;-- if (drawingParam == null) {- return;- }-- const { unitId } = drawingParam;-- const renderObject = renderManagerService.getRenderById(unitId);+ const drawingParam = drawings[0] as ISheetDrawing | undefined;+ const renderObject = drawingParam ? renderManagerService.getRenderById(drawingParam.unitId) : undefined;const scene = renderObject?.scene;- if (scene == null) {- return;- }- const transformer = scene.getTransformerByCreate();+ const transformer = scene?.getTransformerByCreate();const [anchorShow, setAnchorShow] = useState(true);- const type = drawingParam.anchorType ?? SheetDrawingAnchorType.Position;+ const type = drawingParam?.anchorType ?? SheetDrawingAnchorType.Position;const [value, setValue] = useState(type);function getUpdateParams(objects: Map<string, BaseObject>, drawingManagerService: IDrawingManagerService): Nullable<ISheetDrawing>[] {@@ -87,6 +77,10 @@ export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {}useEffect(() => {+ if (!transformer) {+ return;+ }+const onClearControlObserver = transformer.clearControl$.subscribe((changeSelf) => {if (changeSelf === true) {setAnchorShow(false);@@ -110,7 +104,11 @@ export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {onChangeStartObserver.unsubscribe();onClearControlObserver.unsubscribe();};- }, []);+ }, [drawingManagerService, transformer]);++ if (!drawingParam || !transformer) {+ return null;+ }function handleChange(value: string | number | boolean) {setValue((value as SheetDrawingAnchorType));diff --git a/packages/sheets-filter-ui/src/views/components/SheetsFilterSyncSwitch.tsx b/packages/sheets-filter-ui/src/views/components/SheetsFilterSyncSwitch.tsxindex c5b9605f4e..cc84a04eba 100644--- a/packages/sheets-filter-ui/src/views/components/SheetsFilterSyncSwitch.tsx+++ b/packages/sheets-filter-ui/src/views/components/SheetsFilterSyncSwitch.tsx@@ -24,12 +24,12 @@ import { IMessageService, useDependency, useObservable } from '@univerjs/ui';export function FilterSyncSwitch() {const sheetsFilterSyncController = useDependency(SheetsFilterSyncController);const visible = useObservable(sheetsFilterSyncController.visible$, undefined, true);- if (!visible) return null;-const localeService = useDependency(LocaleService);const messageService = useDependency(IMessageService);const enabled = useObservable(sheetsFilterSyncController.enabled$, undefined, true);+ if (!visible) return null;+return (<divclassName={`diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex 0ecb81ab66..dc81582459 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -198,7 +198,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFconst [isFocus, setIsFocus] = useState(_isFocus);const formulaEditorContainerRef = useRef<HTMLDivElement>(null);const editorId = useMemo(() => propEditorId ?? createInternalEditorID(`${EMBEDDING_FORMULA_EDITOR}-${generateRandomId(4)}`), []);- const isError = useMemo(() => errorText !== undefined, [errorText]);+ const isError = errorText !== undefined;const univerInstanceService = useDependency(IUniverInstanceService);const document = univerInstanceService.getUnit<DocumentDataModel>(editorId);useObservable(document?.change$);@@ -216,8 +216,8 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFconst currentDoc$ = useMemo(() => univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC), [univerInstanceService]);const currentDoc = useObservable(currentDoc$);const docFocusing = currentDoc?.getUnitId() === editorId;- const refSelections = useRef([] as IRefSelection[]);- const getRefSelections = useEvent(() => refSelections.current);+ const refSelectionsRef = useRef([] as IRefSelection[]);+ const getRefSelections = useEvent(() => refSelectionsRef.current);const getRefSelectionCount = useEvent(() => getRefSelections().length);const selectingMode = isSelecting;@@ -270,7 +270,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFnewSelections,formulaStr);- refSelections.current = ranges;+ refSelectionsRef.current = ranges;if (isEnd) {const currentDocSelections = newSelections ?? editor?.getSelectionRanges();diff --git a/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx b/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsxindex b188c82022..a4e7af343c 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx@@ -43,7 +43,7 @@ function SearchFunctionFactory(props: ISearchFunctionProps, ref: any) {const shortcutService = useDependency(IShortcutService);const commandService = useDependency(ICommandService);const { searchList, searchText, handlerFormulaReplace, reset: resetFormulaSearch } = useFormulaSearch(isFocus, sequenceNodes, editor);- const visible = useMemo(() => !!searchList.length, [searchList]);+ const visible = searchList.length > 0;const ulRef = useRef<HTMLUListElement>(undefined);const [active, setActive] = useState(0);const isEnableMouseEnterOrOut = useRef(false);diff --git a/packages/sheets-formula-ui/src/views/more-functions/input-params/InputParams.tsx b/packages/sheets-formula-ui/src/views/more-functions/input-params/InputParams.tsxindex c99eba4512..0ed9904754 100644--- a/packages/sheets-formula-ui/src/views/more-functions/input-params/InputParams.tsx+++ b/packages/sheets-formula-ui/src/views/more-functions/input-params/InputParams.tsx@@ -29,6 +29,12 @@ export function InputParams(props: IInputParamsProps) {const { functionInfo, onChange } = props;if (!functionInfo) return null;+ return <InputParamsInner functionInfo={functionInfo} onChange={onChange} />;+}++function InputParamsInner(props: IInputParamsProps & { functionInfo: IFunctionInfo }) {+ const { functionInfo, onChange } = props;+const [params, setParams] = useState<string[]>([]);const [functionParameter, setFunctionParameter] = useState<IFunctionParam[]>(functionInfo.functionParameter);const [activeIndex, setActiveIndex] = useState(-1);diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.tsindex 5e81973e6f..71e7ef76a6 100644--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts@@ -41,7 +41,6 @@ import {import {ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,- FormulaCalculationTriggerService,FormulaDataModel,FormulaExecutedStateType,FormulaExecuteStageType,@@ -98,7 +97,12 @@ export class TriggerCalculationController extends Disposable {private _calculateProgress(label: string): void {if (this._executionInProgressParams) {- const { totalFormulasToCalculate, completedFormulasCount, totalArrayFormulasToCalculate, completedArrayFormulasCount } = this._executionInProgressParams;+ const {+ totalFormulasToCalculate,+ completedFormulasCount,+ totalArrayFormulasToCalculate,+ completedArrayFormulasCount,+ } = this._executionInProgressParams;this._doneCalculationTaskCount = completedFormulasCount + completedArrayFormulasCount;this._totalCalculationTaskCount = totalFormulasToCalculate + totalArrayFormulasToCalculate;@@ -126,7 +130,6 @@ export class TriggerCalculationController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(FormulaCalculationTriggerService) formulaCalculationTriggerService: FormulaCalculationTriggerService,@ILogService private readonly _logService: ILogService,@IConfigService private readonly _configService: IConfigService,@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,@@ -135,8 +138,6 @@ export class TriggerCalculationController extends Disposable {) {super();- void formulaCalculationTriggerService;-this._commandExecutedListener();this._initialExecuteFormulaProcessListener();diff --git a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.tsindex 4a9ee37a65..d4751a126c 100644--- a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts+++ b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts@@ -158,8 +158,8 @@ describe('sheets-formula facade mixins', () => {resolve();});- void commandService.executeCommand(SetFormulaCalculationResultMutation.id, resultPayload);- void commandService.executeCommand(+ commandService.executeCommand(SetFormulaCalculationResultMutation.id, resultPayload);+ commandService.executeCommand(SetRangeValuesMutation.id,{unitId: 'test',@@ -200,7 +200,7 @@ describe('sheets-formula facade mixins', () => {resolve();});- void commandService.executeCommand(+ commandService.executeCommand(SetRangeValuesMutation.id,{unitId: 'unit1',@@ -211,7 +211,7 @@ describe('sheets-formula facade mixins', () => {applyFormulaCalculationResult: true,});- void commandService.executeCommand(SetFormulaCalculationResultMutation.id, resultPayload);+ commandService.executeCommand(SetFormulaCalculationResultMutation.id, resultPayload);});});@@ -324,7 +324,7 @@ describe('sheets-formula facade mixins', () => {const formula = univerAPI.getFormula();const waitForResult = formula.onCalculationResultApplied();let resolved = false;- void waitForResult.then(() => {+ waitForResult.then(() => {resolved = true;});diff --git a/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts b/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.tsindex 0eb084fa8b..c35ce366ad 100644--- a/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts+++ b/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts@@ -38,7 +38,7 @@ describe('FormulaCalculationSessionService', () => {service.initialize();const waitForApplied = service.waitForLatestApplied();let resolved = false;- void waitForApplied.then(() => {+ waitForApplied.then(() => {resolved = true;});@@ -120,7 +120,7 @@ describe('FormulaCalculationSessionService', () => {const waitForApplied = service.waitForLatestApplied();let resolved = false;- void waitForApplied.then(() => {+ waitForApplied.then(() => {resolved = true;});@@ -244,7 +244,7 @@ describe('FormulaCalculationSessionService', () => {const service = createService();const waitForApplied = service.waitForLatestApplied();let resolved = false;- void waitForApplied.then(() => {+ waitForApplied.then(() => {resolved = true;});@@ -270,7 +270,7 @@ describe('FormulaCalculationSessionService', () => {const waitForApplied = service.waitForLatestApplied();let settled = false;- void waitForApplied.then(() => {+ waitForApplied.then(() => {settled = true;});diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsxindex 0290d00320..ad6a9d314e 100644--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx@@ -321,6 +321,21 @@ export const CellLinkEdit = () => {...sidePanelOptions,];+ const handleRangeChange = useEvent((rangeText: string) => {+ const newPayload = resolveRangePayload(rangeText, workbook?.getActiveSheet()?.getName() || '');+ if (!newPayload) {+ setPayload('');+ return;+ }++ setPayload(newPayload);++ if (getIsDisplaySyncedWithPayload() || !display) {+ setDisplay(newPayload);+ setDisplaySyncedWithPayload(true);+ }+ });+if (!workbook) {return;}@@ -348,21 +363,6 @@ export const CellLinkEdit = () => {return `#${type}=${payload}`;};- const handleRangeChange = useEvent((rangeText: string) => {- const newPayload = resolveRangePayload(rangeText, workbook.getActiveSheet()?.getName() || '');- if (!newPayload) {- setPayload('');- return;- }-- setPayload(newPayload);-- if (newPayload && (getIsDisplaySyncedWithPayload() || !display)) {- setDisplay(newPayload);- setDisplaySyncedWithPayload(true);- }- });-const handleSubmit = async () => {if ((showLabel && isBlankInput(display)) || !payload || (type === SheetHyperLinkType.URL && !isLegalLink(payload))) {setShowError(true);diff --git a/packages/sheets-note-ui/src/views/Note.tsx b/packages/sheets-note-ui/src/views/Note.tsxindex 578fdf7058..39c5e6f659 100644--- a/packages/sheets-note-ui/src/views/Note.tsx+++ b/packages/sheets-note-ui/src/views/Note.tsx@@ -34,20 +34,23 @@ type INotePopupLocation = ISheetLocationBase & {};export const SheetsNote = (props: { popup: IPopup<{ location: INotePopupLocation }> }) => {- const { popup } = props;+ const activePopup = props.popup.extraProps?.location;+ if (!activePopup) {+ console.error('Popup extraProps or location is undefined.');+ return null;+ }++ return <SheetsNoteContent activePopup={activePopup} />;+};++function SheetsNoteContent({ activePopup }: { activePopup: INotePopupLocation }) {const noteModel = useDependency(SheetsNoteModel);const localeService = useDependency(LocaleService);const renderManagerService = useDependency(IRenderManagerService);const notePopupService = useDependency(SheetsNotePopupService);const config = useConfigValue<IUniverSheetsNoteUIConfig>(SHEETS_NOTE_UI_PLUGIN_CONFIG_KEY);- const activePopup = popup.extraProps?.location;- if (!activePopup) {- console.error('Popup extraProps or location is undefined.');- return null; // Or handle this case appropriately- }-const textareaRef = useRef<HTMLTextAreaElement>(null);const initialWidthRef = useRef<number | null>(null);const currentRender = renderManagerService.getRenderById(activePopup.unitId)!;@@ -168,4 +171,4 @@ export const SheetsNote = (props: { popup: IPopup<{ location: INotePopupLocation}}/>);-};+}diff --git a/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx b/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsxindex c9b806fb62..f1cc0b9c12 100644--- a/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx+++ b/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx@@ -63,7 +63,7 @@ export function SheetNumfmtPanel(props: ISheetNumfmtPanelProps) {const [key, setKey] = useState(() => `${row}_${col}_${defaultPattern}`);const { mark, userHabitCurrency } = useCurrencyOptions(() => setKey(`${row}_${col}_${defaultPattern}_userCurrency`));- const BusinessComponent = useMemo(() => typeOptions.find((item) => item.label === type)?.component, [type]);+ const BusinessComponent = typeOptions.find((item) => item.label === type)?.component;function findDefaultType() {const list = [isGeneralPanel, isAccountingPanel, isCurrencyPanel, isDatePanel, isThousandthPercentilePanel];diff --git a/packages/sheets-numfmt-ui/src/views/components/CustomFormat.tsx b/packages/sheets-numfmt-ui/src/views/components/CustomFormat.tsxindex 1039bb3ebc..3344138db2 100644--- a/packages/sheets-numfmt-ui/src/views/components/CustomFormat.tsx+++ b/packages/sheets-numfmt-ui/src/views/components/CustomFormat.tsx@@ -47,20 +47,26 @@ export function CustomFormat(props: IBusinessComponentProps) {const [options, setOptions] = useState<(string | number)[]>([]);useEffect(() => {- localStorageService.getItem<string[]>(historyPatternKey).then((historyList) => {+ let cancelled = false;++ void localStorageService.getItem<string[]>(historyPatternKey).then((historyList) => {const list = [...CURRENCYFORMAT.map((item) => item.suffix('$')),...DATEFMTLISG.map((item) => item.suffix),...NUMBERFORMAT.map((item) => item.suffix),+ ...(historyList ?? []),];- list.push(...(historyList || []));- userHabitController.addHabit(key, []).finally(() => {- userHabitController.getHabit(key, list).then((list) => {- setOptions([...new Set(list)]);- });- });+ return userHabitController.addHabit(key, []).then(() => userHabitController.getHabit(key, list));+ }).then((list) => {+ if (!cancelled) {+ setOptions([...new Set(list)]);+ }});- }, []);++ return () => {+ cancelled = true;+ };+ }, [localStorageService, userHabitController]);const handleClick = (p: string) => {setPattern(p);diff --git a/packages/sheets-numfmt-ui/src/views/components/ThousandthPercentile.tsx b/packages/sheets-numfmt-ui/src/views/components/ThousandthPercentile.tsxindex 90945f0341..e7c28aacbd 100644--- a/packages/sheets-numfmt-ui/src/views/components/ThousandthPercentile.tsx+++ b/packages/sheets-numfmt-ui/src/views/components/ThousandthPercentile.tsx@@ -44,7 +44,7 @@ export function ThousandthPercentilePanel(props: IBusinessComponentProps) {const pattern = useMemo(() => setPatternDecimal(suffix, Number(decimal || 0)), [suffix, decimal]);- const isInputDisable = useMemo(() => !isPatternHasDecimal(suffix), [suffix]);+ const isInputDisable = !isPatternHasDecimal(suffix);const handleDecimalChange = (decimal: number | null) => {setDecimal(decimal || 0);diff --git a/packages/sheets-table-ui/src/views/components/SheetTableFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/SheetTableFilterPanel.tsxindex d7a855e62d..4971c92ee8 100644--- a/packages/sheets-table-ui/src/views/components/SheetTableFilterPanel.tsx+++ b/packages/sheets-table-ui/src/views/components/SheetTableFilterPanel.tsx@@ -74,7 +74,7 @@ export function SheetTableFilterPanel() {const { data } = tableUiService.getTableFilterItems(unitId, subUnitId, tableId, columnIndex);const checkedItems = tableUiService.getTableFilterCheckedItems(unitId, tableId, columnIndex);- const [checkedItemSet, setCheckedItemSet] = useState<Set<string>>(new Set<string>(checkedItems));+ const [checkedItemSet, setCheckedItemSet] = useState<Set<string>>(() => new Set<string>(checkedItems));const [filterBy, setFilterBy] = useState(currentFilterBy || FilterByEnum.Items);const [conditionInfo, setConditionInfo] = useState<IConditionInfo>(() => {diff --git a/packages/sheets-table-ui/src/views/components/SheetTableItemsFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/SheetTableItemsFilterPanel.tsxindex 62b473ea27..3698e60638 100644--- a/packages/sheets-table-ui/src/views/components/SheetTableItemsFilterPanel.tsx+++ b/packages/sheets-table-ui/src/views/components/SheetTableItemsFilterPanel.tsx@@ -51,7 +51,7 @@ export function SheetTableItemsFilterPanel(props: ISheetTableItemsFilterPanelPro// const allChecked = tableFilter === undefined ? true : checkedItemSet.size === itemsCountMap.size;const [allChecked, setAllChecked] = useState<boolean>(tableFilter === undefined ? true : checkedItemSet.size === itemsCountMap.size);- const [checkedCount, setCheckedCount] = useState<number>(allChecked ? allItemsCount : getCheckedItemCount(itemsCountMap, checkedItemSet));+ const [checkedCount, setCheckedCount] = useState<number>(() => allChecked ? allItemsCount : getCheckedItemCount(itemsCountMap, checkedItemSet));const indeterminate = !allChecked && checkedItemSet.size > 0;const [searchText, setSearchText] = useState('');diff --git a/packages/sheets-table-ui/src/views/components/SheetTableThemePanel.tsx b/packages/sheets-table-ui/src/views/components/SheetTableThemePanel.tsxindex d88dab95c0..49925f3cbb 100644--- a/packages/sheets-table-ui/src/views/components/SheetTableThemePanel.tsx+++ b/packages/sheets-table-ui/src/views/components/SheetTableThemePanel.tsx@@ -68,7 +68,7 @@ export const SheetTableThemePanel = (props: ISheetTableThemePanelProps) => {const errorService = useDependency(ErrorService);- const [, setRefresh] = useState(Math.random());+ const [, setRefresh] = useState(Math.random);const themeConfig = useObservable(tableManager.tableThemeChanged$, {theme: table?.getTableStyleId(),diff --git a/packages/sheets-ui/src/views/CellPopup.tsx b/packages/sheets-ui/src/views/CellPopup.tsxindex aac1efd084..2f4bebcea5 100644--- a/packages/sheets-ui/src/views/CellPopup.tsx+++ b/packages/sheets-ui/src/views/CellPopup.tsx@@ -15,15 +15,15 @@*/import type { ISheetLocationBase } from '@univerjs/sheets';-import type { IPopup } from '@univerjs/ui';+import type { IPopupWithExtraProps } from '@univerjs/ui';import { ComponentManager, useDependency, useObservable } from '@univerjs/ui';import { useMemo } from 'react';import { filter } from 'rxjs';import { CellPopupManagerService } from '../services/cell-popup-manager.service';-export const CellPopup = (props: { popup: IPopup<ISheetLocationBase & { direction: 'horizontal' | 'vertical' }> }) => {+export const CellPopup = (props: { popup: IPopupWithExtraProps<ISheetLocationBase & { direction: 'horizontal' | 'vertical' }> }) => {const { popup } = props;- const location = popup.extraProps!;+ const location = popup.extraProps;const { row, col, direction, unitId, subUnitId } = location;const cellPopupManagerService = useDependency(CellPopupManagerService);useObservable(diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsxindex 07d172e744..f5e1c3b1dc 100644--- a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx@@ -38,6 +38,13 @@ export interface IDefinedNameInputProps extends Omit<IDefinedNamesServiceParam,}export const DefinedNameInput = (props: IDefinedNameInputProps) => {+ const univerInstanceService = useDependency(IUniverInstanceService);+ const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);++ return workbook ? <DefinedNameInputContent {...props} /> : null;+};++function DefinedNameInputContent(props: IDefinedNameInputProps) {const {inputId,state = false,@@ -62,13 +69,8 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {const RangeSelector: ComponentType<IRangeSelectorProps> = useMemo(() => componentManager.get(RANGE_SELECTOR_COMPONENT_KEY), []) as any;const FormulaEditor = useMemo(() => componentManager.get(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY), []);- if (workbook == null) {- return;- }-- const unitId = useMemo(() => workbook.getUnitId(), []);-- const subUnitId = useMemo(() => workbook.getActiveSheet().getSheetId(), []);+ const unitId = workbook.getUnitId();+ const subUnitId = workbook.getActiveSheet().getSheetId();const [nameValue, setNameValue] = useState(name);@@ -295,4 +297,4 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {</div></div>);-};+}diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsxindex 6dcbf3dab1..1daaf4713f 100644--- a/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx@@ -45,7 +45,7 @@ export function DefinedNameOverlay({ search, isInputEvent }: { search: string; ireturn [];};- const [definedNames, setDefinedNames] = useState<IDefinedNamesServiceParam[]>(getDefinedNameMap());+ const [definedNames, setDefinedNames] = useState<IDefinedNamesServiceParam[]>(() => getDefinedNameMap());useEffect(() => {const definedNamesSubscription = definedNamesService.update$.subscribe(() => {@@ -59,10 +59,14 @@ export function DefinedNameOverlay({ search, isInputEvent }: { search: string; i// When closing the panel, clear the react cacheuseEffect(() => {+ let timer: ReturnType<typeof setTimeout> | undefined;const d = sidebarService.sidebarOptions$.subscribe((info) => {if (info.id === DEFINED_NAME_CONTAINER) {if (!info.visible) {- setTimeout(() => {+ if (timer !== undefined) {+ clearTimeout(timer);+ }+ timer = setTimeout(() => {sidebarService.sidebarOptions$.next({ visible: false });});}@@ -70,6 +74,9 @@ export function DefinedNameOverlay({ search, isInputEvent }: { search: string; i});return () => {d.unsubscribe();+ if (timer !== undefined) {+ clearTimeout(timer);+ }};}, []);diff --git a/packages/sheets-ui/src/views/dropdown/CascaderDropdown.tsx b/packages/sheets-ui/src/views/dropdown/CascaderDropdown.tsxindex 7c699f54e2..483e23e482 100644--- a/packages/sheets-ui/src/views/dropdown/CascaderDropdown.tsx+++ b/packages/sheets-ui/src/views/dropdown/CascaderDropdown.tsx@@ -15,7 +15,7 @@*/import type { ICascaderOption } from '@univerjs/design';-import type { IPopup } from '@univerjs/ui';+import type { IPopupWithExtraProps } from '@univerjs/ui';import type { IBaseDropdownProps } from './type';import { CascaderList } from '@univerjs/design';import { useState } from 'react';@@ -26,10 +26,12 @@ export interface ICascaderDropdownProps {onChange: (value: string[]) => void;}-export function CascaderDropdown(props: { popup: IPopup<ICascaderDropdownProps & IBaseDropdownProps> }) {+export function CascaderDropdown(props: {+ popup: IPopupWithExtraProps<ICascaderDropdownProps & IBaseDropdownProps>;+}) {const { popup } = props;const { extraProps } = popup;- const { options, defaultValue, onChange } = extraProps!;+ const { options, defaultValue, onChange } = extraProps;const [localValue, setLocalValue] = useState(defaultValue ?? []);return (diff --git a/packages/sheets-ui/src/views/dropdown/ColorDropdown.tsx b/packages/sheets-ui/src/views/dropdown/ColorDropdown.tsxindex db32ab1b9a..e033341c76 100644--- a/packages/sheets-ui/src/views/dropdown/ColorDropdown.tsx+++ b/packages/sheets-ui/src/views/dropdown/ColorDropdown.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IPopup } from '@univerjs/ui';+import type { IPopupWithExtraProps } from '@univerjs/ui';import type { IBaseDropdownProps } from './type';import { ColorPicker } from '@univerjs/design';@@ -23,10 +23,12 @@ export interface IColorDropdownProps {onChange?: (value: string) => void;}-export function ColorDropdown(props: { popup: IPopup<IColorDropdownProps & IBaseDropdownProps> }) {+export function ColorDropdown(props: {+ popup: IPopupWithExtraProps<IColorDropdownProps & IBaseDropdownProps>;+}) {const { popup } = props;const { extraProps } = popup;- const { defaultValue, onChange } = extraProps!;+ const { defaultValue, onChange } = extraProps;return (<ColorPickerdiff --git a/packages/sheets-ui/src/views/dropdown/DateDropdown.tsx b/packages/sheets-ui/src/views/dropdown/DateDropdown.tsxindex 062baea797..d81f52dde4 100644--- a/packages/sheets-ui/src/views/dropdown/DateDropdown.tsx+++ b/packages/sheets-ui/src/views/dropdown/DateDropdown.tsx@@ -15,7 +15,7 @@*/import type { DateKit } from '@univerjs/core';-import type { IPopup } from '@univerjs/ui';+import type { IPopupWithExtraProps } from '@univerjs/ui';import type { LocaleKey } from '../../locale/types';import type { IBaseDropdownProps } from './type';import { dateKit, LocaleService } from '@univerjs/core';@@ -30,10 +30,12 @@ export interface IDateDropdownProps {showTime?: boolean;}-export function DateDropdown(props: { popup: IPopup<IDateDropdownProps & IBaseDropdownProps> }) {+export function DateDropdown(props: {+ popup: IPopupWithExtraProps<IDateDropdownProps & IBaseDropdownProps>;+}) {const { popup } = props;const { extraProps } = popup;- const { hideFn, patternType, defaultValue, onChange, showTime } = extraProps!;+ const { hideFn, patternType, defaultValue, onChange, showTime } = extraProps;const [localDate, setLocalDate] = useState<DateKit | undefined>(defaultValue);const defaultDate = useMemo(() => patternType !== 'time' ? dateKit() : dateKit('1900-01-01 00:00:00'), []);const date = localDate && localDate.isValid() ? localDate : defaultDate;@@ -76,7 +78,12 @@ export function DateDropdown(props: { popup: IPopup<IDateDropdownProps & IBaseDr<footerclassName={clsx('univer-mt-2 univer-flex univer-justify-end univer-pt-2', borderTopClassName)}>- <Button size="small" variant="primary" onClick={handleSave} disabled={!date || !date.isValid()}>+ <Button+ size="small"+ variant="primary"+ onClick={handleSave}+ disabled={!date || !date.isValid()}+ >{localeService.t<LocaleKey>('sheets-ui.data-validation.alert.ok')}</Button></footer>diff --git a/packages/sheets-ui/src/views/dropdown/ListDropDown.tsx b/packages/sheets-ui/src/views/dropdown/ListDropDown.tsxindex adc7698641..bd4f944b6f 100644--- a/packages/sheets-ui/src/views/dropdown/ListDropDown.tsx+++ b/packages/sheets-ui/src/views/dropdown/ListDropDown.tsx@@ -15,7 +15,7 @@*/import type { ISheetLocation } from '@univerjs/sheets';-import type { IPopup } from '@univerjs/ui';+import type { IPopupWithExtraProps } from '@univerjs/ui';import type { CSSProperties } from 'react';import type { LocaleKey } from '../../locale/types';import type { IBaseDropdownProps } from './type';@@ -231,14 +231,14 @@ export interface IListDropdownProps {showSearch?: boolean;}-export function ListDropDown(props: { popup: IPopup<IListDropdownProps & IBaseDropdownProps> }) {+export function ListDropDown(props: { popup: IPopupWithExtraProps<IListDropdownProps & IBaseDropdownProps> }) {const { popup: { extraProps, anchorRect } } = props;- const { location, hideFn, onChange, onEdit, options, defaultValue, multiple, showSearch, showEdit } = extraProps!;+ const { location, hideFn, onChange, onEdit, options, defaultValue, multiple, showSearch, showEdit } = extraProps;const { worksheet } = location;- if (!worksheet) return null;-const [localValue, setLocalValue] = useState(defaultValue);++ if (!worksheet) return null;const cellWidth = (anchorRect?.right ?? 0) - (anchorRect?.left ?? 0);return (diff --git a/packages/sheets-ui/src/views/dropdown/__tests__/ListDropDown.spec.tsx b/packages/sheets-ui/src/views/dropdown/__tests__/ListDropDown.spec.tsxindex 2dc81c44de..e38dd48285 100644--- a/packages/sheets-ui/src/views/dropdown/__tests__/ListDropDown.spec.tsx+++ b/packages/sheets-ui/src/views/dropdown/__tests__/ListDropDown.spec.tsx@@ -15,7 +15,7 @@*/import type { ISheetLocation } from '@univerjs/sheets';-import type { IPopup } from '@univerjs/ui';+import type { IPopupWithExtraProps } from '@univerjs/ui';import type { ReactElement } from 'react';import type { IListDropdownProps } from '../ListDropDown';import type { IBaseDropdownProps } from '../type';@@ -102,7 +102,7 @@ function createLocation(): ISheetLocation {} as ISheetLocation;}-function createPopup(extraProps: Partial<IListPopupProps> = {}): IPopup<IListPopupProps> {+function createPopup(extraProps: Partial<IListPopupProps> = {}): IPopupWithExtraProps<IListPopupProps> {return {componentKey: ListDropDown.componentKey,unitId: UNIT_ID,@@ -120,7 +120,7 @@ function createPopup(extraProps: Partial<IListPopupProps> = {}): IPopup<IListPop],...extraProps,},- } as IPopup<IListPopupProps>;+ } as IPopupWithExtraProps<IListPopupProps>;}function renderWithDependencies(element: ReactElement) {diff --git a/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx b/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsxindex c1456152da..802ecc55e8 100644--- a/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx+++ b/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx@@ -57,14 +57,13 @@ export const SheetPermissionDialog = () => {const permissionService = useDependency(IPermissionService);const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const worksheet = workbook.getActiveSheet();- if (!worksheet) {- throw new Error('No active sheet found');- }+ const unitId = workbook.getUnitId();+ const subUnitId = worksheet.getSheetId();const [collaborators, setCollaborators] = useState<ICollaborator[]>([]);const commandService = useDependency(ICommandService);const [loading, setLoading] = useState(() => {- const pointRule = worksheetProtectionPointRuleModel.getRule(workbook.getUnitId(), worksheet.getSheetId());+ const pointRule = worksheetProtectionPointRuleModel.getRule(unitId, subUnitId);return !!pointRule;});@@ -79,47 +78,62 @@ export const SheetPermissionDialog = () => {});useEffect(() => {- const getUserList = async () => {- const unitId = workbook.getUnitId();- const collaborators = await authzIoService.listCollaborators({- objectID: unitId,- unitID: unitId,- });- setCollaborators(collaborators);+ let cancelled = false;++ void authzIoService.listCollaborators({+ objectID: unitId,+ unitID: unitId,+ }).then((collaborators) => {+ if (!cancelled) {+ setCollaborators(collaborators);+ }+ });++ return () => {+ cancelled = true;};- getUserList();- }, []);+ }, [authzIoService, unitId]);useEffect(() => {- const getPermissionPoints = async () => {- const unitId = workbook.getUnitId();- const worksheetPointRule = worksheetProtectionPointRuleModel.getRule(unitId, worksheet.getSheetId());- if (!worksheetPointRule) {- return;- };+ let cancelled = false;+ let loadingTimer: ReturnType<typeof setTimeout> | undefined;++ const worksheetPointRule = worksheetProtectionPointRuleModel.getRule(unitId, subUnitId);+ if (worksheetPointRule) {setLoading(true);- const result = await authzIoService.list({- unitID: workbook.getUnitId(),++ void authzIoService.list({+ unitID: unitId,objectIDs: [worksheetPointRule.permissionId],actions: defaultWorksheetUnitActionList,- });- const actions = result[0].strategies.reduce((p, c) => {- if (subUnitPermissionTypeMap[c.action]) {- p[c.action] = {- text: localeService.t(`sheets-ui.permission.panel.${subUnitPermissionTypeMap[c.action]}`),- allowed: c.role !== UnitRole.Owner,- };+ }).then((result) => {+ if (cancelled) {+ return;}- return p;- }, {} as IPermissionMap);- setPermissionMap(actions);- setTimeout(() => {- setLoading(false);- }, 100);- };- getPermissionPoints();- }, []);+ const actions = result[0].strategies.reduce((p, c) => {+ if (subUnitPermissionTypeMap[c.action]) {+ p[c.action] = {+ text: localeService.t(`sheets-ui.permission.panel.${subUnitPermissionTypeMap[c.action]}`),+ allowed: c.role !== UnitRole.Owner,+ };+ }+ return p;+ }, {} as IPermissionMap);+ setPermissionMap(actions);+ loadingTimer = setTimeout(() => {+ setLoading(false);+ }, 100);+ });+ }++ return () => {+ cancelled = true;+ if (loadingTimer !== undefined) {+ clearTimeout(loadingTimer);+ }+ };+ }, [authzIoService, localeService, subUnitId, unitId, worksheetProtectionPointRuleModel]);const handleChangeActionPermission = async () => {const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;diff --git a/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx b/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsxindex 8b62f2bf5d..0000390a49 100644--- a/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx+++ b/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx@@ -53,6 +53,13 @@ import { panelListEmptyBase64 } from './panel-list/constant';type IRuleItem = IRangeProtectionRule | IWorksheetProtectionRule;export function SheetPermissionPanelList() {+ const univerInstanceService = useDependency(IUniverInstanceService);+ const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);++ return workbook ? <SheetPermissionPanelListContent /> : null;+}++function SheetPermissionPanelListContent() {const [isCurrentSheet, setIsCurrentSheet] = useState(true);const [forceUpdateFlag, setForceUpdateFlag] = useState(false);const [currentRuleRanges, setCurrentRuleRanges] = useState<IRange[]>([]);@@ -72,9 +79,7 @@ export function SheetPermissionPanelList() {const sheetRuleRefresh = useObservable(worksheetProtectionModel.ruleRefresh$, '');const rangeRuleRefresh = useObservable(rangeProtectionRuleModel.ruleRefresh$, '');- const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);-- if (!workbook) return null;+ const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const unitId = workbook.getUnitId();@@ -118,44 +123,60 @@ export function SheetPermissionPanelList() {});return isCurrentSheet ? subUnitRuleList : allPermissionRule;- }, []);+ }, [authzIoService, rangeProtectionRuleModel, workbook, worksheetProtectionModel]);const [ruleList, setRuleList] = useState<IPermissionPoint[]>([]);useEffect(() => {+ let active = true;const subscription = merge(rangeProtectionRuleModel.ruleChange$,worksheetProtectionModel.ruleChange$- ).subscribe(async () => {- const ruleList = await getRuleList(isCurrentSheet);- setRuleList(ruleList);+ ).subscribe(() => {+ void getRuleList(isCurrentSheet).then((ruleList) => {+ if (active) {+ setRuleList(ruleList);+ }+ });});return () => {+ active = false;subscription.unsubscribe();};- }, [isCurrentSheet]);+ }, [getRuleList, isCurrentSheet, rangeProtectionRuleModel.ruleChange$, worksheetProtectionModel.ruleChange$]);useEffect(() => {+ let active = true;const subscribe = workbook.activeSheet$.pipe(distinctUntilChanged((prevSheet, currSheet) => prevSheet?.getSheetId() === currSheet?.getSheetId())- ).subscribe(async () => {- const ruleList = await getRuleList(isCurrentSheet);- setRuleList(ruleList);+ ).subscribe(() => {+ void getRuleList(isCurrentSheet).then((ruleList) => {+ if (active) {+ setRuleList(ruleList);+ }+ });});return () => {+ active = false;subscribe.unsubscribe();};- }, [isCurrentSheet]);+ }, [getRuleList, isCurrentSheet, workbook.activeSheet$]);useEffect(() => {- const getRuleListByRefresh = async () => {- if (sheetRuleRefresh || rangeRuleRefresh) {- const ruleList = await getRuleList(true);- setRuleList(ruleList);- };+ let cancelled = false;++ if (sheetRuleRefresh || rangeRuleRefresh) {+ void getRuleList(true).then((ruleList) => {+ if (!cancelled) {+ setRuleList(ruleList);+ }+ });+ }++ return () => {+ cancelled = true;};- getRuleListByRefresh();- }, [sheetRuleRefresh, rangeRuleRefresh]);+ }, [getRuleList, sheetRuleRefresh, rangeRuleRefresh]);function handleDelete(rule: IRuleItem) {const { unitId, subUnitId, unitType } = rule;@@ -176,7 +197,7 @@ export function SheetPermissionPanelList() {useEffect(() => {sheetPermissionUserManagerService.reset();- }, []);+ }, [sheetPermissionUserManagerService]);useHighlightRange(currentRuleRanges);diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsxindex 6fb71b9d49..6c12e8d76e 100644--- a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx@@ -27,9 +27,12 @@ import {import { Avatar, borderClassName, clsx, FormLayout, Radio, RadioGroup, Select } from '@univerjs/design';import { UnitRole } from '@univerjs/protocol';import { EditStateEnum, ViewStateEnum } from '@univerjs/sheets';-import { IDialogService, useDependency, useObservable } from '@univerjs/ui';+import { IDialogService, useDependency, useEvent, useObservable } from '@univerjs/ui';import { useEffect } from 'react';-import { UNIVER_SHEET_PERMISSION_USER_DIALOG, UNIVER_SHEET_PERMISSION_USER_DIALOG_ID } from '../../../consts/permission';+import {+ UNIVER_SHEET_PERMISSION_USER_DIALOG,+ UNIVER_SHEET_PERMISSION_USER_DIALOG_ID,+} from '../../../consts/permission';import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';import { UserEmptyBase64 } from '../user-dialog/constant';@@ -49,14 +52,15 @@ export const PermissionDetailUserPart = (props: IPermissionDetailUserPartProps)const sheetPermissionUserManagerService = useDependency(SheetPermissionUserManagerService);const userManagerService = useDependency(UserManagerService);const univerInstanceService = useDependency(IUniverInstanceService);- const selectUserList = useObservable(sheetPermissionUserManagerService.selectUserList$, sheetPermissionUserManagerService.selectUserList);+ const selectUserList = useObservable(+ sheetPermissionUserManagerService.selectUserList$,+ sheetPermissionUserManagerService.selectUserList+ );const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);const worksheet = workbook?.getActiveSheet();- if (!workbook || !worksheet) {- return null;- }- const unitId = workbook.getUnitId();+ const unitId = workbook?.getUnitId() ?? '';+ const handleEditStateChange = useEvent(onEditStateChange);const handleAddPerson = async () => {const userList = await authzIoService.listCollaborators({@@ -79,27 +83,43 @@ export const PermissionDetailUserPart = (props: IPermissionDetailUserPartProps)};useEffect(() => {- const getSelectUserList = async () => {- const collaborators = await authzIoService.listCollaborators({- objectID: permissionId!,+ let cancelled = false;++ if (permissionId && unitId) {+ void authzIoService.listCollaborators({+ objectID: permissionId,unitID: unitId,+ }).then((collaborators) => {+ if (cancelled) {+ return;+ }++ const editors: ICollaborator[] = collaborators.filter((user) => user.role === UnitRole.Editor);+ if (editors.length > 0) {+ handleEditStateChange(EditStateEnum.DesignedUserCanEdit);+ }+ sheetPermissionUserManagerService.setSelectUserList(editors);+ sheetPermissionUserManagerService.setOldCollaboratorList(editors);});- const selectUserList: ICollaborator[] = collaborators.filter((user) => {- return user.role === UnitRole.Editor;- });- if (selectUserList.length > 0) {- onEditStateChange(EditStateEnum.DesignedUserCanEdit);- }- sheetPermissionUserManagerService.setSelectUserList(selectUserList);- sheetPermissionUserManagerService.setOldCollaboratorList(selectUserList);- };- if (permissionId) {- getSelectUserList();} else {sheetPermissionUserManagerService.setSelectUserList([]);sheetPermissionUserManagerService.setOldCollaboratorList([]);}- }, []);++ return () => {+ cancelled = true;+ };+ }, [+ authzIoService,+ handleEditStateChange,+ permissionId,+ sheetPermissionUserManagerService,+ unitId,+ ]);++ if (!workbook || !worksheet) {+ return null;+ }return (<>diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsxindex fbb01f0072..f54386879c 100644--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx@@ -321,7 +321,7 @@ export function SheetBarTabs() {return;}- void commandService.executeCommand(SetWorksheetActiveOperation.id, {+ commandService.executeCommand(SetWorksheetActiveOperation.id, {subUnitId,unitId: workbookRef.current.getUnitId(),}).then((result) => {@@ -517,7 +517,7 @@ export function SheetBarTabs() {},onChangeTab: (_event: MouseEvent, subUnitId: string) => {// Do not use SetWorksheetActivateCommand, otherwise activation timing may be incorrect.- void commandService+ commandService.executeCommand(SetWorksheetActiveOperation.id, {subUnitId,unitId: workbook.getUnitId(),diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsxindex 5399fc7eff..02152afb49 100644--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx@@ -206,7 +206,7 @@ function RenderSheetEmbedTabHost(props: { workbook: Workbook; worksheet: Workshefunction useHasWorkbook(): boolean {const univerInstanceService = useDependency(IUniverInstanceService);const workbook = useObservable(() => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET), null, false, []);- return useMemo(() => !!workbook, [workbook]);+ return !!workbook;}function useActiveWorkbookIsEmbeddedRender(workbook: Workbook | null): boolean {diff --git a/packages/sheets-ui/src/views/status-bar/StatusBar.tsx b/packages/sheets-ui/src/views/status-bar/StatusBar.tsxindex 251fd59936..f699786853 100644--- a/packages/sheets-ui/src/views/status-bar/StatusBar.tsx+++ b/packages/sheets-ui/src/views/status-bar/StatusBar.tsx@@ -117,50 +117,36 @@ export const StatusBar = () => {};}, [isSingle]);- const useStatisticLayout = (+ const getStatisticLayout = (showList: IStatisticItem[],rowCountThreshold: number,CopyableStatisticItem: ComponentType<IStatisticItem>) => {if (!showStatistic) return null;- const renderContent = useMemo(() => {- if (showList.length > rowCountThreshold) {- const doubleLineList = showList.reduce<IStatisticItem[][]>((acc, _, index) => {- if (index % 2 === 0) {- acc.push(showList.slice(index, index + 2));- }- return acc;- }, []);-- return doubleLineList.map((item, index) => (- <div key={`stat-col-${index}`} className="univer-grid univer-h-full univer-items-center">- {item[0] && (- <CopyableStatisticItem- key={item[0].name}- {...item[0]}- />- )}- {item[1] && (- <CopyableStatisticItem- key={item[1].name}- {...item[1]}- />- )}- </div>- ));- }-- return showList.map((item) => (- <div key={item.name} className="univer-grid univer-h-full univer-items-center">- <CopyableStatisticItem {...item} />+ if (showList.length > rowCountThreshold) {+ const doubleLineList = showList.reduce<IStatisticItem[][]>((acc, _, index) => {+ if (index % 2 === 0) {+ acc.push(showList.slice(index, index + 2));+ }+ return acc;+ }, []);++ return doubleLineList.map((item, index) => (+ <div key={`stat-col-${index}`} className="univer-grid univer-h-full univer-items-center">+ {item[0] && <CopyableStatisticItem key={item[0].name} {...item[0]} />}+ {item[1] && <CopyableStatisticItem key={item[1].name} {...item[1]} />}</div>));- }, [showList, rowCountThreshold, CopyableStatisticItem]);+ }- return renderContent;+ return showList.map((item) => (+ <div key={item.name} className="univer-grid univer-h-full univer-items-center">+ <CopyableStatisticItem {...item} />+ </div>+ ));};- const renderContent = useStatisticLayout(showList, ROW_COUNT_THRESHOLD, CopyableStatisticItem);+ const renderContent = getStatisticLayout(showList, ROW_COUNT_THRESHOLD, CopyableStatisticItem);return (show && (diff --git a/packages/slides-ui/src/views/editor-container/EditorContainer.tsx b/packages/slides-ui/src/views/editor-container/EditorContainer.tsxindex 362cf0814d..3c0dea2f8e 100644--- a/packages/slides-ui/src/views/editor-container/EditorContainer.tsx+++ b/packages/slides-ui/src/views/editor-container/EditorContainer.tsx@@ -70,7 +70,7 @@ export function SlideEditorContainer() {};useEffect(() => {- slideEditorManagerService.state$.subscribe((param) => {+ const subscription = slideEditorManagerService.state$.subscribe((param) => {if (param == null) {return;}@@ -106,7 +106,9 @@ export function SlideEditorContainer() {slideEditorManagerService.setRect({ left, top, width, height });}});- }, []); // Empty dependency array means this effect runs once on mount and clean up on unmount++ return () => subscription.unsubscribe();+ }, [editorService, slideEditorManagerService]);useEffect(() => {if (!disableAutoFocus) {diff --git a/packages/slides-ui/src/views/image-popup-menu/ImagePopupMenu.tsx b/packages/slides-ui/src/views/image-popup-menu/ImagePopupMenu.tsxindex cb2dea689e..cfe7593b6a 100644--- a/packages/slides-ui/src/views/image-popup-menu/ImagePopupMenu.tsx+++ b/packages/slides-ui/src/views/image-popup-menu/ImagePopupMenu.tsx@@ -41,23 +41,21 @@ export interface IImagePopupMenuProps {export function SlideImagePopupMenu(props: IImagePopupMenuProps) {const menuItems = props.popup?.extraProps?.menuItems;+ const commandService = useDependency(ICommandService);+ const localeService = useDependency(LocaleService);+ const [visible, setVisible] = useState(false);+ const [isHovered, setIsHovered] = useState(false);if (!menuItems) {return null;}- const commandService = useDependency(ICommandService);- const localeService = useDependency(LocaleService);-- const [visible, setVisible] = useState(false);- const [isHovered, setHovered] = useState(false);-const handleMouseEnter = () => {- setHovered(true);+ setIsHovered(true);};const handleMouseLeave = () => {- setHovered(false);+ setIsHovered(false);};const onVisibleChange = (visible: boolean) => {diff --git a/packages/slides-ui/src/views/panels/FillPanel.tsx b/packages/slides-ui/src/views/panels/FillPanel.tsxindex c965efdcc8..9b5cd59c75 100644--- a/packages/slides-ui/src/views/panels/FillPanel.tsx+++ b/packages/slides-ui/src/views/panels/FillPanel.tsx@@ -43,16 +43,11 @@ export default function ArrangePanel(props: IProps) {const page = canvasView.getRenderUnitByPageId(pageId, unitId);const scene = page?.scene;- if (!scene) return null;+ const transformer = scene?.getTransformer();+ const object = transformer?.getSelectedObjectMap().values().next().value as Nullable<Rect>;+ const [color, setColor] = useState<string>(object?.fill?.toString() ?? '');- const transformer = scene.getTransformer();- if (!transformer) return null;-- const selectedObjects = transformer.getSelectedObjectMap();- const object = selectedObjects.values().next().value as Nullable<Rect>;- if (!object) return null;-- const [color, setColor] = useState<string>(object.fill?.toString() ?? '');+ if (!scene || !transformer || !object) return null;/***diff --git a/packages/slides-ui/src/views/panels/TransformPanel.tsx b/packages/slides-ui/src/views/panels/TransformPanel.tsxindex 70f22025d7..04797d9a5e 100644--- a/packages/slides-ui/src/views/panels/TransformPanel.tsx+++ b/packages/slides-ui/src/views/panels/TransformPanel.tsx@@ -38,14 +38,8 @@ export default function TransformPanel(props: IProps) {const page = canvasView.getRenderUnitByPageId(pageId, unitId);const scene = page?.scene;- if (!scene) return null;-- const transformer = scene.getTransformer();- if (!transformer) return null;-- const selectedObjects = transformer.getSelectedObjectMap();- const object = selectedObjects.values().next().value as Nullable<Rect | Image | RichText>;- if (!object) return null;+ const transformer = scene?.getTransformer();+ const object = transformer?.getSelectedObjectMap().values().next().value as Nullable<Rect | Image | RichText>;const {width: originWidth = 0,@@ -53,7 +47,7 @@ export default function TransformPanel(props: IProps) {left: originX = 0,top: originY = 0,angle: originRotation = 0,- } = object;+ } = object ?? {};const [width, setWidth] = useState<number>(originWidth);const [height, setHeight] = useState(originHeight);@@ -88,6 +82,7 @@ export default function TransformPanel(props: IProps) {};useEffect(() => {+ if (!transformer) return;const changeStartSub = transformer.changeStart$.subscribe((state) => {changeObs(state);});@@ -101,7 +96,9 @@ export default function TransformPanel(props: IProps) {changeStartSub.unsubscribe();// focusSub.unsubscribe();};- }, []);+ }, [transformer]);++ if (!scene || !transformer || !object) return null;function handleWidthChange(val: number | null) {if (!val || !object) return;diff --git a/packages/slides-ui/src/views/slide-bar/SlideBar.tsx b/packages/slides-ui/src/views/slide-bar/SlideBar.tsxindex 28579f74ee..3b8fe9cc9c 100644--- a/packages/slides-ui/src/views/slide-bar/SlideBar.tsx+++ b/packages/slides-ui/src/views/slide-bar/SlideBar.tsx@@ -46,11 +46,7 @@ export function SlideSideBar() {// );const pages = currentSlide?.getPages();const pageOrder = currentSlide?.getPageOrder();- if (!pages || !pageOrder) {- return null;- }-- const slideList = pageOrder.map((id) => pages[id]);+ const slideList = useMemo(() => pages && pageOrder ? pageOrder.map((id) => pages[id]) : [], [pageOrder, pages]);const [activatePageId, setActivatePageId] = useState<string | null>(currentSlide?.getActivePage()?.id ?? null);@@ -89,6 +85,10 @@ export function SlideSideBar() {commandService.syncExecuteCommand(AppendSlideOperation.id, { unitId: currentSlide?.getUnitId() });}, [commandService, currentSlide]);+ if (!pages || !pageOrder) {+ return null;+ }+return (<asideref={slideBarRef}diff --git a/packages/ui/scripts/generate-emojis.mts b/packages/ui/scripts/generate-emojis.mtsindex f00d351519..52e43e9903 100644--- a/packages/ui/scripts/generate-emojis.mts+++ b/packages/ui/scripts/generate-emojis.mts@@ -386,9 +386,8 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {? Promise.resolve(): generate();- void task- .catch((error) => {- console.error(error);- process.exitCode = 1;- });+ task.catch((error) => {+ console.error(error);+ process.exitCode = 1;+ });}diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex c9659ee7a8..2b2ae7b7f2 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -112,7 +112,7 @@ export { INotificationService } from './services/notification/notification.serviexport { BuiltInUIPart, IUIPartsService, UIPartsService } from './services/parts/parts.service';export { IPlatformService, PlatformService } from './services/platform/platform.service';export { CanvasPopupService, ICanvasPopupService } from './services/popup/canvas-popup.service';-export type { IPopup } from './services/popup/canvas-popup.service';+export type { IPopup, IPopupWithExtraProps } from './services/popup/canvas-popup.service';export { IRibbonOverrideService, RibbonOverrideService } from './services/ribbon/ribbon-override.service';export type { IRibbonOverride } from './services/ribbon/ribbon-override.service';export { DesktopRibbonService, IRibbonService } from './services/ribbon/ribbon.service';diff --git a/packages/ui/src/services/popup/canvas-popup.service.ts b/packages/ui/src/services/popup/canvas-popup.service.tsindex 45995f2030..4f2d61ef4e 100644--- a/packages/ui/src/services/popup/canvas-popup.service.ts+++ b/packages/ui/src/services/popup/canvas-popup.service.ts@@ -42,6 +42,8 @@ export interface IPopup<T = Record<string, unknown>> extends Omit<IRectPopupProponActiveChange?: (active: boolean) => void;}+export type IPopupWithExtraProps<T> = IPopup<T> & { extraProps: T };+export interface ICanvasPopupService {addPopup(item: IPopup): string;removePopup(id: string): void;diff --git a/packages/ui/src/utils/__tests__/storage-driver.spec.ts b/packages/ui/src/utils/__tests__/storage-driver.spec.tsindex 4f27f7d23d..c8abd05e67 100644--- a/packages/ui/src/utils/__tests__/storage-driver.spec.ts+++ b/packages/ui/src/utils/__tests__/storage-driver.spec.ts@@ -171,8 +171,7 @@ describe('browserStorage (LocalStorageDriver fallback)', () => {it('should return undefined when iteratee never returns non-undefined', async () => {await browserStorage.setItem('a', 1);- const result = await browserStorage.iterate<number, string>((value) => {- void value;+ const result = await browserStorage.iterate<number, string>(() => {return undefined as unknown as string;});diff --git a/packages/ui/src/views/components/ComponentContainer.tsx b/packages/ui/src/views/components/ComponentContainer.tsxindex 8310bc92ff..ccda5191f3 100644--- a/packages/ui/src/views/components/ComponentContainer.tsx+++ b/packages/ui/src/views/components/ComponentContainer.tsx@@ -46,7 +46,8 @@ export function ComponentContainer(props: IComponentContainerProps): ReactNode {*/export function useComponentsOfPart(part: string, injector?: Injector): Set<ComponentRenderer> {- const uiPartsService = injector?.get(IUIPartsService) ?? useDependency(IUIPartsService);+ const injectedUIPartsService = useDependency(IUIPartsService);+ const uiPartsService = injector?.get(IUIPartsService) ?? injectedUIPartsService;const uiVisibleChange$ = useMemo(() => uiPartsService.uiVisibleChange$.pipe(filter((ui) => ui.ui === part)), [part, uiPartsService]);const changeInfo = useObservable(uiVisibleChange$);diff --git a/packages/ui/src/views/components/dom/FloatDom.tsx b/packages/ui/src/views/components/dom/FloatDom.tsxindex c9f4d3bee4..18133bafc0 100644--- a/packages/ui/src/views/components/dom/FloatDom.tsx+++ b/packages/ui/src/views/components/dom/FloatDom.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import type { CSSProperties } from 'react';+import type { ComponentType, CSSProperties } from 'react';import type { IFloatDom } from '../../../services/dom/canvas-dom-layer.service';import { DocumentDataModel, IUniverInstanceService } from '@univerjs/core';import { memo, useEffect, useMemo, useRef } from 'react';@@ -48,12 +48,26 @@ function applyFloatDomLayout(}export const FloatDomSingle = memo((props: { layer: IFloatDom; id: string }) => {- const { layer, id } = props;+ const { layer } = props;++ return typeof layer.componentKey === 'string'+ ? <RegisteredFloatDomSingle {...props} componentKey={layer.componentKey} />+ : <FloatDomSingleContent {...props} Component={layer.componentKey} />;+});++function RegisteredFloatDomSingle(props: { layer: IFloatDom; id: string; componentKey: string }) {+ const componentManager = useDependency(ComponentManager);+ return <FloatDomSingleContent {...props} Component={componentManager.get(props.componentKey)} />;+}++function FloatDomSingleContent(props: { layer: IFloatDom; id: string; Component?: ComponentType<any> }) {+ const { layer, id, Component } = props;+const univerInstanceService = useDependency(IUniverInstanceService);const position = useObservable(useMemo(() => layer.position$.pipe(first()), [layer.position$]));const domRef = useRef<HTMLDivElement>(null);const innerDomRef = useRef<HTMLDivElement>(null);- const Component = typeof layer.componentKey === 'string' ? useDependency(ComponentManager).get(layer.componentKey) : layer.componentKey;+const layerProps: any = useMemo(() => ({data: layer.data,...layer.props,@@ -137,7 +151,7 @@ export const FloatDomSingle = memo((props: { layer: IFloatDom; id: string }) =></div></div>);-});+}export const FloatDom = ({ unitId }: { unitId?: string }) => {const instanceService = useDependency(IUniverInstanceService);diff --git a/packages/ui/src/views/components/dom/Print.tsx b/packages/ui/src/views/components/dom/Print.tsxindex 394a5731b1..63afbd8802 100644--- a/packages/ui/src/views/components/dom/Print.tsx+++ b/packages/ui/src/views/components/dom/Print.tsx@@ -14,6 +14,7 @@* limitations under the License.*/+import type { ComponentType } from 'react';import type { IFloatDom, IFloatDomLayout } from '../../../services/dom/canvas-dom-layer.service';import { IUniverInstanceService } from '@univerjs/core';import { useDependency } from '@wendellhu/redi/react-bindings';@@ -22,7 +23,21 @@ import { ComponentManager } from '../../../common';import { shouldForwardFloatDomEvents } from '../../../services/dom/canvas-dom-layer.service';export const PrintFloatDomSingle = memo((props: { layer: IFloatDom; id: string; position: IFloatDomLayout }) => {- const { layer, id, position } = props;+ const { layer } = props;++ return typeof layer.componentKey === 'string'+ ? <RegisteredPrintFloatDomSingle {...props} componentKey={layer.componentKey} />+ : <PrintFloatDomSingleContent {...props} Component={layer.componentKey} />;+});++function RegisteredPrintFloatDomSingle(props: { layer: IFloatDom; id: string; position: IFloatDomLayout; componentKey: string }) {+ const componentManager = useDependency(ComponentManager);+ return <PrintFloatDomSingleContent {...props} Component={componentManager.get(props.componentKey)} />;+}++function PrintFloatDomSingleContent(props: { layer: IFloatDom; id: string; position: IFloatDomLayout; Component?: ComponentType<any> }) {+ const { layer, id, position, Component } = props;+const univerInstanceService = useDependency(IUniverInstanceService);const domRef = useRef<HTMLDivElement>(null);const innerDomRef = useRef<HTMLDivElement>(null);@@ -30,7 +45,6 @@ export const PrintFloatDomSingle = memo((props: { layer: IFloatDom; id: string;const topRef = useRef<number>(position?.startY ?? 0);const leftRef = useRef<number>(position?.startX ?? 0);- const Component = typeof layer.componentKey === 'string' ? useDependency(ComponentManager).get(layer.componentKey) : layer.componentKey;const layerProps: any = useMemo(() => ({data: layer.data,...layer.props,@@ -111,4 +125,4 @@ export const PrintFloatDomSingle = memo((props: { layer: IFloatDom; id: string;</div></div>);-});+}diff --git a/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx b/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsxindex 69d120f336..6bc79a0961 100644--- a/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx+++ b/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx@@ -15,11 +15,11 @@*/import type { ComponentType, ReactElement } from 'react';-import type { IPopup } from '../../../../services/popup/canvas-popup.service';+import type { IPopup, IPopupWithExtraProps } from '../../../../services/popup/canvas-popup.service';import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { ConfigService, IConfigService, Injector, LocaleService } from '@univerjs/core';import { BehaviorSubject } from 'rxjs';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, expectTypeOf, it } from 'vitest';import { ComponentManager } from '../../../../common';import { CanvasPopupService, ICanvasPopupService } from '../../../../services/popup/canvas-popup.service';import { connectInjector } from '../../../../utils/di';@@ -35,8 +35,8 @@ class TestResizeObserver {let previousResizeObserver: typeof ResizeObserver | undefined;let previousAnimationFrame: typeof requestAnimationFrame | undefined;-function TestPopup({ popup }: { popup: IPopup<{ label: string }> }) {- return <button type="button">{popup.extraProps?.label}</button>;+function TestPopup({ popup }: { popup: IPopupWithExtraProps<{ label: string }> }) {+ return <button type="button">{popup.extraProps.label}</button>;}function renderWithDependencies(element: ReactElement) {@@ -71,6 +71,11 @@ function createCanvasElement(rect: DOMRect): HTMLCanvasElement {}describe('CanvasPopup', () => {+ it('requires extraProps only for popups that declare them', () => {+ expectTypeOf<IPopup['extraProps']>().toEqualTypeOf<Record<string, unknown> | undefined>();+ expectTypeOf<IPopupWithExtraProps<{ label: string }>['extraProps']>().toEqualTypeOf<{ label: string }>();+ });+beforeEach(() => {previousResizeObserver = globalThis.ResizeObserver;previousAnimationFrame = globalThis.requestAnimationFrame;diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsxindex ba8e1fdf5e..1e26407154 100644--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx@@ -213,7 +213,7 @@ export function DropdownMenuWrapper({const menuManagerService = useDependency(IMenuManagerService);const [hiddenStates, setHiddenStates] = useState<Record<string, boolean>>({});- const [menuVersion, setMenuVersion] = useState(0);+ const [_, setMenuVersion] = useState(0);useEffect(() => {const subscription = menuManagerService.menuChanged$.subscribe(() => {@@ -224,9 +224,8 @@ export function DropdownMenuWrapper({}, [menuManagerService]);const menuItems = useMemo(() => {- void menuVersion;return menuId ? menuManagerService.getMenuByPositionKey(menuId) : [];- }, [menuId, menuManagerService, menuVersion]);+ }, [menuId, menuManagerService]);const filteredMenuItems = useMemo(() => {return menuItems.filter((item) => {diff --git a/packages/ui/src/views/emoji-picker/EmojiPicker.tsx b/packages/ui/src/views/emoji-picker/EmojiPicker.tsxindex 5b2abf0fba..6c00f35f13 100644--- a/packages/ui/src/views/emoji-picker/EmojiPicker.tsx+++ b/packages/ui/src/views/emoji-picker/EmojiPicker.tsx@@ -353,7 +353,7 @@ function CategoryButton(props: { children: ReactElement; onClick: () => void; se}function writeRecents(localStorageService: ILocalStorageService, storageKey: string, recents: IEmojiItem[]): void {- void localStorageService+ localStorageService.setItem(storageKey, recents).catch(() => undefined);}diff --git a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsxindex 4c50ca8cf9..5502f4033c 100644--- a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx+++ b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx@@ -94,8 +94,8 @@ export function MobileWorkbench(props: IUniverAppProps) {}}, [onRendered]);- const [locale, setLocale] = useState(localeService.getLocales());- const [direction, setDirection] = useState(localeService.getDirection());+ const [locale, setLocale] = useState(() => localeService.getLocales());+ const [direction, setDirection] = useState(() => localeService.getDirection());// Create a portal container for injecting global component themes.const portalContainer = useMemo<HTMLElement>(() => document.createElement('div'), []);diff --git a/packages/ui/src/views/workbench/Workbench.tsx b/packages/ui/src/views/workbench/Workbench.tsxindex 57feaa6a1e..5f6dac5dd3 100644--- a/packages/ui/src/views/workbench/Workbench.tsx+++ b/packages/ui/src/views/workbench/Workbench.tsx@@ -122,8 +122,8 @@ export function DesktopWorkbenchContent(props: IUniverWorkbenchProps) {}}, [onRendered]);- const [locale, setLocale] = useState(localeService.getLocales());- const [direction, setDirection] = useState(localeService.getDirection());+ const [locale, setLocale] = useState(() => localeService.getLocales());+ const [direction, setDirection] = useState(() => localeService.getDirection());// Create a portal container for injecting global component themes.const portalContainer = useMemo<HTMLElement>(() => document.createElement('div'), []);