Skip to content

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

feat(docs): add emoji and symbol pickers to ribbon (#7314)

白熱8045a328e1b9
diff --git a/packages/docs-ui/src/commands/commands/__tests__/insert-special-character.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/insert-special-character.command.spec.ts
new file mode 100644
index 0000000000..e6605d65af
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/__tests__/insert-special-character.command.spec.ts
@@ -0,0 +1,109 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';
+import { awaitTime, BooleanNumber, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import {
+ DocSelectionManagerService,
+ InsertTextCommand,
+ RichTextEditingMutation,
+ SetTextSelectionsOperation,
+} from '@univerjs/docs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { InsertSpecialCharacterCommand } from '../insert-special-character.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+function getDocumentData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello world\r\n',
+ textRuns: [{
+ st: 0,
+ ed: 11,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ fs: 18,
+ },
+ }],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+describe('InsertSpecialCharacterCommand', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed(getDocumentData());
+ univer = testBed.univer;
+ get = testBed.get;
+ commandService = get(ICommandService);
+ commandService.registerCommand(InsertTextCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ commandService.registerCommand(InsertSpecialCharacterCommand);
+
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
+ });
+
+ afterEach(() => univer.dispose());
+
+ it('inserts the selected character at the active range with the current text style', async () => {
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 5,
+ endOffset: 5,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ const result = await commandService.executeCommand(InsertSpecialCharacterCommand.id, { value: '😀' });
+ await awaitTime(0);
+
+ const body = get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)
+ ?.getBody();
+ const insertedTextRun = body?.textRuns?.find(({ st, ed }) => st <= 5 && ed >= 7);
+
+ expect(result).toBe(true);
+ expect(body?.dataStream).toBe('Hello😀 world\r\n');
+ expect(insertedTextRun?.ts).toMatchObject({ bl: BooleanNumber.TRUE, fs: 18 });
+ });
+
+ it('does nothing when there is no active text range', async () => {
+ const result = await commandService.executeCommand(InsertSpecialCharacterCommand.id, { value: '∞' });
+
+ expect(result).toBe(false);
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/insert-special-character.command.ts b/packages/docs-ui/src/commands/commands/insert-special-character.command.ts
new file mode 100644
index 0000000000..76e7630136
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/insert-special-character.command.ts
@@ -0,0 +1,87 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, ICommand } from '@univerjs/core';
+import type { IInsertTextCommandParams } from '@univerjs/docs';
+import { CommandType, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, InsertTextCommand } from '@univerjs/docs';
+import { getCustomDecorationAtPosition, getCustomRangeAtPosition, getTextRunAtPosition } from '../../basics/paragraph';
+import { DocMenuStyleService } from '../../services/doc-menu-style.service';
+
+export const InsertSpecialCharacterCommand: ICommand<{
+ value: string;
+}> = {
+ id: 'doc.command.insert-special-character',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params?.value) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const docSelectionManagerService = accessor.get(DocSelectionManagerService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const docMenuStyleService = accessor.get(DocMenuStyleService);
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const activeRange = docSelectionManagerService.getActiveTextRange();
+
+ if (!docDataModel || !activeRange) {
+ return false;
+ }
+
+ const { segmentId } = activeRange;
+ const originBody = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (!originBody) {
+ return false;
+ }
+
+ const { value } = params;
+ const curTextRun = getTextRunAtPosition(
+ originBody,
+ activeRange.endOffset,
+ docMenuStyleService.getDefaultStyle(),
+ docMenuStyleService.getStyleCache()
+ );
+ const curCustomRange = getCustomRangeAtPosition(originBody.customRanges ?? [], activeRange.endOffset);
+ const curCustomDecorations = getCustomDecorationAtPosition(originBody.customDecorations ?? [], activeRange.endOffset);
+
+ return commandService.executeCommand<IInsertTextCommandParams>(InsertTextCommand.id, {
+ unitId: docDataModel.getUnitId(),
+ body: {
+ dataStream: value,
+ textRuns: [{
+ ...curTextRun,
+ st: 0,
+ ed: value.length,
+ }],
+ customRanges: curCustomRange
+ ? [{
+ ...curCustomRange,
+ startIndex: 0,
+ endIndex: value.length - 1,
+ }]
+ : [],
+ customDecorations: curCustomDecorations.map((customDecoration) => ({
+ ...customDecoration,
+ startIndex: 0,
+ endIndex: value.length - 1,
+ })),
+ },
+ range: activeRange,
+ segmentId,
+ });
+ },
+};
diff --git a/packages/docs-ui/src/controllers/components.controller.ts b/packages/docs-ui/src/controllers/components.controller.ts
index 3f2d85a148..770cc128c8 100644
--- a/packages/docs-ui/src/controllers/components.controller.ts
+++ b/packages/docs-ui/src/controllers/components.controller.ts
@@ -56,9 +56,11 @@ import {
RightInsertColumnDoubleIcon,
RightJustifyingIcon,
ShapeIcon,
+ SmileIcon,
StrikethroughIcon,
SubscriptIcon,
SuperscriptIcon,
+ SymbolsIcon,
TextTypeIcon,
TodoListDoubleIcon,
UnderlineIcon,
@@ -175,9 +177,11 @@ export class ComponentsController extends Disposable {
RightInsertColumnDoubleIcon,
RightJustifyingIcon,
ShapeIcon,
+ SmileIcon,
StrikethroughIcon,
SubscriptIcon,
SuperscriptIcon,
+ SymbolsIcon,
TitleTypeIcon,
SubtitleTypeIcon,
TodoListDoubleIcon,
diff --git a/packages/docs-ui/src/menu/menu.ts b/packages/docs-ui/src/menu/menu.ts
index e5a13cf877..394905ffcc 100644
--- a/packages/docs-ui/src/menu/menu.ts
+++ b/packages/docs-ui/src/menu/menu.ts
@@ -45,6 +45,7 @@ import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render
import {
COLOR_PICKER_COMPONENT,
COMMON_LABEL_COMPONENT,
+ EMOJI_PICKER_COMPONENT,
FONT_FAMILY_COMPONENT,
FONT_FAMILY_ITEM_COMPONENT,
FONT_SIZE_COMPONENT,
@@ -53,6 +54,7 @@ import {
HEADING_ITEM_COMPONENT,
HEADING_LIST,
MenuItemType,
+ SYMBOL_PICKER_COMPONENT,
} from '@univerjs/ui';
import { combineLatest, distinctUntilChanged, map, Observable, shareReplay } from 'rxjs';
import { OpenHeaderFooterPanelCommand } from '../commands/commands/doc-header-footer.command';
@@ -73,6 +75,7 @@ import {
SetInlineFormatTextColorCommand,
SetInlineFormatUnderlineCommand,
} from '../commands/commands/inline-format.command';
+import { InsertSpecialCharacterCommand } from '../commands/commands/insert-special-character.command';
import { BulletListCommand, CheckListCommand, OrderListCommand } from '../commands/commands/list.command';
import {
AlignCenterCommand,
@@ -350,6 +353,49 @@ export function disableMenuWhenNoDocRange(accessor: IAccessor): Observable<boole
});
}
+export const DOC_INSERT_EMOJI_MENU_ID = 'doc.menu.insert-emoji';
+export const DOC_INSERT_SYMBOL_MENU_ID = 'doc.menu.insert-symbol';
+
+export function EmojiPickerMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string, string, string> {
+ return {
+ id: DOC_INSERT_EMOJI_MENU_ID,
+ type: MenuItemType.SELECTOR,
+ icon: 'SmileIcon',
+ tooltip: 'ui.emojiPicker.emojis',
+ selectionsCommandId: InsertSpecialCharacterCommand.id,
+ selections: [{
+ label: {
+ name: EMOJI_PICKER_COMPONENT,
+ hoverable: false,
+ selectable: false,
+ props: { embedded: true },
+ },
+ }],
+ disabled$: disableMenuWhenNoDocRange(accessor),
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ };
+}
+
+export function SymbolPickerMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string, string, string> {
+ return {
+ id: DOC_INSERT_SYMBOL_MENU_ID,
+ type: MenuItemType.SELECTOR,
+ icon: 'SymbolsIcon',
+ tooltip: 'ui.emojiPicker.symbols',
+ selectionsCommandId: InsertSpecialCharacterCommand.id,
+ selections: [{
+ label: {
+ name: SYMBOL_PICKER_COMPONENT,
+ hoverable: false,
+ selectable: false,
+ props: { embedded: true },
+ },
+ }],
+ disabled$: disableMenuWhenNoDocRange(accessor),
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ };
+}
+
export function isTextRangeInAnyBlockRange(document: Nullable<DocumentDataModel>, range: ITextRangeParam): boolean {
const blockRanges = document?.getBody()?.blockRanges ?? [];
const startOffset = range.startOffset;
diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.ts
index 31768e1af1..b3f539969b 100644
--- a/packages/docs-ui/src/menu/schema.ts
+++ b/packages/docs-ui/src/menu/schema.ts
@@ -107,7 +107,10 @@ import {
BoldMenuItemFactory,
BulletListMenuItemFactory,
CheckListMenuItemFactory,
+ DOC_INSERT_EMOJI_MENU_ID,
+ DOC_INSERT_SYMBOL_MENU_ID,
// DocSwitchModeMenuItemFactory,
+ EmojiPickerMenuItemFactory,
FLOAT_TEXT_STYLE_MENU_ID,
FLOAT_TOOLBAR_MENU_POSITION,
FloatTextStyleMenuItemFactory,
@@ -126,6 +129,7 @@ import {
StrikeThroughMenuItemFactory,
SubscriptMenuItemFactory,
SuperscriptMenuItemFactory,
+ SymbolPickerMenuItemFactory,
TABLE_MENU_ID,
TableMenuFactory,
TextColorSelectorMenuItemFactory,
@@ -320,6 +324,16 @@ export const menuSchema: MenuSchemaType = {
gridLayout: { row: 1, column: 2, rowSpan: 2, showLabel: true },
menuItemFactory: HorizontalLineFactory,
},
+ [DOC_INSERT_EMOJI_MENU_ID]: {
+ order: 4,
+ gridLayout: { row: 1, column: 3 },
+ menuItemFactory: EmojiPickerMenuItemFactory,
+ },
+ [DOC_INSERT_SYMBOL_MENU_ID]: {
+ order: 5,
+ gridLayout: { row: 2, column: 3 },
+ menuItemFactory: SymbolPickerMenuItemFactory,
+ },
},
[ContextMenuPosition.MAIN_AREA]: {
[ContextMenuGroup.QUICK]: ({
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 784697793f..1a109acc3e 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -29,18 +29,39 @@ import {
touchDependencies,
UniverInstanceType,
} from '@univerjs/core';
-import { DocInterceptorService, DocSkeletonManagerService, IDocStateChangeInterceptorService, UniverDocsPlugin } from '@univerjs/docs';
+import {
+ DocInterceptorService,
+ DocSkeletonManagerService,
+ IDocStateChangeInterceptorService,
+ UniverDocsPlugin,
+} from '@univerjs/docs';
import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
import { IShortcutService } from '@univerjs/ui';
import pkg from '../package.json';
import { AfterSpaceCommand, EnterCommand, TabCommand } from './commands/commands/auto-format.command';
import { BreakLineCommand } from './commands/commands/break-line.command';
-import { DocCopyCommand, DocCopyCurrentParagraphCommand, DocCutCommand, DocCutCurrentParagraphCommand, DocPasteCommand } from './commands/commands/clipboard.command';
+import {
+ DocCopyCommand,
+ DocCopyCurrentParagraphCommand,
+ DocCutCommand,
+ DocCutCurrentParagraphCommand,
+ DocPasteCommand,
+} from './commands/commands/clipboard.command';
import { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';
import { MoveDocBlockCommand } from './commands/commands/doc-block-move.command';
-import { DeleteCurrentParagraphCommand, DeleteCustomBlockCommand, DeleteLeftCommand, DeleteRightCommand, MergeTwoParagraphCommand, RemoveHorizontalLineCommand } from './commands/commands/doc-delete.command';
+import {
+ DeleteCurrentParagraphCommand,
+ DeleteCustomBlockCommand,
+ DeleteLeftCommand,
+ DeleteRightCommand,
+ MergeTwoParagraphCommand,
+ RemoveHorizontalLineCommand,
+} from './commands/commands/doc-delete.command';
import { CloseHeaderFooterCommand } from './commands/commands/doc-header-footer.command';
-import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from './commands/commands/doc-horizontal-line.command';
+import {
+ HorizontalLineCommand,
+ InsertHorizontalLineBellowCommand,
+} from './commands/commands/doc-horizontal-line.command';
import { DocPageSetupCommand } from './commands/commands/doc-page-setup.command';
import { DocParagraphSettingCommand } from './commands/commands/doc-paragraph-setting.command';
import { DocSelectAllCommand } from './commands/commands/doc-select-all.command';
@@ -62,6 +83,7 @@ import {
SetInlineFormatUnderlineCommand,
} from './commands/commands/inline-format.command';
import { InsertCustomRangeCommand } from './commands/commands/insert-custom-range.command';
+import { InsertSpecialCharacterCommand } from './commands/commands/insert-special-character.command';
import {
BulletListCommand,
ChangeListNestingLevelCommand,
@@ -75,13 +97,40 @@ import {
QuickListCommand,
ToggleCheckListCommand,
} from './commands/commands/list.command';
-import { AlignCenterCommand, AlignJustifyCommand, AlignLeftCommand, AlignOperationCommand, AlignRightCommand } from './commands/commands/paragraph-align.command';
-import { CoverContentCommand, ReplaceContentCommand, ReplaceSelectionCommand, ReplaceSnapshotCommand, ReplaceTextRunsCommand } from './commands/commands/replace-content.command';
+import {
+ AlignCenterCommand,
+ AlignJustifyCommand,
+ AlignLeftCommand,
+ AlignOperationCommand,
+ AlignRightCommand,
+} from './commands/commands/paragraph-align.command';
+import {
+ CoverContentCommand,
+ ReplaceContentCommand,
+ ReplaceSelectionCommand,
+ ReplaceSnapshotCommand,
+ ReplaceTextRunsCommand,
+} from './commands/commands/replace-content.command';
import { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
-import { H1HeadingCommand, H2HeadingCommand, H3HeadingCommand, H4HeadingCommand, H5HeadingCommand, NormalTextHeadingCommand, QuickHeadingCommand, SetParagraphNamedStyleCommand, SubtitleHeadingCommand, TitleHeadingCommand } from './commands/commands/set-heading.command';
+import {
+ H1HeadingCommand,
+ H2HeadingCommand,
+ H3HeadingCommand,
+ H4HeadingCommand,
+ H5HeadingCommand,
+ NormalTextHeadingCommand,
+ QuickHeadingCommand,
+ SetParagraphNamedStyleCommand,
+ SubtitleHeadingCommand,
+ TitleHeadingCommand,
+} from './commands/commands/set-heading.command';
import { SwitchDocModeCommand } from './commands/commands/switch-doc-mode.command';
import { CreateDocTableCommand } from './commands/commands/table/doc-table-create.command';
-import { DocTableDeleteColumnsCommand, DocTableDeleteRowsCommand, DocTableDeleteTableCommand } from './commands/commands/table/doc-table-delete.command';
+import {
+ DocTableDeleteColumnsCommand,
+ DocTableDeleteRowsCommand,
+ DocTableDeleteTableCommand,
+} from './commands/commands/table/doc-table-delete.command';
import {
DocTableInsertColumnCommand,
DocTableInsertColumnLeftCommand,
@@ -111,14 +160,19 @@ import { DocContextMenuRenderController } from './controllers/render-controllers
import { DocEditorBridgeController } from './controllers/render-controllers/doc-editor-bridge.controller';
import { DocIMEInputController } from './controllers/render-controllers/doc-ime-input.controller';
import { DocInputController } from './controllers/render-controllers/doc-input.controller';
-import { DocParagraphPlaceholderRenderController } from './controllers/render-controllers/doc-paragraph-placeholder.render-controller';
+import {
+ DocParagraphPlaceholderRenderController,
+} from './controllers/render-controllers/doc-paragraph-placeholder.render-controller';
import { DocResizeRenderController } from './controllers/render-controllers/doc-resize.render-controller';
import { DocSelectionRenderController } from './controllers/render-controllers/doc-selection-render.controller';
import { DocRenderController } from './controllers/render-controllers/doc.render-controller';
import { DocZoomRenderController } from './controllers/render-controllers/zoom.render-controller';
import { DocUIController } from './controllers/ui.controller';
import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';
-import { DocClipboardPasteAdapterService, IDocClipboardPasteAdapterService } from './services/clipboard/doc-paste-mutation-adapter.service';
+import {
+ DocClipboardPasteAdapterService,
+ IDocClipboardPasteAdapterService,
+} from './services/clipboard/doc-paste-mutation-adapter.service';
import { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-export.service';
import { DocAutoFormatService } from './services/doc-auto-format.service';
import { DocEventManagerService } from './services/doc-event-manager.service';
@@ -134,7 +188,13 @@ import { DocsRenderService } from './services/docs-render.service';
import { EditorService, IEditorService } from './services/editor/editor-manager.service';
import { DocFloatMenuService } from './services/float-menu.service';
import { DocSelectionRenderService } from './services/selection/doc-selection-render.service';
-import { BreakLineShortcut, CloseHeaderFooterShortcut, DeleteLeftShortcut, DeleteRightShortcut, SoftBreakLineShortcut } from './shortcuts/core-editing.shortcut';
+import {
+ BreakLineShortcut,
+ CloseHeaderFooterShortcut,
+ DeleteLeftShortcut,
+ DeleteRightShortcut,
+ SoftBreakLineShortcut,
+} from './shortcuts/core-editing.shortcut';
import {
MoveCursorDocumentEndShortcut,
MoveCursorDocumentStartShortcut,
@@ -163,7 +223,14 @@ import {
SelectAllShortcut,
} from './shortcuts/cursor.shortcut';
import { ShiftTabShortCut } from './shortcuts/format.shortcut';
-import { H1HeadingShortcut, H2HeadingShortcut, H3HeadingShortcut, H4HeadingShortcut, H5HeadingShortcut, NormalTextHeadingShortcut } from './shortcuts/heading.shortcut';
+import {
+ H1HeadingShortcut,
+ H2HeadingShortcut,
+ H3HeadingShortcut,
+ H4HeadingShortcut,
+ H5HeadingShortcut,
+ NormalTextHeadingShortcut,
+} from './shortcuts/heading.shortcut';
@DependentOn(UniverRenderEnginePlugin, UniverDocsPlugin)
export class UniverDocsUIPlugin extends Plugin {
@@ -294,6 +361,7 @@ export class UniverDocsUIPlugin extends Plugin {
ReplaceTextRunsCommand,
ReplaceSelectionCommand,
InsertCustomRangeCommand,
+ InsertSpecialCharacterCommand,
SetParagraphNamedStyleCommand,
QuickHeadingCommand,
DocCopyCurrentParagraphCommand,
diff --git a/packages/docs-ui/src/views/PageSettings.tsx b/packages/docs-ui/src/views/PageSettings.tsx
index 6924dffee5..9101033d73 100644
--- a/packages/docs-ui/src/views/PageSettings.tsx
+++ b/packages/docs-ui/src/views/PageSettings.tsx
@@ -29,7 +29,7 @@ import {
PAPER_TYPES,
UniverInstanceType,
} from '@univerjs/core';
-import { clsx, InputNumber, Select } from '@univerjs/design';
+import { borderClassName, clsx, InputNumber, resetButtonClassName, Select } from '@univerjs/design';
import { useDependency } from '@univerjs/ui';
import { useEffect, useState } from 'react';
@@ -197,13 +197,11 @@ export function PageSettings(props: IConfirmChildrenProps) {
<button
key={option}
type="button"
- className={clsx(`
- univer-flex univer-h-16 univer-cursor-pointer univer-flex-col univer-items-center
- univer-justify-center univer-gap-1 univer-rounded-lg univer-border
- univer-border-solid univer-border-gray-200 univer-bg-white univer-text-sm
- univer-font-medium univer-text-gray-700 univer-transition-colors
+ className={clsx(resetButtonClassName, borderClassName, `
+ univer-h-16 univer-flex-col univer-gap-1 univer-rounded-lg univer-bg-white
+ univer-text-sm univer-font-medium univer-text-gray-700 univer-transition-colors
hover:univer-border-primary-500 hover:univer-text-primary-600
- dark:!univer-border-gray-600 dark:!univer-bg-gray-900 dark:!univer-text-gray-100
+ dark:!univer-bg-gray-900 dark:!univer-text-gray-100
`, {
'!univer-border-primary-500 !univer-bg-primary-50 !univer-text-primary-600 dark:!univer-bg-primary-900': settings.modernWidth === option,
})}
diff --git a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
index b9d032e726..3e13e47f53 100644
--- a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
+++ b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
@@ -323,7 +323,7 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
<div
className="
univer-box-border univer-flex univer-size-full univer-min-w-0 univer-max-w-full univer-flex-col
- univer-gap-3 univer-overflow-hidden univer-text-gray-700
+ univer-gap-3 univer-overflow-hidden univer-py-2 univer-text-gray-700
dark:!univer-text-gray-200
"
data-drawing-object-list-panel="true"
diff --git a/packages/ui/src/views/__tests__/picker-callbacks.spec.tsx b/packages/ui/src/views/__tests__/picker-callbacks.spec.tsx
new file mode 100644
index 0000000000..f611f7b0c8
--- /dev/null
+++ b/packages/ui/src/views/__tests__/picker-callbacks.spec.tsx
@@ -0,0 +1,121 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ILocalStorageService as ILocalStorageServiceType } from '@univerjs/core';
+import type { ComponentType, ReactElement } from 'react';
+import { cleanup, fireEvent, render } from '@testing-library/react';
+import { ILocalStorageService, Injector, LocaleService, LocaleType } from '@univerjs/core';
+import { scrollbarClassName } from '@univerjs/design';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../locale/en-US';
+import { connectInjector } from '../../utils/di';
+import { EmojiPicker } from '../emoji-picker/EmojiPicker';
+import { SymbolPicker } from '../symbol-picker/SymbolPicker';
+
+class TestLocalStorageService implements ILocalStorageServiceType {
+ async getItem<T>(): Promise<T | null> {
+ return null;
+ }
+
+ async setItem<T>(_key: string, value: T): Promise<T> {
+ return value;
+ }
+
+ async removeItem(): Promise<void> {}
+
+ async clear(): Promise<void> {}
+
+ async key(): Promise<string | null> {
+ return null;
+ }
+
+ async keys(): Promise<string[]> {
+ return [];
+ }
+
+ async iterate<_T, U>(): Promise<U> {
+ return undefined as U;
+ }
+}
+
+function renderWithDependencies(element: ReactElement) {
+ const injector = new Injector();
+ injector.add([LocaleService]);
+ injector.add([ILocalStorageService, { useClass: TestLocalStorageService }]);
+
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+
+ const ConnectedTestRoot = connectInjector(() => element, injector) as ComponentType;
+ return render(<ConnectedTestRoot />);
+}
+
+afterEach(cleanup);
+
+describe('picker callbacks', () => {
+ it('omits the popup frame when the emoji picker is embedded', () => {
+ const { container } = renderWithDependencies(<EmojiPicker embedded />);
+ const picker = container.querySelector('[data-u-comp="ui.emoji-picker"]');
+
+ expect(picker?.className).not.toContain('univer-border');
+ expect(picker?.className).not.toContain('univer-shadow-lg');
+ });
+
+ it('reports an emoji through the direct change callback', () => {
+ const onChange = vi.fn();
+ const { getAllByRole } = renderWithDependencies(<EmojiPicker onChange={onChange} />);
+
+ fireEvent.click(getAllByRole('button', { name: 'grinning face' })[0]);
+
+ expect(onChange).toHaveBeenCalledWith('😀');
+ });
+
+ it('uses the design scrollbar styles for emoji content', () => {
+ const { container } = renderWithDependencies(<EmojiPicker />);
+ const scrollContainer = container.querySelector('.univer-overflow-y-auto');
+
+ for (const className of scrollbarClassName.split(' ')) {
+ expect(scrollContainer?.classList.contains(className)).toBe(true);
+ }
+ });
+
+ it('reports a symbol through the direct change callback', () => {
+ const onChange = vi.fn();
+ const { getByRole } = renderWithDependencies(<SymbolPicker onChange={onChange} />);
+
+ fireEvent.click(getByRole('button', { name: '∞' }));
+
+ expect(onChange).toHaveBeenCalledWith('∞');
+ });
+
+ it('omits the popup frame when the symbol picker is embedded', () => {
+ const { container } = renderWithDependencies(<SymbolPicker embedded />);
+ const picker = container.querySelector('[data-u-comp="ui.symbol-picker"]');
+
+ expect(picker?.className).not.toContain('univer-border');
+ expect(picker?.className).not.toContain('univer-shadow-lg');
+ });
+
+ it('uses the design scrollbar styles for symbol content', () => {
+ const { container } = renderWithDependencies(<SymbolPicker />);
+ const scrollContainer = container.querySelector('.univer-overflow-y-auto');
+
+ for (const className of scrollbarClassName.split(' ')) {
+ expect(scrollContainer?.classList.contains(className)).toBe(true);
+ }
+ });
+});
diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
index bdeab1590b..6bcabf024b 100644
--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
@@ -309,10 +309,12 @@ export function DropdownMenuWrapper({
// options menu
if (options?.length) {
+ const isSingleCustomPanel = options.length === 1 && typeof options[0].label === 'object' && options[0].label?.hoverable === false;
const items: IDropdownMenuProps['items'] = options.map((option) => ({
type: 'item',
className: clsx({
'focus:univer-bg-white': typeof option.label !== 'string' && option.label?.hoverable === false,
+ '!univer-p-0': typeof option.label !== 'string' && option.label?.hoverable === false,
}),
children: (
<DropdownMenuLabel
@@ -373,6 +375,7 @@ export function DropdownMenuWrapper({
return (
<DropdownMenu
align="start"
+ className={clsx({ '!univer-p-0': isSingleCustomPanel })}
items={items}
disabled={disabled}
open={dropdownVisible}
diff --git a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
index 59bb0bfab7..dfa1e265f3 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
@@ -21,11 +21,19 @@
import type { ComponentType, ReactElement } from 'react';
import { cleanup, fireEvent, render } from '@testing-library/react';
import { ILogService, Injector, LocaleService } from '@univerjs/core';
+import { of } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
+import { IMenuManagerService } from '../../../../services/menu/menu-manager.service';
import { connectInjector } from '../../../../utils/di';
-import { DropdownMenuLabel, DropdownWrapper, ToolbarDropdownProvider, TooltipWrapper } from '../TooltipButtonWrapper';
+import {
+ DropdownMenuLabel,
+ DropdownMenuWrapper,
+ DropdownWrapper,
+ ToolbarDropdownProvider,
+ TooltipWrapper,
+} from '../TooltipButtonWrapper';
class TestLocaleService {
t(key: string) {
@@ -43,6 +51,15 @@ function renderWithDependencies(element: ReactElement) {
injector.add([ILogService, { useClass: TestLogService as never }]);
injector.add([ComponentManager]);
injector.add([IconManager]);
+ injector.add([IMenuManagerService, {
+ useValue: {
+ menuChanged$: of(undefined),
+ mergeMenu: () => {},
+ appendRootMenu: () => {},
+ getMenuByPositionKey: () => [],
+ getFlatMenuByPositionKey: () => [],
+ },
+ }]);
injector.get(ComponentManager).register('TestDynamicOption', ({ onChange }: { onChange: (value: string) => void }) => (
<button type="button" onClick={() => onChange('dynamic-value')}>Choose dynamic value</button>
));
@@ -101,3 +118,35 @@ describe('DropdownWrapper', () => {
expect(queryByText('Dropdown content')).toBeNull();
});
});
+
+describe('DropdownMenuWrapper', () => {
+ it('renders a single non-hoverable custom panel flush with the dropdown edge', async () => {
+ const { findByRole, getByRole } = renderWithDependencies(
+ <ToolbarDropdownProvider>
+ <TooltipWrapper dropdownKey="test-custom-panel">
+ <DropdownMenuWrapper
+ menuId="test-menu"
+ options={[{
+ label: {
+ name: 'TestDynamicOption',
+ hoverable: false,
+ selectable: false,
+ },
+ }]}
+ onOptionSelect={vi.fn()}
+ >
+ <button type="button">Open custom panel</button>
+ </DropdownMenuWrapper>
+ </TooltipWrapper>
+ </ToolbarDropdownProvider>
+ );
+
+ fireEvent.pointerDown(getByRole('button', { name: 'Open custom panel' }), { button: 0, ctrlKey: false });
+ const option = await findByRole('button', { name: 'Choose dynamic value' });
+ const menuItem = option.closest('[data-slot="dropdown-menu-item"]');
+ const menuContent = option.closest('[data-slot="dropdown-menu-content"]');
+
+ expect(menuItem?.className).toContain('!univer-p-0');
+ expect(menuContent?.className).toContain('!univer-p-0');
+ });
+});
diff --git a/packages/ui/src/views/emoji-picker/EmojiPicker.tsx b/packages/ui/src/views/emoji-picker/EmojiPicker.tsx
index 6c00f35f13..500f809e62 100644
--- a/packages/ui/src/views/emoji-picker/EmojiPicker.tsx
+++ b/packages/ui/src/views/emoji-picker/EmojiPicker.tsx
@@ -19,7 +19,7 @@ import type { LocaleKey } from '../../locale/types';
import type { IPopup } from '../../services/popup/canvas-popup.service';
import type { EmojiCategory, IEmojiItem } from './emoji-picker-utils';
import { ILocalStorageService, LocaleService } from '@univerjs/core';
-import { borderTopClassName, clsx, Input } from '@univerjs/design';
+import { borderTopClassName, clsx, Input, scrollbarClassName } from '@univerjs/design';
import {
ActivityIcon,
FoodsIcon,
@@ -51,16 +51,22 @@ export const EMOJI_PICKER_COMPONENT = 'ui.emoji-picker';
const RECENTS_STORAGE_KEY = 'univer.ui.recent-emojis';
const ACTIVE_SECTION_SCROLL_OFFSET = 28;
-export interface IEmojiPickerPopupProps {
+interface IEmojiPickerPopupProps {
activeEmoji?: string;
onSelect?: (emoji: string, options?: { keepOpen?: boolean }) => void;
recentStorageKey?: string;
}
+interface IEmojiPickerProps {
+ embedded?: boolean;
+ onChange?: (emoji: string) => void;
+ popup?: IPopup<IEmojiPickerPopupProps>;
+}
+
type EmojiSectionKey = 'recent' | EmojiCategory;
interface IEmojiSection { emojis: IEmojiItem[]; key: EmojiSectionKey; title: string }
-export function EmojiPicker(props: { popup?: IPopup<IEmojiPickerPopupProps> }) {
+export function EmojiPicker(props: IEmojiPickerProps) {
const extraProps = props.popup?.extraProps;
const localeService = useDependency(LocaleService);
const localStorageService = useDependency(ILocalStorageService);
@@ -114,6 +120,7 @@ export function EmojiPicker(props: { popup?: IPopup<IEmojiPickerPopupProps> }) {
setActiveEmoji(item.emoji);
setRecents(nextRecents);
writeRecents(localStorageService, recentStorageKey, nextRecents);
+ props.onChange?.(item.emoji);
extraProps?.onSelect?.(item.emoji, options);
};
@@ -143,11 +150,14 @@ export function EmojiPicker(props: { popup?: IPopup<IEmojiPickerPopupProps> }) {
return (
<section
data-u-comp={EMOJI_PICKER_COMPONENT}
- className="
- univer-flex univer-h-[340px] univer-w-[420px] univer-flex-col univer-overflow-hidden univer-rounded-[10px]
- univer-border univer-border-solid univer-border-gray-200 univer-bg-white univer-shadow-lg
- dark:!univer-border-gray-600 dark:!univer-bg-gray-900
- "
+ className={clsx(
+ 'univer-flex univer-h-[340px] univer-w-[420px] univer-flex-col univer-overflow-hidden',
+ !props.embedded && `
+ univer-rounded-[10px] univer-border univer-border-solid univer-border-gray-200 univer-bg-white
+ univer-shadow-lg
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-900
+ `
+ )}
>
<div className="univer-flex univer-items-center univer-gap-1 univer-px-3 univer-pb-2 univer-pt-3">
<Input
@@ -185,7 +195,10 @@ export function EmojiPicker(props: { popup?: IPopup<IEmojiPickerPopupProps> }) {
<div
ref={scrollRef}
- className="univer-relative univer-min-h-0 univer-flex-1 univer-overflow-y-auto univer-px-3"
+ className={clsx(
+ 'univer-relative univer-min-h-0 univer-flex-1 univer-overflow-y-auto univer-px-3',
+ scrollbarClassName
+ )}
onScroll={handleScroll}
>
{renderedSections.length
diff --git a/packages/ui/src/views/emoji-picker/index.ts b/packages/ui/src/views/emoji-picker/index.ts
index e310c756a4..9f2c2826d9 100644
--- a/packages/ui/src/views/emoji-picker/index.ts
+++ b/packages/ui/src/views/emoji-picker/index.ts
@@ -28,4 +28,3 @@ export {
} from './emoji-picker-utils';
export type { EmojiCategory, IEmojiItem, IEmojiLocaleData } from './emoji-picker-utils';
export { EMOJI_PICKER_COMPONENT, EmojiPicker } from './EmojiPicker';
-export type { IEmojiPickerPopupProps } from './EmojiPicker';
diff --git a/packages/ui/src/views/symbol-picker/SymbolPicker.tsx b/packages/ui/src/views/symbol-picker/SymbolPicker.tsx
index 75eeadae55..58c3e0cfa3 100644
--- a/packages/ui/src/views/symbol-picker/SymbolPicker.tsx
+++ b/packages/ui/src/views/symbol-picker/SymbolPicker.tsx
@@ -18,19 +18,26 @@ import type { LocaleKey } from '../../locale/types';
import type { IPopup } from '../../services/popup/canvas-popup.service';
import type { ISymbolCategory } from './symbols';
import { LocaleService } from '@univerjs/core';
-import { clsx } from '@univerjs/design';
+import { clsx, scrollbarClassName } from '@univerjs/design';
import { useState } from 'react';
import { useDependency, useObservable } from '../../utils/di';
import { SYMBOL_CATEGORIES } from './symbols';
export const SYMBOL_PICKER_COMPONENT = 'ui.symbol-picker';
-export interface ISymbolPickerPopupProps {
+interface ISymbolPickerPopupProps {
activeSymbol?: string;
onSelect?: (symbol: string, options?: { keepOpen?: boolean }) => void;
}
-export function SymbolPicker(props: { popup?: IPopup<ISymbolPickerPopupProps>; className?: string }) {
+interface ISymbolPickerProps {
+ className?: string;
+ embedded?: boolean;
+ onChange?: (symbol: string) => void;
+ popup?: IPopup<ISymbolPickerPopupProps>;
+}
+
+export function SymbolPicker(props: ISymbolPickerProps) {
const extraProps = props.popup?.extraProps;
const localeService = useDependency(LocaleService);
useObservable(localeService.currentLocale$, localeService.getCurrentLocale());
@@ -38,6 +45,7 @@ export function SymbolPicker(props: { popup?: IPopup<ISymbolPickerPopupProps>; c
const handleSelect = (symbol: string) => {
setActiveSymbol(symbol);
+ props.onChange?.(symbol);
extraProps?.onSelect?.(symbol, { keepOpen: true });
};
@@ -45,8 +53,8 @@ export function SymbolPicker(props: { popup?: IPopup<ISymbolPickerPopupProps>; c
<section
data-u-comp={SYMBOL_PICKER_COMPONENT}
className={clsx(
- `
- univer-flex univer-h-[340px] univer-w-[420px] univer-flex-col univer-overflow-hidden
+ 'univer-flex univer-h-[340px] univer-w-[420px] univer-flex-col univer-overflow-hidden',
+ !props.embedded && `
univer-rounded-[10px] univer-border univer-border-solid univer-border-gray-200 univer-bg-white
univer-shadow-lg
dark:!univer-border-gray-600 dark:!univer-bg-gray-900
@@ -54,7 +62,12 @@ export function SymbolPicker(props: { popup?: IPopup<ISymbolPickerPopupProps>; c
props.className
)}
>
- <div className="univer-min-h-0 univer-flex-1 univer-overflow-y-auto univer-p-4">
+ <div
+ className={clsx(
+ 'univer-min-h-0 univer-flex-1 univer-overflow-y-auto univer-p-4',
+ scrollbarClassName
+ )}
+ >
<div className="univer-flex univer-flex-col univer-gap-5">
{SYMBOL_CATEGORIES.map((category) => (
<SymbolSection
diff --git a/packages/ui/src/views/symbol-picker/index.ts b/packages/ui/src/views/symbol-picker/index.ts
index 2dcc5b8e24..eaa152a835 100644
--- a/packages/ui/src/views/symbol-picker/index.ts
+++ b/packages/ui/src/views/symbol-picker/index.ts
@@ -15,6 +15,5 @@
*/
export { SYMBOL_PICKER_COMPONENT, SymbolPicker } from './SymbolPicker';
-export type { ISymbolPickerPopupProps } from './SymbolPicker';
export { SYMBOL_CATEGORIES } from './symbols';
export type { ISymbolCategory, SymbolCategory } from './symbols';