antd#Tooltip TypeScript Examples

The following examples show how to use antd#Tooltip. 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: utils.tsx    From erda-ui with GNU Affero General Public License v3.0 7 votes vote down vote up
getTitleRender = (column?: CP_TABLE2.ColumnItem) => {
  const { title, tip } = column || {};
  if (title && tip) {
    return (
      <div className="flex items-center">
        {title}
        <Tooltip title={tip}>
          <ErdaIcon type="info" size="14" className="text-sm text-sub ml-2" />
        </Tooltip>
      </div>
    );
  }
  return title;
}
Example #2
Source File: GeneralButtons.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function GeneralButtons(props: GeneralButtonsProps): React.ReactElement {
  return (
    <FormItemWrapper
      {...props}
      className={classNames(styles.formButtons, {
        [styles.isFormElement]: props.formElement?.layout === "horizontal",
      })}
    >
      <Tooltip title={props.submitTooltip}>
        <Button
          disabled={props.submitDisabled}
          type={props.submitType}
          onClick={props.onSubmitClick}
          style={{ marginRight: "8px" }}
          data-testid="submit-button"
          loading={props.loading}
        >
          {props.submitText}
        </Button>
      </Tooltip>
      {props.showCancelButton && (
        <Button
          type={props.cancelType}
          onClick={props.onCancelClick}
          data-testid="cancel-button"
        >
          {props.cancelText}
        </Button>
      )}
    </FormItemWrapper>
  );
}
Example #3
Source File: influenceFlag.tsx    From covid_dashboard with MIT License 6 votes vote down vote up
InfluenceFlag = (props: IProps) => {
  const influence = Math.max(0, props.influence || 0);

  return (
    <Tooltip title={props.lang == 'zh' ? "风险影响力" : "Risk Influence"}>
      <span className='inf'>
        <i className='fa fa-arrow-up' />{influence.toFixed(2)}
      </span>
    </Tooltip>
  )
}
Example #4
Source File: MenuTooltip.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function MenuTooltip(
  props: React.PropsWithChildren<MenuTooltipProps>
): React.ReactElement {
  const tooltipProps: TooltipProps = {
    title: props.title
  };

  if (!props.collapsed) {
    tooltipProps.title = null;
    tooltipProps.visible = false;
  }

  return (
    <Tooltip
      {...tooltipProps}
      placement="right"
      overlayClassName="ant-menu-inline-collapsed-tooltip"
    >
      {props.children}
    </Tooltip>
  );
}
Example #5
Source File: render-types.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
getTitleRender = (cItem: CP_TABLE.Column) => {
  const { title, titleTip } = cItem;
  const res = { title } as any;
  if (titleTip) {
    res.title = (
      <div className="flex items-center">
        {title}
        <Tooltip title={getTitleTip(titleTip)}>
          <ErdaIcon type="info" size="14" className="text-sm text-sub ml-2" />
        </Tooltip>
      </div>
    );
  }
  switch (cItem.titleRenderType) {
    case 'gantt':
      {
        let totalDay = 0;
        map(cItem.data, ({ date }) => {
          totalDay += date.length;
        });
        res.title = <GantteTitle dateRange={cItem.data} />;
        res.width = cItem?.width || totalDay * 50 || 400;
      }
      break;
    default:
      break;
  }
  return res;
}
Example #6
Source File: MenuTooltip.spec.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
describe("MenuTooltip", () => {
  it("should render as visible is false when not collapsed", () => {
    const wrapper = shallow(<MenuTooltip title="hello" collapsed={false} />);
    expect(wrapper.find(Tooltip).prop("visible")).toBe(false);
    expect(wrapper.find(Tooltip).prop("title")).toBe(null);
  });

  it("should render tooltip when collapsed", () => {
    const wrapper = shallow(<MenuTooltip title="hello" collapsed={true} />);
    expect(wrapper.find(Tooltip).prop("visible")).toBe(undefined);
    expect(wrapper.find(Tooltip).prop("title")).toBe("hello");
  });
});
Example #7
Source File: linear-distribution.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
CP_LINEAR_DISTRIBUTION = (props: CP_LINEAR_DISTRIBUTION.Props) => {
  const { props: configProps, data } = props;
  const { size = 'normal' } = configProps || {};
  const { list, total: _total } = data || {};
  const total = _total ?? sumBy(list, 'value');

  const labelArr: JSX.Element[] = [];
  const linearArr: JSX.Element[] = [];
  list?.forEach((item, idx) => {
    const { tip, label, color, value, status } = item;
    const _color = colorMap[color] || statusColorMap[status] || color;
    labelArr.push(
      <div key={`${idx}`} className="cp-linear-distribution-label flex justify-items-center items-center">
        <span className="label-dot rounded-full" style={{ backgroundColor: _color }} />
        <span>{label}</span>
      </div>,
    );
    linearArr.push(
      <Tooltip title={tip} key={`${idx}`}>
        <div className={'h-full cp-linear-distribution-item bg-white'} style={{ width: `${(value / total) * 100}%` }}>
          <span className="block h-full w-full" style={{ backgroundColor: _color }} />
        </div>
      </Tooltip>,
    );
  });

  return (
    <div className="my-4">
      <div className="mb-2 flex">{labelArr}</div>
      <div className={`w-full cp-linear-distribution size-${size}`}>{linearArr}</div>
    </div>
  );
}
Example #8
Source File: index.tsx    From LogicFlow with Apache License 2.0 6 votes vote down vote up
export default function ExampleHeader(props: IProps): ReactElement {

  function getGithubTool() {
    return (
      <Tooltip
        arrowPointAtCenter
        placement="bottomRight"
        title="在 Github 中查看"
      >
        <Button
          type="text"
          shape="circle"
          target="_blank"
          href={githubBaseLink + props.githubPath}
          icon={<GithubOutlined />}
        />
      </Tooltip>
    );
  }

  return (
    <div className="example-header">
      <div
        className="content"
        style={props.contentStyle}
      >
        { props.content ? <span className="content-text">{props.content}</span> : ''} 
        {props.children}
      </div>
      <div className="tools">
        <a href="http://logic-flow.org/examples/" rel="noreferrer" target="_blank">查看全部示例</a>
        {props.githubPath ? getGithubTool() : null}
      </div>
    </div>
  )
}
Example #9
Source File: Seeds.tsx    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Component for Button to Add Seed to Workspace on a seed browser card
 * @param existsInWorkspace - does the seed already exist in the users workspace?
 * @param seedId - seed unique ID
 * @returns
 */
export function AddToWorkspaceButton({
  existsInWorkspace,
  seedId,
}: {
  existsInWorkspace: boolean;
  seedId: string;
}) {
  function onClick() {
    postVSCodeMessage({
      type: SeedBrowserMessageType.onSeedAdd,
      data: { data: seedId },
      source: DMessageSource.webClient,
    } as SeedBrowserMessage);
  }

  if (!existsInWorkspace) {
    return (
      <Tooltip placement="top" title="Add to Workspace">
        <DownloadOutlined key="download" onClick={onClick} />
      </Tooltip>
    );
  }
  return (
    <Tooltip placement="top" title="Already in Workspace">
      <CheckCircleOutlined key="installed" disabled />
    </Tooltip>
  );
}
Example #10
Source File: str-num-date.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 截取字符串
 * @param fullStr 字符串
 * @param limit 长度限制
 * @param options.suffix 截取添加的后缀,默认为...
 * @param options.showTip 是否超过长度后显示提示
 */
export function cutStr(fullStr: string, limit = 0, options?: ICutOptions) {
  if (typeof fullStr !== 'string') {
    return '';
  }
  const { suffix = '...', showTip = false } = options || {};
  const str = fullStr.length > limit ? `${fullStr.substring(0, limit)}${suffix}` : fullStr;
  const sameLength = fullStr.length === str.length;
  return showTip && !sameLength ? <Tooltip title={fullStr}>{str}</Tooltip> : str;
}
Example #11
Source File: SelectAddProps.tsx    From brick-design with MIT License 6 votes vote down vote up
function SelectAddProps(props: SelectAddPropsType) {
  const [newPropField, setNewPropField] = useState('');
  const [propType, setPropType] = useState(PROPS_TYPES.string);

  function addParam() {
    if (/^[0-9a-zA-Z$_][0-9a-zA-Z\d_]*$/.test(newPropField)) {
      setNewPropField('');
    }
  }

  function renderAddonBefore() {
    return (
      <Select defaultValue={propType} onChange={(v: any) => setPropType(v)}>
        {map(TYPES_TO_COMPONENT, (_, type) => (
          <Option value={type} key={type}>
            <Tooltip overlayStyle={{ zIndex: 1800 }} title={type}>
              {type}
            </Tooltip>
          </Option>
        ))}
      </Select>
    );
  }

  return (
    <Input.Search
      addonBefore={renderAddonBefore()}
      placeholder="新增字段名称"
      value={newPropField}
      onChange={(e) => setNewPropField(e.target.value)}
      onSearch={addParam}
      enterButton="Add"
    />
  );
}
Example #12
Source File: index.tsx    From XFlow with MIT License 6 votes vote down vote up
RenderTooltip: React.FC<IConfigProps> = props => {
  const xflow = useXFlowApp()
  const [state, , renderModel] = createComponentModel<ACTIVE_NODE_PORT.IState | null>(null)

  React.useEffect(() => {
    if (!xflow) {
      return
    }
    const subscribe = async () => {
      const { model } = await ACTIVE_NODE_PORT.useModel(xflow.modelService)
      return model.watch(value => {
        renderModel.setValue(value)
      })
    }
    const subscription = subscribe()
    return () => {
      subscription.then(disposable => {
        disposable.dispose()
      })
    }
  }, [renderModel, xflow])

  const visible = !!(state && state.position && state.position.x)

  if (!visible) {
    return null
  }

  const title = props.getTooltip ? props.getTooltip(state) : state.tooltip

  return (
    <Tooltip visible={visible} title={title} placement={state.placement || 'top'}>
      <span
        className="canvas-node-port-tooltip"
        style={{ position: 'absolute', left: state.position.x, top: state.position.y }}
      />
    </Tooltip>
  )
}
Example #13
Source File: no-auth-tip.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
NoAuthTip = ({ children, tip = i18n.t('common:no permission') }: any): any => {
  if (!children) return null;
  const childrenWithProps = React.Children.map(children, (child) => {
    const ele = React.cloneElement(child, {
      className: classnames(child.props.className, 'not-allowed'),
      onClick: undefined,
      disabled: true,
    });
    return <Tooltip title={tip}>{ele}</Tooltip>;
  });
  return childrenWithProps;
}
Example #14
Source File: edge1.tsx    From XFlow with MIT License 6 votes vote down vote up
Edge1: NsGraph.IEdgeRender = (props) => {
  const ctx = useAppContext();
  // console.log('edge useAppContext', ctx);
  // console.log('edge props:', props);
  return (
    <div className="edge1-container">
      <Tooltip
        title="这是连线上渲染的React内容"
        // defaultVisible={true}
      >
        <div>hover我</div>
      </Tooltip>
    </div>
  );
}
Example #15
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
ToolBarWithFilter.FilterButton = ({ onClick = noop, btnClassName = '' }: IFilterButtonProps) => {
  return (
    <Tooltip title={i18n.t('common:advanced filter')}>
      <Button onClick={onClick} className={btnClassName}>
        <CustomIcon type="filter" />
      </Button>
    </Tooltip>
  );
};
Example #16
Source File: UndoRedo.tsx    From dnde with GNU General Public License v3.0 6 votes vote down vote up
UndoRedo = ({ undoCallback, redoCallback }: UndoRedoProps) => {
  return (
    <div
      style={{
        position: 'fixed',
        padding: '8px',
        display: 'flex',
        flexDirection: 'column',
        rowGap: '4px',
        zIndex: 200,
      }}
    >
      <Tooltip mouseEnterDelay={0.5} color="cyan" title="undo" placement="right">
        <Button
          disabled={UNDOREDO.isUndoEmpty()}
          onClick={undoCallback}
          type="default"
          size="large"
          style={{ background: '#fff' }}
          icon={<UndoOutlined />}
        />
      </Tooltip>

      <Tooltip mouseEnterDelay={0.5} color="cyan" title="redo" placement="right">
        <Button
          disabled={UNDOREDO.isRedoEmpty()}
          onClick={redoCallback}
          type="default"
          style={{ background: '#fff' }}
          size="large"
          icon={<RedoOutlined />}
        />
      </Tooltip>
    </div>
  );
}
Example #17
Source File: DataTableListEditor.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
function ListItemTag(props: ListItemTagProps) {
  const { item, onClose } = props;
  const isLong = item.caption.length > 20;
  const tag = (
    <Tag closable={true}
         onClose={() => onClose(item)}>
      {isLong ? `${item.caption.substr(0, 20)}...` : item.caption}
    </Tag>
  );

  return isLong ? (
    <Tooltip title={item.caption}>
      {tag}
    </Tooltip>
  ) : (
    tag
  );
}
Example #18
Source File: CouponTag.tsx    From Shopping-Cart with MIT License 6 votes vote down vote up
CouponTag: FC<PropTypes> = props => {
  const { label, color, tooltip } = props;

  return (
    <Tooltip title={tooltip} placement="bottom">
      <Tag color={color}>
        {label}
        <Icon
          type="question-circle"
          theme="twoTone"
          style={{ marginLeft: 3 }}
        />
      </Tag>
    </Tooltip>
  );
}
Example #19
Source File: Align.tsx    From dnde with GNU General Public License v3.0 6 votes vote down vote up
Align = () => {
  const [visible, path] = useVisibility({ attribute: ATTRIBUTE });
  const { mjmlJson, setMjmlJson } = useEditor();
  const { active } = useHtmlWrapper();

  const onClick = (align: string) => {
    if (active && visible && path) {
      let item = _.get(mjmlJson, path);
      if (item && item.attributes && item.attributes) {
        item.attributes['align'] = align;
        const updated = _.set(mjmlJson, path, item);
        setMjmlJson({ ...updated });
      }
    }
  };

  return visible ? (
    <Row>
      <Col flex="3">
        <Form.Item label="Align"></Form.Item>
      </Col>
      <Col flex="2">
        <Row justify="space-between">
          {alignOptions.map(({ prop, component, title }, key) => {
            return (
              <Col key={key}>
                <Tooltip title={title}>
                  <Button onClick={() => onClick(prop)} type="ghost" icon={component} />
                </Tooltip>
              </Col>
            );
          })}
        </Row>
      </Col>
    </Row>
  ) : null;
}
Example #20
Source File: LineItem.tsx    From yugong with MIT License 6 votes vote down vote up
LineItem: React.FC<Props> = ({ label, describe, children }) => {
  return (
    <Row className={s.row} gutter={10}>
      <Col span={4} className={s.label}>
        {describe ? <Tooltip
          placement="topRight"
          title={parse(describe || '')}
        >
          {label}
        </Tooltip> : label}
      </Col>
      <Col span={20}>
        {children}
      </Col>
    </Row>
  )
}
Example #21
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
BackToTop = ({ containerId }: { containerId?: string }) => {
  const [visible, setVisible] = React.useState(false);
  const isMoving = React.useRef(false);
  const mainElement = React.useMemo(
    () => document.querySelector(containerId ? `#${containerId}` : '#main'),
    [containerId],
  );

  const handleScroll = React.useCallback(
    throttle(() => {
      const isV = mainElement ? mainElement.scrollTop * 1.25 > mainElement!.clientHeight : false;
      setVisible(isV);
    }, 300),
    [mainElement],
  );

  useEffectOnce(() => {
    mainElement && mainElement.addEventListener('scroll', handleScroll);
    return () => {
      mainElement && mainElement.removeEventListener('scroll', handleScroll);
    };
  });

  const onBackToTop = () => {
    if (isMoving.current) {
      return;
    }
    isMoving.current = true;
    mainElement!.scrollTo({ top: 0, behavior: 'smooth' });
    isMoving.current = false;
  };

  return visible ? (
    <Tooltip title={i18n.t('Back to Top')}>
      <ErdaIcon size="20" className="scroll-top-btn" type="huidaodingbu" onClick={onBackToTop} />
    </Tooltip>
  ) : null;
}
Example #22
Source File: index.tsx    From RareCamp with Apache License 2.0 6 votes vote down vote up
export default function PageHeading({
  title,
  description,
  renderEdit,
}: {
  title?: string
  description?: string
  renderEdit?: any
}) {
  return (
    <Space>
      <PageTitle title={title} />
      {description ? (
        <Tooltip placement="bottom" title={description}>
          <InfoCircleOutlined />
        </Tooltip>
      ) : null}
      {renderEdit ? renderEdit() : null}
    </Space>
  )
}
Example #23
Source File: Timestamp.tsx    From posthog-foss with MIT License 6 votes vote down vote up
export function Timestamp(): JSX.Element {
    const { seekBackward, seekForward } = useActions(sessionRecordingPlayerLogic)
    const { jumpTimeMs, currentPlayerTime, sessionPlayerData } = useValues(sessionRecordingPlayerLogic)
    const { isScrubbing, scrubbingTime } = useValues(seekbarLogic)

    return (
        <>
            <Tooltip
                placement="top"
                overlayInnerStyle={{ minHeight: 'auto' }}
                overlay={`Back ${jumpTimeMs / 1000}s (← left arrow)`}
            >
                <span>
                    <IconSeekBack onClick={seekBackward} time={jumpTimeMs / 1000} />
                </span>
            </Tooltip>
            <Tooltip
                placement="top"
                overlayInnerStyle={{ minHeight: 'auto' }}
                overlay={`Forward ${jumpTimeMs / 1000}s (→ right arrow)`}
            >
                <span>
                    <IconSeekForward onClick={seekForward} time={jumpTimeMs / 1000} />
                </span>
            </Tooltip>
            <div className="rrweb-timestamp">
                {colonDelimitedDuration(((isScrubbing ? scrubbingTime : currentPlayerTime) ?? 0) / 1000)} /{' '}
                {colonDelimitedDuration(Math.floor((sessionPlayerData?.metadata?.recordingDurationMs ?? 0) / 1000))}
            </div>
        </>
    )
}
Example #24
Source File: utils.tsx    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
getRender = (val: Obj, record: Obj, extra?: Extra) => {
  const { type, data, key } = val || {};
  let Comp: React.ReactNode = null;
  const { userMap = {} } = extra || {};

  if (!data) {
    return '-';
  }

  switch (type) {
    case 'multiple':
      {
        const { props } = extra || ({} as Extra);
        const render = get(props, `columnsRender.${key}`) || defaultMultiple;

        const CompMap = {};
        map(data, (v, k) => {
          CompMap[k] = getRender(v, record, extra);
        });
        Comp = <div>{render(val, record, CompMap)}</div>;
      }
      break;
    case 'icon':
      {
        const { type: iconType, url } = data;
        if (url) {
          Comp = <img src={url} />;
        } else if (iconType) {
          Comp = <ErdaIcon isConfigPageIcon size={16} type={iconType} />;
        } else {
          Comp = '';
        }
      }
      break;
    case 'duration':
      {
        const { value, tip } = data;
        if (!value) {
          Comp = '0s';
        } else if (value === -1) {
          Comp = '-';
        } else {
          const _duration = moment.duration(value, 'seconds');
          const duration = [
            { value: _duration.years(), unit: 'y' },
            { value: _duration.months(), unit: 'm' },
            { value: _duration.days(), unit: 'd' },
            { value: _duration.hours(), unit: 'h' },
            { value: _duration.minutes(), unit: 'min' },
            { value: _duration.seconds(), unit: 's' },
          ];
          const durationArr = duration.filter((item) => item.value) || [];
          const durationStr = durationArr.map((item) => `${item.value}${item.unit}`).join('');
          Comp = tip ? <Tooltip title={tip}>{durationStr}</Tooltip> : durationStr;
        }
      }
      break;
    case 'progressBar':
      {
        const { barCompletedNum, barTotalNum, barPercent, text, status, tip } = data;
        const value = barPercent || (barCompletedNum / barTotalNum) * 100 || 0;

        const content = (
          <>
            <Progress
              percent={value}
              type="circle"
              width={20}
              strokeWidth={18}
              format={() => null}
              strokeColor={statusColorMap[status]}
            />
            <span className="text-black-8  ml-2">{text}</span>
          </>
        );
        Comp = tip ? <Tooltip title={tip}>{content}</Tooltip> : content;
      }
      break;
    case 'user':
      const curUsers = [];
      if (isArray(data.id)) {
        data.id.forEach((vItem: any) => {
          curUsers.push(userMap[vItem] || {});
        });
      } else {
        curUsers.push(userMap[data.id] || {});
      }
      if (data.showIcon === false) {
        Comp = map(curUsers, (item) => item.nick || item.name || item.id || i18n.t('common:None')).join(', ');
      } else {
        Comp = (
          <div>
            {map(curUsers, (cU, idx) => {
              return (
                <span key={idx}>
                  {data.showIcon === false ? null : (
                    <Avatar src={cU.avatar} size="small">
                      {cU.nick ? getAvatarChars(cU.nick) : i18n.t('None')}
                    </Avatar>
                  )}
                  <span className="ml-0.5 mr-1" title={cU.name}>
                    {cU.nick || cU.name || data.value || i18n.t('common:None')}
                  </span>
                </span>
              );
            })}
          </div>
        );
      }
      break;
    case 'dropDownMenu':
      // {
      // const {menus, operations} = data || {};
      // Comp = <DropdownSelectNew options={} />
      // }
      break;
    case 'text':
      if (typeof data === 'string') {
        Comp = data;
      } else if (typeof data === 'object') {
        const { text, enableCopy, status, showDot = false, tip, onlyText = false } = data;
        let value = status ? <Badge text={text} status={status} showDot={showDot} onlyText={onlyText} /> : text;

        if (tip) {
          value = (
            <Tooltip overlayClassName="whitespace-pre" title={tip} className="truncate w-full inline-block">
              {value}
            </Tooltip>
          );
        } else {
          value = <Ellipsis title={value} />;
        }

        Comp = enableCopy ? (
          <span className="flex group">
            <span className="ant-table-cell-ellipsis group-hover:text-purple-deep" title={text}>
              {text}
            </span>
            <Copy>
              <ErdaIcon
                type="fz1"
                size={12}
                data-clipboard-text={text}
                onClick={(e) => e.stopPropagation()}
                className="ml-1 cursor-copy text-desc opacity-0 group-hover:text-purple-deep group-hover:opacity-100"
              />
            </Copy>
          </span>
        ) : (
          value
        );
      }
      break;
    case 'labels':
      {
        const { labels, showCount } = data;
        // TODO showCount should be calculated based on the container width
        Comp = (
          <TagsRow
            labels={labels.map((item: { id: string; title?: string; color?: string; group?: string }) => ({
              ...item,
              label: item.title || item.id,
            }))}
            showCount={showCount ?? 2}
          />
        );
      }
      break;
    case 'moreOperations':
      {
        const { ops } = data;

        const getIcon = (icon: { type?: string; url?: string }) => {
          if (icon.type) {
            return <ErdaIcon type={icon.type} color="currentColor" className="mr-1 text-white-6" />;
          }
          if (icon.url) {
            return <img src={icon.url} />;
          }
          return null;
        };

        const getTableOperationItem = (op: CP_COMMON.Operation, key: string, record: Obj) => {
          const { confirm, disabled, disabledTip, text, icon, operations } = op;
          const { click } = operations || {};
          const { serverData } = click || {};
          if (disabled === true) {
            // 无权限操作
            return (
              <Menu.Item key={key} className="p-0">
                <WithAuth noAuthTip={disabledTip} key={key} pass={false}>
                  <span className="table-operations-btn px-4 py-1 block flex-h-center">
                    {icon ? getIcon(icon) : null}
                    {text}
                  </span>
                </WithAuth>
              </Menu.Item>
            );
          } else if (confirm) {
            // 需要确认的操作
            return (
              <Menu.Item key={key} className="p-0 bg-transparent">
                <Popconfirm
                  title={confirm}
                  onConfirm={(e) => {
                    e && e.stopPropagation();
                    extra?.execOperation({
                      key: 'click',
                      ...click,
                      clientData: {
                        dataRef: op,
                        parentDataRef: record,
                      },
                      serverData,
                    });
                    const customFunc = get(extra, `customOp.operations.${key}`);
                    if (customFunc) {
                      customFunc(op, record);
                    }
                  }}
                  key={key}
                  onCancel={(e: any) => e && e.stopPropagation()}
                  zIndex={1100}
                >
                  <span
                    className="table-operations-btn px-4 py-1 block flex-h-center text-white-9"
                    onClick={(e: any) => e.stopPropagation()}
                  >
                    {icon ? getIcon(icon) : null}
                    {text}
                  </span>
                </Popconfirm>
              </Menu.Item>
            );
          } else {
            // 普通的操作
            return (
              <Menu.Item key={key} className="p-0">
                <span
                  className="table-operations-btn px-4 py-1 block flex-h-center text-white-9"
                  key={key}
                  onClick={(e: any) => {
                    e.stopPropagation();
                    extra?.execOperation({
                      key: 'click',
                      ...click,
                      clientData: {
                        dataRef: op,
                        parentDataRef: record,
                      },
                      serverData,
                    });
                    const customFunc = get(extra, `customOp.operations.${key}`);
                    if (customFunc) {
                      customFunc(op, record);
                    }
                  }}
                >
                  {icon ? getIcon(icon) : null}
                  {text}
                </span>
              </Menu.Item>
            );
          }
        };

        const operationList = [] as any[];
        if (ops) {
          // 根据配置的operations展示
          const operations = sortBy(
            filter(map(ops) || [], (item: CP_COMMON.Operation) => item.show !== false),
            'showIndex',
          );

          map(operations, (item: CP_COMMON.Operation) => {
            if (item) {
              operationList.push(getTableOperationItem(item, item.id, record));
            }
          });
        }

        if (!operationList.length) {
          Comp = null;
        } else {
          Comp = (
            <div className="table-operations">
              <Dropdown
                overlay={
                  <Menu theme="dark" style={{ minWidth: 160, padding: '8px 0' }}>
                    {operationList}
                  </Menu>
                }
                align={{ offset: [0, 5] }}
                trigger={['click']}
                overlayStyle={{ zIndex: 1040 }}
              >
                <ErdaIcon
                  type="more"
                  className="cursor-pointer p-1 bg-hover rounded-sm"
                  onClick={(e) => e.stopPropagation()}
                />
              </Dropdown>
            </div>
          );
        }
      }
      break;
    default:
      Comp = (typeof data === 'string' ? data : data?.text) || '-';
      break;
  }
  return Comp;
}
Example #25
Source File: SettingDropdown.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function SettingDropdown(): React.ReactElement {
  const { toolboxTab } = useBuilderUIContext();
  const { t } = useTranslation(NS_NEXT_BUILDER);
  const [visible, setVisible] = useState(false);
  const storage = React.useMemo(() => new JsonStorage(localStorage), []);
  const [showRelatedBricks, setShowRelatedBricks] = React.useState(
    storage.getItem(localStorageKeyForShowRelatedNodesBasedOnEvents) ?? false
  );
  const manager = useBuilderDataManager();

  const handleClick = (): void => {
    setVisible(!visible);
  };

  const handleVisibleChange = (value: boolean): void => {
    setVisible(value);
  };

  const handleShowRelatedBricksChange = (value: boolean): void => {
    setShowRelatedBricks(value);
    storage.setItem(localStorageKeyForShowRelatedNodesBasedOnEvents, value);
    if (toolboxTab !== ToolboxTab.EVENTS_VIEW) {
      manager.setShowRelatedNodesBasedOnEvents(value);
    }
  };

  const content = (
    <Menu>
      <div className={styles.settingContainer}>
        <div className={styles.headerContainer}>
          <span>{t(K.SETTINGS)}</span>
        </div>
        <div className={styles.settingItem}>
          <span>{t(K.SHOW_RELATED_NODES_BASED_ON_EVENTS_WHEN_HOVERING)}</span>
          <Switch
            size="small"
            checked={showRelatedBricks}
            onChange={handleShowRelatedBricksChange}
          />
        </div>
      </div>
    </Menu>
  );

  return (
    <Dropdown
      overlay={content}
      overlayClassName={shareStyles.customAnimation}
      trigger={["click"]}
      placement="bottomLeft"
      visible={visible}
      onVisibleChange={handleVisibleChange}
    >
      <Tooltip
        title={t(K.SETTINGS)}
        placement="bottomRight"
        overlayStyle={{
          // Hide tooltip when dropdown is open.
          display: visible ? "none" : undefined,
        }}
      >
        <a
          className={shareStyles.tabLink}
          role="button"
          onClick={handleClick}
          data-testid="setting-btn"
        >
          <SettingOutlined />
        </a>
      </Tooltip>
    </Dropdown>
  );
}
Example #26
Source File: Seeds.tsx    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Component for the GoToSite button on a seed browser card
 * @param url - URL to open
 * @param inVscode - set if within vs code webview, do not set for browser.
 * @returns
 */
export function GoToSiteButton({
  url,
  inVscode,
}: {
  url: string | undefined;
  inVscode: boolean;
}) {
  function onClick() {
    if (url) {
      // If we're in VSCode, the webview does not allow popups, so send a
      // message back to the plugin and open the link from within the plugin
      if (inVscode) {
        postVSCodeMessage({
          type: SeedBrowserMessageType.onOpenUrl,
          data: { data: url },
          source: DMessageSource.webClient,
        } as SeedBrowserMessage);
      } else {
        window.open(url);
      }
    }
  }

  if (url) {
    return (
      <Tooltip placement="top" title="Go to Site">
        <GlobalOutlined key="website" onClick={onClick} />
      </Tooltip>
    );
  } else {
    return (
      <Tooltip placement="top" title="Site Unavailable">
        <DisconnectOutlined key="website" onClick={onClick} />
      </Tooltip>
    );
  }
}
Example #27
Source File: MapChart.tsx    From nodestatus with MIT License 5 votes vote down vote up
MapChart: FC<Props> = props => (
  <div className="bg-rose-500 w-full">
    <ComposableMap
      projection="geoMercator"
      projectionConfig={{ center: [0, 45] }}
      className="w-full h-52 xl:h-72 lg:64 md:h-60 sm:h-56"
    >
      <Geographies geography={geoMap}>
        {({ geographies }) => geographies.filter(d => d.properties.REGION_UN !== 'Antarctica').map(geo => (
          <Geography
            key={geo.rsmKey}
            geography={geo}
            fill="#f9fafb"
            style={{
              default: { outline: 'none' },
              hover: { outline: 'none' },
              pressed: { outline: 'none' }
            }}
          />
        ))}
      </Geographies>
      {
        Object.keys(props.count).map(key => {
          const count = props.count[key];
          const K = key as keyof typeof coordinates;
          if (!coordinates[K]) return;
          const country = countries.getName(key, 'en', { select: 'official' });
          return (
            <Tooltip
              title={`${country}: ${count}`}
              key={key}
            >
              <Marker coordinates={[coordinates[K].lng, coordinates[K].lat]}>
                <circle r={6 + count} fill="#8B5CF6" stroke="#fff" strokeWidth={2} />
              </Marker>
            </Tooltip>
          );
        })
      }
    </ComposableMap>
  </div>
)
Example #28
Source File: SwitchMultiTypes.tsx    From brick-design with MIT License 5 votes vote down vote up
function SwitchMultiTypes(props: SwitchMultiTypesPropsType, ref: any) {
  const {
    types,
    form: { getFieldValue, setFieldsValue, getFieldDecorator },
    field,
    childPropsConfig,
    extraObj = {},
    itemOption = {},
    formItemProps = {},
    tip,
    label,
    componentProps,
  } = props;
  const [type, setType] = useState(types[0]);
  const value = getFieldValue(field);
  useEffect(() => {
    let type = null;
    if (isArray(value)) {
      const firstValue = value[0];
      if (isNumber(firstValue)) {
        type = PROPS_TYPES.numberArray;
      } else if (isString(firstValue)) {
        type = PROPS_TYPES.stringArray;
      } else if (isObject(firstValue)) {
        type = PROPS_TYPES.objectArray;
      }
    } else if (isObject(value)) {
      if (
        isEmpty(childPropsConfig) ||
        !isEqual(keys(value), keys(childPropsConfig))
      ) {
        type = PROPS_TYPES.json;
      } else {
        type = PROPS_TYPES.object;
      }
    } else if (isNumber(value)) {
      type = PROPS_TYPES.number;
    } else if (isString(value)) {
      type = PROPS_TYPES.string;
    } else if (isBoolean(value)) {
      type = PROPS_TYPES.boolean;
    }
    type && setType(type);
  }, []);

  useEffect(() => {
    setFieldsValue({ [field]: value });
  }, [type]);

  if (type === PROPS_TYPES.boolean) {
    extraObj.valuePropName = 'checked';
  }
  return (
    <FormItem
      style={{ marginLeft: 10, marginRight: 10, marginBottom: 5 }}
      {...formItemProps}
      label={
        <div className={styles['multi-type']}>
          <Tooltip title={`${field}:${tip || label}`}>{label}</Tooltip>
          <EnumComponent
            value={type}
            enumData={types}
            allowClear={false}
            style={{ width: 90, marginLeft: 10 }}
            onChange={(newType) => setType(newType)}
          />
        </div>
      }
    >
      {getFieldDecorator(field, { ...extraObj, ...itemOption })(
        createElement(get(TYPES_TO_COMPONENT, type), {
          ...componentProps,
          type,
          size: type === PROPS_TYPES.boolean ? 'default' : 'small',
        }),
      )}
    </FormItem>
  );
}
Example #29
Source File: StatisticCard.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function StatisticCard(props: StatisticCardProps): React.ReactElement {
  const { title, value, icon, iconType, url, tip, disabled, showCard } = props;

  const getIconNode = () => {
    switch (iconType) {
      case "fa":
        return <i className={`fa ${icon}`} />;
      case "svg": {
        const parser = new Parser();
        return (
          <Icon
            component={(props) => {
              const { children, ...iconProps } = props;

              return React.cloneElement(
                parser.parse(icon as string),
                iconProps
              );
            }}
          />
        );
      }
      case "antd":
      default:
        return <LegacyIcon type={icon as string} />;
    }
  };

  const getContentNode = () => (
    <div
      className={classNames(styles.statisticCardContentContainer, {
        [styles.disabled]: disabled,
      })}
    >
      <div className={styles.statisticCardContent}>
        <div className={styles.statisticCardValue}>
          {value !== undefined ? value : "-"}
        </div>
        <div className={styles.statisticCardTitle}>{title}</div>
      </div>
      {iconType ? (
        <div className={styles.statisticCardIcon}>{getIconNode()}</div>
      ) : (
        <div className={styles.statisticCardIcon}>
          <GeneralIcon icon={icon as MenuIcon}></GeneralIcon>
        </div>
      )}
    </div>
  );

  const getStatisticCardNode = (hoverable = false) => {
    const node = showCard ? (
      <Card
        className={styles.statisticCard}
        bordered={false}
        hoverable={hoverable}
      >
        {getContentNode()}
      </Card>
    ) : (
      getContentNode()
    );

    return tip ? <Tooltip title={tip}>{node}</Tooltip> : node;
  };

  return url && !disabled ? (
    <Link to={url}>{getStatisticCardNode(true)}</Link>
  ) : (
    getStatisticCardNode()
  );
}