antd#Menu TypeScript Examples

The following examples show how to use antd#Menu. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From shippo with MIT License 6 votes vote down vote up
StyledMenu = styled(Menu)`
  &.ant-menu {
    .ant-menu-sub.ant-menu-inline {
      background-color: #fff;
    }
    .ant-menu-item-selected {
      background-color: #fff;
    }
    .ant-menu-item::after {
      border: 0;
    }
    .ant-menu-item:active,
    .ant-menu-submenu-title:active {
      background-color: #fff;
    }
  }
`
Example #2
Source File: HorizontalMenu.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
export function HorizontalMenu<T = MenuProps>({children, style, ...restProps}: Props & T) {
  return (
    <Menu
      mode={"horizontal"}
      style={{ 
        height: "100%", 
        borderRight: 0 ,
        ...style
      }}
      {...restProps}
    >
      {children}
    </Menu>
  )
}
Example #3
Source File: Header.tsx    From vite-react-ts with MIT License 6 votes vote down vote up
MyHeader: React.FC = () => {
  const user = useStore((state) => state.user);

  const handleChange = (e: { key: string }) => {
    if (e.key === '0') {
      localStorage.removeItem('vite-react-ts-antd-token');
      window.location.href = '/user/login';
    }
  };

  const menu = (
    <Menu onClick={handleChange}>
      <Menu.Item key="0">退出登录</Menu.Item>
    </Menu>
  );
  return (
    <Header className={cls.layout_header}>
      <Dropdown overlay={menu}>
        <Space>
          <Avatar src={logo} />
          {user?.username}
        </Space>
      </Dropdown>
    </Header>
  );
}
Example #4
Source File: InsightSaveButton.tsx    From posthog-foss with MIT License 6 votes vote down vote up
export function InsightSaveButton({
    saveAs,
    saveInsight,
    isSaved,
}: {
    saveAs: () => void
    saveInsight: (options: Record<string, any>) => void
    isSaved: boolean | undefined
}): JSX.Element {
    const menu = (
        <Menu>
            <Menu.Item key="2" onClick={saveInsight} data-attr="insight-save-and-continue">
                Save and continue editing
            </Menu.Item>
            {isSaved && (
                <Menu.Item key="3" onClick={saveAs} data-attr="insight-save-as-new-insight">
                    Save as new insight
                </Menu.Item>
            )}
        </Menu>
    )
    return (
        <Dropdown.Button
            style={{ marginLeft: 8 }}
            type="primary"
            onClick={() => saveInsight({ setViewMode: true })}
            overlay={menu}
            data-attr="insight-save-button"
            icon={<IconArrowDropDown data-attr="insight-save-dropdown" style={{ fontSize: 25 }} />}
        >
            Save
        </Dropdown.Button>
    )
}
Example #5
Source File: index.tsx    From RareCamp with Apache License 2.0 6 votes vote down vote up
OFMenu = styled(Menu)`
  &.ant-menu-root.ant-menu-vertical {
    border-radius: 2px;
    box-shadow: 0 9px 28px 8px rgba(0, 0, 0, 0.05),
      0 6px 16px 0 rgba(0, 0, 0, 0.08),
      0 3px 6px -4px rgba(0, 0, 0, 0.12);
    background-color: #ffffff;
    margin-top: -15px;
    li {
      height: 32px;
    }
    a,
    button {
      font-family: Roboto, serif;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85);
    }
    button {
      padding: 0;
      border: none;
    }
  }
`
Example #6
Source File: GlobalMenu.tsx    From ant-extensions with MIT License 6 votes vote down vote up
GlobalMenu: React.FC<{ disabled: boolean }> = React.memo(({ disabled }) => {
  const { t } = useTranslation(I18nKey);
  const { filters, enableAll, toggleExclude, removeAll } = useContext(Context);

  const menu = useMemo(() => {
    const someEnabled = filters.some((f) => !f.required && f.active);
    const someDisabled = filters.some((f) => !f.required && !f.active);
    const hasNotRequired = filters.some((f) => !f.required);

    return (
      <Menu>
        <h4 style={{ padding: "0 16px" }}>{t("label.all_filters")}</h4>
        <Menu.Item disabled={!someDisabled} onClick={() => enableAll(true)}>
          <EyeOutlined /> {t("label.enable_all")}
        </Menu.Item>
        <Menu.Item disabled={!someEnabled} onClick={() => enableAll(false)}>
          <EyeInvisibleOutlined /> {t("label.disable_all")}
        </Menu.Item>
        <Menu.Item disabled={!hasNotRequired} onClick={toggleExclude}>
          {<Icon component={TwoTone} />} {t("label.invert")}
        </Menu.Item>
        <Menu.Item
          className="ant-typography ant-typography-danger"
          disabled={!hasNotRequired}
          onClick={removeAll}
        >
          <DeleteOutlined /> {t("label.remove_all")}
        </Menu.Item>
      </Menu>
    );
  }, [filters, enableAll, removeAll, t, toggleExclude]);

  return (
    <Dropdown overlay={menu} trigger={["click"]} disabled={disabled || filters.length === 0}>
      <Button type="link" icon={<SettingOutlined />} />
    </Dropdown>
  );
})
Example #7
Source File: Header.tsx    From nodestatus with MIT License 6 votes vote down vote up
Header: FC<Props> = props => {
  const navigate = useNavigate();
  const { isCollapsed, toggleCollapsed } = props.collapsed;

  const menu = (
    <Menu
      items={[
        {
          key: 'logout',
          label: 'Logout',
          icon: <LogoutOutlined className="mr-2 align-middle" />,
          className: 'align-middle'
        }
      ]}
      onClick={({ key }) => {
        if (key === 'logout') {
          localStorage.removeItem('token');
          navigate('/login');
        }
      }}
    />
  );

  return (
    <div className="h-full flex items-center justify-between">
      {React.createElement(isCollapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
        className: 'text-2xl',
        onClick: toggleCollapsed
      })}
      <Dropdown overlay={menu} placement="bottom">
        <Avatar size={40} icon={<UserOutlined />} />
      </Dropdown>
    </div>
  );
}
Example #8
Source File: App.tsx    From LogicFlow with Apache License 2.0 6 votes vote down vote up
function App() {
  const history = useHistory();
  const m = genMenus();
  let { search } = useLocation();
  let isInDoc = search.indexOf('from=doc') !== -1
  const renderNav = () => {
    return (
      <Menu
        mode="inline"
        style={{ flexShrink: 0, width: 300 }}
        onClick={(e) => history.push(e.key)}
      >
        {m.map((it) => it.children)}
      </Menu>
    );
  };

  return (
    <div className="App">
      { isInDoc ? '' : renderNav()}
      <div className="container">{Routes}</div>
    </div>
  );
}
Example #9
Source File: NavMenu.spec.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
describe("NavMenu", () => {
  it("should work", () => {
    const wrapper = mount(<NavMenu menuItems={sideBarMenuItem} />);

    expect(wrapper.find(Menu).prop("selectedKeys")).toEqual(["0.0.1"]);

    expect(wrapper.find(Menu.SubMenu).length).toBe(2);

    expect(wrapper.find(Menu.Item).length).toBe(2);
  });

  it("should work while customItem was true", () => {
    const wrapper = mount(<NavMenu menuItems={[]} />);

    expect(wrapper.find(Menu.SubMenu).length).toBe(0);
  });
});
Example #10
Source File: utils.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
export function renderActions<T extends object = any>(
  clsPrefix: string,
  locale: { operation: string },
  actions?: TableRowActions<T> | null,
): Array<ErdaColumnType<T>> {
  if (actions) {
    const { render } = actions;
    return [
      {
        title: locale.operation,
        width: 100,
        dataIndex: 'operation',
        fixed: 'right',
        render: (_: unknown, record: T) => {
          const list = render(record).filter((item) => item.show !== false);

          const menu = (
            <Menu theme="dark">
              {list.map((item, index) => {
                const { title, onClick, disabled = false, disabledTip } = item;
                return (
                  <Menu.Item key={index} onClick={disabled ? undefined : onClick}>
                    <Tooltip title={disabled && disabledTip}>
                      <span
                        className={cn(`${clsPrefix}-menu-item`, {
                          [`${clsPrefix}-menu-item-disabled`]: !!disabled,
                        })}
                        onClick={disabled ? (e: any) => e && e.stopPropagation && e.stopPropagation() : undefined}
                      >
                        {title}
                      </span>
                    </Tooltip>
                  </Menu.Item>
                );
              })}
            </Menu>
          );

          return (
            <span onClick={(e) => e.stopPropagation()}>
              {!!list.length && (
                <Dropdown overlay={menu} align={{ offset: [0, 5] }} trigger={['click']}>
                  <ErdaIcon type="gengduo" size="16" className={`${clsPrefix}-action-more`} />
                </Dropdown>
              )}
            </span>
          );
        },
      },
    ];
  }
  return [];
}
Example #11
Source File: index.tsx    From gant-design with MIT License 6 votes vote down vote up
//渲染menu主体
  renderSubMenu(prefixCls) {
    const { collapsed, mode } = this.state;
    const { selectedKey, menuData } = this.props;
    let selectedKeys = selectedKey ? [selectedKey] : (menuData.length && [menuData[0].key]) || [];
    let inlineCollapsed = mode == 'inline' && collapsed;
    let inlineProperty = mode == 'inline' ? { inlineCollapsed: collapsed } : {};
    return (
      <Menu
        className={prefixCls}
        selectedKeys={selectedKeys}
        mode={mode}
        onClick={this.onClick}
        {...inlineProperty}
      >
        {menuData.map((item: menuItem) => (
          <Menu.Item
            className={inlineCollapsed && `${prefixCls}-collapsed`}
            disabled={item.disabled}
            key={item.key}
          >
            {typeof item.icon == 'string' ? (
              <Icon type={item.icon} wrapperStyle={{ width: 'auto' }} />
            ) : (
              item.icon
            )}
            <span>{item.title}</span>
            {item.count && (
              <span className={`${prefixCls}-item-count`}>
                <Badge count={item.count} />
              </span>
            )}
          </Menu.Item>
        ))}
      </Menu>
    );
  }
Example #12
Source File: AnnotationGroupList.tsx    From slim with Apache License 2.0 6 votes vote down vote up
render (): React.ReactNode {
    const items = this.props.annotationGroups.map((annotationGroup, index) => {
      const uid = annotationGroup.uid
      return (
        <AnnotationGroupItem
          key={annotationGroup.uid}
          annotationGroup={annotationGroup}
          metadata={this.props.metadata[uid]}
          isVisible={this.props.visibleAnnotationGroupUIDs.includes(uid)}
          defaultStyle={this.props.defaultAnnotationGroupStyles[uid]}
          onVisibilityChange={this.props.onAnnotationGroupVisibilityChange}
          onStyleChange={this.props.onAnnotationGroupStyleChange}
        />
      )
    })

    return (
      <Menu selectable={false}>
        {items}
      </Menu>
    )
  }
Example #13
Source File: index.tsx    From react-resume-site with GNU General Public License v3.0 6 votes vote down vote up
FeedBack = () => {
  const feedbackMenu = (
    <Menu>
      <Menu.Item>
        <div className="rs-feed-group">
          <div className="rs-feed-group__wechat">
            <div className="rs-feed-group__text">微信群(wx号: qiufengblue)</div>
            <div className="bg"></div>
          </div>
          <div className="rs-feed-group__qq">
            <div className="rs-feed-group__text">qq群(699817990)</div>
            <div className="bg"></div>
          </div>
        </div>
      </Menu.Item>
    </Menu>
  );

  return (
    <Dropdown overlay={feedbackMenu}>
      <a
        className="ant-dropdown-link rs-link"
        onClick={(e) => e.preventDefault()}
      >
        交流与反馈
      </a>
    </Dropdown>
  )
}
Example #14
Source File: index.tsx    From imove with MIT License 6 votes vote down vote up
FlowChartContextMenu: React.FC<IProps> = (props) => {
  const menuRef = useRef(null);
  const { x, y, scene, visible, flowChart } = props;
  const menuConfig = menuConfigMap[scene];

  useClickAway(() => onClickAway(), menuRef);

  const onClickAway = useCallback(
    () => flowChart.trigger('graph:hideContextMenu'),
    [flowChart],
  );
  const onClickMenu = useCallback(
    ({ key }) => {
      const handlerMap = Helper.makeMenuHandlerMap(menuConfig);
      const handler = handlerMap[key];
      if (handler) {
        onClickAway();
        handler(flowChart);
      }
    },
    [flowChart, menuConfig],
  );

  return !visible ? null : (
    <div
      ref={menuRef}
      className={styles.contextMenu}
      style={{ left: x, top: y }}
    >
      <Menu mode={'vertical'} selectable={false} onClick={onClickMenu}>
        {Helper.makeMenuContent(flowChart, menuConfig)}
      </Menu>
    </div>
  );
}
Example #15
Source File: MenuDefault.tsx    From react_admin with MIT License 5 votes vote down vote up
MenuDefault: React.FC<Iprops> = (props) => {
  const { collapsed } = props;

  /** 构建树结构 **/
  const makeTreeDom = useCallback((data): JSX.Element[] => {
    return data.map((v: MenuTypes) => {
      if (v.children) {
        return (
          <Menu.SubMenu
            key={v.key}
            title={
              <span>
                <Icon type={v.icon} />
                <span>{v.title}</span>
              </span>
            }
          >
            {makeTreeDom(v.children)}
          </Menu.SubMenu>
        );
      } else {
        return (
          <Menu.Item key={v.key}>
            <Link to={v.key}>
              <Icon type={v.icon} />
              <span>{v.title}</span>
            </Link>
          </Menu.Item>
        );
      }
    });
  }, []);

  /** 处理原始数据,将原始数据处理为层级关系 **/
  const treeDom: JSX.Element[] = useMemo(() => {
    const treeDom = makeTreeDom(MenuConfig);
    return treeDom;
  }, [MenuConfig]);

  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div className="logo-home">
        <Link className="logo-link" to="/">
          <img src={require("src/assets/img/logo.f16d.png")} />
          <div className={collapsed ? "show" : ""}>TS + Hooks</div>
        </Link>
      </div>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={[props.history.location.pathname]}
      >
        {treeDom}
      </Menu>
    </Sider>
  );
}
Example #16
Source File: index.tsx    From shippo with MIT License 5 votes vote down vote up
{ SubMenu } = Menu
Example #17
Source File: App.tsx    From generator-earth with MIT License 5 votes vote down vote up
render() {
        let totalPath: string = this.props.location.pathname;
        let prefixArr: RegExpMatchArray = totalPath.match(/^\/[^/]*/) || [];

        return (
            <Spin spinning={false} style={{ maxHeight: window.innerHeight }}>
                <Layout style={{ minHeight: '100vh' }}>

                    <Sider collapsible>
                        <div className="logo">金融</div>
                        <Menu theme="dark"
                              defaultSelectedKeys={[ '/' ]}
                              defaultOpenKeys={[ '/Asset', '/Funder' ]}
                              mode="inline"
                              selectedKeys={[ prefixArr[0] ]}
                        >
                            <Menu.Item key={'/'}>
                                <Icon type="book"/>
                                <span>首页</span>
                                <Link to="/"></Link>
                            </Menu.Item>

                            <SubMenu key="/page" title={<span><Icon type="book"/>测试</span>}>
                                <Item key="/Details">
                                    <span>详情信息</span>
                                    <Link to="/Details"></Link>
                                </Item>
                            </SubMenu>
                        </Menu>
                    </Sider>

                    <Layout>
                        <Header style={{ background: '#fff', textAlign: 'center' }}>
                            <h1>金融</h1>
                        </Header>
                        <Content style={{ margin: '0 16px' }}>
                            <Switch>
                                {/* 首页 */}
                                <Route exact path="/" component={Home}/>

                                {/* 对账管理 */}
                                <Route path="/Details" component={Details}/>

                            </Switch>
                        </Content>
                    </Layout>

                </Layout>
            </Spin>
        )
    }
Example #18
Source File: DropdownSelector.tsx    From posthog-foss with MIT License 5 votes vote down vote up
export function DropdownSelector({
    label,
    value,
    onValueChange,
    options,
    hideDescriptionOnDisplay,
    disabled,
    compact,
}: DropdownSelectorProps): JSX.Element {
    const selectedOption = options.find((opt) => opt.key === value)

    const menu = (
        <Menu>
            {options.map(({ key, hidden, ...props }) => {
                if (hidden) {
                    return null
                }
                return (
                    <Menu.Item key={key}>
                        <SelectItem {...props} onClick={() => onValueChange(key)} />
                    </Menu.Item>
                )
            })}
        </Menu>
    )

    return (
        <>
            {label && <label className="ant-form-item-label">{label}</label>}
            <Dropdown overlay={menu} trigger={['click']} disabled={disabled}>
                <div
                    className={clsx('dropdown-selector', disabled && ' disabled', compact && 'compact')}
                    onClick={(e) => e.preventDefault()}
                >
                    <div style={{ flexGrow: 1 }}>
                        {selectedOption && (
                            <SelectItem
                                {...selectedOption}
                                onClick={() => {}}
                                description={hideDescriptionOnDisplay ? undefined : selectedOption.description}
                            />
                        )}
                    </div>
                    <div className="dropdown-arrow">
                        <IconArrowDropDown />
                    </div>
                </div>
            </Dropdown>
        </>
    )
}
Example #19
Source File: index.tsx    From RareCamp with Apache License 2.0 5 votes vote down vote up
export default function TaskStatus({ task, programId }) {
  const taskMutation = useEditTaskMutation({
    taskId: task.taskId,
    programId,
    projectId: task.projectId,
  })
  const menu = (
    <Menu>
      {Object.values(TaskStatuses).map((status) => (
        <Menu.Item
          key={status}
          style={{
            backgroundColor:
              status !== task.status ? 'transparent' : '#eee',
          }}
        >
          <Button
            type="text"
            onClick={() => {
              if (status !== task.status)
                taskMutation.mutate({ ...task, status })
            }}
          >
            <Tag color={statusMeta[status].bgColor}>
              {statusMeta[status].label}
            </Tag>
          </Button>
        </Menu.Item>
      ))}
    </Menu>
  )

  return (
    <Dropdown overlay={menu}>
      <Tag
        style={{ cursor: 'pointer' }}
        color={statusMeta[task.status].bgColor}
      >
        {taskMutation.isLoading ? (
          <LoadingOutlined />
        ) : (
          statusMeta[task.status].label
        )}
      </Tag>
    </Dropdown>
  )
}
Example #20
Source File: index.tsx    From S2 with MIT License 5 votes vote down vote up
Export: React.FC<ExportProps> = React.memo((props) => {
  const {
    className,
    icon,
    syncCopy = false,
    copyOriginalText = i18n('复制原始数据'),
    copyFormatText = i18n('复制格式化数据'),
    downloadOriginalText = i18n('下载原始数据'),
    downloadFormatText = i18n('下载格式化数据'),
    successText = i18n('操作成功'),
    errorText = i18n('操作失败'),
    sheet,
    fileName,
    ...restProps
  } = props;

  const PRE_CLASS = `${S2_PREFIX_CLS}-export`;

  const copyData = (isFormat: boolean) => {
    const data = getSheetData(sheet, '\t', isFormat);

    copyToClipboard(data, syncCopy)
      .then(() => {
        message.success(successText);
      })
      .catch((error) => {
        // eslint-disable-next-line no-console
        console.log('copy failed: ', error);
        message.error(errorText);
      });
  };

  const downloadData = (isFormat: boolean) => {
    const data = getSheetData(sheet, ',', isFormat);
    try {
      download(data, fileName);
      message.success(successText);
    } catch (err) {
      message.error(errorText);
    }
  };

  const menu = (
    <Menu>
      <Menu.Item key="copyOriginal" onClick={() => copyData(false)}>
        {copyOriginalText}
      </Menu.Item>
      <Menu.Item key="copyFormat" onClick={() => copyData(true)}>
        {copyFormatText}
      </Menu.Item>
      <Menu.Item key="downloadOriginal" onClick={() => downloadData(false)}>
        {downloadOriginalText}
      </Menu.Item>
      <Menu.Item key="downloadFormat" onClick={() => downloadData(true)}>
        {downloadFormatText}
      </Menu.Item>
    </Menu>
  );

  return (
    <Dropdown
      overlay={menu}
      trigger={['click']}
      className={cx(PRE_CLASS, className)}
      {...restProps}
    >
      <a
        className="ant-dropdown-link"
        key="export"
        onClick={(e) => e.preventDefault()}
      >
        {icon || <DotIcon />}
      </a>
    </Dropdown>
  );
})
Example #21
Source File: SwitchPlatform.tsx    From brick-design with MIT License 5 votes vote down vote up
function SwitchPlatform(props: SwitchPlatformPropsType) {
	const { menus } = props
	const [isMobile, setIsMobile] = useState(false)
	const [mobileModel, setMobileModel] = useState(Object.keys(menus)[0])
	const [isVertical, setIsVertical] = useState(true)

	useEffect(() => {
		const size = isMobile ? [...menus[mobileModel]] : ['100%', '100%']
		!isVertical && size.reverse()
		changePlatform({
			isMobile,
			size,
		})
	}, [isMobile, isVertical, mobileModel])

	const renderMenu = useCallback(() => {
		return (
			<Menu
				selectedKeys={[mobileModel]}
				onClick={({ key }: any) => setMobileModel(key)}
			>
				{map(menus, (_, key) => {
					return <MenuItem key={key}>{key}</MenuItem>
				})}
			</Menu>
		)
	}, [mobileModel])

	const dropProps = isMobile ? {} : { visible: false }
	return (
		<div className={styles['switch-container']}>
			<Dropdown
				overlay={useMemo(() => renderMenu(), [mobileModel])}
				{...dropProps}
				trigger={['hover']}
			>
				<div
					className={styles['switch-platform']}
					onClick={() => setIsMobile(!isMobile)}
				>
					<Icon
						style={{ fontSize: 18 }}
						type={isMobile ? 'android' : 'windows'}
					/>
					<span>{isMobile ? 'mobile' : 'PC'}</span>
				</div>
			</Dropdown>
			{isMobile && (
				<Icon
					onClick={() => setIsVertical(!isVertical)}
					style={{ fontSize: 20 }}
					type={'sync'}
				/>
			)}
		</div>
	)
}
Example #22
Source File: AntdMenuItemWrapper.tsx    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
function AntdMenuItemWrapper(props: MenuItemProps) {
  return <Menu.Item {...props} />;
}
Example #23
Source File: App.tsx    From LogicFlow with Apache License 2.0 5 votes vote down vote up
{ SubMenu } = Menu
Example #24
Source File: LibraryDropdown.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function LibraryDropdown({
  type,
  onVisbleChange,
  children,
  menuItems,
}: React.PropsWithChildren<LibraryDropdownProps>): React.ReactElement {
  const { t } = useTranslation(NS_NEXT_BUILDER);
  const [visible, setVisible] = useState(false);
  const isOpen = useRef(false);

  const handleVisibleChange = React.useCallback(
    (value: boolean) => {
      isOpen.current = value;
      setVisible(value);
      onVisbleChange?.(value);
    },
    [onVisbleChange]
  );

  const handleClose = React.useCallback(() => {
    setVisible(false);
  }, []);

  const handleDraggingChange = React.useCallback(
    (isDragging: boolean): void => {
      if (isOpen.current) {
        setVisible(!isDragging);
        isOpen.current = !isDragging;
      }
    },
    []
  );

  const content = (
    <Menu style={{ padding: "2px 0" }}>
      <LibraryDropdownMenu
        menuItems={menuItems}
        onCloseClick={handleClose}
        onDraggingChange={handleDraggingChange}
        type={type}
      />
    </Menu>
  );

  return (
    <Dropdown
      overlay={content}
      overlayClassName={shareStyles.customAnimation}
      trigger={["click"]}
      placement="bottomLeft"
      visible={visible}
      onVisibleChange={handleVisibleChange}
    >
      {children}
    </Dropdown>
  );
}
Example #25
Source File: Layout.tsx    From yugong with MIT License 5 votes vote down vote up
MainLayout: React.FC<Props> = ({ children }) => {
  const [collapsed, setCollapsed] = useState(true);
  
  let location = useLocation();
  const history = useHistory();
  const { auth } = useSelector((state: RootState) => state.controller);
  const { loginOut } = useDispatch<Dispatch>().controller;
  return (
    <Layout>
      <Sider
        theme="light"
        className={s.side}
        trigger={null}
        collapsible
        collapsed={collapsed}
      >
        <div className={s.logo}>
          <GroupOutlined /> {collapsed ? "" : "YuGong"}
        </div>
        <Menu
          theme="light"
          mode="inline"
          defaultSelectedKeys={[location.pathname]}
        >
          {menus.map((item) => (
            <Menu.Item key={item.path} icon={item.icon}>
              {item.name}
              <Link to={item.path || "/"} />
            </Menu.Item>
          ))}
        </Menu>
      </Sider>
      <Layout className="site-layout">
        <Header className={s.layout} style={{ padding: 0 }}>
          {React.createElement(
            collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
            {
              className: s.trigger,
              onClick: () => setCollapsed(!collapsed),
            }
          )}
          <div className={s.auto} />
          <div className={s.auth}>
            {auth?.isLogin ? (
              <div>
                <Avatar size="small" icon={<UserOutlined />} />&nbsp;&nbsp;
                {auth.session?.username}
                <Button type="link" onClick={loginOut}>退出</Button>
              </div>
            ) : (
              <>
              {location.pathname !== '/login' ? <Button type="link" onClick={() => history.push('/login')}>登录</Button> : null}
              {location.pathname !== '/register' ? <Button type="link" onClick={() => history.push('/register')}>注册</Button> : null}
              </>
            )}
          </div>
        </Header>
        <Content className={s.content}>{children}</Content>
      </Layout>
    </Layout>
  );
}
Example #26
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
function renderActions<T extends object = any>(actions?: IActions<T>): Array<ColumnProps<T>> {
  if (actions) {
    const { width, render, limitNum } = actions;
    return [
      {
        title: i18n.t('Operations'),
        width,
        dataIndex: 'operation',
        ellipsis: true,
        fixed: 'right',
        render: (_: any, record: T) => {
          const list = render(record);

          const menu = (limitNum || limitNum === 0) && (
            <Menu>
              {list.slice(limitNum).map((item) => (
                <Menu.Item key={item.title} onClick={item.onClick}>
                  <span className="fake-link mr-1">{item.title}</span>
                </Menu.Item>
              ))}
            </Menu>
          );

          return (
            <span className="operate-list">
              {list.slice(0, limitNum).map((item, index: number) => (
                <>
                  {index !== 0 && <Divider type="vertical" />}
                  <span className="fake-link mr-1 align-middle" key={item.title} onClick={item.onClick}>
                    {item.title}
                  </span>
                </>
              ))}
              {menu && (
                <Dropdown overlay={menu} align={{ offset: [0, 5] }}>
                  <Icon />
                </Dropdown>
              )}
            </span>
          );
        },
      },
    ];
  } else {
    return [];
  }
}
Example #27
Source File: Layout.tsx    From nextjs-ant-design-typescript with MIT License 5 votes vote down vote up
{ SubMenu, Item } = Menu
Example #28
Source File: OpticalPathList.tsx    From slim with Apache License 2.0 5 votes vote down vote up
render (): React.ReactNode {
    if (this.props.metadata === undefined) {
      return null
    }

    const isSelectable = (
      this.props.opticalPaths.length > 1 &&
      this.props.selectedPresentationStateUID == null
    )
    const opticalPathItems: React.ReactNode[] = []
    const optionItems: React.ReactNode[] = []
    this.props.opticalPaths.forEach(opticalPath => {
      const opticalPathIdentifier = opticalPath.identifier
      const images = this.props.metadata[opticalPathIdentifier]
      const seriesInstanceUID = images[0].SeriesInstanceUID
      images[0].OpticalPathSequence.forEach(opticalPathItem => {
        const id = opticalPathItem.OpticalPathIdentifier
        const description = opticalPathItem.OpticalPathDescription
        if (opticalPath.identifier === id) {
          if (this.props.activeOpticalPathIdentifiers.includes(id)) {
            opticalPathItems.push(
              <OpticalPathItem
                key={`${seriesInstanceUID}-${id}`}
                opticalPath={opticalPath}
                metadata={images}
                isVisible={this.props.visibleOpticalPathIdentifiers.includes(id)}
                defaultStyle={this.props.defaultOpticalPathStyles[id]}
                onVisibilityChange={this.props.onOpticalPathVisibilityChange}
                onStyleChange={this.props.onOpticalPathStyleChange}
                onRemoval={this.handleItemRemoval}
                isRemovable={isSelectable}
              />
            )
          } else {
            let title
            if (description !== '') {
              title = `${id} - ${description}`
            } else {
              title = `${id}`
            }
            optionItems.push(
              <Option key={id} value={id}>{title}</Option>
            )
          }
        }
      })
    })

    let opticalPathSelector
    if (isSelectable) {
      opticalPathSelector = (
        <Space align='center' size={20} style={{ padding: '14px' }}>
          <Select
            defaultValue=''
            style={{ width: 200 }}
            onChange={this.handleItemSelectionChange}
            value={this.state.selectedOpticalPathIdentifier}
            allowClear
          >
            {optionItems}
          </Select>
          <Tooltip title='Add'>
            <Btn
              icon={<AppstoreAddOutlined />}
              type='primary'
              onClick={this.handleItemAddition}
            />
          </Tooltip>
        </Space>
      )
    }

    return (
      <Menu selectable={false}>
        {opticalPathItems}
        {opticalPathSelector}
      </Menu>
    )
  }
Example #29
Source File: index.tsx    From imove with MIT License 5 votes vote down vote up
Helper = {
  makeMenuHandlerMap(config: IMenuConfig[]) {
    const queue = config.slice(0);
    const handlerMap: { [key: string]: (flowChart: Graph) => void } = {};
    while (queue.length > 0) {
      const { key, handler, children } = queue.pop() as IMenuConfig;
      if (children && children.length > 0) {
        queue.push(...children);
      } else {
        handlerMap[key] = handler;
      }
    }
    return handlerMap;
  },
  makeMenuContent(flowChart: Graph, menuConfig: IMenuConfig[]) {
    const loop = (config: IMenuConfig[]) => {
      return config.map((item) => {
        let content = null;
        let {
          key,
          title,
          icon,
          children,
          disabled = false,
          showDividerBehind,
        } = item;
        if (typeof disabled === 'function') {
          disabled = disabled(flowChart);
        }
        if (children && children.length > 0) {
          content = (
            <Menu.SubMenu
              key={key}
              icon={icon}
              title={title}
              disabled={disabled}
            >
              {loop(children)}
            </Menu.SubMenu>
          );
        } else {
          content = (
            <Menu.Item key={key} icon={icon} disabled={disabled}>
              {title}
            </Menu.Item>
          );
        }
        return [content, showDividerBehind && <Menu.Divider />];
      });
    };
    return loop(menuConfig);
  },
}