Migrated Hosted Explorer to React (#360)

Co-authored-by: Victor Meng <vimeng@microsoft.com>
Co-authored-by: Steve Faulkner <stfaul@microsoft.com>
This commit is contained in:
Steve Faulkner
2021-01-19 16:31:55 -06:00
committed by GitHub
parent 8c40df0fa1
commit 2b2de7c645
79 changed files with 2250 additions and 6025 deletions

View File

@@ -0,0 +1,46 @@
jest.mock("../../../hooks/useSubscriptions");
jest.mock("../../../hooks/useDatabaseAccounts");
import React from "react";
import { render, fireEvent, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import { AccountSwitcher } from "./AccountSwitcher";
import { useSubscriptions } from "../../../hooks/useSubscriptions";
import { useDatabaseAccounts } from "../../../hooks/useDatabaseAccounts";
import { DatabaseAccount, Subscription } from "../../../Contracts/DataModels";
it("calls setAccount from parent component", () => {
const armToken = "fakeToken";
const setDatabaseAccount = jest.fn();
const subscriptions = [
{ subscriptionId: "testSub1", displayName: "Test Sub 1" },
{ subscriptionId: "testSub2", displayName: "Test Sub 2" }
] as Subscription[];
(useSubscriptions as jest.Mock).mockReturnValue(subscriptions);
const accounts = [{ name: "testAccount1" }, { name: "testAccount2" }] as DatabaseAccount[];
(useDatabaseAccounts as jest.Mock).mockReturnValue(accounts);
render(<AccountSwitcher armToken={armToken} setDatabaseAccount={setDatabaseAccount} />);
fireEvent.click(screen.getByText("Select a Database Account"));
expect(screen.getByLabelText("Subscription")).toHaveTextContent("Select a Subscription");
fireEvent.click(screen.getByText("Select a Subscription"));
fireEvent.click(screen.getByText(subscriptions[0].displayName));
expect(screen.getByLabelText("Cosmos DB Account Name")).toHaveTextContent("Select an Account");
fireEvent.click(screen.getByText("Select an Account"));
fireEvent.click(screen.getByText(accounts[0].name));
expect(setDatabaseAccount).toHaveBeenCalledWith(accounts[0]);
});
it("No subscriptions", () => {
const armToken = "fakeToken";
const setDatabaseAccount = jest.fn();
const subscriptions = [] as Subscription[];
(useSubscriptions as jest.Mock).mockReturnValue(subscriptions);
const accounts = [] as DatabaseAccount[];
(useDatabaseAccounts as jest.Mock).mockReturnValue(accounts);
render(<AccountSwitcher armToken={armToken} setDatabaseAccount={setDatabaseAccount} />);
fireEvent.click(screen.getByText("Select a Database Account"));
expect(screen.getByLabelText("Subscription")).toHaveTextContent("No Subscriptions Found");
});

View File

@@ -0,0 +1,109 @@
// TODO: Renable this rule for the file or turn it off everywhere
/* eslint-disable react/display-name */
import { StyleConstants } from "../../../Common/Constants";
import { FunctionComponent, useState, useEffect } from "react";
import * as React from "react";
import { DefaultButton, IButtonStyles } from "office-ui-fabric-react/lib/Button";
import { IContextualMenuItem } from "office-ui-fabric-react/lib/ContextualMenu";
import { DatabaseAccount } from "../../../Contracts/DataModels";
import { useSubscriptions } from "../../../hooks/useSubscriptions";
import { useDatabaseAccounts } from "../../../hooks/useDatabaseAccounts";
import { SwitchSubscription } from "./SwitchSubscription";
import { SwitchAccount } from "./SwitchAccount";
const buttonStyles: IButtonStyles = {
root: {
fontSize: StyleConstants.DefaultFontSize,
height: 40,
padding: 0,
paddingLeft: 10,
marginRight: 5,
backgroundColor: StyleConstants.BaseDark,
color: StyleConstants.BaseLight
},
rootHovered: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootFocused: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootPressed: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
rootExpanded: {
backgroundColor: StyleConstants.BaseHigh,
color: StyleConstants.BaseLight
},
textContainer: {
flexGrow: "initial"
}
};
interface Props {
armToken: string;
setDatabaseAccount: (account: DatabaseAccount) => void;
}
export const AccountSwitcher: FunctionComponent<Props> = ({ armToken, setDatabaseAccount }: Props) => {
const subscriptions = useSubscriptions(armToken);
const [selectedSubscriptionId, setSelectedSubscriptionId] = useState<string>(() =>
localStorage.getItem("cachedSubscriptionId")
);
const selectedSubscription = subscriptions?.find(sub => sub.subscriptionId === selectedSubscriptionId);
const accounts = useDatabaseAccounts(selectedSubscription?.subscriptionId, armToken);
const [selectedAccountName, setSelectedAccountName] = useState<string>(() =>
localStorage.getItem("cachedDatabaseAccountName")
);
const selectedAccount = accounts?.find(account => account.name === selectedAccountName);
useEffect(() => {
if (selectedAccountName) {
localStorage.setItem("cachedDatabaseAccountName", selectedAccountName);
}
}, [selectedAccountName]);
useEffect(() => {
if (selectedSubscriptionId) {
localStorage.setItem("cachedSubscriptionId", selectedSubscriptionId);
}
}, [selectedSubscriptionId]);
useEffect(() => {
if (selectedAccount) {
setDatabaseAccount(selectedAccount);
}
}, [selectedAccount]);
const buttonText = selectedAccount?.name || "Select a Database Account";
const items: IContextualMenuItem[] = [
{
key: "switchSubscription",
onRender: () => <SwitchSubscription {...{ subscriptions, setSelectedSubscriptionId, selectedSubscription }} />
},
{
key: "switchAccount",
onRender: (_, dismissMenu) => (
<SwitchAccount {...{ accounts, dismissMenu, selectedAccount, setSelectedAccountName }} />
)
}
];
return (
<DefaultButton
text={buttonText}
menuProps={{
directionalHintFixed: true,
className: "accountSwitchContextualMenu",
items
}}
styles={buttonStyles}
className="accountSwitchButton"
id="accountSwitchButton"
/>
);
};

View File

@@ -0,0 +1,18 @@
jest.mock("../../../hooks/useDirectories");
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { ConnectExplorer } from "./ConnectExplorer";
it("shows the connect form", () => {
const connectionString = "fakeConnectionString";
const login = jest.fn();
const setConnectionString = jest.fn();
const setEncryptedToken = jest.fn();
const setAuthType = jest.fn();
render(<ConnectExplorer {...{ login, setEncryptedToken, setAuthType, connectionString, setConnectionString }} />);
expect(screen.queryByPlaceholderText("Please enter a connection string")).toBeNull();
fireEvent.click(screen.getByText("Connect to your account with connection string"));
expect(screen.queryByPlaceholderText("Please enter a connection string")).toBeDefined();
});

View File

@@ -0,0 +1,94 @@
import * as React from "react";
import { useBoolean } from "@uifabric/react-hooks";
import { HttpHeaders } from "../../../Common/Constants";
import { GenerateTokenResponse } from "../../../Contracts/DataModels";
import { configContext } from "../../../ConfigContext";
import { AuthType } from "../../../AuthType";
import { isResourceTokenConnectionString } from "../Helpers/ResourceTokenUtils";
interface Props {
connectionString: string;
login: () => void;
setEncryptedToken: (token: string) => void;
setConnectionString: (connectionString: string) => void;
setAuthType: (authType: AuthType) => void;
}
export const ConnectExplorer: React.FunctionComponent<Props> = ({
setEncryptedToken,
login,
setAuthType,
connectionString,
setConnectionString
}: Props) => {
const [isFormVisible, { setTrue: showForm }] = useBoolean(false);
return (
<div id="connectExplorer" className="connectExplorerContainer" style={{ display: "flex" }}>
<div className="connectExplorerFormContainer">
<div className="connectExplorer">
<p className="connectExplorerContent">
<img src="images/HdeConnectCosmosDB.svg" alt="Azure Cosmos DB" />
</p>
<p className="welcomeText">Welcome to Azure Cosmos DB</p>
{isFormVisible ? (
<form
id="connectWithConnectionString"
onSubmit={async event => {
event.preventDefault();
if (isResourceTokenConnectionString(connectionString)) {
setAuthType(AuthType.ResourceToken);
return;
}
const headers = new Headers();
headers.append(HttpHeaders.connectionString, connectionString);
const url = configContext.BACKEND_ENDPOINT + "/api/guest/tokens/generateToken";
const response = await fetch(url, { headers, method: "POST" });
if (!response.ok) {
throw response;
}
// This API has a quirk where it must be parsed twice
const result: GenerateTokenResponse = JSON.parse(await response.json());
setEncryptedToken(decodeURIComponent(result.readWrite || result.read));
setAuthType(AuthType.ConnectionString);
}}
>
<p className="connectExplorerContent connectStringText">Connect to your account with connection string</p>
<p className="connectExplorerContent">
<input
className="inputToken"
type="text"
required
placeholder="Please enter a connection string"
value={connectionString}
onChange={event => {
setConnectionString(event.target.value);
}}
/>
<span className="errorDetailsInfoTooltip" style={{ display: "none" }}>
<img className="errorImg" src="images/error.svg" alt="Error notification" />
<span className="errorDetails"></span>
</span>
</p>
<p className="connectExplorerContent">
<input className="filterbtnstyle" type="submit" value="Connect" />
</p>
<p className="switchConnectTypeText" onClick={login}>
Sign In with Azure Account
</p>
</form>
) : (
<div id="connectWithAad">
<input className="filterbtnstyle" type="button" value="Sign In" onClick={login} />
<p className="switchConnectTypeText" onClick={showForm}>
Connect to your account with connection string
</p>
</div>
)}
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,31 @@
jest.mock("../../../hooks/useDirectories");
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { Tenant } from "../../../Contracts/DataModels";
import { useDirectories } from "../../../hooks/useDirectories";
import { DirectoryPickerPanel } from "./DirectoryPickerPanel";
it("switches tenant for user", () => {
const armToken = "fakeToken";
const switchTenant = jest.fn();
const dismissPanel = jest.fn();
const directories = [
{ displayName: "test1", tenantId: "test1-id" },
{ displayName: "test2", tenantId: "test2-id" }
] as Tenant[];
(useDirectories as jest.Mock).mockReturnValue(directories);
render(
<DirectoryPickerPanel
armToken={armToken}
isOpen={true}
tenantId="test1-id"
switchTenant={switchTenant}
dismissPanel={dismissPanel}
/>
);
fireEvent.click(screen.getByLabelText(/test2-id/));
expect(switchTenant).toHaveBeenCalledWith(directories[1].tenantId);
expect(dismissPanel).toHaveBeenCalled();
});

View File

@@ -0,0 +1,39 @@
import { Panel, PanelType, ChoiceGroup } from "office-ui-fabric-react";
import * as React from "react";
import { useDirectories } from "../../../hooks/useDirectories";
interface Props {
isOpen: boolean;
dismissPanel: () => void;
tenantId: string;
armToken: string;
switchTenant: (tenantId: string) => void;
}
export const DirectoryPickerPanel: React.FunctionComponent<Props> = ({
isOpen,
dismissPanel,
armToken,
tenantId,
switchTenant
}: Props) => {
const directories = useDirectories(armToken);
return (
<Panel
type={PanelType.medium}
headerText="Select Directory"
isOpen={isOpen}
onDismiss={dismissPanel}
closeButtonAriaLabel="Close"
>
<ChoiceGroup
options={directories.map(dir => ({ key: dir.tenantId, text: `${dir.displayName} (${dir.tenantId})` }))}
selectedKey={tenantId}
onChange={(event, option) => {
switchTenant(option.key);
dismissPanel();
}}
/>
</Panel>
);
};

View File

@@ -0,0 +1,22 @@
import * as React from "react";
import { CommandButtonComponent } from "../../../Explorer/Controls/CommandButton/CommandButtonComponent";
import FeedbackIcon from "../../../../images/Feedback.svg";
export const FeedbackCommandButton: React.FunctionComponent = () => {
return (
<div className="feedbackConnectSettingIcons">
<CommandButtonComponent
id="commandbutton-feedback"
iconSrc={FeedbackIcon}
iconAlt="feeback button"
onCommandClick={() =>
window.open("https://aka.ms/cosmosdbfeedback?subject=Cosmos%20DB%20Hosted%20Data%20Explorer%20Feedback")
}
ariaLabel="feeback button"
tooltipText="Send feedback"
hasPopup={true}
disabled={false}
/>
</div>
);
};

View File

@@ -0,0 +1,17 @@
jest.mock("../../../hooks/useDirectories");
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import { MeControl } from "./MeControl";
import { Account } from "msal";
it("renders", () => {
const account = {} as Account;
const logout = jest.fn();
const openPanel = jest.fn();
render(<MeControl graphToken="" account={account} logout={logout} openPanel={openPanel} />);
fireEvent.click(screen.getByRole("button"));
expect(screen.getByText("Switch Directory")).toBeDefined();
expect(screen.getByText("Sign Out")).toBeDefined();
});

View File

@@ -0,0 +1,68 @@
import {
FocusZone,
DefaultButton,
DirectionalHint,
Persona,
PersonaInitialsColor,
PersonaSize
} from "office-ui-fabric-react";
import * as React from "react";
import { Account } from "msal";
import { useGraphPhoto } from "../../../hooks/useGraphPhoto";
interface Props {
graphToken: string;
account: Account;
openPanel: () => void;
logout: () => void;
}
export const MeControl: React.FunctionComponent<Props> = ({ openPanel, logout, account, graphToken }: Props) => {
const photo = useGraphPhoto(graphToken);
return (
<FocusZone>
<DefaultButton
id="mecontrolHeader"
className="mecontrolHeaderButton"
menuProps={{
className: "mecontrolContextualMenu",
isBeakVisible: false,
directionalHintFixed: true,
directionalHint: DirectionalHint.bottomRightEdge,
calloutProps: {
minPagePadding: 0
},
items: [
{
key: "SwitchDirectory",
text: "Switch Directory",
onClick: openPanel
},
{
key: "SignOut",
text: "Sign Out",
onClick: logout
}
]
}}
styles={{
rootHovered: { backgroundColor: "#393939" },
rootFocused: { backgroundColor: "#393939" },
rootPressed: { backgroundColor: "#393939" },
rootExpanded: { backgroundColor: "#393939" }
}}
>
<Persona
imageUrl={photo}
text={account?.name}
secondaryText={account?.userName}
showSecondaryText={true}
showInitialsUntilImageLoads={true}
initialsColor={PersonaInitialsColor.teal}
size={PersonaSize.size28}
className="mecontrolHeaderPersona"
/>
</DefaultButton>
</FocusZone>
);
};

View File

@@ -0,0 +1,21 @@
import { DefaultButton } from "office-ui-fabric-react";
import * as React from "react";
interface Props {
login: () => void;
}
export const SignInButton: React.FunctionComponent<Props> = ({ login }: Props) => {
return (
<DefaultButton
className="mecontrolSigninButton"
text="Sign In"
onClick={login}
styles={{
rootHovered: { backgroundColor: "#393939", color: "#fff" },
rootFocused: { backgroundColor: "#393939", color: "#fff" },
rootPressed: { backgroundColor: "#393939", color: "#fff" }
}}
/>
);
};

View File

@@ -0,0 +1,39 @@
import { Dropdown } from "office-ui-fabric-react/lib/Dropdown";
import * as React from "react";
import { FunctionComponent } from "react";
import { DatabaseAccount } from "../../../Contracts/DataModels";
interface Props {
accounts: DatabaseAccount[];
selectedAccount: DatabaseAccount;
setSelectedAccountName: (id: string) => void;
dismissMenu: () => void;
}
export const SwitchAccount: FunctionComponent<Props> = ({
accounts,
setSelectedAccountName,
selectedAccount,
dismissMenu
}: Props) => {
return (
<Dropdown
label="Cosmos DB Account Name"
className="accountSwitchAccountDropdown"
options={accounts?.map(account => ({
key: account.name,
text: account.name,
data: account
}))}
onChange={(_, option) => {
setSelectedAccountName(String(option.key));
dismissMenu();
}}
defaultSelectedKey={selectedAccount?.name}
placeholder={accounts && accounts.length === 0 ? "No Accounts Found" : "Select an Account"}
styles={{
callout: "accountSwitchAccountDropdownMenu"
}}
/>
);
};

View File

@@ -0,0 +1,38 @@
import { Dropdown } from "office-ui-fabric-react/lib/Dropdown";
import * as React from "react";
import { FunctionComponent } from "react";
import { Subscription } from "../../../Contracts/DataModels";
interface Props {
subscriptions: Subscription[];
selectedSubscription: Subscription;
setSelectedSubscriptionId: (id: string) => void;
}
export const SwitchSubscription: FunctionComponent<Props> = ({
subscriptions,
setSelectedSubscriptionId,
selectedSubscription
}: Props) => {
return (
<Dropdown
label="Subscription"
className="accountSwitchSubscriptionDropdown"
options={subscriptions?.map(sub => {
return {
key: sub.subscriptionId,
text: sub.displayName,
data: sub
};
})}
onChange={(_, option) => {
setSelectedSubscriptionId(String(option.key));
}}
defaultSelectedKey={selectedSubscription?.subscriptionId}
placeholder={subscriptions && subscriptions.length === 0 ? "No Subscriptions Found" : "Select a Subscription"}
styles={{
callout: "accountSwitchSubscriptionDropdownMenu"
}}
/>
);
};