diff --git a/frontend/common/hooks/useSortedProjectEnvironments.ts b/frontend/common/hooks/useSortedProjectEnvironments.ts new file mode 100644 index 000000000000..0e17f16b8ba4 --- /dev/null +++ b/frontend/common/hooks/useSortedProjectEnvironments.ts @@ -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, + } +} diff --git a/frontend/common/stores/organisation-store.js b/frontend/common/stores/organisation-store.js index ff50e0ba316a..9a1b7499ac92 100644 --- a/frontend/common/stores/organisation-store.js +++ b/frontend/common/stores/organisation-store.js @@ -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' @@ -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) @@ -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, @@ -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() } }) } diff --git a/frontend/common/utils/__tests__/environmentFixture.ts b/frontend/common/utils/__tests__/environmentFixture.ts new file mode 100644 index 000000000000..106695074a8a --- /dev/null +++ b/frontend/common/utils/__tests__/environmentFixture.ts @@ -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, +}) diff --git a/frontend/common/utils/__tests__/projectLandingPath.test.ts b/frontend/common/utils/__tests__/projectLandingPath.test.ts new file mode 100644 index 000000000000..9ac8738e95a7 --- /dev/null +++ b/frontend/common/utils/__tests__/projectLandingPath.test.ts @@ -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') + }) +}) diff --git a/frontend/common/utils/__tests__/sortEnvironmentsByName.test.ts b/frontend/common/utils/__tests__/sortEnvironmentsByName.test.ts new file mode 100644 index 000000000000..1be1ee4a5046 --- /dev/null +++ b/frontend/common/utils/__tests__/sortEnvironmentsByName.test.ts @@ -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', + ]) + }) +}) diff --git a/frontend/common/utils/projectLandingPath.ts b/frontend/common/utils/projectLandingPath.ts new file mode 100644 index 000000000000..90b4ea6e4da3 --- /dev/null +++ b/frontend/common/utils/projectLandingPath.ts @@ -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` +} diff --git a/frontend/common/utils/sortEnvironmentsByName.ts b/frontend/common/utils/sortEnvironmentsByName.ts new file mode 100644 index 000000000000..df3d82dc0717 --- /dev/null +++ b/frontend/common/utils/sortEnvironmentsByName.ts @@ -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') +} diff --git a/frontend/documentation/components/EmptyState.stories.tsx b/frontend/documentation/components/EmptyState.stories.tsx index e3e567620606..817030e73617 100644 --- a/frontend/documentation/components/EmptyState.stories.tsx +++ b/frontend/documentation/components/EmptyState.stories.tsx @@ -40,7 +40,18 @@ const meta: Meta = { 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', @@ -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', + }, +} diff --git a/frontend/e2e/helpers/e2e-helpers.playwright.ts b/frontend/e2e/helpers/e2e-helpers.playwright.ts index 724a1282e4b8..3bf344b6eab9 100644 --- a/frontend/e2e/helpers/e2e-helpers.playwright.ts +++ b/frontend/e2e/helpers/e2e-helpers.playwright.ts @@ -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(); } diff --git a/frontend/e2e/tests/user-permissions-test.pw.ts b/frontend/e2e/tests/user-permissions-test.pw.ts new file mode 100644 index 000000000000..95966ce15b87 --- /dev/null +++ b/frontend/e2e/tests/user-permissions-test.pw.ts @@ -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 }), + ).toBeVisible() + + log("Switching project loads the new project's list") + await pickProject(PROJECT_WITH_TWO_ENVIRONMENTS) + await expect( + dialog.getByText('Production', { exact: true }), + ).toBeVisible() + }) + } +}) diff --git a/frontend/web/components/App.js b/frontend/web/components/App.js index bda5c996deca..58bbad3e30da 100644 --- a/frontend/web/components/App.js +++ b/frontend/web/components/App.js @@ -293,8 +293,13 @@ const App = class extends Component { return } 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 ( diff --git a/frontend/web/components/EmptyState.tsx b/frontend/web/components/EmptyState.tsx index 6bff60883a01..374397f3aa0b 100644 --- a/frontend/web/components/EmptyState.tsx +++ b/frontend/web/components/EmptyState.tsx @@ -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 } @@ -19,19 +27,34 @@ const EmptyState: FC = ({ 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 ( -
- {icon && ( +
+ {iconName && (
- +
)}
{title}
- {description && ( -
{description}
+ {text && ( +
{text}
)} {docsUrl && ( = ({ )} {action} + {onRetry && ( + + )}
) } diff --git a/frontend/web/components/PermissionsTabs.tsx b/frontend/web/components/PermissionsTabs.tsx index cd3988c86800..f028992d694c 100644 --- a/frontend/web/components/PermissionsTabs.tsx +++ b/frontend/web/components/PermissionsTabs.tsx @@ -1,12 +1,6 @@ -import React, { FC, Ref, useEffect, useState } from 'react' +import React, { FC, Ref, useState } from 'react' import { EditPermissionsModal } from './EditPermissions' -import { - Environment, - Project, - Role, - User, - UserGroupSummary, -} from 'common/types/responses' +import { Project, Role, User, UserGroupSummary } from 'common/types/responses' import Tabs from './navigation/TabMenu/Tabs' import TabItem from './navigation/TabMenu/TabItem' import Input from './base/forms/Input' @@ -16,6 +10,8 @@ import ProjectFilter from './ProjectFilter' import OrganisationStore from 'common/stores/organisation-store' import PlanBasedAccess from './PlanBasedAccess' import WarningMessage from './WarningMessage' +import EmptyState from './EmptyState' +import { useSortedProjectEnvironments } from 'common/hooks/useSortedProjectEnvironments' type PermissionsTabsType = { orgId?: number @@ -42,16 +38,8 @@ const PermissionsTabs: FC = ({ const [searchEnv, setSearchEnv] = useState('') const projectData: Project[] | undefined = OrganisationStore.getProjects() const [project, setProject] = useState('') - const [environments, setEnvironments] = useState([]) - - useEffect(() => { - if (project && projectData) { - const environments = projectData.find( - (p) => p.id === parseInt(project), - )?.environments - setEnvironments(environments || []) - } - }, [project, projectData]) + const { environments, isError, isLoading, refetch } = + useSortedProjectEnvironments(Number(project) || undefined) if (!orgId) { return @@ -154,13 +142,21 @@ const PermissionsTabs: FC = ({ />
- {environments.length > 0 && ( + {isLoading && } + {isError && !environments?.length && ( + + )} + {!!environments?.length && ( { + mainItems={environments.map((v) => { return { id: role ? v.id : v.api_key, name: v.name, diff --git a/frontend/web/components/ProjectManageWidget.tsx b/frontend/web/components/ProjectManageWidget.tsx index cfd9768cfdea..62821e48f747 100644 --- a/frontend/web/components/ProjectManageWidget.tsx +++ b/frontend/web/components/ProjectManageWidget.tsx @@ -115,7 +115,7 @@ const ProjectManageWidget: FC = ({ organisationId }) => {
} items={projects} - renderRow={({ environments, id, name }, i) => { + renderRow={({ id, name }, i) => { return ( <> {i === 0 && ( @@ -152,11 +152,7 @@ const ProjectManageWidget: FC = ({ organisationId }) => { key={id} id={`project-select-${i}`} data-test={`project-${Utils.toKebabCase(name)}`} - to={`/project/${id}/environment/${ - environments && environments[0] - ? `${environments[0].api_key}/features` - : 'create' - }`} + to={`/project/${id}`} className='clickable col-md-6 col-xl-3' style={{ minWidth: '190px' }} > diff --git a/frontend/web/components/inspect-permissions/EnvironmentPermissions.tsx b/frontend/web/components/inspect-permissions/EnvironmentPermissions.tsx index 107ed69a30eb..03a598ae3d02 100644 --- a/frontend/web/components/inspect-permissions/EnvironmentPermissions.tsx +++ b/frontend/web/components/inspect-permissions/EnvironmentPermissions.tsx @@ -1,7 +1,6 @@ -import { useMemo } from 'react' import ExpandablePermissionsList from './ExpandablePermissionsList' -import OrganisationStore from 'common/stores/organisation-store' -import { Project } from 'common/types/responses' +import { useSortedProjectEnvironments } from 'common/hooks/useSortedProjectEnvironments' +import EmptyState from 'components/EmptyState' import PanelSearch from 'components/PanelSearch' type EnvironmentPermissionsProps = { @@ -15,19 +14,29 @@ const EnvironmentPermissions = ({ searchEnvironment = '', userId, }: EnvironmentPermissionsProps) => { - const projectData: Project[] = OrganisationStore.getProjects() - const environments = useMemo(() => { - if (!projectData || !projectId) { - return - } - return projectData.find((p) => p.id === parseInt(projectId))?.environments - }, [projectData, projectId]) + const { environments, isError, isLoading, refetch } = + useSortedProjectEnvironments(Number(projectId) || undefined) const filteredEnvironments = environments?.filter((v) => { const search = searchEnvironment?.toLowerCase() if (!search) return true return `${v.name}`.toLowerCase().includes(search) }) + if (isLoading) { + return + } + if (isError && !environments?.length) { + return ( + + ) + } + if (!environments?.length) { + return null + } return ( <> env.name} getItemId={(env) => env.id} getLevelId={(env) => env.api_key} diff --git a/frontend/web/components/inspect-permissions/InspectPermissions.tsx b/frontend/web/components/inspect-permissions/InspectPermissions.tsx index 09052fb06e6a..d2c85ad282ca 100644 --- a/frontend/web/components/inspect-permissions/InspectPermissions.tsx +++ b/frontend/web/components/inspect-permissions/InspectPermissions.tsx @@ -1,11 +1,10 @@ -import React, { FC, Ref, useMemo, useState } from 'react' -import { Project, Role, User, UserGroupSummary } from 'common/types/responses' +import React, { FC, Ref, useState } from 'react' +import { Role, User, UserGroupSummary } from 'common/types/responses' import Tabs from 'components/navigation/TabMenu/Tabs' import TabItem from 'components/navigation/TabMenu/TabItem' import Input from 'components/base/forms/Input' import Utils from 'common/utils/utils' import ProjectFilter from 'components/ProjectFilter' -import OrganisationStore from 'common/stores/organisation-store' import PlanBasedAccess from 'components/PlanBasedAccess' import Permissions from './Permissions' import ProjectPermissions from './ProjectPermissions' @@ -30,16 +29,8 @@ const InspectPermissions: FC = ({ value, }) => { const [searchEnv, setSearchEnv] = useState('') - const projectData: Project[] = OrganisationStore.getProjects() const [project, setProject] = useState('') - const environments = useMemo(() => { - if (!project || !projectData) { - return null - } - return projectData.find((p) => p.id === parseInt(project))?.environments - }, [project, projectData]) - if (!orgId) { return null } @@ -95,13 +86,11 @@ const InspectPermissions: FC = ({ />
- {environments?.length !== 0 && ( - - )} +
diff --git a/frontend/web/components/pages/ProjectRedirectPage.tsx b/frontend/web/components/pages/ProjectRedirectPage.tsx index d41e09e67ecd..fcc3f5a76a8a 100644 --- a/frontend/web/components/pages/ProjectRedirectPage.tsx +++ b/frontend/web/components/pages/ProjectRedirectPage.tsx @@ -1,33 +1,21 @@ -import { FC, useEffect } from 'react' -import { useGetEnvironmentsQuery } from 'common/services/useEnvironment' -import { useHistory } from 'react-router-dom' +import { FC } from 'react' +import { Redirect } from 'react-router-dom' +import { useSortedProjectEnvironments } from 'common/hooks/useSortedProjectEnvironments' import Utils from 'common/utils/utils' +import { getProjectLandingPath } from 'common/utils/projectLandingPath' import ConfigProvider from 'common/providers/ConfigProvider' import { useRouteContext } from 'components/providers/RouteContext' const ProjectRedirectPage: FC = () => { - const history = useHistory() const { projectId } = useRouteContext() + const { environments, isError } = useSortedProjectEnvironments(projectId) - const { data, error } = useGetEnvironmentsQuery({ - projectId: projectId?.toString() || '', - }) - useEffect(() => { - if (!data) { - return - } - if (error) { - history.replace(Utils.getOrganisationHomePage()) - } - const environment = data?.results?.[0] - if (environment) { - history.replace( - `/project/${projectId}/environment/${environment.api_key}/features`, - ) - } else { - history.replace(`/project/${projectId}/environment/create`) - } - }, [data, error, history]) + if (isError) { + return + } + if (projectId && environments) { + return + } return (