Compare commits

..

18 Commits

Author SHA1 Message Date
Laurent Nguyen
8141799ffd Initial move of command bar to react 2021-04-14 11:44:22 +02:00
Steve Faulkner
732d7ce8fa Fix upload worker error display (#547) 2021-03-15 22:47:49 -05:00
Steve Faulkner
254c551999 Test Explorer Improvements (#541) 2021-03-14 22:53:16 -05:00
Jordi Bunster
f86883de6c MostRecentActivity changes (#463)
This changes the public API a bit, so that recording activity (the most common use) is less involved.
2021-03-15 03:10:48 +00:00
Steve Faulkner
62550f8d6a Deprecate Explorer Properties (#535) 2021-03-10 23:02:55 -06:00
hardiknai-techm
184910ee6c Resolve Lint errors in NotebookConfigurationUtils.ts (#490) 2021-03-10 21:47:08 -06:00
Steve Faulkner
9253ab1876 Run Emulator test only on master (#536) 2021-03-10 18:52:32 -06:00
Steve Faulkner
920c95b614 Fix cleanup databases task 2021-03-10 16:03:50 -06:00
Srinath Narayanan
1d98c83be5 Created selfServe landing page (#444)
* Portal changes for DedicatedGateway

Changes to support creation and deletion of DedicatedGateway resource.

Tested locally with various scenarios.

* Portal changes for DedicatedGateway. CR feedback

* Stylecop changes

* created selfServe.html landing page

* Removing TODO comments

* exposed baselineValues

* added getOnSaveNotification

* disable UI when onSave is taking place

* minro edits

* made polling optional

* added optional polling

* added default

* Added portal notifications

* merged more changes

* minor edits

* added label for description

* Added correlationids and polling of refresh

* Added correlationids and polling of refresh

* minor edit

* added label tooltip

* removed ClassInfo decorator

* Added dynamic decription

* added info and warninf types for description

* more changes to promise retry

* promise retry changes

* added spinner on selfserve load

* compile errors fixed

* New changes

* added operationstatus link

* merged sqlxEdits

* undid sqlx changes

* added completed notification

* passed retryInterval in notif options

* more retry changes

* more changes

* added polling on landing on the page

* edits for error display

* added keys blade link

* added link generation

* added link to blade

* Modified info and description

* fixed format errors

* added selfserve contract to output files

* addressed PR comments

Co-authored-by: Balaji Sridharan <fnbalaji@microsoft.com>
Co-authored-by: fnbalaji <75445927+fnbalaji@users.noreply.github.com>
2021-03-10 13:55:05 -08:00
Sunil Kumar Yadav
b85a20cbea Fix Lint errors in StringUtility.ts (#479) 2021-03-09 19:33:29 -06:00
hardiknai-techm
d0f6923d24 Configure onsave auto format eslint in vscode (#478) 2021-03-09 19:31:38 -06:00
Srinath Narayanan
ecdc41ada9 Added more selfserve changes (#443)
* exposed baselineValues

* added getOnSaveNotification

* disable UI when onSave is taking place

* added optional polling

* Added portal notifications

* minor edits

* added label for description

* Added correlationids and polling of refresh

* added label tooltip

* removed ClassInfo decorator

* Added dynamic decription

* added info and warninf types for description

* promise retry changes

* compile errors fixed

* merged sqlxEdits

* undid sqlx changes

* added completed notification

* passed retryInterval in notif options

* added polling on landing on the page

* edits for error display

* added link generation

* addressed PR comments

* modified test

* fixed compilation error
2021-03-09 16:07:23 -08:00
Tanuj Mittal
c1b74266eb Gallery fixes (#514)
- Fix COC overlay height
- Make standalone gallery usable on mobile devices

Before:
![image](https://user-images.githubusercontent.com/693092/110415215-81cd0680-80b7-11eb-8000-bd0b8536607a.png)

After:
![image](https://user-images.githubusercontent.com/693092/110415236-898cab00-80b7-11eb-8266-94a5718113fe.png)
2021-03-09 18:42:54 +00:00
hardiknai-techm
ef6ecf0a5f Resolve Lint errors in NavBar component (#528) 2021-03-09 12:34:01 -06:00
Sunil Kumar Yadav
b241771e69 fixed eslint of IteratorUtility (#469) 2021-03-09 12:27:24 -06:00
victor-meng
9d63a346e4 Fix issues in the add collection pane (#501) 2021-03-09 10:18:40 -08:00
hardiknai-techm
2e7c7440d3 Resolve Lint errors in CommandBarUtil.test.tsx (#529) 2021-03-09 10:20:14 -06:00
Sunil Kumar Yadav
641dae30a1 fix-eslint-NTeractUtil.ts (#493) 2021-03-09 10:17:02 -06:00
85 changed files with 2231 additions and 28198 deletions

View File

@@ -14,8 +14,6 @@ src/Common/DataAccessUtilityBase.ts
src/Common/EditableUtility.ts
src/Common/HashMap.test.ts
src/Common/HashMap.ts
src/Common/IteratorUtilities.test.ts
src/Common/IteratorUtilities.ts
src/Common/Logger.test.ts
src/Common/MessageHandler.test.ts
src/Common/MessageHandler.ts
@@ -101,7 +99,6 @@ src/Explorer/Menus/CommandBar/CommandBarComponentButtonFactory.ts
src/Explorer/Menus/ContextMenu.ts
src/Explorer/MostRecentActivity/MostRecentActivity.ts
src/Explorer/Notebook/FileSystemUtil.ts
src/Explorer/Notebook/NTeractUtil.ts
src/Explorer/Notebook/NotebookClientV2.ts
src/Explorer/Notebook/NotebookComponent/NotebookContentProvider.ts
src/Explorer/Notebook/NotebookComponent/__mocks__/rx-jupyter.ts
@@ -115,6 +112,7 @@ src/Explorer/Notebook/NotebookComponent/types.ts
src/Explorer/Notebook/NotebookContainerClient.ts
src/Explorer/Notebook/NotebookContentClient.ts
src/Explorer/Notebook/NotebookContentItem.ts
src/Explorer/Notebook/NotebookUtil.ts
src/Explorer/OpenActions.test.ts
src/Explorer/OpenActions.ts
src/Explorer/OpenActionsStubs.ts
@@ -250,8 +248,6 @@ src/Shared/ExplorerSettings.ts
src/Shared/PriceEstimateCalculator.ts
src/Shared/StorageUtility.test.ts
src/Shared/StorageUtility.ts
src/Shared/StringUtility.test.ts
src/Shared/StringUtility.ts
src/Shared/appInsights.ts
src/SparkClusterManager/ArcadiaResourceManager.ts
src/SparkClusterManager/SparkClusterManager.ts
@@ -262,7 +258,6 @@ src/TokenProviders/PortalTokenProvider.ts
src/TokenProviders/TokenProviderFactory.ts
src/Utils/DatabaseAccountUtils.test.ts
src/Utils/DatabaseAccountUtils.ts
src/Utils/NotebookConfigurationUtils.ts
src/Utils/PricingUtils.test.ts
src/Utils/QueryUtils.test.ts
src/Utils/QueryUtils.ts
@@ -315,15 +310,7 @@ src/Explorer/Graph/GraphExplorerComponent/QueryContainerComponent.tsx
src/Explorer/Graph/GraphExplorerComponent/ReadOnlyNeighborsComponent.tsx
src/Explorer/Graph/GraphExplorerComponent/ReadOnlyNodePropertiesComponent.test.tsx
src/Explorer/Graph/GraphExplorerComponent/ReadOnlyNodePropertiesComponent.tsx
src/Explorer/Menus/CommandBar/CommandBarComponentAdapter.tsx
src/Explorer/Menus/CommandBar/CommandBarUtil.test.tsx
src/Explorer/Menus/CommandBar/CommandBarUtil.tsx
src/Explorer/Menus/CommandBar/MemoryTrackerComponent.tsx
src/Explorer/Menus/NavBar/ControlBarComponent.tsx
src/Explorer/Menus/NavBar/ControlBarComponentAdapter.tsx
src/Explorer/Menus/NavBar/MeControlComponent.test.tsx
src/Explorer/Menus/NavBar/MeControlComponent.tsx
src/Explorer/Menus/NavBar/MeControlComponentAdapter.tsx
src/Explorer/Menus/NotificationConsole/NotificationConsoleComponent.test.tsx
src/Explorer/Menus/NotificationConsole/NotificationConsoleComponent.tsx
src/Explorer/Menus/NotificationConsole/NotificationConsoleComponentAdapter.tsx

View File

@@ -15,10 +15,10 @@ jobs:
if: github.ref == 'refs/heads/master'
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 12.x
node-version: 14.x
- run: npm ci
- run: node utils/codeMetrics.js
env:
@@ -28,10 +28,10 @@ jobs:
name: "Compile TypeScript"
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 12.x
node-version: 14.x
- run: npm ci
- run: npm run compile
- run: npm run compile:strict
@@ -40,10 +40,10 @@ jobs:
name: "Check Format"
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 12.x
node-version: 14.x
- run: npm ci
- run: npm run format:check
lint:
@@ -51,10 +51,10 @@ jobs:
name: "Lint"
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 12.x
node-version: 14.x
- run: npm ci
- run: npm run lint
unittest:
@@ -62,10 +62,10 @@ jobs:
name: "Unit Tests"
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 12.x
node-version: 14.x
- run: npm ci
- run: npm run test
build:
@@ -74,10 +74,10 @@ jobs:
name: "Build"
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 12.x
node-version: 14.x
- run: npm ci
- run: npm run build:contracts
- name: Restore Build Cache
@@ -94,14 +94,14 @@ jobs:
path: dist/
endtoendemulator:
name: "End To End Emulator Tests"
needs: [lint, format, compile, unittest]
if: github.ref == 'refs/heads/master' || contains(github.ref, 'hotfix/') || contains(github.ref, 'release/')
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 12.x
node-version: 14.x
- uses: southpolesteve/cosmos-emulator-github-action@v1
- name: End to End Tests
run: |
@@ -125,10 +125,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js 12.x
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 12.x
node-version: 14.x
- name: Accessibility Check
run: |
# Ubuntu gets mad when webpack runs too many files watchers
@@ -163,6 +163,7 @@ jobs:
TABLES_CONNECTION_STRING: ${{ secrets.CONNECTION_STRING_TABLE }}
DATA_EXPLORER_ENDPOINT: "https://localhost:1234/hostedExplorer.html"
strategy:
fail-fast: false
matrix:
test-file:
- ./test/cassandra/container.spec.ts

View File

@@ -17,5 +17,10 @@
"test/out/**": true,
"workers/libs/**": true
},
"typescript.tsdk": "node_modules/typescript/lib"
"typescript.tsdk": "node_modules/typescript/lib",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
"source.organizeImports": true
}
}

4
config.json Normal file
View File

@@ -0,0 +1,4 @@
{
"GITHUB_CLIENT_ID": "167ea4b09801db1de03d",
"GITHUB_CLIENT_SECRET": "e7bb10a3a8da428815805c6fc483560a035a73c1"
}

26411
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,10 @@
import * as Cosmos from "@azure/cosmos";
import { RequestInfo, setAuthorizationTokenHeaderUsingMasterKey } from "@azure/cosmos";
import { configContext, Platform } from "../ConfigContext";
import { getErrorMessage } from "./ErrorHandlingUtils";
import { userContext } from "../UserContext";
import { logConsoleError } from "../Utils/NotificationConsoleUtils";
import { EmulatorMasterKey, HttpHeaders } from "./Constants";
import { userContext } from "../UserContext";
import { getErrorMessage } from "./ErrorHandlingUtils";
const _global = typeof self === "undefined" ? window : self;

View File

@@ -1,8 +1,9 @@
import { ARMError } from "../Utils/arm/request";
import { HttpStatusCodes } from "./Constants";
import { MessageTypes } from "../Contracts/ExplorerContracts";
import { SubscriptionType } from "../Contracts/SubscriptionType";
import { userContext } from "../UserContext";
import { ARMError } from "../Utils/arm/request";
import { logConsoleError } from "../Utils/NotificationConsoleUtils";
import { HttpStatusCodes } from "./Constants";
import { logError } from "./Logger";
import { sendMessage } from "./MessageHandler";
@@ -44,7 +45,7 @@ const sendNotificationForError = (errorMessage: string, errorCode: number | stri
const replaceKnownError = (errorMessage: string): string => {
if (
window.dataExplorer?.subscriptionType() === SubscriptionType.Internal &&
userContext.subscriptionType === SubscriptionType.Internal &&
errorMessage?.indexOf("SharedOffer is Disabled for your account") >= 0
) {
return "Database throughput is not supported for internal subscriptions.";

View File

@@ -1,6 +1,8 @@
import { QueryResults } from "../Contracts/ViewModels";
interface QueryResponse {
// [Todo] remove any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resources: any[];
hasMoreResults: boolean;
activityId: string;
@@ -16,6 +18,7 @@ export interface MinimalQueryIterator {
export function nextPage(documentsIterator: MinimalQueryIterator, firstItemIndex: number): Promise<QueryResults> {
return documentsIterator.fetchNext().then((response) => {
const documents = response.resources;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const headers = (response as any).headers || {}; // TODO this is a private key. Remove any
const itemCount = (documents && documents.length) || 0;
return {

View File

@@ -9,10 +9,10 @@ export interface DatabaseAccount {
}
export interface DatabaseAccountExtendedProperties {
documentEndpoint: string;
tableEndpoint: string;
gremlinEndpoint: string;
cassandraEndpoint: string;
documentEndpoint?: string;
tableEndpoint?: string;
gremlinEndpoint?: string;
cassandraEndpoint?: string;
configurationOverrides?: ConfigurationOverrides;
capabilities?: Capability[];
enableMultipleWriteLocations?: boolean;

View File

@@ -0,0 +1,9 @@
/**
* Messaging types used with SelfServe Component <-> Portal communication
* and Hosted <-> SelfServe Component communication
*/
export enum SelfServeMessageTypes {
TelemetryInfo = "TelemetryInfo",
Notification = "Notification",
}

View File

@@ -393,7 +393,16 @@ export interface DataExplorerInputsFrame {
isAuthWithresourceToken?: boolean;
defaultCollectionThroughput?: CollectionCreationDefaults;
flights?: readonly string[];
selfServeType?: SelfServeType;
}
export interface SelfServeFrameInputs {
selfServeType: SelfServeType;
databaseAccount: any;
subscriptionId: string;
resourceGroup: string;
authorizationToken: string;
csmEndpoint: string;
flights?: readonly string[];
}
export interface CollectionCreationDefaults {

View File

@@ -11,7 +11,7 @@
.publicGalleryTabContainer {
position: relative;
height: 100vh;
min-height: 100vh;
}
.publicGalleryTabOverlayContent {

View File

@@ -388,7 +388,7 @@ export class GalleryViewerComponent extends React.Component<GalleryViewerCompone
private createSearchBarHeader(content: JSX.Element): JSX.Element {
return (
<Stack tokens={{ childrenGap: 10 }}>
<Stack horizontal tokens={{ childrenGap: 20, padding: 10 }}>
<Stack horizontal wrap tokens={{ childrenGap: 20, padding: 10 }}>
<Stack.Item grow>
<SearchBox value={this.state.searchText} placeholder="Search" onChange={this.onSearchBoxChange} />
</Stack.Item>

View File

@@ -36,6 +36,7 @@ exports[`GalleryViewerComponent renders 1`] = `
"padding": 10,
}
}
wrap={true}
>
<StackItem
grow={true}
@@ -121,6 +122,7 @@ exports[`GalleryViewerComponent renders 1`] = `
"padding": 10,
}
}
wrap={true}
>
<StackItem
grow={true}

View File

@@ -1060,14 +1060,6 @@ exports[`SettingsComponent renders 1`] = `
},
"selectedDatabaseId": [Function],
"selectedNode": [Function],
"selfServeComponentAdapter": SelfServeComponentAdapter {
"container": [Circular],
"parameters": [Function],
},
"selfServeLoadingComponentAdapter": SelfServeLoadingComponentAdapter {
"parameters": [Function],
},
"selfServeType": [Function],
"serverId": [Function],
"setInProgressConsoleDataIdToBeDeleted": undefined,
"setIsNotificationConsoleExpanded": undefined,
@@ -2269,14 +2261,6 @@ exports[`SettingsComponent renders 1`] = `
},
"selectedDatabaseId": [Function],
"selectedNode": [Function],
"selfServeComponentAdapter": SelfServeComponentAdapter {
"container": [Circular],
"parameters": [Function],
},
"selfServeLoadingComponentAdapter": SelfServeLoadingComponentAdapter {
"parameters": [Function],
},
"selfServeType": [Function],
"serverId": [Function],
"setInProgressConsoleDataIdToBeDeleted": undefined,
"setIsNotificationConsoleExpanded": undefined,
@@ -3491,14 +3475,6 @@ exports[`SettingsComponent renders 1`] = `
},
"selectedDatabaseId": [Function],
"selectedNode": [Function],
"selfServeComponentAdapter": SelfServeComponentAdapter {
"container": [Circular],
"parameters": [Function],
},
"selfServeLoadingComponentAdapter": SelfServeLoadingComponentAdapter {
"parameters": [Function],
},
"selfServeType": [Function],
"serverId": [Function],
"setInProgressConsoleDataIdToBeDeleted": undefined,
"setIsNotificationConsoleExpanded": undefined,
@@ -4700,14 +4676,6 @@ exports[`SettingsComponent renders 1`] = `
},
"selectedDatabaseId": [Function],
"selectedNode": [Function],
"selfServeComponentAdapter": SelfServeComponentAdapter {
"container": [Circular],
"parameters": [Function],
},
"selfServeLoadingComponentAdapter": SelfServeLoadingComponentAdapter {
"parameters": [Function],
},
"selfServeType": [Function],
"serverId": [Function],
"setInProgressConsoleDataIdToBeDeleted": undefined,
"setIsNotificationConsoleExpanded": undefined,

View File

@@ -1,7 +1,7 @@
import React from "react";
import { shallow } from "enzyme";
import { SmartUiComponent, SmartUiDescriptor } from "./SmartUiComponent";
import { NumberUiType, SmartUiInput } from "../../../SelfServe/SelfServeTypes";
import { NumberUiType, SmartUiInput, DescriptionType } from "../../../SelfServe/SelfServeTypes";
describe("SmartUiComponent", () => {
const exampleData: SmartUiDescriptor = {
@@ -18,10 +18,12 @@ describe("SmartUiComponent", () => {
{
id: "description",
input: {
labelTKey: undefined,
dataFieldName: "description",
type: "string",
description: {
textTKey: "this is an example description text.",
type: DescriptionType.Text,
link: {
href: "https://docs.microsoft.com/en-us/azure/cosmos-db/introduction",
textTKey: "Click here for more information.",

View File

@@ -6,12 +6,13 @@ import { Dropdown, IDropdownOption } from "office-ui-fabric-react/lib/Dropdown";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import { Text } from "office-ui-fabric-react/lib/Text";
import { Stack, IStackTokens } from "office-ui-fabric-react/lib/Stack";
import { Link, MessageBar, MessageBarType, Toggle } from "office-ui-fabric-react";
import { Label, Link, MessageBar, MessageBarType, Toggle } from "office-ui-fabric-react";
import * as InputUtils from "./InputUtils";
import "./SmartUiComponent.less";
import {
ChoiceItem,
Description,
DescriptionType,
Info,
InputType,
InputTypeValue,
@@ -19,6 +20,7 @@ import {
SmartUiInput,
} from "../../../SelfServe/SelfServeTypes";
import { TFunction } from "i18next";
import { ToolTipLabelComponent } from "../Settings/SettingsSubComponents/ToolTipLabelComponent";
/**
* Generic UX renderer
@@ -29,15 +31,14 @@ import { TFunction } from "i18next";
*/
interface BaseDisplay {
labelTKey: string;
dataFieldName: string;
errorMessage?: string;
type: InputTypeValue;
}
interface BaseInput extends BaseDisplay {
labelTKey: string;
placeholderTKey?: string;
errorMessage?: string;
}
/**
@@ -67,7 +68,8 @@ interface ChoiceInput extends BaseInput {
}
interface DescriptionDisplay extends BaseDisplay {
description: Description;
description?: Description;
isDynamicDescription?: boolean;
}
type AnyDisplay = NumberInput | BooleanInput | StringInput | ChoiceInput | DescriptionDisplay;
@@ -123,25 +125,27 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
private renderInfo(info: Info): JSX.Element {
return (
<MessageBar styles={{ root: { width: 400 } }}>
{this.props.getTranslation(info.messageTKey)}
info && (
<Text>
{this.props.getTranslation(info.messageTKey)}{" "}
{info.link && (
<Link href={info.link.href} target="_blank">
{this.props.getTranslation(info.link.textTKey)}
</Link>
)}
</MessageBar>
</Text>
)
);
}
private renderTextInput(input: StringInput): JSX.Element {
private renderTextInput(input: StringInput, labelId: string): JSX.Element {
const value = this.props.currentValues.get(input.dataFieldName)?.value as string;
const disabled = this.props.disabled || this.props.currentValues.get(input.dataFieldName)?.disabled;
return (
<div className="stringInputContainer">
<TextField
id={`${input.dataFieldName}-textField-input`}
label={this.props.getTranslation(input.labelTKey)}
aria-labelledby={labelId}
type="text"
value={value || ""}
placeholder={this.props.getTranslation(input.placeholderTKey)}
@@ -149,32 +153,35 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
onChange={(_, newValue) => this.props.onInputChange(input, newValue)}
styles={{
root: { width: 400 },
subComponentStyles: {
label: {
root: {
...SmartUiComponent.labelStyle,
fontWeight: 600,
},
},
},
}}
/>
</div>
);
}
private renderDescription(input: DescriptionDisplay): JSX.Element {
const description = input.description;
return (
<Text id={`${input.dataFieldName}-text-display`}>
{this.props.getTranslation(input.description.textTKey)}{" "}
private renderDescription(input: DescriptionDisplay, labelId: string): JSX.Element {
const dataFieldName = input.dataFieldName;
const description = input.description || (this.props.currentValues.get(dataFieldName)?.value as Description);
if (!description) {
return this.renderError("Description is not provided.");
}
const descriptionElement = (
<Text id={`${dataFieldName}-text-display`} aria-labelledby={labelId}>
{this.props.getTranslation(description.textTKey)}{" "}
{description.link && (
<Link target="_blank" href={input.description.link.href}>
{this.props.getTranslation(input.description.link.textTKey)}
<Link target="_blank" href={description.link.href}>
{this.props.getTranslation(description.link.textTKey)}
</Link>
)}
</Text>
);
if (description.type === DescriptionType.Text) {
return descriptionElement;
}
const messageBarType =
description.type === DescriptionType.InfoMessageBar ? MessageBarType.info : MessageBarType.warning;
return <MessageBar messageBarType={messageBarType}>{descriptionElement}</MessageBar>;
}
private clearError(dataFieldName: string): void {
@@ -220,13 +227,12 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
return undefined;
};
private renderNumberInput(input: NumberInput): JSX.Element {
private renderNumberInput(input: NumberInput, labelId: string): JSX.Element {
const { labelTKey, min, max, dataFieldName, step } = input;
const props = {
label: this.props.getTranslation(labelTKey),
min: min,
max: max,
ariaLabel: labelTKey,
ariaLabel: this.props.getTranslation(labelTKey),
step: step,
};
@@ -243,13 +249,8 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
onIncrement={(newValue) => this.onIncrement(input, newValue, props.step, props.max)}
onDecrement={(newValue) => this.onDecrement(input, newValue, props.step, props.min)}
labelPosition={Position.top}
aria-labelledby={labelId}
disabled={disabled}
styles={{
label: {
...SmartUiComponent.labelStyle,
fontWeight: 600,
},
}}
/>
{this.state.errors.has(dataFieldName) && (
<MessageBar messageBarType={MessageBarType.error}>Error: {this.state.errors.get(dataFieldName)}</MessageBar>
@@ -266,10 +267,6 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
onChange={(newValue) => this.props.onInputChange(input, newValue)}
styles={{
root: { width: 400 },
titleLabel: {
...SmartUiComponent.labelStyle,
fontWeight: 600,
},
valueLabel: SmartUiComponent.labelStyle,
}}
/>
@@ -280,13 +277,13 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
}
}
private renderBooleanInput(input: BooleanInput): JSX.Element {
private renderBooleanInput(input: BooleanInput, labelId: string): JSX.Element {
const value = this.props.currentValues.get(input.dataFieldName)?.value as boolean;
const disabled = this.props.disabled || this.props.currentValues.get(input.dataFieldName)?.disabled;
return (
<Toggle
id={`${input.dataFieldName}-toggle-input`}
label={this.props.getTranslation(input.labelTKey)}
aria-labelledby={labelId}
checked={value || false}
onText={this.props.getTranslation(input.trueLabelTKey)}
offText={this.props.getTranslation(input.falseLabelTKey)}
@@ -297,8 +294,8 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
);
}
private renderChoiceInput(input: ChoiceInput): JSX.Element {
const { labelTKey, defaultKey, dataFieldName, choices, placeholderTKey } = input;
private renderChoiceInput(input: ChoiceInput, labelId: string): JSX.Element {
const { defaultKey, dataFieldName, choices, placeholderTKey } = input;
const value = this.props.currentValues.get(dataFieldName)?.value as string;
const disabled = this.props.disabled || this.props.currentValues.get(dataFieldName)?.disabled;
let selectedKey = value ? value : defaultKey;
@@ -308,7 +305,7 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
return (
<Dropdown
id={`${input.dataFieldName}-dropdown-input`}
label={this.props.getTranslation(labelTKey)}
aria-labelledby={labelId}
selectedKey={selectedKey}
onChange={(_, item: IDropdownOption) => this.props.onInputChange(input, item.key.toString())}
placeholder={this.props.getTranslation(placeholderTKey)}
@@ -319,40 +316,53 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
}))}
styles={{
root: { width: 400 },
label: {
...SmartUiComponent.labelStyle,
fontWeight: 600,
},
dropdown: SmartUiComponent.labelStyle,
}}
/>
);
}
private renderError(input: AnyDisplay): JSX.Element {
return <MessageBar messageBarType={MessageBarType.error}>Error: {input.errorMessage}</MessageBar>;
private renderError(errorMessage: string): JSX.Element {
return <MessageBar messageBarType={MessageBarType.error}>Error: {errorMessage}</MessageBar>;
}
private renderDisplay(input: AnyDisplay): JSX.Element {
private renderDisplayWithInfoBubble(input: AnyDisplay, info: Info): JSX.Element {
if (input.errorMessage) {
return this.renderError(input);
return this.renderError(input.errorMessage);
}
const inputHidden = this.props.currentValues.get(input.dataFieldName)?.hidden;
if (inputHidden) {
return <></>;
}
const labelId = `${input.dataFieldName}-label`;
return (
<Stack>
{input.labelTKey && (
<Label id={labelId}>
<ToolTipLabelComponent
label={this.props.getTranslation(input.labelTKey)}
toolTipElement={this.renderInfo(info)}
/>
</Label>
)}
{this.renderDisplay(input, labelId)}
</Stack>
);
}
private renderDisplay(input: AnyDisplay, labelId: string): JSX.Element {
switch (input.type) {
case "string":
if ("description" in input) {
return this.renderDescription(input as DescriptionDisplay);
if ("description" in input || "isDynamicDescription" in input) {
return this.renderDescription(input as DescriptionDisplay, labelId);
}
return this.renderTextInput(input as StringInput);
return this.renderTextInput(input as StringInput, labelId);
case "number":
return this.renderNumberInput(input as NumberInput);
return this.renderNumberInput(input as NumberInput, labelId);
case "boolean":
return this.renderBooleanInput(input as BooleanInput);
return this.renderBooleanInput(input as BooleanInput, labelId);
case "object":
return this.renderChoiceInput(input as ChoiceInput);
return this.renderChoiceInput(input as ChoiceInput, labelId);
default:
throw new Error(`Unknown input type: ${input.type}`);
}
@@ -363,10 +373,7 @@ export class SmartUiComponent extends React.Component<SmartUiComponentProps, Sma
return (
<Stack tokens={containerStackTokens} className="widgetRendererContainer">
<Stack.Item>
{node.info && this.renderInfo(node.info as Info)}
{node.input && this.renderDisplay(node.input)}
</Stack.Item>
<Stack.Item>{node.input && this.renderDisplayWithInfoBubble(node.input, node.info as Info)}</Stack.Item>
{node.children && node.children.map((child) => <div key={child.id}>{this.renderNode(child)}</div>)}
</Stack>
);

View File

@@ -9,25 +9,7 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
}
>
<StackItem>
<StyledMessageBarBase
styles={
Object {
"root": Object {
"width": 400,
},
}
}
>
Start at $24/mo per database
<StyledLinkBase
href="https://aka.ms/azure-cosmos-db-pricing"
target="_blank"
>
More Details
</StyledLinkBase>
</StyledMessageBarBase>
</StackItem>
<StackItem />
<div
key="description"
>
@@ -40,7 +22,9 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
>
<StackItem>
<Stack>
<Text
aria-labelledby="description-label"
id="description-text-display"
>
this is an example description text.
@@ -52,6 +36,7 @@ exports[`SmartUiComponent disable all inputs 1`] = `
Click here for more information.
</StyledLinkBase>
</Text>
</Stack>
</StackItem>
</Stack>
</div>
@@ -67,6 +52,14 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="throughput-label"
>
<ToolTipLabelComponent
label="Throughput (input)"
/>
</StyledLabelBase>
<Stack
styles={
Object {
@@ -82,6 +75,7 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
>
<CustomizedSpinButton
aria-labelledby="throughput-label"
ariaLabel="Throughput (input)"
decrementButtonIcon={
Object {
@@ -95,7 +89,7 @@ exports[`SmartUiComponent disable all inputs 1`] = `
"iconName": "ChevronUpSmall",
}
}
label="Throughput (input)"
label=""
labelPosition={0}
max={500}
min={400}
@@ -103,18 +97,9 @@ exports[`SmartUiComponent disable all inputs 1`] = `
onIncrement={[Function]}
onValidate={[Function]}
step={10}
styles={
Object {
"label": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
"fontWeight": 600,
},
}
}
/>
</Stack>
</Stack>
</StackItem>
</Stack>
</div>
@@ -130,13 +115,20 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="throughput2-label"
>
<ToolTipLabelComponent
label="Throughput (Slider)"
/>
</StyledLabelBase>
<div
id="throughput2-slider-input"
>
<StyledSliderBase
ariaLabel="Throughput (Slider)"
disabled={true}
label="Throughput (Slider)"
max={500}
min={400}
onChange={[Function]}
@@ -146,12 +138,6 @@ exports[`SmartUiComponent disable all inputs 1`] = `
"root": Object {
"width": 400,
},
"titleLabel": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
"fontWeight": 600,
},
"valueLabel": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
@@ -161,6 +147,7 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
/>
</div>
</Stack>
</StackItem>
</Stack>
</div>
@@ -197,35 +184,34 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="containerId-label"
>
<ToolTipLabelComponent
label="Container id"
/>
</StyledLabelBase>
<div
className="stringInputContainer"
>
<StyledTextFieldBase
aria-labelledby="containerId-label"
disabled={true}
id="containerId-textField-input"
label="Container id"
onChange={[Function]}
styles={
Object {
"root": Object {
"width": 400,
},
"subComponentStyles": Object {
"label": Object {
"root": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
"fontWeight": 600,
},
},
},
}
}
type="text"
value=""
/>
</div>
</Stack>
</StackItem>
</Stack>
</div>
@@ -241,11 +227,19 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="analyticalStore-label"
>
<ToolTipLabelComponent
label="Analytical Store"
/>
</StyledLabelBase>
<StyledToggleBase
aria-labelledby="analyticalStore-label"
checked={false}
disabled={true}
id="analyticalStore-toggle-input"
label="Analytical Store"
offText="Disabled"
onChange={[Function]}
onText="Enabled"
@@ -257,6 +251,7 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
}
/>
</Stack>
</StackItem>
</Stack>
</div>
@@ -272,10 +267,18 @@ exports[`SmartUiComponent disable all inputs 1`] = `
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="database-label"
>
<ToolTipLabelComponent
label="Database"
/>
</StyledLabelBase>
<StyledWithResponsiveMode
aria-labelledby="database-label"
disabled={true}
id="database-dropdown-input"
label="Database"
onChange={[Function]}
options={
Array [
@@ -301,18 +304,13 @@ exports[`SmartUiComponent disable all inputs 1`] = `
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
},
"label": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
"fontWeight": 600,
},
"root": Object {
"width": 400,
},
}
}
/>
</Stack>
</StackItem>
</Stack>
</div>
@@ -328,25 +326,7 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
}
>
<StackItem>
<StyledMessageBarBase
styles={
Object {
"root": Object {
"width": 400,
},
}
}
>
Start at $24/mo per database
<StyledLinkBase
href="https://aka.ms/azure-cosmos-db-pricing"
target="_blank"
>
More Details
</StyledLinkBase>
</StyledMessageBarBase>
</StackItem>
<StackItem />
<div
key="description"
>
@@ -359,7 +339,9 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
>
<StackItem>
<Stack>
<Text
aria-labelledby="description-label"
id="description-text-display"
>
this is an example description text.
@@ -371,6 +353,7 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
Click here for more information.
</StyledLinkBase>
</Text>
</Stack>
</StackItem>
</Stack>
</div>
@@ -386,6 +369,14 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="throughput-label"
>
<ToolTipLabelComponent
label="Throughput (input)"
/>
</StyledLabelBase>
<Stack
styles={
Object {
@@ -401,6 +392,7 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
>
<CustomizedSpinButton
aria-labelledby="throughput-label"
ariaLabel="Throughput (input)"
decrementButtonIcon={
Object {
@@ -414,7 +406,7 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
"iconName": "ChevronUpSmall",
}
}
label="Throughput (input)"
label=""
labelPosition={0}
max={500}
min={400}
@@ -422,18 +414,9 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
onIncrement={[Function]}
onValidate={[Function]}
step={10}
styles={
Object {
"label": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
"fontWeight": 600,
},
}
}
/>
</Stack>
</Stack>
</StackItem>
</Stack>
</div>
@@ -449,12 +432,19 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="throughput2-label"
>
<ToolTipLabelComponent
label="Throughput (Slider)"
/>
</StyledLabelBase>
<div
id="throughput2-slider-input"
>
<StyledSliderBase
ariaLabel="Throughput (Slider)"
label="Throughput (Slider)"
max={500}
min={400}
onChange={[Function]}
@@ -464,12 +454,6 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
"root": Object {
"width": 400,
},
"titleLabel": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
"fontWeight": 600,
},
"valueLabel": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
@@ -479,6 +463,7 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
/>
</div>
</Stack>
</StackItem>
</Stack>
</div>
@@ -515,34 +500,33 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="containerId-label"
>
<ToolTipLabelComponent
label="Container id"
/>
</StyledLabelBase>
<div
className="stringInputContainer"
>
<StyledTextFieldBase
aria-labelledby="containerId-label"
id="containerId-textField-input"
label="Container id"
onChange={[Function]}
styles={
Object {
"root": Object {
"width": 400,
},
"subComponentStyles": Object {
"label": Object {
"root": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
"fontWeight": 600,
},
},
},
}
}
type="text"
value=""
/>
</div>
</Stack>
</StackItem>
</Stack>
</div>
@@ -558,10 +542,18 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
>
<StackItem>
<Stack>
<StyledLabelBase
id="analyticalStore-label"
>
<ToolTipLabelComponent
label="Analytical Store"
/>
</StyledLabelBase>
<StyledToggleBase
aria-labelledby="analyticalStore-label"
checked={false}
id="analyticalStore-toggle-input"
label="Analytical Store"
offText="Disabled"
onChange={[Function]}
onText="Enabled"
@@ -573,6 +565,7 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
}
/>
</Stack>
</StackItem>
</Stack>
</div>
@@ -588,9 +581,17 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
}
>
<StackItem>
<StyledWithResponsiveMode
id="database-dropdown-input"
<Stack>
<StyledLabelBase
id="database-label"
>
<ToolTipLabelComponent
label="Database"
/>
</StyledLabelBase>
<StyledWithResponsiveMode
aria-labelledby="database-label"
id="database-dropdown-input"
onChange={[Function]}
options={
Array [
@@ -616,18 +617,13 @@ exports[`SmartUiComponent should render and honor input's hidden, disabled state
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
},
"label": Object {
"color": "#393939",
"fontFamily": "wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif",
"fontSize": 12,
"fontWeight": 600,
},
"root": Object {
"width": 400,
},
}
}
/>
</Stack>
</StackItem>
</Stack>
</div>

View File

@@ -129,7 +129,6 @@ export interface ThroughputInputParams {
throughputModeRadioName: string;
maxAutoPilotThroughputSet: ViewModels.Editable<number>;
autoPilotUsageCost: ko.Computed<string>;
showAutoPilot?: ko.Observable<boolean>;
overrideWithAutoPilotSettings: ko.Observable<boolean>;
overrideWithProvisionedThroughputSettings: ko.Observable<boolean>;
freeTierExceedThroughputTooltip?: ko.Observable<string>;
@@ -158,7 +157,6 @@ export class ThroughputInputViewModel extends WaitsForTemplateViewModel {
public infoBubbleText: string | ko.Observable<string>;
public label: ko.Observable<string>;
public isFixed: boolean;
public showAutoPilot: ko.Observable<boolean>;
public isAutoPilotSelected: ko.Observable<boolean>;
public throughputAutoPilotRadioId: string;
public throughputProvisionedRadioId: string;
@@ -202,7 +200,6 @@ export class ThroughputInputViewModel extends WaitsForTemplateViewModel {
this.isFixed = !!options.isFixed;
this.infoBubbleText = options.infoBubbleText || ko.observable<string>();
this.label = options.label || ko.observable<string>();
this.showAutoPilot = options.showAutoPilot !== undefined ? options.showAutoPilot : ko.observable<boolean>(true);
this.isAutoPilotSelected = options.isAutoPilotSelected || ko.observable<boolean>(false);
this.isAutoPilotSelected.subscribe((value) => {
TelemetryProcessor.trace(Action.ToggleAutoscaleSetting, ActionModifiers.Mark, {

View File

@@ -17,7 +17,7 @@
</div>
<!-- ko if: !isFixed -->
<div data-bind="visible: showAutoPilot" class="throughputModeContainer">
<div class="throughputModeContainer">
<input
class="throughputModeRadio"
aria-label="Autopilot mode"

View File

@@ -1,93 +1,87 @@
import React from "react";
import * as ComponentRegisterer from "./ComponentRegisterer";
import * as Constants from "../Common/Constants";
import * as DataModels from "../Contracts/DataModels";
import * as ko from "knockout";
import { IChoiceGroupProps } from "office-ui-fabric-react";
import * as path from "path";
import * as SharedConstants from "../Shared/Constants";
import * as ViewModels from "../Contracts/ViewModels";
import _ from "underscore";
import AddCollectionPane from "./Panes/AddCollectionPane";
import AddDatabasePane from "./Panes/AddDatabasePane";
import AddTableEntityPane from "./Panes/Tables/AddTableEntityPane";
import AuthHeadersUtil from "../Platform/Hosted/Authorization";
import CassandraAddCollectionPane from "./Panes/CassandraAddCollectionPane";
import Database from "./Tree/Database";
import DeleteCollectionConfirmationPane from "./Panes/DeleteCollectionConfirmationPane";
import DeleteDatabaseConfirmationPane from "./Panes/DeleteDatabaseConfirmationPane";
import { readCollection } from "../Common/dataAccess/readCollection";
import { readDatabases } from "../Common/dataAccess/readDatabases";
import EditTableEntityPane from "./Panes/Tables/EditTableEntityPane";
import { normalizeArmEndpoint } from "../Common/EnvironmentUtility";
import GraphStylingPane from "./Panes/GraphStylingPane";
import NewVertexPane from "./Panes/NewVertexPane";
import NotebookV2Tab, { NotebookTabOptions } from "./Tabs/NotebookV2Tab";
import Q from "q";
import ResourceTokenCollection from "./Tree/ResourceTokenCollection";
import * as TelemetryProcessor from "../Shared/Telemetry/TelemetryProcessor";
import TerminalTab from "./Tabs/TerminalTab";
import { Action, ActionModifiers } from "../Shared/Telemetry/TelemetryConstants";
import { MessageTypes } from "../Contracts/ExplorerContracts";
import { ArcadiaResourceManager } from "../SparkClusterManager/ArcadiaResourceManager";
import { ArcadiaWorkspaceItem } from "./Controls/Arcadia/ArcadiaMenuPicker";
import React from "react";
import _ from "underscore";
import { AuthType } from "../AuthType";
import { BindingHandlersRegisterer } from "../Bindings/BindingHandlersRegisterer";
import { BrowseQueriesPane } from "./Panes/BrowseQueriesPane";
import { CassandraAPIDataClient, TableDataClient, TablesAPIDataClient } from "./Tables/TableDataClient";
import { CommandBarComponentAdapter } from "./Menus/CommandBar/CommandBarComponentAdapter";
import { configContext, Platform, updateConfigContext } from "../ConfigContext";
import { ConsoleData, ConsoleDataType } from "./Menus/NotificationConsole/NotificationConsoleComponent";
import { decryptJWTToken, getAuthorizationHeader } from "../Utils/AuthorizationUtils";
import { DefaultExperienceUtility } from "../Shared/DefaultExperienceUtility";
import { DialogProps, TextFieldProps } from "./Controls/Dialog";
import { ExecuteSprocParamsPane } from "./Panes/ExecuteSprocParamsPane";
import { ReactAdapter } from "../Bindings/ReactBindingHandler";
import * as Constants from "../Common/Constants";
import { ExplorerMetrics } from "../Common/Constants";
import { ExplorerSettings } from "../Shared/ExplorerSettings";
import { FileSystemUtil } from "./Notebook/FileSystemUtil";
import { IGalleryItem } from "../Juno/JunoClient";
import { LoadQueryPane } from "./Panes/LoadQueryPane";
import { readCollection } from "../Common/dataAccess/readCollection";
import { readDatabases } from "../Common/dataAccess/readDatabases";
import { getErrorMessage, getErrorStack, handleError } from "../Common/ErrorHandlingUtils";
import * as Logger from "../Common/Logger";
import { sendMessage, sendCachedDataMessage } from "../Common/MessageHandler";
import { NotebookContentItem, NotebookContentItemType } from "./Notebook/NotebookContentItem";
import * as NotebookUtil from "./Notebook/NotebookUtil";
import { NotebookWorkspaceManager } from "../NotebookWorkspaceManager/NotebookWorkspaceManager";
import * as NotificationConsoleUtils from "../Utils/NotificationConsoleUtils";
import { sendCachedDataMessage, sendMessage } from "../Common/MessageHandler";
import { QueriesClient } from "../Common/QueriesClient";
import { QuerySelectPane } from "./Panes/Tables/QuerySelectPane";
import { Splitter, SplitterBounds, SplitterDirection } from "../Common/Splitter";
import { configContext, Platform } from "../ConfigContext";
import * as DataModels from "../Contracts/DataModels";
import { MessageTypes } from "../Contracts/ExplorerContracts";
import { SubscriptionType } from "../Contracts/SubscriptionType";
import * as ViewModels from "../Contracts/ViewModels";
import { IGalleryItem } from "../Juno/JunoClient";
import { NotebookWorkspaceManager } from "../NotebookWorkspaceManager/NotebookWorkspaceManager";
import { ResourceProviderClientFactory } from "../ResourceProvider/ResourceProviderClientFactory";
import { ResourceTreeAdapter } from "./Tree/ResourceTreeAdapter";
import { ResourceTreeAdapterForResourceToken } from "./Tree/ResourceTreeAdapterForResourceToken";
import { RouteHandler } from "../RouteHandlers/RouteHandler";
import { appInsights } from "../Shared/appInsights";
import * as SharedConstants from "../Shared/Constants";
import { DefaultExperienceUtility } from "../Shared/DefaultExperienceUtility";
import { ExplorerSettings } from "../Shared/ExplorerSettings";
import { Action, ActionModifiers } from "../Shared/Telemetry/TelemetryConstants";
import * as TelemetryProcessor from "../Shared/Telemetry/TelemetryProcessor";
import { ArcadiaResourceManager } from "../SparkClusterManager/ArcadiaResourceManager";
import { updateUserContext, userContext } from "../UserContext";
import { decryptJWTToken, getAuthorizationHeader } from "../Utils/AuthorizationUtils";
import { stringToBlob } from "../Utils/BlobUtils";
import { fromContentUri, toRawContentUri } from "../Utils/GitHubUtils";
import * as NotificationConsoleUtils from "../Utils/NotificationConsoleUtils";
import * as ComponentRegisterer from "./ComponentRegisterer";
import { ArcadiaWorkspaceItem } from "./Controls/Arcadia/ArcadiaMenuPicker";
import { CommandButtonComponentProps } from "./Controls/CommandButton/CommandButtonComponent";
import { DialogProps, TextFieldProps } from "./Controls/Dialog";
import { GalleryTab } from "./Controls/NotebookGallery/GalleryViewerComponent";
import { CommandBarComponentAdapter } from "./Menus/CommandBar/CommandBarComponentAdapter";
import { ConsoleData, ConsoleDataType } from "./Menus/NotificationConsole/NotificationConsoleComponent";
import { FileSystemUtil } from "./Notebook/FileSystemUtil";
import { NotebookContentItem, NotebookContentItemType } from "./Notebook/NotebookContentItem";
import { NotebookUtil } from "./Notebook/NotebookUtil";
import AddCollectionPane from "./Panes/AddCollectionPane";
import AddDatabasePane from "./Panes/AddDatabasePane";
import { BrowseQueriesPane } from "./Panes/BrowseQueriesPane";
import CassandraAddCollectionPane from "./Panes/CassandraAddCollectionPane";
import { ContextualPaneBase } from "./Panes/ContextualPaneBase";
import DeleteCollectionConfirmationPane from "./Panes/DeleteCollectionConfirmationPane";
import { DeleteCollectionConfirmationPanel } from "./Panes/DeleteCollectionConfirmationPanel";
import DeleteDatabaseConfirmationPane from "./Panes/DeleteDatabaseConfirmationPane";
import { ExecuteSprocParamsPane } from "./Panes/ExecuteSprocParamsPane";
import GraphStylingPane from "./Panes/GraphStylingPane";
import { LoadQueryPane } from "./Panes/LoadQueryPane";
import NewVertexPane from "./Panes/NewVertexPane";
import { SaveQueryPane } from "./Panes/SaveQueryPane";
import { SettingsPane } from "./Panes/SettingsPane";
import { SetupNotebooksPane } from "./Panes/SetupNotebooksPane";
import { SplashScreen } from "./SplashScreen/SplashScreen";
import { Splitter, SplitterBounds, SplitterDirection } from "../Common/Splitter";
import { StringInputPane } from "./Panes/StringInputPane";
import AddTableEntityPane from "./Panes/Tables/AddTableEntityPane";
import EditTableEntityPane from "./Panes/Tables/EditTableEntityPane";
import { QuerySelectPane } from "./Panes/Tables/QuerySelectPane";
import { TableColumnOptionsPane } from "./Panes/Tables/TableColumnOptionsPane";
import { TabsManager } from "./Tabs/TabsManager";
import { UploadFilePane } from "./Panes/UploadFilePane";
import { UploadItemsPane } from "./Panes/UploadItemsPane";
import { UploadItemsPaneAdapter } from "./Panes/UploadItemsPaneAdapter";
import { ReactAdapter } from "../Bindings/ReactBindingHandler";
import { toRawContentUri, fromContentUri } from "../Utils/GitHubUtils";
import UserDefinedFunction from "./Tree/UserDefinedFunction";
import { CassandraAPIDataClient, TableDataClient, TablesAPIDataClient } from "./Tables/TableDataClient";
import NotebookV2Tab, { NotebookTabOptions } from "./Tabs/NotebookV2Tab";
import TabsBase from "./Tabs/TabsBase";
import { TabsManager } from "./Tabs/TabsManager";
import TerminalTab from "./Tabs/TerminalTab";
import Database from "./Tree/Database";
import ResourceTokenCollection from "./Tree/ResourceTokenCollection";
import { ResourceTreeAdapter } from "./Tree/ResourceTreeAdapter";
import { ResourceTreeAdapterForResourceToken } from "./Tree/ResourceTreeAdapterForResourceToken";
import StoredProcedure from "./Tree/StoredProcedure";
import Trigger from "./Tree/Trigger";
import { ContextualPaneBase } from "./Panes/ContextualPaneBase";
import TabsBase from "./Tabs/TabsBase";
import { CommandButtonComponentProps } from "./Controls/CommandButton/CommandButtonComponent";
import { updateUserContext, userContext } from "../UserContext";
import { stringToBlob } from "../Utils/BlobUtils";
import { IChoiceGroupProps } from "office-ui-fabric-react";
import { getErrorMessage, handleError, getErrorStack } from "../Common/ErrorHandlingUtils";
import { SubscriptionType } from "../Contracts/SubscriptionType";
import { appInsights } from "../Shared/appInsights";
import { SelfServeLoadingComponentAdapter } from "../SelfServe/SelfServeLoadingComponentAdapter";
import { SelfServeType } from "../SelfServe/SelfServeUtils";
import { SelfServeComponentAdapter } from "../SelfServe/SelfServeComponentAdapter";
import { GalleryTab } from "./Controls/NotebookGallery/GalleryViewerComponent";
import { DeleteCollectionConfirmationPanel } from "./Panes/DeleteCollectionConfirmationPanel";
import UserDefinedFunction from "./Tree/UserDefinedFunction";
BindingHandlersRegisterer.registerBindingHandlers();
// Hold a reference to ComponentRegisterer to prevent transpiler to ignore import
@@ -118,20 +112,55 @@ export default class Explorer {
public hasWriteAccess: ko.Observable<boolean>;
public collapsedResourceTreeWidth: number = ExplorerMetrics.CollapsedResourceTreeWidth;
/**
* @deprecated
* Use userContext.databaseAccount instead
* */
public databaseAccount: ko.Observable<DataModels.DatabaseAccount>;
public collectionCreationDefaults: ViewModels.CollectionCreationDefaults = SharedConstants.CollectionCreationDefaults;
/**
* @deprecated
* Use userContext.subscriptionType instead
* */
public subscriptionType: ko.Observable<SubscriptionType>;
/**
* @deprecated
* Use userContext.apiType instead
* */
public defaultExperience: ko.Observable<string>;
/**
* @deprecated
* Compare a string with userContext.apiType instead: userContext.apiType === "SQL"
* */
public isPreferredApiDocumentDB: ko.Computed<boolean>;
/**
* @deprecated
* Compare a string with userContext.apiType instead: userContext.apiType === "Cassandra"
* */
public isPreferredApiCassandra: ko.Computed<boolean>;
/**
* @deprecated
* Compare a string with userContext.apiType instead: userContext.apiType === "Mongo"
* */
public isPreferredApiMongoDB: ko.Computed<boolean>;
/**
* @deprecated
* Compare a string with userContext.apiType instead: userContext.apiType === "Gremlin"
* */
public isPreferredApiGraph: ko.Computed<boolean>;
/**
* @deprecated
* Compare a string with userContext.apiType instead: userContext.apiType === "Tables"
* */
public isPreferredApiTable: ko.Computed<boolean>;
public isFixedCollectionWithSharedThroughputSupported: ko.Computed<boolean>;
/**
* @deprecated
* Compare a string with userContext.apiType instead: userContext.apiType === "Mongo"
* */
public isEnableMongoCapabilityPresent: ko.Computed<boolean>;
public isServerlessEnabled: ko.Computed<boolean>;
public isAccountReady: ko.Observable<boolean>;
public selfServeType: ko.Observable<SelfServeType>;
public canSaveQueries: ko.Computed<boolean>;
public features: ko.Observable<any>;
public serverId: ko.Observable<string>;
@@ -157,9 +186,12 @@ export default class Explorer {
public selectedCollectionId: ko.Computed<string>;
public isLeftPaneExpanded: ko.Observable<boolean>;
public selectedNode: ko.Observable<ViewModels.TreeNode>;
/**
* @deprecated
* Use a local loading state and spinner instead. Using a global isRefreshing state causes problems.
* */
public isRefreshingExplorer: ko.Observable<boolean>;
private resourceTree: ResourceTreeAdapter;
private selfServeComponentAdapter: SelfServeComponentAdapter;
// Resource Token
public resourceTokenDatabaseId: ko.Observable<string>;
@@ -243,7 +275,6 @@ export default class Explorer {
// React adapters
private commandBarComponentAdapter: CommandBarComponentAdapter;
private selfServeLoadingComponentAdapter: SelfServeLoadingComponentAdapter;
private static readonly MaxNbDatabasesToAutoExpand = 5;
@@ -287,7 +318,6 @@ export default class Explorer {
}
});
this.isAccountReady = ko.observable<boolean>(false);
this.selfServeType = ko.observable<SelfServeType>(undefined);
this._isInitializingNotebooks = false;
this.arcadiaToken = ko.observable<string>();
this.arcadiaToken.subscribe((token: string) => {
@@ -439,6 +469,7 @@ export default class Explorer {
databaseAccount
);
this.defaultExperience(defaultExperience);
// TODO. Remove this entirely
updateUserContext({
defaultExperience: DefaultExperienceUtility.mapDefaultExperienceStringToEnum(defaultExperience),
});
@@ -662,7 +693,6 @@ export default class Explorer {
});
this.uploadItemsPaneAdapter = new UploadItemsPaneAdapter(this);
this.selfServeComponentAdapter = new SelfServeComponentAdapter(this);
this.loadQueryPane = new LoadQueryPane({
id: "loadquerypane",
@@ -745,14 +775,8 @@ export default class Explorer {
$(document.body).click(() => $(".commandDropdownContainer").hide());
});
// TODO move this to API customization class
this.defaultExperience.subscribe((defaultExperience) => {
const defaultExperienceNormalizedString = (
defaultExperience || Constants.DefaultAccountExperience.Default
).toLowerCase();
switch (defaultExperienceNormalizedString) {
case Constants.DefaultAccountExperience.DocumentDB.toLowerCase():
switch (userContext.apiType) {
case "SQL":
this.addCollectionText("New Container");
this.addDatabaseText("New Database");
this.collectionTitle("SQL API");
@@ -768,8 +792,7 @@ export default class Explorer {
this.deleteCollectionConfirmationPane.collectionIdConfirmationText("Confirm by typing the container id");
this.refreshTreeTitle("Refresh containers");
break;
case Constants.DefaultAccountExperience.MongoDB.toLowerCase():
case Constants.DefaultAccountExperience.ApiForMongoDB.toLowerCase():
case "Mongo":
this.addCollectionText("New Collection");
this.addDatabaseText("New Database");
this.collectionTitle("Collections");
@@ -783,7 +806,7 @@ export default class Explorer {
);
this.refreshTreeTitle("Refresh collections");
break;
case Constants.DefaultAccountExperience.Graph.toLowerCase():
case "Gremlin":
this.addCollectionText("New Graph");
this.addDatabaseText("New Database");
this.deleteCollectionText("Delete Graph");
@@ -797,7 +820,7 @@ export default class Explorer {
this.deleteCollectionConfirmationPane.collectionIdConfirmationText("Confirm by typing the graph id");
this.refreshTreeTitle("Refresh graphs");
break;
case Constants.DefaultAccountExperience.Table.toLowerCase():
case "Tables":
this.addCollectionText("New Table");
this.addDatabaseText("New Database");
this.deleteCollectionText("Delete Table");
@@ -814,7 +837,7 @@ export default class Explorer {
this.deleteCollectionConfirmationPane.collectionIdConfirmationText("Confirm by typing the table id");
this.tableDataClient = new TablesAPIDataClient();
break;
case Constants.DefaultAccountExperience.Cassandra.toLowerCase():
case "Cassandra":
this.addCollectionText("New Table");
this.addDatabaseText("New Keyspace");
this.deleteCollectionText("Delete Table");
@@ -834,10 +857,8 @@ export default class Explorer {
this.tableDataClient = new CassandraAPIDataClient();
break;
}
});
this.commandBarComponentAdapter = new CommandBarComponentAdapter(this);
this.selfServeLoadingComponentAdapter = new SelfServeLoadingComponentAdapter();
this._initSettings();
@@ -1407,20 +1428,6 @@ export default class Explorer {
return false;
}
public setSelfServeType(inputs: ViewModels.DataExplorerInputsFrame): void {
const selfServeFeature = inputs.features[Constants.Features.selfServeType];
if (selfServeFeature) {
// self serve type received from query string
const selfServeType = SelfServeType[selfServeFeature?.toLowerCase() as keyof typeof SelfServeType];
this.selfServeType(selfServeType ? selfServeType : SelfServeType.invalid);
} else if (inputs.selfServeType) {
// self serve type received from portal
this.selfServeType(inputs.selfServeType);
} else {
this.selfServeType(SelfServeType.none);
}
}
public configure(inputs: ViewModels.DataExplorerInputsFrame): void {
if (inputs != null) {
// In development mode, save the iframe message from the portal in session storage.
@@ -1429,8 +1436,6 @@ export default class Explorer {
sessionStorage.setItem("portalDataExplorerInitMessage", JSON.stringify(inputs));
}
const authorizationToken = inputs.authorizationToken || "";
const masterKey = inputs.masterKey || "";
const databaseAccount = inputs.databaseAccount || null;
if (inputs.defaultCollectionThroughput) {
this.collectionCreationDefaults = inputs.defaultCollectionThroughput;
@@ -1446,22 +1451,6 @@ export default class Explorer {
this.isTryCosmosDBSubscription(inputs.isTryCosmosDBSubscription ?? false);
this.isAuthWithResourceToken(inputs.isAuthWithresourceToken ?? false);
this.setFeatureFlagsFromFlights(inputs.flights);
this.setSelfServeType(inputs);
updateConfigContext({
BACKEND_ENDPOINT: inputs.extensionEndpoint || configContext.BACKEND_ENDPOINT,
ARM_ENDPOINT: normalizeArmEndpoint(inputs.csmEndpoint || configContext.ARM_ENDPOINT),
});
updateUserContext({
authorizationToken,
masterKey,
databaseAccount,
resourceGroup: inputs.resourceGroup,
subscriptionId: inputs.subscriptionId,
subscriptionType: inputs.subscriptionType,
quotaId: inputs.quotaId,
});
TelemetryProcessor.traceSuccess(
Action.LoadDatabaseAccount,
{

View File

@@ -0,0 +1,107 @@
/**
* This adapter is responsible to render the React component
* If the component signals a change through the callback passed in the properties, it must render the React component when appropriate
* and update any knockout observables passed from the parent.
*/
import * as ko from "knockout";
import { CommandBar, ICommandBarItemProps } from "office-ui-fabric-react/lib/CommandBar";
import * as React from "react";
import { StyleConstants } from "../../../Common/Constants";
import { CommandButtonComponentProps } from "../../Controls/CommandButton/CommandButtonComponent";
import * as CommandBarComponentButtonFactory from "./CommandBarComponentButtonFactory";
import * as CommandBarUtil from "./CommandBarUtil";
export interface CommandBarComponentProps {
isNotebookTabActive: boolean;
tabsButtons: CommandButtonComponentProps[];
}
export const CommandBarComponent: React.FunctionComponent = ({ isNotebookTabActive, tabsButtons }: CommandBarComponentProps) {
constructor(props: CommandBarComponentProps) {
super(props);
this.state = {
isNotebookTabActive: false
}
this.container = container;
this.tabsButtons = [];
// this.isNotebookTabActive = ko.computed(() =>
// container.tabsManager.isTabActive(ViewModels.CollectionTabKind.NotebookV2)
// );
// These are the parameters watched by the react binding that will trigger a renderComponent() if one of the ko mutates
const toWatch = [
container.isPreferredApiTable,
container.isPreferredApiMongoDB,
container.isPreferredApiDocumentDB,
container.isPreferredApiCassandra,
container.isPreferredApiGraph,
container.deleteCollectionText,
container.deleteDatabaseText,
container.addCollectionText,
container.addDatabaseText,
container.isDatabaseNodeOrNoneSelected,
container.isDatabaseNodeSelected,
container.isNoneSelected,
container.isResourceTokenCollectionNodeSelected,
container.isHostedDataExplorerEnabled,
container.isSynapseLinkUpdating,
container.databaseAccount,
this.isNotebookTabActive,
container.isServerlessEnabled,
];
ko.computed(() => ko.toJSON(toWatch)).subscribe(() => this.triggerRender());
this.parameters = ko.observable(Date.now());
}
public onUpdateTabsButtons(buttons: CommandButtonComponentProps[]): void {
this.tabsButtons = buttons;
this.triggerRender();
}
const backgroundColor = StyleConstants.BaseLight;
const staticButtons = CommandBarComponentButtonFactory.createStaticCommandBarButtons(this.container);
const contextButtons = (this.tabsButtons || []).concat(
CommandBarComponentButtonFactory.createContextCommandBarButtons(this.container)
);
const controlButtons = CommandBarComponentButtonFactory.createControlCommandBarButtons(this.container);
const uiFabricStaticButtons = CommandBarUtil.convertButton(staticButtons, backgroundColor);
if (this.tabsButtons && this.tabsButtons.length > 0) {
uiFabricStaticButtons.forEach((btn: ICommandBarItemProps) => (btn.iconOnly = true));
}
const uiFabricTabsButtons: ICommandBarItemProps[] = CommandBarUtil.convertButton(contextButtons, backgroundColor);
if (uiFabricTabsButtons.length > 0) {
uiFabricStaticButtons.push(CommandBarUtil.createDivider("commandBarDivider"));
}
const uiFabricControlButtons = CommandBarUtil.convertButton(controlButtons, backgroundColor);
uiFabricControlButtons.forEach((btn: ICommandBarItemProps) => (btn.iconOnly = true));
if (props.isNotebookTabActive) {
uiFabricControlButtons.unshift(
CommandBarUtil.createMemoryTracker("memoryTracker", this.container.memoryUsageInfo)
);
}
return (
<React.Fragment>
<div className="commandBarContainer">
<CommandBar
ariaLabel="Use left and right arrow keys to navigate between commands"
items={uiFabricStaticButtons.concat(uiFabricTabsButtons)}
farItems={uiFabricControlButtons}
styles={{
root: { backgroundColor: backgroundColor },
}}
overflowButtonProps={{ ariaLabel: "More commands" }}
/>
</div>
</React.Fragment>
);
}

View File

@@ -1,110 +0,0 @@
/**
* This adapter is responsible to render the React component
* If the component signals a change through the callback passed in the properties, it must render the React component when appropriate
* and update any knockout observables passed from the parent.
*/
import * as ko from "knockout";
import * as React from "react";
import { ReactAdapter } from "../../../Bindings/ReactBindingHandler";
import * as ViewModels from "../../../Contracts/ViewModels";
import * as CommandBarComponentButtonFactory from "./CommandBarComponentButtonFactory";
import { CommandBar, ICommandBarItemProps } from "office-ui-fabric-react/lib/CommandBar";
import { StyleConstants } from "../../../Common/Constants";
import * as CommandBarUtil from "./CommandBarUtil";
import Explorer from "../../Explorer";
import { CommandButtonComponentProps } from "../../Controls/CommandButton/CommandButtonComponent";
export class CommandBarComponentAdapter implements ReactAdapter {
public parameters: ko.Observable<number>;
public container: Explorer;
private tabsButtons: CommandButtonComponentProps[];
private isNotebookTabActive: ko.Computed<boolean>;
constructor(container: Explorer) {
this.container = container;
this.tabsButtons = [];
this.isNotebookTabActive = ko.computed(() =>
container.tabsManager.isTabActive(ViewModels.CollectionTabKind.NotebookV2)
);
// These are the parameters watched by the react binding that will trigger a renderComponent() if one of the ko mutates
const toWatch = [
container.isPreferredApiTable,
container.isPreferredApiMongoDB,
container.isPreferredApiDocumentDB,
container.isPreferredApiCassandra,
container.isPreferredApiGraph,
container.deleteCollectionText,
container.deleteDatabaseText,
container.addCollectionText,
container.addDatabaseText,
container.isDatabaseNodeOrNoneSelected,
container.isDatabaseNodeSelected,
container.isNoneSelected,
container.isResourceTokenCollectionNodeSelected,
container.isHostedDataExplorerEnabled,
container.isSynapseLinkUpdating,
container.databaseAccount,
this.isNotebookTabActive,
container.isServerlessEnabled,
];
ko.computed(() => ko.toJSON(toWatch)).subscribe(() => this.triggerRender());
this.parameters = ko.observable(Date.now());
}
public onUpdateTabsButtons(buttons: CommandButtonComponentProps[]): void {
this.tabsButtons = buttons;
this.triggerRender();
}
public renderComponent(): JSX.Element {
const backgroundColor = StyleConstants.BaseLight;
const staticButtons = CommandBarComponentButtonFactory.createStaticCommandBarButtons(this.container);
const contextButtons = (this.tabsButtons || []).concat(
CommandBarComponentButtonFactory.createContextCommandBarButtons(this.container)
);
const controlButtons = CommandBarComponentButtonFactory.createControlCommandBarButtons(this.container);
const uiFabricStaticButtons = CommandBarUtil.convertButton(staticButtons, backgroundColor);
if (this.tabsButtons && this.tabsButtons.length > 0) {
uiFabricStaticButtons.forEach((btn: ICommandBarItemProps) => (btn.iconOnly = true));
}
const uiFabricTabsButtons: ICommandBarItemProps[] = CommandBarUtil.convertButton(contextButtons, backgroundColor);
if (uiFabricTabsButtons.length > 0) {
uiFabricStaticButtons.push(CommandBarUtil.createDivider("commandBarDivider"));
}
const uiFabricControlButtons = CommandBarUtil.convertButton(controlButtons, backgroundColor);
uiFabricControlButtons.forEach((btn: ICommandBarItemProps) => (btn.iconOnly = true));
if (this.isNotebookTabActive()) {
uiFabricControlButtons.unshift(
CommandBarUtil.createMemoryTracker("memoryTracker", this.container.memoryUsageInfo)
);
}
return (
<React.Fragment>
<div className="commandBarContainer">
<CommandBar
ariaLabel="Use left and right arrow keys to navigate between commands"
items={uiFabricStaticButtons.concat(uiFabricTabsButtons)}
farItems={uiFabricControlButtons}
styles={{
root: { backgroundColor: backgroundColor },
}}
overflowButtonProps={{ ariaLabel: "More commands" }}
/>
</div>
</React.Fragment>
);
}
private triggerRender() {
window.requestAnimationFrame(() => this.parameters(Date.now()));
}
}

View File

@@ -1,5 +1,4 @@
import * as CommandBarUtil from "./CommandBarUtil";
import * as ViewModels from "../../../Contracts/ViewModels";
import { ICommandBarItemProps } from "office-ui-fabric-react/lib/CommandBar";
import { CommandButtonComponentProps } from "../../Controls/CommandButton/CommandButtonComponent";
@@ -26,7 +25,7 @@ describe("CommandBarUtil tests", () => {
const converteds = CommandBarUtil.convertButton([btn], backgroundColor);
expect(converteds.length).toBe(1);
const converted = converteds[0];
expect(!converted.split);
expect(converted.split).toBe(undefined);
expect(converted.iconProps.imageProps.src).toEqual(btn.iconSrc);
expect(converted.iconProps.imageProps.alt).toEqual(btn.iconAlt);
expect(converted.text).toEqual(btn.commandButtonLabel);
@@ -50,7 +49,7 @@ describe("CommandBarUtil tests", () => {
const converteds = CommandBarUtil.convertButton([btn], "backgroundColor");
expect(converteds.length).toBe(1);
const converted = converteds[0];
expect(converted.split);
expect(converted.split).toBe(true);
expect(converted.subMenuProps.items.length).toBe(btn.children.length);
for (let i = 0; i < converted.subMenuProps.items.length; i++) {
expect(converted.subMenuProps.items[i].text).toEqual(btn.children[i].commandButtonLabel);
@@ -64,7 +63,6 @@ describe("CommandBarUtil tests", () => {
}
const converteds = CommandBarUtil.convertButton(btns, "backgroundColor");
const keys = converteds.map((btn: ICommandBarItemProps) => btn.key);
const uniqueKeys = converteds
.map((btn: ICommandBarItemProps) => btn.key)
.filter((value: string, index: number, self: string[]) => self.indexOf(value) === index);
@@ -75,7 +73,7 @@ describe("CommandBarUtil tests", () => {
const btn = createButton();
const backgroundColor = "backgroundColor";
btn.commandButtonLabel = null;
btn.commandButtonLabel = undefined;
let converted = CommandBarUtil.convertButton([btn], backgroundColor)[0];
expect(converted.text).toEqual(btn.tooltipText);

View File

@@ -17,7 +17,7 @@ export class ControlBarComponent extends React.Component<ControlBarComponentProp
return commandButtonOptions.map(
(btn: CommandButtonComponentProps, index: number): JSX.Element => {
// Remove label
btn.commandButtonLabel = null;
btn.commandButtonLabel = undefined;
return CommandButtonComponent.renderButton(btn, `${index}`);
}
);

View File

@@ -0,0 +1,86 @@
import { observable } from "knockout";
import { mostRecentActivity } from "./MostRecentActivity";
describe("MostRecentActivity", () => {
const accountId = "some account";
beforeEach(() => mostRecentActivity.clear(accountId));
it("Has no items at first", () => {
expect(mostRecentActivity.getItems(accountId)).toStrictEqual([]);
});
it("Can record collections being opened", () => {
const collectionId = "some collection";
const databaseId = "some database";
const collection = {
id: observable(collectionId),
databaseId,
};
mostRecentActivity.collectionWasOpened(accountId, collection);
const activity = mostRecentActivity.getItems(accountId);
expect(activity).toEqual([
expect.objectContaining({
collectionId,
databaseId,
}),
]);
});
it("Can record notebooks being opened", () => {
const name = "some notebook";
const path = "some path";
const notebook = { name, path };
mostRecentActivity.notebookWasItemOpened(accountId, notebook);
const activity = mostRecentActivity.getItems(accountId);
expect(activity).toEqual([expect.objectContaining(notebook)]);
});
it("Filters out duplicates", () => {
const name = "some notebook";
const path = "some path";
const notebook = { name, path };
const sameNotebook = { name, path };
mostRecentActivity.notebookWasItemOpened(accountId, notebook);
mostRecentActivity.notebookWasItemOpened(accountId, sameNotebook);
const activity = mostRecentActivity.getItems(accountId);
expect(activity.length).toEqual(1);
expect(activity).toEqual([expect.objectContaining(notebook)]);
});
it("Allows for multiple accounts", () => {
const name = "some notebook";
const path = "some path";
const notebook = { name, path };
const anotherNotebook = { name: "Another " + name, path };
const anotherAccountId = "Another " + accountId;
mostRecentActivity.notebookWasItemOpened(accountId, notebook);
mostRecentActivity.notebookWasItemOpened(anotherAccountId, anotherNotebook);
expect(mostRecentActivity.getItems(accountId)).toEqual([expect.objectContaining(notebook)]);
expect(mostRecentActivity.getItems(anotherAccountId)).toEqual([expect.objectContaining(anotherNotebook)]);
});
it("Can store multiple distinct elements, in FIFO order", () => {
const name = "some notebook";
const path = "some path";
const first = { name, path };
const second = { name: "Another " + name, path };
const third = { name, path: "Another " + path };
mostRecentActivity.notebookWasItemOpened(accountId, first);
mostRecentActivity.notebookWasItemOpened(accountId, second);
mostRecentActivity.notebookWasItemOpened(accountId, third);
const activity = mostRecentActivity.getItems(accountId);
expect(activity).toEqual([third, second, first].map(expect.objectContaining));
});
});

View File

@@ -1,4 +1,6 @@
import { CollectionBase } from "../../Contracts/ViewModels";
import { StorageKey, LocalStorageUtility } from "../../Shared/StorageUtility";
import { NotebookContentItem } from "../Notebook/NotebookContentItem";
export enum Type {
OpenCollection,
@@ -6,21 +8,18 @@ export enum Type {
}
export interface OpenNotebookItem {
type: Type.OpenNotebook;
name: string;
path: string;
}
export interface OpenCollectionItem {
type: Type.OpenCollection;
databaseId: string;
collectionId: string;
}
export interface Item {
type: Type;
title: string;
description: string;
data: OpenNotebookItem | OpenCollectionItem;
}
type Item = OpenNotebookItem | OpenCollectionItem;
// Update schemaVersion if you are going to change this interface
interface StoredData {
@@ -32,7 +31,7 @@ interface StoredData {
* Stores most recent activity
*/
class MostRecentActivity {
private static readonly schemaVersion: string = "1";
private static readonly schemaVersion: string = "2";
private static itemsMaxNumber: number = 5;
private storedData: StoredData;
constructor() {
@@ -92,7 +91,7 @@ class MostRecentActivity {
LocalStorageUtility.setEntryString(StorageKey.MostRecentActivity, JSON.stringify(this.storedData));
}
public addItem(accountId: string, newItem: Item): void {
private addItem(accountId: string, newItem: Item): void {
// When debugging, accountId is "undefined": most recent activity cannot be saved by account. Uncomment to disable.
// if (!accountId) {
// return;
@@ -111,6 +110,23 @@ class MostRecentActivity {
return this.storedData.itemsMap[accountId] || [];
}
public collectionWasOpened(accountId: string, { id, databaseId }: Pick<CollectionBase, "id" | "databaseId">) {
const collectionId = id();
this.addItem(accountId, {
type: Type.OpenCollection,
databaseId,
collectionId,
});
}
public notebookWasItemOpened(accountId: string, { name, path }: Pick<NotebookContentItem, "name" | "path">) {
this.addItem(accountId, {
type: Type.OpenNotebook,
name,
path,
});
}
public clear(accountId: string): void {
delete this.storedData.itemsMap[accountId];
this.saveToLocalStorage();
@@ -128,11 +144,7 @@ class MostRecentActivity {
let index = -1;
for (let i = 0; i < itemsArray.length; i++) {
const currentItem = itemsArray[i];
if (
currentItem.title === item.title &&
currentItem.description === item.description &&
JSON.stringify(currentItem.data) === JSON.stringify(item.data)
) {
if (JSON.stringify(currentItem) === JSON.stringify(item)) {
index = i;
break;
}

View File

@@ -3,8 +3,7 @@ import { NotebookContentRecordProps, selectors } from "@nteract/core";
/**
* A bunch of utilities to interact with nteract
*/
export default class NTeractUtil {
public static getCurrentCellType(content: NotebookContentRecordProps): "markdown" | "code" | "raw" | undefined {
export function getCurrentCellType(content: NotebookContentRecordProps): "markdown" | "code" | "raw" | undefined {
if (!content) {
return undefined;
}
@@ -18,5 +17,4 @@ export default class NTeractUtil {
}
return undefined;
}
}

View File

@@ -2,7 +2,7 @@ import * as React from "react";
import { NotebookComponent } from "./NotebookComponent";
import { NotebookClientV2 } from "../NotebookClientV2";
import * as NotebookUtil from "../NotebookUtil";
import { NotebookUtil } from "../NotebookUtil";
// Vendor modules
import {
@@ -29,7 +29,7 @@ import "@nteract/styles/global-variables.css";
import "react-table/react-table.css";
import * as CdbActions from "./actions";
import NteractUtil from "../NTeractUtil";
import * as NteractUtil from "../NTeractUtil";
export interface NotebookComponentBootstrapperOptions {
notebookClient: NotebookClientV2;

View File

@@ -1,7 +1,7 @@
import * as React from "react";
import { AppState, ContentRef, selectors } from "@nteract/core";
import { connect } from "react-redux";
import NteractUtil from "../NTeractUtil";
import * as NteractUtil from "../NTeractUtil";
interface VirtualCommandBarComponentProps {
kernelSpecName: string;

View File

@@ -8,7 +8,7 @@ import * as sinon from "sinon";
import { CdbAppState, makeCdbRecord } from "./types";
import { launchWebSocketKernelEpic } from "./epics";
import * as NotebookUtil from "../NotebookUtil";
import { NotebookUtil } from "../NotebookUtil";
import { sessions } from "rx-jupyter";

View File

@@ -43,7 +43,7 @@ import { Action as TelemetryAction, ActionModifiers } from "../../../Shared/Tele
import { CdbAppState } from "./types";
import { decryptJWTToken } from "../../../Utils/AuthorizationUtils";
import * as TextFile from "./contents/file/text-file";
import * as NotebookUtil from "../NotebookUtil";
import { NotebookUtil } from "../NotebookUtil";
import { FileSystemUtil } from "../FileSystemUtil";
import * as cdbActions from "../NotebookComponent/actions";
import { Areas } from "../../../Common/Constants";

View File

@@ -2,7 +2,7 @@ import * as DataModels from "../../Contracts/DataModels";
import { NotebookContentItem, NotebookContentItemType } from "./NotebookContentItem";
import * as StringUtils from "../../Utils/StringUtils";
import { FileSystemUtil } from "./FileSystemUtil";
import * as NotebookUtil from "./NotebookUtil";
import { NotebookUtil } from "./NotebookUtil";
import { ServerConfig, IContent, IContentProvider, FileType, IEmptyContent } from "@nteract/core";
import { AjaxResponse } from "rxjs/ajax";

View File

@@ -1,4 +1,4 @@
import * as NotebookUtil from "./NotebookUtil";
import { NotebookUtil } from "./NotebookUtil";
import * as GitHubUtils from "../../Utils/GitHubUtils";
import {
ImmutableNotebook,

View File

@@ -7,33 +7,34 @@ import * as GitHubUtils from "../../Utils/GitHubUtils";
// Must match rx-jupyter' FileType
export type FileType = "directory" | "file" | "notebook";
// Utilities for notebooks
/**
export class NotebookUtil {
/**
* It's a notebook file if the filename ends with .ipynb.
*/
export function isNotebookFile(notebookPath: string): boolean {
const fileName = getName(notebookPath);
public static isNotebookFile(notebookPath: string): boolean {
const fileName = NotebookUtil.getName(notebookPath);
return !!fileName && StringUtils.endsWith(fileName, ".ipynb");
}
}
/**
/**
* Note: this does not connect the item to a parent in a tree.
* @param name
* @param path
*/
export function createNotebookContentItem(name: string, path: string, type: FileType): NotebookContentItem {
public static createNotebookContentItem(name: string, path: string, type: FileType): NotebookContentItem {
return {
name,
path,
type: getType(type),
timestamp: getCurrentTimestamp(),
type: NotebookUtil.getType(type),
timestamp: NotebookUtil.getCurrentTimestamp(),
};
}
}
/**
/**
* Convert rx-jupyter type to our type
* @param type
*/
export function getType(type: FileType): NotebookContentItemType {
public static getType(type: FileType): NotebookContentItemType {
switch (type) {
case "directory":
return NotebookContentItemType.Directory;
@@ -44,20 +45,20 @@ export function getType(type: FileType): NotebookContentItemType {
default:
throw new Error(`Unknown file type: ${type}`);
}
}
}
export function getCurrentTimestamp(): number {
public static getCurrentTimestamp(): number {
return new Date().getTime();
}
}
/**
/**
* Override from kernel-lifecycle.ts to improve kernel selection:
* Only return the kernel name persisted in the notebook
*
* @param filepath
* @param notebook
*/
export function extractNewKernel(filepath: string | null, notebook: ImmutableNotebook) {
public static extractNewKernel(filepath: string | null, notebook: ImmutableNotebook) {
const cwd = (filepath && path.dirname(filepath)) || "/";
const kernelSpecName =
@@ -67,9 +68,9 @@ export function extractNewKernel(filepath: string | null, notebook: ImmutableNot
cwd,
kernelSpecName,
};
}
}
export function getFilePath(path: string, fileName: string): string {
public static getFilePath(path: string, fileName: string): string {
const contentInfo = GitHubUtils.fromContentUri(path);
if (contentInfo) {
let path = fileName;
@@ -80,10 +81,10 @@ export function getFilePath(path: string, fileName: string): string {
}
return `${path}/${fileName}`;
}
}
export function getParentPath(filepath: string): undefined | string {
const basename = getName(filepath);
public static getParentPath(filepath: string): undefined | string {
const basename = NotebookUtil.getName(filepath);
if (basename) {
const contentInfo = GitHubUtils.fromContentUri(filepath);
if (contentInfo) {
@@ -107,9 +108,9 @@ export function getParentPath(filepath: string): undefined | string {
}
return undefined;
}
}
export function getName(path: string): undefined | string {
public static getName(path: string): undefined | string {
let relativePath: string = path;
const contentInfo = GitHubUtils.fromContentUri(path);
if (contentInfo) {
@@ -117,9 +118,9 @@ export function getName(path: string): undefined | string {
}
return relativePath.split("/").pop();
}
}
export function replaceName(path: string, newName: string): string {
public static replaceName(path: string, newName: string): string {
const contentInfo = GitHubUtils.fromContentUri(path);
if (contentInfo) {
const contentName = contentInfo.path.split("/").pop();
@@ -138,9 +139,9 @@ export function replaceName(path: string, newName: string): string {
const basePath = path.split(contentName).shift();
return `${basePath}${newName}`;
}
}
export function findFirstCodeCellWithDisplay(notebookObject: ImmutableNotebook): number {
public static findFirstCodeCellWithDisplay(notebookObject: ImmutableNotebook): number {
let codeCellIndex = 0;
for (let i = 0; i < notebookObject.cellOrder.size; i++) {
const cellId = notebookObject.cellOrder.get(i);
@@ -158,4 +159,5 @@ export function findFirstCodeCellWithDisplay(notebookObject: ImmutableNotebook):
}
}
throw new Error("Output does not exist for any of the cells.");
}
}

View File

@@ -214,7 +214,6 @@
maxAutoPilotThroughputSet: sharedAutoPilotThroughput,
autoPilotUsageCost: autoPilotUsageCost,
canExceedMaximumValue: canExceedMaximumValue,
showAutoPilot: !isFreeTierAccount(),
freeTierExceedThroughputTooltip: freeTierExceedThroughputTooltip
}"
>
@@ -435,7 +434,6 @@
maxAutoPilotThroughputSet: autoPilotThroughput,
autoPilotUsageCost: autoPilotUsageCost,
canExceedMaximumValue: canExceedMaximumValue,
showAutoPilot: !isFixedStorageSelected(),
freeTierExceedThroughputTooltip: freeTierExceedThroughputTooltip
}"
>

View File

@@ -749,13 +749,17 @@ export default class AddCollectionPane extends ContextualPaneBase {
return undefined;
}
if (this.isAutoPilotSelected()) {
return undefined;
}
// return undefined if autopilot is selected for the new database/collection
if (this.databaseCreateNew()) {
// database is shared and autopilot is sleected for the database
if (this.databaseCreateNewShared() && this.isSharedAutoPilotSelected()) {
return undefined;
}
// database is not shared and autopilot is selected for the collection
if (!this.databaseCreateNewShared() && this.isAutoPilotSelected()) {
return undefined;
}
}
return this._getThroughput();
}

View File

@@ -149,7 +149,6 @@
maxAutoPilotThroughputSet: maxAutoPilotThroughputSet,
autoPilotUsageCost: autoPilotUsageCost,
canExceedMaximumValue: canExceedMaximumValue,
showAutoPilot: !isFreeTierAccount(),
freeTierExceedThroughputTooltip: freeTierExceedThroughputTooltip
}"
>

View File

@@ -166,7 +166,6 @@
autoPilotUsageCost: autoPilotUsageCost,
canExceedMaximumValue: canExceedMaximumValue,
costsVisible: costsVisible,
showAutoPilot: !isFreeTierAccount()
}"
>
</throughput-input-autopilot-v3>

View File

@@ -5,7 +5,7 @@ import { FileSystemUtil } from "../Notebook/FileSystemUtil";
import "./PublishNotebookPaneComponent.less";
import Html2Canvas from "html2canvas";
import { ImmutableNotebook } from "@nteract/commutable/src";
import * as NotebookUtil from "../Notebook/NotebookUtil";
import { NotebookUtil } from "../Notebook/NotebookUtil";
export interface PublishNotebookPaneProps {
notebookName: string;

View File

@@ -5,7 +5,7 @@ import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsol
import { ContextualPaneBase } from "./ContextualPaneBase";
import { LocalStorageUtility, StorageKey } from "../../Shared/StorageUtility";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import { StringUtility } from "../../Shared/StringUtility";
import * as StringUtility from "../../Shared/StringUtility";
import { configContext } from "../../ConfigContext";
export class SettingsPane extends ContextualPaneBase {

View File

@@ -217,42 +217,6 @@ export class SplashScreen extends React.Component<SplashScreenProps> {
return heroes;
}
private getItemIcon(item: MostRecentActivity.Item): string {
switch (item.type) {
case MostRecentActivity.Type.OpenCollection:
return CollectionIcon;
case MostRecentActivity.Type.OpenNotebook:
return NotebookIcon;
default:
return null;
}
}
private onItemClicked(item: MostRecentActivity.Item) {
switch (item.type) {
case MostRecentActivity.Type.OpenCollection: {
const openCollectionitem = item.data as MostRecentActivity.OpenCollectionItem;
const collection = this.container.findCollection(
openCollectionitem.databaseId,
openCollectionitem.collectionId
);
if (collection) {
collection.openTab();
}
break;
}
case MostRecentActivity.Type.OpenNotebook: {
const openNotebookItem = item.data as MostRecentActivity.OpenNotebookItem;
const notebookItem = this.container.createNotebookContentItemFile(openNotebookItem.name, openNotebookItem.path);
notebookItem && this.container.openNotebook(notebookItem);
break;
}
default:
console.error("Unknown item type", item);
break;
}
}
private createCommonTaskItems(): SplashScreenItem[] {
const items: SplashScreenItem[] = [];
@@ -333,23 +297,45 @@ export class SplashScreen extends React.Component<SplashScreenProps> {
return items;
}
private static getInfo(item: MostRecentActivity.Item): string {
if (item.type === MostRecentActivity.Type.OpenNotebook) {
const data = item.data as MostRecentActivity.OpenNotebookItem;
return data.path;
} else {
return undefined;
private decorateOpenCollectionActivity({ databaseId, collectionId }: MostRecentActivity.OpenCollectionItem) {
return {
iconSrc: NotebookIcon,
title: collectionId,
description: "Data",
onClick: () => {
const collection = this.container.findCollection(databaseId, collectionId);
collection && collection.openTab();
},
};
}
private decorateOpenNotebookActivity({ name, path }: MostRecentActivity.OpenNotebookItem) {
return {
info: path,
iconSrc: CollectionIcon,
title: name,
description: "Notebook",
onClick: () => {
const notebookItem = this.container.createNotebookContentItemFile(name, path);
notebookItem && this.container.openNotebook(notebookItem);
},
};
}
private createRecentItems(): SplashScreenItem[] {
return MostRecentActivity.mostRecentActivity.getItems(userContext.databaseAccount?.id).map((item) => ({
iconSrc: this.getItemIcon(item),
title: item.title,
description: item.description,
info: SplashScreen.getInfo(item),
onClick: () => this.onItemClicked(item),
}));
return MostRecentActivity.mostRecentActivity.getItems(userContext.databaseAccount?.id).map((activity) => {
switch (activity.type) {
default: {
const unknownActivity: never = activity;
throw new Error(`Unknown activity: ${unknownActivity}`);
}
case MostRecentActivity.Type.OpenNotebook:
return this.decorateOpenNotebookActivity(activity);
case MostRecentActivity.Type.OpenCollection:
return this.decorateOpenCollectionActivity(activity);
}
});
}
private createTipsItems(): SplashScreenItem[] {

View File

@@ -53,7 +53,6 @@
throughputAutoPilotRadioId: throughputAutoPilotRadioId,
throughputProvisionedRadioId: throughputProvisionedRadioId,
throughputModeRadioName: throughputModeRadioName,
showAutoPilot: userCanChangeProvisioningTypes,
isAutoPilotSelected: isAutoPilotSelected,
maxAutoPilotThroughputSet: autoPilotThroughput,
autoPilotUsageCost: autoPilotUsageCost,

View File

@@ -1,23 +1,23 @@
import * as AutoPilotUtils from "../../Utils/AutoPilotUtils";
import * as Constants from "../../Common/Constants";
import * as DataModels from "../../Contracts/DataModels";
import * as ko from "knockout";
import * as PricingUtils from "../../Utils/PricingUtils";
import * as SharedConstants from "../../Shared/Constants";
import * as ViewModels from "../../Contracts/ViewModels";
import DiscardIcon from "../../../images/discard.svg";
import editable from "../../Common/EditableUtility";
import Q from "q";
import DiscardIcon from "../../../images/discard.svg";
import SaveIcon from "../../../images/save-cosmos.svg";
import TabsBase from "./TabsBase";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import { Action } from "../../Shared/Telemetry/TelemetryConstants";
import { RequestOptions } from "@azure/cosmos/dist-esm";
import Explorer from "../Explorer";
import * as Constants from "../../Common/Constants";
import { updateOffer } from "../../Common/dataAccess/updateOffer";
import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent";
import { configContext, Platform } from "../../ConfigContext";
import editable from "../../Common/EditableUtility";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
import { configContext, Platform } from "../../ConfigContext";
import * as DataModels from "../../Contracts/DataModels";
import * as ViewModels from "../../Contracts/ViewModels";
import * as SharedConstants from "../../Shared/Constants";
import { Action } from "../../Shared/Telemetry/TelemetryConstants";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import { userContext } from "../../UserContext";
import * as AutoPilotUtils from "../../Utils/AutoPilotUtils";
import * as PricingUtils from "../../Utils/PricingUtils";
import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent";
import Explorer from "../Explorer";
import TabsBase from "./TabsBase";
const updateThroughputBeyondLimitWarningMessage: string = `
You are about to request an increase in throughput beyond the pre-allocated capacity.
@@ -73,7 +73,6 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
public shouldShowStatusBar: ko.Computed<boolean>;
public throughputTitle: ko.PureComputed<string>;
public throughputAriaLabel: ko.PureComputed<string>;
public userCanChangeProvisioningTypes: ko.Observable<boolean>;
public autoPilotUsageCost: ko.PureComputed<string>;
public warningMessage: ko.Computed<string>;
public canExceedMaximumValue: ko.PureComputed<boolean>;
@@ -106,7 +105,6 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
this._wasAutopilotOriginallySet = ko.observable(false);
this.isAutoPilotSelected = editable.observable(false);
this.autoPilotThroughput = editable.observable<number>();
this.userCanChangeProvisioningTypes = ko.observable(true);
const autoscaleMaxThroughput = this.database?.offer()?.autoscaleMaxThroughput;
if (autoscaleMaxThroughput) {
@@ -118,9 +116,6 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
}
this._hasProvisioningTypeChanged = ko.pureComputed<boolean>(() => {
if (!this.userCanChangeProvisioningTypes()) {
return false;
}
if (this._wasAutopilotOriginallySet() !== this.isAutoPilotSelected()) {
return true;
}
@@ -136,7 +131,7 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
});
this.requestUnitsUsageCost = ko.pureComputed(() => {
const account = this.container.databaseAccount();
const account = userContext.databaseAccount;
if (!account) {
return "";
}
@@ -362,7 +357,7 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
this.isTemplateReady = ko.observable<boolean>(false);
this.isFreeTierAccount = ko.computed<boolean>(() => {
const databaseAccount = this.container?.databaseAccount();
const databaseAccount = userContext.databaseAccount;
return databaseAccount?.properties?.enableFreeTier;
});
@@ -448,7 +443,6 @@ export default class DatabaseSettingsTab extends TabsBase implements ViewModels.
this.isAutoPilotSelected.setBaseline(AutoPilotUtils.isValidAutoPilotThroughput(offer.autoscaleMaxThroughput));
this.autoPilotThroughput.setBaseline(offer.autoscaleMaxThroughput);
this.throughput.setBaseline(offer.manualThroughput);
this.userCanChangeProvisioningTypes(true);
}
protected getTabsButtons(): CommandButtonComponentProps[] {

View File

@@ -24,7 +24,7 @@ import * as CommandBarComponentButtonFactory from "../Menus/CommandBar/CommandBa
import { ConsoleDataType } from "../Menus/NotificationConsole/NotificationConsoleComponent";
import * as NotificationConsoleUtils from "../../Utils/NotificationConsoleUtils";
import { NotebookComponentAdapter } from "../Notebook/NotebookComponent/NotebookComponentAdapter";
import { NotebookConfigurationUtils } from "../../Utils/NotebookConfigurationUtils";
import * as NotebookConfigurationUtils from "../../Utils/NotebookConfigurationUtils";
import { KernelSpecsDisplay, NotebookClientV2 } from "../Notebook/NotebookClientV2";
import { configContext } from "../../ConfigContext";
import Explorer from "../Explorer";

View File

@@ -6,7 +6,7 @@ import { TreeComponent, TreeNode, TreeNodeMenuItem, TreeNodeComponent } from "..
import * as ViewModels from "../../Contracts/ViewModels";
import { NotebookContentItem, NotebookContentItemType } from "../Notebook/NotebookContentItem";
import { ResourceTreeContextMenuButtonFactory } from "../ContextMenuButtonFactory";
import * as MostRecentActivity from "../MostRecentActivity/MostRecentActivity";
import { mostRecentActivity } from "../MostRecentActivity/MostRecentActivity";
import CopyIcon from "../../../images/notebook/Notebook-copy.svg";
import CosmosDBIcon from "../../../images/Azure-Cosmos-DB.svg";
import CollectionIcon from "../../../images/tree-collection.svg";
@@ -17,7 +17,7 @@ import NewNotebookIcon from "../../../images/notebook/Notebook-new.svg";
import FileIcon from "../../../images/notebook/file-cosmos.svg";
import PublishIcon from "../../../images/notebook/publish_content.svg";
import { ArrayHashMap } from "../../Common/ArrayHashMap";
import * as NotebookUtil from "../Notebook/NotebookUtil";
import { NotebookUtil } from "../Notebook/NotebookUtil";
import _ from "underscore";
import { IPinnedRepo } from "../../Juno/JunoClient";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
@@ -264,15 +264,7 @@ export class ResourceTreeAdapter implements ReactAdapter {
onClick: () => {
collection.openTab();
// push to most recent
MostRecentActivity.mostRecentActivity.addItem(userContext.databaseAccount?.id, {
type: MostRecentActivity.Type.OpenCollection,
title: collection.id(),
description: "Data",
data: {
databaseId: collection.databaseId,
collectionId: collection.id(),
},
});
mostRecentActivity.collectionWasOpened(userContext.databaseAccount?.id, collection);
},
isSelected: () =>
this.isDataNodeSelected(collection.databaseId, collection.id(), [
@@ -573,7 +565,7 @@ export class ResourceTreeAdapter implements ReactAdapter {
(item: NotebookContentItem) => {
this.container.openNotebook(item).then((hasOpened) => {
if (hasOpened) {
this.pushItemToMostRecent(item);
mostRecentActivity.notebookWasItemOpened(userContext.databaseAccount?.id, item);
}
});
},
@@ -594,7 +586,7 @@ export class ResourceTreeAdapter implements ReactAdapter {
(item: NotebookContentItem) => {
this.container.openNotebook(item).then((hasOpened) => {
if (hasOpened) {
this.pushItemToMostRecent(item);
mostRecentActivity.notebookWasItemOpened(userContext.databaseAccount?.id, item);
}
});
},
@@ -624,18 +616,6 @@ export class ResourceTreeAdapter implements ReactAdapter {
return gitHubNotebooksTree;
}
private pushItemToMostRecent(item: NotebookContentItem) {
MostRecentActivity.mostRecentActivity.addItem(userContext.databaseAccount?.id, {
type: MostRecentActivity.Type.OpenNotebook,
title: item.name,
description: "Notebook",
data: {
name: item.name,
path: item.path,
},
});
}
private buildChildNodes(
item: NotebookContentItem,
onFileClick: (item: NotebookContentItem) => void,

View File

@@ -1,5 +1,5 @@
import * as ko from "knockout";
import * as MostRecentActivity from "../MostRecentActivity/MostRecentActivity";
import { mostRecentActivity } from "../MostRecentActivity/MostRecentActivity";
import * as React from "react";
import * as ViewModels from "../../Contracts/ViewModels";
import { NotebookContentItem } from "../Notebook/NotebookContentItem";
@@ -44,15 +44,7 @@ export class ResourceTreeAdapterForResourceToken implements ReactAdapter {
onClick: () => {
collection.onDocumentDBDocumentsClick();
// push to most recent
MostRecentActivity.mostRecentActivity.addItem(userContext.databaseAccount?.id, {
type: MostRecentActivity.Type.OpenCollection,
title: collection.id(),
description: "Data",
data: {
databaseId: collection.databaseId,
collectionId: collection.id(),
},
});
mostRecentActivity.collectionWasOpened(userContext.databaseAccount?.id, collection);
},
isSelected: () =>
this.isDataNodeSelected(collection.databaseId, collection.id(), ViewModels.CollectionTabKind.Documents),

View File

@@ -36,7 +36,7 @@ const onInit = async () => {
<header>
<GalleryHeaderComponent />
</header>
<div style={{ marginLeft: 138, marginRight: 138 }}>
<div style={{ margin: "auto", width: "85%" }}>
<div style={{ paddingLeft: 26, paddingRight: 26, paddingTop: 20 }}>
<Text block>
Welcome to the Azure Cosmos DB notebooks gallery! View the sample notebooks to learn about use cases, best

View File

@@ -2,7 +2,7 @@ import { Octokit } from "@octokit/rest";
import { HttpStatusCodes } from "../Common/Constants";
import * as Logger from "../Common/Logger";
import UrlUtility from "../Common/UrlUtility";
import * as NotebookUtil from "../Explorer/Notebook/NotebookUtil";
import { NotebookUtil } from "../Explorer/Notebook/NotebookUtil";
import { getErrorMessage } from "../Common/ErrorHandlingUtils";
export interface IGitHubPageInfo {

View File

@@ -5,7 +5,7 @@ import { AjaxResponse } from "rxjs/ajax";
import * as Base64Utils from "../Utils/Base64Utils";
import { HttpStatusCodes } from "../Common/Constants";
import * as Logger from "../Common/Logger";
import * as NotebookUtil from "../Explorer/Notebook/NotebookUtil";
import { NotebookUtil } from "../Explorer/Notebook/NotebookUtil";
import { GitHubClient, IGitHubFile, IGitHubResponse } from "./GitHubClient";
import * as GitHubUtils from "../Utils/GitHubUtils";
import UrlUtility from "../Common/UrlUtility";

View File

@@ -9,9 +9,11 @@
"North Central US": "North Central US",
"West US": "West US",
"East US 2": "East US 2",
"ClassInfo": "This is a self serve class",
"Current Region": "Current Region",
"RegionDropdownInfo": "More regions can be added in the future.",
"ValidationError": "Regions and AccountName should not be empty.",
"RegionsAndAccountNameValidationError": "Regions and account name should not be empty.",
"DbThroughputValidationError": "Please update throughput for database.",
"DescriptionLabel": "Description",
"DescriptionText": "This class sets collection and database throughput.",
"DecriptionLinkText": "Click here for more information",
"Regions": "Regions",
@@ -22,10 +24,17 @@
"Account Name": "Account Name",
"AccountNamePlaceHolder": "Enter the account name",
"Collection Throughput": "Collection Throughput",
"Enable DB level throughput": "Enable DB level throughput",
"Enable DB level throughput": "Enable Database Level Throughput",
"Database Throughput": "Database Throughput",
"RefreshMessage": "Self Serve Example successfully refreshing",
"SubmissionMessage": "Submitted successfully"
"UpdateInProgressMessage": "Data is being updated",
"UpdateCompletedMessageTitle":"Update succeeded",
"UpdateCompletedMessageText": "Data updation completed.",
"SubmissionMessageSuccessTitle": "Update started",
"SubmissionMessageForNewRegionText": "Data update started. Region changed.",
"SubmissionMessageForSameRegionText": "Data update started. Region not changed.",
"SubmissionMessageErrorTitle": "Data update failed",
"SubmissionMessageErrorText": "Data update failed because of errors.",
"OnSaveFailureMessage": "Data save operation not currently permitted."
},
"SqlX": {
}

View File

@@ -1,74 +1,72 @@
// CSS Dependencies
import "abort-controller/polyfill";
import "babel-polyfill";
import "bootstrap/dist/css/bootstrap.css";
import "../less/documentDB.less";
import "../less/tree.less";
import "../less/forms.less";
import "../less/menus.less";
import "../less/infobox.less";
import "../less/messagebox.less";
import "./Explorer/Controls/ErrorDisplayComponent/ErrorDisplayComponent.less";
import "./Explorer/Menus/NotificationConsole/NotificationConsole.less";
import "./Explorer/Menus/CommandBar/CommandBarComponent.less";
import "./Explorer/Menus/CommandBar/MemoryTrackerComponent.less";
import "./Explorer/Controls/CollapsiblePanel/CollapsiblePanelComponent.less";
import "./Explorer/Controls/DynamicList/DynamicListComponent.less";
import "./Explorer/Controls/JsonEditor/JsonEditorComponent.less";
import "./Explorer/Graph/GraphExplorerComponent/graphExplorer.less";
import "./Explorer/Panes/PanelComponent.less";
import "../less/TableStyles/queryBuilder.less";
import "../externals/jquery.dataTables.min.css";
import "../less/TableStyles/fulldatatables.less";
import "../less/TableStyles/EntityEditor.less";
import "../less/TableStyles/CustomizeColumns.less";
import "../less/resourceTree.less";
import "../externals/jquery.typeahead.min.css";
import "es6-object-assign/auto";
import "es6-symbol/implement";
import "object.entries/auto";
import { initializeIcons } from "office-ui-fabric-react/lib/Icons";
import "promise-polyfill/src/polyfill";
import "promise.prototype.finally/auto";
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "url-polyfill/url-polyfill.min";
import "webcrypto-liner/build/webcrypto-liner.shim.min";
import "whatwg-fetch";
import "../externals/jquery-ui.min.css";
import "../externals/jquery-ui.min.js";
import "../externals/jquery-ui.structure.min.css";
import "../externals/jquery-ui.theme.min.css";
import "./Explorer/Graph/NewVertexComponent/newVertexComponent.less";
import "./Explorer/Panes/GraphNewVertexPane.less";
import "./Explorer/Tabs/QueryTab.less";
import "./Explorer/Controls/TreeComponent/treeComponent.less";
import "./Explorer/Controls/Accordion/AccordionComponent.less";
import "./Explorer/SplashScreen/SplashScreen.less";
import "./Explorer/Controls/Notebook/NotebookTerminalComponent.less";
import "../externals/jquery.dataTables.min.css";
import "../externals/jquery.typeahead.min.css";
import "../externals/jquery.typeahead.min.js";
// Image Dependencies
import "../images/CosmosDB_rgb_ui_lighttheme.ico";
import "../images/favicon.ico";
import "./Shared/appInsights";
import "babel-polyfill";
import "es6-symbol/implement";
import "webcrypto-liner/build/webcrypto-liner.shim.min";
import "./Libs/jquery";
import "bootstrap/dist/js/npm";
import "../externals/jquery.typeahead.min.js";
import "../externals/jquery-ui.min.js";
import "promise-polyfill/src/polyfill";
import "abort-controller/polyfill";
import "whatwg-fetch";
import "es6-object-assign/auto";
import "promise.prototype.finally/auto";
import "object.entries/auto";
import "./Libs/is-integer-polyfill";
import "url-polyfill/url-polyfill.min";
import { initializeIcons } from "office-ui-fabric-react/lib/Icons";
import { ExplorerParams } from "./Explorer/Explorer";
import React, { useState } from "react";
import ReactDOM from "react-dom";
import hdeConnectImage from "../images/HdeConnectCosmosDB.svg";
import refreshImg from "../images/refresh-cosmos.svg";
import arrowLeftImg from "../images/imgarrowlefticon.svg";
import { KOCommentEnd, KOCommentIfStart } from "./koComment";
import { useConfig } from "./hooks/useConfig";
import { useKnockoutExplorer } from "./hooks/useKnockoutExplorer";
import { useSidePanel } from "./hooks/useSidePanel";
import refreshImg from "../images/refresh-cosmos.svg";
import "../less/documentDB.less";
import "../less/forms.less";
import "../less/infobox.less";
import "../less/menus.less";
import "../less/messagebox.less";
import "../less/resourceTree.less";
import "../less/TableStyles/CustomizeColumns.less";
import "../less/TableStyles/EntityEditor.less";
import "../less/TableStyles/fulldatatables.less";
import "../less/TableStyles/queryBuilder.less";
import "../less/tree.less";
import "./Explorer/Controls/Accordion/AccordionComponent.less";
import "./Explorer/Controls/CollapsiblePanel/CollapsiblePanelComponent.less";
import { Dialog, DialogProps } from "./Explorer/Controls/Dialog";
import "./Explorer/Controls/DynamicList/DynamicListComponent.less";
import "./Explorer/Controls/ErrorDisplayComponent/ErrorDisplayComponent.less";
import "./Explorer/Controls/JsonEditor/JsonEditorComponent.less";
import "./Explorer/Controls/Notebook/NotebookTerminalComponent.less";
import "./Explorer/Controls/TreeComponent/treeComponent.less";
import { ExplorerParams } from "./Explorer/Explorer";
import "./Explorer/Graph/GraphExplorerComponent/graphExplorer.less";
import "./Explorer/Graph/NewVertexComponent/newVertexComponent.less";
import { CommandBarComponent } from "./Explorer/Menus/CommandBar/CommandBarComponent";
import "./Explorer/Menus/CommandBar/CommandBarComponent.less";
import "./Explorer/Menus/CommandBar/MemoryTrackerComponent.less";
import "./Explorer/Menus/NotificationConsole/NotificationConsole.less";
import { NotificationConsoleComponent } from "./Explorer/Menus/NotificationConsole/NotificationConsoleComponent";
import "./Explorer/Panes/GraphNewVertexPane.less";
import "./Explorer/Panes/PanelComponent.less";
import { PanelContainerComponent } from "./Explorer/Panes/PanelContainerComponent";
import { SplashScreen } from "./Explorer/SplashScreen/SplashScreen";
import { Dialog, DialogProps } from "./Explorer/Controls/Dialog";
import "./Explorer/SplashScreen/SplashScreen.less";
import "./Explorer/Tabs/QueryTab.less";
import { useConfig } from "./hooks/useConfig";
import { useExplorerState } from "./hooks/useExplorerState";
import { useKnockoutExplorer } from "./hooks/useKnockoutExplorer";
import { useSidePanel } from "./hooks/useSidePanel";
import { KOCommentEnd, KOCommentIfStart } from "./koComment";
import "./Libs/is-integer-polyfill";
import "./Libs/jquery";
import "./Shared/appInsights";
initializeIcons();
@@ -103,20 +101,17 @@ const App: React.FunctionComponent = () => {
const config = useConfig();
const explorer = useKnockoutExplorer(config?.platform, explorerParams);
const { commandBarProperties } = useExplorerState(explorer);
if (!explorer) {
return <LoadingExplorer />;
}
return (
<div className="flexContainer">
<div
id="divSelfServe"
className="flexContainer"
data-bind="visible: selfServeType() && selfServeType() !== 'none', react: selfServeComponentAdapter"
></div>
<div
id="divExplorer"
data-bind="if: selfServeType() === 'none'"
className="flexContainer hideOverflows"
style={{ display: "none" }}
>
<div data-bind="react: commandBarComponentAdapter" />
<div id="divExplorer" className="flexContainer hideOverflows" style={{ display: "none" }}>
{/* Main Command Bar - Start */}
<CommandBarComponent {...commandBarProperties} />
{/* Collections Tree and Tabs - Begin */}
<div className="resourceTreeAndTabs">
{/* Collections Tree - Start */}
@@ -245,25 +240,6 @@ const App: React.FunctionComponent = () => {
/>
</div>
</div>
{/* Global loader - Start */}
<div className="splashLoaderContainer" data-bind="visible: isRefreshingExplorer">
<div className="splashLoaderContentContainer">
<div data-bind="visible: selfServeType() === undefined, react: selfServeLoadingComponentAdapter"></div>
<div data-bind="if: selfServeType() === 'none'" style={{ display: "none" }}>
<p className="connectExplorerContent">
<img src={hdeConnectImage} alt="Azure Cosmos DB" />
</p>
<p className="splashLoaderTitle" id="explorerLoadingStatusTitle">
Welcome to Azure Cosmos DB
</p>
<p className="splashLoaderText" id="explorerLoadingStatusText" role="alert">
Connecting...
</p>
</div>
</div>
</div>
{/* Global loader - End */}
<PanelContainerComponent
isOpen={isPanelOpen}
panelContent={panelContent}
@@ -307,3 +283,21 @@ const App: React.FunctionComponent = () => {
};
ReactDOM.render(<App />, document.body);
function LoadingExplorer(): JSX.Element {
return (
<div className="splashLoaderContainer">
<div className="splashLoaderContentContainer">
<p className="connectExplorerContent">
<img src={hdeConnectImage} alt="Azure Cosmos DB" />
</p>
<p className="splashLoaderTitle" id="explorerLoadingStatusTitle">
Welcome to Azure Cosmos DB
</p>
<p className="splashLoaderText" id="explorerLoadingStatusText" role="alert">
Connecting...
</p>
</div>
</div>
);
}

View File

@@ -1,4 +1,4 @@
import { ChoiceItem, Description, Info, InputType, NumberUiType, SmartUiInput } from "./SelfServeTypes";
import { ChoiceItem, Description, Info, InputType, NumberUiType, SmartUiInput, RefreshParams } from "./SelfServeTypes";
import { addPropertyToMap, DecoratorProperties, buildSmartUiDescriptor } from "./SelfServeUtils";
type ValueOf<T> = T[keyof T];
@@ -33,7 +33,9 @@ export interface ChoiceInputOptions extends InputOptionsBase {
}
export interface DescriptionDisplayOptions {
labelTKey?: string;
description?: (() => Promise<Description>) | Description;
isDynamicDescription?: boolean;
}
type InputOptions =
@@ -56,7 +58,7 @@ const isChoiceInputOptions = (inputOptions: InputOptions): inputOptions is Choic
};
const isDescriptionDisplayOptions = (inputOptions: InputOptions): inputOptions is DescriptionDisplayOptions => {
return "description" in inputOptions;
return "description" in inputOptions || "isDynamicDescription" in inputOptions;
};
const addToMap = (...decorators: Decorator[]): PropertyDecorator => {
@@ -80,7 +82,11 @@ const addToMap = (...decorators: Decorator[]): PropertyDecorator => {
};
export const OnChange = (
onChange: (currentState: Map<string, SmartUiInput>, newValue: InputType) => Map<string, SmartUiInput>
onChange: (
newValue: InputType,
currentState: Map<string, SmartUiInput>,
baselineValues: ReadonlyMap<string, SmartUiInput>
) => Map<string, SmartUiInput>
): PropertyDecorator => {
return addToMap({ name: "onChange", value: onChange });
};
@@ -111,7 +117,11 @@ export const Values = (inputOptions: InputOptions): PropertyDecorator => {
{ name: "choices", value: inputOptions.choices }
);
} else if (isDescriptionDisplayOptions(inputOptions)) {
return addToMap({ name: "description", value: inputOptions.description });
return addToMap(
{ name: "labelTKey", value: inputOptions.labelTKey },
{ name: "description", value: inputOptions.description },
{ name: "isDynamicDescription", value: inputOptions.isDynamicDescription }
);
} else {
return addToMap(
{ name: "labelTKey", value: inputOptions.labelTKey },
@@ -126,8 +136,8 @@ export const IsDisplayable = (): ClassDecorator => {
};
};
export const ClassInfo = (info: (() => Promise<Info>) | Info): ClassDecorator => {
export const RefreshOptions = (refreshParams: RefreshParams): ClassDecorator => {
return (target) => {
addPropertyToMap(target.prototype, "root", target.name, "info", info);
addPropertyToMap(target.prototype, "root", target.name, "refreshParams", refreshParams);
};
};

View File

@@ -64,13 +64,20 @@ export const initialize = async (): Promise<InitializeResponse> => {
};
export const onRefreshSelfServeExample = async (): Promise<RefreshResult> => {
const refreshCountString = SessionStorageUtility.getEntry("refreshCount");
const refreshCount = refreshCountString ? parseInt(refreshCountString) : 0;
const subscriptionId = userContext.subscriptionId;
const resourceGroup = userContext.resourceGroup;
const databaseAccountName = userContext.databaseAccount.name;
const databaseAccountGetResults = await get(subscriptionId, resourceGroup, databaseAccountName);
const isUpdateInProgress = databaseAccountGetResults.properties.provisioningState !== "Succeeded";
const progressToBeSent = refreshCount % 5 === 0 ? isUpdateInProgress : true;
SessionStorageUtility.setEntry("refreshCount", (refreshCount + 1).toString());
return {
isUpdateInProgress: isUpdateInProgress,
notificationMessage: "RefreshMessage",
isUpdateInProgress: progressToBeSent,
updateInProgressMessageTKey: "UpdateInProgressMessage",
};
};

View File

@@ -1,13 +1,14 @@
import { PropertyInfo, OnChange, Values, IsDisplayable, ClassInfo } from "../Decorators";
import { PropertyInfo, OnChange, Values, IsDisplayable, RefreshOptions } from "../Decorators";
import {
ChoiceItem,
Description,
DescriptionType,
Info,
InputType,
NumberUiType,
OnSaveResult,
RefreshResult,
SelfServeBaseClass,
SelfServeNotification,
SelfServeNotificationType,
SmartUiInput,
} from "../SelfServeTypes";
import {
@@ -27,16 +28,19 @@ const regionDropdownItems: ChoiceItem[] = [
{ label: "East US 2", key: Regions.EastUS2 },
];
const selfServeExampleInfo: Info = {
messageTKey: "ClassInfo",
};
const regionDropdownInfo: Info = {
messageTKey: "RegionDropdownInfo",
};
const onRegionsChange = (currentState: Map<string, SmartUiInput>, newValue: InputType): Map<string, SmartUiInput> => {
const onRegionsChange = (newValue: InputType, currentState: Map<string, SmartUiInput>): Map<string, SmartUiInput> => {
currentState.set("regions", { value: newValue });
const currentRegionText = `current region selected is ${newValue}`;
currentState.set("currentRegionText", {
value: { textTKey: currentRegionText, type: DescriptionType.Text } as Description,
hidden: false,
});
const currentEnableLogging = currentState.get("enableLogging");
if (newValue === Regions.NorthCentralUS) {
currentState.set("enableLogging", { value: false, disabled: true });
@@ -47,8 +51,8 @@ const onRegionsChange = (currentState: Map<string, SmartUiInput>, newValue: Inpu
};
const onEnableDbLevelThroughputChange = (
currentState: Map<string, SmartUiInput>,
newValue: InputType
newValue: InputType,
currentState: Map<string, SmartUiInput>
): Map<string, SmartUiInput> => {
currentState.set("enableDbLevelThroughput", { value: newValue });
const currentDbThroughput = currentState.get("dbThroughput");
@@ -57,9 +61,15 @@ const onEnableDbLevelThroughputChange = (
return currentState;
};
const validate = (currentvalues: Map<string, SmartUiInput>): void => {
const validate = (
currentvalues: Map<string, SmartUiInput>,
baselineValues: ReadonlyMap<string, SmartUiInput>
): void => {
if (currentvalues.get("dbThroughput") === baselineValues.get("dbThroughput")) {
throw new Error("DbThroughputValidationError");
}
if (!currentvalues.get("regions").value || !currentvalues.get("accountName").value) {
throw new Error("ValidationError");
throw new Error("RegionsAndAccountNameValidationError");
}
};
@@ -86,12 +96,12 @@ const validate = (currentvalues: Map<string, SmartUiInput>): void => {
*/
@IsDisplayable()
/*
@ClassInfo()
- optional
- input: Info | () => Promise<Info>
- role: Display an Info bar as the first element of the UI.
@RefreshOptions()
- role: Passes the refresh options to be used by the self serve model.
- inputs:
retryIntervalInMs - The time interval between refresh attempts when an update in ongoing.
*/
@ClassInfo(selfServeExampleInfo)
@RefreshOptions({ retryIntervalInMs: 2000 })
export default class SelfServeExample extends SelfServeBaseClass {
/*
onRefresh()
@@ -109,18 +119,21 @@ export default class SelfServeExample extends SelfServeBaseClass {
/*
onSave()
- input: (currentValues: Map<string, InputType>) => Promise<void>
- input: (currentValues: Map<string, InputType>, baselineValues: ReadonlyMap<string, SmartUiInput>) => Promise<string>
- role: Callback that is triggerred when the submit button is clicked. You should perform your rest API
calls here using the data from the different inputs passed as a Map to this callback function.
In this example, the onSave callback simply sets the value for keys corresponding to the field name
in the SessionStorage.
- returns: SelfServeNotification -
message: The message to be displayed in the message bar after the onSave is completed
type: The type of message bar to be used (info, warning, error)
in the SessionStorage. It uses the currentValues and baselineValues maps to perform custom validations
as well.
- returns: The initialize, success and failure messages to be displayed in the Portal Notification blade after the operation is completed.
*/
public onSave = async (currentValues: Map<string, SmartUiInput>): Promise<SelfServeNotification> => {
validate(currentValues);
public onSave = async (
currentValues: Map<string, SmartUiInput>,
baselineValues: ReadonlyMap<string, SmartUiInput>
): Promise<OnSaveResult> => {
validate(currentValues, baselineValues);
const regions = Regions[currentValues.get("regions")?.value as keyof typeof Regions];
const enableLogging = currentValues.get("enableLogging")?.value as boolean;
const accountName = currentValues.get("accountName")?.value as string;
@@ -128,8 +141,48 @@ export default class SelfServeExample extends SelfServeBaseClass {
const enableDbLevelThroughput = currentValues.get("enableDbLevelThroughput")?.value as boolean;
let dbThroughput = currentValues.get("dbThroughput")?.value as number;
dbThroughput = enableDbLevelThroughput ? dbThroughput : undefined;
try {
await update(regions, enableLogging, accountName, collectionThroughput, dbThroughput);
return { message: "SubmissionMessage", type: SelfServeNotificationType.info };
if (currentValues.get("regions") === baselineValues.get("regions")) {
return {
operationStatusUrl: undefined,
portalNotification: {
initialize: {
titleTKey: "SubmissionMessageSuccessTitle",
messageTKey: "SubmissionMessageForSameRegionText",
},
success: {
titleTKey: "UpdateCompletedMessageTitle",
messageTKey: "UpdateCompletedMessageText",
},
failure: {
titleTKey: "SubmissionMessageErrorTitle",
messageTKey: "SubmissionMessageErrorText",
},
},
};
} else {
return {
operationStatusUrl: undefined,
portalNotification: {
initialize: {
titleTKey: "SubmissionMessageSuccessTitle",
messageTKey: "SubmissionMessageForNewRegionText",
},
success: {
titleTKey: "UpdateCompletedMessageTitle",
messageTKey: "UpdateCompletedMessageText",
},
failure: {
titleTKey: "SubmissionMessageErrorTitle",
messageTKey: "SubmissionMessageErrorText",
},
},
};
}
} catch (error) {
throw new Error("OnSaveFailureMessage");
}
};
/*
@@ -150,6 +203,11 @@ export default class SelfServeExample extends SelfServeBaseClass {
public initialize = async (): Promise<Map<string, SmartUiInput>> => {
const initializeResponse = await initialize();
const defaults = new Map<string, SmartUiInput>();
const currentRegionText = `current region selected is ${initializeResponse.regions}`;
defaults.set("currentRegionText", {
value: { textTKey: currentRegionText, type: DescriptionType.Text } as Description,
hidden: false,
});
defaults.set("regions", { value: initializeResponse.regions });
defaults.set("enableLogging", { value: initializeResponse.enableLogging });
const accountName = initializeResponse.accountName;
@@ -172,15 +230,24 @@ export default class SelfServeExample extends SelfServeBaseClass {
e) Text (with optional hyperlink) for descriptions
*/
@Values({
labelTKey: "DescriptionLabel",
description: {
textTKey: "DescriptionText",
type: DescriptionType.Text,
link: {
href: "https://docs.microsoft.com/en-us/azure/cosmos-db/introduction",
href: "https://aka.ms/cosmos-create-account-portal",
textTKey: "DecriptionLinkText",
},
},
})
description: string;
@Values({
labelTKey: "Current Region",
isDynamicDescription: true,
})
currentRegionText: string;
/*
@PropertyInfo()
- optional
@@ -192,8 +259,8 @@ export default class SelfServeExample extends SelfServeBaseClass {
/*
@OnChange()
- optional
- input: (currentValues: Map<string, InputType>, newValue: InputType) => Map<string, InputType>
- role: Takes a Map of current values and the newValue for this property as inputs. This is called when a property,
- input: (currentValues: Map<string, InputType>, newValue: InputType, baselineValues: ReadonlyMap<string, SmartUiInput>) => Map<string, InputType>
- role: Takes a Map of current values, the newValue for this property and a ReadonlyMap of baselineValues as inputs. This is called when a property,
say prop1, changes its value in the UI. This can be used to
a) Change the value (and reflect it in the UI) for prop2 based on prop1.
b) Change the visibility for prop2 in the UI, based on prop1

View File

@@ -0,0 +1,16 @@
.selfServeComponentContainer {
text-transform: none;
line-height: 1.28581;
letter-spacing: 0;
font-size: 14px;
font-weight: 400;
color: #182026;
height: 100%;
min-height: 100vh;
width: 100%;
background-color: #FFFFFF;
}
body {
margin: 0;
}

View File

@@ -0,0 +1,92 @@
import * as React from "react";
import ReactDOM from "react-dom";
import { sendMessage } from "../Common/MessageHandler";
import { isInvalidParentFrameOrigin } from "../Utils/MessageValidation";
import { SelfServeComponent } from "./SelfServeComponent";
import { SelfServeDescriptor } from "./SelfServeTypes";
import { SelfServeType } from "./SelfServeUtils";
import { SelfServeFrameInputs } from "../Contracts/ViewModels";
import { initializeIcons } from "office-ui-fabric-react/lib/Icons";
import { configContext, updateConfigContext } from "../ConfigContext";
import { normalizeArmEndpoint } from "../Common/EnvironmentUtility";
import { updateUserContext } from "../UserContext";
import "./SelfServe.less";
import { Spinner, SpinnerSize } from "office-ui-fabric-react";
initializeIcons();
const getDescriptor = async (selfServeType: SelfServeType): Promise<SelfServeDescriptor> => {
switch (selfServeType) {
case SelfServeType.example: {
const SelfServeExample = await import(/* webpackChunkName: "SelfServeExample" */ "./Example/SelfServeExample");
return new SelfServeExample.default().toSelfServeDescriptor();
}
case SelfServeType.sqlx: {
const SqlX = await import(/* webpackChunkName: "SqlX" */ "./SqlX/SqlX");
return new SqlX.default().toSelfServeDescriptor();
}
default:
return undefined;
}
};
const renderComponent = (selfServeDescriptor: SelfServeDescriptor): JSX.Element => {
if (!selfServeDescriptor) {
return <h1>Invalid self serve type!</h1>;
}
return <SelfServeComponent descriptor={selfServeDescriptor} />;
};
const renderSpinner = (): JSX.Element => {
return <Spinner size={SpinnerSize.large}></Spinner>;
};
const handleMessage = async (event: MessageEvent): Promise<void> => {
if (isInvalidParentFrameOrigin(event)) {
return;
}
if (event.data["signature"] !== "pcIframe") {
return;
}
if (typeof event.data !== "object") {
return;
}
const inputs = event.data.data.inputs as SelfServeFrameInputs;
if (!inputs) {
return;
}
const urlSearchParams = new URLSearchParams(window.location.search);
const selfServeTypeText = inputs.selfServeType || urlSearchParams.get("selfServeType");
const selfServeType = SelfServeType[selfServeTypeText?.toLowerCase() as keyof typeof SelfServeType];
if (
!inputs.subscriptionId ||
!inputs.resourceGroup ||
!inputs.databaseAccount ||
!inputs.authorizationToken ||
!inputs.csmEndpoint ||
!selfServeType
) {
return;
}
updateConfigContext({
ARM_ENDPOINT: normalizeArmEndpoint(inputs.csmEndpoint || configContext.ARM_ENDPOINT),
});
updateUserContext({
authorizationToken: inputs.authorizationToken,
databaseAccount: inputs.databaseAccount,
resourceGroup: inputs.resourceGroup,
subscriptionId: inputs.subscriptionId,
});
const descriptor = await getDescriptor(selfServeType);
ReactDOM.render(renderComponent(descriptor), document.getElementById("selfServeContent"));
};
ReactDOM.render(renderSpinner(), document.getElementById("selfServeContent"));
window.addEventListener("message", handleMessage, false);
sendMessage("ready");

View File

@@ -1,7 +1,7 @@
import React from "react";
import { shallow } from "enzyme";
import { SelfServeComponent, SelfServeComponentState } from "./SelfServeComponent";
import { NumberUiType, SelfServeDescriptor, SelfServeNotificationType, SmartUiInput } from "./SelfServeTypes";
import { NumberUiType, OnSaveResult, SelfServeDescriptor, SmartUiInput } from "./SelfServeTypes";
describe("SelfServeComponent", () => {
const defaultValues = new Map<string, SmartUiInput>([
@@ -17,13 +17,20 @@ describe("SelfServeComponent", () => {
const initializeMock = jest.fn(async () => new Map(defaultValues));
const onSaveMock = jest.fn(async () => {
return { message: "submitted successfully", type: SelfServeNotificationType.info };
return {
operationStatusUrl: undefined,
} as OnSaveResult;
});
const refreshResult = {
isUpdateInProgress: false,
updateInProgressMessageTKey: "refresh performed successfully",
};
const onRefreshMock = jest.fn(async () => {
return { isUpdateInProgress: false, notificationMessage: "refresh performed successfully" };
return { ...refreshResult };
});
const onRefreshIsUpdatingMock = jest.fn(async () => {
return { isUpdateInProgress: true, notificationMessage: "refresh performed successfully" };
return { ...refreshResult, isUpdateInProgress: true };
});
const exampleData: SelfServeDescriptor = {
@@ -136,16 +143,15 @@ describe("SelfServeComponent", () => {
wrapper.update();
state = wrapper.state() as SelfServeComponentState;
isEqual(state.baselineValues, updatedValues);
selfServeComponent.resetBaselineValues();
selfServeComponent.updateBaselineValues();
state = wrapper.state() as SelfServeComponentState;
isEqual(state.baselineValues, defaultValues);
isEqual(state.currentValues, state.baselineValues);
// clicking refresh calls onRefresh. If component is not updating, it calls initialize() as well
// clicking refresh calls onRefresh.
selfServeComponent.onRefreshClicked();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(onRefreshMock).toHaveBeenCalledTimes(2);
expect(initializeMock).toHaveBeenCalledTimes(2);
selfServeComponent.onSaveButtonClick();
expect(onSaveMock).toHaveBeenCalledTimes(1);

View File

@@ -15,20 +15,45 @@ import {
InputType,
RefreshResult,
SelfServeDescriptor,
SelfServeNotification,
SmartUiInput,
DescriptionDisplay,
StringInput,
NumberInput,
BooleanInput,
ChoiceInput,
SelfServeNotificationType,
} from "./SelfServeTypes";
import { SmartUiComponent, SmartUiDescriptor } from "../Explorer/Controls/SmartUi/SmartUiComponent";
import { getMessageBarType } from "./SelfServeUtils";
import { Translation } from "react-i18next";
import { TFunction } from "i18next";
import "../i18n";
import { sendMessage } from "../Common/MessageHandler";
import { SelfServeMessageTypes } from "../Contracts/SelfServeContracts";
import promiseRetry, { AbortError } from "p-retry";
interface SelfServeNotification {
message: string;
type: MessageBarType;
isCancellable: boolean;
}
interface PortalNotificationContent {
retryIntervalInMs: number;
operationStatusUrl: string;
portalNotification?: {
initialize: {
title: string;
message: string;
};
success: {
title: string;
message: string;
};
failure: {
title: string;
message: string;
};
};
}
export interface SelfServeComponentProps {
descriptor: SelfServeDescriptor;
@@ -39,17 +64,26 @@ export interface SelfServeComponentState {
currentValues: Map<string, SmartUiInput>;
baselineValues: Map<string, SmartUiInput>;
isInitializing: boolean;
isSaving: boolean;
hasErrors: boolean;
compileErrorMessage: string;
notification: SelfServeNotification;
refreshResult: RefreshResult;
notification: SelfServeNotification;
}
export class SelfServeComponent extends React.Component<SelfServeComponentProps, SelfServeComponentState> {
private static readonly defaultRetryIntervalInMs = 30000;
private smartUiGeneratorClassName: string;
private retryIntervalInMs: number;
private retryOptions: promiseRetry.Options;
private translationFunction: TFunction;
componentDidMount(): void {
this.performRefresh();
this.performRefresh().then(() => {
if (this.state.refreshResult?.isUpdateInProgress) {
promiseRetry(() => this.pollRefresh(), this.retryOptions);
}
});
this.initializeSmartUiComponent();
}
@@ -60,12 +94,18 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
currentValues: new Map(),
baselineValues: new Map(),
isInitializing: true,
isSaving: false,
hasErrors: false,
compileErrorMessage: undefined,
notification: undefined,
refreshResult: undefined,
notification: undefined,
};
this.smartUiGeneratorClassName = this.props.descriptor.root.id;
this.retryIntervalInMs = this.props.descriptor.refreshParams?.retryIntervalInMs;
if (!this.retryIntervalInMs) {
this.retryIntervalInMs = SelfServeComponent.defaultRetryIntervalInMs;
}
this.retryOptions = { forever: true, maxTimeout: this.retryIntervalInMs, minTimeout: this.retryIntervalInMs };
}
private onError = (hasErrors: boolean): void => {
@@ -109,7 +149,7 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
this.setState({ currentValues, baselineValues });
};
public resetBaselineValues = (): void => {
public updateBaselineValues = (): void => {
const currentValues = this.state.currentValues;
let baselineValues = this.state.baselineValues;
for (const key of currentValues.keys()) {
@@ -204,7 +244,11 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
private onInputChange = (input: AnyDisplay, newValue: InputType) => {
if (input.onChange) {
const newValues = input.onChange(this.state.currentValues, newValue);
const newValues = input.onChange(
newValue,
this.state.currentValues,
this.state.baselineValues as ReadonlyMap<string, SmartUiInput>
);
this.setState({ currentValues: newValues });
} else {
const dataFieldName = input.dataFieldName;
@@ -215,29 +259,62 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
}
};
public performSave = async (): Promise<void> => {
this.setState({ isSaving: true, notification: undefined });
try {
const onSaveResult = await this.props.descriptor.onSave(
this.state.currentValues,
this.state.baselineValues as ReadonlyMap<string, SmartUiInput>
);
if (onSaveResult.portalNotification) {
const requestInitializedPortalNotification = onSaveResult.portalNotification.initialize;
const requestSucceededPortalNotification = onSaveResult.portalNotification.success;
const requestFailedPortalNotification = onSaveResult.portalNotification.failure;
this.sendNotificationMessage({
retryIntervalInMs: this.retryIntervalInMs,
operationStatusUrl: onSaveResult.operationStatusUrl,
portalNotification: {
initialize: {
title: this.getTranslation(requestInitializedPortalNotification.titleTKey),
message: this.getTranslation(requestInitializedPortalNotification.messageTKey),
},
success: {
title: this.getTranslation(requestSucceededPortalNotification.titleTKey),
message: this.getTranslation(requestSucceededPortalNotification.messageTKey),
},
failure: {
title: this.getTranslation(requestFailedPortalNotification.titleTKey),
message: this.getTranslation(requestFailedPortalNotification.messageTKey),
},
},
});
}
promiseRetry(() => this.pollRefresh(), this.retryOptions);
} catch (error) {
this.setState({
notification: {
type: MessageBarType.error,
isCancellable: true,
message: this.getTranslation(error.message),
},
});
throw error;
} finally {
this.setState({ isSaving: false });
}
await this.onRefreshClicked();
this.updateBaselineValues();
};
public onSaveButtonClick = (): void => {
const onSavePromise = this.props.descriptor.onSave(this.state.currentValues);
onSavePromise.catch((error) => {
this.setState({
notification: {
message: `${error.message}`,
type: SelfServeNotificationType.error,
},
});
});
onSavePromise.then((notification: SelfServeNotification) => {
this.setState({
notification: {
message: notification.message,
type: notification.type,
},
});
this.resetBaselineValues();
this.onRefreshClicked();
});
this.performSave();
};
public isDiscardButtonDisabled = (): boolean => {
if (this.state.isSaving) {
return true;
}
for (const key of this.state.currentValues.keys()) {
const currentValue = JSON.stringify(this.state.currentValues.get(key));
const baselineValue = JSON.stringify(this.state.baselineValues.get(key));
@@ -250,7 +327,7 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
};
public isSaveButtonDisabled = (): boolean => {
if (this.state.hasErrors) {
if (this.state.hasErrors || this.state.isSaving) {
return true;
}
for (const key of this.state.currentValues.keys()) {
@@ -264,38 +341,69 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
return true;
};
private performRefresh = async (): Promise<RefreshResult> => {
private performRefresh = async (): Promise<void> => {
const refreshResult = await this.props.descriptor.onRefresh();
this.setState({ refreshResult: { ...refreshResult } });
return refreshResult;
let updateInProgressNotification: SelfServeNotification;
if (this.state.refreshResult?.isUpdateInProgress && !refreshResult.isUpdateInProgress) {
await this.initializeSmartUiComponent();
}
if (refreshResult.isUpdateInProgress) {
updateInProgressNotification = {
type: MessageBarType.info,
isCancellable: false,
message: this.getTranslation(refreshResult.updateInProgressMessageTKey),
};
}
this.setState({
refreshResult: { ...refreshResult },
notification: updateInProgressNotification,
});
};
public onRefreshClicked = async (): Promise<void> => {
this.setState({ isInitializing: true });
const refreshResult = await this.performRefresh();
if (!refreshResult.isUpdateInProgress) {
this.initializeSmartUiComponent();
}
await this.performRefresh();
this.setState({ isInitializing: false });
};
public getCommonTranslation = (translationFunction: TFunction, key: string): string => {
return translationFunction(`Common.${key}`);
public pollRefresh = async (): Promise<void> => {
try {
await this.performRefresh();
} catch (error) {
throw new AbortError(error);
}
const refreshResult = this.state.refreshResult;
if (refreshResult.isUpdateInProgress) {
throw new Error("update in progress. retrying ...");
}
};
private getCommandBarItems = (translate: TFunction): ICommandBarItemProps[] => {
public getCommonTranslation = (key: string): string => {
return this.getTranslation(key, "Common");
};
private getTranslation = (messageKey: string, prefix = `${this.smartUiGeneratorClassName}`): string => {
const translationKey = `${prefix}.${messageKey}`;
const translation = this.translationFunction ? this.translationFunction(translationKey) : messageKey;
if (translation === translationKey) {
return messageKey;
}
return translation;
};
private getCommandBarItems = (): ICommandBarItemProps[] => {
return [
{
key: "save",
text: this.getCommonTranslation(translate, "Save"),
text: this.getCommonTranslation("Save"),
iconProps: { iconName: "Save" },
split: true,
disabled: this.isSaveButtonDisabled(),
onClick: this.onSaveButtonClick,
onClick: () => this.onSaveButtonClick(),
},
{
key: "discard",
text: this.getCommonTranslation(translate, "Discard"),
text: this.getCommonTranslation("Discard"),
iconProps: { iconName: "Undo" },
split: true,
disabled: this.isDiscardButtonDisabled(),
@@ -305,7 +413,7 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
},
{
key: "refresh",
text: this.getCommonTranslation(translate, "Refresh"),
text: this.getCommonTranslation("Refresh"),
disabled: this.state.isInitializing,
iconProps: { iconName: "Refresh" },
split: true,
@@ -316,12 +424,11 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
];
};
private getNotificationMessageTranslation = (translationFunction: TFunction, messageKey: string): string => {
const translation = translationFunction(messageKey);
if (translation === `${this.smartUiGeneratorClassName}.${messageKey}`) {
return messageKey;
}
return translation;
private sendNotificationMessage = (portalNotificationContent: PortalNotificationContent): void => {
sendMessage({
type: SelfServeMessageTypes.Notification,
data: { portalNotificationContent },
});
};
public render(): JSX.Element {
@@ -332,14 +439,14 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
return (
<Translation>
{(translate) => {
const getTranslation = (key: string): string => {
return translate(`${this.smartUiGeneratorClassName}.${key}`);
};
if (!this.translationFunction) {
this.translationFunction = translate;
}
return (
<div style={{ overflowX: "auto" }}>
<Stack tokens={containerStackTokens} styles={{ root: { padding: 10 } }}>
<CommandBar styles={{ root: { paddingLeft: 0 } }} items={this.getCommandBarItems(translate)} />
<CommandBar styles={{ root: { paddingLeft: 0 } }} items={this.getCommandBarItems()} />
{this.state.isInitializing ? (
<Spinner
size={SpinnerSize.large}
@@ -347,27 +454,25 @@ export class SelfServeComponent extends React.Component<SelfServeComponentProps,
/>
) : (
<>
{this.state.refreshResult?.isUpdateInProgress && (
<MessageBar messageBarType={MessageBarType.info} styles={{ root: { width: 400 } }}>
{getTranslation(this.state.refreshResult.notificationMessage)}
</MessageBar>
)}
{this.state.notification && (
<MessageBar
messageBarType={getMessageBarType(this.state.notification.type)}
styles={{ root: { width: 400 } }}
onDismiss={() => this.setState({ notification: undefined })}
messageBarType={this.state.notification.type}
onDismiss={
this.state.notification.isCancellable
? () => this.setState({ notification: undefined })
: undefined
}
>
{this.getNotificationMessageTranslation(getTranslation, this.state.notification.message)}
{this.state.notification.message}
</MessageBar>
)}
<SmartUiComponent
disabled={this.state.refreshResult?.isUpdateInProgress}
disabled={this.state.refreshResult?.isUpdateInProgress || this.state.isSaving}
descriptor={this.state.root as SmartUiDescriptor}
currentValues={this.state.currentValues}
onInputChange={this.onInputChange}
onError={this.onError}
getTranslation={getTranslation}
getTranslation={this.getTranslation}
/>
</>
)}

View File

@@ -1,56 +0,0 @@
/**
* This adapter is responsible to render the React component
* If the component signals a change through the callback passed in the properties, it must render the React component when appropriate
* and update any knockout observables passed from the parent.
*/
import * as ko from "knockout";
import * as React from "react";
import { ReactAdapter } from "../Bindings/ReactBindingHandler";
import Explorer from "../Explorer/Explorer";
import { SelfServeComponent } from "./SelfServeComponent";
import { SelfServeDescriptor } from "./SelfServeTypes";
import { SelfServeType } from "./SelfServeUtils";
export class SelfServeComponentAdapter implements ReactAdapter {
public parameters: ko.Observable<SelfServeDescriptor>;
public container: Explorer;
constructor(container: Explorer) {
this.container = container;
this.parameters = ko.observable(undefined);
this.container.selfServeType.subscribe(() => {
this.triggerRender();
});
}
public static getDescriptor = async (selfServeType: SelfServeType): Promise<SelfServeDescriptor> => {
switch (selfServeType) {
case SelfServeType.example: {
const SelfServeExample = await import(/* webpackChunkName: "SelfServeExample" */ "./Example/SelfServeExample");
return new SelfServeExample.default().toSelfServeDescriptor();
}
case SelfServeType.sqlx: {
const SqlX = await import(/* webpackChunkName: "SqlX" */ "./SqlX/SqlX");
return new SqlX.default().toSelfServeDescriptor();
}
default:
return undefined;
}
};
public renderComponent(): JSX.Element {
if (this.container.selfServeType() === SelfServeType.invalid) {
return <h1>Invalid self serve type!</h1>;
}
const smartUiDescriptor = this.parameters();
return smartUiDescriptor ? <SelfServeComponent descriptor={smartUiDescriptor} /> : <></>;
}
private triggerRender() {
window.requestAnimationFrame(async () => {
const selfServeType = this.container.selfServeType();
const smartUiDescriptor = await SelfServeComponentAdapter.getDescriptor(selfServeType);
this.parameters(smartUiDescriptor);
});
}
}

View File

@@ -1,25 +0,0 @@
/**
* This adapter is responsible to render the React component
* If the component signals a change through the callback passed in the properties, it must render the React component when appropriate
* and update any knockout observables passed from the parent.
*/
import * as ko from "knockout";
import { Spinner, SpinnerSize } from "office-ui-fabric-react";
import * as React from "react";
import { ReactAdapter } from "../Bindings/ReactBindingHandler";
export class SelfServeLoadingComponentAdapter implements ReactAdapter {
public parameters: ko.Observable<number>;
constructor() {
this.parameters = ko.observable(Date.now());
}
public renderComponent(): JSX.Element {
return <Spinner size={SpinnerSize.large} />;
}
private triggerRender() {
window.requestAnimationFrame(() => this.renderComponent());
}
}

View File

@@ -3,7 +3,11 @@ interface BaseInput {
errorMessage?: string;
type: InputTypeValue;
labelTKey?: (() => Promise<string>) | string;
onChange?: (currentState: Map<string, SmartUiInput>, newValue: InputType) => Map<string, SmartUiInput>;
onChange?: (
newValue: InputType,
currentState: Map<string, SmartUiInput>,
baselineValues: ReadonlyMap<string, SmartUiInput>
) => Map<string, SmartUiInput>;
placeholderTKey?: (() => Promise<string>) | string;
}
@@ -44,16 +48,23 @@ export interface Node {
export interface SelfServeDescriptor {
root: Node;
initialize?: () => Promise<Map<string, SmartUiInput>>;
onSave?: (currentValues: Map<string, SmartUiInput>) => Promise<SelfServeNotification>;
onSave?: (
currentValues: Map<string, SmartUiInput>,
baselineValues: ReadonlyMap<string, SmartUiInput>
) => Promise<OnSaveResult>;
inputNames?: string[];
onRefresh?: () => Promise<RefreshResult>;
refreshParams?: RefreshParams;
}
export type AnyDisplay = NumberInput | BooleanInput | StringInput | ChoiceInput | DescriptionDisplay;
export abstract class SelfServeBaseClass {
public abstract initialize: () => Promise<Map<string, SmartUiInput>>;
public abstract onSave: (currentValues: Map<string, SmartUiInput>) => Promise<SelfServeNotification>;
public abstract onSave: (
currentValues: Map<string, SmartUiInput>,
baselineValues: ReadonlyMap<string, SmartUiInput>
) => Promise<OnSaveResult>;
public abstract onRefresh: () => Promise<RefreshResult>;
public toSelfServeDescriptor(): SelfServeDescriptor {
@@ -70,7 +81,7 @@ export abstract class SelfServeBaseClass {
throw new Error(`onRefresh() was not declared for the class '${className}'`);
}
if (!selfServeDescriptor?.root) {
throw new Error(`@SmartUi decorator was not declared for the class '${className}'`);
throw new Error(`@IsDisplayable decorator was not declared for the class '${className}'`);
}
selfServeDescriptor.initialize = this.initialize;
@@ -89,7 +100,7 @@ export enum NumberUiType {
export type ChoiceItem = { label: string; key: string };
export type InputType = number | string | boolean | ChoiceItem;
export type InputType = number | string | boolean | ChoiceItem | Description;
export interface Info {
messageTKey: string;
@@ -99,8 +110,15 @@ export interface Info {
};
}
export enum DescriptionType {
Text,
InfoMessageBar,
WarningMessageBar,
}
export interface Description {
textTKey: string;
type: DescriptionType;
link?: {
href: string;
textTKey: string;
@@ -113,18 +131,29 @@ export interface SmartUiInput {
disabled?: boolean;
}
export enum SelfServeNotificationType {
info = "info",
warning = "warning",
error = "error",
}
export interface SelfServeNotification {
message: string;
type: SelfServeNotificationType;
export interface OnSaveResult {
operationStatusUrl: string;
portalNotification?: {
initialize: {
titleTKey: string;
messageTKey: string;
};
success: {
titleTKey: string;
messageTKey: string;
};
failure: {
titleTKey: string;
messageTKey: string;
};
};
}
export interface RefreshResult {
isUpdateInProgress: boolean;
notificationMessage: string;
updateInProgressMessageTKey: string;
}
export interface RefreshParams {
retryIntervalInMs: number;
}

View File

@@ -1,11 +1,11 @@
import { NumberUiType, RefreshResult, SelfServeBaseClass, SelfServeNotification, SmartUiInput } from "./SelfServeTypes";
import { NumberUiType, OnSaveResult, RefreshResult, SelfServeBaseClass, SmartUiInput } from "./SelfServeTypes";
import { DecoratorProperties, mapToSmartUiDescriptor, updateContextWithDecorator } from "./SelfServeUtils";
describe("SelfServeUtils", () => {
it("initialize should be declared for self serve classes", () => {
class Test extends SelfServeBaseClass {
public initialize: () => Promise<Map<string, SmartUiInput>>;
public onSave: (currentValues: Map<string, SmartUiInput>) => Promise<SelfServeNotification>;
public onSave: (currentValues: Map<string, SmartUiInput>) => Promise<OnSaveResult>;
public onRefresh: () => Promise<RefreshResult>;
}
expect(() => new Test().toSelfServeDescriptor()).toThrow("initialize() was not declared for the class 'Test'");
@@ -14,7 +14,7 @@ describe("SelfServeUtils", () => {
it("onSave should be declared for self serve classes", () => {
class Test extends SelfServeBaseClass {
public initialize = jest.fn();
public onSave: () => Promise<SelfServeNotification>;
public onSave: () => Promise<OnSaveResult>;
public onRefresh: () => Promise<RefreshResult>;
}
expect(() => new Test().toSelfServeDescriptor()).toThrow("onSave() was not declared for the class 'Test'");
@@ -29,14 +29,14 @@ describe("SelfServeUtils", () => {
expect(() => new Test().toSelfServeDescriptor()).toThrow("onRefresh() was not declared for the class 'Test'");
});
it("@SmartUi decorator must be present for self serve classes", () => {
it("@IsDisplayable decorator must be present for self serve classes", () => {
class Test extends SelfServeBaseClass {
public initialize = jest.fn();
public onSave = jest.fn();
public onRefresh = jest.fn();
}
expect(() => new Test().toSelfServeDescriptor()).toThrow(
"@SmartUi decorator was not declared for the class 'Test'"
"@IsDisplayable decorator was not declared for the class 'Test'"
);
});

View File

@@ -1,4 +1,3 @@
import { MessageBarType } from "office-ui-fabric-react";
import "reflect-metadata";
import {
Node,
@@ -15,8 +14,9 @@ import {
SelfServeDescriptor,
SmartUiInput,
StringInput,
SelfServeNotificationType,
RefreshParams,
} from "./SelfServeTypes";
import { userContext } from "../UserContext";
export enum SelfServeType {
// No self serve type passed, launch explorer
@@ -28,6 +28,14 @@ export enum SelfServeType {
sqlx = "sqlx",
}
export enum BladeType {
SqlKeys = "keys",
MongoKeys = "mongoDbKeys",
CassandraKeys = "cassandraDbKeys",
GremlinKeys = "keys",
TableKeys = "tableKeys",
}
export interface DecoratorProperties {
id: string;
info?: (() => Promise<Info>) | Info;
@@ -44,9 +52,13 @@ export interface DecoratorProperties {
uiType?: string;
errorMessage?: string;
description?: (() => Promise<Description>) | Description;
onChange?: (currentState: Map<string, SmartUiInput>, newValue: InputType) => Map<string, SmartUiInput>;
onSave?: (currentValues: Map<string, SmartUiInput>) => Promise<void>;
initialize?: () => Promise<Map<string, SmartUiInput>>;
isDynamicDescription?: boolean;
refreshParams?: RefreshParams;
onChange?: (
newValue: InputType,
currentState: Map<string, SmartUiInput>,
baselineValues: ReadonlyMap<string, SmartUiInput>
) => Map<string, SmartUiInput>;
}
const setValue = <T extends keyof DecoratorProperties, K extends DecoratorProperties[T]>(
@@ -83,7 +95,7 @@ export const updateContextWithDecorator = <T extends keyof DecoratorProperties,
descriptorValue: K
): void => {
if (!(context instanceof Map)) {
throw new Error(`@SmartUi should be the first decorator for the class '${className}'.`);
throw new Error(`@IsDisplayable should be the first decorator for the class '${className}'.`);
}
const propertyObject = context.get(propertyName) ?? { id: propertyName };
@@ -108,16 +120,17 @@ export const mapToSmartUiDescriptor = (
className: string,
context: Map<string, DecoratorProperties>
): SelfServeDescriptor => {
const inputNames: string[] = [];
const root = context.get("root");
context.delete("root");
const inputNames: string[] = [];
const smartUiDescriptor: SelfServeDescriptor = {
root: {
id: className,
info: root?.info,
info: undefined,
children: [],
},
refreshParams: root?.refreshParams,
};
while (context.size > 0) {
@@ -155,7 +168,10 @@ const getInput = (value: DecoratorProperties): AnyDisplay => {
}
return value as NumberInput;
case "string":
if (value.description) {
if (value.description || value.isDynamicDescription) {
if (value.description && value.isDynamicDescription) {
value.errorMessage = `dynamic descriptions should not have defaults set here.`;
}
return value as DescriptionDisplay;
}
if (!value.labelTKey) {
@@ -175,13 +191,9 @@ const getInput = (value: DecoratorProperties): AnyDisplay => {
}
};
export const getMessageBarType = (type: SelfServeNotificationType): MessageBarType => {
switch (type) {
case SelfServeNotificationType.info:
return MessageBarType.info;
case SelfServeNotificationType.warning:
return MessageBarType.warning;
case SelfServeNotificationType.error:
return MessageBarType.error;
}
export const generateBladeLink = (blade: BladeType): string => {
const subscriptionId = userContext.subscriptionId;
const resourceGroupName = userContext.resourceGroup;
const databaseAccountName = userContext.databaseAccount.name;
return `www.portal.azure.com/#@microsoft.onmicrosoft.com/resource/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.DocumentDb/databaseAccounts/${databaseAccountName}/${blade}`;
};

View File

@@ -1,18 +1,19 @@
import { IsDisplayable, OnChange, Values } from "../Decorators";
import {
ChoiceItem,
DescriptionType,
InputType,
NumberUiType,
OnSaveResult,
RefreshResult,
SelfServeBaseClass,
SelfServeNotification,
SmartUiInput,
} from "../SelfServeTypes";
import { refreshDedicatedGatewayProvisioning } from "./SqlX.rp";
const onEnableDedicatedGatewayChange = (
currentState: Map<string, SmartUiInput>,
newValue: InputType
newValue: InputType,
currentState: Map<string, SmartUiInput>
): Map<string, SmartUiInput> => {
const sku = currentState.get("sku");
const instances = currentState.get("instances");
@@ -49,7 +50,7 @@ export default class SqlX extends SelfServeBaseClass {
return refreshDedicatedGatewayProvisioning();
};
public onSave = async (currentValues: Map<string, SmartUiInput>): Promise<SelfServeNotification> => {
public onSave = async (currentValues: Map<string, SmartUiInput>): Promise<OnSaveResult> => {
validate(currentValues);
// TODO: add pre processing logic before calling the updateDedicatedGatewayProvisioning() RP call.
throw new Error(`onSave not implemented. No. of properties to save: ${currentValues.size}`);
@@ -63,6 +64,7 @@ export default class SqlX extends SelfServeBaseClass {
@Values({
description: {
textTKey: "Provisioning dedicated gateways for SqlX accounts.",
type: DescriptionType.Text,
link: {
href: "https://docs.microsoft.com/en-us/azure/cosmos-db/introduction",
textTKey: "Learn more about dedicated gateway.",

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="selfServeViewport" content="height=device-height, width=device-width, initial-scale=1.0" />
<title>Self Serve</title>
<link rel="shortcut icon" href="images/CosmosDB_rgb_ui_lighttheme.ico" type="image/x-icon" />
</head>
<body>
<div class="selfServeComponentContainer" id="selfServeContent"></div>
</body>
</html>

View File

@@ -1,4 +1,4 @@
import { StringUtility } from "./StringUtility";
import * as StringUtility from "./StringUtility";
export class LocalStorageUtility {
public static hasItem(key: StorageKey): boolean {

View File

@@ -1,4 +1,4 @@
import { StringUtility } from "./StringUtility";
import * as StringUtility from "./StringUtility";
describe("String utility", () => {
it("Convert to integer from string", () => {

View File

@@ -1,9 +1,7 @@
export class StringUtility {
public static toNumber(num: string | null): number {
export function toNumber(num: string | null): number {
return Number(num);
}
public static toBoolean(valueStr: string | null): boolean {
return valueStr === "true";
}
}
export function toBoolean(valueStr: string | null): boolean {
return valueStr === "true";
}

View File

@@ -17,12 +17,43 @@ interface UserContext {
useSDKOperations?: boolean;
subscriptionType?: SubscriptionType;
quotaId?: string;
// API Type is not yet provided by ARM. You need to manually inspect all the capabilities+kind so we abstract that logic in userContext
// This is coming in a future Cosmos ARM API version as a prperty on databaseAccount
apiType?: ApiType;
}
const userContext: Readonly<UserContext> = {} as const;
type ApiType = "SQL" | "Mongo" | "Gremlin" | "Tables" | "Cassandra";
const userContext: UserContext = {};
function updateUserContext(newContext: UserContext): void {
Object.assign(userContext, newContext);
Object.assign(userContext, { apiType: apiType(userContext.databaseAccount) });
}
function apiType(account: DatabaseAccount | undefined): ApiType {
if (!account) {
return "SQL";
}
const capabilities = account.properties?.capabilities;
if (capabilities) {
if (capabilities.find((c) => c.name === "EnableCassandra")) {
return "Cassandra";
}
if (capabilities.find((c) => c.name === "EnableGremlin")) {
return "Gremlin";
}
if (capabilities.find((c) => c.name === "EnableMongo")) {
return "Mongo";
}
if (capabilities.find((c) => c.name === "EnableTable")) {
return "Tables";
}
}
if (account.kind === "MongoDB" || account.kind === "Parse") {
return "Mongo";
}
return "SQL";
}
export { userContext, updateUserContext };

View File

@@ -8,15 +8,46 @@ interface KernelConnectionMetadata {
notebookConnectionInfo: DataModels.NotebookWorkspaceConnectionInfo;
}
export class NotebookConfigurationUtils {
private constructor() {}
export const _configureServiceEndpoints = async (kernelMetadata: KernelConnectionMetadata): Promise<void> => {
if (!kernelMetadata) {
// should never get into this state
Logger.logWarning("kernel metadata is null or undefined", "NotebookConfigurationUtils/configureServiceEndpoints");
return;
}
public static async configureServiceEndpoints(
const notebookConnectionInfo = kernelMetadata.notebookConnectionInfo;
const configurationEndpoints = kernelMetadata.configurationEndpoints;
if (notebookConnectionInfo && configurationEndpoints) {
try {
const headers: HeadersInit = { "Content-Type": "application/json" };
if (notebookConnectionInfo.authToken) {
headers["Authorization"] = `token ${notebookConnectionInfo.authToken}`;
}
const response = await fetch(`${notebookConnectionInfo.notebookServerEndpoint}/api/configureEndpoints`, {
method: "POST",
headers,
body: JSON.stringify(configurationEndpoints),
});
if (!response.ok) {
const responseMessage = await response.json();
Logger.logError(
getErrorMessage(responseMessage),
"NotebookConfigurationUtils/configureServiceEndpoints",
response.status
);
}
} catch (error) {
Logger.logError(getErrorMessage(error), "NotebookConfigurationUtils/configureServiceEndpoints");
}
}
};
export const configureServiceEndpoints = async (
notebookPath: string,
notebookConnectionInfo: DataModels.NotebookWorkspaceConnectionInfo,
kernelName: string,
clusterConnectionInfo: DataModels.SparkClusterConnectionInfo
): Promise<void> {
): Promise<void> => {
if (!notebookPath || !notebookConnectionInfo || !kernelName) {
Logger.logError(
"Invalid or missing notebook connection info/path",
@@ -53,40 +84,5 @@ export class NotebookConfigurationUtils {
name: kernelName,
};
return await NotebookConfigurationUtils._configureServiceEndpoints(kernelMetadata);
}
private static async _configureServiceEndpoints(kernelMetadata: KernelConnectionMetadata): Promise<void> {
if (!kernelMetadata) {
// should never get into this state
Logger.logWarning("kernel metadata is null or undefined", "NotebookConfigurationUtils/configureServiceEndpoints");
return;
}
const notebookConnectionInfo = kernelMetadata.notebookConnectionInfo;
const configurationEndpoints = kernelMetadata.configurationEndpoints;
if (notebookConnectionInfo && configurationEndpoints) {
try {
const headers: any = { "Content-Type": "application/json" };
if (notebookConnectionInfo.authToken) {
headers["Authorization"] = `token ${notebookConnectionInfo.authToken}`;
}
const response = await fetch(`${notebookConnectionInfo.notebookServerEndpoint}/api/configureEndpoints`, {
method: "POST",
headers,
body: JSON.stringify(configurationEndpoints),
});
if (!response.ok) {
const responseMessage = await response.json();
Logger.logError(
getErrorMessage(responseMessage),
"NotebookConfigurationUtils/configureServiceEndpoints",
response.status
);
}
} catch (error) {
Logger.logError(getErrorMessage(error), "NotebookConfigurationUtils/configureServiceEndpoints");
}
}
}
}
return await _configureServiceEndpoints(kernelMetadata);
};

View File

@@ -47,15 +47,14 @@ interface Options {
queryParams?: ARMQueryParams;
}
// TODO: This is very similar to what is happening in ResourceProviderClient.ts. Should probably merge them.
export async function armRequest<T>({
export async function armRequestWithoutPolling<T>({
host,
path,
apiVersion,
method,
body: requestBody,
queryParams,
}: Options): Promise<T> {
}: Options): Promise<{ result: T; operationStatusUrl: string }> {
const url = new URL(path, host);
url.searchParams.append("api-version", configContext.armAPIVersion || apiVersion);
if (queryParams) {
@@ -92,13 +91,33 @@ export async function armRequest<T>({
throw error;
}
const operationStatusUrl = response.headers && response.headers.get("location");
const operationStatusUrl = (response.headers && response.headers.get("location")) || "";
const responseBody = (await response.json()) as T;
return { result: responseBody, operationStatusUrl: operationStatusUrl };
}
// TODO: This is very similar to what is happening in ResourceProviderClient.ts. Should probably merge them.
export async function armRequest<T>({
host,
path,
apiVersion,
method,
body: requestBody,
queryParams,
}: Options): Promise<T> {
const armRequestResult = await armRequestWithoutPolling<T>({
host,
path,
apiVersion,
method,
body: requestBody,
queryParams,
});
const operationStatusUrl = armRequestResult.operationStatusUrl;
if (operationStatusUrl) {
return await promiseRetry(() => getOperationStatus(operationStatusUrl));
}
const responseBody = (await response.json()) as T;
return responseBody;
return armRequestResult.result;
}
async function getOperationStatus(operationStatusUrl: string) {

13
src/global.d.ts vendored
View File

@@ -1,11 +1,22 @@
import { AuthType } from "./AuthType";
import Explorer from "./Explorer/Explorer";
declare global {
interface Window {
/**
* @deprecated
* DO NOT take new usage of window.dataExplorer. If you must use Explorer, find it directly.
* */
dataExplorer: Explorer;
__REACT_DEVTOOLS_GLOBAL_HOOK__: any;
/**
* @deprecated
* No new usage of jQuery ($)
* */
$: any;
/**
* @deprecated
* No new usage of jQuery
* */
jQuery: any;
gitSha: string;
}

View File

@@ -0,0 +1,15 @@
import { useState } from "react";
import Explorer from "../Explorer/Explorer";
export interface ExplorerStateProperties {
commandBarProperties: {
}
}
export const useExplorerState = (container: Explorer): ExplorerStateProperties => {
const [isPanelOpen, setIsPanelOpen] = useState<boolean>(false);
return {};
};

View File

@@ -1,9 +1,10 @@
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { applyExplorerBindings } from "../applyExplorerBindings";
import { AuthType } from "../AuthType";
import { AccountKind, DefaultAccountExperience } from "../Common/Constants";
import { normalizeArmEndpoint } from "../Common/EnvironmentUtility";
import { sendMessage } from "../Common/MessageHandler";
import { configContext, Platform } from "../ConfigContext";
import { configContext, Platform, updateConfigContext } from "../ConfigContext";
import { ActionType, DataExplorerAction } from "../Contracts/ActionContracts";
import { MessageTypes } from "../Contracts/ExplorerContracts";
import { DataExplorerInputsFrame } from "../Contracts/ViewModels";
@@ -23,7 +24,6 @@ import {
getDatabaseAccountKindFromExperience,
getDatabaseAccountPropertiesFromMetadata,
} from "../Platform/Hosted/HostedUtils";
import { SelfServeType } from "../SelfServe/SelfServeUtils";
import { DefaultExperienceUtility } from "../Shared/DefaultExperienceUtility";
import { updateUserContext } from "../UserContext";
import { listKeys } from "../Utils/arm/generatedClients/2020-04-01/databaseAccounts";
@@ -32,54 +32,65 @@ import { isInvalidParentFrameOrigin } from "../Utils/MessageValidation";
// This hook will create a new instance of Explorer.ts and bind it to the DOM
// This hook has a LOT of magic, but ideally we can delete it once we have removed KO and switched entirely to React
// Pleas tread carefully :)
let explorer: Explorer;
export function useKnockoutExplorer(platform: Platform, explorerParams: ExplorerParams): Explorer {
explorer = explorer || new Explorer(explorerParams);
const [explorer, setExplorer] = useState<Explorer>();
useEffect(() => {
const effect = async () => {
if (platform) {
if (platform === Platform.Hosted) {
await configureHosted();
applyExplorerBindings(explorer);
const explorer = await configureHosted(explorerParams);
setExplorer(explorer);
} else if (platform === Platform.Emulator) {
configureEmulator();
applyExplorerBindings(explorer);
const explorer = configureEmulator(explorerParams);
setExplorer(explorer);
} else if (platform === Platform.Portal) {
configurePortal();
const explorer = await configurePortal(explorerParams);
setExplorer(explorer);
}
}
};
effect();
}, [platform]);
useEffect(() => {
if (explorer) {
applyExplorerBindings(explorer);
}
}, [explorer]);
return explorer;
}
async function configureHosted() {
async function configureHosted(explorerParams: ExplorerParams): Promise<Explorer> {
const win = (window as unknown) as HostedExplorerChildFrame;
explorer.selfServeType(SelfServeType.none);
if (win.hostedConfig.authType === AuthType.EncryptedToken) {
configureHostedWithEncryptedToken(win.hostedConfig);
return configureHostedWithEncryptedToken(win.hostedConfig, explorerParams);
} else if (win.hostedConfig.authType === AuthType.ResourceToken) {
configureHostedWithResourceToken(win.hostedConfig);
return configureHostedWithResourceToken(win.hostedConfig, explorerParams);
} else if (win.hostedConfig.authType === AuthType.ConnectionString) {
configureHostedWithConnectionString(win.hostedConfig);
return configureHostedWithConnectionString(win.hostedConfig, explorerParams);
} else if (win.hostedConfig.authType === AuthType.AAD) {
await configureHostedWithAAD(win.hostedConfig);
return configureHostedWithAAD(win.hostedConfig, explorerParams);
}
throw new Error(`Unknown hosted config: ${win.hostedConfig}`);
}
async function configureHostedWithAAD(config: AAD) {
async function configureHostedWithAAD(config: AAD, explorerParams: ExplorerParams): Promise<Explorer> {
const account = config.databaseAccount;
const accountResourceId = account.id;
const subscriptionId = accountResourceId && accountResourceId.split("subscriptions/")[1].split("/")[0];
const resourceGroup = accountResourceId && accountResourceId.split("resourceGroups/")[1].split("/")[0];
updateUserContext({
subscriptionId,
resourceGroup,
authType: AuthType.AAD,
authorizationToken: `Bearer ${config.authorizationToken}`,
databaseAccount: config.databaseAccount,
});
const keys = await listKeys(subscriptionId, resourceGroup, account.name);
const explorer = new Explorer(explorerParams);
explorer.configure({
databaseAccount: account,
subscriptionId,
@@ -88,56 +99,69 @@ async function configureHostedWithAAD(config: AAD) {
authorizationToken: `Bearer ${config.authorizationToken}`,
features: extractFeatures(),
});
return explorer;
}
function configureHostedWithConnectionString(config: ConnectionString) {
updateUserContext({
// For legacy reasons lots of code expects a connection string login to look and act like an encrypted token login
authType: AuthType.EncryptedToken,
accessToken: encodeURIComponent(config.encryptedToken),
});
function configureHostedWithConnectionString(config: ConnectionString, explorerParams: ExplorerParams): Explorer {
const apiExperience = DefaultExperienceUtility.getDefaultExperienceFromApiKind(config.encryptedTokenMetadata.apiKind);
explorer.configure({
databaseAccount: {
const databaseAccount = {
id: "",
location: "",
type: "",
name: config.encryptedTokenMetadata.accountName,
kind: getDatabaseAccountKindFromExperience(apiExperience),
properties: getDatabaseAccountPropertiesFromMetadata(config.encryptedTokenMetadata),
tags: {},
},
};
updateUserContext({
// For legacy reasons lots of code expects a connection string login to look and act like an encrypted token login
authType: AuthType.EncryptedToken,
accessToken: encodeURIComponent(config.encryptedToken),
databaseAccount,
});
const explorer = new Explorer(explorerParams);
explorer.configure({
databaseAccount,
masterKey: config.masterKey,
features: extractFeatures(),
});
return explorer;
}
function configureHostedWithResourceToken(config: ResourceToken) {
function configureHostedWithResourceToken(config: ResourceToken, explorerParams: ExplorerParams): Explorer {
const parsedResourceToken = parseResourceTokenConnectionString(config.resourceToken);
const databaseAccount = {
id: "",
location: "",
type: "",
name: parsedResourceToken.accountEndpoint,
kind: AccountKind.GlobalDocumentDB,
properties: { documentEndpoint: parsedResourceToken.accountEndpoint },
// Resource tokens can only be used with SQL API
tags: { defaultExperience: DefaultAccountExperience.DocumentDB },
};
updateUserContext({
databaseAccount,
authType: AuthType.ResourceToken,
resourceToken: parsedResourceToken.resourceToken,
endpoint: parsedResourceToken.accountEndpoint,
});
const explorer = new Explorer(explorerParams);
explorer.resourceTokenDatabaseId(parsedResourceToken.databaseId);
explorer.resourceTokenCollectionId(parsedResourceToken.collectionId);
if (parsedResourceToken.partitionKey) {
explorer.resourceTokenPartitionKey(parsedResourceToken.partitionKey);
}
explorer.configure({
databaseAccount: {
id: "",
name: parsedResourceToken.accountEndpoint,
kind: AccountKind.GlobalDocumentDB,
properties: { documentEndpoint: parsedResourceToken.accountEndpoint },
// Resource tokens can only be used with SQL API
tags: { defaultExperience: DefaultAccountExperience.DocumentDB },
},
databaseAccount,
features: extractFeatures(),
isAuthWithresourceToken: true,
});
explorer.isRefreshingExplorer(false);
return explorer;
}
function configureHostedWithEncryptedToken(config: EncryptedToken) {
function configureHostedWithEncryptedToken(config: EncryptedToken, explorerParams: ExplorerParams): Explorer {
updateUserContext({
authType: AuthType.EncryptedToken,
accessToken: encodeURIComponent(config.encryptedToken),
@@ -145,6 +169,7 @@ function configureHostedWithEncryptedToken(config: EncryptedToken) {
const apiExperience: string = DefaultExperienceUtility.getDefaultExperienceFromApiKind(
config.encryptedTokenMetadata.apiKind
);
const explorer = new Explorer(explorerParams);
explorer.configure({
databaseAccount: {
id: "",
@@ -155,21 +180,25 @@ function configureHostedWithEncryptedToken(config: EncryptedToken) {
},
features: extractFeatures(),
});
return explorer;
}
function configureEmulator() {
function configureEmulator(explorerParams: ExplorerParams): Explorer {
updateUserContext({
databaseAccount: emulatorAccount,
authType: AuthType.MasterKey,
});
explorer.selfServeType(SelfServeType.none);
const explorer = new Explorer(explorerParams);
explorer.databaseAccount(emulatorAccount);
explorer.isAccountReady(true);
return explorer;
}
function configurePortal() {
async function configurePortal(explorerParams: ExplorerParams): Promise<Explorer> {
updateUserContext({
authType: AuthType.AAD,
});
return new Promise((resolve) => {
// In development mode, try to load the iframe message from session storage.
// This allows webpack hot reload to function properly in the portal
if (process.env.NODE_ENV === "development" && !window.location.search.includes("disablePortalInitCache")) {
@@ -180,8 +209,9 @@ function configurePortal() {
"Loaded cached portal iframe message from session storage. Do a full page refresh to get a new message"
);
console.dir(message);
const explorer = new Explorer(explorerParams);
explorer.configure(message);
applyExplorerBindings(explorer);
resolve(explorer);
}
}
@@ -210,8 +240,28 @@ function configurePortal() {
inputs.extensionEndpoint = configContext.PROXY_PATH;
}
const authorizationToken = inputs.authorizationToken || "";
const masterKey = inputs.masterKey || "";
const databaseAccount = inputs.databaseAccount;
updateConfigContext({
BACKEND_ENDPOINT: inputs.extensionEndpoint || configContext.BACKEND_ENDPOINT,
ARM_ENDPOINT: normalizeArmEndpoint(inputs.csmEndpoint || configContext.ARM_ENDPOINT),
});
updateUserContext({
authorizationToken,
masterKey,
databaseAccount,
resourceGroup: inputs.resourceGroup,
subscriptionId: inputs.subscriptionId,
subscriptionType: inputs.subscriptionType,
quotaId: inputs.quotaId,
});
const explorer = new Explorer(explorerParams);
explorer.configure(inputs);
applyExplorerBindings(explorer);
resolve(explorer);
if (openAction) {
handleOpenAction(openAction, explorer.nonSystemDatabases(), explorer);
}
@@ -221,6 +271,7 @@ function configurePortal() {
);
sendMessage("ready");
});
}
function shouldProcessMessage(event: MessageEvent): boolean {

View File

@@ -1,8 +1,5 @@
import "expect-puppeteer";
import { getTestExplorerFrame } from "../testExplorer/TestExplorerUtils";
import { createDatabase, onClickSaveButton } from "../utils/shared";
import { generateUniqueName } from "../utils/shared";
import { ApiKind } from "../../src/Contracts/DataModels";
import { createDatabase, generateUniqueName, onClickSaveButton } from "../utils/shared";
const LOADING_STATE_DELAY = 5000;
jest.setTimeout(300000);
@@ -12,7 +9,9 @@ describe("MongoDB Index policy tests", () => {
try {
const singleFieldId = generateUniqueName("key");
const wildCardId = generateUniqueName("key") + "$**";
const frame = await getTestExplorerFrame(ApiKind.MongoDB);
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-mongo-runner");
const handle = await page.waitForSelector("iframe");
const frame = await handle.contentFrame();
const dropDown = "Index Type ";
let index = 0;
@@ -20,24 +19,18 @@ describe("MongoDB Index policy tests", () => {
await frame.waitForSelector('div[class="splashScreen"] > div[class="title"]', { visible: true });
await frame.waitFor(LOADING_STATE_DELAY);
await frame.waitForSelector('div[class="splashScreen"] > div[class="title"]', { visible: true });
const dbId = await createDatabase(frame);
const { databaseId, collectionId } = await createDatabase(frame);
await frame.waitFor(25000);
// click on database
await frame.waitForSelector(`div[data-test="${dbId}"]`);
await frame.waitForSelector(`div[data-test="${databaseId}"]`);
await frame.waitFor(LOADING_STATE_DELAY);
await frame.click(`div[data-test="${dbId}"]`);
await frame.click(`div[data-test="${databaseId}"]`);
await frame.waitFor(LOADING_STATE_DELAY);
// click on scale & setting
const containers = await frame.$$(
`div[class="nodeChildren"] > div[class="collectionHeader main2 nodeItem "]> div[class="treeNodeHeader "]`
);
const selectedContainer = (await frame.evaluate((element) => element.innerText, containers[0]))
.replace(/[\u{0080}-\u{FFFF}]/gu, "")
.trim();
await frame.waitFor(`div[data-test="${selectedContainer}"]`), { visible: true };
await frame.waitFor(`div[data-test="${collectionId}"]`), { visible: true };
await frame.waitFor(LOADING_STATE_DELAY);
await frame.click(`div[data-test="${selectedContainer}"]`);
await frame.click(`div[data-test="${collectionId}"]`);
await frame.waitFor(`div[data-test="Scale & Settings"]`), { visible: true };
await frame.waitFor(LOADING_STATE_DELAY);

View File

@@ -1,19 +1,17 @@
import { uploadNotebookIfNotExist } from "./notebookTestUtils";
import { ElementHandle, Frame } from "puppeteer";
import { getTestExplorerFrame } from "../testExplorer/TestExplorerUtils";
jest.setTimeout(300000);
const notebookName = "GettingStarted.ipynb";
let frame: Frame;
let uploadedNotebookNode: ElementHandle<Element>;
describe("Notebook UI tests", () => {
it("Upload, Open and Delete Notebook", async () => {
try {
frame = await getTestExplorerFrame();
await page.goto("https://localhost:1234/testExplorer.html");
const handle = await page.waitForSelector("iframe");
const frame = await handle.contentFrame();
await frame.waitForSelector(".galleryHeader");
uploadedNotebookNode = await uploadNotebookIfNotExist(frame, notebookName);
const uploadedNotebookNode = await uploadNotebookIfNotExist(frame, notebookName);
await uploadedNotebookNode.click();
await frame.waitForSelector(".tabNavText");
const tabTitle = await frame.$eval(".tabNavText", (element) => element.textContent);

View File

@@ -1,25 +1,18 @@
import { Frame } from "puppeteer";
import { TestExplorerParams } from "../testExplorer/TestExplorerParams";
import { getTestExplorerFrame } from "../testExplorer/TestExplorerUtils";
import { SelfServeType } from "../../src/SelfServe/SelfServeUtils";
import { ApiKind } from "../../src/Contracts/DataModels";
jest.setTimeout(300000);
let frame: Frame;
describe("Self Serve", () => {
it("Launch Self Serve Example", async () => {
try {
frame = await getTestExplorerFrame(
ApiKind.SQL,
new Map<string, string>([[TestExplorerParams.selfServeType, SelfServeType.example]])
);
await page.goto("https://localhost:1234/testExplorer.html?iframeSrc=selfServe.html");
const handle = await page.waitForSelector("iframe");
const frame = await handle.contentFrame();
// wait for refresh RP call to end
await frame.waitFor(10000);
// id of the display element is in the format {PROPERTY_NAME}-{DISPLAY_NAME}-{DISPLAY_TYPE}
await frame.waitForSelector("#description-text-display");
await frame.waitForSelector("#currentRegionText-text-display");
const regions = await frame.waitForSelector("#regions-dropdown-input");
let disabledLoggingToggle = await frame.$$("#enableLogging-toggle-input[disabled]");

View File

@@ -1,82 +1,50 @@
/* eslint-disable no-console */
import { ClientSecretCredential } from "@azure/identity";
import "../../less/hostedexplorer.less";
import { TestExplorerParams } from "./TestExplorerParams";
import { CosmosDBManagementClient } from "@azure/arm-cosmosdb";
import * as msRest from "@azure/ms-rest-js";
import * as ViewModels from "../../src/Contracts/ViewModels";
import { Capability, DatabaseAccount } from "../../src/Contracts/DataModels";
import { DataExplorerInputsFrame } from "../../src/Contracts/ViewModels";
import { updateUserContext } from "../../src/UserContext";
import { get, listKeys } from "../../src/Utils/arm/generatedClients/2020-04-01/databaseAccounts";
class CustomSigner implements msRest.ServiceClientCredentials {
private token: string;
constructor(token: string) {
this.token = token;
}
const resourceGroup = process.env.RESOURCE_GROUP || "";
const subscriptionId = process.env.SUBSCRIPTION_ID || "";
const urlSearchParams = new URLSearchParams(window.location.search);
const accountName = urlSearchParams.get("accountName") || "portal-sql-runner";
const selfServeType = urlSearchParams.get("selfServeType") || "example";
const iframeSrc = urlSearchParams.get("iframeSrc") || "explorer.html?platform=Portal&disablePortalInitCache";
async signRequest(webResource: msRest.WebResourceLike): Promise<msRest.WebResourceLike> {
webResource.headers.set("authorization", `bearer ${this.token}`);
return webResource;
}
if (!process.env.AZURE_CLIENT_SECRET) {
throw new Error(
"process.env.AZURE_CLIENT_SECRET was not set! Set it in your .env file and restart webpack dev server"
);
}
const getDatabaseAccount = async (
token: string,
notebooksAccountSubscriptonId: string,
notebooksAccountResourceGroup: string,
notebooksAccountName: string
): Promise<DatabaseAccount> => {
const client = new CosmosDBManagementClient(new CustomSigner(token), notebooksAccountSubscriptonId);
const databaseAccountGetResponse = await client.databaseAccounts.get(
notebooksAccountResourceGroup,
notebooksAccountName
);
// Azure SDK clients accept the credential as a parameter
const credentials = new ClientSecretCredential(
process.env.AZURE_TENANT_ID,
process.env.AZURE_CLIENT_ID,
process.env.AZURE_CLIENT_SECRET,
{
authorityHost: "https://localhost:1234",
}
);
const databaseAccount: DatabaseAccount = {
id: databaseAccountGetResponse.id,
name: databaseAccountGetResponse.name,
location: databaseAccountGetResponse.location,
type: databaseAccountGetResponse.type,
kind: databaseAccountGetResponse.kind,
tags: databaseAccountGetResponse.tags,
properties: {
documentEndpoint: databaseAccountGetResponse.documentEndpoint,
tableEndpoint: undefined,
gremlinEndpoint: undefined,
cassandraEndpoint: undefined,
capabilities: databaseAccountGetResponse.capabilities.map((capability) => {
return { name: capability.name } as Capability;
}),
},
};
return databaseAccount;
};
console.log("Resource Group:", resourceGroup);
console.log("Subcription: ", subscriptionId);
console.log("Account Name: ", accountName);
const initTestExplorer = async (): Promise<void> => {
const urlSearchParams = new URLSearchParams(window.location.search);
const portalRunnerDatabaseAccount = decodeURIComponent(
urlSearchParams.get(TestExplorerParams.portalRunnerDatabaseAccount)
);
const portalRunnerDatabaseAccountKey = decodeURIComponent(
urlSearchParams.get(TestExplorerParams.portalRunnerDatabaseAccountKey)
);
const portalRunnerSubscripton = decodeURIComponent(urlSearchParams.get(TestExplorerParams.portalRunnerSubscripton));
const portalRunnerResourceGroup = decodeURIComponent(
urlSearchParams.get(TestExplorerParams.portalRunnerResourceGroup)
);
const selfServeType = urlSearchParams.get(TestExplorerParams.selfServeType);
const token = decodeURIComponent(urlSearchParams.get(TestExplorerParams.token));
const databaseAccount = await getDatabaseAccount(
token,
portalRunnerSubscripton,
portalRunnerResourceGroup,
portalRunnerDatabaseAccount
);
const { token } = await credentials.getToken("https://management.core.windows.net/.default");
updateUserContext({
authorizationToken: `bearer ${token}`,
});
const databaseAccount = await get(subscriptionId, resourceGroup, accountName);
const keys = await listKeys(subscriptionId, resourceGroup, accountName);
const initTestExplorerContent = {
inputs: {
databaseAccount: databaseAccount,
subscriptionId: portalRunnerSubscripton,
resourceGroup: portalRunnerResourceGroup,
subscriptionId,
resourceGroup,
authorizationToken: `Bearer ${token}`,
features: {},
hasWriteAccess: true,
@@ -88,7 +56,7 @@ const initTestExplorer = async (): Promise<void> => {
quotaId: "Internal_2014-09-01",
addCollectionDefaultFlight: "2",
isTryCosmosDBSubscription: false,
masterKey: portalRunnerDatabaseAccountKey,
masterKey: keys.primaryMasterKey,
loadDatabaseAccountTimestamp: 1604663109836,
dataExplorerVersion: "1.0.1",
sharedThroughputMinimum: 400,
@@ -101,7 +69,7 @@ const initTestExplorer = async (): Promise<void> => {
// add UI test only when feature is not dependent on flights anymore
flights: [],
selfServeType,
} as ViewModels.DataExplorerInputsFrame,
} as DataExplorerInputsFrame,
};
const iframe = document.createElement("iframe");
@@ -127,7 +95,7 @@ const initTestExplorer = async (): Promise<void> => {
iframe.name = "explorer";
iframe.classList.add("iframe");
iframe.title = "explorer";
iframe.src = "explorer.html?platform=Portal&disablePortalInitCache";
iframe.src = iframeSrc;
document.body.appendChild(iframe);
};

View File

@@ -1,8 +0,0 @@
export enum TestExplorerParams {
portalRunnerDatabaseAccount = "portalRunnerDatabaseAccount",
portalRunnerDatabaseAccountKey = "portalRunnerDatabaseAccountKey",
portalRunnerSubscripton = "portalRunnerSubscripton",
portalRunnerResourceGroup = "portalRunnerResourceGroup",
selfServeType = "selfServeType",
token = "token",
}

View File

@@ -1,64 +0,0 @@
import { Frame } from "puppeteer";
import { TestExplorerParams } from "./TestExplorerParams";
import { ClientSecretCredential } from "@azure/identity";
import { ApiKind } from "../../src/Contracts/DataModels";
let testExplorerFrame: Frame;
export const getTestExplorerFrame = async (apiKind?: ApiKind, params?: Map<string, string>): Promise<Frame> => {
if (testExplorerFrame) {
return testExplorerFrame;
}
let portalRunnerDatabaseAccount: string;
let portalRunnerDatabaseAccountKey: string;
switch (apiKind) {
case ApiKind.MongoDB:
portalRunnerDatabaseAccount = process.env.PORTAL_RUNNER_MONGO_DATABASE_ACCOUNT;
portalRunnerDatabaseAccountKey = process.env.PORTAL_RUNNER_MONGO_DATABASE_ACCOUNT_KEY;
break;
default:
portalRunnerDatabaseAccount = process.env.PORTAL_RUNNER_DATABASE_ACCOUNT;
portalRunnerDatabaseAccountKey = process.env.PORTAL_RUNNER_DATABASE_ACCOUNT_KEY;
}
const notebooksTestRunnerTenantId = process.env.NOTEBOOKS_TEST_RUNNER_TENANT_ID;
const notebooksTestRunnerClientId = process.env.NOTEBOOKS_TEST_RUNNER_CLIENT_ID;
const notebooksTestRunnerClientSecret = process.env.NOTEBOOKS_TEST_RUNNER_CLIENT_SECRET;
const portalRunnerSubscripton = process.env.PORTAL_RUNNER_SUBSCRIPTION;
const portalRunnerResourceGroup = process.env.PORTAL_RUNNER_RESOURCE_GROUP;
const credentials = new ClientSecretCredential(
notebooksTestRunnerTenantId,
notebooksTestRunnerClientId,
notebooksTestRunnerClientSecret
);
const { token } = await credentials.getToken("https://management.core.windows.net/.default");
const testExplorerUrl = new URL("testExplorer.html", "https://localhost:1234");
testExplorerUrl.searchParams.append(
TestExplorerParams.portalRunnerDatabaseAccount,
encodeURI(portalRunnerDatabaseAccount)
);
testExplorerUrl.searchParams.append(
TestExplorerParams.portalRunnerDatabaseAccountKey,
encodeURI(portalRunnerDatabaseAccountKey)
);
testExplorerUrl.searchParams.append(TestExplorerParams.portalRunnerSubscripton, encodeURI(portalRunnerSubscripton));
testExplorerUrl.searchParams.append(
TestExplorerParams.portalRunnerResourceGroup,
encodeURI(portalRunnerResourceGroup)
);
testExplorerUrl.searchParams.append(TestExplorerParams.token, encodeURI(token));
if (params) {
for (const key of params.keys()) {
testExplorerUrl.searchParams.append(key, encodeURI(params.get(key)));
}
}
await page.goto(testExplorerUrl.toString());
const handle = await page.waitForSelector("iframe");
return await handle.contentFrame();
};

View File

@@ -30,8 +30,8 @@ export function generateDatabaseName(baseName = "db", length = 1): string {
return `${baseName}${crypto.randomBytes(length).toString("hex")}-${Date.now()}`;
}
export async function createDatabase(frame: Frame): Promise<string> {
const dbId = generateDatabaseName();
export async function createDatabase(frame: Frame): Promise<{ databaseId: string; collectionId: string }> {
const databaseId = generateDatabaseName();
const collectionId = generateUniqueName("col");
const shardKey = "partitionKey";
// create new collection
@@ -50,7 +50,7 @@ export async function createDatabase(frame: Frame): Promise<string> {
await frame.waitFor('input[data-test="addCollection-newDatabaseId"]');
const dbInput = await frame.$('input[data-test="addCollection-newDatabaseId"]');
await dbInput.press("Backspace");
await dbInput.type(dbId);
await dbInput.type(databaseId);
// type collection id
await frame.waitFor('input[data-test="addCollection-collectionId"]');
@@ -67,7 +67,7 @@ export async function createDatabase(frame: Frame): Promise<string> {
// click submit
await frame.waitFor("#submitBtnAddCollection");
await frame.click("#submitBtnAddCollection");
return dbId;
return { databaseId, collectionId };
}
export async function onClickSaveButton(frame: Frame): Promise<void> {

View File

@@ -10,6 +10,7 @@
"./src/Contracts/ActionContracts.ts",
"./src/Contracts/Diagnostics.ts",
"./src/Contracts/ExplorerContracts.ts",
"./src/Contracts/SelfServeContracts.ts",
"./src/Contracts/Versions.ts"
],
}

View File

@@ -1,7 +1,6 @@
const msRestNodeAuth = require("@azure/ms-rest-nodeauth");
const { CosmosDBManagementClient } = require("@azure/arm-cosmosdb");
const ms = require("ms");
const { time } = require("console");
const clientId = process.env["NOTEBOOKS_TEST_RUNNER_CLIENT_ID"];
const secret = process.env["NOTEBOOKS_TEST_RUNNER_CLIENT_SECRET"];
@@ -9,7 +8,15 @@ const tenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
const subscriptionId = "69e02f2d-f059-4409-9eac-97e8a276ae2c";
const resourceGroupName = "runners";
const sixtyMinutesAgo = new Date(Date.now() - 1000 * 60 * 60).getTime();
const thirtyMinutesAgo = new Date(Date.now() - 1000 * 60 * 30).getTime();
function friendlyTime(date) {
try {
return ms(date);
} catch (error) {
return "Unknown";
}
}
// Deletes all SQL and Mongo databases created more than 20 minutes ago in the test runner accounts
async function main() {
@@ -21,22 +28,22 @@ async function main() {
const mongoDatabases = await client.mongoDBResources.listMongoDBDatabases(resourceGroupName, account.name);
for (const database of mongoDatabases) {
const timestamp = Number(database.name.split("-")[1]);
if (timestamp && timestamp < sixtyMinutesAgo) {
if (timestamp && timestamp < thirtyMinutesAgo) {
await client.mongoDBResources.deleteMongoDBDatabase(resourceGroupName, account.name, database.name);
console.log(`DELETED: ${account.name} | ${database.name} | Age: ${ms(Date.now() - timestamp)}`);
console.log(`DELETED: ${account.name} | ${database.name} | Age: ${friendlyTime(Date.now() - timestamp)}`);
} else {
console.log(`SKIPPED: ${account.name} | ${database.name} | Age: ${ms(Date.now() - timestamp)}`);
console.log(`SKIPPED: ${account.name} | ${database.name} | Age: ${friendlyTime(Date.now() - timestamp)}`);
}
}
} else if (account.kind === "GlobalDocumentDB") {
const sqlDatabases = await client.sqlResources.listSqlDatabases(resourceGroupName, account.name);
for (const database of sqlDatabases) {
const timestamp = Number(database.name.split("-")[1]);
if (timestamp && timestamp < sixtyMinutesAgo) {
if (timestamp && timestamp < thirtyMinutesAgo) {
await client.sqlResources.deleteSqlDatabase(resourceGroupName, account.name, database.name);
console.log(`DELETED: ${account.name} | ${database.name} | Age: ${ms(Date.now() - timestamp)}`);
console.log(`DELETED: ${account.name} | ${database.name} | Age: ${friendlyTime(Date.now() - timestamp)}`);
} else {
console.log(`SKIPPED: ${account.name} | ${database.name} | Age: ${ms(Date.now() - timestamp)}`);
console.log(`SKIPPED: ${account.name} | ${database.name} | Age: ${friendlyTime(Date.now() - timestamp)}`);
}
}
}

View File

@@ -1,3 +1,4 @@
require("dotenv/config");
const path = require("path");
const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
@@ -14,6 +15,16 @@ const isCI = require("is-ci");
const gitSha = childProcess.execSync("git rev-parse HEAD").toString("utf8");
const AZURE_CLIENT_ID = "fd8753b0-0707-4e32-84e9-2532af865fb4";
const AZURE_TENANT_ID = "72f988bf-86f1-41af-91ab-2d7cd011db47";
const SUBSCRIPTION_ID = "69e02f2d-f059-4409-9eac-97e8a276ae2c";
const RESOURCE_GROUP = "runners";
const AZURE_CLIENT_SECRET = process.env.AZURE_CLIENT_SECRET || process.env.NOTEBOOKS_TEST_RUNNER_CLIENT_SECRET; // TODO Remove. Exists for backwards compat with old .env files. Prefer AZURE_CLIENT_SECRET
if (!AZURE_CLIENT_SECRET) {
console.warn("AZURE_CLIENT_SECRET is not set. testExplorer.html will not work.");
}
const cssRule = {
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
@@ -102,6 +113,11 @@ module.exports = function (env = {}, argv = {}) {
if (mode === "development") {
envVars.NODE_ENV = "development";
envVars.AZURE_CLIENT_ID = AZURE_CLIENT_ID;
envVars.AZURE_TENANT_ID = AZURE_TENANT_ID;
envVars.AZURE_CLIENT_SECRET = AZURE_CLIENT_SECRET;
envVars.SUBSCRIPTION_ID = SUBSCRIPTION_ID;
envVars.RESOURCE_GROUP = RESOURCE_GROUP;
typescriptRule.use[0].options.compilerOptions = { target: "ES2018" };
}
@@ -166,6 +182,11 @@ module.exports = function (env = {}, argv = {}) {
template: "src/connectToGitHub.html",
chunks: ["connectToGitHub"],
}),
new HtmlWebpackPlugin({
filename: "selfServe.html",
template: "src/SelfServe/selfServe.html",
chunks: ["selfServe"],
}),
new MonacoWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [{ from: "DataExplorer.nuspec" }, { from: "web.config" }, { from: "quickstart/*.zip" }],
@@ -189,6 +210,7 @@ module.exports = function (env = {}, argv = {}) {
terminal: "./src/Terminal/index.ts",
notebookViewer: "./src/NotebookViewer/NotebookViewer.tsx",
galleryViewer: "./src/GalleryViewer/GalleryViewer.tsx",
selfServe: "./src/SelfServe/SelfServe.tsx",
connectToGitHub: "./src/GitHub/GitHubConnector.ts",
},
node: {
@@ -276,6 +298,12 @@ module.exports = function (env = {}, argv = {}) {
secure: false,
logLevel: "debug",
},
[`/${AZURE_TENANT_ID}`]: {
target: "https://login.microsoftonline.com/",
changeOrigin: true,
secure: false,
logLevel: "debug",
},
},
},
stats: "minimal",