Skip to content
Merged
15 changes: 15 additions & 0 deletions frontend/common/hooks/useSortedProjectEnvironments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { skipToken } from '@reduxjs/toolkit/query'
import { useGetAllEnvironmentsQuery } from 'common/services/useEnvironment'
import { sortEnvironmentsByName } from 'common/utils/sortEnvironmentsByName'

export const useSortedProjectEnvironments = (projectId: number | undefined) => {
// currentData: data would keep the previous project's list while the next loads
const { currentData, isError, isFetching, refetch } =
useGetAllEnvironmentsQuery(projectId ? { projectId } : skipToken)
return {
environments: currentData && sortEnvironmentsByName(currentData),
isError,
isLoading: isFetching && !currentData,
refetch,
}
}
34 changes: 7 additions & 27 deletions frontend/common/stores/organisation-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import Dispatcher from 'common/dispatcher/dispatcher'
import BaseStore from './base/_store'
import data from 'common/data/base/_data'
import filter from 'lodash/filter'
import find from 'lodash/find'
import findIndex from 'lodash/findIndex'
import keyBy from 'lodash/keyBy'

Expand Down Expand Up @@ -75,10 +74,7 @@ const controller = {
const idInt = parseInt(id)
store.saving()
if (store.model) {
store.model.projects = filter(
store.model.projects,
(p) => p.id !== idInt,
)
store.model.projects = filter(store.model.projects, (p) => p.id !== idInt)
store.model.keyedProjects = keyBy(store.model.projects, 'id')
}
API.trackEvent(Constants.events.REMOVE_PROJECT)
Expand Down Expand Up @@ -140,7 +136,9 @@ const controller = {
if (`${id}` === `${store.id}`) {
// eslint-disable-next-line prefer-const
let [_projects, users, invites, subscriptionMeta] = res
let projects = sortBy(_projects, 'name')
let projects = sortBy(_projects, (project) =>
project.name.toLowerCase(),
)

store.model = {
...store.model,
Expand Down Expand Up @@ -196,27 +194,9 @@ const controller = {
})
}

return Promise.all(
projects.map((project, i) =>
data
.get(`${Project.api}environments/?project=${project.id}`)
.then((res) => {
projects[i].environments = sortBy(res.results, 'name')
})
.catch(() => {
projects[i].environments = []
}),
),
).then(() => {
projects.sort((a, b) => {
const textA = a.name.toLowerCase()
const textB = b.name.toLowerCase()
return textA < textB ? -1 : textA > textB ? 1 : 0
})
store.model.projects = projects
store.model.keyedProjects = keyBy(store.model.projects, 'id')
store.loaded()
})
store.model.projects = projects
store.model.keyedProjects = keyBy(store.model.projects, 'id')
store.loaded()
}
})
}
Expand Down
19 changes: 19 additions & 0 deletions frontend/common/utils/__tests__/environmentFixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { Environment } from 'common/types/responses'

export const makeEnvironment = (id: number, name: string): Environment => ({
allow_client_traits: true,
api_key: `key-${id}`,
hide_disabled_flags: null,
hide_sensitive_data: false,
id,
is_creating: false,
metadata: [],
minimum_change_request_approvals: null,
name,
project: 1,
show_disabled_flags: false,
use_identity_composite_key_for_hashing: false,
use_identity_overrides_in_local_eval: false,
use_mv_v2_evaluation: false,
use_v2_feature_versioning: false,
})
19 changes: 19 additions & 0 deletions frontend/common/utils/__tests__/projectLandingPath.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { getProjectLandingPath } from 'common/utils/projectLandingPath'
import { makeEnvironment } from './environmentFixture'

describe('getProjectLandingPath', () => {
it('opens the features of the first environment', () => {
const environments = [
makeEnvironment(2, 'Development'),
makeEnvironment(1, 'Production'),
]

expect(getProjectLandingPath(7, environments)).toBe(
'/project/7/environment/key-2/features',
)
})

it('opens create environment when the project has none', () => {
expect(getProjectLandingPath(7, [])).toBe('/project/7/environment/create')
})
})
37 changes: 37 additions & 0 deletions frontend/common/utils/__tests__/sortEnvironmentsByName.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { sortEnvironmentsByName } from 'common/utils/sortEnvironmentsByName'
import { makeEnvironment } from './environmentFixture'

const names = (environments: { name: string }[]) =>
environments.map((env) => env.name)

describe('sortEnvironmentsByName', () => {
it('orders environments by name rather than by id', () => {
const environments = [
makeEnvironment(1, 'Production'),
makeEnvironment(2, 'Development'),
makeEnvironment(3, 'Staging'),
]

expect(names(sortEnvironmentsByName(environments))).toEqual([
'Development',
'Production',
'Staging',
])
})

it('puts capitalised names before lowercase ones, as the UI always has', () => {
const environments = [
makeEnvironment(1, 'test'),
makeEnvironment(2, 'Production'),
makeEnvironment(3, 'new env'),
makeEnvironment(4, 'Development'),
]

expect(names(sortEnvironmentsByName(environments))).toEqual([
'Development',
'Production',
'new env',
'test',
])
})
})
11 changes: 11 additions & 0 deletions frontend/common/utils/projectLandingPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Environment } from 'common/types/responses'

export function getProjectLandingPath(
projectId: number,
environmentsByName: Environment[],
): string {
const environment = environmentsByName[0]
return environment
? `/project/${projectId}/environment/${environment.api_key}/features`
: `/project/${projectId}/environment/create`
}
9 changes: 9 additions & 0 deletions frontend/common/utils/sortEnvironmentsByName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import sortBy from 'lodash/sortBy'
import type { Environment } from 'common/types/responses'

// The API orders environments by id
export function sortEnvironmentsByName(
environments: Environment[],
): Environment[] {
return sortBy(environments, 'name')
}
24 changes: 23 additions & 1 deletion frontend/documentation/components/EmptyState.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,18 @@ const meta: Meta<EmptyStateProps> = {
iconColour: {
control: 'color',
description:
'Icon fill colour. Defaults to a neutral grey when not provided.',
'Icon fill colour. Defaults to the secondary icon colour, or the danger colour for `status="error"`.',
},
onRetry: {
control: false,
description:
'Renders a Try again button, with "Try again in a few moments." as the description unless one is given.',
},
status: {
control: 'inline-radio',
description:
'`error` is for content that failed to load: it defaults to a warning icon in the danger colour and is announced to screen readers. Pair it with a retry action.',
options: ['empty', 'error'],
},
title: {
control: 'text',
Expand Down Expand Up @@ -93,3 +104,14 @@ export const WithDocsLink: Story = {
title: 'No projects yet',
},
}

export const LoadError: Story = {
args: {
description: undefined,
// Clears the shared icon so the error status shows its warning icon
icon: undefined,
onRetry: () => undefined,
status: 'error',
title: 'Could not load projects',
},
}
4 changes: 2 additions & 2 deletions frontend/e2e/helpers/e2e-helpers.playwright.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@ export class E2EHelpers {
const projectLink = this.page.locator('a').filter({ has: this.page.locator(`text="${projectName}"`) }).first();
await projectLink.waitFor({ state: 'visible', timeout: LONG_TIMEOUT });
await projectLink.click();
// Wait for project page to load - could be features page or create environment page
await this.page.waitForURL(/\/project\/\d+/, { timeout: LONG_TIMEOUT });
// Cards go to /project/:id, which redirects to an environment page
await this.page.waitForURL(/\/project\/\d+\/environment\//, { timeout: LONG_TIMEOUT });
await this.waitForPageFullyLoaded();
}

Expand Down
59 changes: 59 additions & 0 deletions frontend/e2e/tests/user-permissions-test.pw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { test, expect } from '../test-setup'
import { createHelpers, log } from '../helpers'
import {
E2E_NON_ADMIN_USER_WITH_ENV_PERMISSIONS,
E2E_USER,
PASSWORD,
} from '../config'

// Seeded projects: the first has Development and Production, the second only Development
const PROJECT_WITH_TWO_ENVIRONMENTS = 'My Test Project'
const PROJECT_WITH_ONE_ENVIRONMENT = 'My Test Project 2'

const MEMBER_ACTIONS = ['Manage user', 'Inspect permissions']

test.describe('User permissions dialogs', () => {
for (const action of MEMBER_ACTIONS) {
test(`${action} lists only the picked project's environments @enterprise`, async ({
page,
}) => {
const { login } = createHelpers(page)

log(`Open ${action} for a member`)
await login(E2E_USER, PASSWORD)
await page.getByRole('link', { name: 'Users and Permissions' }).click()
await page
.getByRole('button', {
name: `More actions for ${E2E_NON_ADMIN_USER_WITH_ENV_PERMISSIONS}`,
})
.click()
// The menu items aren't buttons yet
await page.getByText(action, { exact: true }).click()
const dialog = page.getByRole('dialog')
await dialog
.getByRole('button', { exact: true, name: 'Environment' })
.click()

// E2E builds render Select's options as plain, always visible links
const pickProject = async (name: string) => {
// Inactive tabs stay in the page, so the Project tab also lists the name
await dialog
.getByText(name, { exact: true })
.filter({ visible: true })
.click()
}

log('A project lists its environments')
await pickProject(PROJECT_WITH_ONE_ENVIRONMENT)
await expect(
dialog.getByText('Development', { exact: true }),
Comment thread
talissoncosta marked this conversation as resolved.
Resolved
).toBeVisible()

log("Switching project loads the new project's list")
await pickProject(PROJECT_WITH_TWO_ENVIRONMENTS)
await expect(
dialog.getByText('Production', { exact: true }),
).toBeVisible()
})
}
})
7 changes: 6 additions & 1 deletion frontend/web/components/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,13 @@ const App = class extends Component {
return <Maintenance />
}
const activeProject = OrganisationStore.getProject(projectId)
// Pages still read the project from ProjectStore (e.g. Edge identities),
// so wait for it as well as the organisation's project list
const projectNotLoaded =
!activeProject && document.location.href.includes('project/')
document.location.href.includes('project/') &&
(!activeProject ||
!ProjectStore.model ||
`${ProjectStore.id}` !== `${projectId}`)

if (this.props.isLoading) {
return (
Expand Down
40 changes: 34 additions & 6 deletions frontend/web/components/EmptyState.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import React, { FC, ReactNode } from 'react'
import { colorIconDanger, colorIconSecondary } from 'common/theme/tokens'
import Icon, { IconName } from './icons/Icon'
import Button from './base/forms/Button'

export type EmptyStateStatus = 'empty' | 'error'

type EmptyStateProps = {
title: string
description?: string | ReactNode
// 'error' is for content that failed to load: pair it with a retry action
status?: EmptyStateStatus
icon?: IconName
iconColour?: string
docsUrl?: string
docsLabel?: string
action?: ReactNode
// Renders a Try again button, and a matching description unless one is given
onRetry?: () => void
className?: string
}

Expand All @@ -19,19 +27,34 @@ const EmptyState: FC<EmptyStateProps> = ({
docsLabel = 'View docs',
docsUrl,
icon,
iconColour = '#9DA4AE',
iconColour,
onRetry,
status = 'empty',
title,
}) => {
const isError = status === 'error'
const iconName = icon ?? (isError ? 'warning' : undefined)
const text =
description ?? (onRetry ? 'Try again in a few moments.' : undefined)
return (
<div className={`empty-state ${className || ''}`}>
{icon && (
<div
role={isError ? 'alert' : undefined}
className={`empty-state ${className || ''}`}
>
{iconName && (
<div className='empty-state__icon'>
<Icon name={icon} width={40} fill={iconColour} />
<Icon
name={iconName}
width={40}
fill={
iconColour ?? (isError ? colorIconDanger : colorIconSecondary)
}
/>
</div>
)}
<h5 className='empty-state__title'>{title}</h5>
{description && (
<div className='empty-state__description text-muted'>{description}</div>
{text && (
<div className='empty-state__description text-muted'>{text}</div>
)}
{docsUrl && (
<a
Expand All @@ -44,6 +67,11 @@ const EmptyState: FC<EmptyStateProps> = ({
</a>
)}
{action}
{onRetry && (
<Button theme='outline' size='small' onClick={onRetry}>
Try again
</Button>
)}
</div>
)
}
Expand Down
Loading
Loading