@ant-design/icons#GithubOutlined TypeScript Examples

The following examples show how to use @ant-design/icons#GithubOutlined. 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 posthog-foss with MIT License 6 votes vote down vote up
export function SocialLoginLink({ provider, queryString }: SocialLoginButtonProps): JSX.Element | null {
    const { preflight } = useValues(preflightLogic)

    const icon = useMemo(() => {
        if (provider === SocialAuthProviders.Google) {
            return <GoogleOutlined />
        } else if (provider === SocialAuthProviders.GitHub) {
            return <GithubOutlined />
        } else if (provider === SocialAuthProviders.GitLab) {
            return <GitlabOutlined />
        } else if (provider === SocialAuthProviders.SAML) {
            return <KeyOutlined />
        }
    }, [provider])

    if (!preflight?.available_social_auth_providers[provider]) {
        return null
    }

    // SAML-based login requires an extra param as technically we can support multiple SAML backends
    const extraParam =
        provider === SocialAuthProviders.SAML ? (queryString ? '&idp=posthog_custom' : '?idp=posthog_custom') : ''

    return (
        <Button
            className={`link-social-login ${provider}`}
            href={`/login/${provider}/${queryString || ''}${extraParam}`}
            icon={icon}
            type="link"
        >
            <span>{ProviderNames[provider]}</span>
        </Button>
    )
}
Example #2
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 #3
Source File: BasicLayout.tsx    From ant-design-pro-V4 with MIT License 6 votes vote down vote up
defaultFooterDom = (
  <DefaultFooter
    copyright={`${new Date().getFullYear()} Produced by Ant Group Experience Technology Department`}
    links={[
      {
        key: 'Ant Design Pro',
        title: 'Ant Design Pro',
        href: 'https://pro.ant.design',
        blankTarget: true,
      },
      {
        key: 'github',
        title: <GithubOutlined />,
        href: 'https://github.com/ant-design/ant-design-pro',
        blankTarget: true,
      },
      {
        key: 'Ant Design',
        title: 'Ant Design',
        href: 'https://ant.design',
        blankTarget: true,
      },
    ]}
  />
)
Example #4
Source File: BasicLayout.tsx    From ui-visualization with MIT License 6 votes vote down vote up
defaultFooterDom = (
  <DefaultFooter
    copyright="2019 蚂蚁金服体验技术部出品"
    links={[
      {
        key: 'Ant Design Pro',
        title: 'Ant Design Pro',
        href: 'https://pro.ant.design',
        blankTarget: true,
      },
      {
        key: 'github',
        title: <GithubOutlined />,
        href: 'https://github.com/ant-design/ant-design-pro',
        blankTarget: true,
      },
      {
        key: 'Ant Design',
        title: 'Ant Design',
        href: 'https://ant.design',
        blankTarget: true,
      },
    ]}
  />
)
Example #5
Source File: index.tsx    From nanolooker with MIT License 6 votes vote down vote up
AppFooter: React.FC = () => {
  const { t } = useTranslation();
  const { theme } = React.useContext(PreferencesContext);

  const donateColor =
    theme === Theme.DARK ? TwoToneColors.DONATE_DARK : TwoToneColors.DONATE;

  return (
    <Footer style={{ textAlign: "center" }}>
      <div>
        <a
          href="https://github.com/running-coder/nanolooker"
          rel="noopener noreferrer"
          target="_blank"
        >
          <GithubOutlined /> NanoLooker
        </a>{" "}
        ©{new Date().getFullYear()}{" "}
        {t("footer.createdBy", { creator: "RunningCoder" })}
      </div>

      <QRCodeModal
        account={DONATION_ACCOUNT}
        header={<Text>{t("footer.donations.title")}</Text>}
      >
        <Tag
          color={donateColor}
          icon={<HeartTwoTone twoToneColor={donateColor} />}
          style={{ cursor: "pointer", marginTop: "6px" }}
        >
          {t("footer.donations.donate")}
        </Tag>
      </QRCodeModal>
    </Footer>
  );
}
Example #6
Source File: constants.tsx    From datart with Apache License 2.0 6 votes vote down vote up
AUTH_CLIENT_ICON_MAPPING = {
  github: <GithubOutlined />,
  dingding: <DingdingOutlined />,
  qq: <QqOutlined />,
  gitlab: <GitlabOutlined />,
  weibo: <WeiboCircleOutlined />,
  zhihu: <ZhihuOutlined />,
  alipay: <AlipayCircleOutlined />,
  aliyun: <AliyunOutlined />,
  google: <GoogleOutlined />,
  facebook: <FacebookOutlined />,
  slack: <SlackOutlined />,
  instagram: <InstagramOutlined />,
  codepen: <CodepenCircleOutlined />,
}
Example #7
Source File: YakitStorePage.tsx    From yakit with GNU Affero General Public License v3.0 6 votes vote down vote up
gitUrlIcon = (url: string | undefined, noTag?: boolean) => {
    if (!url) {
        return <></>
    }

    if (url.startsWith("https://github.com/yaklang/yakit-store") && !noTag) {
        return <Tag color={"green"}>yaklang.io</Tag>
    }

    return (
        <Tooltip title={url}>
            <Button
                type={"link"}
                style={{
                    paddingLeft: 0,
                    paddingRight: 0,
                    marginLeft: 0,
                    marginRight: 0
                }}
                icon={<GithubOutlined/>}
            />
        </Tooltip>
    )
}
Example #8
Source File: index.tsx    From react_admin with MIT License 4 votes vote down vote up
Login: React.FC<Iprops> = (props) => {
  const username = useInput("");
  const password = useInput("");
  const code = useInput("");
  const inputRef = useRef<any>(null);
  const [loading, setLoading] = useState(false);

  /**
   * 判断是否登录过 && 获取焦点
   */
  useEffect(() => {
    const userinfo = localStorage.getItem("userinfo")
      ? JSON.parse(localStorage.getItem("userinfo") as string)
      : null;
    if (userinfo) {
      props.history.replace("/home");
    } else {
      inputRef.current.focus();
    }
  }, []);

  /**
   * @function
   * 登录校验 发出请求
   */
  const handleSubmit = async () => {
    const _loginName = username.val.trim();
    const _password = password.val.trim();
    const _code = code.val.trim();

    try {
      if (!_loginName) throw new Error("用户名不能为空");
      if (!_password) throw new Error("密码不能为空");
      if (!_code) throw new Error("验证码不能为空");
      if (_code !== captcha) throw new Error("验证码错误");

      setLoading(true);
      const data = (await getUserLoginData({
        data: { _loginName, _password },
        url: API.getLogin,
      })) as Ilogin;
      setLoading(false);
      // 登录成功
      if (_loginName === data.username && _password === data.password) {
        localStorage.setItem(
          "userinfo",
          JSON.stringify({ _loginName, _password })
        );
        await props.setUserInfoMy({ _loginName, _password });
        props.history.replace("/home");
      } else {
        throw new Error("用户名密码错误");
      }
    } catch (err) {
      message.error(err.message);
      return;
    }
  };
  const reloadCaptcha = useCallback((e) => {
    captcha = getRandom();
    let url = API.getCaptcha + captcha;
    e.target.src = url;
  }, []);

  return (
    <section className="login-page">
      <a
        rel="noopener noreferrer"
        className="login-right"
        href="https://github.com/2662419405"
        target="_blank"
      >
        <img
          src="https://github.blog/wp-content/uploads/2008/12/forkme_right_darkblue_121621.png?resize=149%2C149"
          alt="github"
        />
      </a>
      <div className="wrap">
        <div>
          <div className="logo-wrap">
            <img
              alt="logo"
              className="logo"
              src={require("../../assets/img/sh.png")}
            />
            <em>TS + Hooks</em>
          </div>
          <Input.Group>
            <Input
              ref={inputRef}
              {...username}
              onPressEnter={handleSubmit}
              prefix={<UserOutlined />}
              maxLength={32}
              autoComplete="off"
              placeholder="username/admin"
            />
            <Input
              {...password}
              prefix={<LockOutlined />}
              onPressEnter={handleSubmit}
              type="password"
              maxLength={32}
              autoComplete="off"
              placeholder="password/123456"
            />
            <Input
              {...code}
              onKeyDown={(e) => {
                if (e.keyCode === 13) handleSubmit();
              }}
              prefix={<PictureOutlined />}
              onPressEnter={handleSubmit}
              maxLength={4}
              autoComplete="off"
              placeholder="请输入验证码"
              suffix={
                <img
                  className="captcha"
                  src={API.getCaptcha + captcha}
                  onClick={reloadCaptcha}
                  alt="code"
                />
              }
            />
          </Input.Group>
          <Button
            size="large"
            className="weitiao-btn"
            block={true}
            type="primary"
            onClick={handleSubmit}
            loading={loading}
          >
            {loading ? "正在登录" : "登录"}
          </Button>
          <div className="other-login">
            <span className="txt">其他登录方式</span>
            <GithubOutlined className="github-icon" />
            <div className="href-right">
              <Tooltip
                placement="bottom"
                title="账号为admin,密码为123456,推荐使用第三方github进行登录"
              >
                <span className="text-right">注册账号</span>
              </Tooltip>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </section>
  );
}
Example #9
Source File: Icon.tsx    From html2sketch with MIT License 4 votes vote down vote up
IconSymbol: FC = () => {
  return (
    <Row>
      {/*<CaretUpOutlined*/}
      {/*  className="icon"*/}
      {/*  symbolName={'1.General/2.Icons/1.CaretUpOutlined'}*/}
      {/*/>*/}
      {/*  className="icon"*/}
      {/*  symbolName={'1.General/2.Icons/2.MailOutlined'}*/}
      {/*/>*/}
      {/*<StepBackwardOutlined*/}
      {/*  className="icon"*/}
      {/*  symbolName={'1.General/2.Icons/2.StepBackwardOutlined'}*/}
      {/*/>*/}
      {/*<StepForwardOutlined*/}
      {/*  className="icon"*/}
      {/*  symbolName={'1.General/2.Icons/2.StepBackwardOutlined'}*/}
      {/*/>*/}
      <StepForwardOutlined />
      <ShrinkOutlined />
      <ArrowsAltOutlined />
      <DownOutlined />
      <UpOutlined />
      <LeftOutlined />
      <RightOutlined />
      <CaretUpOutlined />
      <CaretDownOutlined />
      <CaretLeftOutlined />
      <CaretRightOutlined />
      <VerticalAlignTopOutlined />
      <RollbackOutlined />
      <FastBackwardOutlined />
      <FastForwardOutlined />
      <DoubleRightOutlined />
      <DoubleLeftOutlined />
      <VerticalLeftOutlined />
      <VerticalRightOutlined />
      <VerticalAlignMiddleOutlined />
      <VerticalAlignBottomOutlined />
      <ForwardOutlined />
      <BackwardOutlined />
      <EnterOutlined />
      <RetweetOutlined />
      <SwapOutlined />
      <SwapLeftOutlined />
      <SwapRightOutlined />
      <ArrowUpOutlined />
      <ArrowDownOutlined />
      <ArrowLeftOutlined />
      <ArrowRightOutlined />
      <LoginOutlined />
      <LogoutOutlined />
      <MenuFoldOutlined />
      <MenuUnfoldOutlined />
      <BorderBottomOutlined />
      <BorderHorizontalOutlined />
      <BorderInnerOutlined />
      <BorderOuterOutlined />
      <BorderLeftOutlined />
      <BorderRightOutlined />
      <BorderTopOutlined />
      <BorderVerticleOutlined />
      <PicCenterOutlined />
      <PicLeftOutlined />
      <PicRightOutlined />
      <RadiusBottomleftOutlined />
      <RadiusBottomrightOutlined />
      <RadiusUpleftOutlined />
      <RadiusUprightOutlined />
      <FullscreenOutlined />
      <FullscreenExitOutlined />
      <QuestionOutlined />
      <PauseOutlined />
      <MinusOutlined />
      <PauseCircleOutlined />
      <InfoOutlined />
      <CloseOutlined />
      <ExclamationOutlined />
      <CheckOutlined />
      <WarningOutlined />
      <IssuesCloseOutlined />
      <StopOutlined />
      <EditOutlined />
      <CopyOutlined />
      <ScissorOutlined />
      <DeleteOutlined />
      <SnippetsOutlined />
      <DiffOutlined />
      <HighlightOutlined />
      <AlignCenterOutlined />
      <AlignLeftOutlined />
      <AlignRightOutlined />
      <BgColorsOutlined />
      <BoldOutlined />
      <ItalicOutlined />
      <UnderlineOutlined />
      <StrikethroughOutlined />
      <RedoOutlined />
      <UndoOutlined />
      <ZoomInOutlined />
      <ZoomOutOutlined />
      <FontColorsOutlined />
      <FontSizeOutlined />
      <LineHeightOutlined />
      <SortAscendingOutlined />
      <SortDescendingOutlined />
      <DragOutlined />
      <OrderedListOutlined />
      <UnorderedListOutlined />
      <RadiusSettingOutlined />
      <ColumnWidthOutlined />
      <ColumnHeightOutlined />
      <AreaChartOutlined />
      <PieChartOutlined />
      <BarChartOutlined />
      <DotChartOutlined />
      <LineChartOutlined />
      <RadarChartOutlined />
      <HeatMapOutlined />
      <FallOutlined />
      <RiseOutlined />
      <StockOutlined />
      <BoxPlotOutlined />
      <FundOutlined />
      <SlidersOutlined />
      <AndroidOutlined />
      <AppleOutlined />
      <WindowsOutlined />
      <IeOutlined />
      <ChromeOutlined />
      <GithubOutlined />
      <AliwangwangOutlined />
      <DingdingOutlined />
      <WeiboSquareOutlined />
      <WeiboCircleOutlined />
      <TaobaoCircleOutlined />
      <Html5Outlined />
      <WeiboOutlined />
      <TwitterOutlined />
      <WechatOutlined />
      <AlipayCircleOutlined />
      <TaobaoOutlined />
      <SkypeOutlined />
      <FacebookOutlined />
      <CodepenOutlined />
      <CodeSandboxOutlined />
      <AmazonOutlined />
      <GoogleOutlined />
      <AlipayOutlined />
      <AntDesignOutlined />
      <AntCloudOutlined />
      <ZhihuOutlined />
      <SlackOutlined />
      <SlackSquareOutlined />
      <BehanceSquareOutlined />
      <DribbbleOutlined />
      <DribbbleSquareOutlined />
      <InstagramOutlined />
      <YuqueOutlined />
      <AlibabaOutlined />
      <YahooOutlined />
      <RedditOutlined />
      <SketchOutlined />
      <AccountBookOutlined />
      <AlertOutlined />
      <ApartmentOutlined />
      <ApiOutlined />
      <QqOutlined />
      <MediumWorkmarkOutlined />
      <GitlabOutlined />
      <MediumOutlined />
      <GooglePlusOutlined />
      <AppstoreAddOutlined />
      <AppstoreOutlined />
      <AudioOutlined />
      <AudioMutedOutlined />
      <AuditOutlined />
      <BankOutlined />
      <BarcodeOutlined />
      <BarsOutlined />
      <BellOutlined />
      <BlockOutlined />
      <BookOutlined />
      <BorderOutlined />
      <BranchesOutlined />
      <BuildOutlined />
      <BulbOutlined />
      <CalculatorOutlined />
      <CalendarOutlined />
      <CameraOutlined />
      <CarOutlined />
      <CarryOutOutlined />
      <CiCircleOutlined />
      <CiOutlined />
      <CloudOutlined />
      <ClearOutlined />
      <ClusterOutlined />
      <CodeOutlined />
      <CoffeeOutlined />
      <CompassOutlined />
      <CompressOutlined />
      <ContactsOutlined />
      <ContainerOutlined />
      <ControlOutlined />
      <CopyrightCircleOutlined />
      <CopyrightOutlined />
      <CreditCardOutlined />
      <CrownOutlined />
      <CustomerServiceOutlined />
      <DashboardOutlined />
      <DatabaseOutlined />
      <DeleteColumnOutlined />
      <DeleteRowOutlined />
      <DisconnectOutlined />
      <DislikeOutlined />
      <DollarCircleOutlined />
      <DollarOutlined />
      <DownloadOutlined />
      <EllipsisOutlined />
      <EnvironmentOutlined />
      <EuroCircleOutlined />
      <EuroOutlined />
      <ExceptionOutlined />
      <ExpandAltOutlined />
      <ExpandOutlined />
      <ExperimentOutlined />
      <ExportOutlined />
      <EyeOutlined />
      <FieldBinaryOutlined />
      <FieldNumberOutlined />
      <FieldStringOutlined />
      <DesktopOutlined />
      <DingtalkOutlined />
      <FileAddOutlined />
      <FileDoneOutlined />
      <FileExcelOutlined />
      <FileExclamationOutlined />
      <FileOutlined />
      <FileImageOutlined />
      <FileJpgOutlined />
      <FileMarkdownOutlined />
      <FilePdfOutlined />
      <FilePptOutlined />
      <FileProtectOutlined />
      <FileSearchOutlined />
      <FileSyncOutlined />
      <FileTextOutlined />
      <FileUnknownOutlined />
      <FileWordOutlined />
      <FilterOutlined />
      <FireOutlined />
      <FlagOutlined />
      <FolderAddOutlined />
      <FolderOutlined />
      <FolderOpenOutlined />
      <ForkOutlined />
      <FormatPainterOutlined />
      <FrownOutlined />
      <FunctionOutlined />
      <FunnelPlotOutlined />
      <GatewayOutlined />
      <GifOutlined />
      <GiftOutlined />
      <GlobalOutlined />
      <GoldOutlined />
      <GroupOutlined />
      <HddOutlined />
      <HeartOutlined />
      <HistoryOutlined />
      <HomeOutlined />
      <HourglassOutlined />
      <IdcardOutlined />
      <ImportOutlined />
      <InboxOutlined />
      <InsertRowAboveOutlined />
      <InsertRowBelowOutlined />
      <InsertRowLeftOutlined />
      <InsertRowRightOutlined />
      <InsuranceOutlined />
      <InteractionOutlined />
      <KeyOutlined />
      <LaptopOutlined />
      <LayoutOutlined />
      <LikeOutlined />
      <LineOutlined />
      <LinkOutlined />
      <Loading3QuartersOutlined />
      <LoadingOutlined />
      <LockOutlined />
      <MailOutlined />
      <ManOutlined />
      <MedicineBoxOutlined />
      <MehOutlined />
      <MenuOutlined />
      <MergeCellsOutlined />
      <MessageOutlined />
      <MobileOutlined />
      <MoneyCollectOutlined />
      <MonitorOutlined />
      <MoreOutlined />
      <NodeCollapseOutlined />
      <NodeExpandOutlined />
      <NodeIndexOutlined />
      <NotificationOutlined />
      <NumberOutlined />
      <PaperClipOutlined />
      <PartitionOutlined />
      <PayCircleOutlined />
      <PercentageOutlined />
      <PhoneOutlined />
      <PictureOutlined />
      <PoundCircleOutlined />
      <PoundOutlined />
      <PoweroffOutlined />
      <PrinterOutlined />
      <ProfileOutlined />
      <ProjectOutlined />
      <PropertySafetyOutlined />
      <PullRequestOutlined />
      <PushpinOutlined />
      <QrcodeOutlined />
      <ReadOutlined />
      <ReconciliationOutlined />
      <RedEnvelopeOutlined />
      <ReloadOutlined />
      <RestOutlined />
      <RobotOutlined />
      <RocketOutlined />
      <SafetyCertificateOutlined />
      <SafetyOutlined />
      <ScanOutlined />
      <ScheduleOutlined />
      <SearchOutlined />
      <SecurityScanOutlined />
      <SelectOutlined />
      <SendOutlined />
      <SettingOutlined />
      <ShakeOutlined />
      <ShareAltOutlined />
      <ShopOutlined />
      <ShoppingCartOutlined />
      <ShoppingOutlined />
      <SisternodeOutlined />
      <SkinOutlined />
      <SmileOutlined />
      <SolutionOutlined />
      <SoundOutlined />
      <SplitCellsOutlined />
      <StarOutlined />
      <SubnodeOutlined />
      <SyncOutlined />
      <TableOutlined />
      <TabletOutlined />
      <TagOutlined />
      <TagsOutlined />
      <TeamOutlined />
      <ThunderboltOutlined />
      <ToTopOutlined />
      <ToolOutlined />
      <TrademarkCircleOutlined />
      <TrademarkOutlined />
      <TransactionOutlined />
      <TrophyOutlined />
      <UngroupOutlined />
      <UnlockOutlined />
      <UploadOutlined />
      <UsbOutlined />
      <UserAddOutlined />
      <UserDeleteOutlined />
      <UserOutlined />
      <UserSwitchOutlined />
      <UsergroupAddOutlined />
      <UsergroupDeleteOutlined />
      <VideoCameraOutlined />
      <WalletOutlined />
      <WifiOutlined />
      <BorderlessTableOutlined />
      <WomanOutlined />
      <BehanceOutlined />
      <DropboxOutlined />
      <DeploymentUnitOutlined />
      <UpCircleOutlined />
      <DownCircleOutlined />
      <LeftCircleOutlined />
      <RightCircleOutlined />
      <UpSquareOutlined />
      <DownSquareOutlined />
      <LeftSquareOutlined />
      <RightSquareOutlined />
      <PlayCircleOutlined />
      <QuestionCircleOutlined />
      <PlusCircleOutlined />
      <PlusSquareOutlined />
      <MinusSquareOutlined />
      <MinusCircleOutlined />
      <InfoCircleOutlined />
      <ExclamationCircleOutlined />
      <CloseCircleOutlined />
      <CloseSquareOutlined />
      <CheckCircleOutlined />
      <CheckSquareOutlined />
      <ClockCircleOutlined />
      <FormOutlined />
      <DashOutlined />
      <SmallDashOutlined />
      <YoutubeOutlined />
      <CodepenCircleOutlined />
      <AliyunOutlined />
      <PlusOutlined />
      <LinkedinOutlined />
      <AimOutlined />
      <BugOutlined />
      <CloudDownloadOutlined />
      <CloudServerOutlined />
      <CloudSyncOutlined />
      <CloudUploadOutlined />
      <CommentOutlined />
      <ConsoleSqlOutlined />
      <EyeInvisibleOutlined />
      <FileGifOutlined />
      <DeliveredProcedureOutlined />
      <FieldTimeOutlined />
      <FileZipOutlined />
      <FolderViewOutlined />
      <FundProjectionScreenOutlined />
      <FundViewOutlined />
      <MacCommandOutlined />
      <PlaySquareOutlined />
      <OneToOneOutlined />
      <RotateLeftOutlined />
      <RotateRightOutlined />
      <SaveOutlined />
      <SwitcherOutlined />
      <TranslationOutlined />
      <VerifiedOutlined />
      <VideoCameraAddOutlined />
      <WhatsAppOutlined />

      {/*</Col>*/}
    </Row>
  );
}
Example #10
Source File: Previewer.tsx    From XFlow with MIT License 4 votes vote down vote up
Previewer: React.FC<IPreviewerProps> = oProps => {
  const demoRef = useRef()
  const { locale, meta } = useContext(context)
  const props = useLocaleProps<IPreviewerProps>(locale, oProps)
  const builtinDemoUrl = useDemoUrl(props.identifier)
  const demoUrl = props.demoUrl || builtinDemoUrl
  const isActive = history?.location.hash === `#${props.identifier}`
  const isSingleFile = Object.keys(props.sources).length === 1
  const openCSB = useCodeSandbox(props.hideActions?.includes('CSB') ? null : props)
  const openRiddle = useRiddle(props.hideActions?.includes('RIDDLE') ? null : props)
  const [execMotions, isMotionRunning] = useMotions(props.motions || [], demoRef.current)
  const [copyCode, copyStatus] = useCopy()
  const [currentFile, setCurrentFile] = useState(() =>
    props.sources._ ? '_' : Object.keys(props.sources)[0],
  )
  const [sourceType, setSourceType] = useState(
    getSourceType(currentFile, props.sources[currentFile]),
  )
  const [showSource, setShowSource] = useState(Boolean(props.defaultShowCode))
  const [iframeKey, setIframeKey] = useState(Math.random())
  const currentFileCode =
    props.sources[currentFile][sourceType] || props.sources[currentFile].content
  const playgroundUrl = useTSPlaygroundUrl(locale, currentFileCode)
  const iframeRef = useRef<HTMLIFrameElement>()
  const [color] = usePrefersColor()

  // re-render iframe if prefers color changed
  useEffect(() => {
    setIframeKey(Math.random())
  }, [color])

  function handleFileChange(filename: string) {
    setCurrentFile(filename)
    setSourceType(getSourceType(filename, props.sources[filename]))
  }

  return (
    <div
      style={props.style}
      className={[
        props.className,
        '__dumi-default-previewer',
        isActive ? '__dumi-default-previewer-target' : '',
      ]
        .filter(Boolean)
        .join(' ')}
      id={props.identifier}
      data-debug={props.debug || undefined}
      data-iframe={props.iframe || undefined}
    >
      {props.iframe && <div className="__dumi-default-previewer-browser-nav" />}
      <div
        ref={demoRef}
        className="__dumi-default-previewer-demo"
        style={{
          transform: props.transform ? 'translate(0, 0)' : undefined,
          padding: props.compact || (props.iframe && props.compact !== false) ? '0' : undefined,
          background: props.background,
        }}
      >
        {props.iframe ? (
          <iframe
            title="dumi-previewer"
            style={{
              // both compatible with unit or non-unit, such as 100, 100px, 100vh
              height: String(props.iframe).replace(/(\d)$/, '$1px'),
            }}
            key={iframeKey}
            src={demoUrl}
            ref={iframeRef}
          />
        ) : (
          props.children
        )}
      </div>
      <div className="__dumi-default-previewer-desc" data-title={props.title}>
        {props.title && <AnchorLink to={`#${props.identifier}`}>{props.title}</AnchorLink>}
        {props.description && (
          <div
            // eslint-disable-next-line
            dangerouslySetInnerHTML={{ __html: props.description }}
          />
        )}
      </div>
      <div className="__dumi-default-previewer-actions">
        <a
          target="_blank"
          title="Open demo code on github.com "
          className="github-code-link"
          href={`${getFolderUrl(`${GITHUB_PKG_URL}/${meta.filePath}`)}`}
        >
          <button>
            <GithubOutlined style={{ fontSize: '16px', position: 'absolute', top: 0, left: 0 }} />
          </button>
        </a>
        {openCSB && (
          <button
            title="Open demo on CodeSandbox.io"
            className="__dumi-default-icon"
            role="codesandbox"
            onClick={openCSB}
          />
        )}
        {openRiddle && (
          <button
            title="Open demo on Riddle"
            className="__dumi-default-icon"
            role="riddle"
            onClick={openRiddle}
          />
        )}
        {props.motions && (
          <button
            title="Execute motions"
            className="__dumi-default-icon"
            role="motions"
            disabled={isMotionRunning}
            onClick={() => execMotions()}
          />
        )}
        {props.iframe && (
          <button
            title="Reload demo iframe page"
            className="__dumi-default-icon"
            role="refresh"
            onClick={() => setIframeKey(Math.random())}
          />
        )}
        {!props.hideActions?.includes('EXTERNAL') && (
          <Link target="_blank" to={demoUrl}>
            <button
              title="Open demo in new tab"
              className="__dumi-default-icon"
              role="open-demo"
              type="button"
            />
          </Link>
        )}
        <span />
        <button
          title="Copy source code"
          className="__dumi-default-icon"
          role="copy"
          data-status={copyStatus}
          onClick={() => copyCode(currentFileCode)}
        />
        {sourceType === 'tsx' && showSource && (
          <Link target="_blank" to={playgroundUrl}>
            <button
              title="Get JSX via TypeScript Playground"
              className="__dumi-default-icon"
              role="change-tsx"
              type="button"
            />
          </Link>
        )}
        <button
          title="Toggle source code panel"
          className={`__dumi-default-icon${showSource ? ' __dumi-default-btn-expand' : ''}`}
          role="source"
          type="button"
          onClick={() => setShowSource(!showSource)}
        />
      </div>
      {showSource && (
        <div className="__dumi-default-previewer-source-wrapper">
          {!isSingleFile && (
            <Tabs
              className="__dumi-default-previewer-source-tab"
              prefixCls="__dumi-default-tabs"
              moreIcon="···"
              defaultActiveKey={currentFile}
              onChange={handleFileChange}
            >
              {Object.keys(props.sources).map(filename => (
                <TabPane
                  tab={
                    filename === '_'
                      ? `index.${getSourceType(filename, props.sources[filename])}`
                      : filename
                  }
                  key={filename}
                />
              ))}
            </Tabs>
          )}
          <div className="__dumi-default-previewer-source">
            <SourceCode code={currentFileCode} lang={sourceType} showCopy={false} />
          </div>
        </div>
      )}
    </div>
  )
}
Example #11
Source File: index.tsx    From XFlow with MIT License 4 votes vote down vote up
Footer: React.FC<FooterProps> = ({ columns, bottom, theme = 'dark', language, rootDomain = '', footerProps }) => {
  const { t, i18n } = useTranslation();
  const lang = language || i18n.language;

  const products = getProducts({
    t,
    language: lang,
    rootDomain,
  });

  const more = {
    icon: <img src="https://gw.alipayobjects.com/zos/rmsportal/nBVXkrFdWHxbZlmMbsaH.svg" alt="more products" />,
    title: t('更多产品'),
    items: [
      {
        icon: <img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="Ant Design" />,
        title: 'Ant Design',
        url: 'https://ant.design',
        description: t('企业级 UI 设计语言'),
        openExternal: true,
      },
      {
        icon: <img src="https://gw.alipayobjects.com/zos/rmsportal/XuVpGqBFxXplzvLjJBZB.svg" alt="yuque" />,
        title: t('语雀'),
        url: 'https://yuque.com',
        description: t('知识创作与分享工具'),
        openExternal: true,
      },
      {
        icon: <img src="https://gw.alipayobjects.com/zos/antfincdn/sAEs8aHCnd/yunfengdie.png" alt="yunfengdie" />,
        title: t('云凤蝶'),
        url: 'https://yunfengdie.com',
        description: t('中台建站平台'),
        openExternal: true,
      },
      {
        icon: (
          <img
            src="https://gw.alipayobjects.com/zos/antfincdn/v2%24rh7lqpu/82f338dd-b0a6-41bc-9a86-58aaa9df217b.png"
            alt="Egg"
          />
        ),
        title: 'Egg',
        url: 'https://eggjs.org',
        description: t('企业级 Node 开发框架'),
        openExternal: true,
      },
      {
        icon: <img src="https://gw.alipayobjects.com/zos/rmsportal/DMDOlAUhmktLyEODCMBR.ico" alt="kitchen" />,
        title: 'Kitchen',
        description: t('Sketch 工具集'),
        url: 'https://kitchen.alipay.com',
        openExternal: true,
      },
      {
        icon: <img src="https://gw.alipayobjects.com/zos/rmsportal/nBVXkrFdWHxbZlmMbsaH.svg" alt="xtech" />,
        title: t('蚂蚁体验科技'),
        url: 'https://xtech.antfin.com/',
        openExternal: true,
      },
    ],
  };

  const defaultColumns = products
    .filter(product => product.category !== 'ecology')
    .map(product => ({
      title: (
        <span>
          {product.title}
          <span className={styles.description}>{product.slogan}</span>
        </span>
      ),
      items: product.links,
    }));

  return (
    <RCFooter
      maxColumnsPerRow={4}
      theme={theme}
      columns={columns || [...defaultColumns, more]}
      className={styles.footer}
      bottom={
        bottom || (
          <div className={styles.bottom}>
            <div>
              <a href="https://weibo.com/antv2017" target="_blank" rel="noopener noreferrer">
                <WeiboOutlined />
              </a>
              <a href="https://zhuanlan.zhihu.com/aiux-antv" target="_blank" rel="noopener noreferrer">
                <ZhihuOutlined />
              </a>
              <a href="https://github.com/antvis" target="_blank" rel="noopener noreferrer">
                <GithubOutlined />
              </a>
              <a href={`${rootDomain}/${lang}/about`}>{t('关于我们')}</a>
              <a href={OLD_SITE_DOMAIN} target="_blank" rel="noopener noreferrer">
                {t('返回旧版')}
              </a>
            </div>
            <div>
              © {new Date().getFullYear()} Made with ❤ by <a href="https://xtech.antfin.com/">XTech</a>
            </div>
          </div>
        )
      }
      {...footerProps}
    />
  );
}
Example #12
Source File: getProducts.tsx    From XFlow with MIT License 4 votes vote down vote up
getProducts = ({
  t,
  language,
}: {
  t: (key: string) => string;
  language: string;
  rootDomain?: string;
  isChinaMirrorHost?: boolean;
}): ProductItem[] => {
  const hosts: { [name: string]: string } = {};
  ['g2', 'g2plot', 'g6', 'l7', 'f2', 'graphin', 'g', 'x6', 'ava'].forEach((name: string) => {
    hosts[name] = `${name}.${ANTV_DOMAIN}`;
  });
  const products = [
    {
      title: 'G2',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/trEfLRh5pc/G2%252520keshihuatuxingyufa.svg',
      slogan: t('可视化引擎'),
      description: t('数据驱动,高度易用,可扩展的可视化图形语法。'),
      category: Categories[0],
      links: [
        {
          icon: <HomeOutlined />,
          title: t('产品首页'),
          url: `https://${hosts.g2}/${language}`,
        },
        {
          icon: <PieChartOutlined />,
          title: t('图表示例'),
          url: `https://${hosts.g2}/${language}/examples`,
        },
        {
          icon: <ReadOutlined />,
          title: t('使用文档'),
          url: `https://${hosts.g2}/${language}/docs/manual`,
        },
        {
          icon: <ReadOutlined />,
          title: t('API 文档'),
          url: `https://${hosts.g2}/${language}/docs/api`,
        },
        {
          icon: <HistoryOutlined />,
          title: t('更新日志'),
          url: `https://github.com/antvis/g2/blob/master/CHANGELOG.md`,
          openExternal: true,
        },
        {
          icon: <GithubOutlined />,
          title: t('GitHub 仓库'),
          url: `https://github.com/antvis/g2`,
          openExternal: true,
        },
        {
          icon: '??',
          title: t('国内镜像'),
          url: `https://antv-g2.gitee.io`,
          openExternal: true,
        },
      ],
    },
    {
      title: 'G6',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/zS1wZZJVcJ/G6%252520tukeshihuayinqing.svg',
      slogan: t('图可视化引擎'),
      description: t('便捷的关系数据可视化引擎与图分析工具。'),
      category: Categories[0],
      links: [
        {
          icon: <HomeOutlined />,
          title: t('产品首页'),
          url: `https://${hosts.g6}/${language}`,
        },
        {
          icon: <PieChartOutlined />,
          title: t('图表示例'),
          url: `https://${hosts.g6}/${language}/examples`,
        },
        {
          icon: <ReadOutlined />,
          title: t('使用文档'),
          url: `https://${hosts.g6}/${language}/docs/manual`,
        },
        {
          icon: <ReadOutlined />,
          title: t('API 文档'),
          url: `https://${hosts.g6}/${language}/docs/api`,
        },
        {
          icon: <HistoryOutlined />,
          title: t('更新日志'),
          url: `https://github.com/antvis/g6/blob/master/CHANGELOG.md`,
          openExternal: true,
        },
        {
          icon: <GithubOutlined />,
          title: t('GitHub 仓库'),
          url: `https://github.com/antvis/g6`,
          openExternal: true,
        },
        {
          icon: '??',
          title: t('国内镜像'),
          url: `https://antv-g6.gitee.io`,
          openExternal: true,
        },
      ],
    },
    {
      title: 'F2',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/D%26fDbWqVkv/F2%252520yidongduankeshihuafangan.svg',
      slogan: t('移动可视化方案'),
      description: t('专注于移动端的可视化解决方案,兼容 H5/小程序/Weex 等多端环境'),
      category: Categories[0],
      links: [
        {
          icon: <HomeOutlined />,
          title: t('产品首页'),
          url: `https://${hosts.f2}/${language}`,
        },
        {
          icon: <PieChartOutlined />,
          title: t('图表示例'),
          url: `https://${hosts.f2}/${language}/examples`,
        },
        {
          icon: <ReadOutlined />,
          title: t('使用文档'),
          url: `https://${hosts.f2}/${language}/docs/tutorial/getting-started`,
        },
        {
          icon: <ReadOutlined />,
          title: t('API 文档'),
          url: `https://${hosts.f2}/${language}/docs/api`,
        },
        {
          icon: <HistoryOutlined />,
          title: t('更新日志'),
          url: `https://github.com/antvis/f2/blob/master/CHANGELOG.md`,
          openExternal: true,
        },
        {
          icon: <GithubOutlined />,
          title: t('GitHub 仓库'),
          url: `https://github.com/antvis/f2`,
          openExternal: true,
        },
        {
          icon: '??',
          title: t('国内镜像'),
          url: `https://antv-f2.gitee.io`,
          openExternal: true,
        },
      ],
    },
    {
      title: 'L7',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/OI%26h7HXH33/L7%252520dilikongjianshujukeshihua.svg',
      slogan: t('地理空间数据可视化'),
      description: t('高性能/高渲染质量的地理空间数据可视化框架。'),
      category: Categories[0],
      links: [
        {
          icon: <HomeOutlined />,
          title: t('产品首页'),
          url: `https://${hosts.l7}/${language}`,
        },
        {
          icon: <PieChartOutlined />,
          title: t('图表示例'),
          url: `https://${hosts.l7}/${language}/examples`,
        },
        {
          icon: <ReadOutlined />,
          title: t('使用文档'),
          url: `https://${hosts.l7}/${language}/docs/tutorial`,
        },
        {
          icon: <ReadOutlined />,
          title: t('API 文档'),
          url: `https://${hosts.l7}/${language}/docs/api/l7`,
        },
        {
          icon: <HistoryOutlined />,
          title: t('更新日志'),
          url: `https://github.com/antvis/L7/blob/master/CHANGELOG.md`,
          openExternal: true,
        },
        {
          icon: <GithubOutlined />,
          title: t('GitHub 仓库'),
          url: `https://github.com/antvis/L7`,
          openExternal: true,
        },
        {
          icon: '??',
          title: t('国内镜像'),
          url: `https://antv-l7.gitee.io`,
          openExternal: true,
        },
      ],
    },
    {
      title: 'G2Plot',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/SlbIagEvT7/G2plot.svg',
      slogan: t('开箱即用的图表库'),
      description: t('开箱即用、易于配置、极致体验的通用图表库。'),
      category: Categories[1],
      links: [
        {
          icon: <HomeOutlined />,
          title: t('产品首页'),
          url: `https://${hosts.g2plot}/${language}`,
        },
        {
          icon: <PieChartOutlined />,
          title: t('图表示例'),
          url: `https://${hosts.g2plot}/${language}/examples`,
        },
        {
          icon: <ReadOutlined />,
          title: t('使用文档'),
          url: `https://${hosts.g2plot}/${language}/docs/manual`,
        },
        {
          icon: <HistoryOutlined />,
          title: t('更新日志'),
          url: `https://github.com/antvis/g2plot/blob/master/CHANGELOG.md`,
          openExternal: true,
        },
        {
          icon: <GithubOutlined />,
          title: t('GitHub 仓库'),
          url: `https://github.com/antvis/g2plot`,
          openExternal: true,
        },
        {
          icon: '??',
          title: t('国内镜像'),
          url: `https://antv-g2plot.gitee.io`,
          openExternal: true,
        },
      ],
    },
    {
      title: 'Graphin',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/0b4HzOcEJY/Graphin.svg',
      slogan: t(''),
      description: t('基于 G6 封装的图分析应用组件。'),
      category: Categories[1],
      links: [
        {
          icon: <HomeOutlined />,
          title: t('产品首页'),
          url: `https://${hosts.graphin}/${language}`,
        },
        {
          icon: <ReadOutlined />,
          title: t('使用文档'),
          url: `https://${hosts.graphin}/${language}/docs/manual/introduction`,
        },
        {
          icon: <ReadOutlined />,
          title: t('API 文档'),
          url: `https://${hosts.graphin}/${language}/docs/api/graphin`,
        },
        {
          icon: <HistoryOutlined />,
          title: t('更新日志'),
          url: `https://github.com/antvis/graphin/blob/master/CHANGELOG.md`,
          openExternal: true,
        },
        {
          icon: <GithubOutlined />,
          title: t('GitHub 仓库'),
          url: `https://github.com/antvis/graphin`,
          openExternal: true,
        },
        {
          icon: '??',
          title: t('国内镜像'),
          url: `https://antv-graphin.gitee.io`,
          openExternal: true,
        },
      ],
    },
    {
      title: 'ChartCube',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/Zr74jx8YNX/chartcube.svg',
      slogan: t('图表魔方'),
      description: t('AntV 在线图表制作利器。'),
      category: Categories[1],
      links: [
        {
          icon: <HomeOutlined />,
          title: t('产品首页'),
          url: `https://chartcube.alipay.com`,
          openExternal: true,
        },
        {
          icon: <AreaChartOutlined />,
          title: t('生成图表'),
          url: `https://chartcube.alipay.com/guide`,
          openExternal: true,
        },
        {
          icon: <YuqueOutlined />,
          title: t('语雀社区'),
          url: `https://www.yuque.com/chartcube`,
          openExternal: true,
        },
        {
          icon: <DingdingOutlined />,
          title: t('钉钉服务群'),
          url: `dingtalk://dingtalkclient/action/joingroup?cid=8305538734`,
          openExternal: true,
        },
      ],
    },
    {
      title: t('墨者学院'),
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/12j36RPVldO/mozhexueyuan.svg',
      description: t('数据可视化社团'),
      category: Categories[2],
      links: [
        {
          title: t('学院首页'),
          url: `https://www.yuque.com/mo-college`,
          openExternal: true,
        },
      ],
    },
    {
      title: 'BizCharts',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/Q1pbg%26O2TM/BizCharts.svg',
      description: t('基于商业场景下的数据可视化解决方案'),
      category: Categories[2],
      links: [
        {
          title: t('产品首页'),
          url: 'https://bizcharts.net',
          openExternal: true,
        },
      ],
    },
    {
      title: 'Viser',
      icon: 'https://gw.alipayobjects.com/zos/antfincdn/QAyW5h99HVa/Viser.svg',
      description: t('基于 G2 实现的可视化解决方案'),
      category: Categories[2],
      links: [
        {
          title: t('产品首页'),
          url: `https://viserjs.github.io/`,
          openExternal: true,
        },
      ],
    },
  ];

  return products;
}
Example #13
Source File: Responsive.tsx    From yugong with MIT License 4 votes vote down vote up
Responsive: React.FC<Props> = () => {
  useEffect(() => {
    trackPageView('/首页');
  }, []);
  /**
   * ----------
   * 定义编辑模式
   * ----------
   */
  const { isEditing, auth } = useSelector(
    (state: RootState) => state.controller,
  );

  const history = useHistory();

  const appData = useSelector((state: RootState) => state.appData);
  const activationItem = useSelector(
    (state: RootState) => state.activationItem,
  );
  const stateTag = useSelector((state: RootState) => state.controller.stateTag);

  const forceUpdateByStateTag =
    useDispatch<Dispatch>().controller.forceUpdateByStateTag;
  const setIsEditing = useDispatch<Dispatch>().controller.setIsEditing;
  const updateAppData = useDispatch<Dispatch>().appData.updateAppData;
  const updatePageData = useDispatch<Dispatch>().pageData.updatePage;
  const setWindowHeight = useDispatch<Dispatch>().pageData.setWindowHeight;
  const setWindowWidth = useDispatch<Dispatch>().pageData.setWindowWidth;
  const updateActivationItem =
    useDispatch<Dispatch>().activationItem.updateActivationItem;
  const removeActivationItem =
    useDispatch<Dispatch>().activationItem.removeActivationItem;

  const setRunningTimes = useDispatch<Dispatch>().runningTimes.setRunningTimes;

  const ref = useRef(null);

  const pageData = useSelector((state: RootState) => state.pageData);
  const runningTimes = useSelector((state: RootState) => state.runningTimes);
  const setIsReady = useDispatch<Dispatch>().record.setIsReady;

  const [, setLocalPageData] = useLocalStorage('pageData', null);

  const [showDrawer, setShowDrawer] = useState(false);
  const [showPageDrawer, setShowPageDrawer] = useState(false);
  const [isCreate, setIsCreate] = useState(true);
  const [showTemplateModal, setShowTemplateModal] = useState(false);
  const [hideIframe, sethideIframe] = useState(true);
  const [visibleQrcode, setVisibleQrcode] = useState(false);

  // 创建postmessage通信 usePostMessage收集数据 redux 更新数据
  const sendMessage = usePostMessage(({ tag, value }) => {
    switch (tag) {
      case 'setIsEditing':
        setIsEditing(value);
        break;
      case 'updateAppData':
        updateAppData(value);
        // 同步更新被选模块的属性
        if (activationItem.moduleId === undefined) return;
        const asynAcactivationItem = (value as AppDataListTypes).find(
          (item) => item.moduleId === activationItem.moduleId,
        );
        if (asynAcactivationItem?.moduleId) {
          updateActivationItem(asynAcactivationItem);
        }
        break;
      case 'updateRunningTimes':
        setRunningTimes(value);
        break;
      case 'updatePage':
        updatePageData(value);
        break;
      case 'id':
        // 设置当前项正在被编辑
        // 禁止重复设置当前编辑项
        if (activationItem.moduleId === value) return;
        for (let index = 0; index < appData.length; index++) {
          const element = appData[index];
          if (element.moduleId === value) {
            updateActivationItem({ ...element });
            break;
          }
        }
        setShowDashboard(true);
        break;
      case 'record':
        saveRecord(value)
        break
      default:
        break;
    }
  });

  // 收发处理,子窗口onload时向子窗口发送信息, 通知当前正处于编辑模式下,
  const win: Window | null = ref.current
    ? (ref.current as any).contentWindow
    : null;

  useEffect(() => {
    const windows = (document.getElementById('wrapiframe') as any)
      ?.contentWindow;
    if (windows && !isCreate) {
      windows.onload = () => {
        sendMessage({ tag: 'setIsEditing', value: true }, windows);
        setIsEditing(true);
        setIsReady(true);
        sethideIframe(false);
      };
    }
  }, [sendMessage, setIsEditing, isCreate, setIsReady]);

  useEffect(() => {
    sendMessage({ tag: 'setIsEditing', value: true }, win);
    setIsEditing(true);
  }, [sendMessage, setIsEditing, win]);

  const toggleEdit = useCallback(() => {
    const states = !isEditing;
    sendMessage({ tag: 'setIsEditing', value: states }, win);
    setIsEditing(states);
  }, [isEditing, sendMessage, setIsEditing, win]);

  const toggleCreate = useCallback(() => {
    setIsCreate(!isCreate);
  }, [isCreate]);

  // 收发处理,编辑完数据后通过sendMessage向子窗口发送最新数据。
  useEffect(() => {
    sendMessage(
      {
        tag: 'updateAppData',
        value: appData,
      },
      win,
    );
  }, [sendMessage, win, appData]);

  const onChangeRule = (
    width: number,
    height: number = window.innerHeight - 140,
  ) => {
    setWindowWidth(width);
    setWindowHeight(height);
    const optPageData = { ...pageData };
    optPageData.windowWidth = width;
    optPageData.windowHeight = height;
    setLocalPageData(optPageData);
    if (win) {
      sendMessage({ tag: 'updatePage', value: true }, win);
      sendMessage({ tag: 'setIsEditing', value: isEditing }, win);
    }
    setIsEditing(true);
    forceUpdateByStateTag();
  };

  const [showDashboard, setShowDashboard] = useState(false);
  const [opacity, setOpacity] = useState('1');
  // 无激活模块时隐藏设置面板
  useEffect(() => {
    if (!activationItem.moduleId) {
      setShowDashboard(false);
    }
  }, [activationItem]);

  const hideDashboard = useCallback(() => {
    setShowDashboard(false);
    removeActivationItem();
    if (win) {
      sendMessage({ tag: 'removeActivationItem', value: undefined }, win);
    }
  }, [removeActivationItem, sendMessage, win]);

  const updateProject = useCallback(
    (data: Template) => {
      data.id = pageData.template?.id;
      return updateTemplate(data);
    },
    [pageData],
  );

  interface TemplateAll extends Template {
    pageData: string;
    appData: string;
  }

  // 保存或更新项目
  const onSaveProject = useCallback(
    async ({
      cove = [],
      terminal,
      isPublic,
      describe,
      tag,
      title,
      id,
    }: TemplateInfo) => {
      if (!auth?.isLogin) {
        history.push('/login');
        return;
      }

      // copy
      const pageDataCopy = cloneDeep(pageData);

      // template数据
      const templateData: Template = {
        title: title || pageData.pageTitle,
        terminal,
        cove: cove[0]?.thumbUrl,
        describe,
        tag: tag?.join(','),
        isPublic: isPublic === true ? 1 : 0,
      };
      // 存入模板信息到pageData
      if (!pageDataCopy.template) {
        pageDataCopy.template = templateData;
      }

      // 完整数据
      /**
       * 完整数据包含页面数据、组件数据与模板信息三个部分,
       * 页面数据同时也包含一份模板信息供页面处理
       */
      const params: TemplateAll = {
        pageData: JSON.stringify(pageData),
        appData: JSON.stringify(appData),
        id,
        userId: auth.session?.id,
        ...templateData,
      };
      try {
        loading.show();
        // 更新
        if (!!pageData.template?.id) {
          await updateProject(params);
        } else {
          // 新增
          const newId = await createTemplate(params);
          pageDataCopy.template.id = newId;
        }
        message.success('已发布');
        // 更新
        updatePageData(pageDataCopy);
        // 关闭弹窗
        setShowTemplateModal(false);
        // todo 展示二维码与模板访问链接,支持扫码访问
        setVisibleQrcode(true);
        loading.hide();
      } catch (error) {
        console.error(error);
        loading.hide();
      }
      
    },
    [
      appData,
      auth?.isLogin,
      auth?.session?.id,
      history,
      pageData,
      updatePageData,
      updateProject,
    ],
  );

  const showPublishModal = useCallback(() => {
    if (!auth?.isLogin) {
      history.push('/login');
    }
    setShowTemplateModal(true);
  }, [auth?.isLogin, history]);

  const pageSearch = stringify({ tpl: pageData.template?.id, ...runningTimes.search });

  const codeViewUrl = `${process.env.REACT_APP_SITE_PATH || ''}${pageSearch ? `?${pageSearch}` : ''}`;

  const viewUrl = `${process.env.REACT_APP_SITE_PATH || ''}${window.location.search || '?isediting'
    }`


  return (
    <>
      {isCreate ? (
        <CreateProject goBack={() => toggleCreate()} />
      ) : (
        <div className={s.main}>
          {showDashboard && isEditing ? (
            <Draggable
              axis="both"
              handle={`.${s.header}`}
              onDrag={() => setOpacity('0.5')}
              onStop={() => setOpacity('1')}
            >
              <div className={s.dashboard} style={{ opacity }}>
                <div className={s.header}>
                  <h3>设置面板</h3>
                  <CloseOutlined className={s.icon} onClick={hideDashboard} />
                </div>
                <MiniDashboard />
              </div>
            </Draggable>
          ) : null}
          <div className={s.topmenu}>
            <div className={s.create}>
              <Button
                type="primary"
                onClick={toggleCreate}
                icon={<FileAddOutlined />}
              />
              &nbsp;
              {!isEditing ? (
                <Button
                  type="default"
                  className={s.toggle}
                  onClick={toggleEdit}
                  icon={<EditOutlined />}
                />
              ) : null}
              {isEditing ? (
                <Button
                  type="default"
                  className={s.toggle}
                  onClick={toggleEdit}
                  icon={<EyeOutlined />}
                />
              ) : null}
              &nbsp;
              <Button
                type="default"
                icon={<SettingOutlined />}
                onClick={() => setShowPageDrawer(true)}
              >
                页面
              </Button>
              &nbsp;
              <Button
                type="default"
                icon={<PlusOutlined />}
                onClick={() => setShowDrawer(true)}
              >
                组件
              </Button>
              
              <Undo />
              &nbsp;
              <a href="https://github.com/eightfeet/yugong">
                <Button type="default" icon={<GithubOutlined />}>
                  github
                </Button>
              </a>
            </div>
            <div className={s.save}>
              <Button
                type="primary"
                icon={<CloudUploadOutlined />}
                onClick={showPublishModal}
              >
                {pageData.template?.id ? '修改' : '发布'}
              </Button>
              {pageData.template?.id ? <>
                &nbsp;
                <Button
                  icon={<QrcodeOutlined />}
                  onClick={() => setVisibleQrcode(true)}
                />
              </> : null}

            </div>
          </div>
          <Ruler onChange={onChangeRule} />
          <Drawer
            className={s.drawer}
            title="页面设置"
            width={580}
            onClose={() => setShowPageDrawer(false)}
            visible={showPageDrawer}
            bodyStyle={{ padding: '0', overflow: 'auto' }}
            maskStyle={{ backgroundColor: 'transparent' }}
            footer={null}
          >
            {showPageDrawer ? <PageSetting /> : null}
          </Drawer>
          <Drawer
            className={s.drawer}
            title="组件库"
            width={580}
            onClose={() => setShowDrawer(false)}
            visible={showDrawer}
            bodyStyle={{ padding: '0px' }}
            maskStyle={{ backgroundColor: 'transparent' }}
            footer={null}
          >
            <Repository />
          </Drawer>
          <div className={s.box}>
            <div
              className={classNames({
                [s.viewbg]: !isEditing,
              })}
              style={{ transition: 'all 0.5s' }}
            />
            {!stateTag ? (
              <div
                className={s.iframebox}
                style={{
                  width:
                    pageData.windowWidth === -1
                      ? `100%`
                      : `${pageData.windowWidth}px`,
                  height: `${pageData.windowHeight}px`,
                }}
              >
                <LoadingAnimate />
                <iframe
                  ref={ref}
                  id="wrapiframe"
                  title="wrapiframe"
                  src={viewUrl}
                  style={{
                    border: 'none',
                    opacity: hideIframe ? 0 : 1,
                    minWidth: '100%',
                    minHeight: `${pageData.windowHeight}px`,
                  }}
                />
              </div>
            ) : null}
          </div>
        </div>
      )}
      <TemplateInfoModal
        visible={showTemplateModal}
        onOk={onSaveProject}
        onCancel={() => setShowTemplateModal(false)}
      />
      <QrcodeModal
        visible={visibleQrcode}
        onCancel={() => setVisibleQrcode(false)}
        sourceData={codeViewUrl}
        title="请扫码访问"
        info={<div className={s.viewurl}>访问地址:<a href={codeViewUrl} target={'_blank'} rel="noreferrer">{codeViewUrl}</a></div>}
        options={{
          width: 122,
          margin: 1
        }}
      />
    </>
  );
}
Example #14
Source File: index.tsx    From nanolooker with MIT License 4 votes vote down vote up
StatisticsSocialPage: React.FC = () => {
  const { t } = useTranslation();
  const { statistics, isLoading } = useStatisticsSocial();
  const [filter, setFilter] = React.useState(Filter.REDDIT);

  React.useEffect(() => {
    if (isLoading || !statistics.length) return;

    const data = orderBy(
      statistics.filter(
        statistic => !!statistic[filterPerBillionToKeyMap[filter]],
      ),
      [filterPerBillionToKeyMap[filter]],
      ["desc"],
    ).map((statistic, index) => {
      statistic.rank = index + 1;
      return statistic;
    });

    const config = {
      data,
      xField: filterPerBillionToKeyMap[filter],
      yField: "name",
      seriesField: "name",
      height: data.length * 40,
      legend: {
        visible: false,
      },
      label: {
        content: (data: CryptoCurrency) => {
          const group = new G.Group({});
          group.addShape({
            type: "image",
            attrs: {
              x: 0,
              y: 0,
              width: 20,
              height: 20,
              img: `/cryptocurrencies/logo/${data.symbol}.png`,
            },
          });

          group.addShape({
            type: "text",
            attrs: {
              x: 25,
              y: 5,
              text: data[filterPerBillionToKeyMap[filter]],
              textAlign: "left",
              textBaseline: "top",
              fill: "#595959",
            },
          });

          return group;
        },
        position: "right",
        offset: 4,
      },
      tooltip: {
        // @ts-ignore
        title: (text, data) => `#${data.rank} ${text}`,
        customItems: (originalItems: any) => {
          const items = [
            {
              color: originalItems[0].color,
              name: t("pages.statistics.social.engagementPerBillion"),
              value: originalItems[0].value,
            },
            {
              name: t("pages.statistics.social.marketCap"),
              value: `$${new BigNumber(originalItems[0].data.marketCap)
                .dividedBy(1_000_000_000)
                .toFixed(2)}B`,
            },
            {
              name: t("pages.statistics.social.totalEngagement"),
              value: originalItems[0].data[filterTotalToKeyMap[filter]],
            },
          ];

          return items;
        },
      },
    };

    if (!socialChart) {
      socialChart = new Bar(
        document.getElementById("social-chart") as HTMLElement,
        // @ts-ignore
        config,
      );
      socialChart.render();
    } else {
      socialChart.update(config);
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isLoading, statistics, filter]);

  React.useEffect(() => {
    return () => {
      socialChart?.destroy();
      socialChart = null;
    };
  }, []);

  return (
    <>
      <Helmet>
        <title>{t("pages.statistics.social.title")}</title>
      </Helmet>
      <Title level={3}>
        {t("pages.statistics.social.title")}
        <Tooltip placement="right" title={t("tooltips.socialStatistics")}>
          <QuestionCircle />
        </Tooltip>
      </Title>
      <Card size="small" bordered={false} className="detail-layout">
        <Row>
          <Col xs={24}>
            <Radio.Group
              value={filter}
              onChange={({ target: { value } }) => {
                setFilter(value);
              }}
            >
              <Radio.Button value={Filter.REDDIT}>
                <RedditOutlined /> Reddit
              </Radio.Button>
              <Radio.Button value={Filter.TWITTER}>
                <TwitterOutlined /> Twitter
              </Radio.Button>
              <Radio.Button value={Filter.GITHUB}>
                <GithubOutlined /> Github
              </Radio.Button>
            </Radio.Group>
            <br />
            <br />
            <Text>
              {t(`pages.statistics.social.${filterTotalToKeyMap[filter]}`)}
            </Text>
          </Col>
        </Row>
        <Row>
          <Col xs={24}>
            <Skeleton loading={isLoading || !statistics.length} active>
              <div id="social-chart" />
            </Skeleton>
          </Col>
        </Row>
      </Card>
    </>
  );
}
Example #15
Source File: index.tsx    From datart with Apache License 2.0 4 votes vote down vote up
Outputs = memo(() => {
  const { actions } = useViewSlice();
  const dispatch = useDispatch();
  const systemInfo = useSelector(selectSystemInfo);
  const t = useI18NPrefix('view');

  const error = useSelector(state =>
    selectCurrentEditingViewAttr(state, { name: 'error' }),
  ) as string;
  const stage = useSelector(state =>
    selectCurrentEditingViewAttr(state, { name: 'stage' }),
  ) as ViewViewModelStages;
  const warnings = useSelector(state =>
    selectCurrentEditingViewAttr(state, { name: 'warnings' }),
  ) as string[];
  const { width, height, ref } = useResizeObserver({
    refreshMode: 'debounce',
    refreshRate: 200,
  });

  const removeViewWarnings = useCallback(() => {
    dispatch(
      actions.changeCurrentEditingView({
        warnings: null,
      }),
    );
  }, [dispatch, actions]);

  const submitIssue = useCallback(
    type => {
      let params: any = {
        type: type,
        title: 'Sql parse bug',
      };
      if (type === 'github') {
        params.body = `version: ${systemInfo?.version}\n` + warnings.join('');
      } else {
        params.description =
          `version: ${systemInfo?.version}\n` + warnings.join('');
      }
      let url = newIssueUrl(params);
      window.open(url);
    },
    [warnings, systemInfo],
  );

  return (
    <Wrapper ref={ref}>
      {warnings && (
        <Alert
          className="warningBox"
          message=""
          description={
            <p>
              {t('sqlRunWraning')}
              <Popover
                trigger={['click']}
                placement="top"
                overlayStyle={{ width: SPACE_TIMES(96) }}
                content={t('warningDescription')}
              >
                <Button className="detail" type="link" size="small">
                  {t('detail')}
                </Button>
              </Popover>
            </p>
          }
          type="warning"
          closable={false}
          action={
            <Space>
              <Button
                type="primary"
                icon={<GithubOutlined />}
                onClick={() => submitIssue('github')}
              >
                Github
              </Button>
              <Button type="primary" onClick={() => submitIssue('gitee')}>
                Gitee
              </Button>
              <Button onClick={removeViewWarnings}>{t('close')}</Button>
            </Space>
          }
        />
      )}

      <Results width={width} height={height} />
      {error && <Error />}
      {stage === ViewViewModelStages.Running && (
        <LoadingMask>
          <Spin />
        </LoadingMask>
      )}
    </Wrapper>
  );
})