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.

refactor(base-ui): change to function component,fix forwardRef (#134)

Dushusir4884e082b794
diff --git a/packages/base-ui/src/Components/ColorPicker/ColorPicker.tsx b/packages/base-ui/src/Components/ColorPicker/ColorPicker.tsx
index 127667b4ff..8120d5bc0d 100644
--- a/packages/base-ui/src/Components/ColorPicker/ColorPicker.tsx
+++ b/packages/base-ui/src/Components/ColorPicker/ColorPicker.tsx
@@ -240,7 +240,7 @@ export function ColorPicker(props: BaseColorPickerProps) {
const [style, setStyles] = useState({});
const [currentLocale, setCurrentLocale] = useState('');
const [root, setRoot] = useState(null);
- const [show, setShow] = useState(props.show || false);
+ // const [show, setShow] = useState(props.show || false);
useEffect(() => {
setPresetColors(allColor);
@@ -253,14 +253,14 @@ export function ColorPicker(props: BaseColorPickerProps) {
setRoot(null);
}, [props.color]);
- useEffect(() => {
- const { show = false } = props;
- setShow(show);
+ // useEffect(() => {
+ // const { show = false } = props;
+ // setShow(show);
- if (show) {
- document.addEventListener('click', hideSelect, true);
- }
- }, [props.show]);
+ // // if (show) {
+ // // document.addEventListener('click', hideSelect, true);
+ // // }
+ // }, [props.show]);
const onChange = (presetColor: string) => {
props.onChange && props.onChange(presetColor);
@@ -276,14 +276,14 @@ export function ColorPicker(props: BaseColorPickerProps) {
props.onCancel && props.onCancel();
};
- const hideSelect = (e?: MouseEvent) => {
- console.info('hide color picker. If it triggers too frequently, it needs to be corrected');
- if (e && ulRef.current && ulRef.current.contains(e.target as Node)) return;
+ // const hideSelect = (e?: MouseEvent) => {
+ // console.info('hide color picker. If it triggers too frequently, it needs to be corrected');
+ // if (e && ulRef.current && ulRef.current.contains(e.target as Node)) return;
- setShow(false);
+ // setShow(false);
- document.removeEventListener('click', hideSelect, true);
- };
+ // document.removeEventListener('click', hideSelect, true);
+ // };
/**
* TODO handle ele?
@@ -332,7 +332,7 @@ export function ColorPicker(props: BaseColorPickerProps) {
const obj = Object.assign(style || {}, props.style);
return (
- <div className={`${styles.colorPickerOuter} ${props.className}`} ref={ulRef} style={{ ...obj, display: show ? 'block' : 'none' }}>
+ <div className={`${styles.colorPickerOuter} ${props.className}`} ref={ulRef} style={{ ...obj }}>
<div className={styles.colorPicker}>
<div className={styles.picker}>
<div className={styles.pickerSwatches}>
diff --git a/packages/base-ui/src/Components/Dropdown/Dropdown.tsx b/packages/base-ui/src/Components/Dropdown/Dropdown.tsx
index ab515ac474..b893259658 100644
--- a/packages/base-ui/src/Components/Dropdown/Dropdown.tsx
+++ b/packages/base-ui/src/Components/Dropdown/Dropdown.tsx
@@ -93,6 +93,7 @@
// };
// }
// }
+import { IKeyValue } from '@univerjs/core';
import React, { useEffect, useRef, useState } from 'react';
import { Icon } from '..';
@@ -114,8 +115,7 @@ export interface BaseDropdownProps {
content?: React.ReactNode;
}
-export function Dropdown(props: BaseDropdownProps) {
- // const MenuRef = useRef<Menu>(null);
+export const Dropdown = (props: BaseDropdownProps) => {
const DropRef = useRef<HTMLDivElement>(null);
const IconRef = useRef<HTMLDivElement>(null);
const [menuStyle, setMenuStyle] = useState<Record<string, string | number>>({});
@@ -126,24 +126,22 @@ export function Dropdown(props: BaseDropdownProps) {
props.onMainClick?.();
const { icon } = props;
if (!icon) {
- // MenuRef.current?.showMenu(true);
- setMenuShow(true);
+ showMenu();
}
};
- const handleSubClick = () => {
- console.info('show');
- // MenuRef.current?.showMenu(true);
+ const showMenu = () => {
setMenuShow(true);
+ window.addEventListener('click', hideMenuClick, true);
};
const hideMenu = () => {
- // MenuRef.current?.showMenu(false);
setMenuShow(false);
+ window.removeEventListener('click', hideMenuClick, true);
};
const hideMenuClick = (e: MouseEvent) => {
- if (!DropRef.current || !DropRef.current?.contains(e.target as Node)) {
+ if (!(DropRef as IKeyValue).current || !(DropRef as IKeyValue).current?.contains(e.target as Node)) {
hideMenu();
}
};
@@ -165,11 +163,6 @@ export function Dropdown(props: BaseDropdownProps) {
style.top = 0;
}
setMenuStyle(style);
- window.addEventListener('click', hideMenuClick, true);
-
- return () => {
- window.removeEventListener('click', hideMenuClick, true);
- };
}, [props.placement]);
return (
<div className={styles.dropdown} ref={DropRef}>
@@ -180,7 +173,7 @@ export function Dropdown(props: BaseDropdownProps) {
</div>
</Tooltip>
{props.icon && (
- <div ref={IconRef} className={styles.dropIcon} onClick={handleSubClick}>
+ <div ref={IconRef} className={styles.dropIcon} onClick={showMenu}>
{props.icon}
</div>
)}
@@ -190,7 +183,6 @@ export function Dropdown(props: BaseDropdownProps) {
options={props.menu.options}
display={props.menu.display}
onClick={props.menu.onClick}
- // ref={MenuRef}
value={props.menu.value}
menu={props.menu.menu}
className={props.menu.className}
@@ -203,4 +195,4 @@ export function Dropdown(props: BaseDropdownProps) {
></Menu>
</div>
);
-}
+};
diff --git a/packages/base-ui/src/Components/Menu/Menu.tsx b/packages/base-ui/src/Components/Menu/Menu.tsx
index 6ffb7b7032..0ca2ebfa35 100644
--- a/packages/base-ui/src/Components/Menu/Menu.tsx
+++ b/packages/base-ui/src/Components/Menu/Menu.tsx
@@ -342,8 +342,8 @@
// }
// }
// }
-import { ICommandService, IKeyValue, isRealNum } from '@univerjs/core';
-import React, { forwardRef, Ref, useContext, useEffect, useState } from 'react';
+import { ICommandService, isRealNum } from '@univerjs/core';
+import React, { useContext, useEffect, useRef, useState } from 'react';
import { Subscription } from 'rxjs';
import { AppContext } from '../../Common/AppContext';
@@ -363,11 +363,7 @@ export interface BaseMenuProps {
/** @deprecated */
style?: React.CSSProperties;
/** @deprecated */
- parent?: any;
- /** @deprecated */
- dom?: HTMLElement;
- /** @deprecated */
- ref?: any;
+ parent?: boolean;
/** @deprecated */
deep?: number;
/** @deprecated this is legacy menu mechanism. Do not use it. Use `menuItems` instead. */
@@ -381,13 +377,12 @@ export interface BaseMenuProps {
options?: Array<IValueOption | ICustomComponentOption>;
onOptionSelect?: (option: IValueOption) => void;
show?: boolean;
+ clientPosition?: {
+ clientX: number;
+ clientY: number;
+ }; //Right-click menu adaptive position, send the location of the mouse click
}
-export type BaseMenuState = {
- show: boolean;
- posStyle: BaseMenuStyle;
-};
-
export type BaseMenuStyle = {
left?: string;
right?: string;
@@ -436,16 +431,13 @@ export type BaseMenuStyle = {
// onOptionSelect?: (option: IValueOption) => void;
// }
-// TODODushusir remove forwardRef
-export const Menu = forwardRef((props: BaseMenuProps, MenuRef: Ref<HTMLUListElement>) => {
- const { display, menuId, value, options, onOptionSelect, dom, parent, onClick, deep = 0, menu = [], className = '', style = {}, show = false } = props;
+export const Menu = (props: BaseMenuProps) => {
+ const { display, menuId, value, options, onOptionSelect, parent, onClick, deep = 0, menu = [], className = '', style = {}, show = false, clientPosition } = props;
const context = useContext(AppContext);
const [isShow, setIsShow] = useState(show);
const [posStyle, setPosStyle] = useState<BaseMenuStyle>({});
const [menuItems, setMenuItems] = useState<Array<IDisplayMenuItem<IMenuItem>>>([]);
- // const MenuRef = useRef<HTMLUListElement | null>(null);
- // const refs: Array<React.RefObject<Menu>> = []; // FIXME type error
- const refs: Array<React.RefObject<IKeyValue>> = [];
+ const MenuRef = useRef<HTMLUListElement | null>(null);
useEffect(() => {
getSubMenus();
@@ -453,50 +445,40 @@ export const Menu = forwardRef((props: BaseMenuProps, MenuRef: Ref<HTMLUListElem
useEffect(() => {
const { show = false } = props;
- setIsShow(show);
- }, [show]);
+ showMenu(show);
+ }, [props.show]);
- const handleClick = (e: MouseEvent, item: BaseMenuItem, index: number) => {
- item.onClick?.call(null, e, item.label, index, deep);
- onClick?.call(null, e, item.value, index, deep);
- setIsShow(false);
- };
+ useEffect(() => {
+ const { clientPosition } = props;
+ if (!clientPosition) return;
+ const { clientX = 0, clientY = 0 } = clientPosition;
+ setAutoPosition(clientX, clientY);
+ }, [props.clientPosition]);
+
+ // const handleClick = (e: MouseEvent, item: BaseMenuItem, index: number) => {
+ // item.onClick?.call(null, e, item.label, index, deep);
+ // onClick?.call(null, e, item.value, index, deep);
+ // setIsShow(false);
+ // };
const showMenu = (show: boolean) => {
setIsShow(show);
getStyle();
};
- const mouseEnter = (e: MouseEvent, index: number) => {
- if (menu[index] && menu[index].hasOwnProperty('children')) {
- refs[index].current?.showMenu(true);
- }
- };
-
- const mouseLeave = (e: MouseEvent, index: number) => {
- if (menu[index] && menu[index].hasOwnProperty('children')) {
- refs[index].current?.showMenu(false);
- }
- };
-
const getStyle = () => {
- const current = (MenuRef as IKeyValue).current;
+ const current = MenuRef.current;
if (!current) return;
const style: BaseMenuStyle = {};
const curPosition = current.getBoundingClientRect();
- let docPosition;
-
- if (dom) {
- docPosition = dom.getBoundingClientRect();
- } else {
- docPosition = {
- left: 0,
- right: document.documentElement.clientWidth,
- top: 0,
- bottom: document.documentElement.clientHeight,
- };
- }
+ const docPosition = {
+ left: 0,
+ right: document.documentElement.clientWidth,
+ top: 0,
+ bottom: document.documentElement.clientHeight,
+ };
+ // Nested submenus
if (parent) {
current.style.position = 'fixed';
const parPosition = current.parentElement?.getBoundingClientRect();
@@ -516,8 +498,48 @@ export const Menu = forwardRef((props: BaseMenuProps, MenuRef: Ref<HTMLUListElem
}
};
- const handleItemClick = (item: IMenuButtonItem) => {
- showMenu(false);
+ const setAutoPosition = (clientX: number, clientY: number) => {
+ const current = MenuRef.current;
+ if (!current) return;
+ const style: BaseMenuStyle = {};
+ const curPosition = current.getBoundingClientRect();
+ const docPosition = {
+ left: 0,
+ right: document.documentElement.clientWidth,
+ top: 0,
+ bottom: document.documentElement.clientHeight,
+ };
+
+ const screenW = docPosition.right;
+ const screenH = docPosition.bottom;
+ const clickX = clientX;
+ const clickY = clientY;
+ const rootW = curPosition.width;
+ const rootH = curPosition.height;
+
+ // right is true, which means that the width from the mouse click position to the right border of the browser can be used to place the menu. Otherwise, the menu is moved to the left.
+ // bottom is true, which means that the menu can be dropped from the height of the mouse click position to the lower border of the browser. Otherwise, the menu is placed above.
+ const right = screenW - clickX > rootW;
+ const left = !right;
+ const bottom = screenH - clickY > rootH;
+ const top = !bottom;
+
+ if (right) {
+ style.left = `${clickX}px`;
+ }
+
+ if (left) {
+ style.left = `${clickX - rootW}px`;
+ }
+
+ if (bottom) {
+ style.top = `${clickY}px`;
+ }
+ if (top) {
+ style.top = `${clickY - rootH}px`;
+ }
+
+ setPosStyle(style);
};
const getSubMenus = () => {
@@ -564,7 +586,6 @@ export const Menu = forwardRef((props: BaseMenuProps, MenuRef: Ref<HTMLUListElem
<CustomComponent
onValueChange={(v: string | number) => {
onOptionSelect?.({ value: v, label: option.id });
- showMenu(false);
}}
/>
</li>
@@ -572,11 +593,18 @@ export const Menu = forwardRef((props: BaseMenuProps, MenuRef: Ref<HTMLUListElem
})}
{/* render submenus */}
{menuItems?.map((item: IDisplayMenuItem<IMenuItem>, index) => (
- <MenuItem menuItem={item} key={index} index={index} onClick={() => handleItemClick(item as IMenuButtonItem)} />
+ <MenuItem
+ menuItem={item}
+ key={index}
+ index={index}
+ onClick={() => {
+ onOptionSelect?.({ value: item.id, label: item.title });
+ }}
+ />
))}
</ul>
);
-});
+};
export interface IMenuItemProps {
menuItem: IDisplayMenuItem<IMenuItem>;
@@ -597,15 +625,14 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
const [menuItems, setMenuItems] = useState<Array<IDisplayMenuItem<IMenuItem>>>([]);
const [disabledSubscription, setDisabledSubscription] = useState<Subscription | undefined>();
const [valueSubscription, setValueSubscription] = useState<Subscription | undefined>();
- // const _refs: Menu[] = [];
- const _refs: IKeyValue[] = [];
+ const [itemShow, setItemShow] = useState<boolean>(false);
const mouseEnter = (e: React.MouseEvent<HTMLLIElement, MouseEvent>, index: number) => {
- _refs[index]?.showMenu(true);
+ setItemShow(true);
};
const mouseLeave = (e: React.MouseEvent<HTMLLIElement, MouseEvent>, index: number) => {
- _refs[index]?.showMenu(false);
+ setItemShow(false);
};
const getSubMenus = () => {
@@ -617,13 +644,13 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
}
};
- const handleClick = (e: React.MouseEvent<HTMLLIElement, MouseEvent>, item: IDisplayMenuItem<IMenuItem>, index: number) => {
- // const commandService: ICommandService = context.injector.get(ICommandService);
- onClick();
+ // const handleClick = (e: React.MouseEvent<HTMLLIElement, MouseEvent>, item: IDisplayMenuItem<IMenuItem>, index: number) => {
+ // // const commandService: ICommandService = context.injector.get(ICommandService);
+ // onClick();
- const itemValue = value;
- // !(item.subMenuItems && item.subMenuItems.length > 0) && commandService.executeCommand(item.id, { value });
- };
+ // const itemValue = value;
+ // // !(item.subMenuItems && item.subMenuItems.length > 0) && commandService.executeCommand(item.id, { value });
+ // };
/**
* user input change value from CustomLabel
@@ -702,18 +729,21 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
className={joinClassNames(styles.colsMenuitem, disabled ? styles.colsMenuitemDisabled : '')}
onMouseEnter={(e) => mouseEnter(e, index)}
onMouseLeave={(e) => mouseLeave(e, index)}
- onClick={(e) => handleClick(e, item, index)}
+ // onClick={(e) => handleClick(e, item, index)} // Nested select without click events, like border style
>
<NeoCustomLabel title={item.title} value={value} onChange={onChange} icon={item.icon} display={item.display} label={item.label}></NeoCustomLabel>
{item.shortcut && ` (${item.shortcut})`}
{(menuItems.length > 0 || (item as IMenuSelectorItem<unknown>).selections?.length) && (
<Menu
- ref={(ele: HTMLUListElement) => (_refs[index] = ele)}
- onOptionSelect={(v) => commandService.executeCommand(item.id, { value: v.value })}
+ show={itemShow}
+ onOptionSelect={(v) => {
+ commandService.executeCommand(item.id, { value: v.value });
+ // onClick(); // border style don't trigger hide menu
+ }}
menuId={item.id}
options={item.selections}
display={item.display}
- // parent={this}
+ parent={true}
></Menu>
)}
</li>
@@ -728,12 +758,11 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
className={joinClassNames(styles.colsMenuitem, disabled ? styles.colsMenuitemDisabled : '')}
onMouseEnter={(e) => mouseEnter(e, index)}
onMouseLeave={(e) => mouseLeave(e, index)}
- onClick={(e) => handleClick(e, item, index)}
+ // onClick={(e) => handleClick(e, item, index)} // Nested menus without click events, like right menu delete cell
>
<NeoCustomLabel title={item.title} value={item.title} icon={item.icon} display={item.display} label={item.label}></NeoCustomLabel>
{(menuItems.length > 0 || (item as IMenuSelectorItem<unknown>).selections?.length) && (
- // <Menu ref={(ele: Menu) => (_refs[index] = ele)} menuId={item.id} parent={this} display={item.display}></Menu>
- <Menu ref={(ele: HTMLUListElement) => (_refs[index] = ele)} menuId={item.id} display={item.display}></Menu>
+ <Menu show={itemShow} menuId={item.id} display={item.display} parent={true} onOptionSelect={onClick}></Menu>
)}
</li>
);
diff --git a/packages/base-ui/src/Components/Select/Select.tsx b/packages/base-ui/src/Components/Select/Select.tsx
index 0f8f0743be..6df2751c0a 100644
--- a/packages/base-ui/src/Components/Select/Select.tsx
+++ b/packages/base-ui/src/Components/Select/Select.tsx
@@ -1,12 +1,331 @@
-import { ComponentChildren, createRef, RefObject, PureComponent } from 'react';
-import { AppContext, ICustomComponent } from '../../Common';
-import { BaseMenuItem } from '../../Interfaces';
+// interface IState {
+// menu: BaseMenuItem[];
+// color: string; // TODO@wzhudev: this state is strange
+// content: ComponentChildren;
+// // eslint-disable-next-line @typescript-eslint/no-explicit-any
+// value: any;
+// }
+// export class Select extends PureComponent<BaseSelectProps, IState> {
+// static override contextType = AppContext;
+// // eslint-disable-next-line @typescript-eslint/no-explicit-any
+// ColorRef: any;
+// // eslint-disable-next-line @typescript-eslint/no-explicit-any
+// onClick: (...arg: any) => void;
+// // eslint-disable-next-line @typescript-eslint/no-explicit-any
+// onPressEnter: (...arg: any[]) => void;
+// constructor(props: BaseSelectProps) {
+// super(props);
+// this.initialize();
+// }
+// initialize() {
+// const { children = [], hideSelectedIcon } = this.props;
+// const list = this.resetMenu(children, hideSelectedIcon);
+// this.state = {
+// menu: list,
+// color: this.props.defaultColor ?? '#000',
+// content: '',
+// value: '',
+// };
+// }
+// getType(type: SelectTypes) {
+// switch (type) {
+// case SelectTypes.SINGLE:
+// return this.getSingle();
+// case SelectTypes.INPUT:
+// return this.getInput();
+// case SelectTypes.DOUBLE:
+// return this.getDouble();
+// case SelectTypes.FIX:
+// return this.getFix();
+// case SelectTypes.DOUBLE_FIX:
+// return this.getDoubleFix();
+// case SelectTypes.NEO:
+// return this.renderNeo();
+// }
+// }
+// // eslint-disable-next-line max-lines-per-function
+// initData() {
+// const { type, display, children = [], label } = this.props;
+// // TODO@wzhudev: the way of binding onClick is ridiculous. Fix it.
+// // 显示值可变
+// if (type === 0 || type === 3) {
+// if (!children.length) return;
+// let index = children.findIndex((item) => item.selected);
+// if (index < 0) index = 0;
+// const list = this.handleSelected(index);
+// const item = children[index];
+// if (display === DisplayTypes.SUFFIX) {
+// this.setState({
+// content: item.suffix,
+// menu: list,
+// });
+// } else {
+// this.setState({
+// content: item.label,
+// menu: list,
+// });
+// }
+// this.onClick = (...arg) => {
+// const item = children[arg[2]];
+// this.props.onClick?.(arg[1], arg[2], arg[3]);
+// if (item.unSelectable) {
+// return;
+// }
+// const list = this.handleSelected(arg[2]);
+// if (display === DisplayTypes.SUFFIX) {
+// this.setState({
+// content: children[arg[2]].suffix,
+// menu: list,
+// });
+// } else {
+// this.setState({
+// content: children[arg[2]].label,
+// menu: list,
+// });
+// }
+// };
+// } else if (type === 1) {
+// // 输入框
+// if (!children.length) return;
+// // 匹配label和选项label确定选中项
+// const getLabel = (label: ComponentChildren) => {
+// if (label !== null) {
+// if (label === '') return;
+// const index = children.findIndex((item) => label === item.label);
+// const list = this.handleSelected(index < 0 ? null : index);
+// this.setState({
+// content: label,
+// menu: list,
+// });
+// } else {
+// let index = children.findIndex((item) => item.selected);
+// if (index < 0) index = 0;
+// const list = this.handleSelected(index);
+// const item = children[index];
+// this.setState({
+// content: item.label,
+// menu: list,
+// });
+// }
+// };
+// getLabel(label);
+// this.onClick = (...arg) => {
+// this.props.onClick?.(arg[1], arg[2], arg[3]);
+// const list = this.handleSelected(arg[2]);
+// this.setState({
+// content: children[arg[2]].label,
+// menu: list,
+// });
+// };
+// this.onPressEnter = (e: KeyboardEvent) => {
+// const value = (e.currentTarget as HTMLInputElement).value;
+// this.props.onPressEnter?.(value);
+// getLabel(value);
+// };
+// } else if (type === 2) {
+// // 颜色选择器
+// const list = this.handleSelected(null);
+// this.setState({
+// menu: list,
+// });
+// this.onClick = () => {
+// const { color } = this.state;
+// this.props.onClick?.(color);
+// };
+// } else if (type === 4 || type === 5) {
+// //固定显示值
+// if (!children.length) return;
+// let index = children.findIndex((item) => item.selected);
+// if (index < 0) index = 0;
+// const item = children[index];
+// const list = this.handleSelected(index);
+// this.setState({
+// menu: list,
+// value: item.value,
+// });
+// this.onClick = (...arg) => {
+// if (arg.length) {
+// this.props.onClick?.(arg[1], arg[2], arg[3]);
+// const list = this.handleSelected(arg[2]);
+// this.setState({
+// menu: list,
+// value: children[arg[2]].value,
+// });
+// } else {
+// this.props.onClick?.(this.state.value);
+// }
+// };
+// }
+// }
+// updateData() {
+// if (this.props.type === SelectTypes.INPUT) {
+// this.setState({ content: this.props.label });
+// }
+// }
+// override componentDidMount() {
+// this.initData();
+// }
+// override UNSAFE_componentWillReceiveProps(nextProps: BaseSelectProps) {
+// this.updateData();
+// }
+// resetMenu(children: BaseSelectChildrenProps[], hideSelectedIcon?: boolean) {
+// const list: BaseMenuItem[] = [];
+// // TODO@wzhudev: ID prop is not handled
+// for (let i = 0; i < children.length; i++) {
+// let selected = false;
+// if (!hideSelectedIcon) {
+// selected = children[i].selected ?? false;
+// }
+// list[i] = { label: '' };
+// list[i].label = <Item disabled={children[i].disabled} border={children[i].border} selected={selected} label={children[i].label} suffix={children[i].suffix}></Item>;
+// list[i].disabled = children[i].disabled;
+// list[i].style = children[i].style;
+// list[i].value = children[i].value;
+// list[i].className = children[i].className;
+// list[i].onClick = children[i].onClick;
+// list[i].border = children[i].border;
+// if (children[i].children) {
+// list[i].children = this.resetMenu(children[i].children!);
+// }
+// }
+// return list;
+// }
+// // 处理选中
+// handleSelected = (index: number | null): BaseMenuItem[] | undefined => {
+// const { children = [], hideSelectedIcon } = this.props;
+// if (children.length) {
+// children.forEach((item) => {
+// item.selected = false;
+// });
+// if (index !== null) {
+// children[index].selected = true;
+// }
+// }
+// const list = this.resetMenu(children, hideSelectedIcon);
+// return list;
+// };
+// // 普通下拉
+// getSingle = () => {
+// const { content, menu } = this.state;
+// const { className = '', tooltip, onMainClick } = this.props;
+// return (
+// <div className={`${styles.selectSingle} ${className}`}>
+// <Dropdown onMainClick={onMainClick} tooltip={tooltip} menu={{ menu, onClick: this.onClick }} showArrow>
+// <div>
+// <CustomLabel label={content} />
+// </div>
+// </Dropdown>
+// </div>
+// );
+// };
+// handlePressEnter = (e: KeyboardEvent, ref: RefObject<Dropdown>) => {
+// this.onPressEnter(e);
+// ref.current?.hideMenu();
+// };
+// //Input下拉
+// getInput = () => {
+// const { content, menu } = this.state;
+// const { className = '', tooltip, onMainClick } = this.props;
+// const ref = createRef<Dropdown>();
+// return (
+// <div className={`${styles.selectInput} ${className}`}>
+// <Dropdown onMainClick={onMainClick} ref={ref} tooltip={tooltip} menu={{ menu, onClick: this.onClick }} showArrow>
+// <Input
+// onPressEnter={(e) => this.handlePressEnter(e, ref)}
+// onBlur={this.onPressEnter}
+// type="number"
+// value={`${this.props.label as number}` ?? (content as string)}
+// />
+// </Dropdown>
+// </div>
+// );
+// };
+// getDouble = () => {
+// const { content, menu } = this.state;
+// const { className = '', tooltip, onClick } = this.props;
+// return (
+// <div className={`${styles.selectDouble} ${className}`}>
+// <Dropdown onClick={onClick} tooltip={tooltip} menu={{ menu, onClick: this.onClick }} icon={<Icon.NextIcon />}>
+// <div className={styles.selectLabel}>
+// <CustomLabel label={content} />
+// </div>
+// </Dropdown>
+// </div>
+// );
+// };
+// getFix = () => {
+// const { label, className = '', tooltip } = this.props;
+// const { menu } = this.state;
+// return (
+// <div className={`${styles.selectDouble} ${className}`}>
+// <Dropdown tooltip={tooltip} menu={{ menu, onClick: this.onClick }} showArrow>
+// <div className={styles.selectLabel}>
+// <CustomLabel label={label} />
+// </div>
+// </Dropdown>
+// </div>
+// );
+// };
+// getDoubleFix = () => {
+// const { label, className = '', tooltip, onClick, display, value, icon } = this.props;
+// const { menu } = this.state;
+// return (
+// <div className={`${styles.selectDouble} ${className}`}>
+// <Dropdown tooltip={tooltip} onClick={onClick} menu={{ menu, onClick: this.onClick }} icon={<Icon.NextIcon />}>
+// <div className={styles.selectLabel}>
+// <CustomLabel display={display} label={label} value={`${value}`} icon={icon} />
+// </div>
+// </Dropdown>
+// </div>
+// );
+// };
+// renderNeo = () => {
+// const { tooltip, onClick, display, value, icon, title, id, options, type } = this.props;
+// const onClickInner = (...args: unknown[]) => {
+// onClick?.(args[1] as number | string);
+// };
+// const onOptionSelect = (option: IValueOption) => {
+// onClick?.(option.value);
+// };
+// const iconToDisplay = options?.find((o) => o.value === value)?.icon ?? icon;
+// const displayInSubMenu = display === DisplayTypes.ICON ? DisplayTypes.LABEL : display === DisplayTypes.INPUT ? DisplayTypes.LABEL : display;
+// return (
+// <div className={`${styles.selectDouble}`}>
+// <Dropdown
+// tooltip={tooltip}
+// onClick={type === SelectTypes.NEO ? () => onClick?.(value) : onClick}
+// menu={{
+// menuId: id,
+// options,
+// onClick: onClickInner,
+// onOptionSelect,
+// value,
+// display: displayInSubMenu,
+// }}
+// icon={<Icon.NextIcon />}
+// >
+// <div className={styles.selectLabel}>
+// <NeoCustomLabel icon={iconToDisplay} display={display} title={title!} value={value} onChange={(v) => onClick?.(v)} />
+// </div>
+// </Dropdown>
+// </div>
+// );
+// };
+// render() {
+// const { type = 0 } = this.props;
+// return <div className={styles.selectComponent}>{this.getType(type)}</div>;
+// }
+// }
+import React, { useEffect, useRef, useState } from 'react';
+
+import { ICustomComponent } from '../../Common';
+import { IValueOption } from '../../services/menu/menu';
+import { CustomLabel, NeoCustomLabel } from '../CustomLabel';
import { Dropdown } from '../Dropdown';
+import { NextIcon } from '../Icon/Format';
import { Input } from '../Input';
-import { BaseItemProps, Item } from '../Item/Item';
-import { CustomLabel, NeoCustomLabel } from '../CustomLabel';
+import { BaseItemProps, BaseMenuItem, Item } from '../Item/Item';
import styles from './index.module.less';
-import { Icon, IValueOption } from '../..'; // FIXME: strange import
// TODO: these type definitions should be moved out of components to menu service
@@ -21,7 +340,7 @@ export enum SelectTypes {
/** 显示一个固定的值 */
FIX,
/** 显示一个固定的值 */
- DOUBLEFIX,
+ DOUBLE_FIX,
/** This should be the only type. The enum would be removed after we finish refactor. */
NEO,
@@ -45,12 +364,12 @@ export enum DisplayTypes {
CUSTOM,
}
-export interface BaseSelectChildrenProps extends BaseItemProps {
+export interface BaseSelectChildrenProps extends Omit<BaseItemProps, 'suffix' | 'label' | 'children'> {
onPressEnter?: (...arg: any) => void;
children?: BaseSelectChildrenProps[];
unSelectable?: boolean; //选中后不生效事件
- label?: ICustomComponent | ComponentChildren | string;
- suffix?: ICustomComponent | ComponentChildren | string;
+ label?: ICustomComponent | React.ReactNode | string;
+ suffix?: ICustomComponent | React.ReactNode | string;
name?: string;
}
@@ -58,7 +377,7 @@ export interface BaseSelectProps {
type?: SelectTypes;
children?: BaseSelectChildrenProps[];
display?: DisplayTypes;
- label?: ComponentChildren;
+ label?: React.ReactNode;
onClick?: (...arg: any) => void; //下拉Ul点击事件
onPressEnter?: (...arg: any) => void;
onMainClick?: () => void; // 非功能按钮事件
@@ -75,162 +394,130 @@ export interface BaseSelectProps {
title?: string;
}
-interface IState {
- menu: BaseMenuItem[];
- color: string; // TODO@wzhudev: this state is strange
- content: ComponentChildren;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- value: any;
-}
-
-export class Select extends PureComponent<BaseSelectProps, IState> {
- static override contextType = AppContext;
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- ColorRef: any;
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- onClick: (...arg: any) => void;
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- onPressEnter: (...arg: any[]) => void;
-
- constructor(props: BaseSelectProps) {
- super(props);
- this.initialize();
- }
-
- initialize() {
- const { children = [], hideSelectedIcon } = this.props;
- const list = this.resetMenu(children, hideSelectedIcon);
+export function Select(props: BaseSelectProps) {
+ const [menu, setMenu] = useState<BaseMenuItem[]>([]);
+ const [color, setColor] = useState(props.defaultColor ?? '#000');
+ const [content, setContent] = useState('');
+ const [value, setValue] = useState('');
+ const ColorRef = useRef(null);
+ let onClick: (...arg: any) => void;
+ let onPressEnter: (...arg: any[]) => void;
- this.state = {
- menu: list,
- color: this.props.defaultColor ?? '#000',
- content: '',
- value: '',
- };
- }
+ const resetMenu = (children: BaseSelectChildrenProps[], hideSelectedIcon?: boolean): BaseMenuItem[] => {
+ const list: BaseMenuItem[] = [];
+ // TODO@wzhudev: ID prop is not handled
+ for (let i = 0; i < children.length; i++) {
+ let selected = false;
+ if (!hideSelectedIcon) {
+ selected = children[i].selected ?? false;
+ }
+ list[i] = { label: '' };
+ list[i].label = (
+ <Item
+ disabled={children[i].disabled}
+ border={children[i].border}
+ selected={selected}
+ label={children[i].label as string}
+ suffix={children[i].suffix as string}
+ ></Item>
+ );
+ list[i].disabled = children[i].disabled;
+ list[i].style = children[i].style;
+ list[i].value = children[i].value;
+ list[i].className = children[i].className;
+ list[i].onClick = children[i].onClick;
+ list[i].border = children[i].border;
- getType(type: SelectTypes) {
- switch (type) {
- case SelectTypes.SINGLE:
- return this.getSingle();
- case SelectTypes.INPUT:
- return this.getInput();
- case SelectTypes.DOUBLE:
- return this.getDouble();
- case SelectTypes.FIX:
- return this.getFix();
- case SelectTypes.DOUBLEFIX:
- return this.getDoubleFix();
- case SelectTypes.NEO:
- return this.renderNeo();
+ if (children[i].children) {
+ list[i].children = resetMenu(children[i].children as BaseSelectChildrenProps[]);
+ }
}
- }
- // eslint-disable-next-line max-lines-per-function
- initData() {
- const { type, display, children = [], label } = this.props;
+ return list;
+ };
+ const initData = () => {
+ const { type, display, children = [], label } = props;
// TODO@wzhudev: the way of binding onClick is ridiculous. Fix it.
-
// 显示值可变
if (type === 0 || type === 3) {
if (!children.length) return;
let index = children.findIndex((item) => item.selected);
if (index < 0) index = 0;
- const list = this.handleSelected(index);
+ const list = handleSelected(index);
const item = children[index];
if (display === DisplayTypes.SUFFIX) {
- this.setState({
- content: item.suffix,
- menu: list,
- });
+ setContent(item.suffix as string);
+ setMenu(list);
} else {
- this.setState({
- content: item.label,
- menu: list,
- });
+ setContent(item.label as string);
+ setMenu(list);
}
- this.onClick = (...arg) => {
+ onClick = (...arg: any[]) => {
const item = children[arg[2]];
- this.props.onClick?.(arg[1], arg[2], arg[3]);
+ props.onClick?.(arg[1], arg[2], arg[3]);
if (item.unSelectable) {
return;
}
- const list = this.handleSelected(arg[2]);
+ const list = handleSelected(arg[2]);
if (display === DisplayTypes.SUFFIX) {
- this.setState({
- content: children[arg[2]].suffix,
- menu: list,
- });
+ setContent(children[arg[2]].suffix as string);
+ setMenu(list);
} else {
- this.setState({
- content: children[arg[2]].label,
- menu: list,
- });
+ setContent(children[arg[2]].label as string);
+ setMenu(list);
}
};
} else if (type === 1) {
// 输入框
if (!children.length) return;
- // 匹配label和选项label确定选中项
- const getLabel = (label: ComponentChildren) => {
+
+ const getLabel = (label: React.ReactNode) => {
if (label !== null) {
if (label === '') return;
const index = children.findIndex((item) => label === item.label);
- const list = this.handleSelected(index < 0 ? null : index);
- this.setState({
- content: label,
- menu: list,
- });
+ const list = handleSelected(index < 0 ? null : index);
+ setContent(label as string);
+ setMenu(list);
} else {
let index = children.findIndex((item) => item.selected);
if (index < 0) index = 0;
- const list = this.handleSelected(index);
+ const list = handleSelected(index);
const item = children[index];
- this.setState({
- content: item.label,
- menu: list,
- });
+ setContent(item.label as string);
+ setMenu(list);
}
};
getLabel(label);
- this.onClick = (...arg) => {
- this.props.onClick?.(arg[1], arg[2], arg[3]);
+ onClick = (...arg) => {
+ props.onClick?.(arg[1], arg[2], arg[3]);
- const list = this.handleSelected(arg[2]);
- this.setState({
- content: children[arg[2]].label,
- menu: list,
- });
+ const list = handleSelected(arg[2]);
+ setContent(children[arg[2]].label as string);
+ setMenu(list);
};
- this.onPressEnter = (e: KeyboardEvent) => {
- const value = (e.currentTarget as HTMLInputElement).value;
- this.props.onPressEnter?.(value);
+ onPressEnter = (e) => {
+ const value = e.currentTarget.value;
+ props.onPressEnter?.(value);
getLabel(value);
};
} else if (type === 2) {
// 颜色选择器
- const list = this.handleSelected(null);
- this.setState({
- menu: list,
- });
+ const list = handleSelected(null);
+ setMenu(list);
- this.onClick = () => {
- const { color } = this.state;
- this.props.onClick?.(color);
+ onClick = () => {
+ props.onClick?.(color);
};
} else if (type === 4 || type === 5) {
//固定显示值
@@ -238,69 +525,35 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
let index = children.findIndex((item) => item.selected);
if (index < 0) index = 0;
const item = children[index];
- const list = this.handleSelected(index);
- this.setState({
- menu: list,
- value: item.value,
- });
+ const list = handleSelected(index);
+ setMenu(list);
+ setValue(item.value);
- this.onClick = (...arg) => {
+ onClick = (...arg: any[]) => {
if (arg.length) {
- this.props.onClick?.(arg[1], arg[2], arg[3]);
- const list = this.handleSelected(arg[2]);
- this.setState({
- menu: list,
- value: children[arg[2]].value,
- });
+ props.onClick?.(arg[1], arg[2], arg[3]);
+ const list = handleSelected(arg[2]);
+ setMenu(list);
+ setValue(children[arg[2]].value);
} else {
- this.props.onClick?.(this.state.value);
+ props.onClick?.(value);
}
};
}
- }
-
- updateData() {
- if (this.props.type === SelectTypes.INPUT) {
- this.setState({ content: this.props.label });
- }
- }
-
- override componentDidMount() {
- this.initData();
- }
+ };
- override UNSAFE_componentWillReceiveProps(nextProps: BaseSelectProps) {
- this.updateData();
- }
+ useEffect(() => {
+ initData();
+ }, []);
- resetMenu(children: BaseSelectChildrenProps[], hideSelectedIcon?: boolean) {
- const list: BaseMenuItem[] = [];
- // TODO@wzhudev: ID prop is not handled
- for (let i = 0; i < children.length; i++) {
- let selected = false;
- if (!hideSelectedIcon) {
- selected = children[i].selected ?? false;
- }
- list[i] = { label: '' };
- list[i].label = <Item disabled={children[i].disabled} border={children[i].border} selected={selected} label={children[i].label} suffix={children[i].suffix}></Item>;
- list[i].disabled = children[i].disabled;
- list[i].style = children[i].style;
- list[i].value = children[i].value;
- list[i].className = children[i].className;
- list[i].onClick = children[i].onClick;
- list[i].border = children[i].border;
-
- if (children[i].children) {
- list[i].children = this.resetMenu(children[i].children!);
- }
+ useEffect(() => {
+ if (props.type === SelectTypes.INPUT) {
+ setContent(props.label as string);
}
+ }, [props.label]);
- return list;
- }
-
- // 处理选中
- handleSelected = (index: number | null): BaseMenuItem[] | undefined => {
- const { children = [], hideSelectedIcon } = this.props;
+ const handleSelected = (index: number | null): BaseMenuItem[] => {
+ const { children = [], hideSelectedIcon } = props;
if (children.length) {
children.forEach((item) => {
item.selected = false;
@@ -310,18 +563,35 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
}
}
- const list = this.resetMenu(children, hideSelectedIcon);
+ const list = resetMenu(children, hideSelectedIcon);
return list;
};
- // 普通下拉
- getSingle = () => {
- const { content, menu } = this.state;
- const { className = '', tooltip, onMainClick } = this.props;
+ const getType = (type: SelectTypes) => {
+ switch (type) {
+ case SelectTypes.SINGLE:
+ return getSingle();
+ case SelectTypes.INPUT: // unused now
+ return getInput();
+ case SelectTypes.DOUBLE:
+ return getDouble();
+ case SelectTypes.FIX:
+ return getFix();
+ case SelectTypes.DOUBLE_FIX:
+ return getDoubleFix();
+ case SelectTypes.NEO:
+ return renderNeo();
+ default:
+ return null;
+ }
+ };
+
+ const getSingle = () => {
+ const { className = '', tooltip, onMainClick } = props;
return (
<div className={`${styles.selectSingle} ${className}`}>
- <Dropdown onMainClick={onMainClick} tooltip={tooltip} menu={{ menu, onClick: this.onClick }} showArrow>
+ <Dropdown onMainClick={onMainClick} tooltip={tooltip} menu={{ menu, onClick }} showArrow>
<div>
<CustomLabel label={content} />
</div>
@@ -330,38 +600,29 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
);
};
- handlePressEnter = (e: KeyboardEvent, ref: RefObject<Dropdown>) => {
- this.onPressEnter(e);
- ref.current?.hideMenu();
+ const handlePressEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ console.info('press enter');
+ onPressEnter(e);
};
- //Input下拉
- getInput = () => {
- const { content, menu } = this.state;
- const { className = '', tooltip, onMainClick } = this.props;
- const ref = createRef<Dropdown>();
+ const getInput = () => {
+ const { className = '', tooltip, onMainClick } = props;
return (
<div className={`${styles.selectInput} ${className}`}>
- <Dropdown onMainClick={onMainClick} ref={ref} tooltip={tooltip} menu={{ menu, onClick: this.onClick }} showArrow>
- <Input
- onPressEnter={(e) => this.handlePressEnter(e, ref)}
- onBlur={this.onPressEnter}
- type="number"
- value={`${this.props.label as number}` ?? (content as string)}
- />
+ <Dropdown onMainClick={onMainClick} tooltip={tooltip} menu={{ menu, onClick }}>
+ <Input onPressEnter={(e) => handlePressEnter(e)} onBlur={onPressEnter} type="number" value={`${props.label as number}` ?? (content as string)} />
</Dropdown>
</div>
);
};
- getDouble = () => {
- const { content, menu } = this.state;
- const { className = '', tooltip, onClick } = this.props;
+ const getDouble = () => {
+ const { className = '', tooltip, onClick } = props;
return (
<div className={`${styles.selectDouble} ${className}`}>
- <Dropdown onClick={onClick} tooltip={tooltip} menu={{ menu, onClick: this.onClick }} icon={<Icon.NextIcon />}>
+ <Dropdown onClick={onClick} tooltip={tooltip} menu={{ menu, onClick }} icon={<NextIcon />}>
<div className={styles.selectLabel}>
<CustomLabel label={content} />
</div>
@@ -370,13 +631,12 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
);
};
- getFix = () => {
- const { label, className = '', tooltip } = this.props;
- const { menu } = this.state;
+ const getFix = () => {
+ const { label, className = '', tooltip } = props;
return (
<div className={`${styles.selectDouble} ${className}`}>
- <Dropdown tooltip={tooltip} menu={{ menu, onClick: this.onClick }} showArrow>
+ <Dropdown tooltip={tooltip} menu={{ menu, onClick }}>
<div className={styles.selectLabel}>
<CustomLabel label={label} />
</div>
@@ -385,13 +645,12 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
);
};
- getDoubleFix = () => {
- const { label, className = '', tooltip, onClick, display, value, icon } = this.props;
- const { menu } = this.state;
+ const getDoubleFix = () => {
+ const { label, className = '', tooltip, onClick, display, value, icon } = props;
return (
<div className={`${styles.selectDouble} ${className}`}>
- <Dropdown tooltip={tooltip} onClick={onClick} menu={{ menu, onClick: this.onClick }} icon={<Icon.NextIcon />}>
+ <Dropdown tooltip={tooltip} onClick={onClick} menu={{ menu, onClick }} icon={<NextIcon />}>
<div className={styles.selectLabel}>
<CustomLabel display={display} label={label} value={`${value}`} icon={icon} />
</div>
@@ -400,8 +659,8 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
);
};
- renderNeo = () => {
- const { tooltip, onClick, display, value, icon, title, id, options, type } = this.props;
+ const renderNeo = () => {
+ const { tooltip, onClick, display, value, icon, title, id, options, type } = props;
const onClickInner = (...args: unknown[]) => {
onClick?.(args[1] as number | string);
@@ -413,6 +672,7 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
const iconToDisplay = options?.find((o) => o.value === value)?.icon ?? icon;
const displayInSubMenu = display === DisplayTypes.ICON ? DisplayTypes.LABEL : display === DisplayTypes.INPUT ? DisplayTypes.LABEL : display;
+
return (
<div className={`${styles.selectDouble}`}>
<Dropdown
@@ -426,7 +686,7 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
value,
display: displayInSubMenu,
}}
- icon={<Icon.NextIcon />}
+ icon={<NextIcon />}
>
<div className={styles.selectLabel}>
<NeoCustomLabel icon={iconToDisplay} display={display} title={title!} value={value} onChange={(v) => onClick?.(v)} />
@@ -436,9 +696,6 @@ export class Select extends PureComponent<BaseSelectProps, IState> {
);
};
- render() {
- const { type = 0 } = this.props;
-
- return <div className={styles.selectComponent}>{this.getType(type)}</div>;
- }
+ const { type = 0 } = props;
+ return <div className={styles.selectComponent}>{getType(type)}</div>;
}
diff --git a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
index 6d2c8dde3d..ee6b4b2648 100644
--- a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
+++ b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
@@ -11,11 +11,14 @@ interface IState {
eventType: string | null;
children: RightMenuProps[];
menuItems: Array<IDisplayMenuItem<IMenuItem>>;
+ menuShow: boolean;
+ clientPosition: {
+ clientX: number;
+ clientY: number;
+ };
}
export class RightMenu extends Component<BaseRightMenuProps, IState> {
- ulRef = createRef<Menu>();
-
root = createRef<HTMLDivElement>();
constructor(props: BaseRightMenuProps) {
@@ -30,6 +33,11 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
eventType: null,
children: [],
menuItems: [],
+ menuShow: false,
+ clientPosition: {
+ clientX: 0,
+ clientY: 0,
+ },
};
}
@@ -58,52 +66,22 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
}
// 右键菜单事件
- handleContextMenu = async (event: IMouseEvent, rect?: any, down?: boolean) => {
+ handleContextMenu = async (event: IMouseEvent) => {
event.preventDefault();
this.setState({ visible: true, srcElement: event.target, eventType: event.type }, () => {
new Promise<void>((resolve, reject) => {
- this.ulRef.current?.showMenu(true);
resolve();
}).then(() => {
- // clientX/Y 获取到的是触发点相对于浏览器可视区域左上角距离
- const clickX = !down ? event.clientX : rect.x;
- const clickY = !down ? event.clientY : rect.y;
-
- // console.log(event);
-
- // window.innerWidth/innerHeight 获取的是当前浏览器窗口的视口宽度/高度
- const screenW = window.innerWidth;
- const screenH = window.innerHeight;
- // 获取自定义菜单的宽度/高度
- const currentUl = this.ulRef.current?.getMenuRef().current;
- const rootW = currentUl?.offsetWidth || 0;
- const rootH = currentUl?.offsetHeight || 0;
-
- // right为true,说明鼠标点击的位置到浏览器的右边界的宽度可以放下菜单。否则,菜单放到左边。
- // bottom为true,说明鼠标点击位置到浏览器的下边界的高度可以放下菜单。否则,菜单放到上边。
- const right = screenW - clickX > rootW;
- const left = !right;
- const bottom = screenH - clickY > rootH;
- const top = !bottom;
-
- const current = this.root.current;
- if (!current) return;
-
- if (right) {
- current.style.left = `${clickX}px`;
- }
-
- if (left) {
- current.style.left = `${clickX - rootW}px`;
- }
-
- if (bottom) {
- current.style.top = `${clickY}px`;
- }
- if (top) {
- current.style.top = `${clickY - rootH}px`;
- }
+ // clientX/Y obtains the distance between the trigger point and the upper left corner of the browser's visible area.
+ this.setState({
+ clientPosition: {
+ clientX: event.clientX,
+ clientY: event.clientY,
+ },
+ });
+
+ this.showRightMenu(true);
});
});
};
@@ -115,7 +93,7 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
if (eventType === 'click' && srcElement && srcElement.contains(e.target)) {
return;
}
- if (this.root.current.contains(e.target)) {
+ if (this.root.current.contains(e.target as Node)) {
return;
}
if (visible) {
@@ -125,12 +103,14 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
// 显示隐藏菜单栏
showRightMenu(show: boolean) {
- this.ulRef.current.showMenu(show);
+ this.setState({
+ menuShow: show,
+ });
}
override render() {
const wrapStyles = { ...this.props.style };
- const { visible } = this.state;
+ const { visible, menuShow, clientPosition } = this.state;
return (
visible && (
@@ -142,7 +122,15 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
e.preventDefault();
}}
>
- <Menu ref={this.ulRef} menuId={MenuPosition.CONTEXT_MENU} onClick={this.handleClick}></Menu>
+ <Menu
+ show={menuShow}
+ menuId={MenuPosition.CONTEXT_MENU}
+ onClick={this.handleClick}
+ clientPosition={clientPosition}
+ onOptionSelect={() => {
+ this.showRightMenu(false);
+ }}
+ ></Menu>
</div>
)
);
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
index a464eb7026..9ba3b8711a 100644
--- a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
@@ -1,7 +1,7 @@
import { SetWorksheetActivateCommand } from '@univerjs/base-sheets';
import { AppContext, BaseMenuItem, BaseSheetBarProps, Button, CustomLabel, Icon, IDisplayMenuItem, IMenuItem, Menu, MenuPosition } from '@univerjs/base-ui';
-import { ICommandService } from '@univerjs/core';
-import { Component, createRef, RefObject } from 'react';
+import { ICommandService, IKeyValue } from '@univerjs/core';
+import { Component, createRef } from 'react';
import styles from './index.module.less';
import { ISheetBarMenuItem, SheetBarMenu } from './SheetBarMenu';
@@ -12,6 +12,8 @@ type SheetState = {
menuList: BaseSheetBarProps[];
sheetUl: BaseMenuItem[];
menuItems: Array<IDisplayMenuItem<IMenuItem>>;
+ showMenu: boolean;
+ menuStyle: React.CSSProperties;
};
export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
@@ -19,8 +21,6 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
ref = createRef<SheetBarMenu>();
- ulRef = createRef<Menu>();
-
sheetContainerRef = createRef<HTMLDivElement>();
slideTabRoot = createRef<HTMLDivElement>();
@@ -55,6 +55,8 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
sheetUl: [],
menuList: [],
menuItems: [],
+ showMenu: false,
+ menuStyle: {},
};
}
@@ -86,7 +88,8 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
});
// activate command
- const commandService: ICommandService = this.context.injector.get(ICommandService);
+ // FIXME this.context type error
+ const commandService: ICommandService = (this.context as IKeyValue).injector.get(ICommandService);
commandService.executeCommand(SetWorksheetActivateCommand.id, { worksheetId });
};
@@ -104,25 +107,28 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
} else {
this.setSlideTabActive(worksheetId);
// activate command
- const commandService: ICommandService = this.context.injector.get(ICommandService);
+ // FIXME this.context type error
+ const commandService: ICommandService = (this.context as IKeyValue).injector.get(ICommandService);
commandService.executeCommand(SetWorksheetActivateCommand.id, { worksheetId });
}
};
// 显示下拉
- showSelect = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, ref: RefObject<Menu>) => {
+ showSelect = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e.stopPropagation();
e.preventDefault();
- const current = ref.current;
- if (current) current.showMenu(true);
+ this.setState({
+ showMenu: true,
+ });
// 点击外部隐藏子组件
window.addEventListener('click', this.hideSelect);
};
// 隐藏下拉
hideSelect = (e: MouseEvent) => {
- const ulCurrent = this.ulRef.current;
- if (ulCurrent) ulCurrent.showMenu(false);
+ this.setState({
+ showMenu: false,
+ });
window.removeEventListener('click', this.hideSelect);
};
@@ -130,8 +136,6 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
showUlList = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, cb?: () => void) => {
new Promise<void>((resolve) => {
const target = e.currentTarget as HTMLDivElement;
- const id = target.dataset.id as string;
- this.showSelect(e, this.ulRef);
resolve();
}).then(() => {
const currentTarget = (e.target as HTMLElement).closest(`.${styles.slideTabItem}`);
@@ -139,12 +143,18 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
const currentRect = currentTarget.getBoundingClientRect();
const left = `${currentRect.left}px`;
const bottom = `${currentRect.height}px`;
- const ul = this.ulRef.current?.getMenuRef().current;
- if (!ul) return;
- ul.style.left = left;
- ul.style.bottom = bottom;
- ul.style.top = 'auto';
- ul.style.right = 'auto';
+ const top = 'auto';
+ const right = 'auto';
+ this.setState({
+ menuStyle: {
+ left,
+ bottom,
+ top,
+ right,
+ },
+ });
+
+ this.showSelect(e);
cb && cb();
}
@@ -232,7 +242,7 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
}
override render() {
- const { sheetList, menuList, sheetUl } = this.state;
+ const { sheetList, menuList, sheetUl, showMenu, menuStyle } = this.state;
const { addSheet, selectSheet } = this.props;
@@ -286,7 +296,7 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
</div>
{/* mouse right button context menu */}
- <Menu className={styles.sheetUl} menu={sheetUl} menuId={MenuPosition.SHEET_BAR} ref={this.ulRef} />
+ <Menu className={styles.sheetUl} menu={sheetUl} menuId={MenuPosition.SHEET_BAR} show={showMenu} style={menuStyle} />
{/* prev next scroll button */}
<div className={`${styles.sheetBarOptions} ${styles.sheetBarScrollButton}`}>
diff --git a/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx b/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
index 6d53a5fd62..7a5b54fe98 100644
--- a/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
+++ b/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
@@ -1,5 +1,5 @@
import { AppContext, Button, CustomLabel, IDisplayMenuItem, IMenuButtonItem, IMenuItem, IMenuSelectorItem, IValueOption, MenuItemType, Select, Tooltip } from '@univerjs/base-ui';
-import { ICommandService } from '@univerjs/core';
+import { ICommandService, IKeyValue } from '@univerjs/core';
import { Component } from 'react';
import { Subscription } from 'rxjs';
@@ -70,7 +70,7 @@ export class ToolbarItem extends Component<IDisplayMenuItem<IMenuItem>, IToolbar
private renderSelectorType() {
const { context, state } = this;
- const commandService: ICommandService = context.injector.get(ICommandService);
+ const commandService: ICommandService = (context as IKeyValue).injector.get(ICommandService);
const { disabled, value } = state;
const props = this.props as IDisplayMenuItem<IMenuSelectorItem<unknown>>;
@@ -99,7 +99,7 @@ export class ToolbarItem extends Component<IDisplayMenuItem<IMenuItem>, IToolbar
const { props, context, state } = this;
const { disabled, activated } = state;
const { icon, title } = props;
- const commandService: ICommandService = context.injector.get(ICommandService);
+ const commandService: ICommandService = (context as IKeyValue).injector.get(ICommandService);
return (
<Tooltip title={this.getTooltip()} placement="bottom">
@@ -111,6 +111,6 @@ export class ToolbarItem extends Component<IDisplayMenuItem<IMenuItem>, IToolbar
}
private getTooltip(): string {
- return this.context.localeService?.t(this.props.tooltip) + (this.props.shortcut ? ` (${this.props.shortcut})` : '');
+ return (this.context as IKeyValue).localeService?.t(this.props.tooltip) + (this.props.shortcut ? ` (${this.props.shortcut})` : '');
}
}