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: extract hooks for better customization (#2301)

Wenzhao Hu2b75400dd788
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index af6d91cfe5..6346c40b4d 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -92,6 +92,7 @@ export { CanvasPopupService, ICanvasPopupService, type IPopup } from './services
export { ContextMenu } from './views/components/context-menu/ContextMenu';
export { CanvasPopup } from './views/components/popup/CanvasPopup';
export { ProgressBar } from './components/progress-bar/ProgressBar';
+export { type IMenuGroup, useToolbarGroups, useToolbarItemStatus, useToolbarCollapseObserver } from './views/components/doc-bars/hook';
export { mergeMenuConfigs } from './common/menu-merge-configs';
export { IProgressService, ProgressService } from './services/progress/progress.service';
export type { IProgressStep } from './services/progress/progress.service';
diff --git a/packages/ui/src/views/components/doc-bars/Toolbar.tsx b/packages/ui/src/views/components/doc-bars/Toolbar.tsx
index d94b35a2a9..b6dce97528 100644
--- a/packages/ui/src/views/components/doc-bars/Toolbar.tsx
+++ b/packages/ui/src/views/components/doc-bars/Toolbar.tsx
@@ -20,23 +20,16 @@ import { MoreFunctionSingle } from '@univerjs/icons';
import { useDependency } from '@wendellhu/redi/react-bindings';
import clsx from 'clsx';
import type { ComponentType } from 'react';
-import React, { useEffect, useMemo, useRef, useState } from 'react';
+import React, { useMemo } from 'react';
-import { combineLatest, map, Observable } from 'rxjs';
-import type { IDisplayMenuItem, IMenuItem } from '../../../services/menu/menu';
-import { MenuGroup, MenuPosition } from '../../../services/menu/menu';
-import { IMenuService } from '../../../services/menu/menu.service';
+import { MenuPosition } from '../../../services/menu/menu';
import { ComponentContainer } from '../ComponentContainer';
import { ToolbarButton } from './Button/ToolbarButton';
import styles from './index.module.less';
import { ToolbarItem } from './ToolbarItem';
+import { useToolbarCollapseObserver, useToolbarGroups } from './hook';
-interface IMenuGroup {
- name: MenuPosition;
- menuItems: Array<IDisplayMenuItem<IMenuItem>>;
-}
-
-export const positions = [
+const MENU_POSITIONS = [
MenuPosition.TOOLBAR_START,
MenuPosition.TOOLBAR_INSERT,
MenuPosition.TOOLBAR_FORMULAS,
@@ -49,124 +42,18 @@ export interface IToolbarProps {
headerMenuComponents?: Set<() => ComponentType>;
}
+/**
+ * Univer's built in toolbar component.
+ */
export function Toolbar(props: IToolbarProps) {
const { headerMenuComponents } = props;
const localeService = useDependency(LocaleService);
- const menuService = useDependency(IMenuService);
- const [position, setPosition] = useState<MenuPosition>(MenuPosition.TOOLBAR_START);
-
- const toolbarRef = useRef<HTMLDivElement>(null);
- const toolbarItemRefs = useRef<
- Record<
- string,
- {
- el: HTMLDivElement;
- key: string;
- }
- >
- >({});
-
- const [group, setGroup] = useState<IMenuGroup[]>([]);
- const [collapsedId, setCollapsedId] = useState<string[]>([]);
- const [visibleItems, setVisibleItems] = useState<IDisplayMenuItem<IMenuItem>[]>([]);
-
- useEffect(() => {
- const activeItems = group.find((g) => g.name === position)?.menuItems ?? [];
- const filteredItems$ = combineLatest(
- activeItems.map((item) => item.hidden$ ?? new Observable((observer) => observer.next(false)) as any)
- ).pipe(
- map((hiddenValues) => activeItems.filter((_, index) => !hiddenValues[index]))
- );
-
- const subscribe = filteredItems$.subscribe((items) => {
- setVisibleItems(items);
- });
-
- return () => {
- subscribe.unsubscribe();
- };
- }, [group]);
-
- useEffect(() => {
- const listener = menuService.menuChanged$.subscribe(() => {
- const group: IMenuGroup[] = [];
- for (const position of positions) {
- const menuItems = menuService.getMenuItems(position);
-
- if (menuItems.length) {
- group.push({
- name: position,
- menuItems,
- });
- }
- }
-
- setGroup(group);
- });
-
- return () => {
- listener.unsubscribe();
- };
- }, [position]);
-
- useEffect(() => {
- function resize() {
- const wrapperWidth = toolbarRef.current?.clientWidth ?? 0;
- const GAP = 8;
-
- const itemWidths = Object.entries(toolbarItemRefs.current)
- .filter(([_, ref]) => {
- return ref.el && ref.key && visibleItems.find((item) => item.id === ref.key);
- })
- .map(([_, ref]) => {
- return {
- key: ref.key,
- width: ref.el?.clientWidth + GAP,
- };
- });
-
- const collapsedId: string[] = [];
-
- let currentWidth = 182;
- for (const item of itemWidths) {
- currentWidth += item.width;
-
- if (currentWidth > wrapperWidth) {
- collapsedId.push(item.key);
- }
- }
-
- setCollapsedId(collapsedId);
- }
-
- resize();
- const observer = new ResizeObserver(() => resize());
-
- observer.observe(document.body);
-
- return () => {
- observer.unobserve(document.body);
- };
- }, [visibleItems, group, position]);
-
- const toolbarGroups = useMemo(() => {
- return group
- .find((g) => g.name === position)
- ?.menuItems.reduce(
- (acc, item) => {
- const key = item.group ?? MenuGroup.TOOLBAR_OTHERS;
- if (!acc[key]) {
- acc[key] = [];
- }
- acc[key].push(item);
- return acc;
- },
- {} as Record<MenuGroup, Array<IDisplayMenuItem<IMenuItem>>>
- ) ?? ({} as Record<MenuGroup, Array<IDisplayMenuItem<IMenuItem>>>);
- }, [group]);
+ const { setCategory, visibleItems, groups, category, groupsByKey } = useToolbarGroups(MENU_POSITIONS);
+ const { toolbarItemRefs, toolbarRef, collapsedId } = useToolbarCollapseObserver(visibleItems);
- const hasHeaderMenu = useMemo(() => (headerMenuComponents && headerMenuComponents.size > 0) || group.length > 1, [headerMenuComponents, group]);
+ // Should the header when there is at least one header menu components or menu groups.
+ const hasHeaderMenu = useMemo(() => (headerMenuComponents && headerMenuComponents.size > 0) || groups.length > 1, [headerMenuComponents, groups]);
return (
<>
@@ -174,15 +61,15 @@ export function Toolbar(props: IToolbarProps) {
? (
<header className={styles.headerbar}>
<div className={styles.menubar}>
- {group.length > 1 &&
- group.map((item, index) => (
+ {groups.length > 1 &&
+ groups.map((item, index) => (
<a
key={index}
className={clsx(styles.menubarItem, {
- [styles.menubarItemActive]: item.name === position,
+ [styles.menubarItemActive]: item.name === category,
})}
onClick={() => {
- setPosition(item.name);
+ setCategory(item.name);
}}
>
{localeService.t(item.name)}
@@ -198,7 +85,7 @@ export function Toolbar(props: IToolbarProps) {
<div ref={toolbarRef} className={styles.toolbar}>
<div className={styles.toolbarContainer}>
- {Object.entries(toolbarGroups)
+ {Object.entries(groupsByKey)
.filter(([_, item]) => {
const count = item.filter((subItem) => !collapsedId.includes(subItem.id)).length;
return count;
@@ -221,7 +108,7 @@ export function Toolbar(props: IToolbarProps) {
className={styles.toolbarMore}
overlay={(
<div className={styles.toolbarMoreContainer} onClick={(e) => e.stopPropagation()}>
- {Object.entries(toolbarGroups).map(([key, item]) => (
+ {Object.entries(groupsByKey).map(([key, item]) => (
<div key={key} className={styles.toolbarGroup}>
{item.map(
(subItem) =>
@@ -253,9 +140,10 @@ export function Toolbar(props: IToolbarProps) {
opacity: 0,
}}
>
- {Object.entries(toolbarGroups).map(([key, item]) => (
+ {Object.entries(groupsByKey).map(([key, item]) => (
<div key={key} className={styles.toolbarGroup}>
{item.map((subItem) => (
+ // TODO@jikkai: use fake ToolbarItem (no business logic) to improve performance.
<ToolbarItem
key={subItem.id}
ref={(ref) => {
diff --git a/packages/ui/src/views/components/doc-bars/ToolbarItem.tsx b/packages/ui/src/views/components/doc-bars/ToolbarItem.tsx
index ba8e08b261..03c6a3350d 100644
--- a/packages/ui/src/views/components/doc-bars/ToolbarItem.tsx
+++ b/packages/ui/src/views/components/doc-bars/ToolbarItem.tsx
@@ -20,8 +20,7 @@ import { ITextSelectionRenderManager } from '@univerjs/engine-render';
import { MoreDownSingle } from '@univerjs/icons';
import { useDependency, useInjector } from '@wendellhu/redi/react-bindings';
import type { Ref } from 'react';
-import React, { forwardRef, useEffect, useMemo, useState } from 'react';
-import type { Subscription } from 'rxjs';
+import React, { forwardRef, useMemo, useState } from 'react';
import { isObservable, Observable } from 'rxjs';
import clsx from 'clsx';
@@ -33,19 +32,17 @@ import type { IDisplayMenuItem, IMenuItem, IMenuSelectorItem, IValueOption } fro
import { MenuItemType } from '../../../services/menu/menu';
import { ToolbarButton } from './Button/ToolbarButton';
import styles from './index.module.less';
+import { useToolbarItemStatus } from './hook';
export const ToolbarItem = forwardRef((props: IDisplayMenuItem<IMenuItem>, ref: Ref<any>) => {
const localeService = useDependency(LocaleService);
const commandService = useDependency(ICommandService);
const injector = useInjector();
- const [value, setValue] = useState<any>();
- const [disabled, setDisabled] = useState(false);
- const [activated, setActivated] = useState(false);
- const [hidden, setHidden] = useState(false);
-
const [tooltipVisible, setTooltipVisible] = useState(false);
const [dropdownVisible, setDropdownVisible] = useState(false);
+ const { value, hidden, disabled, activated } = useToolbarItemStatus(props);
+
const handleCommandExecuted = (commandId: string, params?: Record<string, any>) => {
commandService.executeCommand(commandId, params);
const textSelectionRenderManager = injector.get(ITextSelectionRenderManager);
@@ -64,44 +61,6 @@ export const ToolbarItem = forwardRef((props: IDisplayMenuItem<IMenuItem>, ref:
}
}
- useEffect(() => {
- const subscriptions: Subscription[] = [];
-
- props.disabled$ &&
- subscriptions.push(
- props.disabled$.subscribe((disabled) => {
- setDisabled(disabled);
- })
- );
-
- props.hidden$ &&
- subscriptions.push(
- props.hidden$.subscribe((hidden) => {
- setHidden(hidden);
- })
- );
-
- props.activated$ &&
- subscriptions.push(
- props.activated$.subscribe((activated) => {
- setActivated(activated);
- })
- );
-
- props.value$ &&
- subscriptions.push(
- props.value$.subscribe((value) => {
- setValue(value);
- })
- );
-
- return () => {
- subscriptions.forEach((subscription) => {
- subscription.unsubscribe();
- });
- };
- }, []);
-
const { tooltip, shortcut, icon, title, label, id } = props;
const tooltipTitle = localeService.t(tooltip ?? '') + (shortcut ? ` (${shortcut})` : '');
diff --git a/packages/ui/src/views/components/doc-bars/hook.ts b/packages/ui/src/views/components/doc-bars/hook.ts
new file mode 100644
index 0000000000..d2656c2c90
--- /dev/null
+++ b/packages/ui/src/views/components/doc-bars/hook.ts
@@ -0,0 +1,193 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { useEffect, useMemo, useRef, useState } from 'react';
+import type { Subscription } from 'rxjs';
+import { combineLatest, map, Observable } from 'rxjs';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import { type IDisplayMenuItem, type IMenuItem, MenuGroup, MenuPosition } from '../../../services/menu/menu';
+import { IMenuService } from '../../../services/menu/menu.service';
+
+type MenuPositionWithCustom = MenuPosition | string;
+
+export interface IMenuGroup {
+ name: MenuPositionWithCustom;
+ menuItems: Array<IDisplayMenuItem<IMenuItem>>;
+}
+
+export interface IToolbarRenderHookHandler {
+ /** The activated category. */
+ category: MenuPositionWithCustom;
+
+ /** Update current activate category. */
+ setCategory: (position: MenuPositionWithCustom) => void;
+
+ visibleItems: IDisplayMenuItem<IMenuItem>[];
+
+ /** Menu grouped in this category. */
+ groups: IMenuGroup[];
+
+ groupsByKey: Record<MenuGroup, Array<IDisplayMenuItem<IMenuItem>>>;
+}
+
+/**
+ * If your custom toolbar component need to render menu items by their category,
+ * you can use this hook to get the toolbar status.
+ * @returns toolbar status
+ */
+export function useToolbarGroups(categories: MenuPositionWithCustom[]): IToolbarRenderHookHandler {
+ const menuService = useDependency(IMenuService);
+ const [category, setCategory] = useState<MenuPositionWithCustom>(MenuPosition.TOOLBAR_START);
+ const [groups, setGroups] = useState<IMenuGroup[]>([]);
+ const [visibleItems, setVisibleItems] = useState<IDisplayMenuItem<IMenuItem>[]>([]);
+
+ // Update visible menu items when the active group changes or the visibility of an item (hidden$) changes.
+ useEffect(() => {
+ const activeItems = groups.find((g) => g.name === category)?.menuItems ?? [];
+ const filteredItems$ = combineLatest(
+ activeItems.map((item) => item.hidden$ ?? new Observable((observer) => observer.next(false)))
+ ).pipe(map((hiddenValues) => activeItems.filter((_, index) => !hiddenValues[index])));
+
+ const s = filteredItems$.subscribe((items) => setVisibleItems(items));
+ return () => s.unsubscribe();
+ }, [groups, category]);
+
+ // Update menu items when new items get registered or old items get unregistered.
+ useEffect(() => {
+ const s = menuService.menuChanged$.subscribe(() => {
+ const group: IMenuGroup[] = [];
+ for (const position of categories) {
+ const menuItems = menuService.getMenuItems(position);
+ if (menuItems.length) {
+ group.push({ name: position, menuItems });
+ }
+ }
+
+ setGroups(group);
+ });
+
+ return () => s.unsubscribe();
+ }, [menuService, category, categories]);
+
+ const groupsByKey = useMemo(() => {
+ return groups.find((g) => g.name === category)?.menuItems.reduce(
+ (acc, item) => {
+ const key = item.group ?? MenuGroup.TOOLBAR_OTHERS;
+ if (!acc[key]) {
+ acc[key] = [];
+ }
+
+ acc[key].push(item);
+ return acc;
+ },
+ {} as Record<MenuGroup, Array<IDisplayMenuItem<IMenuItem>>>
+ ) ?? ({} as Record<MenuGroup, Array<IDisplayMenuItem<IMenuItem>>>);
+ }, [groups, category]);
+
+ return {
+ setCategory,
+ category,
+ visibleItems,
+ groups,
+ groupsByKey,
+ };
+}
+
+export interface IToolbarItemStatus {
+ disabled: boolean;
+ // eslint-disable-next-line ts/no-explicit-any
+ value: any;
+ activated: boolean;
+ hidden: boolean;
+}
+
+// TODO@wzhudev: maybe we should use `useObservable` here.
+
+/**
+ * Subscribe to a menu item's status change and return the latest status.
+ * @param menuItem The menu item
+ * @returns The menu item's status
+ */
+export function useToolbarItemStatus(menuItem: IDisplayMenuItem<IMenuItem>): IToolbarItemStatus {
+ const { disabled$, hidden$, activated$, value$ } = menuItem;
+
+ // eslint-disable-next-line ts/no-explicit-any
+ const [value, setValue] = useState<any>();
+ const [disabled, setDisabled] = useState(false);
+ const [activated, setActivated] = useState(false);
+ const [hidden, setHidden] = useState(false);
+
+ useEffect(() => {
+ const subscriptions: Subscription[] = [];
+
+ disabled$ && subscriptions.push(disabled$.subscribe((disabled) => setDisabled(disabled)));
+ hidden$ && subscriptions.push(hidden$.subscribe((hidden) => setHidden(hidden)));
+ activated$ && subscriptions.push(activated$.subscribe((activated) => setActivated(activated)));
+ value$ && subscriptions.push(value$.subscribe((value) => setValue(value)));
+
+ return () => subscriptions.forEach((subscription) => subscription.unsubscribe()); ;
+ }, [activated$, disabled$, hidden$, value$]);
+
+ return { disabled, value, activated, hidden };
+}
+
+export function useToolbarCollapseObserver(visibleItems: IToolbarRenderHookHandler['visibleItems']) {
+ const toolbarItemRefs = useRef<Record<string, {
+ el: HTMLDivElement;
+ key: string;
+ }>>({});
+
+ const toolbarRef = useRef<HTMLDivElement>(null);
+ const [collapsedId, setCollapsedId] = useState<string[]>([]);
+
+ // Deal with toolbar collapsing.
+ useEffect(() => {
+ function resize() {
+ const wrapperWidth = toolbarRef.current?.clientWidth ?? 0;
+ const GAP = 8;
+ const itemWidths = Object.entries(toolbarItemRefs.current)
+ .filter(([_, ref]) => ref.el && ref.key && visibleItems.find((item) => item.id === ref.key))
+ .map(([_, ref]) => ({
+ key: ref.key,
+ width: ref.el?.clientWidth + GAP,
+ }));
+
+ const collapsedId: string[] = [];
+
+ let currentWidth = 182;
+ for (const item of itemWidths) {
+ currentWidth += item.width;
+
+ if (currentWidth > wrapperWidth) {
+ collapsedId.push(item.key);
+ }
+ }
+
+ setCollapsedId(collapsedId);
+ }
+
+ resize();
+ const observer = new ResizeObserver(() => resize());
+ observer.observe(document.body);
+ return () => observer.unobserve(document.body);
+ }, [visibleItems]);
+
+ return {
+ toolbarRef,
+ toolbarItemRefs,
+ collapsedId,
+ };
+}