All files / modules/75-cf/pages/feature-flags FeatureFlagsPage.tsx

77.65% Statements 132/170
60.37% Branches 131/217
69.7% Functions 23/33
77.98% Lines 131/168

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655              3x 3x 3x                       3x 3x 3x     3x 3x 3x                 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                   3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                     3x               108x 108x 108x 108x 108x 108x 108x 108x   108x   108x   108x                     108x                                                                     108x 3x                     108x                                                                                     108x 54x 54x       108x 54x 54x   54x 53x       108x   108x           108x   108x 108x       108x   108x 2x   106x       108x                                                                                                                                                         3x 52x 52x 52x 52x   52x   52x 52x   52x                                                                                 3x 52x 52x 52x           52x   52x                           3x 13x 12x 12x 12x 12x 12x 6x                                 12x                   12x     4x 4x             12x             12x   12x 12x 12x   12x 6x     12x 6x     12x 6x       12x   12x   12x   12x 12x     52x     52x                                                 52x                 52x                   52x     53x               52x                             12x               12x 12x 12x 12x   12x                                                                                                                   1x                                                   3x  
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useEffect, useMemo, useRef, useState, useCallback, ReactElement } from 'react'
import { useHistory, useParams } from 'react-router-dom'
import {
  Button,
  Container,
  ExpandingSearchInput,
  Heading,
  Layout,
  Pagination,
  Text,
  Utils,
  TableV2,
  Popover
} from '@wings-software/uicore'
import { noop } from 'lodash-es'
import { Classes, Position, Switch, PopoverInteractionKind } from '@blueprintjs/core'
import { Color } from '@harness/design-system'
import type { Cell, CellProps, Column, Renderer } from 'react-table'
import type { MutateMethod } from 'restful-react'
import routes from '@common/RouteDefinitions'
import { useToaster } from '@common/exports'
import {
  DeleteFeatureFlagQueryParams,
  Feature,
  Features,
  FeatureState,
  GitSyncErrorResponse,
  useDeleteFeatureFlag,
  useGetAllFeatures
} from 'services/cf'
import { useStrings, String } from 'framework/strings'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import RBACTooltip from '@rbac/components/RBACTooltip/RBACTooltip'
import { usePermission } from '@rbac/hooks/usePermission'
import { UseToggleFeatureFlag, useToggleFeatureFlag } from '@cf/hooks/useToggleFeatureFlag'
import { VariationTypeIcon } from '@cf/components/VariationTypeIcon/VariationTypeIcon'
import { VariationWithIcon } from '@cf/components/VariationWithIcon/VariationWithIcon'
import ListingPageTemplate from '@cf/components/ListingPageTemplate/ListingPageTemplate'
import { NoData } from '@cf/components/NoData/NoData'
import { useEnvironmentSelectV2 } from '@cf/hooks/useEnvironmentSelectV2'
import { CFEnvironmentSelect } from '@cf/components/CFEnvironmentSelect/CFEnvironmentSelect'
import useActiveEnvironment from '@cf/hooks/useActiveEnvironment'
import {
  CF_DEFAULT_PAGE_SIZE,
  FeatureFlagActivationStatus,
  featureFlagHasCustomRules,
  getDefaultVariation,
  getErrorMessage,
  isFeatureFlagOn,
  rewriteCurrentLocationWithActiveEnvironment,
  useFeatureFlagTypeToStringMapping
} from '@cf/utils/CFUtils'
import { FlagTypeVariations } from '@cf/components/CreateFlagDialog/FlagDialogUtils'
import FlagDialog from '@cf/components/CreateFlagDialog/FlagDialog'
 
import SaveFlagToGitModal from '@cf/components/SaveFlagToGitModal/SaveFlagToGitModal'
import { AUTO_COMMIT_MESSAGES } from '@cf/constants/GitSyncConstants'
import GitSyncActions from '@cf/components/GitSyncActions/GitSyncActions'
import { GitDetails, GitSyncFormValues, GIT_SYNC_ERROR_CODE, useGitSync, UseGitSync } from '@cf/hooks/useGitSync'
import { useGovernance, UseGovernancePayload } from '@cf/hooks/useGovernance'
import usePlanEnforcement from '@cf/hooks/usePlanEnforcement'
import FlagOptionsMenuButton from '@cf/components/FlagOptionsMenuButton/FlagOptionsMenuButton'
import { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import { useFeature } from '@common/hooks/useFeatures'
import { FeatureWarningTooltip } from '@common/components/FeatureWarning/FeatureWarningWithTooltip'
import imageURL from '@cf/images/Feature_Flags_Teepee.svg'
import { FeatureFlagStatus, FlagStatus } from './FlagStatus'
import { FlagResult } from './FlagResult'
import css from './FeatureFlagsPage.module.scss'
 
export interface RenderColumnFlagProps {
  numberOfEnvs?: number
  gitSync: UseGitSync
  cell: Cell<Feature>
  toggleFeatureFlag: UseToggleFeatureFlag
  governance: UseGovernancePayload
  update: (status: boolean) => void
}
 
export const RenderColumnFlag: React.FC<RenderColumnFlagProps> = ({
  numberOfEnvs,
  gitSync,
  toggleFeatureFlag,
  governance,
  cell: { row },
  update
}) => {
  const data = row.original
  const [status, setStatus] = useState(isFeatureFlagOn(data))
  const { getString } = useStrings()
  const { showError } = useToaster()
  const [flagNameTextSize, setFlagNameTextSize] = useState(300)
  const ref = useRef<HTMLDivElement>(null)
  const { activeEnvironment } = useActiveEnvironment()
  const { handleError: handleGovernanceError, isGovernanceError } = governance
 
  const [isSaveToggleModalOpen, setIsSaveToggleModalOpen] = useState(false)
 
  const { gitSyncInitialValues } = gitSync.getGitSyncFormMeta(AUTO_COMMIT_MESSAGES.TOGGLED_FLAG)
 
  const [canToggle] = usePermission(
    {
      resource: {
        resourceType: ResourceType.ENVIRONMENT,
        resourceIdentifier: activeEnvironment
      },
      permissions: [PermissionIdentifier.TOGGLE_FF_FEATUREFLAG]
    },
    [activeEnvironment]
  )
 
  const handleFlagToggle = async (gitSyncFormValues?: GitSyncFormValues): Promise<void> => {
    let gitDetails: GitDetails | undefined
 
    if (gitSync.isAutoCommitEnabled) {
      gitDetails = gitSyncInitialValues.gitDetails
    } else if (gitSyncFormValues) {
      gitDetails = gitSyncFormValues.gitDetails
    }
 
    try {
      if (status) {
        await toggleFeatureFlag.off(data.identifier, gitDetails)
      } else {
        await toggleFeatureFlag.on(data.identifier, gitDetails)
      }
 
      if (gitSyncFormValues?.autoCommit) {
        gitSync.handleAutoCommit(gitSyncFormValues.autoCommit)
      }
 
      setStatus(!status)
      update(!status)
    } catch (error: any) {
      if (error.status === GIT_SYNC_ERROR_CODE) {
        gitSync.handleError(error.data as GitSyncErrorResponse)
      } else {
        if (isGovernanceError(error)) {
          handleGovernanceError(error.data)
        } else {
          showError(getErrorMessage(error), 0, 'cf.toggle.ff.status.error')
        }
      }
    }
  }
 
  const NoEnvironmentWarningTooltip = (): ReactElement => (
    <Popover interactionKind={PopoverInteractionKind.HOVER} popoverClassName={Classes.DARK}>
      <Layout.Vertical padding="medium" className={css.tooltip}>
        <Text font={{ weight: 'bold' }} color={Color.WHITE} padding={{ bottom: 'large' }}>
          {getString('cf.noEnvironment.title')}
        </Text>
        <Text color={Color.GREY_200}>{getString('cf.noEnvironment.message')}</Text>
      </Layout.Vertical>
    </Popover>
  )
 
  const switchTooltip = (
    <Container width={'350px'} padding="xxxlarge" className={css.switchTooltip}>
      <Heading level={2} style={{ fontWeight: 600, fontSize: '24px', lineHeight: '32px', color: '#22222A' }}>
        {getString(status ? 'cf.featureFlags.turnOffHeading' : 'cf.featureFlags.turnOnHeading')}
      </Heading>
      <Text margin={{ top: 'medium', bottom: 'small' }} style={{ lineHeight: '22px', color: '#383946' }}>
        <String
          stringID={status ? 'cf.featureFlags.turnOffMessage' : 'cf.featureFlags.turnOnMessage'}
          vars={{ name: data.name, env: activeEnvironment || '' }}
          useRichText
        />
      </Text>
      <Text margin={{ top: 'xsmall', bottom: 'xlarge' }} style={{ lineHeight: '22px', color: '#383946' }}>
        {(!featureFlagHasCustomRules(data) && (
          <String
            stringID={'cf.featureFlags.defaultWillBeServed'}
            useRichText
            vars={{ defaultVariation: status ? data.defaultOffVariation : data.defaultOnVariation }}
          />
        )) ||
          getString('cf.featureFlags.customRuleMessage')}
      </Text>
      <Container flex>
        <Layout.Horizontal spacing="small">
          <Button
            intent="primary"
            text={getString('confirm')}
            className={Classes.POPOVER_DISMISS}
            disabled={toggleFeatureFlag.loading}
            onClick={() => {
              if (gitSync.isGitSyncEnabled && !gitSync.isAutoCommitEnabled) {
                setIsSaveToggleModalOpen(true)
              } else {
                handleFlagToggle()
              }
            }}
          />
          <Button text={getString('cancel')} className={Classes.POPOVER_DISMISS} disabled={toggleFeatureFlag.loading} />
        </Layout.Horizontal>
        <span />
      </Container>
    </Container>
  )
 
  const onResize = (): void => {
    Eif (ref.current) {
      setFlagNameTextSize((ref.current.closest('div[role="cell"]') as HTMLDivElement)?.offsetWidth - 100)
    }
  }
 
  useEffect(() => {
    onResize()
    window.addEventListener('resize', onResize)
 
    return () => {
      window.removeEventListener('resize', onResize)
    }
  }, [])
 
  const { isPlanEnforcementEnabled, isFreePlan } = usePlanEnforcement()
 
  const { enabled } = useFeature({
    featureRequest: {
      featureName: FeatureIdentifier.MAUS
    }
  })
 
  const switchDisabled = isPlanEnforcementEnabled && !enabled && isFreePlan
 
  const getTooltip = (): ReactElement | undefined => {
    Iif (!canToggle) {
      return (
        <RBACTooltip permission={PermissionIdentifier.TOGGLE_FF_FEATUREFLAG} resourceType={ResourceType.ENVIRONMENT} />
      )
    } else Iif (switchDisabled) {
      return <FeatureWarningTooltip featureName={FeatureIdentifier.MAUS} />
    } else if (!numberOfEnvs) {
      return <NoEnvironmentWarningTooltip />
    } else {
      return switchTooltip
    }
  }
 
  return (
    <Container flex>
      <Container onClick={Utils.stopEvent}>
        <Button
          noStyling
          tooltip={getTooltip()}
          tooltipProps={{
            interactionKind:
              switchDisabled || !numberOfEnvs ? PopoverInteractionKind.HOVER : PopoverInteractionKind.CLICK,
            hasBackdrop: switchDisabled || !numberOfEnvs ? false : true,
            position: switchDisabled || !numberOfEnvs ? Position.BOTTOM_LEFT : Position.TOP_LEFT
          }}
          className={css.toggleFlagButton}
          disabled={data.archived || !canToggle || switchDisabled || !numberOfEnvs}
        >
          <Switch
            style={{ alignSelf: 'baseline', marginLeft: '-10px' }}
            alignIndicator="right"
            className={Classes.LARGE}
            checked={status}
            onChange={noop}
            disabled={data.archived || !canToggle || !numberOfEnvs}
          />
        </Button>
      </Container>
      <Layout.Horizontal spacing="small" style={{ flexGrow: 1, paddingLeft: 'var(--spacing-medium)' }}>
        <Layout.Vertical flex className={css.generalInfo} ref={ref}>
          <Text
            style={{
              color: '#22222A',
              fontWeight: 500,
              fontSize: '13px',
              lineHeight: '16px'
            }}
            margin={{ right: 'xsmall' }}
            width={flagNameTextSize}
            lineClamp={2}
          >
            {data.name}
            {data.archived && (
              <Text inline color={Color.GREY_400} padding={{ left: 'xsmall' }} font={{ size: 'small' }}>
                ({getString('cf.shared.archived')})
              </Text>
            )}
          </Text>
          {data.description && (
            <Text
              style={{
                color: '#22222A',
                fontSize: '12px',
                lineHeight: '24px'
              }}
              width={flagNameTextSize}
              lineClamp={1}
            >
              {data.description}
            </Text>
          )}
        </Layout.Vertical>
      </Layout.Horizontal>
 
      <Container onClick={event => event.stopPropagation()}>
        {isSaveToggleModalOpen && (
          <SaveFlagToGitModal
            flagName={data.name}
            flagIdentifier={data.identifier}
            onSubmit={handleFlagToggle}
            onClose={() => {
              setIsSaveToggleModalOpen(false)
            }}
          />
        )}
      </Container>
    </Container>
  )
}
 
const RenderColumnDetails: Renderer<CellProps<Feature>> = ({ row }) => {
  const data = row.original
  const { getString } = useStrings()
  const isOn = isFeatureFlagOn(data)
  const hasCustomRules = featureFlagHasCustomRules(data)
 
  const defaultVariation = getDefaultVariation(data)
 
  const isFlagTypeBoolean = data.kind === FlagTypeVariations.booleanFlag
  const typeToString = useFeatureFlagTypeToStringMapping()
 
  return (
    <Layout.Vertical>
      <Layout.Horizontal>
        <Text>
          <VariationTypeIcon multivariate={data.kind !== FlagTypeVariations.booleanFlag} />
          {getString(isFlagTypeBoolean ? 'cf.boolean' : 'cf.multivariate')}
          {!isFlagTypeBoolean && (
            <Text inline color={Color.GREY_400} padding={{ left: 'xsmall' }}>
              ({typeToString[data.kind] || ''})
            </Text>
          )}
        </Text>
      </Layout.Horizontal>
      {!hasCustomRules && (
        <Container style={{ display: 'flex', alignItems: 'center' }}>
          <VariationWithIcon
            variation={defaultVariation}
            index={data.variations.indexOf(defaultVariation)}
            textStyle={{
              fontSize: '12px',
              lineHeight: '24px',
              color: '#9293AB',
              paddingLeft: 'var(--spacing-xsmall)'
            }}
            textElement={getString(isOn ? 'cf.featureFlags.defaultServedOn' : 'cf.featureFlags.defaultServedOff', {
              defaultVariation: defaultVariation.name || defaultVariation.value
            })}
          />
        </Container>
      )}
    </Layout.Vertical>
  )
}
 
interface ColumnMenuProps {
  cell: Cell<Feature>
  environment?: string
  gitSync: UseGitSync
  deleteFlag: MutateMethod<void, string, DeleteFeatureFlagQueryParams, void>
}
 
const RenderColumnEdit: React.FC<ColumnMenuProps> = ({ gitSync, deleteFlag, cell: { row, column }, environment }) => {
  const data = row.original
  const { projectIdentifier, orgIdentifier, accountId: accountIdentifier } = useParams<Record<string, string>>()
  const queryParams = {
    projectIdentifier,
    accountIdentifier,
    orgIdentifier
  } as DeleteFeatureFlagQueryParams
 
  const refetch = (column as unknown as { refetch: () => void }).refetch
 
  return (
    <Container style={{ textAlign: 'right' }} onClick={Utils.stopEvent}>
      <FlagOptionsMenuButton
        environment={environment}
        flagData={data}
        queryParams={queryParams}
        deleteFlag={deleteFlag}
        gitSync={gitSync}
        refetchFlags={refetch}
      />
    </Container>
  )
}
 
const FeatureFlagsPage: React.FC = () => {
  const { projectIdentifier, orgIdentifier, accountId: accountIdentifier } = useParams<Record<string, string>>()
  const history = useHistory()
  const { activeEnvironment: environmentIdentifier, withActiveEnvironment } = useActiveEnvironment()
  const [pageNumber, setPageNumber] = useState(0)
  const [searchTerm, setSearchTerm] = useState('')
  const queryParams = useMemo(
    () => ({
      projectIdentifier,
      environmentIdentifier,
      accountIdentifier,
      orgIdentifier,
      pageSize: CF_DEFAULT_PAGE_SIZE,
      pageNumber,
      metrics: true,
      name: searchTerm
    }),
    [projectIdentifier, environmentIdentifier, accountIdentifier, orgIdentifier, pageNumber, searchTerm] // eslint-disable-line react-hooks/exhaustive-deps
  )
  const {
    data,
    loading: flagsLoading,
    error: flagsError,
    refetch
  } = useGetAllFeatures({
    lazy: true,
    queryParams
  })
  const {
    EnvironmentSelect,
    loading: envsLoading,
    error: envsError,
    refetch: refetchEnvironments,
    environments
  } = useEnvironmentSelectV2({
    selectedEnvironmentIdentifier: environmentIdentifier,
    onChange: (_value, _environment, _userEvent) => {
      rewriteCurrentLocationWithActiveEnvironment(_environment)
      refetch({ queryParams: { ...queryParams, environmentIdentifier: _environment.identifier as string } })
    },
    onEmpty: () => {
      refetch({ queryParams: { ...queryParams, environmentIdentifier: undefined as unknown as string } })
    }
  })
 
  const toggleFeatureFlag = useToggleFeatureFlag({
    accountIdentifier,
    orgIdentifier,
    projectIdentifier,
    environmentIdentifier
  })
 
  const deleteFlag = useDeleteFeatureFlag({ queryParams })
 
  const [features, setFeatures] = useState<Features | null>()
  const { getString } = useStrings()
  const [loading, setLoading] = useState(true)
 
  useEffect(() => {
    setFeatures(data)
  }, [data])
 
  useEffect(() => {
    setLoading(flagsLoading || envsLoading)
  }, [flagsLoading, envsLoading])
 
  const gitSyncing = useMemo<boolean>(
    () => toggleFeatureFlag.loading || deleteFlag.loading,
    [toggleFeatureFlag.loading, deleteFlag.loading]
  )
 
  const gitSync = useGitSync()
 
  const governance = useGovernance()
 
  const error = flagsError || envsError || deleteFlag.error || (toggleFeatureFlag.error && !governance.governanceError)
 
  const columns: Column<Feature>[] = useMemo(
    () => [
      {
        Header: getString('featureFlagsText').toUpperCase(),
        accessor: row => row.name,
        width: '40%',
        Cell: function WrapperRenderColumnFlag(cell: Cell<Feature>) {
          return (
            <RenderColumnFlag
              numberOfEnvs={environments?.length}
              gitSync={gitSync}
              toggleFeatureFlag={toggleFeatureFlag}
              governance={governance}
              cell={cell}
              update={status => {
                const feature = features?.features?.find(f => f.identifier === cell.row.original.identifier)
                if (feature) {
                  if (feature.envProperties) {
                    feature.envProperties.state = (
                      status ? FeatureFlagActivationStatus.ON : FeatureFlagActivationStatus.OFF
                    ) as FeatureState
                  }
                  feature.modifiedAt = Date.now()
                  setFeatures({ ...features } as Features)
                }
              }}
            />
          )
        }
      },
      {
        Header: getString('details').toUpperCase(),
        accessor: row => row.kind,
        width: '22%',
        Cell: RenderColumnDetails
      },
      {
        Header: getString('status').toUpperCase(),
        accessor: 'status',
        width: '21%',
        Cell: function StatusCell(cell: Cell<Feature>) {
          return (
            <FlagStatus
              status={cell.row.original.status?.status as FeatureFlagStatus}
              lastAccess={cell.row.original.status?.lastAccess as unknown as number}
            />
          )
        }
      },
      {
        Header: getString('cf.featureFlags.results').toUpperCase(),
        accessor: row => row.results,
        width: '12%',
        Cell: function ResultCell(cell: Cell<Feature>) {
          return <FlagResult feature={cell.row.original} />
        }
      },
      {
        Header: '',
        id: 'version',
        width: '5%',
        Cell: function WrapperRenderColumnEdit(cell: Cell<Feature>) {
          return (
            <RenderColumnEdit
              gitSync={gitSync}
              deleteFlag={deleteFlag.mutate}
              cell={cell}
              environment={cell.row.original.envProperties?.environment as string}
            />
          )
        },
        disableSortBy: true,
        refetch
      }
    ],
    [gitSync.isAutoCommitEnabled, gitSync.isGitSyncEnabled, features]
  )
  const onSearchInputChanged = useCallback(
    name => {
      setSearchTerm(name)
      refetch({ queryParams: { ...queryParams, name } })
    },
    [setSearchTerm, refetch, queryParams]
  )
 
  const hasFeatureFlags = features?.features && features?.features?.length > 0
  const emptyFeatureFlags = !loading && features?.features?.length === 0
  const title = getString('featureFlagsText')
  const displayToolbar = hasFeatureFlags || searchTerm
 
  return (
    <ListingPageTemplate
      title={title}
      titleTooltipId="ff_ffListing_heading"
      headerContent={!!environments?.length && <CFEnvironmentSelect component={<EnvironmentSelect />} />}
      toolbar={
        displayToolbar && (
          <>
            <div className={css.leftToolbar}>
              <FlagDialog environment={environmentIdentifier} />
              {gitSync?.isGitSyncActionsEnabled && (
                <GitSyncActions
                  isLoading={gitSync.gitSyncLoading || gitSyncing}
                  branch={gitSync.gitRepoDetails?.branch || ''}
                  repository={gitSync.gitRepoDetails?.repoIdentifier || ''}
                  isAutoCommitEnabled={gitSync.isAutoCommitEnabled}
                  isGitSyncPaused={gitSync.isGitSyncPaused}
                  handleToggleAutoCommit={gitSync.handleAutoCommit}
                  handleGitPause={gitSync.handleGitPause}
                />
              )}
            </div>
            <ExpandingSearchInput
              alwaysExpanded
              name="findFlag"
              placeholder={getString('search')}
              onChange={onSearchInputChanged}
            />
          </>
        )
      }
      pagination={
        !!features?.features?.length && (
          <Pagination
            itemCount={features?.itemCount || 0}
            pageSize={features?.pageSize || 0}
            pageCount={features?.pageCount || 0}
            pageIndex={pageNumber}
            gotoPage={index => {
              setPageNumber(index)
              refetch({ queryParams: { ...queryParams, pageNumber: index } })
            }}
          />
        )
      }
      loading={loading}
      error={error}
      retryOnError={() => {
        setPageNumber(0)
        refetchEnvironments()
      }}
    >
      {hasFeatureFlags && (
        <Container padding={{ top: 'medium', right: 'xlarge', left: 'xlarge' }}>
          <TableV2<Feature>
            columns={columns}
            data={features?.features || []}
            onRowClick={feature => {
              history.push(
                withActiveEnvironment(
                  routes.toCFFeatureFlagsDetail({
                    orgIdentifier: orgIdentifier as string,
                    projectIdentifier: projectIdentifier as string,
                    featureFlagIdentifier: feature.identifier,
                    accountId: accountIdentifier
                  })
                )
              )
            }}
          />
        </Container>
      )}
 
      {!loading && emptyFeatureFlags && (
        <Container width="100%" height="100%" flex={{ align: 'center-center' }}>
          <NoData imageURL={imageURL} message={getString(searchTerm ? 'cf.noResultMatch' : 'cf.noFlag')}>
            <FlagDialog environment={environmentIdentifier} />
          </NoData>
        </Container>
      )}
    </ListingPageTemplate>
  )
}
 
export default FeatureFlagsPage