Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Insert layer name fetching #330

Merged
merged 2 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
51 changes: 29 additions & 22 deletions src/components/layers-panel/insert-panel/insert-panel.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
import { fireEvent, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderWithTheme } from "../../../utils/testing-utils/render-with-theme";
import { renderWithThemeProviders } from "../../../utils/testing-utils/render-with-theme";
import { InsertPanel } from "./insert-panel";
import { setupStore } from "../../../redux/store";

const onInsertMock = jest.fn();
const onCancelMock = jest.fn();

const callRender = (renderFunc, props = {}) => {
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

const callRender = (renderFunc, props = {}, store = setupStore()) => {
return renderFunc(
<InsertPanel
title={"Test Title"}
onInsert={onInsertMock}
onCancel={onCancelMock}
{...props}
/>
/>,
store
);
};

describe("Insert panel", () => {
it("Should render insert panel", () => {
const { container } = callRender(renderWithTheme);
const { container } = callRender(renderWithThemeProviders);

expect(container).toBeInTheDocument();
expect(screen.getByText("Test Title")).toBeInTheDocument();
Expand All @@ -30,64 +36,65 @@ describe("Insert panel", () => {
expect(screen.getByText("Insert")).toBeInTheDocument();
});

it("Should show name error and url error if they are not provided", () => {
const { container } = callRender(renderWithTheme);
it("Should show name error and url error if they are not provided", async () => {
const { container } = callRender(renderWithThemeProviders);

userEvent.click(screen.getByText("Insert"));

await sleep(200);
expect(container).toBeInTheDocument();
expect(screen.getByText("Please enter name")).toBeInTheDocument();
expect(screen.getByText("Invalid URL")).toBeInTheDocument();
});

it("Should show only url error if Name field is filled in", () => {
callRender(renderWithTheme);
it("Should show only url error if Name field is filled in", async () => {
callRender(renderWithThemeProviders);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const nameInput = document.querySelector("input[name=Name]")!;

fireEvent.change(nameInput, { target: { value: 'test name' } });
fireEvent.change(nameInput, { target: { value: "test name" } });

userEvent.click(screen.getByText("Insert"));

await sleep(200);
expect(screen.getByText("Invalid URL")).toBeInTheDocument();
expect(screen.queryByText("Please enter name")).toBeNull();
});

it("Should show URL error if it is not valid", () => {
callRender(renderWithTheme);
it("Should show URL error if it is not valid", async () => {
callRender(renderWithThemeProviders);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const nameInput = document.querySelector("input[name=Name]")!;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const urlInput = document.querySelector("input[name=URL]")!;

fireEvent.change(nameInput, { target: { value: 'test name' } });
fireEvent.change(urlInput, { target: { value: 'test url' } });
fireEvent.change(nameInput, { target: { value: "test name" } });
fireEvent.change(urlInput, { target: { value: "test url" } });

userEvent.click(screen.getByText("Insert"));

await sleep(200);
expect(screen.getByText("Invalid URL")).toBeInTheDocument();
expect(screen.queryByText("Please enter name")).toBeNull();
});

it("Should insert if everything is good", () => {
callRender(renderWithTheme);
it("Should insert if everything is good", async () => {
callRender(renderWithThemeProviders);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const nameInput = document.querySelector("input[name=Name]")!;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const urlInput = document.querySelector("input[name=URL]")!;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const tokenInput = document.querySelector("input[name=Token]")!;

fireEvent.change(nameInput, { target: { value: 'test name' } });
fireEvent.change(urlInput, { target: { value: 'http://123.com' } });
fireEvent.change(tokenInput, { target: { value: 'test token' } });
fireEvent.change(nameInput, { target: { value: "test name" } });
fireEvent.change(urlInput, { target: { value: "http://123.com" } });
fireEvent.change(tokenInput, { target: { value: "test token" } });

userEvent.click(screen.getByText("Insert"));
await sleep(200);
expect(onInsertMock).toBeCalled();
});

it("Should be able to cancel panel", () => {
callRender(renderWithTheme);
callRender(renderWithThemeProviders);

userEvent.click(screen.getByText("Cancel"));
expect(onCancelMock).toBeCalled();
Expand Down
90 changes: 76 additions & 14 deletions src/components/layers-panel/insert-panel/insert-panel.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import styled from "styled-components";

import { ActionButtonVariant } from "../../../types";
import {
ActionButtonVariant,
FetchingStatus,
TilesetType,
} from "../../../types";
import {
getCurrentLayoutProperty,
useAppLayout,
} from "../../../utils/hooks/layout";
import { ActionButton } from "../../action-button/action-button";
import { InputText } from "./input-text/input-text";
import { getTilesetType } from "../../../utils/url-utils";
import { LoadingSpinner } from "../../loading-spinner/loading-spinner";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
getLayerNameInfo,
selectLayerNames,
} from "../../../redux/slices/layer-names-slice";

const NO_NAME_ERROR = "Please enter name";
const INVALID_URL_ERROR = "Invalid URL";
Expand All @@ -23,6 +34,10 @@ type LayoutProps = {
layout: string;
};

type VisibilityProps = {
visible: boolean;
};

const Container = styled.div<LayoutProps>`
position: relative;
display: flex;
Expand Down Expand Up @@ -65,6 +80,16 @@ const ButtonsWrapper = styled.div`
padding: 0 6px;
`;

const SpinnerContainer = styled.div<VisibilityProps>`
background: rgba(0, 0, 0, 0.3);
position: absolute;
left: calc(50% - 44px);
top: calc(50% - 44px);
padding: 22px;
border-radius: 8px;
visibility: ${({ visible }) => (visible ? "visible" : "hidden")};
`;

export const InsertPanel = ({
title,
onInsert,
Expand All @@ -77,14 +102,13 @@ export const InsertPanel = ({

const [nameError, setNameError] = useState("");
const [urlError, setUrlError] = useState("");
const [isValidateInProgress, setValidateInProgress] = useState(false);
const layerNames = useAppSelector(selectLayerNames);
const dispatch = useAppDispatch();

const validateFields = () => {
let isFormValid = true;

if (!name) {
setNameError(NO_NAME_ERROR);
isFormValid = false;
}
const type = getTilesetType(url);

try {
new URL(url);
Expand All @@ -93,16 +117,43 @@ export const InsertPanel = ({
isFormValid = false;
}

return isFormValid;
};

const handleInsert = (event) => {
const isFormValid = validateFields();
if (
(type !== TilesetType.I3S && !name) ||
(type === TilesetType.I3S && !name && !layerNames[url]?.name)
) {
setNameError(NO_NAME_ERROR);
isFormValid = false;
}

if (isFormValid) {
onInsert({ name, url, token });
onInsert({ name: name || layerNames[url]?.name, url, token });
}
};

useEffect(() => {
const type = getTilesetType(url);
if (isValidateInProgress && type === TilesetType.I3S) {
if (
(layerNames[url] !== undefined &&
layerNames[url].status === FetchingStatus.ready) ||
name.length > 0
) {
setValidateInProgress(false);
validateFields();
} else if (!layerNames[url]) {
dispatch(getLayerNameInfo({ layerUrl: url, token, type }));
}
}
}, [isValidateInProgress, layerNames]);

const handleInsert = async (event) => {
event.preventDefault();

if (getTilesetType(url) !== TilesetType.I3S) {
validateFields();
} else {
setValidateInProgress(true);
}
};

const handleInputChange = (event) => {
Expand All @@ -122,11 +173,19 @@ export const InsertPanel = ({
}
};

const onCancelHandler = () => {
setValidateInProgress(false);
onCancel();
};

const layout = useAppLayout();

return (
<Container layout={layout}>
<Title>{title}</Title>
<SpinnerContainer visible={isValidateInProgress}>
<LoadingSpinner />
</SpinnerContainer>
<form className="insert-form" onSubmit={handleInsert}>
<InputsWrapper>
<InputText
Expand All @@ -151,7 +210,10 @@ export const InsertPanel = ({
/>
</InputsWrapper>
<ButtonsWrapper>
<ActionButton variant={ActionButtonVariant.cancel} onClick={onCancel}>
<ActionButton
variant={ActionButtonVariant.cancel}
onClick={onCancelHandler}
>
Cancel
</ActionButton>
<ActionButton type="submit">Insert</ActionButton>
Expand Down
105 changes: 105 additions & 0 deletions src/redux/slices/layer-names-slice.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { fetchFile } from "@loaders.gl/core";
import { FetchingStatus, TilesetType } from "../../types";
import { setupStore } from "../store";
import reducer, {
getLayerNameInfo,
selectLayerNames,
} from "./layer-names-slice";

jest.mock("@loaders.gl/core");

describe("slice: bsl-statistics-summary", () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"bsl-statistics-summary" copypaste

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

it("Reducer should return the initial state", () => {
expect(reducer(undefined, { type: undefined })).toEqual({
map: {},
});
});

it("getLayerNameInfo should put layer name and status to the state", async () => {
(fetchFile as unknown as jest.Mock<any>).mockReturnValue(
new Promise((resolve) => {
resolve({
text: async () =>
JSON.stringify({
name: "testName",
}),
});
})
);
const store = setupStore();
await store.dispatch(
getLayerNameInfo({
layerUrl: "https://testUrl",
token: "testToken",
type: TilesetType.I3S,
})
);
const state = store.getState();
expect(state.layerNames).toEqual({
map: {
"https://testUrl": {
name: "testName",
status: FetchingStatus.ready,
},
},
});
//test selector
expect(selectLayerNames(state)).toEqual({
"https://testUrl": {
name: "testName",
status: FetchingStatus.ready,
},
});
});

it("getLayerNameInfo should put layer empty name and status to the state for no name", async () => {
(fetchFile as unknown as jest.Mock<any>).mockReturnValue(
new Promise((resolve) => {
resolve({
text: async () =>
JSON.stringify({
noname: "No Name in the layer",
}),
});
})
);
const store = setupStore();
await store.dispatch(
getLayerNameInfo({
layerUrl: "https://testUrl",
token: "testToken",
type: TilesetType.I3S,
})
);
const state = store.getState();
expect(state.layerNames).toEqual({
map: {
"https://testUrl": {
name: "",
status: FetchingStatus.ready,
},
},
});
});

it("getLayerNameInfo should put layer empty name and status ready in case of rejected fetching", async () => {
(fetchFile as unknown as jest.Mock<any>).mockRejectedValue("Error");
const store = setupStore();
await store.dispatch(
getLayerNameInfo({
layerUrl: "https://testUrl",
token: "testToken",
type: TilesetType.I3S,
})
);
const state = store.getState();
expect(state.layerNames).toEqual({
map: {
"https://testUrl": {
name: "",
status: FetchingStatus.ready,
},
},
});
});
});
Loading