Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(ui): add reusable font family dropdown (#7180)
白熱bae210e24f2a
diff --git a/packages/ui/src/controllers/components.controller.ts b/packages/ui/src/controllers/components.controller.tsindex 633ec76d31..7263f2da2f 100644--- a/packages/ui/src/controllers/components.controller.ts+++ b/packages/ui/src/controllers/components.controller.ts@@ -23,8 +23,7 @@ import { COLOR_PICKER_COMPONENT } from '../views/color-picker/interface';import { COMMON_LABEL_COMPONENT, CommonLabel } from '../views/CommonLabel';import { ShortcutPanel } from '../views/components/shortcut-panel/ShortcutPanel';import { EMOJI_PICKER_COMPONENT, EmojiPicker } from '../views/emoji-picker/index';-import { FontFamily, FontFamilyItem } from '../views/font-family/index';-import { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from '../views/font-family/interface';+import { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT, FontFamily, FontFamilyItem } from '../views/font-family/index';import { FontSize } from '../views/font-size/FontSize';import { FONT_SIZE_COMPONENT } from '../views/font-size/interface';import { HEADING_ITEM_COMPONENT, HeadingItem } from '../views/index';diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 1f7eec8ca6..fe37313879 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -146,10 +146,12 @@ export { ToolbarButton } from './views/components/ribbon/ToolbarButton';export { ToolbarItem } from './views/components/ribbon/ToolbarItem';export { Sidebar } from './views/components/sidebar/Sidebar';export type { ISidebarMethodOptions } from './views/components/sidebar/Sidebar';-export { FontFamily } from './views/font-family/FontFamily';-export { FontFamilyItem } from './views/font-family/FontFamilyItem';-export { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from './views/font-family/interface';-export type { IFontFamilyProps } from './views/font-family/interface';+export { FONT_FAMILY_COMPONENT, FontFamily } from './views/font-family/FontFamily';+export type { IFontFamilyProps } from './views/font-family/FontFamily';+export { FontFamilyDropdown } from './views/font-family/FontFamilyDropdown';+export type { IFontFamilyDropdownProps } from './views/font-family/FontFamilyDropdown';+export { FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem } from './views/font-family/FontFamilyItem';+export type { IFontFamilyItemProps } from './views/font-family/FontFamilyItem';export { FontSize } from './views/font-size/FontSize';export { FONT_SIZE_COMPONENT, FONT_SIZE_LIST, HEADING_LIST } from './views/font-size/interface';export * from './views/hooks/index';diff --git a/packages/ui/src/views/font-family/FontFamily.tsx b/packages/ui/src/views/font-family/FontFamily.tsxindex 0aa2b86ce4..99f421bd8c 100644--- a/packages/ui/src/views/font-family/FontFamily.tsx+++ b/packages/ui/src/views/font-family/FontFamily.tsx@@ -15,33 +15,35 @@*/import type { ChangeEvent, KeyboardEvent } from 'react';-import type { IFontConfig } from '../../services/font.service';-import type { IFontFamilyProps } from './interface';-import { ICommandService, LocaleService } from '@univerjs/core';+import type { Observable } from 'rxjs';+import type { ICustomComponentProps } from '../../services/menu/menu';+import { LocaleService } from '@univerjs/core';+import { clsx } from '@univerjs/design';-import { useEffect, useMemo, useState } from 'react';-import { IFontService } from '../../services/font.service';+import { useMemo, useState } from 'react';import { useDependency, useObservable } from '../../utils/di';+import { useFontList } from './use-font-list';-export const FontFamily = ({ id, value, disabled$ }: IFontFamilyProps) => {- const disabled = useObservable(disabled$);+export interface IFontFamilyProps extends ICustomComponentProps<string> {+ className?: string;- const commandService = useDependency(ICommandService);- const localeService = useDependency(LocaleService);- const fontService = useDependency(IFontService);+ disabled?: boolean;- const [inputValue, setInputValue] = useState('');- const [fonts, setFonts] = useState<IFontConfig[]>([]);+ value: string;- useEffect(() => {- const subscription = fontService.fonts$.subscribe((fonts) => {- setFonts(fonts);- });+ disabled$?: Observable<boolean>;+}++export const FONT_FAMILY_COMPONENT = 'UI_FONT_FAMILY_COMPONENT';++export const FontFamily = ({ className, disabled: disabledProp, value, disabled$, onChange }: IFontFamilyProps) => {+ const disabledObservableValue = useObservable(disabled$);+ const disabled = Boolean(disabledProp || disabledObservableValue);- return () => {- subscription.unsubscribe();- };- }, []);+ const localeService = useDependency(LocaleService);+ const { fonts } = useFontList();++ const [draftValue, setDraftValue] = useState<string | null>(null);const viewValue = useMemo(() => {if (value == null) return '';@@ -56,17 +58,14 @@ export const FontFamily = ({ id, value, disabled$ }: IFontFamilyProps) => {return localeService.t(font.label);}, [value, fonts, localeService]);-- useMemo(() => {- setInputValue(viewValue);- }, [value]);+ const inputValue = draftValue ?? viewValue;function resetValue() {- setInputValue(viewValue);+ setDraftValue(null);}function handleChangeSelection(e: ChangeEvent<HTMLInputElement>) {- setInputValue(e.target.value);+ setDraftValue(e.target.value);}function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {@@ -83,7 +82,7 @@ export const FontFamily = ({ id, value, disabled$ }: IFontFamilyProps) => {}function handleBlur() {- if (inputValue !== value) resetValue();+ if (draftValue !== null && inputValue !== viewValue) resetValue();}function confirm() {@@ -95,18 +94,19 @@ export const FontFamily = ({ id, value, disabled$ }: IFontFamilyProps) => {if (!font) {resetValue();return;- };+ }handleSelectFont(font.value);}- function handleSelectFont(value: string) {- commandService.executeCommand(id, { value });+ function handleSelectFont(nextValue: string) {+ resetValue();+ onChange(nextValue);}return (<div- className="univer-w-32 univer-truncate univer-text-sm"+ className={clsx('univer-w-32 univer-truncate univer-text-sm', className)}style={{ fontFamily: value as string }}><inputdiff --git a/packages/ui/src/views/font-family/FontFamilyDropdown.tsx b/packages/ui/src/views/font-family/FontFamilyDropdown.tsxnew file mode 100644index 0000000000..9e106c4b3e--- /dev/null+++ b/packages/ui/src/views/font-family/FontFamilyDropdown.tsx@@ -0,0 +1,113 @@+/**+ * 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 { MouseEvent, PointerEvent, ReactNode } from 'react';+import type { Observable } from 'rxjs';+import { clsx, Dropdown } from '@univerjs/design';+import { MoreDownIcon } from '@univerjs/icons';+import { useState } from 'react';+import { useObservable } from '../../utils/di';+import { FontFamily } from './FontFamily';+import { FontFamilyItem } from './FontFamilyItem';++export interface IFontFamilyDropdownProps {+ value: string;+ onChange: (value: string) => void;+ ariaLabel?: string;+ className?: string;+ disabled?: boolean;+ disabled$?: Observable<boolean>;+ inputClassName?: string;+ popupClassName?: string;+ popupDataComponent?: string;+ title?: ReactNode;+ onMouseDown?: (event: MouseEvent<HTMLElement>) => void;+ onPointerDown?: (event: PointerEvent<HTMLElement>) => void;+}++export function FontFamilyDropdown(props: IFontFamilyDropdownProps) {+ const {+ value,+ onChange,+ ariaLabel,+ className,+ disabled: disabledProp,+ disabled$,+ inputClassName,+ popupClassName,+ popupDataComponent,+ title,+ onMouseDown,+ onPointerDown,+ } = props;+ const disabledObservableValue = useObservable(disabled$);+ const disabled = Boolean(disabledProp || disabledObservableValue);+ const [open, setOpen] = useState(false);+ const popupDataAttributes = popupDataComponent ? { 'data-u-comp': popupDataComponent } : undefined;++ function handleChange(nextValue: string) {+ setOpen(false);+ onChange(nextValue);+ }++ return (+ <Dropdown+ disabled={disabled}+ open={open}+ onOpenChange={setOpen}+ overlay={(+ <div+ className={clsx(`+ univer-max-h-72 univer-min-w-44 univer-overflow-y-auto univer-rounded-lg univer-border+ univer-border-solid univer-border-gray-200 univer-bg-white univer-p-1 univer-shadow-lg+ dark:!univer-border-gray-700 dark:!univer-bg-gray-900+ `, popupClassName)}+ {...popupDataAttributes}+ >+ <FontFamilyItem value={value} onChange={handleChange} />+ </div>+ )}+ >+ <div+ aria-disabled={disabled}+ aria-expanded={open}+ aria-label={ariaLabel}+ className={clsx(`+ univer-flex univer-h-6 univer-min-w-0 univer-cursor-default univer-items-center univer-justify-between+ univer-gap-1 univer-rounded-md univer-px-1.5 univer-text-sm univer-text-gray-900+ hover:univer-bg-gray-100+ dark:!univer-text-gray-100+ dark:hover:!univer-bg-gray-700+ `, {+ 'univer-cursor-not-allowed univer-opacity-60': disabled,+ }, className)}+ role="combobox"+ tabIndex={disabled ? -1 : 0}+ title={typeof title === 'string' ? title : undefined}+ onMouseDown={onMouseDown}+ onPointerDown={onPointerDown}+ >+ <FontFamily+ className={clsx('univer-min-w-0 univer-flex-1', inputClassName)}+ value={value}+ disabled={disabled}+ onChange={handleChange}+ />+ <MoreDownIcon className="univer-flex-shrink-0 univer-text-xs univer-text-gray-500" />+ </div>+ </Dropdown>+ );+}diff --git a/packages/ui/src/views/font-family/FontFamilyItem.tsx b/packages/ui/src/views/font-family/FontFamilyItem.tsxindex 61ed22d07e..93f6ee0ac0 100644--- a/packages/ui/src/views/font-family/FontFamilyItem.tsx+++ b/packages/ui/src/views/font-family/FontFamilyItem.tsx@@ -15,37 +15,25 @@*/import type { LocaleKey } from '../../locale/types';-import type { IFontConfig } from '../../services/font.service';-import { ICommandService, LocaleService } from '@univerjs/core';+import type { ICustomComponentProps } from '../../services/menu/menu';+import { LocaleService } from '@univerjs/core';import { Tooltip } from '@univerjs/design';import { InfoIcon } from '@univerjs/icons';-import { useEffect, useState } from 'react';-import { IFontService } from '../../services/font.service';-import { ILayoutService } from '../../services/layout/layout.service';import { useDependency } from '../../utils/di';+import { useFontList } from './use-font-list';-export const FontFamilyItem = ({ id, value }: { id: string; value: string }) => {- const commandService = useDependency(ICommandService);- const fontService = useDependency(IFontService);- const layoutService = useDependency(ILayoutService);+export interface IFontFamilyItemProps extends ICustomComponentProps<string> {+ value: string;+}- const [fonts, setFonts] = useState<IFontConfig[]>([]);-- useEffect(() => {- const subscription = fontService.fonts$.subscribe((fonts) => {- setFonts(fonts);- });-- return () => {- subscription.unsubscribe();- };- }, []);+export const FONT_FAMILY_ITEM_COMPONENT = 'UI_FONT_FAMILY_ITEM_COMPONENT';+export const FontFamilyItem = ({ value, onChange }: IFontFamilyItemProps) => {const localeService = useDependency(LocaleService);+ const { fonts, fontService } = useFontList();- function handleSelectFont(value: string) {- layoutService.focus();- commandService.executeCommand(id, { value });+ function handleSelectFont(nextValue: string) {+ onChange(nextValue);}return (diff --git a/packages/ui/src/views/font-family/__tests__/FontInputs.spec.tsx b/packages/ui/src/views/font-family/__tests__/FontInputs.spec.tsxindex 3509646743..5954c0f38e 100644--- a/packages/ui/src/views/font-family/__tests__/FontInputs.spec.tsx+++ b/packages/ui/src/views/font-family/__tests__/FontInputs.spec.tsx@@ -24,6 +24,7 @@ import { FontService, IFontService } from '../../../services/font.service';import { RediProvider } from '../../../utils/di';import { FontSize } from '../../font-size/FontSize';import { FontFamily } from '../FontFamily';+import { FontFamilyItem } from '../FontFamilyItem';class TestState {static commandParams: unknown[] = [];@@ -58,6 +59,15 @@ function renderWithDependencies(element: ReactElement) {'times-new-roman': 'Times New Roman',tahoma: 'Tahoma',verdana: 'Verdana',+ 'microsoft-yahei': 'Microsoft YaHei',+ simsun: 'SimSun',+ simhei: 'SimHei',+ kaiti: 'Kaiti',+ fangsong: 'FangSong',+ nsimsun: 'NSimSun',+ stxinwei: 'STXinwei',+ stxingkai: 'STXingkai',+ stliti: 'STLiti',},},},@@ -84,10 +94,9 @@ describe('font input views', () => {TestState.reset();});- it('executes the font-family command when the typed text matches a known font', () => {+ it('emits onChange when the typed text matches a known font', () => {const rendered = renderWithDependencies(<FontFamily- id={SetFontFamilyCommand.id}value="Arial"onChange={(value) => TestState.familyChanges.push(value)}/>@@ -97,15 +106,14 @@ describe('font input views', () => {fireEvent.change(input, { target: { value: 'times' } });fireEvent.keyDown(input, { key: 'Enter' });- expect(TestState.commandParams).toEqual([{ value: 'Times New Roman' }]);- expect(TestState.familyChanges).toEqual([]);+ expect(TestState.commandParams).toEqual([]);+ expect(TestState.familyChanges).toEqual(['Times New Roman']);rendered.dispose();});it('restores the displayed font when the typed text does not match any font', () => {const rendered = renderWithDependencies(<FontFamily- id={SetFontFamilyCommand.id}value="Arial"onChange={(value) => TestState.familyChanges.push(value)}/>@@ -121,6 +129,21 @@ describe('font input views', () => {rendered.dispose();});+ it('emits onChange when a font-family menu item is selected', () => {+ const rendered = renderWithDependencies(+ <FontFamilyItem+ value="Arial"+ onChange={(value) => TestState.familyChanges.push(value)}+ />+ );++ fireEvent.click(rendered.getByText('Times New Roman'));++ expect(TestState.commandParams).toEqual([]);+ expect(TestState.familyChanges).toEqual(['Times New Roman']);+ rendered.dispose();+ });+it('commits font size only when Enter is pressed', () => {const disabled$ = new BehaviorSubject(false);const rendered = render(diff --git a/packages/ui/src/views/font-family/index.ts b/packages/ui/src/views/font-family/index.tsindex ce41a4aa99..c887e3f9f5 100644--- a/packages/ui/src/views/font-family/index.ts+++ b/packages/ui/src/views/font-family/index.ts@@ -14,5 +14,9 @@* limitations under the License.*/-export { FontFamily } from './FontFamily';-export { FontFamilyItem } from './FontFamilyItem';+export { FONT_FAMILY_COMPONENT, FontFamily } from './FontFamily';+export type { IFontFamilyProps } from './FontFamily';+export { FontFamilyDropdown } from './FontFamilyDropdown';+export type { IFontFamilyDropdownProps } from './FontFamilyDropdown';+export { FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem } from './FontFamilyItem';+export type { IFontFamilyItemProps } from './FontFamilyItem';diff --git a/packages/ui/src/views/font-family/interface.ts b/packages/ui/src/views/font-family/interface.tsdeleted file mode 100644index e1d4649471..0000000000--- a/packages/ui/src/views/font-family/interface.ts+++ /dev/null@@ -1,30 +0,0 @@-/**- * 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 { Observable } from 'rxjs';-import type { ICustomComponentProps } from '../../services/menu/menu';--export interface IFontFamilyProps extends ICustomComponentProps<string> {- id: string;-- value: string;-- disabled$?: Observable<boolean>;-}--export const FONT_FAMILY_COMPONENT = 'UI_FONT_FAMILY_COMPONENT';--export const FONT_FAMILY_ITEM_COMPONENT = 'UI_FONT_FAMILY_ITEM_COMPONENT';diff --git a/packages/ui/src/views/font-family/use-font-list.ts b/packages/ui/src/views/font-family/use-font-list.tsnew file mode 100644index 0000000000..03b8f1f6a1--- /dev/null+++ b/packages/ui/src/views/font-family/use-font-list.ts@@ -0,0 +1,37 @@+/**+ * 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 { IFontConfig } from '../../services/font.service';+import { useEffect, useState } from 'react';+import { IFontService } from '../../services/font.service';+import { useDependency } from '../../utils/di';++export function useFontList() {+ const fontService = useDependency(IFontService);+ const [fonts, setFonts] = useState<IFontConfig[]>(() => fontService.getFonts());++ useEffect(() => {+ const subscription = fontService.fonts$.subscribe((fonts) => {+ setFonts(fonts);+ });++ return () => {+ subscription.unsubscribe();+ };+ }, [fontService]);++ return { fonts, fontService };+}