@ant-design/icons#EyeInvisibleOutlined TypeScript Examples

The following examples show how to use @ant-design/icons#EyeInvisibleOutlined. 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: GlobalMenu.tsx    From ant-extensions with MIT License 6 votes vote down vote up
GlobalMenu: React.FC<{ disabled: boolean }> = React.memo(({ disabled }) => {
  const { t } = useTranslation(I18nKey);
  const { filters, enableAll, toggleExclude, removeAll } = useContext(Context);

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

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

  return (
    <Dropdown overlay={menu} trigger={["click"]} disabled={disabled || filters.length === 0}>
      <Button type="link" icon={<SettingOutlined />} />
    </Dropdown>
  );
})
Example #2
Source File: editor-operate.tsx    From electron-playground with MIT License 6 votes vote down vote up
WrapMenu = function ({ layout, setLayout }: MProp) {
  const visibleMosaics = getVisibleMosaics(layout)
  const menuItem = ['main.js', 'renderer.js', 'index.html', 'preload.js']

  const onItemClick = (str: string) => {
    return () => {
      let newMosaicsArrangement: Array<EditorId>

      if (visibleMosaics.includes(str as EditorId)) {
        newMosaicsArrangement = visibleMosaics.filter(i => i !== str)
      } else {
        newMosaicsArrangement = [...visibleMosaics, str as EditorId]
      }
      setLayout(createMosaicArrangement(newMosaicsArrangement))
    }
  }

  return (
    <Menu>
      {menuItem.map(item => (
        <Menu.Item
          key={item}
          onClick={onItemClick(item)}
          id={item}
          icon={
            visibleMosaics.includes(item as EditorId) ? <EyeOutlined /> : <EyeInvisibleOutlined />
          }>
          {item}
        </Menu.Item>
      ))}
    </Menu>
  )
}
Example #3
Source File: FilterTag.tsx    From ant-extensions with MIT License 4 votes vote down vote up
FilterTag: React.FC<{
  filter: IFilterObject;
  index: number;
  disabled: boolean;
}> = React.memo(({ index, filter, disabled }) => {
  const { t } = useTranslation(I18nKey);

  const { field, operator, type, value, label, compare, active, negative, required } = filter;

  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState(required);
  const { fields, updateFilter, removeFilter } = useContext(Context);

  const displayValue = useMemo(() => {
    const _field = fields.find((f) => f.key === field);
    const _compare = fields.find((f) => f.key === compare);
    let _value = value ? `"${value.toString()}"` : "";
    if (type === "compare") {
      _value = _compare ? _compare.name : compare || "";
    }
    return _value ? (
      <span className="ant-ext-sb__filterTag--clip">
        {_field && value && _field.type === EnumFieldType.DATE
          ? DateUtils.label(value.toString())
          : _value}
      </span>
    ) : undefined;
  }, [fields, value, type, field, compare]);

  const displayLabel = useMemo(() => {
    const _field = fields.find((f) => f.key === field);
    return (
      <>
        <span className="ant-ext-sb__filterTag--clip">{_field ? _field.name : field}</span>
        <b>&nbsp;{t(`operator.${operator}`)}&nbsp;</b>
        {displayValue}
      </>
    );
  }, [field, operator, displayValue, fields, t]);

  const menuOverlay = useMemo(
    () => (
      <Menu className="ant-ext-sb__dropdown">
        <Menu.Item onClick={() => setEditing(true)}>
          <EditOutlined /> {t(`label.edit`)}
        </Menu.Item>
        <Menu.Item onClick={() => updateFilter(index, { active: !active })}>
          {active ? <EyeOutlined /> : <EyeInvisibleOutlined />}{" "}
          {t(`label.${active ? "disable" : "enable"}`)}
        </Menu.Item>
        <Menu.Item onClick={() => updateFilter(index, { negative: !negative })}>
          <Icon component={TwoTone} /> {t(`label.${negative ? "include" : "exclude"}`)}
        </Menu.Item>
        <Menu.Item
          className="ant-typography ant-typography-danger"
          onClick={() => removeFilter(index)}
        >
          <DeleteOutlined /> {t("label.remove")}
        </Menu.Item>
      </Menu>
    ),
    [active, negative, index, removeFilter, t, updateFilter]
  );

  const formOverlay = useMemo(
    () => (
      <div className="ant-ext-sb__dropdown" data-for-required={required}>
        <FilterForm
          filter={filter}
          index={index}
          onCancel={() => [setOpen(false), setEditing(required)]}
        />
      </div>
    ),
    [filter, index, required]
  );

  const color = useMemo(
    () =>
      negative ? (type === "filter" ? "red" : "orange") : type === "filter" ? "blue" : "geekblue",
    [negative, type]
  );

  return (
    <Tag
      className="ant-ext-sb__filterTag"
      color={color}
      data-active={active && !disabled}
      data-negative={negative}
      closable={!required}
      onClose={() => removeFilter(index)}
    >
      {!required && (
        <Checkbox
          style={{ gridArea: "check" }}
          checked={active}
          disabled={disabled}
          onChange={(e) => updateFilter(index, { active: e.target.checked })}
        />
      )}
      <Tooltip overlay={displayLabel} trigger="hover">
        <Dropdown
          overlay={editing ? formOverlay : menuOverlay}
          trigger={["click"]}
          visible={open}
          disabled={disabled}
          overlayStyle={{ zIndex: 1010 }}
          onVisibleChange={(visible) => [setOpen(visible), !visible && setEditing(required)]}
        >
          <span className="ant-ext-sb__filterTag--label" onClick={() => setOpen(true)}>
            {label ? label : displayLabel}
          </span>
        </Dropdown>
      </Tooltip>
    </Tag>
  );
})
Example #4
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 #5
Source File: OpticalPathItem.tsx    From slim with Apache License 2.0 4 votes vote down vote up
render (): React.ReactNode {
    const identifier = this.props.opticalPath.identifier
    const description = this.props.opticalPath.description
    const attributes: Array<{ name: string, value: string }> = []
    if (this.props.opticalPath.illuminationWaveLength !== undefined) {
      attributes.push(
        {
          name: 'Illumination wavelength',
          value: `${this.props.opticalPath.illuminationWaveLength} nm`
        }
      )
    }
    if (this.props.opticalPath.illuminationColor !== undefined) {
      attributes.push(
        {
          name: 'Illumination color',
          value: this.props.opticalPath.illuminationColor.CodeMeaning
        }
      )
    }

    // TID 8001 "Specimen Preparation"
    const specimenDescriptions: dmv.metadata.SpecimenDescription[] = (
      this.props.metadata[0].SpecimenDescriptionSequence ?? []
    )
    specimenDescriptions.forEach(description => {
      const specimenPreparationSteps: dmv.metadata.SpecimenPreparation[] = (
        description.SpecimenPreparationSequence ?? []
      )
      specimenPreparationSteps.forEach(
        (step: dmv.metadata.SpecimenPreparation, index: number): void => {
          step.SpecimenPreparationStepContentItemSequence.forEach((
            item: (
              dcmjs.sr.valueTypes.CodeContentItem |
              dcmjs.sr.valueTypes.TextContentItem |
              dcmjs.sr.valueTypes.UIDRefContentItem |
              dcmjs.sr.valueTypes.PNameContentItem |
              dcmjs.sr.valueTypes.DateTimeContentItem
            ),
            index: number
          ) => {
            const name = new dcmjs.sr.coding.CodedConcept({
              value: item.ConceptNameCodeSequence[0].CodeValue,
              schemeDesignator:
                item.ConceptNameCodeSequence[0].CodingSchemeDesignator,
              meaning: item.ConceptNameCodeSequence[0].CodeMeaning
            })
            if (item.ValueType === dcmjs.sr.valueTypes.ValueTypes.CODE) {
              item = item as dcmjs.sr.valueTypes.CodeContentItem
              const value = new dcmjs.sr.coding.CodedConcept({
                value: item.ConceptCodeSequence[0].CodeValue,
                schemeDesignator:
                  item.ConceptCodeSequence[0].CodingSchemeDesignator,
                meaning: item.ConceptCodeSequence[0].CodeMeaning
              })
              if (!name.equals(SpecimenPreparationStepItems.PROCESSING_TYPE)) {
                if (name.equals(SpecimenPreparationStepItems.STAIN)) {
                  attributes.push({
                    name: 'Tissue stain',
                    value: value.CodeMeaning
                  })
                }
              }
            } else if (item.ValueType === dcmjs.sr.valueTypes.ValueTypes.TEXT) {
              item = item as dcmjs.sr.valueTypes.TextContentItem
              if (!name.equals(SpecimenPreparationStepItems.PROCESSING_TYPE)) {
                if (name.equals(SpecimenPreparationStepItems.STAIN)) {
                  attributes.push({
                    name: 'Tissue stain',
                    value: item.TextValue
                  })
                }
              }
            }
          })
        }
      )
    })

    const maxValue = Math.pow(2, this.props.metadata[0].BitsAllocated) - 1

    const title = (
      description != null ? `${identifier}: ${description}` : identifier
    )
    let settings
    let item
    if (this.props.opticalPath.isMonochromatic) {
      // monochrome images that can be pseudo-colored
      let colorSettings
      if (this.state.currentStyle.color != null) {
        colorSettings = (
          <>
            <Divider plain>
              Color
            </Divider>
            <Row justify='center' align='middle' gutter={[8, 8]}>
              <Col span={5}>
                Red
              </Col>
              <Col span={14}>
                <Slider
                  range={false}
                  min={0}
                  max={255}
                  step={1}
                  value={this.state.currentStyle.color[0]}
                  onChange={this.handleColorRChange}
                />
              </Col>
              <Col span={5}>
                <InputNumber
                  min={0}
                  max={255}
                  size='small'
                  style={{ width: '65px' }}
                  value={this.state.currentStyle.color[0]}
                  onChange={this.handleColorRChange}
                />
              </Col>
            </Row>

            <Row justify='center' align='middle' gutter={[8, 8]}>
              <Col span={5}>
                Green
              </Col>
              <Col span={14}>
                <Slider
                  range={false}
                  min={0}
                  max={255}
                  step={1}
                  value={this.state.currentStyle.color[1]}
                  onChange={this.handleColorGChange}
                />
              </Col>
              <Col span={5}>
                <InputNumber
                  min={0}
                  max={255}
                  size='small'
                  style={{ width: '65px' }}
                  value={this.state.currentStyle.color[1]}
                  onChange={this.handleColorGChange}
                />
              </Col>
            </Row>

            <Row justify='center' align='middle' gutter={[8, 8]}>
              <Col span={5}>
                Blue
              </Col>
              <Col span={14}>
                <Slider
                  range={false}
                  min={0}
                  max={255}
                  step={1}
                  value={this.state.currentStyle.color[2]}
                  onChange={this.handleColorBChange}
                />
              </Col>
              <Col span={5}>
                <InputNumber
                  min={0}
                  max={255}
                  size='small'
                  style={{ width: '65px' }}
                  value={this.state.currentStyle.color[2]}
                  onChange={this.handleColorBChange}
                />
              </Col>
            </Row>
          </>
        )
      }

      let windowSettings
      if (this.state.currentStyle.limitValues != null) {
        windowSettings = (
          <>
            <Divider plain>
              Values of interest
            </Divider>
            <Row justify='center' align='middle' gutter={[8, 8]}>
              <Col span={6}>
                <InputNumber
                  min={0}
                  max={this.state.currentStyle.limitValues[1]}
                  size='small'
                  style={{ width: '75px' }}
                  value={this.state.currentStyle.limitValues[0]}
                  onChange={this.handleLowerLimitChange}
                />
              </Col>
              <Col span={12}>
                <Slider
                  range
                  min={0}
                  max={maxValue}
                  step={1}
                  value={[
                    this.state.currentStyle.limitValues[0],
                    this.state.currentStyle.limitValues[1]
                  ]}
                  onChange={this.handleLimitChange}
                />
              </Col>
              <Col span={6}>
                <InputNumber
                  min={this.state.currentStyle.limitValues[0]}
                  max={maxValue}
                  size='small'
                  style={{ width: '75px' }}
                  value={this.state.currentStyle.limitValues[1]}
                  onChange={this.handleUpperLimitChange}
                />
              </Col>
            </Row>
          </>
        )
      }
      settings = (
        <div>
          {windowSettings}
          {colorSettings}
          <Divider plain />
          <Row justify='center' align='middle' gutter={[8, 8]}>
            <Col span={6}>
              Opacity
            </Col>
            <Col span={12}>
              <Slider
                range={false}
                min={0}
                max={1}
                step={0.01}
                value={this.state.currentStyle.opacity}
                onChange={this.handleOpacityChange}
              />
            </Col>
            <Col span={6}>
              <InputNumber
                min={0}
                max={1}
                size='small'
                step={0.1}
                style={{ width: '65px' }}
                value={this.state.currentStyle.opacity}
                onChange={this.handleOpacityChange}
              />
            </Col>
          </Row>
        </div>
      )
      const colors = this.getCurrentColors()
      item = (
        <Badge
          offset={[-20, 20]}
          count={' '}
          style={{
            borderStyle: 'solid',
            borderWidth: '1px',
            borderColor: 'gray',
            visibility: this.state.isVisible ? 'visible' : 'hidden',
            backgroundImage: `linear-gradient(to right, ${colors.toString()})`
          }}
        >
          <Description
            header={title}
            attributes={attributes}
            selectable
            hasLongValues
          />
        </Badge>
      )
    } else {
      // color images
      settings = (
        <div>
          <Row justify='center' align='middle' gutter={[8, 8]}>
            <Col span={6}>
              Opacity
            </Col>
            <Col span={12}>
              <Slider
                range={false}
                min={0}
                max={1}
                step={0.01}
                value={this.state.currentStyle.opacity}
                onChange={this.handleOpacityChange}
              />
            </Col>
            <Col span={6}>
              <InputNumber
                min={0}
                max={1}
                size='small'
                step={0.1}
                style={{ width: '60px' }}
                value={this.state.currentStyle.opacity}
                onChange={this.handleOpacityChange}
              />
            </Col>
          </Row>
        </div>
      )
      item = (
        <Description
          header={title}
          attributes={attributes}
          selectable
          hasLongValues
        />
      )
    }

    const buttons = []
    if (this.props.isRemovable) {
      buttons.push(
        <Tooltip title='Remove Optical Path'>
          <Button
            type='default'
            shape='circle'
            icon={<DeleteOutlined />}
            onClick={this.handleRemoval}
          />
        </Tooltip>
      )
    }

    const {
      defaultStyle,
      isRemovable,
      isVisible,
      metadata,
      onVisibilityChange,
      onStyleChange,
      onRemoval,
      opticalPath,
      ...otherProps
    } = this.props
    return (
      <Menu.Item
        style={{ height: '100%', paddingLeft: '3px' }}
        key={this.props.opticalPath.identifier}
        {...otherProps}
      >
        <Space align='start'>
          <div style={{ paddingLeft: '14px' }}>
            <Space direction='vertical' align='end'>
              <Switch
                size='small'
                checked={this.state.isVisible}
                onChange={this.handleVisibilityChange}
                checkedChildren={<EyeOutlined />}
                unCheckedChildren={<EyeInvisibleOutlined />}
              />
              <Popover
                placement='left'
                content={settings}
                overlayStyle={{ width: '350px' }}
                title='Display Settings'
              >
                <Button
                  type='primary'
                  shape='circle'
                  icon={<SettingOutlined />}
                />
              </Popover>
              {buttons}
            </Space>
          </div>
          {item}
        </Space>
      </Menu.Item>
    )
  }
Example #6
Source File: index.tsx    From foodie with MIT License 4 votes vote down vote up
Login: React.FC = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [isPasswordVisible, setPasswordVisible] = useState(false);
    const dispatch = useDispatch();

    useDocumentTitle('Login to Foodie');
    useEffect(() => {
        return () => {
            dispatch(setAuthErrorMessage(null));
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const { error, isLoading } = useSelector((state: IRootReducer) => ({
        error: state.error.authError,
        isLoading: state.loading.isLoadingAuth
    }));

    const onUsernameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value.trim();

        setUsername(val);
    };

    const onPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value;

        setPassword(val);
    };

    const onSubmit = async (e: FormEvent) => {
        e.preventDefault();

        if (username && password) {
            dispatch(loginStart(username, password));
        }
    };

    return (
        <div className="min-h-screen flex bg-white">
            <div
                className="relative laptop:w-7/12 h-screen laptop:p-8 hidden laptop:justify-start laptop:items-end laptop:!bg-cover laptop:!bg-no-repeat laptop:!bg-center laptop:flex"
                style={{
                    background: `#f7f7f7 url(${bg})`
                }}
            >
                {/* --- LOGO --- */}
                <Link className="absolute left-8 top-8" to="/">
                    <img src={logo} alt="Foodie Logo" className="w-24" />
                </Link>
                {/* -- INFO --- */}
                <h3 className="animate-fade text-white w-9/12 mb-14">
                    Looking for a new idea for your next menu? You're in the right place.
                </h3>
                {/* --- CREDITS LINK --- */}
                <a
                    className="animate-fade absolute bottom-8 left-8 text-1xs text-white underline"
                    target="_blank"
                    rel="noreferrer"
                    href="https://infinityrimapts.com/5-reasons-host-dinner-party/friends-enjoying-a-meal/"
                >
                    Photo: Credits to the photo owner
                </a>
            </div>
            <div className="animate-fade laptop:w-5/12 w-full flex items-center flex-col justify-center pt-8 laptop:pt-0 relative">
                <Link to="/">
                    <img
                        src={logo_dark}
                        alt="Foodie Logo"
                        className="w-24 relative mx-auto laptop:hidden"
                    />
                </Link>
                {error && (
                    <div className="py-2 w-full text-center bg-red-100 border-red-300 absolute top-0 left-0">
                        <p className="text-red-500">{error?.error?.message || 'Something went wrong :('}</p>
                    </div>
                )}
                <div className="w-full laptop:px-14 px-8 text-center laptop:text-left">
                    <div>
                        <h2 className="mt-6 text-xl laptop:text-2xl font-extrabold text-gray-900">
                            Login to Foodie
                    </h2>
                    </div>
                    <form className="mt-8 space-y-6" onSubmit={onSubmit}>
                        <div className="rounded-md shadow-sm -space-y-px">
                            <div className="mb-2">
                                <label htmlFor="username" className="sr-only">Username</label>
                                <input
                                    id="username"
                                    name="username"
                                    type="text"
                                    autoComplete="username"
                                    value={username}
                                    required
                                    maxLength={30}
                                    className={`text-center ${error ? 'input--error' : ''} laptop:text-left`}
                                    placeholder="Username"
                                    readOnly={isLoading}
                                    onChange={onUsernameChange}
                                />
                            </div>
                            <div className="relative">
                                <label htmlFor="password" className="sr-only">Password</label>
                                <input
                                    id="password"
                                    name="password"
                                    type={isPasswordVisible ? 'text' : 'password'}
                                    autoComplete="current-password"
                                    required
                                    className={`text-center !pr-12 ${error ? 'input--error' : ''} laptop:text-left`}
                                    placeholder="Password"
                                    minLength={8}
                                    maxLength={100}
                                    onChange={onPasswordChange}
                                    readOnly={isLoading}
                                    value={password}
                                />
                                <div className="absolute right-0 top-0 bottom-0 my-auto flex items-center justify-center w-12 h-12 hover:bg-gray-200 cursor-pointer rounded-tr-full rounded-br-full z-10">
                                    {isPasswordVisible ? (
                                        <EyeInvisibleOutlined
                                            className="h-full w-full outline-none text-gray-500"
                                            onClick={() => setPasswordVisible(false)}
                                        />
                                    ) : (
                                        <EyeOutlined
                                            className="h-full w-full outline-none"
                                            onClick={() => setPasswordVisible(true)}
                                        />
                                    )}
                                </div>
                            </div>
                        </div>
                        <Link className="font-medium text-sm text-gray-400 inline-block laptop:block my-4  laptop:mb-0 hover:text-indigo-500 underline laptop:w-2/4 laptop:pl-4" to="/forgot-password">
                            Forgot your password?
                            </Link>
                        <button type="submit" className="button--stretch" disabled={isLoading}>
                            <LockFilled className="absolute left-8 top-0 bottom-0 my-auto" />
                            {isLoading ? 'Logging In...' : 'Login'}
                        </button>
                        {/* -- TOO HARD TO REPLICATE PSEUDO IN TAILWIND :() */}
                        <i className="social-login-divider">OR</i>
                        <div className="flex justify-between space-x-2">
                            <SocialLogin isLoading={isLoading} />
                        </div>
                    </form>
                    <div className="text-center mt-8">
                        <Link
                            className="underline font-medium"
                            onClick={(e) => isLoading && e.preventDefault()}
                            to={REGISTER}
                        >
                            I dont have an account
                        </Link>
                    </div>
                    {/* --- COPYRIGHT -- */}
                    <span className="text-gray-400 text-xs mx-auto text-center block mt-4">
                        &copy;Copyright {new Date().getFullYear()} Foodie
                    </span>
                </div>
            </div>
        </div>
    );
}
Example #7
Source File: index.tsx    From foodie with MIT License 4 votes vote down vote up
Register: React.FC = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [username, setUsername] = useState('');
    const [isPasswordVisible, setPasswordVisible] = useState(false);
    const dispatch = useDispatch();

    useDocumentTitle('Register to Foodie');
    useEffect(() => {
        return () => {
            dispatch(setAuthErrorMessage(null));
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const { error, isLoading } = useSelector((state: IRootReducer) => ({
        error: state.error.authError,
        isLoading: state.loading.isLoadingAuth
    }));

    const onEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value.trim();

        setEmail(val.toLowerCase());
    };

    const onPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value.trim();

        setPassword(val);
    };

    const onUsernameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value.trim();

        setUsername(val.toLowerCase());
    };

    const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        if (email && password && username) {
            dispatch(registerStart({ email, password, username }));
        }
    };
    return (
        <div className="min-h-screen flex bg-white">
            <div
                className="relative hidden laptop:w-7/12 h-screen laptop:p-8 laptop:flex laptop:justify-start laptop:items-end !bg-cover !bg-no-repeat !bg-center"
                style={{
                    background: `#f7f7f7 url(${bg})`
                }}
            >
                {/* --- LOGO --- */}
                <Link className="absolute left-8 top-8" to="/">
                    <img src={logo} alt="Foodie Logo" className="w-24" />
                </Link>
                {/* -- INFO --- */}
                <h3 className="animate-fade text-white w-9/12 mb-14">
                    Create your account now and discover new ideas and connect with people.
                </h3>
                {/* --- CREDITS LINK --- */}
                <a
                    className="animate-fade absolute bottom-8 left-8 text-1xs text-white underline"
                    target="_blank"
                    rel="noreferrer"
                    href="https://infinityrimapts.com/5-reasons-host-dinner-party/friends-enjoying-a-meal/"
                >
                    Photo: Credits to the photo owner
                </a>
            </div>
            <div className="relative animate-fade w-full text-center laptop:w-5/12 laptop:text-left flex items-center flex-col justify-center pt-8 laptop:pt-0">
                <Link to="/">
                    <img
                        src={logo_dark}
                        alt="Foodie Logo"
                        className="w-24 relative mx-auto laptop:hidden"
                    />
                </Link>
                {error && (
                    <div className="p-4 w-full text-center bg-red-100 border-red-400 absolute top-0 left-0">
                        <p className="text-red-500 text-sm">{error?.error?.message || 'Something went wrong :('}</p>
                    </div>
                )}
                <div className="w-full px-8 laptop:px-14">
                    <div>
                        <h2 className="mt-6 text-xl laptop:text-2xl font-extrabold text-gray-900">
                            Create your account
                        </h2>
                    </div>
                    <form className="mt-8 space-y-6" onSubmit={onSubmit}>
                        <div className="rounded-md shadow-sm space-y-2">
                            <div>
                                <label htmlFor="email-address" className="sr-only">Username</label>
                                <input
                                    id="username"
                                    name="username"
                                    type="text"
                                    className={` ${error ? 'input--error' : ''}`}
                                    onChange={onUsernameChange}
                                    autoComplete="username"
                                    maxLength={30}
                                    required
                                    readOnly={isLoading}
                                    placeholder="Username"
                                    value={username}
                                />
                            </div>
                            <div>
                                <label htmlFor="email-address" className="sr-only">Email address</label>
                                <input
                                    id="email-address"
                                    name="email"
                                    type="email"
                                    className={` ${error ? 'input--error' : ''}`}
                                    onChange={onEmailChange}
                                    autoComplete="email"
                                    maxLength={64}
                                    required
                                    readOnly={isLoading}
                                    placeholder="Email Address"
                                    value={email}
                                />
                            </div>
                            <div className="relative">
                                <label htmlFor="password" className="sr-only">Password</label>
                                <input
                                    id="password"
                                    name="password"
                                    type={isPasswordVisible ? 'text' : 'password'}
                                    className={`!pr-12 ${error ? 'input--error' : ''}`}
                                    onChange={onPasswordChange}
                                    autoComplete="current-password"
                                    required
                                    minLength={8}
                                    maxLength={100}
                                    readOnly={isLoading}
                                    placeholder="Password"
                                    value={password}
                                />
                                <div className="absolute right-0 top-0 bottom-0 my-auto flex items-center justify-center w-12 h-12 hover:bg-gray-200 cursor-pointer rounded-tr-full rounded-br-full z-10">
                                    {isPasswordVisible ? (
                                        <EyeInvisibleOutlined
                                            className="h-full w-full outline-none text-gray-500"
                                            onClick={() => setPasswordVisible(false)}
                                        />
                                    ) : (
                                        <EyeOutlined
                                            className="h-full w-full outline-none"
                                            onClick={() => setPasswordVisible(true)}
                                        />
                                    )}
                                </div>
                            </div>
                        </div>
                        <div>
                            <button type="submit" className="button--stretch" disabled={isLoading}>
                                {isLoading ? 'Registering...' : 'Register'}
                            </button>
                        </div>
                        <i className="social-login-divider">OR</i>
                        <div className="flex justify-between space-x-2">
                            <SocialLogin isLoading={isLoading} />
                        </div>
                    </form>
                    <div className="text-center mt-8">
                        <Link
                            className="underline font-medium"
                            onClick={(e) => isLoading && e.preventDefault()}
                            to={LOGIN}
                        >
                            Login instead
                        </Link>
                    </div>
                    {/* --- COPYRIGHT -- */}
                    <span className="text-gray-400 text-xs mx-auto text-center block mt-4">
                        &copy;Copyright {new Date().getFullYear()} Foodie
                    </span>
                </div>
            </div>
        </div>
    );
}
Example #8
Source File: ConfigurableFieldsForm.tsx    From jitsu with MIT License 4 votes vote down vote up
ConfigurableFieldsFormComponent = ({
  fieldsParamsList,
  form,
  extraForms,
  initialValues,
  availableOauthBackendSecrets,
  hideFields,
  handleTouchAnyField,
  setFormValues,
  setInitialFormValues,
}: Props) => {
  const [debugModalsStates, setDebugModalsStates] = useState<{ [id: string]: boolean }>({})
  const [debugModalsValues, setDebugModalsValues] = useState<{ [id: string]: string }>({})

  const forceUpdateAll = useForceUpdate()
  const { forceUpdatedTargets, forceUpdateTheTarget } = useForceUpdateTarget()

  const handleTouchField = debounce(handleTouchAnyField ?? (() => {}), 1000)

  const handleChangeIntInput = useCallback(
    (id: string) => (value: number) => {
      form.setFieldsValue({ [id]: value })
    },
    [form]
  )

  const handleChangeTextInput = useCallback(
    (id: string) => (value: string) => {
      form.setFieldsValue({ [id]: value })
    },
    [form]
  )

  const handleChangeSwitch = useCallback(
    (id: string) => (value: boolean) => {
      form.setFieldsValue({ [id]: value })
      handleTouchAnyField?.()
      forceUpdateAll()
      handleTouchField()
    },
    [form, forceUpdateAll]
  )
  const handleOpenDebugger = useCallback(
    (id: string) => {
      setDebugModalsValues({ ...debugModalsValues, [id]: form.getFieldValue(id) })
      setDebugModalsStates({ ...debugModalsStates, [id]: true })
    },
    [form]
  )

  const handleJsonChange = (id: string) => (value: string) => {
    const values = {
      [id]: value ? value : "",
    }
    form.setFieldsValue(values)
    setFormValues?.(form.getFieldsValue())
    handleTouchField()
  }

  const getInitialValue = (id: string, defaultValue: any, constantValue: any, type: string) => {
    const initial = get(initialValues, id)
    if (typeof initial !== "undefined") {
      return initial
    }

    let calcValue: any
    if (typeof defaultValue !== "undefined") {
      calcValue = defaultValue
    } else if (typeof constantValue !== "undefined") {
      calcValue = constantValue
    } else if (type === "boolean") {
      calcValue = false
    } else if (type === "json") {
      calcValue = {}
    } else if (type === "javascript") {
      calcValue = "return {}"
    } else if (type === "html") {
      calcValue = "<script>\n</script>"
    } else if (type.indexOf("array/") === 0) {
      calcValue = []
    } else {
      calcValue = ""
    }

    return type === "json" ? JSON.stringify(calcValue) : calcValue
  }

  const getFieldComponent = (
    type: ParameterType<any>,
    id: string,
    defaultValue?: any,
    constantValue?: any,
    jsDebugger?: "object" | "string" | null,
    bigField?: boolean,
    displayName?: string,
    codeSuggestions?: string,
    documentation?: React.ReactNode,
    validationRules?: FormItemProps["rules"]
  ) => {
    const defaultValueToDisplay =
      form.getFieldValue(id) ?? getInitialValue(id, defaultValue, constantValue, type?.typeName)
    form.setFieldsValue({ ...form.getFieldsValue(), [id]: defaultValueToDisplay })

    const className = hideFields?.some(field => field === getFieldNameById(id)) ? "hidden" : ""

    const formItemWrapperProps: FormItemWrapperProps = {
      type,
      id,
      bigField,
      displayName,
      documentation,
      validationRules,
      className,
    }

    switch (type?.typeName) {
      case "password":
        return (
          <FormItemWrapper key={id} {...formItemWrapperProps}>
            <Input.Password
              autoComplete="off"
              iconRender={visible => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
            />
          </FormItemWrapper>
        )

      case "int": {
        return (
          <FormItemWrapper key={id} {...formItemWrapperProps}>
            <InputNumber autoComplete="off" inputMode="numeric" onChange={handleChangeIntInput(id)} />
          </FormItemWrapper>
        )
      }

      case "selection": {
        return (
          <FormItemWrapper key={id} {...formItemWrapperProps}>
            <Select
              allowClear
              mode={type.data.maxOptions > 1 ? "multiple" : undefined}
              onChange={() => forceUpdateTheTarget("select")}
            >
              {type.data.options.map(({ id, displayName }: Option) => {
                return (
                  <Select.Option value={id} key={id}>
                    {displayName}
                  </Select.Option>
                )
              })}
            </Select>
          </FormItemWrapper>
        )
      }
      case "array/string":
        return (
          <FormItemWrapper key={id} {...formItemWrapperProps}>
            <EditableList initialValue={defaultValueToDisplay} />
          </FormItemWrapper>
        )
      case "javascript":
      case "html":
      case "json": {
        return (
          <FormItemWrapper key={id} {...formItemWrapperProps}>
            <CodeEditor
              initialValue={defaultValueToDisplay}
              className={styles.codeEditor}
              extraSuggestions={codeSuggestions}
              language={type?.typeName}
              handleChange={handleJsonChange(id)}
            />
            <span className="z-50">
              {jsDebugger && (
                <>
                  {bigField ? (
                    <Button
                      size="large"
                      className="absolute mr-0 mt-0 top-0 right-0"
                      type="text"
                      onClick={() => handleOpenDebugger(id)}
                      icon={<CodeOutlined />}
                    >
                      Open Debugger
                    </Button>
                  ) : (
                    <Tooltip title="Debug expression">
                      <span className="absolute top-1.5 right-3">
                        <BugIcon onClick={() => handleOpenDebugger(id)} className={styles.bugIcon} />
                      </span>
                    </Tooltip>
                  )}
                </>
              )}
            </span>
          </FormItemWrapper>
        )
      }

      case "boolean":
        return (
          <FormItemWrapper key={id} {...formItemWrapperProps}>
            {bigField ? (
              <SwitchWithLabel
                label={displayName}
                id={id}
                onChange={handleChangeSwitch(id)}
                defaultChecked={!!defaultValueToDisplay}
              />
            ) : (
              <Switch className={"mb-0.5"} onChange={handleChangeSwitch(id)} defaultChecked={!!defaultValueToDisplay} />
            )}
          </FormItemWrapper>
        )

      case "file":
        return (
          <FormItemWrapper key={id} {...formItemWrapperProps}>
            <InputWithUpload onChange={handleChangeTextInput(id)} value={defaultValueToDisplay} />
          </FormItemWrapper>
        )

      case "description":
        return (
          <div key={id} className="ant-row ant-form-item form-field_fixed-label">
            <div className="ant-col ant-col-4 ant-form-item-label">
              <label>{displayName}:</label>
            </div>
            <div className="ant-col ant-col-20 ant-form-item-control pt-1.5">{defaultValue}</div>
          </div>
        )

      case "oauthSecret":
      case "string":
      default: {
        const backendSecretAvailable =
          type?.typeName === "oauthSecret" &&
          (availableOauthBackendSecrets === "all_from_config" ||
            availableOauthBackendSecrets?.some(name => getFieldNameById(id) === name))
        if (backendSecretAvailable) {
          formItemWrapperProps.validationRules = validationRules.filter(value => !value["required"])
        }
        const placeholder = backendSecretAvailable
          ? "Leave this field empty to use a value provided by Jitsu"
          : undefined
        return (
          <FormItemWrapper key={id} {...formItemWrapperProps}>
            <InputWithDebug
              id={id}
              placeholder={placeholder}
              jsDebugger={jsDebugger}
              onButtonClick={() => handleOpenDebugger(id)}
            />
          </FormItemWrapper>
        )
      }
    }
  }

  const handleDebuggerRun = async (field: string, debuggerType: "object" | "string", values: DebuggerFormValues) => {
    let transform = {}
    if (field === "_transform") {
      transform = {
        _transform_enabled: true,
        _transform: values.code,
      }
    }
    const configForm = extraForms && extraForms[0]
    const mappingForm = extraForms && extraForms[1]

    const data = {
      reformat: debuggerType == "string",
      uid: initialValues._uid,
      type: initialValues._type,
      field: field,
      expression: values.code,
      object: JSON.parse(values.object),
      config: makeObjectFromFieldsValues({
        ...initialValues,
        ...configForm?.getFieldsValue(),
        ...mappingForm?.getFieldsValue(),
        ...transform,
      }),
      template_variables: Object.entries((configForm || form).getFieldsValue())
        .filter(v => v[0].startsWith("_formData._"))
        .reduce((accumulator: any, currentValue: [string, unknown]) => {
          set(accumulator, currentValue[0].replace("_formData._", ""), currentValue[1])
          return accumulator
        }, {}),
    }

    return services.backendApiClient.post(`/destinations/evaluate?project_id=${services.activeProject.id}`, data)
  }

  const handleCloseDebugger = id => setDebugModalsStates({ ...debugModalsStates, [id]: false })

  const handleSaveDebugger = (id, value: string) => {
    form.setFieldsValue({ [id]: value })
    handleCloseDebugger(id)
  }

  /**
   * Runs after every re-render caused by `Select` field change
   * to pick up the values of conditionally rendered fields.
   */
  useEffect(() => {
    const isInitialRender = !forceUpdatedTargets["select"]
    if (!isInitialRender) setFormValues?.(form.getFieldsValue())
  }, [forceUpdatedTargets["select"]])

  useEffect(() => {
    /**
     *
     * 1st render:
     * component creates fields, fills them with values,
     * lets the `form` instance to pick them
     *
     */
    let formValues = {}
    const formFields: Parameters<typeof form.setFields>[0] = []
    fieldsParamsList.forEach((param: Parameter) => {
      const initConfig = makeObjectFromFieldsValues(formValues)
      const fieldNeeded = !param.omitFieldRule?.(initConfig)
      const id = param.id

      const constantValue = typeof param.constant === "function" ? param.constant?.(initConfig) : param.constant
      const initialValue = getInitialValue(id, param.defaultValue, constantValue, param.type?.typeName)

      if (fieldNeeded) {
        formValues[id] = initialValue
        formFields.push({
          name: id,
          value: initialValue,
          touched: false,
        })
      }
    })

    form.setFields(formFields)

    /**
     * @reason
     * `formValues` holds correct values for dynamically rendered fields
     * @warning
     * Using `form.getFieldsValue()` instead of `formValues` is not recommended because
     * it needs form to re-render once to pick up values of dynamically rendered fields
     */
    setInitialFormValues?.(formValues)

    /**
     *
     * 2nd render: component removes/adds fields conditionally
     *  depending on the form values
     *
     */
    forceUpdateAll()
  }, [])

  return (
    <>
      {fieldsParamsList.map(
        ({
          id,
          documentation,
          displayName,
          type,
          defaultValue,
          required,
          constant,
          omitFieldRule,
          jsDebugger,
          bigField,
          codeSuggestions,
          validator,
        }: Parameter) => {
          const currentFormValues = form.getFieldsValue() ?? {}
          const defaultFormValues = fieldsParamsList.reduce(
            (result, { id, defaultValue }) => ({
              ...result,
              [id]: defaultValue,
            }),
            {}
          )
          const formItemName = id
          const formValues = {
            ...defaultFormValues,
            ...currentFormValues,
          }
          const parsedFormValues = makeObjectFromFieldsValues(formValues)
          const constantValue = typeof constant === "function" ? constant?.(parsedFormValues) : constant
          const isHidden = constantValue !== undefined
          const isOmitted = omitFieldRule ? omitFieldRule(parsedFormValues) : false

          const validationRules: FormItemProps["rules"] = []
          if (!isHidden) {
            const isRequired = typeof required === "boolean" ? required : required?.(parsedFormValues)
            if (isRequired)
              validationRules.push({
                required: true,
                message: `${displayName} field is required.`,
              })
            if (type?.typeName === "isoUtcDate")
              validationRules.push(isoDateValidator(`${displayName} field is required.`))
          }
          if (validator) {
            validationRules.push({ validator: validator })
          }

          return isOmitted ? null : !isHidden ? (
            <Row key={id} className={cn(isHidden && "hidden")}>
              <Col span={24}>
                {jsDebugger ? (
                  <CodeDebuggerModal
                    visible={debugModalsStates[id]}
                    codeFieldLabelDebugger="Expression"
                    extraSuggestionsDebugger={codeSuggestions}
                    defaultCodeValueDebugger={debugModalsValues[id]}
                    handleCloseDebugger={() => handleCloseDebugger(id)}
                    runDebugger={values => handleDebuggerRun(id, jsDebugger, values)}
                    handleSaveCodeDebugger={value => handleSaveDebugger(id, value)}
                  />
                ) : null}
                {getFieldComponent(
                  type,
                  id,
                  defaultValue,
                  constantValue,
                  jsDebugger,
                  bigField,
                  displayName,
                  codeSuggestions,
                  documentation,
                  validationRules
                )}
              </Col>
            </Row>
          ) : (
            <Form.Item key={formItemName} name={formItemName} hidden={true} initialValue={constantValue} />
          )
        }
      )}
    </>
  )
}
Example #9
Source File: index.tsx    From leek with Apache License 2.0 4 votes vote down vote up
IndexPage = () => {
  const { currentApp, currentEnv } = useApplication();
  const [stats, setStats] = useState<any>({});
  const stats_widgets = StatsWidgets(stats);

  // Metadata
  const metricsService = new MetricsService();
  const [seenWorkers, setSeenWorkers] = useState<
    MetricsContextData["seenWorkers"]
  >([]);
  const [seenTasks, setSeenTasks] = useState<MetricsContextData["seenTasks"]>(
    []
  );
  const [processedEvents, setProcessedEvents] =
    useState<MetricsContextData["processedEvents"]>(0);
  const [processedTasks, setProcessedTasks] =
    useState<MetricsContextData["processedTasks"]>(0);
  const [seenStates, setSeenStates] = useState<
    MetricsContextData["seenStates"]
  >([]);
  const [seenTaskStates, setSeenTaskStates] = useState<
    MetricsContextData["seenStates"]
  >([]);
  const [seenRoutingKeys, setSeenRoutingKeys] = useState<
    MetricsContextData["seenRoutingKeys"]
  >([]);
  const [seenQueues, setSeenQueues] = useState<
    MetricsContextData["seenQueues"]
  >([]);
  const [searchDriftLoading, setSearchDriftLoading] = useState<boolean>(true);
  const [searchDrift, setSearchDrift] = useState<any>(null);

  const [timeFilters, setTimeFilters] = useState<any>({
    timestamp_type: "timestamp",
    interval_type: "past",
    offset: 900000,
  });

  function getSearchDrift() {
    if (!currentApp || !currentEnv) return;
    setSearchDriftLoading(true);
    metricsService
      .getSearchDrift(currentApp, currentEnv)
      .then(handleAPIResponse)
      .then((result: any) => {
        setSearchDrift(result);
      }, handleAPIError)
      .catch(handleAPIError)
      .finally(() => setSearchDriftLoading(false));
  }

  function getMetrics() {
    if (!currentApp) return;
    metricsService
      .getBasicMetrics(currentApp, currentEnv, timeFilters)
      .then(handleAPIResponse)
      .then((result: any) => {
        setProcessedEvents(result.aggregations.processed_events.value);
        const processed = result.aggregations.seen_states.buckets.reduce(
          (result, item) => {
            if (!workerStates.includes(item.key)) {
              return result + item.doc_count;
            }
            return result;
          },
          0
        );
        setProcessedTasks(processed);
        setSeenWorkers(result.aggregations.seen_workers.buckets);
        setSeenTasks(result.aggregations.seen_tasks.buckets);
        setSeenStates(result.aggregations.seen_states.buckets);
        setSeenTaskStates(
          tasksStatesDefaults
            .map(
              (obj) =>
                result.aggregations.seen_states.buckets.find(
                  (o) => o.key === obj.key
                ) || obj
            )
            .filter((item) => !workerStates.includes(item.key))
        );
        setSeenRoutingKeys(result.aggregations.seen_routing_keys.buckets);
        setSeenQueues(result.aggregations.seen_queues.buckets);
      }, handleAPIError)
      .catch(handleAPIError);
  }

  useEffect(() => {
    let adapted = {
      SEEN_TASKS: seenTasks.length,
      SEEN_WORKERS: seenWorkers.length,
      PROCESSED_EVENTS: processedEvents,
      PROCESSED_TASKS: processedTasks,
      TASKS: 0,
      EVENTS: 0,
      // Tasks
      QUEUED: 0,
      RECEIVED: 0,
      STARTED: 0,
      SUCCEEDED: 0,
      FAILED: 0,
      REJECTED: 0,
      REVOKED: 0,
      IGNORED: 0,
      RETRY: 0,
      RECOVERED: 0,
      CRITICAL: 0,
      // Worker
      ONLINE: 0,
      HEARTBEAT: 0,
      OFFLINE: 0,
    };
    seenStates.map((task, _) => (adapted[task.key] = task.doc_count));
    setStats(adapted);
  }, [seenTasks, seenWorkers, seenStates]);

  useEffect(() => {
    getMetrics();
    getSearchDrift();
    return () => {
      clearInterval(metricsInterval);
    };
  }, []);

  useEffect(() => {
    // Stop refreshing metadata
    if (metricsInterval) clearInterval(metricsInterval);
    // If no application specified, return
    if (!currentApp) return;

    // Else, get metrics every 10 seconds
    getMetrics();
    getSearchDrift();
    metricsInterval = setInterval(() => {
      getMetrics();
      getSearchDrift();
    }, 10000);
  }, [currentApp, currentEnv, timeFilters]);

  return (
    <>
      <Helmet>
        <html lang="en" />
        <title>Metrics</title>
        <meta name="description" content="Events metrics" />
        <meta name="keywords" content="celery, tasks" />
      </Helmet>

      <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
        <Statistic
          loading={searchDriftLoading}
          title={
            <Tooltip title="The time of the latest event processed by leek.">
              <span>Latest Event </span>
              <InfoCircleOutlined />
            </Tooltip>
          }
          value={
            searchDrift && searchDrift.latest_event_timestamp
              ? moment(searchDrift.latest_event_timestamp).format(
                  "MMM D HH:mm:ss Z"
                )
              : ""
          }
          valueStyle={{ fontSize: 17.5 }}
          prefix={<FieldTimeOutlined />}
        />

        <Affix
          style={{
            position: "fixed",
            left: "50%",
            transform: "translate(-50%, 0)",
          }}
        >
          <Row>
            <TimeFilter
              timeFilter={timeFilters}
              onTimeFilterChange={setTimeFilters}
            />
          </Row>
        </Affix>

        <Statistic
          loading={searchDriftLoading}
          title={
            <Tooltip title="How many events in the queue waiting to be indexed.">
              <span>Current Drift </span>
              <InfoCircleOutlined />
            </Tooltip>
          }
          value={
            searchDrift && searchDrift.messages_count
              ? searchDrift.messages_count
              : "0"
          }
          valueStyle={{ fontSize: 17.5 }}
          prefix={<EyeInvisibleOutlined />}
        />
      </Row>

      <Row gutter={16} justify="center" align="middle">
        {stats_widgets.map((widget, idx) => (
          <Col
            lg={12}
            md={12}
            sm={12}
            xs={24}
            key={idx}
            style={{ marginBottom: "16px" }}
          >
            <StickerWidget
              number={widget.number}
              text={widget.text}
              icon={widget.icon}
              tooltip={widget.tooltip}
            />
          </Col>
        ))}
      </Row>
    </>
  );
}
Example #10
Source File: Results.tsx    From datart with Apache License 2.0 4 votes vote down vote up
Results = memo(({ height = 0, width = 0 }: ResultsProps) => {
  const { actions } = useViewSlice();
  const dispatch = useDispatch();
  const viewId = useSelector(state =>
    selectCurrentEditingViewAttr(state, { name: 'id' }),
  ) as string;
  const model = useSelector(state =>
    selectCurrentEditingViewAttr(state, { name: 'model' }),
  ) as HierarchyModel;
  const columnPermissions = useSelector(state =>
    selectCurrentEditingViewAttr(state, { name: 'columnPermissions' }),
  ) as ColumnPermission[];
  const stage = useSelector(state =>
    selectCurrentEditingViewAttr(state, { name: 'stage' }),
  ) as ViewViewModelStages;
  const previewResults = useSelector(state =>
    selectCurrentEditingViewAttr(state, { name: 'previewResults' }),
  ) as ViewViewModel['previewResults'];
  const roles = useSelector(selectRoles);
  const t = useI18NPrefix('view');

  const dataSource = useMemo(
    () => previewResults.map(o => ({ ...o, [ROW_KEY]: uuidv4() })),
    [previewResults],
  );

  const modelChange = useCallback(
    (columnName: string, column: Omit<Column, 'name'>) =>
      ({ key }) => {
        let value;
        if (key.includes('category')) {
          const category = key.split('-')[1];
          value = { ...column, category };
        } else {
          value = { ...column, type: key };
        }
        const clonedHierarchyModel = CloneValueDeep(model.hierarchy || {});
        if (columnName in clonedHierarchyModel) {
          clonedHierarchyModel[columnName] = value;
        } else {
          Object.values(clonedHierarchyModel)
            .filter(col => !isEmptyArray(col.children))
            .forEach(col => {
              const targetChildColumnIndex = col.children!.findIndex(
                child => child.name === columnName,
              );
              if (targetChildColumnIndex > -1) {
                col.children![targetChildColumnIndex] = value;
              }
            });
        }

        dispatch(
          actions.changeCurrentEditingView({
            model: {
              ...model,
              hierarchy: clonedHierarchyModel,
              version: APP_CURRENT_VERSION,
            },
          }),
        );
      },
    [dispatch, actions, model],
  );

  const roleDropdownData = useMemo(
    () =>
      roles.map(({ id, name }) => ({
        key: id,
        title: name,
        value: id,
        isLeaf: true,
      })),
    [roles],
  );

  const checkRoleColumnPermission = useCallback(
    columnName => checkedKeys => {
      const fullPermissions = Object.keys(model?.columns || {});
      dispatch(
        actions.changeCurrentEditingView({
          columnPermissions: roleDropdownData.reduce<ColumnPermission[]>(
            (updated, { key }) => {
              const permission = columnPermissions.find(
                ({ subjectId }) => subjectId === key,
              );
              const checkOnCurrentRole = checkedKeys.includes(key);
              if (permission) {
                if (checkOnCurrentRole) {
                  const updatedColumnPermission = Array.from(
                    new Set(permission.columnPermission.concat(columnName)),
                  );
                  return fullPermissions.sort().join(',') !==
                    updatedColumnPermission.sort().join(',')
                    ? updated.concat({
                        ...permission,
                        columnPermission: updatedColumnPermission,
                      })
                    : updated;
                } else {
                  return updated.concat({
                    ...permission,
                    columnPermission: permission.columnPermission.filter(
                      c => c !== columnName,
                    ),
                  });
                }
              } else {
                return !checkOnCurrentRole
                  ? updated.concat({
                      id: uuidv4(),
                      viewId,
                      subjectId: key,
                      subjectType: SubjectTypes.Role,
                      columnPermission: fullPermissions.filter(
                        c => c !== columnName,
                      ),
                    })
                  : updated;
              }
            },
            [],
          ),
        }),
      );
    },
    [dispatch, actions, viewId, model, columnPermissions, roleDropdownData],
  );

  const getExtraHeaderActions = useCallback(
    (name: string, column: Omit<Column, 'name'>) => {
      // 没有记录相当于对所有字段都有权限
      const checkedKeys =
        columnPermissions.length > 0
          ? roleDropdownData.reduce<string[]>((selected, { key }) => {
              const permission = columnPermissions.find(
                ({ subjectId }) => subjectId === key,
              );
              if (permission) {
                return permission.columnPermission.includes(name)
                  ? selected.concat(key)
                  : selected;
              } else {
                return selected.concat(key);
              }
            }, [])
          : roleDropdownData.map(({ key }) => key);
      return [
        <Popup
          key={`${name}_columnpermission`}
          trigger={['click']}
          placement="bottomRight"
          content={
            <Tree
              className="dropdown"
              treeData={roleDropdownData}
              checkedKeys={checkedKeys}
              loading={false}
              selectable={false}
              onCheck={checkRoleColumnPermission(name)}
              blockNode
              checkable
            />
          }
        >
          <Tooltip title={t('columnPermission.title')}>
            <ToolbarButton
              size="small"
              iconSize={FONT_SIZE_BASE}
              icon={
                checkedKeys.length > 0 ? (
                  <EyeOutlined
                    className={classnames({
                      partial: checkedKeys.length !== roleDropdownData.length,
                    })}
                  />
                ) : (
                  <EyeInvisibleOutlined />
                )
              }
            />
          </Tooltip>
        </Popup>,
      ];
    },
    [columnPermissions, roleDropdownData, checkRoleColumnPermission, t],
  );

  const pagination = useMemo(
    () => ({
      defaultPageSize: 100,
      pageSizeOptions: ['100', '200', '500', '1000'],
    }),
    [],
  );

  return stage > ViewViewModelStages.Fresh ? (
    <TableWrapper>
      <SchemaTable
        height={height ? height - 96 : 0}
        width={width}
        model={model.columns || {}}
        hierarchy={model.hierarchy || {}}
        dataSource={dataSource}
        pagination={pagination}
        getExtraHeaderActions={getExtraHeaderActions}
        onSchemaTypeChange={modelChange}
        hasCategory
      />
    </TableWrapper>
  ) : (
    <InitialDesc>
      <p>
        {t('resultEmpty1')}
        <CaretRightOutlined />
        {t('resultEmpty2')}
      </p>
    </InitialDesc>
  );
})