Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 36 additions & 36 deletions frontend/app/.betterer.results

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions frontend/app/src/entities/branches/stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,3 @@ import { atom } from "jotai";
import type { BranchListItem } from "@/entities/branches/domain/model/branch";

export const branchesState = atom<BranchListItem[]>([]);

export const currentBranchAtom = atom<BranchListItem | null>(null);
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { Button } from "@infrahub/ui";
import { useQueryState } from "nuqs";

import type { Branch } from "@/shared/api/graphql/generated/types";
import { Row } from "@/shared/components/container";
import CheckboxField from "@/shared/components/form/fields/checkbox.field";
import InputField from "@/shared/components/form/fields/input.field";
import { isMinLength, isRequired } from "@/shared/components/form/utils/validation";
import { Form, FormSubmit } from "@/shared/components/ui/form";
import { QSP } from "@/shared/config/qsp";

import { SYNC_WITH_GIT_DESCRIPTION } from "@/entities/branches/domain/model/branch";
import { useCurrentBranch } from "@/entities/branches/ui/branches-provider";
import { useCreateBranchMutation } from "@/entities/branches/ui/queries/create-branch.mutation";

type BranchFormData = {
Expand All @@ -25,14 +24,14 @@ type BranchCreateFormProps = {
};

const BranchCreateForm = ({ defaultBranchName, onCancel, onSuccess }: BranchCreateFormProps) => {
const [, setBranchInQueryString] = useQueryState(QSP.BRANCH);
const { setCurrentBranch } = useCurrentBranch();
const { mutateAsync: createBranch } = useCreateBranchMutation();

const handleSubmit = async (branchFormData: BranchFormData) => {
await createBranch(branchFormData, {
onSuccess: async (branchCreated) => {
if (!branchCreated) return;
setBranchInQueryString(branchCreated.is_default ? null : branchCreated.name);
setCurrentBranch(branchCreated);
if (onSuccess) onSuccess(branchCreated);
},
onError: (error) => {
Expand Down
4 changes: 0 additions & 4 deletions frontend/app/src/entities/branches/ui/branch-selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,12 @@ import {
Tooltip,
} from "@infrahub/ui";
import { ArrowUpRightIcon, CheckIcon, ChevronsUpDownIcon, PlusIcon } from "lucide-react";
import { useQueryState } from "nuqs";
import React from "react";
import { type ButtonProps as AriaButtonProps, Collection } from "react-aria-components";

import { constructPath } from "@/shared/api/rest/fetch";
import { Separator } from "@/shared/components/aria/separator";
import { Row } from "@/shared/components/container";
import { QSP } from "@/shared/config/qsp";
import { useDebounce } from "@/shared/hooks/useDebounce";

import { useAuth } from "@/entities/authentication/ui/auth-provider";
Expand Down Expand Up @@ -102,7 +100,6 @@ interface BranchListProps {

function BranchList({ closePopover, openCreateForm }: BranchListProps) {
const { currentBranch, setCurrentBranch } = useCurrentBranch();
const [, setBranchInQueryString] = useQueryState(QSP.BRANCH);
const { isAuthenticated } = useAuth();
const [search, setSearch] = React.useState("");
const trimmedSearch = search.trim();
Expand All @@ -113,7 +110,6 @@ function BranchList({ closePopover, openCreateForm }: BranchListProps) {
const branches = data?.pages.flat() ?? [];

function handleBranchChange(branch: BranchListItem) {
setBranchInQueryString(branch.is_default ? null : branch.name);
setCurrentBranch(branch);
closePopover();
}
Expand Down
170 changes: 170 additions & 0 deletions frontend/app/src/entities/branches/ui/branches-provider.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { beforeEach, describe, expect, test, vi } from "vitest";

import { QSP } from "@/shared/config/qsp";

import type { BranchListItem } from "@/entities/branches/domain/model/branch";
import { BranchesProvider, useCurrentBranch } from "@/entities/branches/ui/branches-provider";
import { useGetBranches } from "@/entities/branches/ui/queries/get-branches.query";

import { render } from "../../../../tests/components/render";
import { generateBranch } from "../../../../tests/fake/branch";

vi.mock("@/entities/branches/ui/queries/get-branches.query");

// Deliberately not named "main": INFRAHUB_INITIAL_DEFAULT_BRANCH can rename the default branch,
// so the provider has to resolve it from is_default.
const defaultBranch = generateBranch({ id: "branch-default", name: "primary", is_default: true });
const featureBranch = generateBranch({ id: "branch-feature", name: "feature-1" });

type BranchesQueryState = {
data?: Array<BranchListItem>;
isPending: boolean;
error: Error | null;
};

const mockBranchesQuery = (state: BranchesQueryState) =>
vi.mocked(useGetBranches).mockReturnValue(state as ReturnType<typeof useGetBranches>);

const mockFetchedBranches = () =>
mockBranchesQuery({ data: [defaultBranch, featureBranch], isPending: false, error: null });

const seedBranchInUrl = (branchName: string) =>
window.history.replaceState(null, "", `${window.location.pathname}?${QSP.BRANCH}=${branchName}`);

const getBranchInUrl = () => new URLSearchParams(window.location.search).get(QSP.BRANCH);

function BranchProbe({ switchTo }: { switchTo?: BranchListItem }) {
const { currentBranch, setCurrentBranch } = useCurrentBranch();

return (
<>
<p>Current branch: {currentBranch.name}</p>

{switchTo && (
<button type="button" onClick={() => setCurrentBranch(switchTo)}>
Switch branch
</button>
)}
</>
);
}

describe("BranchesProvider", () => {
beforeEach(() => {
window.history.replaceState(null, "", window.location.pathname);
});

test("resolves the default branch when the URL has no branch", async () => {
// GIVEN
mockFetchedBranches();

// WHEN
const component = await render(
<BranchesProvider>
<BranchProbe />
</BranchesProvider>
);

// THEN
await expect.element(component.getByText("Current branch: primary")).toBeVisible();
});

test("resolves the branch named in the URL", async () => {
// GIVEN
mockFetchedBranches();
seedBranchInUrl(featureBranch.name);

// WHEN
const component = await render(
<BranchesProvider>
<BranchProbe />
</BranchesProvider>
);

// THEN
await expect.element(component.getByText("Current branch: feature-1")).toBeVisible();
});

test("hides its children while the branches are being fetched", async () => {
// GIVEN
mockBranchesQuery({ isPending: true, error: null });

// WHEN
const component = await render(
<BranchesProvider>
<BranchProbe />
</BranchesProvider>
);

// THEN
await expect.element(component.getByText("Loading branches...")).toBeVisible();
expect(component.getByText(/Current branch/).query()).toBeNull();
});

test("shows an error screen when the branches cannot be fetched", async () => {
// GIVEN
mockBranchesQuery({ isPending: false, error: new Error("Branches are unreachable") });

// WHEN
const component = await render(
<BranchesProvider>
<BranchProbe />
</BranchesProvider>
);

// THEN
await expect.element(component.getByText("Branches are unreachable")).toBeVisible();
});

test("drops the branch parameter when switching to the default branch", async () => {
// GIVEN
mockFetchedBranches();
seedBranchInUrl(featureBranch.name);
const component = await render(
<BranchesProvider>
<BranchProbe switchTo={defaultBranch} />
</BranchesProvider>
);

// WHEN
await component.getByRole("button", { name: "Switch branch" }).click();

// THEN
await expect.poll(getBranchInUrl).toBeNull();
});

test("writes the branch name when switching to a non-default branch", async () => {
// GIVEN
mockFetchedBranches();
const component = await render(
<BranchesProvider>
<BranchProbe switchTo={featureBranch} />
</BranchesProvider>
);

// WHEN
await component.getByRole("button", { name: "Switch branch" }).click();

// THEN
await expect.poll(getBranchInUrl).toBe("feature-1");
});

test("falls back to the default branch when the URL names an unknown branch", async () => {
// GIVEN
mockFetchedBranches();
seedBranchInUrl("does-not-exist");

// WHEN
const component = await render(
<BranchesProvider>
<BranchProbe />
</BranchesProvider>
);

// THEN
await expect
.element(component.getByText(/not found, you have been redirected to the main branch/))
.toBeVisible();
await expect.poll(getBranchInUrl).toBeNull();
});
});
29 changes: 12 additions & 17 deletions frontend/app/src/entities/branches/ui/branches-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useAtom } from "jotai";
import { useQueryState } from "nuqs";
import React, { useEffect } from "react";
import React from "react";
import { useNavigate } from "react-router";
import { toast } from "react-toastify";

Expand All @@ -10,9 +9,7 @@ import { ALERT_TYPES, Alert } from "@/shared/components/ui/alert";
import { QSP } from "@/shared/config/qsp";

import type { BranchListItem } from "@/entities/branches/domain/model/branch";
import { DEFAULT_BRANCH_NAME } from "@/entities/branches/domain/model/branch";
import { findSelectedBranch } from "@/entities/branches/domain/rules/find-selected-branch";
import { currentBranchAtom } from "@/entities/branches/stores";
import { useGetBranches } from "@/entities/branches/ui/queries/get-branches.query";

type BranchContext = {
Expand All @@ -33,18 +30,18 @@ export function useCurrentBranch() {

export const BranchesProvider = ({ children }: { children?: React.ReactNode }) => {
const { data: branches, isPending, error } = useGetBranches();
const [currentBranch, setCurrentBranch] = useAtom(currentBranchAtom);
const [branchInQueryString] = useQueryState(QSP.BRANCH);
const [branchInQueryString, setBranchInQueryString] = useQueryState(QSP.BRANCH);
const navigate = useNavigate();

useEffect(() => {
if (!branches) return;
const currentBranch = branches ? findSelectedBranch(branches, branchInQueryString) : null;

const selectedBranch = findSelectedBranch(branches, branchInQueryString);
if (selectedBranch) {
setCurrentBranch(selectedBranch);
return;
}
// The branch QSP is the source of truth: the default branch is represented by its absence
const setCurrentBranch = (branch: BranchListItem) => {
setBranchInQueryString(branch.is_default ? null : branch.name);
};

React.useEffect(() => {
if (!branches || currentBranch) return;

toast(
<Alert
Expand All @@ -57,10 +54,8 @@ export const BranchesProvider = ({ children }: { children?: React.ReactNode }) =
}
/>
);
const mainBranch = findSelectedBranch(branches, DEFAULT_BRANCH_NAME);
setCurrentBranch(mainBranch);
navigate("/");
}, [branches, branchInQueryString]);
}, [branches, currentBranch]);
Comment thread
bilalabbad marked this conversation as resolved.

if (isPending) {
return <InfrahubLoading>Loading branches...</InfrahubLoading>;
Expand All @@ -70,7 +65,7 @@ export const BranchesProvider = ({ children }: { children?: React.ReactNode }) =
return <ErrorScreen message={error.message} />;
}

if (currentBranch?.name !== (branchInQueryString ?? DEFAULT_BRANCH_NAME)) {
if (!currentBranch) {
Comment thread
bilalabbad marked this conversation as resolved.
return <InfrahubLoading>Loading branches...</InfrahubLoading>;
}

Expand Down
3 changes: 3 additions & 0 deletions frontend/app/src/entities/nodes/convert/ui/convert-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { LoadingIndicator } from "@/shared/components/loading/loading-indicator"
import { ALERT_TYPES, Alert } from "@/shared/components/ui/alert";
import { Form, FormSubmit } from "@/shared/components/ui/form";

import { useCurrentBranch } from "@/entities/branches/ui/branches-provider";
import type {
ConvertFieldMapping,
ConvertFormFieldValue,
Expand Down Expand Up @@ -56,10 +57,12 @@ export interface ConvertFormProps {

function ConvertForm({ mappings, sourceObject, sourceSchema, targetSchema }: ConvertFormProps) {
const navigate = useNavigate();
const { currentBranch } = useCurrentBranch();
const { mutateAsync: convertObject } = useConvertObjectMutation();

const fields = getFormFieldsFromSchema({
schema: targetSchema,
isDefaultBranch: !!currentBranch.is_default,
parentSchema: null,
parentData: null,
});
Expand Down
3 changes: 3 additions & 0 deletions frontend/app/src/entities/repository/ui/repository-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Form, FormSubmit } from "@/shared/components/ui/form";
import { classNames } from "@/shared/utils/common";

import { useAuth } from "@/entities/authentication/ui/auth-provider";
import { useCurrentBranch } from "@/entities/branches/ui/branches-provider";
import { useCreateObjectMutation } from "@/entities/nodes/object/ui/queries/create-object.mutation";

const RepositoryForm = ({
Expand All @@ -22,11 +23,13 @@ const RepositoryForm = ({
...props
}: NodeFormProps) => {
const auth = useAuth();
const { currentBranch } = useCurrentBranch();
const { parentSchema, parentData } = useCurrentFormContext();
const createObject = useCreateObjectMutation();

const fields = getFormFieldsFromSchema({
auth,
isDefaultBranch: !!currentBranch.is_default,
initialObject: currentObject,
schema,
parentSchema,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useMemo } from "react";
import { toast } from "react-toastify";

import DynamicForm from "@/shared/components/form/dynamic-form";
Expand All @@ -9,6 +8,7 @@ import { getFormFieldsFromSchema } from "@/shared/components/form/utils/getFormF
import { getCreateMutationFromFormData } from "@/shared/components/form/utils/mutations/getCreateMutationFromFormData";
import { ALERT_TYPES, Alert } from "@/shared/components/ui/alert";

import { useCurrentBranch } from "@/entities/branches/ui/branches-provider";
import { IP_ADDRESS_GENERIC } from "@/entities/ipam/ip-addresses/domain/model/ip-address";
import { useCreateObjectMutation } from "@/entities/nodes/object/ui/queries/create-object.mutation";
import { useUpdateObjectMutation } from "@/entities/nodes/object/ui/queries/update-object.mutation";
Expand All @@ -28,14 +28,16 @@ export const IpAddressPoolForm = ({
...props
}: IpAddressPoolFormProps) => {
const { schema: genericAddressSchema, isGeneric } = useSchema(IP_ADDRESS_GENERIC);
const { currentBranch } = useCurrentBranch();
const { parentSchema, parentData } = useCurrentFormContext();
const createObject = useCreateObjectMutation();
const updateObject = useUpdateObjectMutation();

const fields = useMemo(() => {
const fields = (() => {
const schemaFields = getFormFieldsFromSchema({
...props,
initialObject: currentObject,
isDefaultBranch: !!currentBranch.is_default,
isUpdate,
parentSchema,
parentData,
Expand Down Expand Up @@ -84,7 +86,7 @@ export const IpAddressPoolForm = ({
}
return field;
});
}, [props.schema.kind, genericAddressSchema?.kind, currentObject, isUpdate]);
})();
Comment thread
bilalabbad marked this conversation as resolved.

async function handleSubmit(data: Record<string, FormFieldValue>) {
const newObject = getCreateMutationFromFormData(fields, data, props.objectTemplate?.id);
Expand Down
Loading
Loading