antd#Popover TypeScript Examples

The following examples show how to use antd#Popover. 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: DataTableSettings.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
DataTableSettings = observer(<T, >({
  columns,
  fieldsVisibility,
  onChange
}: DataTableSettingsProps<T>) => {
  const intl = useIntl();
  const content = <List
    dataSource={columns}
    renderItem={item => (
      <List.Item>
        <Checkbox
            checked = {fieldsVisibility.get(item.key as string)}
            onChange={ev => onChange(item.key as string, ev.target.checked)}
        >
          {item.title}
        </Checkbox>
      </List.Item>
    )}
  />;

  return <Popover
    placement="bottom"
    title={intl.formatMessage({id: 'jmix.dataTable.fieldsVisibility'})}
    content={content} 
    trigger="click"
  >
    <Button>
      <SettingOutlined />
    </Button>
  </Popover>
})
Example #2
Source File: index.tsx    From drip-table with MIT License 6 votes vote down vote up
private renderAttributeItem(schema: DTGComponentPropertySchema, index: number, parentIndex: number) {
    if (!this.visible(schema, index, parentIndex)) { return null; }
    return (
      <Row key={index} style={{ lineHeight: '32px', margin: '6px 0' }}>
        <Col span={8}>
          { schema['ui:title'] }
          {
            schema['ui:description']
              ? (
                <Popover content={<RichText html={schema['ui:description'].title} />}>
                  <QuestionCircleOutlined style={{ marginLeft: '12px', cursor: 'pointer' }} />
                </Popover>
              )
              : null
          }
        </Col>
        <Col span={16}>{ this.renderAttributeComponent(schema, index, parentIndex) }</Col>
      </Row>
    );
  }
Example #3
Source File: PluginError.tsx    From posthog-foss with MIT License 6 votes vote down vote up
export function PluginError({ error, reset }: { error: PluginErrorType; reset?: () => void }): JSX.Element | null {
    if (!error) {
        return null
    }
    return (
        <Popover
            title={<div style={{ textAlign: 'center' }}>{dayjs(error.time).format('YYYY-MM-DD - HH:mm:ss')}</div>}
            content={
                <>
                    {reset ? (
                        <Button size="small" onClick={reset} style={{ float: 'right', marginLeft: 10 }}>
                            <ClearOutlined /> Delete
                        </Button>
                    ) : null}
                    <div>
                        {error.name ? <strong>{error.name}: </strong> : ''}
                        {error.message}
                    </div>
                    {error.stack ? (
                        <CodeSnippet wrap style={{ fontSize: 10 }} language={Language.JavaScript}>
                            {error.stack}
                        </CodeSnippet>
                    ) : null}
                    {error.event ? (
                        <CodeSnippet wrap style={{ fontSize: 10 }} language={Language.JSON}>
                            {JSON.stringify(error.event, null, 2)}
                        </CodeSnippet>
                    ) : null}
                </>
            }
            trigger="click"
            placement="top"
        >
            <Tag color="red" style={{ cursor: 'pointer' }}>
                ERROR
            </Tag>
        </Popover>
    )
}
Example #4
Source File: index.tsx    From S2 with MIT License 6 votes vote down vote up
Switcher: FC<SwitcherProps> = ({
  title,
  popover,
  disabled,
  ...otherProps
}) => {
  const [visible, setVisible] = useState(false);

  const onToggleVisible = () => {
    setVisible((prev) => !prev);
  };

  return (
    <Popover
      visible={!disabled && visible}
      content={
        <SwitcherContent {...otherProps} onToggleVisible={onToggleVisible} />
      }
      onVisibleChange={onToggleVisible}
      trigger="click"
      placement="bottomLeft"
      destroyTooltipOnHide
      {...popover}
    >
      {title || (
        <Button
          className={getSwitcherClassName('entry-button')}
          size="small"
          disabled={disabled}
          icon={<SwitcherIcon />}
        >
          {i18n('行列切换')}
        </Button>
      )}
    </Popover>
  );
}
Example #5
Source File: ToolboxPane.spec.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
describe("ToolboxPane", () => {
  it("should work", () => {
    const wrapper = shallow(
      <ToolboxPane title="Storyboard">Content</ToolboxPane>
    );
    expect(wrapper.find(".toolboxPaneTitle").text()).toBe("Storyboard");
    expect(wrapper.find(".toolboxPaneTooltips").length).toBe(0);
  });

  it("should show tooltips", () => {
    const wrapper = shallow(
      <ToolboxPane title="Storyboard" tooltips="For good">
        Content
      </ToolboxPane>
    );
    expect(wrapper.find(Popover).prop("content")).toBe("For good");
    expect(
      wrapper.find(Popover).invoke("getPopupContainer")({
        parentElement: "fake",
      } as any)
    ).toBe("fake");
  });
});
Example #6
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
MenuPopover = ({ content, styleName, placement, iconStyle = 'sm-more-icon', trigger }: IProps) => {
  const [visible, setVisible] = React.useState(false);

  return (
    <Popover
      placement={placement || 'bottom'}
      visible={visible}
      overlayClassName={`menu-popover ${styleName || ''}`}
      content={content(setVisible)}
      trigger={trigger || 'click'}
      onVisibleChange={setVisible}
    >
      <ErdaIcon type="more" className={`${iconStyle} hover-active`} onClick={(e) => e.stopPropagation()} />
    </Popover>
  );
}
Example #7
Source File: index.tsx    From web-pdm with Apache License 2.0 6 votes vote down vote up
ReactDom.render(
    <WebPdm
        components={{ Input, Button, Dropdown, Menu, Select, Tooltip, Tree, Popover }}
        themeColor='green'
        darkness={false}
        models={models}
        modules={modules}
        erdkey={'demo'}
        onIntl={onIntl}
        onlyMode={false}
        // disableIcons={['full', 'reload']}
        IconRenders={{
            ...IconRenders,
            image: <Button size="small" >下载</Button>,
            miniMap: <Button size="small" >显示小地图</Button>,
            miniMapNo: <Button size="small" >屏蔽小地图</Button>,

        }}
        // intl='EN'
        onReload={onReload}
        onModelDetail={a => {
            alert(`打开模型${a.label}(${a.name}) 的查看链接`)
        }}
        onIgnoreEdge={onIgnoreEdge}
    />,
    document.getElementById('app') || document.getElementById('root')
)
Example #8
Source File: info.tsx    From metaplex with Apache License 2.0 6 votes vote down vote up
Info = (props: {
  text: React.ReactElement;
  style?: React.CSSProperties;
}) => {
  return (
    <Popover
      trigger="hover"
      content={<div style={{ width: 300 }}>{props.text}</div>}
    >
      <Button type="text" shape="circle">
        <InfoCircleOutlined style={props.style} />
      </Button>
    </Popover>
  );
}
Example #9
Source File: TcPopover.tsx    From tailchat with GNU General Public License v3.0 6 votes vote down vote up
TcPopover: React.FC<PopoverProps> = React.memo((props) => {
  const [visible, setVisible] = useState(false);

  const handleVisibleChange = useCallback(
    (v) => {
      setVisible(v);

      typeof props.onVisibleChange === 'function' && props.onVisibleChange(v);
    },
    [props.onVisibleChange]
  );

  const closePopover = useCallback(() => {
    setVisible(false);

    typeof props.onVisibleChange === 'function' && props.onVisibleChange(false);
  }, []);

  const handler = useMemo(() => ({ closePopover }), [closePopover]);

  return (
    <TcPopoverContext.Provider value={handler}>
      <Popover
        {...props}
        visible={visible}
        onVisibleChange={handleVisibleChange}
      />
    </TcPopoverContext.Provider>
  );
})
Example #10
Source File: index.tsx    From whiteboard-demo with MIT License 6 votes vote down vote up
public render(): React.ReactNode {
        const { isActive } = this.state;
        return (
            <>
                <TopLoadingBar style={{ backgroundColor: "#71C3FC", height: 4 }} loadingPercent={this.state.ossPercent} />
                <TopLoadingBar style={{ backgroundColor: "#71C3FC", height: 4 }}
                    loadingPercent={this.state.converterPercent} />
                <Popover trigger="hover"
                    key={"oss-upload-popper"}
                    onVisibleChange={this.handleVisibleChange}
                    placement={"leftBottom"}
                    content={this.renderUploadButton()}>
                    <div className="oss-upload-cell-box-left">
                        <div className="oss-upload-cell">
                            <img src={isActive ? uploadActive : upload} alt={"upload"} />
                        </div>
                    </div>
                </Popover>
            </>
        );
    }
Example #11
Source File: LanguageSwitch.tsx    From mayoor with MIT License 6 votes vote down vote up
LanguageSwitch: React.FC = () => {
	const { i18n } = useTranslation();
	const [isVisible, setIsVisible] = useState(false);

	const handleLanguageChange = (language: string) => {
		localStorage.setItem('default-language', language);
		i18n.changeLanguage(language);
	};
	return (
		<Popover
			content={
				<Button.Group>
					{[
						{ code: 'en', languageName: 'English' },
						{ code: 'cs', languageName: 'Čeština' },
					].map(({ code, languageName }) => (
						<Button
							key={code}
							onClick={() => handleLanguageChange(code)}
							disabled={i18n.language === code}
						>
							{languageName}
						</Button>
					))}
				</Button.Group>
			}
			trigger="click"
			placement="bottom"
			visible={isVisible}
			onVisibleChange={setIsVisible}
		>
			<Button icon={<GlobalOutlined />} shape="circle" type="link" />
		</Popover>
	);
}
Example #12
Source File: RecentTransactions.tsx    From nanolooker with MIT License 6 votes vote down vote up
RecentTransactionsPreferences: React.FC = () => {
  return (
    <>
      <Popover
        placement="left"
        content={
          <Card size="small" bordered={false} className="detail-layout">
            <LiveTransactionsPreferences />
            <FilterTransactionsPreferences />
          </Card>
        }
        trigger="click"
      >
        <SettingOutlined />
      </Popover>
    </>
  );
}
Example #13
Source File: index.tsx    From datart with Apache License 2.0 6 votes vote down vote up
export function Popup({
  content,
  overlayClassName,
  onVisibleChange,
  ...rest
}: PopoverProps) {
  const [visible, setVisible] = useState(false);

  const visibleChange = useCallback(
    v => {
      setVisible(v);
      onVisibleChange && onVisibleChange(v);
    },
    [onVisibleChange],
  );

  const onClose = useCallback(() => {
    setVisible(false);
  }, []);

  const injectedContent = useMemo(
    () =>
      isValidElement(content) ? cloneElement(content, { onClose }) : content,
    [content, onClose],
  );

  const className = mergeClassNames(overlayClassName, 'datart-popup');
  return (
    <Popover
      {...rest}
      overlayClassName={className}
      content={injectedContent}
      visible={visible}
      onVisibleChange={visibleChange}
    />
  );
}
Example #14
Source File: control-panel.tsx    From covid_dashboard with MIT License 5 votes vote down vote up
render() {
        // const date = dateformat(this.state.date, 'yyyy-mm-dd')
        const regionInfo = this.props.regionInfo || {name_en: '', name_zh: ''}
        let fullName = this.props.env.lang === 'en' ? regionInfo.name_en : regionInfo.name_zh
        if (fullName === 'United States of America') fullName = "United States"
        else if (fullName === 'People\'s Republic of China') fullName = "China"
        fullName = fullName.replace('Republic', 'Rep.').replace('Democratic', 'Dem.')
        const ep = this.props.dayEp
        let active: number | undefined = ep ? ((ep.confirmed||0) - (ep.cured||0) - (ep.dead||0)) : undefined;
        let active_delta: number | undefined = ep ? ((ep.confirmed_delta||0) - (ep.cured_delta||0) - (ep.dead_delta||0)) : undefined;
        return <div className="control-panel" style={{pointerEvents: 'none'}}>
            {
                !this.props.env.isMobile && (
                    <div className="side-panel left-side-panel">
                        <div className="mask"/>
                        <div className="row">
                            <div className="block" style={{left: 0, background: '#442121'}}>
                                <div className="title"><i className="fas fa-medkit"></i>
                                    <FormattedMessage id="map.control.confirmed"/>
                                </div>
                                <div className="agg">{displayNumber(ep?.confirmed)}</div>
                                <div className="inc">{this.sS(ep?.confirmed_delta)}</div>
                            </div>
                            <div className="block" style={{left: '25%', background: '#605041'}}>
                                <div className="title"><i className="fas fa-diagnoses"></i>
                                    <FormattedMessage id="map.control.active"/>
                                </div>
                                <div className="agg">{displayNumber(active)}</div>
                                <div className="inc">{this.sS(active_delta)}</div>
                            </div>
                            <div className="block" style={{left: '50%', background: '#244c26'}}>
                                <div className="title"><i className="fas fa-star-of-life"></i>
                                    <FormattedMessage id="map.control.cured"/>
                                </div>
                                <div className="agg">{displayNumber(ep?.cured)}</div>
                                <div className="inc">{this.sS(ep?.cured_delta)}</div>
                            </div>
                            <div className="block" style={{left: '75%', background: '#161616'}}>
                                <div className="title"><i className="fas fa-skull-crossbones"></i>
                                    <FormattedMessage id="map.control.dead"/>
                                </div>
                                <div className="agg">{displayNumber(ep?.dead)}</div>
                                <div className="inc">{this.sS(ep?.dead_delta)}</div>
                            </div>
                        </div>
                    </div>
                )
            }
            <TimeSlider
                env={this.props.env}
                transData={this.props.transData}
                epData={this.props.epData}
                onChangeTime={d => this.onChangeTime(d)} mapName={fullName}
                onChangeSpeed={this.props.onChangeSpeed} />
            <Popover
                title={this.props.env.lang == 'zh' ? "风险指数" : "Risk Index"}
                placement='bottom'
                content={this.popover()}>
                <div className="main-circle">
                    <div className='region' ref={(e) => this.regionNameElement = e}>{fullName}</div>
                    <div className="title">
                        <FormattedMessage id="map.control.risk"/>
                    </div>
                    <div className="score">{displayNumber(ep?.risk)}</div>
                </div>
            </Popover>
        </div>
    }
Example #15
Source File: DataTableCell.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
DataTableCell = <EntityType extends unknown>(props: DataTableCellProps<EntityType>): ReactNode => {

  const {type, attributeType, cardinality, name} = props.propertyInfo;

  if ((type as PropertyType) === 'Boolean') {
    return (
      <Checkbox
        checked={props.text as boolean}
        disabled={true}
      />
    );
  }

  if (attributeType === 'ENUM') {
    return (
      <EnumCell text={props.text} propertyInfo={props.propertyInfo} mainStore={props.mainStore!}/>
    );
  }

  if (attributeType === 'ASSOCIATION' && (cardinality === 'MANY_TO_MANY' || cardinality === 'ONE_TO_MANY') ||
    attributeType === 'COMPOSITION' && cardinality === 'ONE_TO_MANY') {
    const associatedEntities = props.record?.[name as keyof EntityType] as unknown as SerializedEntityProps[];
    const quantity = associatedEntities.length;
    const content = <>
      {associatedEntities.map((entity, idx) => <div key = {idx}>
        {entity._instanceName}
      </div>)}
    </>

    if (quantity > 2) {
      return <Popover content={content}>
        <Button type="link" style = {{ margin: 0 }}>
          <FormattedMessage id="jmix.nestedEntityField.xEntities" values={{ quantity }}/>
        </Button>
      </Popover>
    }

    const displayValue = associatedEntities?.map(entity => entity._instanceName).join(', ');

    return (
      <div>{displayValue}</div>
    );
  }

  return (
    <div>{toDisplayValue(props.text, props.propertyInfo)}</div>
  );
}
Example #16
Source File: PropertyKeyInfo.tsx    From posthog-foss with MIT License 5 votes vote down vote up
export function PropertyKeyInfo({
    value,
    type = 'event',
    style,
    tooltipPlacement = undefined,
    disablePopover = false,
    disableIcon = false,
    ellipsis = true,
    className = '',
}: PropertyKeyInfoInterface): JSX.Element {
    value = `${value}` // convert to string
    const data = getKeyMapping(value, type)
    if (!data) {
        return (
            <Typography.Text
                ellipsis={ellipsis}
                style={{ color: 'inherit', maxWidth: 400, ...style }}
                title={value}
                className={className}
            >
                {value !== '' ? value : <i>(empty string)</i>}
            </Typography.Text>
        )
    }
    if (disableIcon) {
        return (
            <Typography.Text
                ellipsis={ellipsis}
                style={{ color: 'inherit', maxWidth: 400 }}
                title={data.label}
                className={className}
            >
                {data.label !== '' ? data.label : <i>(empty string)</i>}
            </Typography.Text>
        )
    }

    const innerContent = (
        <span className="property-key-info">
            <span className="property-key-info-logo" />
            {data.label}
        </span>
    )

    const popoverTitle = <PropertyKeyTitle data={data} />
    const popoverContent = <PropertyKeyDescription data={data} value={value} />

    return disablePopover ? (
        innerContent
    ) : tooltipPlacement ? (
        <Popover
            visible
            overlayStyle={{ zIndex: 99999 }}
            overlayClassName={`property-key-info-tooltip ${className || ''}`}
            placement={tooltipPlacement}
            title={popoverTitle}
            content={popoverContent}
        >
            {innerContent}
        </Popover>
    ) : (
        <Popover
            overlayStyle={{ zIndex: 99999 }}
            overlayClassName={`property-key-info-tooltip ${className || ''}`}
            align={ANTD_TOOLTIP_PLACEMENTS.horizontalPreferRight}
            title={popoverTitle}
            content={popoverContent}
        >
            {innerContent}
        </Popover>
    )
}
Example #17
Source File: BasePicker.tsx    From ant-extensions with MIT License 5 votes vote down vote up
BasePicker = React.forwardRef<Input, AnyObject>(
  ({ value, onChange, onVisibleChange, readOnly, disabled, pickerEl: E, ...props }, ref) => {
    const refDropdown = useRef<typeof Popover>(null);
    const [visible, setVisible] = useState(false);

    const [_value, setValue] = useState(value);
    const isDisabled = useMemo(() => disabled || readOnly, [disabled, readOnly]);

    useEffect(() => {
      setValue(value);
    }, [value]);
    const doUpdate = useCallback(
      (v: DateValue) => {
        setValue(v);
        setVisible(false);
        onChange && onChange(v);
      },
      [onChange]
    );

    const toggleVisible = useCallback(
      (v) => {
        if (!isDisabled) {
          setVisible(v);
          onVisibleChange && onVisibleChange(v);
        }
      },
      [onVisibleChange, isDisabled]
    );

    return (
      <div className="ant-ext-sd__input">
        <Tooltip overlayClassName="ant-ext-sd__tooltip" title={DateUtils.toString(_value)}>
          <Popover
            ref={refDropdown}
            visible={visible}
            destroyTooltipOnHide
            onVisibleChange={toggleVisible}
            overlayClassName="ant-ext-sd__popover"
            content={!readOnly && <E dropdown={refDropdown} value={value} onChange={doUpdate} />}
            trigger="click"
            placement="bottomLeft"
          >
            <DateInput
              ref={ref}
              {...props}
              value={value}
              readOnly={readOnly}
              disabled={disabled}
              onBlur={(e) => !withinDropdown(e.relatedTarget as HTMLElement) && setVisible(false)}
            />
          </Popover>
        </Tooltip>
      </div>
    );
  }
)
Example #18
Source File: CustomInlineEditor.tsx    From dnde with GNU General Public License v3.0 5 votes vote down vote up
LinkItem = ({ setLinkCallback }: LinkItemProps) => {
  const [active, setActive] = useState(false);
  const [link, setLink] = useState('');
  const linkRef = useRef<any>(null);

  const onChange = (e: any) => {
    setLink(e.target.value);
  };

  const onMouseDown = (e: any) => {
    restoreSelection();
  };

  return (
    <Popover
      visible={active}
      content={
        <div style={{ display: 'flex', gap: '8px' }}>
          <Input
            className="inline-editor-link"
            ref={linkRef}
            value={link}
            onMouseDown={onMouseDown}
            onChange={onChange}
            placeholder="link"
          />
          <Button
            type="default"
            onMouseDown={ResetEventBehaviour}
            onClick={() => {
              setActive(false);
              restoreSelection();
              document.execCommand(
                'insertHTML',
                false,
                '<a href="' + addHttps(link) + '" target="_blank">' + document.getSelection() + '</a>'
              );
            }}
          >
            create
          </Button>
        </div>
      }
      trigger="click"
      placement="bottom"
    >
      <Button
        style={{ fontSize: '12px' }}
        onClick={(e) => {
          ResetEventBehaviour(e);
          setActive(!active);
          setLink('');
        }}
        size="small"
        icon={<LinkOutlined />}
      ></Button>
    </Popover>
  );
}
Example #19
Source File: custom-generate-palette.tsx    From S2 with MIT License 5 votes vote down vote up
fetch(
  'https://gw.alipayobjects.com/os/bmw-prod/2a5dbbc8-d0a7-4d02-b7c9-34f6ca63cff6.json',
)
  .then((res) => res.json())
  .then((dataCfg) => {
    const s2Options = {
      width: 600,
      height: 480,
    };

    function App() {
      const [themeColor, setThemeColor] = useState('#EA1720');
      const [themeCfg, setThemeCfg] = useState<ThemeCfg>({
        name: 'colorful',
      });

      const updatePalette = (newThemeColor) => {
        // 使用内置的 colorful 色板作为参考色板
        const palette = getPalette(themeCfg.name);
        // 使用参考色板 & 主题色值生成新色板
        const newPalette = generatePalette({
          ...palette,
          brandColor: newThemeColor,
        });

        // 使用新色板设置主题
        setThemeCfg({
          name: themeCfg.name,
          palette: newPalette,
        });
      };

      useEffect(() => {
        updatePalette(themeColor);
      }, []);

      return (
        <Space direction="vertical">
          <Space>
            <span>当前主题色: {themeColor}</span>
            <Popover
              placement="bottomRight"
              content={
                <ChromePicker
                  disableAlpha
                  color={themeColor}
                  onChangeComplete={(color) => {
                    setThemeColor(color.hex);
                    updatePalette(color.hex);
                  }}
                />
              }
            >
              <Button size="small" style={{ marginLeft: 20 }}>
                主题色调整
              </Button>
            </Popover>
          </Space>
          <SheetComponent
            dataCfg={dataCfg}
            options={s2Options}
            themeCfg={themeCfg}
          />
        </Space>
      );
    }

    ReactDOM.render(<App />, document.getElementById('container'));
  });
Example #20
Source File: Relation.tsx    From XFlow with MIT License 5 votes vote down vote up
Relation = (props: Props) => {
  const relation: RelationCanvasModel = props?.data

  const renderRelationOperationItem = (relation: RelationCanvasModel) => {
    const sourcePropertyName = relation?.source
    const targetPropertyName = relation?.target
    return (
      <div className="relation-operation-item" key={relation.id}>
        <div className="relation-operation-item-content">
          <Tooltip placement="top" title={sourcePropertyName}>
            <span className="relation-property-source">{sourcePropertyName}</span>
          </Tooltip>
          (N:1)
          <Tooltip placement="top" title={targetPropertyName}>
            <span className="relation-property-target">{targetPropertyName}</span>
          </Tooltip>
        </div>
        <Popconfirm
          placement="leftTop"
          title="你确定要删除该关系吗"
          okText="确定"
          cancelText="取消"
          onConfirm={() => {
            props?.deleteRelation(relation.id)
          }}
        >
          <ScissorOutlined />
        </Popconfirm>
      </div>
    )
  }

  const renderPopoverContent = () => {
    return (
      <div className="relation-operation-container">{renderRelationOperationItem(relation)}</div>
    )
  }

  return (
    <Popover
      trigger={'hover'}
      content={renderPopoverContent()}
      overlayClassName="relation-operation-popover"
    >
      <div className="relation-count-container">{1}</div>
    </Popover>
  )
}
Example #21
Source File: PopoverContainer.spec.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
describe("PopoverContainer", () => {
  it("should work", () => {
    const onVisibleChange = jest.fn();
    const wrapper = mount(
      <PopoverContainer
        displayBrick={props.displayBrick}
        popoverBrick={props.popoverBrick}
        onVisibleChange={onVisibleChange}
        showPopoverBg={props.showPopoverBg}
        popoverContentStyle={props.popoverContentStyle}
        triggerByIcon={true}
        showIcon="hover"
      />
    );
    expect(wrapper.find("BrickAsComponent").length).toBe(1);
    wrapper.find(".editIcon").simulate("click");
    expect(onVisibleChange).toHaveBeenCalled();
    wrapper.setProps({
      visible: true,
      popoverContentStyle: {
        width: 50,
      },
      showPopoverBg: true,
    });
    wrapper.update();
    expect(wrapper.find("BrickAsComponent").length).toBe(2);
    wrapper.setProps({
      transferGraphAttrs: true,
      faded: true,
      displayBrick: {
        useBrick: [
          {
            brick: "div",
            properties: {
              textContent: "text",
            },
          },
        ],
      },
    });
    expect(wrapper.find(".displayBrickContainerFaded").length).toBe(1);
    wrapper.setProps({
      displayBrick: null,
    });
    expect(wrapper.find("BrickAsComponent").length).toBe(1);
  });
  it("test showIcon and triggerByIcon", () => {
    const onVisibleChange = jest.fn();
    const wrapper = mount(
      <PopoverContainer
        displayBrick={props.displayBrick}
        popoverBrick={props.popoverBrick}
        onVisibleChange={onVisibleChange}
        showPopoverBg={props.showPopoverBg}
        trigger="hover"
        triggerByIcon={false}
        showIcon="always"
      />
    );
    expect(wrapper.find(".editIconVisible").length).toBe(1);
    wrapper.setProps({
      trigger: "click",
    });
    wrapper.update();
    expect(wrapper.find("BrickAsComponent").length).toBe(1);
    wrapper.find(".displayBrick").simulate("click");
    expect(wrapper.find("BrickAsComponent").length).toBe(2);
    wrapper.find(".displayBrick").simulate("click");
    expect(wrapper.find(Popover).prop("visible")).toBe(false);
  });
});
Example #22
Source File: upload-plugin.tsx    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
UploadPlugin = (props: any) => {
  let hideLoading: any;
  const getUploadProps = (isImage?: boolean) => ({
    action: '/api/files',
    showUploadList: false,
    headers: {
      'OPENAPI-CSRF-TOKEN': getCookies('OPENAPI-CSRF-TOKEN'),
      org: getOrgFromPath(),
    },
    beforeUpload: (file: any) => {
      const UPLOAD_SIZE_LIMIT = 20; // M
      const isLtSize = file.size / 1024 / 1024 < UPLOAD_SIZE_LIMIT;
      if (!isLtSize) {
        message.warning(i18n.t('common:the uploaded file must not exceed {size}M', { size: UPLOAD_SIZE_LIMIT }));
      }
      return isLtSize;
    },
    onChange: ({ file }: any) => {
      const { status, response } = file;
      if (status === 'uploading' && !hideLoading) {
        hideLoading = message.loading(`${i18n.t('uploading')}...`, 0);
      }
      if (!response) {
        return;
      }
      hideLoading && hideLoading();
      hideLoading = undefined;
      const { success, err, data } = response;
      if (!success) {
        message.error(err.msg);
      } else {
        const { name, size, url } = data;
        props.editor.insertText(`\n${isImage ? '!' : ''}[${name}${size})](${url})\n`);
      }
    },
  });

  return (
    <Popover
      key="yf"
      title={i18n.t('common:Add Attachment')}
      content={
        <div className="upload-plugin-menu">
          <Upload accept=".jpg, .jpeg, .png, .gif" {...getUploadProps(true)}>
            <div className="upload-item hover-active-bg">{i18n.t('common:Upload Image')}</div>
          </Upload>
          <Upload {...getUploadProps()}>
            <div className="upload-item hover-active-bg">{i18n.t('common:Upload File')}</div>
          </Upload>
        </div>
      }
    >
      <span className="button button-type-annex" title="annex">
        <CustomIcon type="fujian" style={{ lineHeight: 'unset', marginRight: 0 }} />
      </span>
    </Popover>
  );
}
Example #23
Source File: ApiKeys.tsx    From jitsu with MIT License 5 votes vote down vote up
ApiKeysComponent: React.FC = () => {
  const keys = apiKeysStore.list
  const services = useServices()
  services.storageService.table("api_keys")

  const [loading, setLoading] = useState<LoadingState>(null)
  const [documentationDrawerKey, setDocumentationDrawerKey] = useState<ApiKey>(null)

  return (
    <>
      <div className="flex flex-row mb-5 items-start justify between">
        <div className="flex-grow flex text-secondaryText">
          Jitsu supports many{" "}
          <Popover
            trigger="click"
            placement="bottom"
            title={null}
            content={
              <div className="w-96 flex-wrap flex justify-center">
                {Object.values(jitsuClientLibraries).map(props => (
                  <div className="mx-3 my-4" key={props.name}>
                    <JitsuClientLibraryCard {...props} />
                  </div>
                ))}
              </div>
            }
          >
            {"\u00A0"}
            <a>languages and frameworks</a>
            {"\u00A0"}
          </Popover>
          !
        </div>
        <div className="flex-shrink">
          <ProjectLink to={"/api-keys/new"}>
            <Button type="primary" size="large" icon={<PlusOutlined />} loading={"NEW" === loading}>
              Generate New Key
            </Button>
          </ProjectLink>
        </div>
      </div>

      <div className="flex flex-wrap justify-center">
        {keys
          .slice()
          .reverse()
          .map(key => (
            <ApiKeyCard apiKey={key} key={key.uid} showDocumentation={() => setDocumentationDrawerKey(key)} />
          ))}
      </div>

      <Drawer width="70%" visible={!!documentationDrawerKey} onClose={() => setDocumentationDrawerKey(null)}>
        {documentationDrawerKey && <KeyDocumentation token={documentationDrawerKey} />}
      </Drawer>
    </>
  )
}
Example #24
Source File: preview.tsx    From visual-layout with MIT License 5 votes vote down vote up
Preview: React.FC<{ projectService: ProjectService }> = ({
  projectService,
}) => {
  const page = projectService.getCurrentPage();
  const options = page?.options;

  return (
    <Popover
      content={
        <Checkbox.Group
          value={options?.previewStyle
            .filter(({ isCanUse }) => isCanUse)
            .map(({ key }) => key)}
          style={{ width: '100%' }}
          onChange={(checkedValue: CheckboxValueType[]) => {
            page.setOptions({
              previewStyle: options?.previewStyle.map(option => {
                return {
                  ...option,
                  isCanUse: checkedValue.includes(option.key) ? true : false,
                };
              }),
            });
          }}
        >
          {options?.previewStyle.map(style => {
            return (
              <Row key={style.key}>
                <Checkbox value={style.key}>{style?.title}</Checkbox>
              </Row>
            );
          })}
        </Checkbox.Group>
      }
      title="预览样式设置"
      placement="bottom"
    >
      <EyeOutlined style={{ fontSize: 20 }} />
    </Popover>
  );
}
Example #25
Source File: out.tsx    From web-pdm with Apache License 2.0 5 votes vote down vote up
WebPdm: React.FunctionComponent<IWebPdmProps> = (props) => {
    return <WebPdmCore
        IconRenders={IconRenders}
        components={{ Input, Button, Dropdown, Menu, Select, Tooltip, Tree, Popover }}
        {...props} />
}
Example #26
Source File: index.tsx    From metaplex with Apache License 2.0 5 votes vote down vote up
AppBar = (props: {
  left?: JSX.Element;
  right?: JSX.Element;
  useWalletBadge?: boolean;
  additionalSettings?: JSX.Element;
}) => {
  const { connected } = useWallet();

  const TopBar = (
    <div className="App-Bar-right">
      {props.left}
      {connected ? (
        <CurrentUserBadge />
      ) : (
        <ConnectButton
          type="text"
          size="large"
          style={{ color: '#2abdd2' }}
          allowWalletChange
        />
      )}
      <Popover
        placement="topRight"
        title={LABELS.SETTINGS_TOOLTIP}
        content={<Settings additionalSettings={props.additionalSettings} />}
        trigger="click"
      >
        <Button
          shape="circle"
          size="large"
          type="text"
          icon={<SettingOutlined />}
        />
      </Popover>
      {props.right}
    </div>
  );

  return TopBar;
}
Example #27
Source File: useRenderPluginMessageInterpreter.tsx    From tailchat with GNU General Public License v3.0 5 votes vote down vote up
export function useRenderPluginMessageInterpreter(message: string) {
  const availableInterpreter = useMemo(
    () =>
      messageInterpreter
        .map(({ name, explainMessage }) => ({
          name,
          render: explainMessage(message),
        }))
        .filter(({ render }) => render !== null),
    [message]
  );

  if (availableInterpreter.length === 0) {
    return null;
  }

  return (
    <span className="align-middle hidden group-hover:inline-block">
      <Popover
        placement="topLeft"
        title={t('消息解释')}
        content={
          <div className="max-w-lg">
            {availableInterpreter.map((ai, i) => (
              <p key={i + (ai.name ?? '')}>
                {ai.name && (
                  <span>
                    {t('来自')} <span className="font-bold">{ai.name}</span> :{' '}
                  </span>
                )}
                {ai.render}
              </p>
            ))}
          </div>
        }
        trigger="click"
      >
        <Icon
          className="cursor-pointer text-base"
          icon="mdi:file-question-outline"
        />
      </Popover>
    </span>
  );
}
Example #28
Source File: index.tsx    From fe-v5 with Apache License 2.0 5 votes vote down vote up
render() {
    const { spinning } = this.state;
    const { extraRender, data, showHeader = true } = this.props;
    const { title, metric } = data;
    const graphConfig = this.getGraphConfig(data);
    return (
      <div className={this.state.legend ? 'graph-container graph-container-hasLegend' : 'graph-container'}>
        {showHeader && (
          <div
            className='graph-header'
            style={{
              height: this.headerHeight,
              lineHeight: `${this.headerHeight}px`,
            }}
          >
            <div>{title || metric}</div>
            <div className='graph-extra'>
              <span className='graph-operationbar-item' key='info'>
                <Popover placement='left' content={this.getContent()} trigger='click' autoAdjustOverflow={false} getPopupContainer={() => document.body}>
                  <Button className='' type='link' size='small' onClick={(e) => e.preventDefault()}>
                    <SettingOutlined />
                  </Button>
                </Popover>
              </span>
              {this.props.isShowRefresh === false ? null : (
                <span className='graph-operationbar-item' key='sync'>
                  <Button type='link' size='small' onClick={(e) => e.preventDefault()}>
                    <SyncOutlined onClick={this.refresh} />
                  </Button>
                </span>
              )}
              {this.props.isShowShare === false ? null : (
                <span className='graph-operationbar-item' key='share'>
                  <Button type='link' size='small' onClick={(e) => e.preventDefault()}>
                    <ShareAltOutlined onClick={this.shareChart} />
                  </Button>
                </span>
              )}
              {extraRender && _.isFunction(extraRender) ? extraRender(this) : null}
            </div>
          </div>
        )}
        {this.props.graphConfigInnerVisible ? (
          <GraphConfigInner
            data={graphConfig}
            onChange={(...args) => {
              this.updateGraphConfig(args[2] || {});
            }}
          />
        ) : null}
        {/* 这个spin有点难搞,因为要第一时间获取chart容器的offsetheight */}
        {/* <Spin spinning={spinning} wrapperClassName='graph-spin'> */}
        {this.renderChart()}
        {/* </Spin> */}
        <Legend
          style={{ display: this.state.legend ? 'block' : 'none', overflowY: 'auto', maxHeight: '35%' }}
          graphConfig={graphConfig}
          series={this.getZoomedSeries()}
          onSelectedChange={this.handleLegendRowSelectedChange}
          comparisonOptions={graphConfig.comparisonOptions}
        />
      </div>
    );
  }
Example #29
Source File: index.tsx    From whiteboard-demo with MIT License 5 votes vote down vote up
private renderDraw = (): React.ReactNode => {
        const {roomState} = this.state;
        const currentApplianceName = roomState.memberState.currentApplianceName;
        if (currentApplianceName === ApplianceNames.shape) {
            const currentShapeType = roomState.memberState.shapeType;
            const description = ToolBox.descriptions[`${currentApplianceName}_${currentShapeType}`];
            const isSelected = currentShapeType === this.currentDrawShape;
            const iconUrl = isSelected ? description.iconActive : description.icon;
            const subscriptUrl = isSelected ? subscriptActive : subscript;
            return (
                <Popover key={"draw"}
                         placement={"right"}
                         trigger="hover"
                         content={this.renderDrawContext}>
                    <div key="draw-inner" className="tool-box-cell-box-left">
                        <div className="tool-box-cell"
                             onClick={() => this.clickAppliance(this.currentDraw)}>
                            <img src={iconUrl} alt={"iconUrl"}/>
                            <img className="tool-box-cell-subscript" src={subscriptUrl} alt={"subscriptUrl"}/>
                        </div>
                    </div>
                </Popover>
            );
        } else {
            const description = ToolBox.descriptions[this.currentDraw]
            const isSelected = currentApplianceName === this.currentDraw;
            const iconUrl = isSelected ? description.iconActive : description.icon;
            const subscriptUrl = isSelected ? subscriptActive : subscript;
            return (
                <Popover key={"draw"}
                         placement={"right"}
                         trigger="hover"
                         content={this.renderDrawContext}>
                    <div key="draw-inner" className="tool-box-cell-box-left">
                        <div className="tool-box-cell"
                             onClick={() => this.clickAppliance(this.currentDraw)}>
                            <img src={iconUrl} alt={"iconUrl"}/>
                            <img className="tool-box-cell-subscript" src={subscriptUrl} alt={"subscriptUrl"}/>
                        </div>
                    </div>
                </Popover>
            );
        }
    }