mirror of
https://github.com/Azure/cosmos-explorer.git
synced 2025-12-28 05:11:31 +00:00
Compare commits
3 Commits
migration/
...
users/artr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c287770d7 | ||
|
|
6ce45fd04b | ||
|
|
e4e602a81e |
15
.env.example
15
.env.example
@@ -1 +1,16 @@
|
|||||||
|
PORTAL_RUNNER_USERNAME=
|
||||||
|
PORTAL_RUNNER_PASSWORD=
|
||||||
|
PORTAL_RUNNER_SUBSCRIPTION=
|
||||||
|
PORTAL_RUNNER_RESOURCE_GROUP=
|
||||||
|
PORTAL_RUNNER_DATABASE_ACCOUNT=
|
||||||
|
PORTAL_RUNNER_DATABASE_ACCOUNT_KEY=
|
||||||
|
PORTAL_RUNNER_MONGO_DATABASE_ACCOUNT=
|
||||||
|
PORTAL_RUNNER_MONGO_DATABASE_ACCOUNT_KEY=
|
||||||
|
PORTAL_RUNNER_CONNECTION_STRING=
|
||||||
|
NOTEBOOKS_TEST_RUNNER_TENANT_ID=
|
||||||
|
NOTEBOOKS_TEST_RUNNER_CLIENT_ID=
|
||||||
|
NOTEBOOKS_TEST_RUNNER_CLIENT_SECRET=
|
||||||
|
CASSANDRA_CONNECTION_STRING=
|
||||||
|
MONGO_CONNECTION_STRING=
|
||||||
|
TABLES_CONNECTION_STRING=
|
||||||
DATA_EXPLORER_ENDPOINT=https://localhost:1234/hostedExplorer.html
|
DATA_EXPLORER_ENDPOINT=https://localhost:1234/hostedExplorer.html
|
||||||
@@ -191,4 +191,4 @@ src/Explorer/Notebook/NotebookRenderer/decorators/kbd-shortcuts/index.tsx
|
|||||||
src/Explorer/Notebook/temp/inputs/connected-editors/codemirror.tsx
|
src/Explorer/Notebook/temp/inputs/connected-editors/codemirror.tsx
|
||||||
src/Explorer/Tree/ResourceTreeAdapter.tsx
|
src/Explorer/Tree/ResourceTreeAdapter.tsx
|
||||||
__mocks__/monaco-editor.ts
|
__mocks__/monaco-editor.ts
|
||||||
src/Explorer/Tree/ResourceTree.tsx
|
src/Explorer/Tree/ResourceTreeAdapterForResourceToken.test.tsx
|
||||||
@@ -3068,78 +3068,6 @@ settings-pane {
|
|||||||
display: none;
|
display: none;
|
||||||
height: 0px;
|
height: 0px;
|
||||||
}
|
}
|
||||||
.react-editor {
|
|
||||||
height: 400px;
|
|
||||||
}
|
|
||||||
.documentTabSearchBar{
|
|
||||||
width: 80%;
|
|
||||||
margin: 15px;
|
|
||||||
}
|
|
||||||
.documentSqlTabSearchBar{
|
|
||||||
width: 68%;
|
|
||||||
margin: 15px;
|
|
||||||
}
|
|
||||||
.documentTabFiltetButton{
|
|
||||||
margin-top: 15px;
|
|
||||||
}
|
|
||||||
.filterSuggestions {
|
|
||||||
z-index: 1;
|
|
||||||
position: absolute;
|
|
||||||
top: 133px;
|
|
||||||
padding: 10px;
|
|
||||||
margin-left: 10px;
|
|
||||||
background: white;
|
|
||||||
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
|
|
||||||
transition: 0.3s;
|
|
||||||
width: 20%;
|
|
||||||
height: auto;
|
|
||||||
}
|
|
||||||
.sqlFilterSuggestions {
|
|
||||||
margin-left: 10%;
|
|
||||||
}
|
|
||||||
.documentTabSuggestions {
|
|
||||||
padding: 5px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.documentTabNoFilterView {
|
|
||||||
margin: 15px;
|
|
||||||
}
|
|
||||||
.noFilterText {
|
|
||||||
margin-right: 10px;
|
|
||||||
}
|
|
||||||
.documentTabWatermark{
|
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
flex-direction: column;
|
|
||||||
margin-top: 10%;
|
|
||||||
margin-right: 12%;
|
|
||||||
}
|
|
||||||
.documentCreateText {
|
|
||||||
margin-top: 10px;
|
|
||||||
}
|
|
||||||
.documentLoadMore {
|
|
||||||
color: #0078D4;
|
|
||||||
font-size: 12px;
|
|
||||||
cursor: pointer;
|
|
||||||
margin-top: 10px;
|
|
||||||
}
|
|
||||||
.leftSplitter {
|
|
||||||
align-items: center;
|
|
||||||
text-align: center;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
.documentIdItem{
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.splitterWrapper .splitter-layout .layout-pane.layout-pane-primary{
|
|
||||||
max-height: 60%;
|
|
||||||
}
|
|
||||||
.queryText {
|
|
||||||
padding: 20px;
|
|
||||||
padding-left: 10px;
|
|
||||||
padding-right: 0px;
|
|
||||||
}
|
|
||||||
.spinner {
|
.spinner {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
|||||||
@@ -208,4 +208,4 @@
|
|||||||
}
|
}
|
||||||
.trigger-form {
|
.trigger-form {
|
||||||
padding: 10px 30px 10px 30px;
|
padding: 10px 30px 10px 30px;
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
.dataResourceTree {
|
.dataResourceTree {
|
||||||
margin-left: @MediumSpace;
|
margin-left: @MediumSpace;
|
||||||
overflow: auto;
|
|
||||||
|
|
||||||
.databaseHeader {
|
.databaseHeader {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
|
|||||||
271
less/tree.less
271
less/tree.less
@@ -1,270 +1,273 @@
|
|||||||
@import "./Common/Constants";
|
@import "./Common/Constants";
|
||||||
|
|
||||||
|
|
||||||
.resourceTree {
|
.resourceTree {
|
||||||
height: 100%;
|
|
||||||
flex: 0 0 auto;
|
|
||||||
.main {
|
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
width: 20%;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
.main {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.resourceTreeScroll {
|
.resourceTreeScroll {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
overflow-x: hidden;
|
overflow-x: hidden;
|
||||||
padding-right: 10px;
|
padding-right: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.userSelectNone {
|
.userSelectNone {
|
||||||
-webkit-user-select: none;
|
-webkit-user-select: none;
|
||||||
-moz-user-select: none;
|
-moz-user-select: none;
|
||||||
-ms-user-select: none;
|
-ms-user-select: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeHovermargin {
|
.treeHovermargin {
|
||||||
margin-left: 16px;
|
margin-left: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.highlight {
|
.highlight {
|
||||||
padding: @SmallSpace 2px;
|
padding: @SmallSpace 2px;
|
||||||
outline: 0;
|
outline: 0;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
.hover();
|
.hover();
|
||||||
}
|
}
|
||||||
|
|
||||||
&:active {
|
&:active {
|
||||||
.active();
|
.active();
|
||||||
}
|
}
|
||||||
|
|
||||||
&:focus {
|
&:focus {
|
||||||
.focus();
|
.focus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.contextmenushowing {
|
.contextmenushowing {
|
||||||
background-color: #eee;
|
background-color: #EEE;
|
||||||
}
|
}
|
||||||
|
|
||||||
.collectionstree {
|
.collectionstree {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
margin-top: @DefaultSpace;
|
margin-top: @DefaultSpace;
|
||||||
|
|
||||||
.databaseList {
|
|
||||||
list-style-type: none;
|
|
||||||
padding-left: 0px;
|
|
||||||
|
|
||||||
.collectionList {
|
.databaseList {
|
||||||
padding-left: (2 * @MediumSpace);
|
list-style-type: none;
|
||||||
|
padding-left: 0px;
|
||||||
|
|
||||||
|
.collectionList {
|
||||||
|
padding-left:(2 * @MediumSpace);
|
||||||
|
}
|
||||||
|
|
||||||
|
.collectionChildList {
|
||||||
|
padding-left: @LargeSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.databaseDocuments {
|
||||||
|
padding-left: (5 * @MediumSpace);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.collectionChildList {
|
|
||||||
padding-left: @LargeSpace;
|
|
||||||
}
|
|
||||||
|
|
||||||
.databaseDocuments {
|
|
||||||
padding-left: (5 * @MediumSpace);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.pointerCursor {
|
.pointerCursor {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.menuEllipsis {
|
.menuEllipsis {
|
||||||
padding-right: 6px;
|
padding-right: 6px;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
position: relative;
|
position: relative;
|
||||||
top: -5px;
|
top: -5px;
|
||||||
left: 0px;
|
left: 0px;
|
||||||
float: right;
|
float: right;
|
||||||
display: none;
|
display: none;
|
||||||
padding-left: 6px !important;
|
padding-left: 6px!important;
|
||||||
line-height: @TreeLineHeight;
|
line-height: @TreeLineHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
.databaseMenu {
|
.databaseMenu {
|
||||||
.flex-display();
|
.flex-display();
|
||||||
}
|
}
|
||||||
|
|
||||||
.databaseMenu:hover .menuEllipsis,
|
.databaseMenu:hover .menuEllipsis,
|
||||||
.databaseMenu:focus .menuEllipsis {
|
.databaseMenu:focus .menuEllipsis {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.databaseCollChildTextOverflow {
|
.databaseCollChildTextOverflow {
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.collectionMenu {
|
.collectionMenu {
|
||||||
.flex-display();
|
.flex-display();
|
||||||
}
|
}
|
||||||
|
|
||||||
.collectionMenu:hover .menuEllipsis,
|
.collectionMenu:hover .menuEllipsis,
|
||||||
.collectionMenu:focus .menuEllipsis {
|
.collectionMenu:focus .menuEllipsis {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.documentsMenu:hover .menuEllipsis,
|
.documentsMenu:hover .menuEllipsis,
|
||||||
.documentsMenu:focus .menuEllipsis {
|
.documentsMenu:focus .menuEllipsis {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeChildMenu {
|
.treeChildMenu {
|
||||||
display: flex;
|
display: flex;
|
||||||
}
|
}
|
||||||
|
|
||||||
.storedProcedureMenu:hover .menuEllipsis,
|
.storedProcedureMenu:hover .menuEllipsis,
|
||||||
.storedProcedureMenu:focus .menuEllipsis {
|
.storedProcedureMenu:focus .menuEllipsis {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.childMenu {
|
.childMenu {
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
padding-left: (6 * @MediumSpace);
|
padding-left: (6 * @MediumSpace);
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.storedChildMenu:hover .menuEllipsis,
|
.storedChildMenu:hover .menuEllipsis,
|
||||||
.storedChildMenu:focus .menuEllipsis {
|
.storedChildMenu:focus .menuEllipsis {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.contextmenu6 {
|
.contextmenu6 {
|
||||||
top: -29px;
|
top: -29px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.userDefinedMenu:hover .contextmenu6 {
|
.userDefinedMenu:hover .contextmenu6 {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.userDefinedchildMenu:hover .menuEllipsis,
|
.userDefinedchildMenu:hover .menuEllipsis,
|
||||||
.userDefinedchildMenu:focus .menuEllipsis {
|
.userDefinedchildMenu:focus .menuEllipsis {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.triggersMenu:hover .menuEllipsis,
|
.triggersMenu:hover .menuEllipsis,
|
||||||
.triggersMenu:focus .menuEllipsis {
|
.triggersMenu:focus .menuEllipsis {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.triggersChildMenu:hover .menuEllipsis,
|
.triggersChildMenu:hover .menuEllipsis,
|
||||||
.triggersChildMenu:focus .menuEllipsis {
|
.triggersChildMenu:focus .menuEllipsis {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.databaseId {
|
.databaseId {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.storedUdfTriggerMenu {
|
.storedUdfTriggerMenu {
|
||||||
padding-left: 0px;
|
padding-left: 0px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.collectionstree img {
|
.collectionstree img {
|
||||||
width: 16px;
|
width: 16px;
|
||||||
height: 16px;
|
height: 16px;
|
||||||
vertical-align: text-top;
|
vertical-align: text-top;
|
||||||
}
|
}
|
||||||
|
|
||||||
img.collectionsTreeCollapseExpand {
|
img.collectionsTreeCollapseExpand {
|
||||||
width: 10px;
|
width: 10px;
|
||||||
height: 10px;
|
height: 10px;
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
margin-bottom: 5px;
|
margin-bottom: 5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.collapsed::before {
|
.collapsed::before {
|
||||||
content: "\23F5";
|
content: "\23F5";
|
||||||
margin-left: 0px;
|
margin-left: 0px;
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.expanded::before {
|
.expanded::before {
|
||||||
content: "\23F7";
|
content: '\23F7';
|
||||||
margin-left: 0px;
|
margin-left: 0px;
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.collectionMenuChildren {
|
.collectionMenuChildren {
|
||||||
padding-left: 42px;
|
padding-left: 42px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main-nav {
|
.main-nav {
|
||||||
width: 100vh;
|
width: 100vh;
|
||||||
height: 40px;
|
height: 40px;
|
||||||
background: white;
|
background: white;
|
||||||
transform-origin: left top;
|
transform-origin: left top;
|
||||||
-webkit-transform-origin: left top;
|
-webkit-transform-origin: left top;
|
||||||
-ms-transform-origin: left top;
|
-ms-transform-origin: left top;
|
||||||
transform: rotate(-90deg) translateX(-100%);
|
transform: rotate(-90deg) translateX(-100%);
|
||||||
-webkit-transform: rotate(-90deg) translateX(-100%);
|
-webkit-transform: rotate(-90deg) translateX(-100%);
|
||||||
-ms-transform: rotate(-90deg) translateX(-100%);
|
-ms-transform: rotate(-90deg) translateX(-100%);
|
||||||
border-bottom: 1px solid #ccc;
|
border-bottom: 1px solid #CCC;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main-nav-img {
|
.main-nav-img {
|
||||||
width: 16px;
|
width: 16px;
|
||||||
height: 16px;
|
height: 16px;
|
||||||
margin: -32px 0 0 0;
|
margin: -32px 0 0 0;
|
||||||
transform: rotate(-90deg) translateX(-100%);
|
transform: rotate(-90deg) translateX(-100%);
|
||||||
-webkit-transform: rotate(-90deg) translateX(-100%);
|
-webkit-transform: rotate(-90deg) translateX(-100%);
|
||||||
-ms-transform: rotate(-90deg) translateX(-100%);
|
-ms-transform: rotate(-90deg) translateX(-100%);
|
||||||
}
|
}
|
||||||
|
|
||||||
.main-nav-img.main-nav-sub-img {
|
.main-nav-img.main-nav-sub-img {
|
||||||
width: 16px;
|
width: 16px;
|
||||||
height: 16px;
|
height: 16px;
|
||||||
margin: 0px 0px 0 0;
|
margin: 0px 0px 0 0;
|
||||||
transform: rotate(180deg) translateX(0%);
|
transform: rotate(180deg) translateX(0%);
|
||||||
-webkit-transform: rotate(180deg) translateX(0%);
|
-webkit-transform: rotate(180deg) translateX(0%);
|
||||||
-ms-transform: rotate(180deg) translateX(0%);
|
-ms-transform: rotate(180deg) translateX(0%);
|
||||||
position: absolute;
|
position: absolute;
|
||||||
right: -8px;
|
right: -8px;
|
||||||
top: 16px;
|
top: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
ul.nav {
|
ul.nav {
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
margin-top: 0px;
|
margin-top: 0px;
|
||||||
margin-left: 0px;
|
margin-left: 0px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.mini ul.nav li {
|
.mini ul.nav li {
|
||||||
float: right;
|
float: right;
|
||||||
line-height: 25px;
|
line-height: 25px;
|
||||||
height: auto;
|
height: auto;
|
||||||
margin-top: 3px;
|
margin-top: 3px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.spancolchildstyle {
|
.spancolchildstyle {
|
||||||
padding: 4px;
|
padding: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.contextmenubutton {
|
.contextmenubutton {
|
||||||
float: right;
|
float: right;
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.highlight:hover > .contextmenubutton {
|
.highlight:hover>.contextmenubutton {
|
||||||
display: unset;
|
display: unset;
|
||||||
}
|
}
|
||||||
|
|
||||||
.highlight:hover > .contextmenubutton::after {
|
.highlight:hover>.contextmenubutton::after {
|
||||||
content: "\2026";
|
content: "\2026";
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.showEllipsis {
|
.showEllipsis {
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
29
package-lock.json
generated
29
package-lock.json
generated
@@ -5583,11 +5583,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.7.tgz",
|
||||||
"integrity": "sha512-cxWFQVseBm6O9Gbw1IWb8r6OS4OhSt3hPZLkFApLjM8TEXROBuQGLAH2i2gZpcXdLBIrpXuTDhH7Vbm1iXmNGA=="
|
"integrity": "sha512-cxWFQVseBm6O9Gbw1IWb8r6OS4OhSt3hPZLkFApLjM8TEXROBuQGLAH2i2gZpcXdLBIrpXuTDhH7Vbm1iXmNGA=="
|
||||||
},
|
},
|
||||||
"@types/lodash": {
|
|
||||||
"version": "4.14.171",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.171.tgz",
|
|
||||||
"integrity": "sha512-7eQ2xYLLI/LsicL2nejW9Wyko3lcpN6O/z0ZLHrEQsg280zIdCv1t/0m6UtBjUHokCGBQ3gYTbHzDkZ1xOBwwg=="
|
|
||||||
},
|
|
||||||
"@types/minimatch": {
|
"@types/minimatch": {
|
||||||
"version": "3.0.3",
|
"version": "3.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz",
|
||||||
@@ -20623,9 +20618,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"playwright": {
|
"playwright": {
|
||||||
"version": "1.13.0",
|
"version": "1.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.13.0.tgz",
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.10.0.tgz",
|
||||||
"integrity": "sha512-GA5OyEeKx1v/pRcANmYncCT67Y7Y4N5zLRU5E690dn/Id10sooR5hQZmCDYsjXlutZb/1q0R3sITALnvhEjCjg==",
|
"integrity": "sha512-b7SGBcCPq4W3pb4ImEDmNXtO0ZkJbZMuWiShsaNJd+rGfY/6fqwgllsAojmxGSgFmijYw7WxCoPiAIEDIH16Kw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"requires": {
|
"requires": {
|
||||||
"commander": "^6.1.0",
|
"commander": "^6.1.0",
|
||||||
@@ -20640,8 +20635,7 @@
|
|||||||
"proxy-from-env": "^1.1.0",
|
"proxy-from-env": "^1.1.0",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"stack-utils": "^2.0.3",
|
"stack-utils": "^2.0.3",
|
||||||
"ws": "^7.4.6",
|
"ws": "^7.3.1"
|
||||||
"yazl": "^2.5.1"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"commander": {
|
"commander": {
|
||||||
@@ -20673,12 +20667,6 @@
|
|||||||
"requires": {
|
"requires": {
|
||||||
"escape-string-regexp": "^2.0.0"
|
"escape-string-regexp": "^2.0.0"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
"ws": {
|
|
||||||
"version": "7.5.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.3.tgz",
|
|
||||||
"integrity": "sha512-kQ/dHIzuLrS6Je9+uv81ueZomEwH0qVYstcAQ4/Z93K8zeko9gtAbttJWzoC5ukqXY1PpoouV3+VSOqEAFt5wg==",
|
|
||||||
"dev": true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -26169,15 +26157,6 @@
|
|||||||
"fd-slicer": "~1.1.0"
|
"fd-slicer": "~1.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"yazl": {
|
|
||||||
"version": "2.5.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/yazl/-/yazl-2.5.1.tgz",
|
|
||||||
"integrity": "sha512-phENi2PLiHnHb6QBVot+dJnaAZ0xosj7p3fWl+znIjBDlnMI2PsZCJZ306BPTFOaHf5qdDEI8x5qFrSOBN5vrw==",
|
|
||||||
"dev": true,
|
|
||||||
"requires": {
|
|
||||||
"buffer-crc32": "~0.2.3"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"yocto-queue": {
|
"yocto-queue": {
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||||
|
|||||||
@@ -42,7 +42,6 @@
|
|||||||
"@octokit/rest": "17.9.2",
|
"@octokit/rest": "17.9.2",
|
||||||
"@phosphor/widgets": "1.9.3",
|
"@phosphor/widgets": "1.9.3",
|
||||||
"@testing-library/jest-dom": "5.11.9",
|
"@testing-library/jest-dom": "5.11.9",
|
||||||
"@types/lodash": "4.14.171",
|
|
||||||
"@types/mkdirp": "1.0.1",
|
"@types/mkdirp": "1.0.1",
|
||||||
"@types/node-fetch": "2.5.7",
|
"@types/node-fetch": "2.5.7",
|
||||||
"applicationinsights": "1.8.0",
|
"applicationinsights": "1.8.0",
|
||||||
@@ -164,7 +163,7 @@
|
|||||||
"mini-css-extract-plugin": "0.4.3",
|
"mini-css-extract-plugin": "0.4.3",
|
||||||
"monaco-editor-webpack-plugin": "1.7.0",
|
"monaco-editor-webpack-plugin": "1.7.0",
|
||||||
"node-fetch": "2.6.1",
|
"node-fetch": "2.6.1",
|
||||||
"playwright": "1.13.0",
|
"playwright": "1.10.0",
|
||||||
"prettier": "2.2.1",
|
"prettier": "2.2.1",
|
||||||
"raw-loader": "0.5.1",
|
"raw-loader": "0.5.1",
|
||||||
"react-dev-utils": "11.0.4",
|
"react-dev-utils": "11.0.4",
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import * as DataModels from "../Contracts/DataModels";
|
|||||||
import { MessageTypes } from "../Contracts/ExplorerContracts";
|
import { MessageTypes } from "../Contracts/ExplorerContracts";
|
||||||
import { Collection } from "../Contracts/ViewModels";
|
import { Collection } from "../Contracts/ViewModels";
|
||||||
import DocumentId from "../Explorer/Tree/DocumentId";
|
import DocumentId from "../Explorer/Tree/DocumentId";
|
||||||
|
import { hasFlag } from "../Platform/Hosted/extractFeatures";
|
||||||
import { userContext } from "../UserContext";
|
import { userContext } from "../UserContext";
|
||||||
import { logConsoleError } from "../Utils/NotificationConsoleUtils";
|
import { logConsoleError } from "../Utils/NotificationConsoleUtils";
|
||||||
import { ApiType, HttpHeaders, HttpStatusCodes } from "./Constants";
|
import { ApiType, HttpHeaders, HttpStatusCodes } from "./Constants";
|
||||||
@@ -141,7 +142,8 @@ export function readDocument(
|
|||||||
: "",
|
: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const endpoint = getEndpoint();
|
const endpoint = getFeatureEndpointOrDefault("readDocument");
|
||||||
|
|
||||||
return window
|
return window
|
||||||
.fetch(`${endpoint}?${queryString.stringify(params)}`, {
|
.fetch(`${endpoint}?${queryString.stringify(params)}`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
@@ -342,6 +344,10 @@ export function getEndpoint(): string {
|
|||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getFeatureEndpointOrDefault(feature: string): string {
|
||||||
|
return (hasFlag("mongoProxyFeatures", feature)) ? userContext.features.mongoProxyEndpoint : getEndpoint();
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: This function throws most of the time except on Forbidden which is a bit strange
|
// TODO: This function throws most of the time except on Forbidden which is a bit strange
|
||||||
// It causes problems for TypeScript understanding the types
|
// It causes problems for TypeScript understanding the types
|
||||||
async function errorHandling(response: Response, action: string, params: unknown): Promise<void> {
|
async function errorHandling(response: Response, action: string, params: unknown): Promise<void> {
|
||||||
|
|||||||
@@ -2,22 +2,17 @@ import React, { FunctionComponent } from "react";
|
|||||||
import arrowLeftImg from "../../images/imgarrowlefticon.svg";
|
import arrowLeftImg from "../../images/imgarrowlefticon.svg";
|
||||||
import refreshImg from "../../images/refresh-cosmos.svg";
|
import refreshImg from "../../images/refresh-cosmos.svg";
|
||||||
import { AuthType } from "../AuthType";
|
import { AuthType } from "../AuthType";
|
||||||
import Explorer from "../Explorer/Explorer";
|
|
||||||
import { ResourceTokenTree } from "../Explorer/Tree/ResourceTokenTree";
|
|
||||||
import { ResourceTree } from "../Explorer/Tree/ResourceTree";
|
|
||||||
import { userContext } from "../UserContext";
|
import { userContext } from "../UserContext";
|
||||||
|
|
||||||
export interface ResourceTreeContainerProps {
|
export interface ResourceTreeProps {
|
||||||
toggleLeftPaneExpanded: () => void;
|
toggleLeftPaneExpanded: () => void;
|
||||||
isLeftPaneExpanded: boolean;
|
isLeftPaneExpanded: boolean;
|
||||||
container: Explorer;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ResourceTreeContainer: FunctionComponent<ResourceTreeContainerProps> = ({
|
export const ResourceTree: FunctionComponent<ResourceTreeProps> = ({
|
||||||
toggleLeftPaneExpanded,
|
toggleLeftPaneExpanded,
|
||||||
isLeftPaneExpanded,
|
isLeftPaneExpanded,
|
||||||
container,
|
}: ResourceTreeProps): JSX.Element => {
|
||||||
}: ResourceTreeContainerProps): JSX.Element => {
|
|
||||||
return (
|
return (
|
||||||
<div id="main" className={isLeftPaneExpanded ? "main" : "hiddenMain"}>
|
<div id="main" className={isLeftPaneExpanded ? "main" : "hiddenMain"}>
|
||||||
{/* Collections Window - - Start */}
|
{/* Collections Window - - Start */}
|
||||||
@@ -53,11 +48,9 @@ export const ResourceTreeContainer: FunctionComponent<ResourceTreeContainerProps
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{userContext.authType === AuthType.ResourceToken ? (
|
{userContext.authType === AuthType.ResourceToken ? (
|
||||||
<ResourceTokenTree />
|
<div style={{ overflowY: "auto" }} data-bind="react:resourceTreeForResourceToken" />
|
||||||
) : userContext.features.enableKOResourceTree ? (
|
|
||||||
<div style={{ overflowY: "auto" }} data-bind="react:resourceTree" />
|
|
||||||
) : (
|
) : (
|
||||||
<ResourceTree container={container} />
|
<div style={{ overflowY: "auto" }} data-bind="react:resourceTree" />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{/* Collections Window - End */}
|
{/* Collections Window - End */}
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
jest.mock("../../Utils/arm/request");
|
jest.mock("../../Utils/arm/request");
|
||||||
jest.mock("../CosmosClient");
|
jest.mock("../CosmosClient");
|
||||||
import ko from "knockout";
|
|
||||||
import { AuthType } from "../../AuthType";
|
import { AuthType } from "../../AuthType";
|
||||||
import { CreateCollectionParams, DatabaseAccount } from "../../Contracts/DataModels";
|
import { CreateCollectionParams, DatabaseAccount } from "../../Contracts/DataModels";
|
||||||
import { Database } from "../../Contracts/ViewModels";
|
|
||||||
import { useDatabases } from "../../Explorer/useDatabases";
|
|
||||||
import { updateUserContext } from "../../UserContext";
|
import { updateUserContext } from "../../UserContext";
|
||||||
import { armRequest } from "../../Utils/arm/request";
|
import { armRequest } from "../../Utils/arm/request";
|
||||||
import { client } from "../CosmosClient";
|
import { client } from "../CosmosClient";
|
||||||
@@ -26,15 +23,6 @@ describe("createCollection", () => {
|
|||||||
} as DatabaseAccount,
|
} as DatabaseAccount,
|
||||||
apiType: "SQL",
|
apiType: "SQL",
|
||||||
});
|
});
|
||||||
useDatabases.setState({
|
|
||||||
databases: [
|
|
||||||
{
|
|
||||||
id: ko.observable("testDatabase"),
|
|
||||||
loadCollections: () => undefined,
|
|
||||||
collections: ko.observableArray([]),
|
|
||||||
} as Database,
|
|
||||||
],
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should call ARM if logged in with AAD", async () => {
|
it("should call ARM if logged in with AAD", async () => {
|
||||||
|
|||||||
@@ -4,16 +4,20 @@ import { ContainerRequest } from "@azure/cosmos/dist-esm/client/Container/Contai
|
|||||||
import { DatabaseRequest } from "@azure/cosmos/dist-esm/client/Database/DatabaseRequest";
|
import { DatabaseRequest } from "@azure/cosmos/dist-esm/client/Database/DatabaseRequest";
|
||||||
import { AuthType } from "../../AuthType";
|
import { AuthType } from "../../AuthType";
|
||||||
import * as DataModels from "../../Contracts/DataModels";
|
import * as DataModels from "../../Contracts/DataModels";
|
||||||
import { useDatabases } from "../../Explorer/useDatabases";
|
|
||||||
import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants";
|
import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants";
|
||||||
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
||||||
import { userContext } from "../../UserContext";
|
import { userContext } from "../../UserContext";
|
||||||
import { getCollectionName } from "../../Utils/APITypeUtils";
|
import {
|
||||||
import { createUpdateCassandraTable } from "../../Utils/arm/generatedClients/cosmos/cassandraResources";
|
createUpdateCassandraTable,
|
||||||
import { createUpdateGremlinGraph } from "../../Utils/arm/generatedClients/cosmos/gremlinResources";
|
getCassandraTable,
|
||||||
import { createUpdateMongoDBCollection } from "../../Utils/arm/generatedClients/cosmos/mongoDBResources";
|
} from "../../Utils/arm/generatedClients/cosmos/cassandraResources";
|
||||||
import { createUpdateSqlContainer } from "../../Utils/arm/generatedClients/cosmos/sqlResources";
|
import { createUpdateGremlinGraph, getGremlinGraph } from "../../Utils/arm/generatedClients/cosmos/gremlinResources";
|
||||||
import { createUpdateTable } from "../../Utils/arm/generatedClients/cosmos/tableResources";
|
import {
|
||||||
|
createUpdateMongoDBCollection,
|
||||||
|
getMongoDBCollection,
|
||||||
|
} from "../../Utils/arm/generatedClients/cosmos/mongoDBResources";
|
||||||
|
import { createUpdateSqlContainer, getSqlContainer } from "../../Utils/arm/generatedClients/cosmos/sqlResources";
|
||||||
|
import { createUpdateTable, getTable } from "../../Utils/arm/generatedClients/cosmos/tableResources";
|
||||||
import * as ARMTypes from "../../Utils/arm/generatedClients/cosmos/types";
|
import * as ARMTypes from "../../Utils/arm/generatedClients/cosmos/types";
|
||||||
import { logConsoleInfo, logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
|
import { logConsoleInfo, logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
|
||||||
import { client } from "../CosmosClient";
|
import { client } from "../CosmosClient";
|
||||||
@@ -55,16 +59,6 @@ export const createCollection = async (params: DataModels.CreateCollectionParams
|
|||||||
};
|
};
|
||||||
|
|
||||||
const createCollectionWithARM = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
const createCollectionWithARM = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
||||||
if (!params.createNewDatabase) {
|
|
||||||
const isValid = await useDatabases.getState().validateCollectionId(params.databaseId, params.collectionId);
|
|
||||||
if (!isValid) {
|
|
||||||
const collectionName = getCollectionName().toLocaleLowerCase();
|
|
||||||
throw new Error(
|
|
||||||
`Create ${collectionName} failed: ${collectionName} with id ${params.collectionId} already exists`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const { apiType } = userContext;
|
const { apiType } = userContext;
|
||||||
switch (apiType) {
|
switch (apiType) {
|
||||||
case "SQL":
|
case "SQL":
|
||||||
@@ -83,6 +77,23 @@ const createCollectionWithARM = async (params: DataModels.CreateCollectionParams
|
|||||||
};
|
};
|
||||||
|
|
||||||
const createSqlContainer = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
const createSqlContainer = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
||||||
|
try {
|
||||||
|
const getResponse = await getSqlContainer(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.databaseId,
|
||||||
|
params.collectionId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create container failed: container with id ${params.collectionId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
||||||
const resource: ARMTypes.SqlContainerResource = {
|
const resource: ARMTypes.SqlContainerResource = {
|
||||||
id: params.collectionId,
|
id: params.collectionId,
|
||||||
@@ -120,6 +131,23 @@ const createSqlContainer = async (params: DataModels.CreateCollectionParams): Pr
|
|||||||
|
|
||||||
const createMongoCollection = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
const createMongoCollection = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
||||||
const mongoWildcardIndexOnAllFields: ARMTypes.MongoIndex[] = [{ key: { keys: ["$**"] } }, { key: { keys: ["_id"] } }];
|
const mongoWildcardIndexOnAllFields: ARMTypes.MongoIndex[] = [{ key: { keys: ["$**"] } }, { key: { keys: ["_id"] } }];
|
||||||
|
try {
|
||||||
|
const getResponse = await getMongoDBCollection(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.databaseId,
|
||||||
|
params.collectionId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create collection failed: collection with id ${params.collectionId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
||||||
const resource: ARMTypes.MongoDBCollectionResource = {
|
const resource: ARMTypes.MongoDBCollectionResource = {
|
||||||
id: params.collectionId,
|
id: params.collectionId,
|
||||||
@@ -161,6 +189,23 @@ const createMongoCollection = async (params: DataModels.CreateCollectionParams):
|
|||||||
};
|
};
|
||||||
|
|
||||||
const createCassandraTable = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
const createCassandraTable = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
||||||
|
try {
|
||||||
|
const getResponse = await getCassandraTable(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.databaseId,
|
||||||
|
params.collectionId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create table failed: table with id ${params.collectionId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
||||||
const resource: ARMTypes.CassandraTableResource = {
|
const resource: ARMTypes.CassandraTableResource = {
|
||||||
id: params.collectionId,
|
id: params.collectionId,
|
||||||
@@ -188,6 +233,23 @@ const createCassandraTable = async (params: DataModels.CreateCollectionParams):
|
|||||||
};
|
};
|
||||||
|
|
||||||
const createGraph = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
const createGraph = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
||||||
|
try {
|
||||||
|
const getResponse = await getGremlinGraph(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.databaseId,
|
||||||
|
params.collectionId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create graph failed: graph with id ${params.collectionId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
||||||
const resource: ARMTypes.GremlinGraphResource = {
|
const resource: ARMTypes.GremlinGraphResource = {
|
||||||
id: params.collectionId,
|
id: params.collectionId,
|
||||||
@@ -222,6 +284,22 @@ const createGraph = async (params: DataModels.CreateCollectionParams): Promise<D
|
|||||||
};
|
};
|
||||||
|
|
||||||
const createTable = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
const createTable = async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
|
||||||
|
try {
|
||||||
|
const getResponse = await getTable(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.collectionId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create table failed: table with id ${params.collectionId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
|
||||||
const resource: ARMTypes.TableResource = {
|
const resource: ARMTypes.TableResource = {
|
||||||
id: params.collectionId,
|
id: params.collectionId,
|
||||||
|
|||||||
@@ -2,13 +2,20 @@ import { DatabaseResponse } from "@azure/cosmos";
|
|||||||
import { DatabaseRequest } from "@azure/cosmos/dist-esm/client/Database/DatabaseRequest";
|
import { DatabaseRequest } from "@azure/cosmos/dist-esm/client/Database/DatabaseRequest";
|
||||||
import { AuthType } from "../../AuthType";
|
import { AuthType } from "../../AuthType";
|
||||||
import * as DataModels from "../../Contracts/DataModels";
|
import * as DataModels from "../../Contracts/DataModels";
|
||||||
import { useDatabases } from "../../Explorer/useDatabases";
|
|
||||||
import { userContext } from "../../UserContext";
|
import { userContext } from "../../UserContext";
|
||||||
import { getDatabaseName } from "../../Utils/APITypeUtils";
|
import {
|
||||||
import { createUpdateCassandraKeyspace } from "../../Utils/arm/generatedClients/cosmos/cassandraResources";
|
createUpdateCassandraKeyspace,
|
||||||
import { createUpdateGremlinDatabase } from "../../Utils/arm/generatedClients/cosmos/gremlinResources";
|
getCassandraKeyspace,
|
||||||
import { createUpdateMongoDBDatabase } from "../../Utils/arm/generatedClients/cosmos/mongoDBResources";
|
} from "../../Utils/arm/generatedClients/cosmos/cassandraResources";
|
||||||
import { createUpdateSqlDatabase } from "../../Utils/arm/generatedClients/cosmos/sqlResources";
|
import {
|
||||||
|
createUpdateGremlinDatabase,
|
||||||
|
getGremlinDatabase,
|
||||||
|
} from "../../Utils/arm/generatedClients/cosmos/gremlinResources";
|
||||||
|
import {
|
||||||
|
createUpdateMongoDBDatabase,
|
||||||
|
getMongoDBDatabase,
|
||||||
|
} from "../../Utils/arm/generatedClients/cosmos/mongoDBResources";
|
||||||
|
import { createUpdateSqlDatabase, getSqlDatabase } from "../../Utils/arm/generatedClients/cosmos/sqlResources";
|
||||||
import {
|
import {
|
||||||
CassandraKeyspaceCreateUpdateParameters,
|
CassandraKeyspaceCreateUpdateParameters,
|
||||||
CreateUpdateOptions,
|
CreateUpdateOptions,
|
||||||
@@ -41,11 +48,6 @@ export async function createDatabase(params: DataModels.CreateDatabaseParams): P
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function createDatabaseWithARM(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
async function createDatabaseWithARM(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
||||||
if (!useDatabases.getState().validateDatabaseId(params.databaseId)) {
|
|
||||||
const databaseName = getDatabaseName().toLocaleLowerCase();
|
|
||||||
throw new Error(`Create ${databaseName} failed: ${databaseName} with id ${params.databaseId} already exists`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const { apiType } = userContext;
|
const { apiType } = userContext;
|
||||||
|
|
||||||
switch (apiType) {
|
switch (apiType) {
|
||||||
@@ -63,6 +65,22 @@ async function createDatabaseWithARM(params: DataModels.CreateDatabaseParams): P
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function createSqlDatabase(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
async function createSqlDatabase(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
||||||
|
try {
|
||||||
|
const getResponse = await getSqlDatabase(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.databaseId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create database failed: database with id ${params.databaseId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: CreateUpdateOptions = constructRpOptions(params);
|
const options: CreateUpdateOptions = constructRpOptions(params);
|
||||||
const rpPayload: SqlDatabaseCreateUpdateParameters = {
|
const rpPayload: SqlDatabaseCreateUpdateParameters = {
|
||||||
properties: {
|
properties: {
|
||||||
@@ -83,6 +101,22 @@ async function createSqlDatabase(params: DataModels.CreateDatabaseParams): Promi
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function createMongoDatabase(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
async function createMongoDatabase(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
||||||
|
try {
|
||||||
|
const getResponse = await getMongoDBDatabase(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.databaseId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create database failed: database with id ${params.databaseId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: CreateUpdateOptions = constructRpOptions(params);
|
const options: CreateUpdateOptions = constructRpOptions(params);
|
||||||
const rpPayload: MongoDBDatabaseCreateUpdateParameters = {
|
const rpPayload: MongoDBDatabaseCreateUpdateParameters = {
|
||||||
properties: {
|
properties: {
|
||||||
@@ -103,6 +137,22 @@ async function createMongoDatabase(params: DataModels.CreateDatabaseParams): Pro
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function createCassandraKeyspace(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
async function createCassandraKeyspace(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
||||||
|
try {
|
||||||
|
const getResponse = await getCassandraKeyspace(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.databaseId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create database failed: database with id ${params.databaseId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: CreateUpdateOptions = constructRpOptions(params);
|
const options: CreateUpdateOptions = constructRpOptions(params);
|
||||||
const rpPayload: CassandraKeyspaceCreateUpdateParameters = {
|
const rpPayload: CassandraKeyspaceCreateUpdateParameters = {
|
||||||
properties: {
|
properties: {
|
||||||
@@ -123,6 +173,22 @@ async function createCassandraKeyspace(params: DataModels.CreateDatabaseParams):
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function createGremlineDatabase(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
async function createGremlineDatabase(params: DataModels.CreateDatabaseParams): Promise<DataModels.Database> {
|
||||||
|
try {
|
||||||
|
const getResponse = await getGremlinDatabase(
|
||||||
|
userContext.subscriptionId,
|
||||||
|
userContext.resourceGroup,
|
||||||
|
userContext.databaseAccount.name,
|
||||||
|
params.databaseId
|
||||||
|
);
|
||||||
|
if (getResponse?.properties?.resource) {
|
||||||
|
throw new Error(`Create database failed: database with id ${params.databaseId} already exists`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "NotFound") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const options: CreateUpdateOptions = constructRpOptions(params);
|
const options: CreateUpdateOptions = constructRpOptions(params);
|
||||||
const rpPayload: GremlinDatabaseCreateUpdateParameters = {
|
const rpPayload: GremlinDatabaseCreateUpdateParameters = {
|
||||||
properties: {
|
properties: {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { CollectionBase } from "../../Contracts/ViewModels";
|
import { CollectionBase } from "../../Contracts/ViewModels";
|
||||||
import DocumentId from "../../Explorer/Tree/DocumentId";
|
|
||||||
import { logConsoleInfo, logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
|
|
||||||
import { client } from "../CosmosClient";
|
import { client } from "../CosmosClient";
|
||||||
import { getEntityName } from "../DocumentUtility";
|
import { getEntityName } from "../DocumentUtility";
|
||||||
import { handleError } from "../ErrorHandlingUtils";
|
import { handleError } from "../ErrorHandlingUtils";
|
||||||
|
import { logConsoleInfo, logConsoleProgress } from "../../Utils/NotificationConsoleUtils";
|
||||||
|
import DocumentId from "../../Explorer/Tree/DocumentId";
|
||||||
|
|
||||||
export const deleteDocument = async (collection: CollectionBase, documentId: DocumentId): Promise<void> => {
|
export const deleteDocument = async (collection: CollectionBase, documentId: DocumentId): Promise<void> => {
|
||||||
const entityName: string = getEntityName();
|
const entityName: string = getEntityName();
|
||||||
|
|||||||
@@ -88,9 +88,6 @@ export interface SubscriptionPolicies {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface Resource {
|
export interface Resource {
|
||||||
_partitionKeyValue?: string;
|
|
||||||
_partitionKey?: string;
|
|
||||||
_attachments?: string;
|
|
||||||
_rid: string;
|
_rid: string;
|
||||||
_self: string;
|
_self: string;
|
||||||
_etag: string;
|
_etag: string;
|
||||||
|
|||||||
@@ -33,20 +33,16 @@ export class EditorReact extends React.Component<EditorReactProps, EditorReactSt
|
|||||||
this.createEditor(this.configureEditor.bind(this));
|
this.createEditor(this.configureEditor.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
public shouldComponentUpdate(): boolean {
|
public componentDidUpdate(previous: EditorReactProps) {
|
||||||
return true;
|
if (this.props.content !== previous.content) {
|
||||||
|
this.editor.setValue(this.props.content);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public componentWillUnmount(): void {
|
public componentWillUnmount(): void {
|
||||||
this.selectionListener && this.selectionListener.dispose();
|
this.selectionListener && this.selectionListener.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
public componentDidUpdate(prevProps: EditorReactProps): void {
|
|
||||||
if (this.props.content !== prevProps.content) {
|
|
||||||
this.editor.setValue(this.props.content);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public render(): JSX.Element {
|
public render(): JSX.Element {
|
||||||
return (
|
return (
|
||||||
<React.Fragment>
|
<React.Fragment>
|
||||||
|
|||||||
@@ -42,6 +42,19 @@ exports[`SettingsComponent renders 1`] = `
|
|||||||
"resourceTree": ResourceTreeAdapter {
|
"resourceTree": ResourceTreeAdapter {
|
||||||
"container": [Circular],
|
"container": [Circular],
|
||||||
"copyNotebook": [Function],
|
"copyNotebook": [Function],
|
||||||
|
"gitHubOAuthService": GitHubOAuthService {
|
||||||
|
"junoClient": JunoClient {
|
||||||
|
"cachedPinnedRepos": [Function],
|
||||||
|
},
|
||||||
|
"token": [Function],
|
||||||
|
},
|
||||||
|
"junoClient": JunoClient {
|
||||||
|
"cachedPinnedRepos": [Function],
|
||||||
|
},
|
||||||
|
"parameters": [Function],
|
||||||
|
},
|
||||||
|
"resourceTreeForResourceToken": ResourceTreeAdapterForResourceToken {
|
||||||
|
"container": [Circular],
|
||||||
"parameters": [Function],
|
"parameters": [Function],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -109,6 +122,19 @@ exports[`SettingsComponent renders 1`] = `
|
|||||||
"resourceTree": ResourceTreeAdapter {
|
"resourceTree": ResourceTreeAdapter {
|
||||||
"container": [Circular],
|
"container": [Circular],
|
||||||
"copyNotebook": [Function],
|
"copyNotebook": [Function],
|
||||||
|
"gitHubOAuthService": GitHubOAuthService {
|
||||||
|
"junoClient": JunoClient {
|
||||||
|
"cachedPinnedRepos": [Function],
|
||||||
|
},
|
||||||
|
"token": [Function],
|
||||||
|
},
|
||||||
|
"junoClient": JunoClient {
|
||||||
|
"cachedPinnedRepos": [Function],
|
||||||
|
},
|
||||||
|
"parameters": [Function],
|
||||||
|
},
|
||||||
|
"resourceTreeForResourceToken": ResourceTreeAdapterForResourceToken {
|
||||||
|
"container": [Circular],
|
||||||
"parameters": [Function],
|
"parameters": [Function],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ import TerminalTab from "./Tabs/TerminalTab";
|
|||||||
import Database from "./Tree/Database";
|
import Database from "./Tree/Database";
|
||||||
import ResourceTokenCollection from "./Tree/ResourceTokenCollection";
|
import ResourceTokenCollection from "./Tree/ResourceTokenCollection";
|
||||||
import { ResourceTreeAdapter } from "./Tree/ResourceTreeAdapter";
|
import { ResourceTreeAdapter } from "./Tree/ResourceTreeAdapter";
|
||||||
|
import { ResourceTreeAdapterForResourceToken } from "./Tree/ResourceTreeAdapterForResourceToken";
|
||||||
import StoredProcedure from "./Tree/StoredProcedure";
|
import StoredProcedure from "./Tree/StoredProcedure";
|
||||||
import { useDatabases } from "./useDatabases";
|
import { useDatabases } from "./useDatabases";
|
||||||
import { useSelectedNode } from "./useSelectedNode";
|
import { useSelectedNode } from "./useSelectedNode";
|
||||||
@@ -73,6 +74,9 @@ export default class Explorer {
|
|||||||
// Resource Tree
|
// Resource Tree
|
||||||
private resourceTree: ResourceTreeAdapter;
|
private resourceTree: ResourceTreeAdapter;
|
||||||
|
|
||||||
|
// Resource Token
|
||||||
|
public resourceTreeForResourceToken: ResourceTreeAdapterForResourceToken;
|
||||||
|
|
||||||
// Tabs
|
// Tabs
|
||||||
public isTabsContentExpanded: ko.Observable<boolean>;
|
public isTabsContentExpanded: ko.Observable<boolean>;
|
||||||
|
|
||||||
@@ -182,6 +186,7 @@ export default class Explorer {
|
|||||||
);
|
);
|
||||||
|
|
||||||
this.resourceTree = new ResourceTreeAdapter(this);
|
this.resourceTree = new ResourceTreeAdapter(this);
|
||||||
|
this.resourceTreeForResourceToken = new ResourceTreeAdapterForResourceToken(this);
|
||||||
|
|
||||||
// Override notebook server parameters from URL parameters
|
// Override notebook server parameters from URL parameters
|
||||||
if (userContext.features.notebookServerUrl && userContext.features.notebookServerToken) {
|
if (userContext.features.notebookServerUrl && userContext.features.notebookServerToken) {
|
||||||
@@ -357,9 +362,6 @@ export default class Explorer {
|
|||||||
notebookServerEndpoint: userContext.features.notebookServerUrl || connectionInfo.notebookServerEndpoint,
|
notebookServerEndpoint: userContext.features.notebookServerUrl || connectionInfo.notebookServerEndpoint,
|
||||||
authToken: userContext.features.notebookServerToken || connectionInfo.authToken,
|
authToken: userContext.features.notebookServerToken || connectionInfo.authToken,
|
||||||
});
|
});
|
||||||
|
|
||||||
useNotebook.getState().initializeNotebooksTree(this.notebookManager);
|
|
||||||
|
|
||||||
this.refreshNotebookList();
|
this.refreshNotebookList();
|
||||||
|
|
||||||
this._isInitializingNotebooks = false;
|
this._isInitializingNotebooks = false;
|
||||||
@@ -840,8 +842,6 @@ export default class Explorer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await this.resourceTree.initialize();
|
await this.resourceTree.initialize();
|
||||||
await useNotebook.getState().initializeNotebooksTree(this.notebookManager);
|
|
||||||
|
|
||||||
this.notebookManager?.refreshPinnedRepos();
|
this.notebookManager?.refreshPinnedRepos();
|
||||||
if (this.notebookToImport) {
|
if (this.notebookToImport) {
|
||||||
this.importAndOpenContent(this.notebookToImport.name, this.notebookToImport.content);
|
this.importAndOpenContent(this.notebookToImport.name, this.notebookToImport.content);
|
||||||
@@ -932,15 +932,14 @@ export default class Explorer {
|
|||||||
.finally(clearInProgressMessage);
|
.finally(clearInProgressMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Delete this function when ResourceTreeAdapter is removed.
|
public refreshContentItem(item: NotebookContentItem): Promise<void> {
|
||||||
public async refreshContentItem(item: NotebookContentItem): Promise<void> {
|
|
||||||
if (!useNotebook.getState().isNotebookEnabled || !this.notebookManager?.notebookContentClient) {
|
if (!useNotebook.getState().isNotebookEnabled || !this.notebookManager?.notebookContentClient) {
|
||||||
const error = "Attempt to refresh notebook list, but notebook is not enabled";
|
const error = "Attempt to refresh notebook list, but notebook is not enabled";
|
||||||
handleError(error, "Explorer/refreshContentItem");
|
handleError(error, "Explorer/refreshContentItem");
|
||||||
return Promise.reject(new Error(error));
|
return Promise.reject(new Error(error));
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.notebookManager?.notebookContentClient.updateItemChildrenInPlace(item);
|
return this.notebookManager?.notebookContentClient.updateItemChildren(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
public openNotebookTerminal(kind: ViewModels.TerminalKind) {
|
public openNotebookTerminal(kind: ViewModels.TerminalKind) {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { stringifyNotebook } from "@nteract/commutable";
|
import { stringifyNotebook } from "@nteract/commutable";
|
||||||
import { FileType, IContent, IContentProvider, IEmptyContent, ServerConfig } from "@nteract/core";
|
import { FileType, IContent, IContentProvider, IEmptyContent, ServerConfig } from "@nteract/core";
|
||||||
import { cloneDeep } from "lodash";
|
|
||||||
import { AjaxResponse } from "rxjs/ajax";
|
import { AjaxResponse } from "rxjs/ajax";
|
||||||
import * as StringUtils from "../../Utils/StringUtils";
|
import * as StringUtils from "../../Utils/StringUtils";
|
||||||
import * as FileSystemUtil from "./FileSystemUtil";
|
import * as FileSystemUtil from "./FileSystemUtil";
|
||||||
@@ -15,17 +14,7 @@ export class NotebookContentClient {
|
|||||||
* This updates the item and points all the children's parent to this item
|
* This updates the item and points all the children's parent to this item
|
||||||
* @param item
|
* @param item
|
||||||
*/
|
*/
|
||||||
public async updateItemChildren(item: NotebookContentItem): Promise<NotebookContentItem> {
|
public updateItemChildren(item: NotebookContentItem): Promise<void> {
|
||||||
const subItems = await this.fetchNotebookFiles(item.path);
|
|
||||||
const clonedItem = cloneDeep(item);
|
|
||||||
subItems.forEach((subItem) => (subItem.parent = clonedItem));
|
|
||||||
clonedItem.children = subItems;
|
|
||||||
|
|
||||||
return clonedItem;
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Delete this function when ResourceTreeAdapter is removed.
|
|
||||||
public async updateItemChildrenInPlace(item: NotebookContentItem): Promise<void> {
|
|
||||||
return this.fetchNotebookFiles(item.path).then((subItems) => {
|
return this.fetchNotebookFiles(item.path).then((subItems) => {
|
||||||
item.children = subItems;
|
item.children = subItems;
|
||||||
subItems.forEach((subItem) => (subItem.parent = item));
|
subItems.forEach((subItem) => (subItem.parent = item));
|
||||||
@@ -66,20 +55,18 @@ export class NotebookContentClient {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async deleteContentItem(item: NotebookContentItem): Promise<void> {
|
public deleteContentItem(item: NotebookContentItem): Promise<void> {
|
||||||
const path = await this.deleteNotebookFile(item.path);
|
return this.deleteNotebookFile(item.path).then((path: string) => {
|
||||||
useNotebook.getState().deleteNotebookItem(item);
|
if (!path || path !== item.path) {
|
||||||
|
throw new Error("No path provided");
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Delete once old resource tree is removed
|
if (item.parent && item.parent.children) {
|
||||||
if (!path || path !== item.path) {
|
// Remove deleted child
|
||||||
throw new Error("No path provided");
|
const newChildren = item.parent.children.filter((child) => child.path !== path);
|
||||||
}
|
item.parent.children = newChildren;
|
||||||
|
}
|
||||||
if (item.parent && item.parent.children) {
|
});
|
||||||
// Remove deleted child
|
|
||||||
const newChildren = item.parent.children.filter((child) => child.path !== path);
|
|
||||||
item.parent.children = newChildren;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ import { SnapshotRequest } from "./NotebookComponent/types";
|
|||||||
import { NotebookContainerClient } from "./NotebookContainerClient";
|
import { NotebookContainerClient } from "./NotebookContainerClient";
|
||||||
import { NotebookContentClient } from "./NotebookContentClient";
|
import { NotebookContentClient } from "./NotebookContentClient";
|
||||||
import { SchemaAnalyzerNotebook } from "./SchemaAnalyzer/SchemaAnalyzerUtils";
|
import { SchemaAnalyzerNotebook } from "./SchemaAnalyzer/SchemaAnalyzerUtils";
|
||||||
import { useNotebook } from "./useNotebook";
|
|
||||||
|
|
||||||
type NotebookPaneContent = string | ImmutableNotebook;
|
type NotebookPaneContent = string | ImmutableNotebook;
|
||||||
|
|
||||||
@@ -111,7 +110,6 @@ export default class NotebookManager {
|
|||||||
this.junoClient.subscribeToPinnedRepos((pinnedRepos) => {
|
this.junoClient.subscribeToPinnedRepos((pinnedRepos) => {
|
||||||
this.params.resourceTree.initializeGitHubRepos(pinnedRepos);
|
this.params.resourceTree.initializeGitHubRepos(pinnedRepos);
|
||||||
this.params.resourceTree.triggerRender();
|
this.params.resourceTree.triggerRender();
|
||||||
useNotebook.getState().initializeGitHubRepos(pinnedRepos);
|
|
||||||
});
|
});
|
||||||
this.refreshPinnedRepos();
|
this.refreshPinnedRepos();
|
||||||
}
|
}
|
||||||
@@ -143,7 +141,6 @@ export default class NotebookManager {
|
|||||||
notebookContentRef={notebookContentRef}
|
notebookContentRef={notebookContentRef}
|
||||||
onTakeSnapshot={onTakeSnapshot}
|
onTakeSnapshot={onTakeSnapshot}
|
||||||
/>,
|
/>,
|
||||||
"440px",
|
|
||||||
onClosePanel
|
onClosePanel
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { cloneDeep } from "lodash";
|
|
||||||
import create, { UseStore } from "zustand";
|
import create, { UseStore } from "zustand";
|
||||||
import { AuthType } from "../../AuthType";
|
import { AuthType } from "../../AuthType";
|
||||||
import * as Constants from "../../Common/Constants";
|
import * as Constants from "../../Common/Constants";
|
||||||
@@ -6,14 +5,8 @@ import { getErrorMessage } from "../../Common/ErrorHandlingUtils";
|
|||||||
import * as Logger from "../../Common/Logger";
|
import * as Logger from "../../Common/Logger";
|
||||||
import { configContext } from "../../ConfigContext";
|
import { configContext } from "../../ConfigContext";
|
||||||
import * as DataModels from "../../Contracts/DataModels";
|
import * as DataModels from "../../Contracts/DataModels";
|
||||||
import { IPinnedRepo } from "../../Juno/JunoClient";
|
|
||||||
import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants";
|
|
||||||
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
|
||||||
import { userContext } from "../../UserContext";
|
import { userContext } from "../../UserContext";
|
||||||
import { getAuthorizationHeader } from "../../Utils/AuthorizationUtils";
|
import { getAuthorizationHeader } from "../../Utils/AuthorizationUtils";
|
||||||
import * as GitHubUtils from "../../Utils/GitHubUtils";
|
|
||||||
import { NotebookContentItem, NotebookContentItemType } from "./NotebookContentItem";
|
|
||||||
import NotebookManager from "./NotebookManager";
|
|
||||||
|
|
||||||
interface NotebookState {
|
interface NotebookState {
|
||||||
isNotebookEnabled: boolean;
|
isNotebookEnabled: boolean;
|
||||||
@@ -25,9 +18,6 @@ interface NotebookState {
|
|||||||
isShellEnabled: boolean;
|
isShellEnabled: boolean;
|
||||||
notebookBasePath: string;
|
notebookBasePath: string;
|
||||||
isInitializingNotebooks: boolean;
|
isInitializingNotebooks: boolean;
|
||||||
myNotebooksContentRoot: NotebookContentItem;
|
|
||||||
gitHubNotebooksContentRoot: NotebookContentItem;
|
|
||||||
galleryContentRoot: NotebookContentItem;
|
|
||||||
setIsNotebookEnabled: (isNotebookEnabled: boolean) => void;
|
setIsNotebookEnabled: (isNotebookEnabled: boolean) => void;
|
||||||
setIsNotebooksEnabledForAccount: (isNotebooksEnabledForAccount: boolean) => void;
|
setIsNotebooksEnabledForAccount: (isNotebooksEnabledForAccount: boolean) => void;
|
||||||
setNotebookServerInfo: (notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo) => void;
|
setNotebookServerInfo: (notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo) => void;
|
||||||
@@ -37,14 +27,9 @@ interface NotebookState {
|
|||||||
setIsShellEnabled: (isShellEnabled: boolean) => void;
|
setIsShellEnabled: (isShellEnabled: boolean) => void;
|
||||||
setNotebookBasePath: (notebookBasePath: string) => void;
|
setNotebookBasePath: (notebookBasePath: string) => void;
|
||||||
refreshNotebooksEnabledStateForAccount: () => Promise<void>;
|
refreshNotebooksEnabledStateForAccount: () => Promise<void>;
|
||||||
findItem: (root: NotebookContentItem, item: NotebookContentItem) => NotebookContentItem;
|
|
||||||
updateNotebookItem: (item: NotebookContentItem) => void;
|
|
||||||
deleteNotebookItem: (item: NotebookContentItem) => void;
|
|
||||||
initializeNotebooksTree: (notebookManager: NotebookManager) => Promise<void>;
|
|
||||||
initializeGitHubRepos: (pinnedRepos: IPinnedRepo[]) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useNotebook: UseStore<NotebookState> = create((set, get) => ({
|
export const useNotebook: UseStore<NotebookState> = create((set) => ({
|
||||||
isNotebookEnabled: false,
|
isNotebookEnabled: false,
|
||||||
isNotebooksEnabledForAccount: false,
|
isNotebooksEnabledForAccount: false,
|
||||||
notebookServerInfo: {
|
notebookServerInfo: {
|
||||||
@@ -61,9 +46,6 @@ export const useNotebook: UseStore<NotebookState> = create((set, get) => ({
|
|||||||
isShellEnabled: false,
|
isShellEnabled: false,
|
||||||
notebookBasePath: Constants.Notebook.defaultBasePath,
|
notebookBasePath: Constants.Notebook.defaultBasePath,
|
||||||
isInitializingNotebooks: false,
|
isInitializingNotebooks: false,
|
||||||
myNotebooksContentRoot: undefined,
|
|
||||||
gitHubNotebooksContentRoot: undefined,
|
|
||||||
galleryContentRoot: undefined,
|
|
||||||
setIsNotebookEnabled: (isNotebookEnabled: boolean) => set({ isNotebookEnabled }),
|
setIsNotebookEnabled: (isNotebookEnabled: boolean) => set({ isNotebookEnabled }),
|
||||||
setIsNotebooksEnabledForAccount: (isNotebooksEnabledForAccount: boolean) => set({ isNotebooksEnabledForAccount }),
|
setIsNotebooksEnabledForAccount: (isNotebooksEnabledForAccount: boolean) => set({ isNotebooksEnabledForAccount }),
|
||||||
setNotebookServerInfo: (notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo) =>
|
setNotebookServerInfo: (notebookServerInfo: DataModels.NotebookWorkspaceConnectionInfo) =>
|
||||||
@@ -121,115 +103,4 @@ export const useNotebook: UseStore<NotebookState> = create((set, get) => ({
|
|||||||
set({ isNotebooksEnabledForAccount: false });
|
set({ isNotebooksEnabledForAccount: false });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
findItem: (root: NotebookContentItem, item: NotebookContentItem): NotebookContentItem => {
|
|
||||||
const currentItem = root || get().myNotebooksContentRoot;
|
|
||||||
|
|
||||||
if (currentItem) {
|
|
||||||
if (currentItem.path === item.path && currentItem.name === item.name) {
|
|
||||||
return currentItem;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (currentItem.children) {
|
|
||||||
for (const childItem of currentItem.children) {
|
|
||||||
const result = get().findItem(childItem, item);
|
|
||||||
if (result) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined;
|
|
||||||
},
|
|
||||||
updateNotebookItem: (item: NotebookContentItem): void => {
|
|
||||||
const root = cloneDeep(get().myNotebooksContentRoot);
|
|
||||||
const parentItem = get().findItem(root, item.parent);
|
|
||||||
parentItem.children = parentItem.children.filter((child) => child.path !== item.path);
|
|
||||||
parentItem.children.push(item);
|
|
||||||
item.parent = parentItem;
|
|
||||||
set({ myNotebooksContentRoot: root });
|
|
||||||
},
|
|
||||||
deleteNotebookItem: (item: NotebookContentItem): void => {
|
|
||||||
const root = cloneDeep(get().myNotebooksContentRoot);
|
|
||||||
const parentItem = get().findItem(root, item.parent);
|
|
||||||
parentItem.children = parentItem.children.filter((child) => child.path !== item.path);
|
|
||||||
set({ myNotebooksContentRoot: root });
|
|
||||||
},
|
|
||||||
initializeNotebooksTree: async (notebookManager: NotebookManager): Promise<void> => {
|
|
||||||
const myNotebooksContentRoot = {
|
|
||||||
name: "My Notebooks",
|
|
||||||
path: get().notebookBasePath,
|
|
||||||
type: NotebookContentItemType.Directory,
|
|
||||||
};
|
|
||||||
const galleryContentRoot = {
|
|
||||||
name: "Gallery",
|
|
||||||
path: "Gallery",
|
|
||||||
type: NotebookContentItemType.File,
|
|
||||||
};
|
|
||||||
const gitHubNotebooksContentRoot = notebookManager?.gitHubOAuthService?.isLoggedIn()
|
|
||||||
? {
|
|
||||||
name: "GitHub repos",
|
|
||||||
path: "PsuedoDir",
|
|
||||||
type: NotebookContentItemType.Directory,
|
|
||||||
}
|
|
||||||
: undefined;
|
|
||||||
set({
|
|
||||||
myNotebooksContentRoot,
|
|
||||||
galleryContentRoot,
|
|
||||||
gitHubNotebooksContentRoot,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (get().notebookServerInfo?.notebookServerEndpoint) {
|
|
||||||
const updatedRoot = await notebookManager?.notebookContentClient?.updateItemChildren(myNotebooksContentRoot);
|
|
||||||
set({ myNotebooksContentRoot: updatedRoot });
|
|
||||||
|
|
||||||
if (updatedRoot?.children) {
|
|
||||||
// Count 1st generation children (tree is lazy-loaded)
|
|
||||||
const nodeCounts = { files: 0, notebooks: 0, directories: 0 };
|
|
||||||
updatedRoot.children.forEach((notebookItem) => {
|
|
||||||
switch (notebookItem.type) {
|
|
||||||
case NotebookContentItemType.File:
|
|
||||||
nodeCounts.files++;
|
|
||||||
break;
|
|
||||||
case NotebookContentItemType.Directory:
|
|
||||||
nodeCounts.directories++;
|
|
||||||
break;
|
|
||||||
case NotebookContentItemType.Notebook:
|
|
||||||
nodeCounts.notebooks++;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
TelemetryProcessor.trace(Action.RefreshResourceTreeMyNotebooks, ActionModifiers.Mark, { ...nodeCounts });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
initializeGitHubRepos: (pinnedRepos: IPinnedRepo[]): void => {
|
|
||||||
const gitHubNotebooksContentRoot = cloneDeep(get().gitHubNotebooksContentRoot);
|
|
||||||
if (gitHubNotebooksContentRoot) {
|
|
||||||
gitHubNotebooksContentRoot.children = [];
|
|
||||||
pinnedRepos?.forEach((pinnedRepo) => {
|
|
||||||
const repoFullName = GitHubUtils.toRepoFullName(pinnedRepo.owner, pinnedRepo.name);
|
|
||||||
const repoTreeItem: NotebookContentItem = {
|
|
||||||
name: repoFullName,
|
|
||||||
path: "PsuedoDir",
|
|
||||||
type: NotebookContentItemType.Directory,
|
|
||||||
children: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
pinnedRepo.branches.forEach((branch) => {
|
|
||||||
repoTreeItem.children.push({
|
|
||||||
name: branch.name,
|
|
||||||
path: GitHubUtils.toContentUri(pinnedRepo.owner, pinnedRepo.name, branch.name, ""),
|
|
||||||
type: NotebookContentItemType.Directory,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
gitHubNotebooksContentRoot.children.push(repoTreeItem);
|
|
||||||
});
|
|
||||||
|
|
||||||
set({ gitHubNotebooksContentRoot });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -31,6 +31,19 @@ exports[`GitHub Repos Panel should render Default properly 1`] = `
|
|||||||
"resourceTree": ResourceTreeAdapter {
|
"resourceTree": ResourceTreeAdapter {
|
||||||
"container": [Circular],
|
"container": [Circular],
|
||||||
"copyNotebook": [Function],
|
"copyNotebook": [Function],
|
||||||
|
"gitHubOAuthService": GitHubOAuthService {
|
||||||
|
"junoClient": JunoClient {
|
||||||
|
"cachedPinnedRepos": [Function],
|
||||||
|
},
|
||||||
|
"token": [Function],
|
||||||
|
},
|
||||||
|
"junoClient": JunoClient {
|
||||||
|
"cachedPinnedRepos": [Function],
|
||||||
|
},
|
||||||
|
"parameters": [Function],
|
||||||
|
},
|
||||||
|
"resourceTreeForResourceToken": ResourceTreeAdapterForResourceToken {
|
||||||
|
"container": [Circular],
|
||||||
"parameters": [Function],
|
"parameters": [Function],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -150,6 +150,9 @@
|
|||||||
.backImageIcon {
|
.backImageIcon {
|
||||||
margin-top: 8px;
|
margin-top: 8px;
|
||||||
}
|
}
|
||||||
|
.entityValueTextField {
|
||||||
|
margin: 24px;
|
||||||
|
}
|
||||||
.addEntityDatePicker {
|
.addEntityDatePicker {
|
||||||
max-width: 145px;
|
max-width: 145px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,12 +85,11 @@ export class PanelContainerComponent extends React.Component<PanelContainerProps
|
|||||||
|
|
||||||
export const SidePanel: React.FC = () => {
|
export const SidePanel: React.FC = () => {
|
||||||
const isConsoleExpanded = useNotificationConsole((state) => state.isExpanded);
|
const isConsoleExpanded = useNotificationConsole((state) => state.isExpanded);
|
||||||
const { isOpen, panelContent, panelWidth, headerText } = useSidePanel((state) => {
|
const { isOpen, panelContent, headerText } = useSidePanel((state) => {
|
||||||
return {
|
return {
|
||||||
isOpen: state.isOpen,
|
isOpen: state.isOpen,
|
||||||
panelContent: state.panelContent,
|
panelContent: state.panelContent,
|
||||||
headerText: state.headerText,
|
headerText: state.headerText,
|
||||||
panelWidth: state.panelWidth,
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
// TODO Refactor PanelContainerComponent into a functional component and remove this wrapper
|
// TODO Refactor PanelContainerComponent into a functional component and remove this wrapper
|
||||||
@@ -101,7 +100,6 @@ export const SidePanel: React.FC = () => {
|
|||||||
panelContent={panelContent}
|
panelContent={panelContent}
|
||||||
headerText={headerText}
|
headerText={headerText}
|
||||||
isConsoleExpanded={isConsoleExpanded}
|
isConsoleExpanded={isConsoleExpanded}
|
||||||
panelWidth={panelWidth}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -21,6 +21,19 @@ exports[`StringInput Pane should render Create new directory properly 1`] = `
|
|||||||
"resourceTree": ResourceTreeAdapter {
|
"resourceTree": ResourceTreeAdapter {
|
||||||
"container": [Circular],
|
"container": [Circular],
|
||||||
"copyNotebook": [Function],
|
"copyNotebook": [Function],
|
||||||
|
"gitHubOAuthService": GitHubOAuthService {
|
||||||
|
"junoClient": JunoClient {
|
||||||
|
"cachedPinnedRepos": [Function],
|
||||||
|
},
|
||||||
|
"token": [Function],
|
||||||
|
},
|
||||||
|
"junoClient": JunoClient {
|
||||||
|
"cachedPinnedRepos": [Function],
|
||||||
|
},
|
||||||
|
"parameters": [Function],
|
||||||
|
},
|
||||||
|
"resourceTreeForResourceToken": ResourceTreeAdapterForResourceToken {
|
||||||
|
"container": [Circular],
|
||||||
"parameters": [Function],
|
"parameters": [Function],
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { IDropdownOption, Image, Label, Stack, Text, TextField } from "@fluentui/react";
|
import { IDropdownOption, Image, IPanelProps, IRenderFunction, Label, Stack, Text, TextField } from "@fluentui/react";
|
||||||
import { useBoolean } from "@fluentui/react-hooks";
|
import { useBoolean } from "@fluentui/react-hooks";
|
||||||
import React, { FunctionComponent, useEffect, useState } from "react";
|
import React, { FunctionComponent, useEffect, useState } from "react";
|
||||||
import * as _ from "underscore";
|
import * as _ from "underscore";
|
||||||
import AddPropertyIcon from "../../../../images/Add-property.svg";
|
import AddPropertyIcon from "../../../../images/Add-property.svg";
|
||||||
import RevertBackIcon from "../../../../images/RevertBack.svg";
|
import RevertBackIcon from "../../../../images/RevertBack.svg";
|
||||||
import { getErrorMessage, handleError } from "../../../Common/ErrorHandlingUtils";
|
|
||||||
import { TableEntity } from "../../../Common/TableEntity";
|
import { TableEntity } from "../../../Common/TableEntity";
|
||||||
|
import { useSidePanel } from "../../../hooks/useSidePanel";
|
||||||
import { userContext } from "../../../UserContext";
|
import { userContext } from "../../../UserContext";
|
||||||
import * as TableConstants from "../../Tables/Constants";
|
import * as TableConstants from "../../Tables/Constants";
|
||||||
import * as DataTableUtilities from "../../Tables/DataTable/DataTableUtilities";
|
import * as DataTableUtilities from "../../Tables/DataTable/DataTableUtilities";
|
||||||
@@ -15,7 +15,7 @@ import { CassandraAPIDataClient, CassandraTableKey, TableDataClient } from "../.
|
|||||||
import * as TableEntityProcessor from "../../Tables/TableEntityProcessor";
|
import * as TableEntityProcessor from "../../Tables/TableEntityProcessor";
|
||||||
import * as Utilities from "../../Tables/Utilities";
|
import * as Utilities from "../../Tables/Utilities";
|
||||||
import QueryTablesTab from "../../Tabs/QueryTablesTab";
|
import QueryTablesTab from "../../Tabs/QueryTablesTab";
|
||||||
import { RightPaneForm, RightPaneFormProps } from "../RightPaneForm/RightPaneForm";
|
import { PanelContainerComponent } from "../PanelContainerComponent";
|
||||||
import {
|
import {
|
||||||
attributeNameLabel,
|
attributeNameLabel,
|
||||||
attributeValueLabel,
|
attributeValueLabel,
|
||||||
@@ -30,7 +30,9 @@ import {
|
|||||||
getCassandraDefaultEntities,
|
getCassandraDefaultEntities,
|
||||||
getDefaultEntities,
|
getDefaultEntities,
|
||||||
getEntityValuePlaceholder,
|
getEntityValuePlaceholder,
|
||||||
|
getPanelTitle,
|
||||||
imageProps,
|
imageProps,
|
||||||
|
isValidEntities,
|
||||||
options,
|
options,
|
||||||
} from "./Validators/EntityTableHelper";
|
} from "./Validators/EntityTableHelper";
|
||||||
|
|
||||||
@@ -59,6 +61,7 @@ export const AddTableEntityPanel: FunctionComponent<AddTableEntityPanelProps> =
|
|||||||
tableEntityListViewModel,
|
tableEntityListViewModel,
|
||||||
cassandraApiClient,
|
cassandraApiClient,
|
||||||
}: AddTableEntityPanelProps): JSX.Element => {
|
}: AddTableEntityPanelProps): JSX.Element => {
|
||||||
|
const closeSidePanel = useSidePanel((state) => state.closeSidePanel);
|
||||||
const [entities, setEntities] = useState<EntityRowType[]>([]);
|
const [entities, setEntities] = useState<EntityRowType[]>([]);
|
||||||
const [selectedRow, setSelectedRow] = useState<number>(0);
|
const [selectedRow, setSelectedRow] = useState<number>(0);
|
||||||
const [entityAttributeValue, setEntityAttributeValue] = useState<string>("");
|
const [entityAttributeValue, setEntityAttributeValue] = useState<string>("");
|
||||||
@@ -67,8 +70,6 @@ export const AddTableEntityPanel: FunctionComponent<AddTableEntityPanelProps> =
|
|||||||
isEntityValuePanelOpen,
|
isEntityValuePanelOpen,
|
||||||
{ setTrue: setIsEntityValuePanelTrue, setFalse: setIsEntityValuePanelFalse },
|
{ setTrue: setIsEntityValuePanelTrue, setFalse: setIsEntityValuePanelFalse },
|
||||||
] = useBoolean(false);
|
] = useBoolean(false);
|
||||||
const [formError, setFormError] = useState<string>("");
|
|
||||||
const [isExecuting, setIsExecuting] = useState<boolean>(false);
|
|
||||||
|
|
||||||
/* Get default and previous saved entity headers */
|
/* Get default and previous saved entity headers */
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -97,36 +98,19 @@ export const AddTableEntityPanel: FunctionComponent<AddTableEntityPanelProps> =
|
|||||||
};
|
};
|
||||||
|
|
||||||
/* Add new entity attribute */
|
/* Add new entity attribute */
|
||||||
const onSubmit = async (): Promise<void> => {
|
const submit = async (event: React.FormEvent<HTMLInputElement>): Promise<void> => {
|
||||||
for (let i = 0; i < entities.length; i++) {
|
if (!isValidEntities(entities)) {
|
||||||
const { property, type } = entities[i];
|
return undefined;
|
||||||
if (property === "" || property === undefined) {
|
|
||||||
setFormError(`Property name cannot be empty. Please enter a property name`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!type) {
|
|
||||||
setFormError(`Property type cannot be empty. Please select a type from the dropdown for property ${property}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
setIsExecuting(true);
|
|
||||||
const entity: Entities.ITableEntity = entityFromAttributes(entities);
|
const entity: Entities.ITableEntity = entityFromAttributes(entities);
|
||||||
const newEntity: Entities.ITableEntity = await tableDataClient.createDocument(queryTablesTab.collection, entity);
|
const newEntity: Entities.ITableEntity = await tableDataClient.createDocument(queryTablesTab.collection, entity);
|
||||||
try {
|
await tableEntityListViewModel.addEntityToCache(newEntity);
|
||||||
await tableEntityListViewModel.addEntityToCache(newEntity);
|
if (!tryInsertNewHeaders(tableEntityListViewModel, newEntity)) {
|
||||||
if (!tryInsertNewHeaders(tableEntityListViewModel, newEntity)) {
|
tableEntityListViewModel.redrawTableThrottled();
|
||||||
tableEntityListViewModel.redrawTableThrottled();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
const errorMessage = getErrorMessage(error);
|
|
||||||
setFormError(errorMessage);
|
|
||||||
handleError(errorMessage, "AddTableRow");
|
|
||||||
throw error;
|
|
||||||
} finally {
|
|
||||||
setIsExecuting(false);
|
|
||||||
}
|
}
|
||||||
|
closeSidePanel();
|
||||||
};
|
};
|
||||||
|
|
||||||
const tryInsertNewHeaders = (viewModel: TableEntityListViewModel, newEntity: Entities.ITableEntity): boolean => {
|
const tryInsertNewHeaders = (viewModel: TableEntityListViewModel, newEntity: Entities.ITableEntity): boolean => {
|
||||||
@@ -216,80 +200,110 @@ export const AddTableEntityPanel: FunctionComponent<AddTableEntityPanelProps> =
|
|||||||
setIsEntityValuePanelTrue();
|
setIsEntityValuePanelTrue();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const renderPanelContent = (): JSX.Element => {
|
||||||
|
return (
|
||||||
|
<form className="panelFormWrapper">
|
||||||
|
<div className="panelFormWrapper">
|
||||||
|
<div className="panelMainContent">
|
||||||
|
{entities.map((entity, index) => {
|
||||||
|
return (
|
||||||
|
<TableEntity
|
||||||
|
key={"" + entity.id + index}
|
||||||
|
isDeleteOptionVisible={entity.isDeleteOptionVisible}
|
||||||
|
entityTypeLabel={index === 0 && dataTypeLabel}
|
||||||
|
entityPropertyLabel={index === 0 && attributeNameLabel}
|
||||||
|
entityValueLabel={index === 0 && attributeValueLabel}
|
||||||
|
options={userContext.apiType === "Cassandra" ? cassandraOptions : options}
|
||||||
|
isPropertyTypeDisable={entity.isPropertyTypeDisable}
|
||||||
|
entityProperty={entity.property}
|
||||||
|
selectedKey={entity.type}
|
||||||
|
entityPropertyPlaceHolder={detailedHelp}
|
||||||
|
entityValuePlaceholder={entity.entityValuePlaceholder}
|
||||||
|
entityValue={entity.value}
|
||||||
|
isEntityTypeDate={entity.isEntityTypeDate}
|
||||||
|
entityTimeValue={entity.entityTimeValue}
|
||||||
|
onEditEntity={() => editEntity(index)}
|
||||||
|
onSelectDate={(date: Date) => {
|
||||||
|
entityChange(date, index, "value");
|
||||||
|
}}
|
||||||
|
onDeleteEntity={() => deleteEntityAtIndex(index)}
|
||||||
|
onEntityPropertyChange={(event, newInput?: string) => {
|
||||||
|
entityChange(newInput, index, "property");
|
||||||
|
}}
|
||||||
|
onEntityTypeChange={(event: React.FormEvent<HTMLDivElement>, selectedParam: IDropdownOption) => {
|
||||||
|
entityTypeChange(event, selectedParam, index);
|
||||||
|
}}
|
||||||
|
onEntityValueChange={(event, newInput?: string) => {
|
||||||
|
entityChange(newInput, index, "value");
|
||||||
|
}}
|
||||||
|
onEntityTimeValueChange={(event, newInput?: string) => {
|
||||||
|
entityChange(newInput, index, "time");
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{userContext.apiType !== "Cassandra" && (
|
||||||
|
<Stack horizontal onClick={addNewEntity} className="addButtonEntiy">
|
||||||
|
<Image {...imageProps} src={AddPropertyIcon} alt="Add Entity" />
|
||||||
|
<Text className="addNewParamStyle">{getAddButtonLabel(userContext.apiType)}</Text>
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="paneFooter">
|
||||||
|
<div className="leftpanel-okbut">
|
||||||
|
<input
|
||||||
|
type="submit"
|
||||||
|
onClick={submit}
|
||||||
|
className="genericPaneSubmitBtn"
|
||||||
|
value={getButtonLabel(userContext.apiType)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onRenderNavigationContent: IRenderFunction<IPanelProps> = () => {
|
||||||
|
return (
|
||||||
|
<Stack horizontal {...columnProps}>
|
||||||
|
<Image {...backImageProps} src={RevertBackIcon} alt="back" onClick={() => setIsEntityValuePanelFalse()} />
|
||||||
|
<Label>{entityAttributeProperty}</Label>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
if (isEntityValuePanelOpen) {
|
if (isEntityValuePanelOpen) {
|
||||||
return (
|
return (
|
||||||
<Stack style={{ padding: "20px 34px" }}>
|
<PanelContainerComponent
|
||||||
<Stack horizontal {...columnProps}>
|
headerText=""
|
||||||
<Image {...backImageProps} src={RevertBackIcon} alt="back" onClick={() => setIsEntityValuePanelFalse()} />
|
onRenderNavigationContent={onRenderNavigationContent}
|
||||||
<Label>{entityAttributeProperty}</Label>
|
panelWidth="700px"
|
||||||
</Stack>
|
isOpen={true}
|
||||||
<TextField
|
panelContent={
|
||||||
multiline
|
<TextField
|
||||||
rows={5}
|
multiline
|
||||||
value={entityAttributeValue}
|
rows={5}
|
||||||
onChange={(event, newInput?: string) => {
|
className="entityValueTextField"
|
||||||
entityChange(newInput, selectedRow, "value");
|
value={entityAttributeValue}
|
||||||
setEntityAttributeValue(newInput);
|
onChange={(event, newInput?: string) => {
|
||||||
}}
|
entityChange(newInput, selectedRow, "value");
|
||||||
/>
|
setEntityAttributeValue(newInput);
|
||||||
</Stack>
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
isConsoleExpanded={false}
|
||||||
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const props: RightPaneFormProps = {
|
|
||||||
formError,
|
|
||||||
isExecuting,
|
|
||||||
submitButtonText: getButtonLabel(userContext.apiType),
|
|
||||||
onSubmit,
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<RightPaneForm {...props}>
|
<PanelContainerComponent
|
||||||
<div className="panelMainContent">
|
headerText={getPanelTitle(userContext.apiType)}
|
||||||
{entities.map((entity, index) => {
|
panelWidth="700px"
|
||||||
return (
|
isOpen={true}
|
||||||
<TableEntity
|
panelContent={renderPanelContent()}
|
||||||
key={"" + entity.id + index}
|
isConsoleExpanded={false}
|
||||||
isDeleteOptionVisible={entity.isDeleteOptionVisible}
|
/>
|
||||||
entityTypeLabel={index === 0 && dataTypeLabel}
|
|
||||||
entityPropertyLabel={index === 0 && attributeNameLabel}
|
|
||||||
entityValueLabel={index === 0 && attributeValueLabel}
|
|
||||||
options={userContext.apiType === "Cassandra" ? cassandraOptions : options}
|
|
||||||
isPropertyTypeDisable={entity.isPropertyTypeDisable}
|
|
||||||
entityProperty={entity.property}
|
|
||||||
selectedKey={entity.type}
|
|
||||||
entityPropertyPlaceHolder={detailedHelp}
|
|
||||||
entityValuePlaceholder={entity.entityValuePlaceholder}
|
|
||||||
entityValue={entity.value}
|
|
||||||
isEntityTypeDate={entity.isEntityTypeDate}
|
|
||||||
entityTimeValue={entity.entityTimeValue}
|
|
||||||
onEditEntity={() => editEntity(index)}
|
|
||||||
onSelectDate={(date: Date) => {
|
|
||||||
entityChange(date, index, "value");
|
|
||||||
}}
|
|
||||||
onDeleteEntity={() => deleteEntityAtIndex(index)}
|
|
||||||
onEntityPropertyChange={(event, newInput?: string) => {
|
|
||||||
entityChange(newInput, index, "property");
|
|
||||||
}}
|
|
||||||
onEntityTypeChange={(event: React.FormEvent<HTMLDivElement>, selectedParam: IDropdownOption) => {
|
|
||||||
entityTypeChange(event, selectedParam, index);
|
|
||||||
}}
|
|
||||||
onEntityValueChange={(event, newInput?: string) => {
|
|
||||||
entityChange(newInput, index, "value");
|
|
||||||
}}
|
|
||||||
onEntityTimeValueChange={(event, newInput?: string) => {
|
|
||||||
entityChange(newInput, index, "time");
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{userContext.apiType !== "Cassandra" && (
|
|
||||||
<Stack horizontal onClick={addNewEntity} className="addButtonEntiy">
|
|
||||||
<Image {...imageProps} src={AddPropertyIcon} alt="Add Entity" />
|
|
||||||
<Text className="addNewParamStyle">{getAddButtonLabel(userContext.apiType)}</Text>
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</RightPaneForm>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { IDropdownOption, Image, Label, Stack, Text, TextField } from "@fluentui/react";
|
import { IDropdownOption, Image, IPanelProps, IRenderFunction, Label, Stack, Text, TextField } from "@fluentui/react";
|
||||||
import { useBoolean } from "@fluentui/react-hooks";
|
import { useBoolean } from "@fluentui/react-hooks";
|
||||||
import React, { FunctionComponent, useEffect, useState } from "react";
|
import React, { FunctionComponent, useEffect, useState } from "react";
|
||||||
import * as _ from "underscore";
|
import * as _ from "underscore";
|
||||||
import AddPropertyIcon from "../../../../images/Add-property.svg";
|
import AddPropertyIcon from "../../../../images/Add-property.svg";
|
||||||
import RevertBackIcon from "../../../../images/RevertBack.svg";
|
import RevertBackIcon from "../../../../images/RevertBack.svg";
|
||||||
import { getErrorMessage, handleError } from "../../../Common/ErrorHandlingUtils";
|
|
||||||
import { TableEntity } from "../../../Common/TableEntity";
|
import { TableEntity } from "../../../Common/TableEntity";
|
||||||
|
import { useSidePanel } from "../../../hooks/useSidePanel";
|
||||||
import { userContext } from "../../../UserContext";
|
import { userContext } from "../../../UserContext";
|
||||||
import * as TableConstants from "../../Tables/Constants";
|
import * as TableConstants from "../../Tables/Constants";
|
||||||
import * as DataTableUtilities from "../../Tables/DataTable/DataTableUtilities";
|
import * as DataTableUtilities from "../../Tables/DataTable/DataTableUtilities";
|
||||||
@@ -14,7 +14,7 @@ import * as Entities from "../../Tables/Entities";
|
|||||||
import { CassandraAPIDataClient, TableDataClient } from "../../Tables/TableDataClient";
|
import { CassandraAPIDataClient, TableDataClient } from "../../Tables/TableDataClient";
|
||||||
import * as TableEntityProcessor from "../../Tables/TableEntityProcessor";
|
import * as TableEntityProcessor from "../../Tables/TableEntityProcessor";
|
||||||
import QueryTablesTab from "../../Tabs/QueryTablesTab";
|
import QueryTablesTab from "../../Tabs/QueryTablesTab";
|
||||||
import { RightPaneForm, RightPaneFormProps } from "../RightPaneForm/RightPaneForm";
|
import { PanelContainerComponent } from "../PanelContainerComponent";
|
||||||
import {
|
import {
|
||||||
attributeNameLabel,
|
attributeNameLabel,
|
||||||
attributeValueLabel,
|
attributeValueLabel,
|
||||||
@@ -29,6 +29,7 @@ import {
|
|||||||
getEntityValuePlaceholder,
|
getEntityValuePlaceholder,
|
||||||
getFormattedTime,
|
getFormattedTime,
|
||||||
imageProps,
|
imageProps,
|
||||||
|
isValidEntities,
|
||||||
options,
|
options,
|
||||||
} from "./Validators/EntityTableHelper";
|
} from "./Validators/EntityTableHelper";
|
||||||
|
|
||||||
@@ -58,13 +59,12 @@ export const EditTableEntityPanel: FunctionComponent<EditTableEntityPanelProps>
|
|||||||
tableEntityListViewModel,
|
tableEntityListViewModel,
|
||||||
cassandraApiClient,
|
cassandraApiClient,
|
||||||
}: EditTableEntityPanelProps): JSX.Element => {
|
}: EditTableEntityPanelProps): JSX.Element => {
|
||||||
|
const closeSidePanel = useSidePanel((state) => state.closeSidePanel);
|
||||||
const [entities, setEntities] = useState<EntityRowType[]>([]);
|
const [entities, setEntities] = useState<EntityRowType[]>([]);
|
||||||
const [selectedRow, setSelectedRow] = useState<number>(0);
|
const [selectedRow, setSelectedRow] = useState<number>(0);
|
||||||
const [entityAttributeValue, setEntityAttributeValue] = useState<string>("");
|
const [entityAttributeValue, setEntityAttributeValue] = useState<string>("");
|
||||||
const [originalDocument, setOriginalDocument] = useState<Entities.ITableEntity>({});
|
const [originalDocument, setOriginalDocument] = useState<Entities.ITableEntity>({});
|
||||||
const [entityAttributeProperty, setEntityAttributeProperty] = useState<string>("");
|
const [entityAttributeProperty, setEntityAttributeProperty] = useState<string>("");
|
||||||
const [formError, setFormError] = useState<string>("");
|
|
||||||
const [isExecuting, setIsExecuting] = useState<boolean>(false);
|
|
||||||
|
|
||||||
const [
|
const [
|
||||||
isEntityValuePanelOpen,
|
isEntityValuePanelOpen,
|
||||||
@@ -190,44 +190,26 @@ export const EditTableEntityPanel: FunctionComponent<EditTableEntityPanelProps>
|
|||||||
return displayValue;
|
return displayValue;
|
||||||
};
|
};
|
||||||
|
|
||||||
const onSubmit = async (): Promise<void> => {
|
const submit = async (event: React.FormEvent<HTMLInputElement>): Promise<void> => {
|
||||||
for (let i = 0; i < entities.length; i++) {
|
if (!isValidEntities(entities)) {
|
||||||
const { property, type } = entities[i];
|
return undefined;
|
||||||
if (property === "" || property === undefined) {
|
|
||||||
setFormError(`Property name cannot be empty. Please enter a property name`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!type) {
|
|
||||||
setFormError(`Property type cannot be empty. Please select a type from the dropdown for property ${property}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
event.preventDefault();
|
||||||
setIsExecuting(true);
|
|
||||||
const entity: Entities.ITableEntity = entityFromAttributes(entities);
|
const entity: Entities.ITableEntity = entityFromAttributes(entities);
|
||||||
const newTableDataClient = userContext.apiType === "Cassandra" ? cassandraApiClient : tableDataClient;
|
const newTableDataClient = userContext.apiType === "Cassandra" ? cassandraApiClient : tableDataClient;
|
||||||
const originalDocumentData = userContext.apiType === "Cassandra" ? originalDocument[0] : originalDocument;
|
const originalDocumentData = userContext.apiType === "Cassandra" ? originalDocument[0] : originalDocument;
|
||||||
|
const newEntity: Entities.ITableEntity = await newTableDataClient.updateDocument(
|
||||||
try {
|
queryTablesTab.collection,
|
||||||
const newEntity: Entities.ITableEntity = await newTableDataClient.updateDocument(
|
originalDocumentData,
|
||||||
queryTablesTab.collection,
|
entity
|
||||||
originalDocumentData,
|
);
|
||||||
entity
|
await tableEntityListViewModel.updateCachedEntity(newEntity);
|
||||||
);
|
if (!tryInsertNewHeaders(tableEntityListViewModel, newEntity)) {
|
||||||
await tableEntityListViewModel.updateCachedEntity(newEntity);
|
tableEntityListViewModel.redrawTableThrottled();
|
||||||
if (!tryInsertNewHeaders(tableEntityListViewModel, newEntity)) {
|
|
||||||
tableEntityListViewModel.redrawTableThrottled();
|
|
||||||
}
|
|
||||||
tableEntityListViewModel.selected.removeAll();
|
|
||||||
tableEntityListViewModel.selected.push(newEntity);
|
|
||||||
} catch (error) {
|
|
||||||
const errorMessage = getErrorMessage(error);
|
|
||||||
handleError(errorMessage, "EditTableRow");
|
|
||||||
throw error;
|
|
||||||
} finally {
|
|
||||||
setIsExecuting(false);
|
|
||||||
}
|
}
|
||||||
|
tableEntityListViewModel.selected.removeAll();
|
||||||
|
tableEntityListViewModel.selected.push(newEntity);
|
||||||
|
closeSidePanel();
|
||||||
};
|
};
|
||||||
|
|
||||||
const tryInsertNewHeaders = (viewModel: TableEntityListViewModel, newEntity: Entities.ITableEntity): boolean => {
|
const tryInsertNewHeaders = (viewModel: TableEntityListViewModel, newEntity: Entities.ITableEntity): boolean => {
|
||||||
@@ -317,81 +299,109 @@ export const EditTableEntityPanel: FunctionComponent<EditTableEntityPanelProps>
|
|||||||
setIsEntityValuePanelTrue();
|
setIsEntityValuePanelTrue();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const renderPanelContent = (): JSX.Element => {
|
||||||
|
return (
|
||||||
|
<form className="panelFormWrapper">
|
||||||
|
<div className="panelFormWrapper">
|
||||||
|
<div className="panelMainContent">
|
||||||
|
{entities.map((entity, index) => {
|
||||||
|
return (
|
||||||
|
<TableEntity
|
||||||
|
key={"" + entity.id + index}
|
||||||
|
isDeleteOptionVisible={entity.isDeleteOptionVisible}
|
||||||
|
entityTypeLabel={index === 0 && dataTypeLabel}
|
||||||
|
entityPropertyLabel={index === 0 && attributeNameLabel}
|
||||||
|
entityValueLabel={index === 0 && attributeValueLabel}
|
||||||
|
options={userContext.apiType === "Cassandra" ? cassandraOptions : options}
|
||||||
|
isPropertyTypeDisable={entity.isPropertyTypeDisable}
|
||||||
|
entityProperty={entity.property}
|
||||||
|
selectedKey={entity.type}
|
||||||
|
entityPropertyPlaceHolder={detailedHelp}
|
||||||
|
entityValuePlaceholder={entity.entityValuePlaceholder}
|
||||||
|
entityValue={entity.value?.toString()}
|
||||||
|
isEntityTypeDate={entity.isEntityTypeDate}
|
||||||
|
entityTimeValue={entity.entityTimeValue}
|
||||||
|
isEntityValueDisable={entity.isEntityValueDisable}
|
||||||
|
onEditEntity={() => editEntity(index)}
|
||||||
|
onSelectDate={(date: Date) => {
|
||||||
|
entityChange(date, index, "value");
|
||||||
|
}}
|
||||||
|
onDeleteEntity={() => deleteEntityAtIndex(index)}
|
||||||
|
onEntityPropertyChange={(event, newInput?: string) => {
|
||||||
|
entityChange(newInput, index, "property");
|
||||||
|
}}
|
||||||
|
onEntityTypeChange={(event: React.FormEvent<HTMLDivElement>, selectedParam: IDropdownOption) => {
|
||||||
|
entityTypeChange(event, selectedParam, index);
|
||||||
|
}}
|
||||||
|
onEntityValueChange={(event, newInput?: string) => {
|
||||||
|
entityChange(newInput, index, "value");
|
||||||
|
}}
|
||||||
|
onEntityTimeValueChange={(event, newInput?: string) => {
|
||||||
|
entityChange(newInput, index, "time");
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{userContext.apiType !== "Cassandra" && (
|
||||||
|
<Stack horizontal onClick={addNewEntity} className="addButtonEntiy">
|
||||||
|
<Image {...imageProps} src={AddPropertyIcon} alt="Add Entity" />
|
||||||
|
<Text className="addNewParamStyle">{getAddButtonLabel(userContext.apiType)}</Text>
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{renderPanelFooter()}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderPanelFooter = (): JSX.Element => {
|
||||||
|
return (
|
||||||
|
<div className="paneFooter">
|
||||||
|
<div className="leftpanel-okbut">
|
||||||
|
<input type="submit" onClick={submit} className="genericPaneSubmitBtn" value="Update Entity" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onRenderNavigationContent: IRenderFunction<IPanelProps> = () => (
|
||||||
|
<Stack horizontal {...columnProps}>
|
||||||
|
<Image {...backImageProps} src={RevertBackIcon} alt="back" onClick={() => setIsEntityValuePanelFalse()} />
|
||||||
|
<Label>{entityAttributeProperty}</Label>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
if (isEntityValuePanelOpen) {
|
if (isEntityValuePanelOpen) {
|
||||||
return (
|
return (
|
||||||
<Stack style={{ padding: "20px 34px" }}>
|
<PanelContainerComponent
|
||||||
<Stack horizontal {...columnProps}>
|
headerText=""
|
||||||
<Image {...backImageProps} src={RevertBackIcon} alt="back" onClick={() => setIsEntityValuePanelFalse()} />
|
onRenderNavigationContent={onRenderNavigationContent}
|
||||||
<Label>{entityAttributeProperty}</Label>
|
panelWidth="700px"
|
||||||
</Stack>
|
isOpen={true}
|
||||||
<TextField
|
panelContent={
|
||||||
multiline
|
<TextField
|
||||||
rows={5}
|
multiline
|
||||||
value={entityAttributeValue}
|
rows={5}
|
||||||
onChange={(event, newInput?: string) => {
|
className="entityValueTextField"
|
||||||
setEntityAttributeValue(newInput);
|
value={entityAttributeValue}
|
||||||
entityChange(newInput, selectedRow, "value");
|
onChange={(event, newInput?: string) => {
|
||||||
}}
|
setEntityAttributeValue(newInput);
|
||||||
/>
|
entityChange(newInput, selectedRow, "value");
|
||||||
</Stack>
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
isConsoleExpanded={false}
|
||||||
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const props: RightPaneFormProps = {
|
|
||||||
formError,
|
|
||||||
isExecuting,
|
|
||||||
submitButtonText: "Update",
|
|
||||||
onSubmit,
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<RightPaneForm {...props}>
|
<PanelContainerComponent
|
||||||
<div className="panelMainContent">
|
headerText="Edit Table Entity"
|
||||||
{entities.map((entity, index) => {
|
panelWidth="700px"
|
||||||
return (
|
isOpen={true}
|
||||||
<TableEntity
|
panelContent={renderPanelContent()}
|
||||||
key={"" + entity.id + index}
|
isConsoleExpanded={false}
|
||||||
isDeleteOptionVisible={entity.isDeleteOptionVisible}
|
/>
|
||||||
entityTypeLabel={index === 0 && dataTypeLabel}
|
|
||||||
entityPropertyLabel={index === 0 && attributeNameLabel}
|
|
||||||
entityValueLabel={index === 0 && attributeValueLabel}
|
|
||||||
options={userContext.apiType === "Cassandra" ? cassandraOptions : options}
|
|
||||||
isPropertyTypeDisable={entity.isPropertyTypeDisable}
|
|
||||||
entityProperty={entity.property}
|
|
||||||
selectedKey={entity.type}
|
|
||||||
entityPropertyPlaceHolder={detailedHelp}
|
|
||||||
entityValuePlaceholder={entity.entityValuePlaceholder}
|
|
||||||
entityValue={entity.value?.toString()}
|
|
||||||
isEntityTypeDate={entity.isEntityTypeDate}
|
|
||||||
entityTimeValue={entity.entityTimeValue}
|
|
||||||
isEntityValueDisable={entity.isEntityValueDisable}
|
|
||||||
onEditEntity={() => editEntity(index)}
|
|
||||||
onSelectDate={(date: Date) => {
|
|
||||||
entityChange(date, index, "value");
|
|
||||||
}}
|
|
||||||
onDeleteEntity={() => deleteEntityAtIndex(index)}
|
|
||||||
onEntityPropertyChange={(event, newInput?: string) => {
|
|
||||||
entityChange(newInput, index, "property");
|
|
||||||
}}
|
|
||||||
onEntityTypeChange={(event: React.FormEvent<HTMLDivElement>, selectedParam: IDropdownOption) => {
|
|
||||||
entityTypeChange(event, selectedParam, index);
|
|
||||||
}}
|
|
||||||
onEntityValueChange={(event, newInput?: string) => {
|
|
||||||
entityChange(newInput, index, "value");
|
|
||||||
}}
|
|
||||||
onEntityTimeValueChange={(event, newInput?: string) => {
|
|
||||||
entityChange(newInput, index, "time");
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{userContext.apiType !== "Cassandra" && (
|
|
||||||
<Stack horizontal onClick={addNewEntity} className="addButtonEntiy">
|
|
||||||
<Image {...imageProps} src={AddPropertyIcon} alt="Add Entity" />
|
|
||||||
<Text className="addNewParamStyle">{getAddButtonLabel(userContext.apiType)}</Text>
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</RightPaneForm>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ export const int64Placeholder = "Enter a signed 64-bit integer, in the range (-2
|
|||||||
|
|
||||||
export const columnProps: Partial<IStackProps> = {
|
export const columnProps: Partial<IStackProps> = {
|
||||||
tokens: { childrenGap: 10 },
|
tokens: { childrenGap: 10 },
|
||||||
styles: { root: { marginBottom: 8 } },
|
styles: { root: { width: 680 } },
|
||||||
};
|
};
|
||||||
|
|
||||||
// helper functions
|
// helper functions
|
||||||
@@ -134,8 +134,8 @@ export const getEntityValuePlaceholder = (entityType: string | number): string =
|
|||||||
|
|
||||||
export const isValidEntities = (entities: EntityRowType[]): boolean => {
|
export const isValidEntities = (entities: EntityRowType[]): boolean => {
|
||||||
for (let i = 0; i < entities.length; i++) {
|
for (let i = 0; i < entities.length; i++) {
|
||||||
const { property, type } = entities[i];
|
const { property } = entities[i];
|
||||||
if (property === "" || property === undefined || !type) {
|
if (property === "" || property === undefined) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -170,6 +170,13 @@ export const getDefaultEntities = (headers: string[], entityTypes: EntityType):
|
|||||||
return defaultEntities;
|
return defaultEntities;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getPanelTitle = (apiType: string): string => {
|
||||||
|
if (apiType === "Cassandra") {
|
||||||
|
return "Add Table Row";
|
||||||
|
}
|
||||||
|
return "Add Table Row";
|
||||||
|
};
|
||||||
|
|
||||||
export const getAddButtonLabel = (apiType: string): string => {
|
export const getAddButtonLabel = (apiType: string): string => {
|
||||||
if (apiType === "Cassandra") {
|
if (apiType === "Cassandra") {
|
||||||
return "Add Row";
|
return "Add Row";
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,145 +0,0 @@
|
|||||||
import { extractPartitionKey, PartitionKeyDefinition } from "@azure/cosmos";
|
|
||||||
import { IColumn, IImageProps, ImageFit } from "@fluentui/react";
|
|
||||||
import { Resource } from "../../../src/Contracts/DataModels";
|
|
||||||
import * as DataModels from "../../Contracts/DataModels";
|
|
||||||
import DocumentId from "../Tree/DocumentId";
|
|
||||||
|
|
||||||
export interface IDocumentsTabContentState {
|
|
||||||
columns: IColumn[];
|
|
||||||
isModalSelection: boolean;
|
|
||||||
isCompactMode: boolean;
|
|
||||||
announcedMessage?: string;
|
|
||||||
isSuggestionVisible: boolean;
|
|
||||||
filter: string;
|
|
||||||
isFilterOptionVisible: boolean;
|
|
||||||
isEditorVisible: boolean;
|
|
||||||
documentContent: string;
|
|
||||||
selectedSqlDocumentContent: string;
|
|
||||||
documentIds: Array<DocumentId>;
|
|
||||||
documentSqlIds: Array<Resource>;
|
|
||||||
selectedDocumentId?: DocumentId;
|
|
||||||
selectedSqlDocumentId?: DocumentId;
|
|
||||||
isEditorContentEdited: boolean;
|
|
||||||
isAllDocumentsVisible: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IDocument {
|
|
||||||
value: string;
|
|
||||||
id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IButton {
|
|
||||||
visible: boolean;
|
|
||||||
enabled: boolean;
|
|
||||||
isSelected?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const imageProps: Partial<IImageProps> = {
|
|
||||||
imageFit: ImageFit.centerContain,
|
|
||||||
width: 40,
|
|
||||||
height: 40,
|
|
||||||
style: { marginTop: "15px" },
|
|
||||||
};
|
|
||||||
|
|
||||||
export function hasShardKeySpecified(
|
|
||||||
document: string,
|
|
||||||
partitionKey: DataModels.PartitionKey,
|
|
||||||
partitionKeyProperty: string
|
|
||||||
): boolean {
|
|
||||||
return Boolean(
|
|
||||||
extractPartitionKey(
|
|
||||||
document,
|
|
||||||
getPartitionKeyDefinition(partitionKey, partitionKeyProperty) as PartitionKeyDefinition
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getPartitionKeyDefinition(
|
|
||||||
partitionKey: DataModels.PartitionKey,
|
|
||||||
partitionKeyProperty: string
|
|
||||||
): DataModels.PartitionKey {
|
|
||||||
if (partitionKey?.paths?.[0]?.indexOf("$v") > -1) {
|
|
||||||
// Convert BsonSchema2 to /path format
|
|
||||||
partitionKey = {
|
|
||||||
kind: partitionKey.kind,
|
|
||||||
paths: ["/" + partitionKeyProperty.replace(/\./g, "/")],
|
|
||||||
version: partitionKey.version,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return partitionKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatDocumentContent(row: DocumentId): string {
|
|
||||||
const { partitionKeyProperty, partitionKeyValue, id } = row;
|
|
||||||
const documentContent = JSON.stringify({
|
|
||||||
_id: id(),
|
|
||||||
[partitionKeyProperty]: partitionKeyValue || "",
|
|
||||||
});
|
|
||||||
const formattedDocumentContent = documentContent.replace(/,/g, ",\n").replace("{", "{\n").replace("}", "\n}");
|
|
||||||
return formattedDocumentContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatSqlDocumentContent(row: Resource): string {
|
|
||||||
const { id, _rid, _self, _ts, _etag, _partitionKey, _attachments } = row;
|
|
||||||
const documentContent = JSON.stringify({
|
|
||||||
id: id || "",
|
|
||||||
_rid: _rid || "",
|
|
||||||
_self: _self || "",
|
|
||||||
_ts: _ts || "",
|
|
||||||
_etag: _etag || "",
|
|
||||||
_attachments: _attachments || "",
|
|
||||||
_partitionKey: _partitionKey || "",
|
|
||||||
});
|
|
||||||
const formattedDocumentContent = documentContent.replace(/,/g, ",\n").replace("{", "{\n").replace("}", "\n}");
|
|
||||||
return formattedDocumentContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFilterPlaceholder(isPreferredApiMongoDB: boolean): string {
|
|
||||||
const filterPlaceholder = isPreferredApiMongoDB
|
|
||||||
? "Type a query predicate (e.g., {´a´:´foo´}), or choose one from the drop down list, or leave empty to query all documents."
|
|
||||||
: "Type a query predicate (e.g., WHERE c.id=´1´), or choose one from the drop down list, or leave empty to query all documents.";
|
|
||||||
return filterPlaceholder;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFilterSuggestions(isPreferredApiMongoDB: boolean): { value: string }[] {
|
|
||||||
const filterSuggestions = isPreferredApiMongoDB
|
|
||||||
? [{ value: `{"_id": "foo"}` }, { value: "{ qty: { $gte: 20 } }" }]
|
|
||||||
: [
|
|
||||||
{ value: 'WHERE c.id = "foo"' },
|
|
||||||
{ value: "ORDER BY c._ts DESC" },
|
|
||||||
{ value: 'WHERE c.id = "foo" ORDER BY c._ts DESC' },
|
|
||||||
];
|
|
||||||
return filterSuggestions;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getDocumentItems(
|
|
||||||
isPreferredApiMongoDB: boolean,
|
|
||||||
documentIds: Array<DocumentId>,
|
|
||||||
documentSqlIds: Array<Resource>,
|
|
||||||
isAllDocumentsVisible: boolean
|
|
||||||
): Array<DocumentId> | Array<Resource> {
|
|
||||||
if (isPreferredApiMongoDB) {
|
|
||||||
return isAllDocumentsVisible ? documentIds : documentIds.slice(0, 5);
|
|
||||||
}
|
|
||||||
return isAllDocumentsVisible ? documentSqlIds : documentSqlIds.slice(0, 5);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const assignTabButtonVisibility = (
|
|
||||||
visible: boolean,
|
|
||||||
enabled: boolean
|
|
||||||
): { visible: boolean; enabled: boolean } => {
|
|
||||||
return {
|
|
||||||
visible,
|
|
||||||
enabled,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getfilterText = (isPreferredApiMongoDB: boolean, filter: string): string => {
|
|
||||||
if (isPreferredApiMongoDB) {
|
|
||||||
if (filter) {
|
|
||||||
return `Filter : ${filter}`;
|
|
||||||
}
|
|
||||||
return "No filter applied";
|
|
||||||
}
|
|
||||||
return `Select * from C ${filter}`;
|
|
||||||
};
|
|
||||||
221
src/Explorer/Tabs/DocumentsTab.html
Normal file
221
src/Explorer/Tabs/DocumentsTab.html
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
<div
|
||||||
|
class="tab-pane active tabdocuments flexContainer"
|
||||||
|
data-bind="
|
||||||
|
setTemplateReady: true,
|
||||||
|
attr:{
|
||||||
|
id: tabId
|
||||||
|
},
|
||||||
|
visible: isActive"
|
||||||
|
role="tabpanel"
|
||||||
|
>
|
||||||
|
<!-- ko if: false -->
|
||||||
|
<!-- Messagebox Ok Cancel- Start -->
|
||||||
|
<div class="messagebox-background">
|
||||||
|
<div class="messagebox">
|
||||||
|
<h2 class="messagebox-title">Title</h2>
|
||||||
|
<div class="messagebox-text" tabindex="0">Text</div>
|
||||||
|
<div class="messagebox-buttons">
|
||||||
|
<div class="messagebox-buttons-container">
|
||||||
|
<button value="ok" class="messagebox-button-primary">Ok</button>
|
||||||
|
<button value="cancel" class="messagebox-button-default">Cancel</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- Messagebox OK Cancel - End -->
|
||||||
|
<!-- /ko -->
|
||||||
|
|
||||||
|
<!-- Filter - Start -->
|
||||||
|
<div class="filterdivs" data-bind="visible: isFilterCreated">
|
||||||
|
<!-- Read-only Filter - Start -->
|
||||||
|
<div class="filterDocCollapsed" data-bind="visible: !isFilterExpanded() && !isPreferredApiMongoDB">
|
||||||
|
<span class="selectQuery">SELECT * FROM c</span>
|
||||||
|
<span class="appliedQuery" data-bind="text: appliedFilter"></span>
|
||||||
|
<button class="filterbtnstyle queryButton" data-bind="click: onShowFilterClick">Edit Filter</button>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="filterDocCollapsed"
|
||||||
|
data-bind="
|
||||||
|
visible: !isFilterExpanded() && isPreferredApiMongoDB"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="selectQuery"
|
||||||
|
data-bind="
|
||||||
|
visible: appliedFilter().length > 0"
|
||||||
|
>Filter :
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="noFilterApplied"
|
||||||
|
data-bind="
|
||||||
|
visible: !appliedFilter().length > 0"
|
||||||
|
>No filter applied</span
|
||||||
|
>
|
||||||
|
<span class="appliedQuery" data-bind="text: appliedFilter"></span>
|
||||||
|
<button
|
||||||
|
class="filterbtnstyle queryButton"
|
||||||
|
data-bind="
|
||||||
|
click: onShowFilterClick"
|
||||||
|
>
|
||||||
|
Edit Filter
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<!-- Read-only Filter - End -->
|
||||||
|
|
||||||
|
<!-- Editable Filter - start -->
|
||||||
|
<div
|
||||||
|
class="filterDocExpanded"
|
||||||
|
data-bind="
|
||||||
|
visible: isFilterExpanded"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div class="editFilterContainer">
|
||||||
|
<span class="filterspan" data-bind="visible: !isPreferredApiMongoDB"> SELECT * FROM c </span>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
list="filtersList"
|
||||||
|
class="querydropdown"
|
||||||
|
title="Type a query predicate or choose one from the list."
|
||||||
|
data-bind="
|
||||||
|
attr:{
|
||||||
|
placeholder:isPreferredApiMongoDB?'Type a query predicate (e.g., {´a´:´foo´}), or choose one from the drop down list, or leave empty to query all documents.':'Type a query predicate (e.g., WHERE c.id=´1´), or choose one from the drop down list, or leave empty to query all documents.'
|
||||||
|
},
|
||||||
|
css: { placeholderVisible: filterContent().length === 0 },
|
||||||
|
textInput: filterContent"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<datalist
|
||||||
|
id="filtersList"
|
||||||
|
data-bind="
|
||||||
|
foreach: lastFilterContents"
|
||||||
|
>
|
||||||
|
<option
|
||||||
|
data-bind="
|
||||||
|
value: $data"
|
||||||
|
></option>
|
||||||
|
</datalist>
|
||||||
|
|
||||||
|
<span class="filterbuttonpad">
|
||||||
|
<button
|
||||||
|
class="filterbtnstyle queryButton"
|
||||||
|
data-bind="
|
||||||
|
click: refreshDocumentsGrid,
|
||||||
|
enable: applyFilterButton.enabled"
|
||||||
|
aria-label="Apply filter"
|
||||||
|
tabindex="0"
|
||||||
|
>
|
||||||
|
Apply Filter
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="filterclose"
|
||||||
|
role="button"
|
||||||
|
aria-label="close filter"
|
||||||
|
tabindex="0"
|
||||||
|
data-bind="
|
||||||
|
click: onHideFilterClick, event: { keydown: onCloseButtonKeyDown }"
|
||||||
|
>
|
||||||
|
<img src="/close-black.svg" style="height: 14px; width: 14px" alt="Hide filter" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- Editable Filter - End -->
|
||||||
|
</div>
|
||||||
|
<!-- Filter - End -->
|
||||||
|
|
||||||
|
<!-- Ids and Editor - Start -->
|
||||||
|
<div class="documentsTabGridAndEditor">
|
||||||
|
<div class="documentsContainerWithSplitter" , data-bind="attr: { id: documentContentsContainerId }">
|
||||||
|
<div class="flexContainer">
|
||||||
|
<!-- Document Ids - Start -->
|
||||||
|
<div
|
||||||
|
class="documentsGridHeaderContainer tabdocuments scrollable"
|
||||||
|
data-bind="
|
||||||
|
attr: {
|
||||||
|
id: documentContentsGridId,
|
||||||
|
tabindex: documentIds().length <= 0 ? -1 : 0
|
||||||
|
},
|
||||||
|
style: { height: dataContentsGridScrollHeight },
|
||||||
|
event: { keydown: accessibleDocumentList.onKeyDown }"
|
||||||
|
>
|
||||||
|
<table id="tabsTable" class="table table-hover can-select dataTable">
|
||||||
|
<thead id="theadcontent">
|
||||||
|
<tr>
|
||||||
|
<th class="documentsGridHeader" data-bind="text: idHeader" tabindex="0"></th>
|
||||||
|
<!-- ko if: showPartitionKey -->
|
||||||
|
<th
|
||||||
|
class="documentsGridHeader documentsGridPartition evenlySpacedHeader"
|
||||||
|
data-bind="
|
||||||
|
attr: {
|
||||||
|
title: partitionKeyPropertyHeader
|
||||||
|
},
|
||||||
|
text: partitionKeyPropertyHeader"
|
||||||
|
tabindex="0"
|
||||||
|
></th>
|
||||||
|
<!-- /ko -->
|
||||||
|
<th
|
||||||
|
class="refreshColHeader"
|
||||||
|
role="button"
|
||||||
|
aria-label="Refresh documents"
|
||||||
|
data-bind="event: { keydown: onRefreshButtonKeyDown }"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
class="refreshcol"
|
||||||
|
src="/refresh-cosmos.svg"
|
||||||
|
data-bind="click: refreshDocumentsGrid"
|
||||||
|
alt="Refresh documents"
|
||||||
|
tabindex="0"
|
||||||
|
/>
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="tbodycontent">
|
||||||
|
<!-- ko foreach: documentIds -->
|
||||||
|
<tr
|
||||||
|
class="pointer accessibleListElement"
|
||||||
|
data-bind="
|
||||||
|
click: $data.click,
|
||||||
|
css: {
|
||||||
|
gridRowSelected: $parent.selectedDocumentId && $parent.selectedDocumentId() && $parent.selectedDocumentId().rid === $data.rid,
|
||||||
|
gridRowHighlighted: $parent.accessibleDocumentList.currentItem() && $parent.accessibleDocumentList.currentItem().rid === $data.rid
|
||||||
|
}"
|
||||||
|
tabindex="0"
|
||||||
|
>
|
||||||
|
<td class="tabdocumentsGridElement"><a data-bind="text: $data.id, attr: { title: $data.id }"></a></td>
|
||||||
|
<!-- ko if: $data.partitionKeyProperty -->
|
||||||
|
<td class="tabdocumentsGridElement" colspan="2">
|
||||||
|
<a
|
||||||
|
data-bind="text: $data.stringPartitionKeyValue, attr: { title: $data.stringPartitionKeyValue }"
|
||||||
|
></a>
|
||||||
|
</td>
|
||||||
|
<!-- /ko -->
|
||||||
|
</tr>
|
||||||
|
<!-- /ko -->
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="loadMore">
|
||||||
|
<a role="button" data-bind="click: loadNextPage, event: { keypress: onLoadMoreKeyInput }" tabindex="0"
|
||||||
|
>Load more</a
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<!-- Document Ids - End -->
|
||||||
|
<!-- Splitter -->
|
||||||
|
</div>
|
||||||
|
<div class="splitter ui-resizable-handle ui-resizable-e colResizePointer" id="h_splitter2"></div>
|
||||||
|
</div>
|
||||||
|
<div class="documentWaterMark" data-bind="visible: !shouldShowEditor()">
|
||||||
|
<p><img src="/DocumentWaterMark.svg" alt="Document WaterMark" /></p>
|
||||||
|
<p class="documentWaterMarkText">Create new or work with existing document(s).</p>
|
||||||
|
</div>
|
||||||
|
<!-- Editor - Start -->
|
||||||
|
<json-editor
|
||||||
|
class="editorDivContent"
|
||||||
|
data-bind="visible: shouldShowEditor, css: { mongoDocumentEditor: isPreferredApiMongoDB }"
|
||||||
|
params="{content: initialDocumentContent, isReadOnly: false,lineNumbers: 'on',ariaLabel: 'Document editor',
|
||||||
|
updatedContent: selectedDocumentContent}"
|
||||||
|
></json-editor>
|
||||||
|
<!-- Editor - End -->
|
||||||
|
</div>
|
||||||
|
<!-- Ids and Editor - End -->
|
||||||
|
</div>
|
||||||
152
src/Explorer/Tabs/DocumentsTab.test.ts
Normal file
152
src/Explorer/Tabs/DocumentsTab.test.ts
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
import * as ko from "knockout";
|
||||||
|
import { DatabaseAccount } from "../../Contracts/DataModels";
|
||||||
|
import * as ViewModels from "../../Contracts/ViewModels";
|
||||||
|
import { updateUserContext } from "../../UserContext";
|
||||||
|
import Explorer from "../Explorer";
|
||||||
|
import DocumentId from "../Tree/DocumentId";
|
||||||
|
import DocumentsTab from "./DocumentsTab";
|
||||||
|
|
||||||
|
describe("Documents tab", () => {
|
||||||
|
describe("buildQuery", () => {
|
||||||
|
it("should generate the right select query for SQL API", () => {
|
||||||
|
const documentsTab = new DocumentsTab({
|
||||||
|
partitionKey: null,
|
||||||
|
documentIds: ko.observableArray<DocumentId>(),
|
||||||
|
tabKind: ViewModels.CollectionTabKind.Documents,
|
||||||
|
title: "",
|
||||||
|
tabPath: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(documentsTab.buildQuery("")).toContain("select");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("showPartitionKey", () => {
|
||||||
|
const explorer = new Explorer();
|
||||||
|
const mongoExplorer = new Explorer();
|
||||||
|
updateUserContext({
|
||||||
|
databaseAccount: {
|
||||||
|
properties: {
|
||||||
|
capabilities: [{ name: "EnableGremlin" }],
|
||||||
|
},
|
||||||
|
} as DatabaseAccount,
|
||||||
|
});
|
||||||
|
|
||||||
|
const collectionWithoutPartitionKey = <ViewModels.Collection>(<unknown>{
|
||||||
|
id: ko.observable<string>("foo"),
|
||||||
|
database: {
|
||||||
|
id: ko.observable<string>("foo"),
|
||||||
|
},
|
||||||
|
container: explorer,
|
||||||
|
});
|
||||||
|
|
||||||
|
const collectionWithSystemPartitionKey = <ViewModels.Collection>(<unknown>{
|
||||||
|
id: ko.observable<string>("foo"),
|
||||||
|
database: {
|
||||||
|
id: ko.observable<string>("foo"),
|
||||||
|
},
|
||||||
|
partitionKey: {
|
||||||
|
paths: ["/foo"],
|
||||||
|
kind: "Hash",
|
||||||
|
version: 2,
|
||||||
|
systemKey: true,
|
||||||
|
},
|
||||||
|
container: explorer,
|
||||||
|
});
|
||||||
|
|
||||||
|
const collectionWithNonSystemPartitionKey = <ViewModels.Collection>(<unknown>{
|
||||||
|
id: ko.observable<string>("foo"),
|
||||||
|
database: {
|
||||||
|
id: ko.observable<string>("foo"),
|
||||||
|
},
|
||||||
|
partitionKey: {
|
||||||
|
paths: ["/foo"],
|
||||||
|
kind: "Hash",
|
||||||
|
version: 2,
|
||||||
|
systemKey: false,
|
||||||
|
},
|
||||||
|
container: explorer,
|
||||||
|
});
|
||||||
|
|
||||||
|
const mongoCollectionWithSystemPartitionKey = <ViewModels.Collection>(<unknown>{
|
||||||
|
id: ko.observable<string>("foo"),
|
||||||
|
database: {
|
||||||
|
id: ko.observable<string>("foo"),
|
||||||
|
},
|
||||||
|
partitionKey: {
|
||||||
|
paths: ["/foo"],
|
||||||
|
kind: "Hash",
|
||||||
|
version: 2,
|
||||||
|
systemKey: true,
|
||||||
|
},
|
||||||
|
container: mongoExplorer,
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be false for null or undefined collection", () => {
|
||||||
|
const documentsTab = new DocumentsTab({
|
||||||
|
partitionKey: null,
|
||||||
|
documentIds: ko.observableArray<DocumentId>(),
|
||||||
|
tabKind: ViewModels.CollectionTabKind.Documents,
|
||||||
|
title: "",
|
||||||
|
tabPath: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(documentsTab.showPartitionKey).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be false for null or undefined partitionKey", () => {
|
||||||
|
const documentsTab = new DocumentsTab({
|
||||||
|
collection: collectionWithoutPartitionKey,
|
||||||
|
partitionKey: null,
|
||||||
|
documentIds: ko.observableArray<DocumentId>(),
|
||||||
|
tabKind: ViewModels.CollectionTabKind.Documents,
|
||||||
|
title: "",
|
||||||
|
tabPath: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(documentsTab.showPartitionKey).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be true for non-Mongo accounts with system partitionKey", () => {
|
||||||
|
const documentsTab = new DocumentsTab({
|
||||||
|
collection: collectionWithSystemPartitionKey,
|
||||||
|
partitionKey: null,
|
||||||
|
documentIds: ko.observableArray<DocumentId>(),
|
||||||
|
tabKind: ViewModels.CollectionTabKind.Documents,
|
||||||
|
title: "",
|
||||||
|
tabPath: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(documentsTab.showPartitionKey).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be false for Mongo accounts with system partitionKey", () => {
|
||||||
|
updateUserContext({
|
||||||
|
apiType: "Mongo",
|
||||||
|
});
|
||||||
|
const documentsTab = new DocumentsTab({
|
||||||
|
collection: mongoCollectionWithSystemPartitionKey,
|
||||||
|
partitionKey: null,
|
||||||
|
documentIds: ko.observableArray<DocumentId>(),
|
||||||
|
tabKind: ViewModels.CollectionTabKind.Documents,
|
||||||
|
title: "",
|
||||||
|
tabPath: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(documentsTab.showPartitionKey).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be true for non-system partitionKey", () => {
|
||||||
|
const documentsTab = new DocumentsTab({
|
||||||
|
collection: collectionWithNonSystemPartitionKey,
|
||||||
|
partitionKey: null,
|
||||||
|
documentIds: ko.observableArray<DocumentId>(),
|
||||||
|
tabKind: ViewModels.CollectionTabKind.Documents,
|
||||||
|
title: "",
|
||||||
|
tabPath: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(documentsTab.showPartitionKey).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
924
src/Explorer/Tabs/DocumentsTab.ts
Normal file
924
src/Explorer/Tabs/DocumentsTab.ts
Normal file
@@ -0,0 +1,924 @@
|
|||||||
|
import { extractPartitionKey, ItemDefinition, PartitionKeyDefinition, QueryIterator, Resource } from "@azure/cosmos";
|
||||||
|
import * as ko from "knockout";
|
||||||
|
import Q from "q";
|
||||||
|
import DeleteDocumentIcon from "../../../images/DeleteDocument.svg";
|
||||||
|
import DiscardIcon from "../../../images/discard.svg";
|
||||||
|
import NewDocumentIcon from "../../../images/NewDocument.svg";
|
||||||
|
import SaveIcon from "../../../images/save-cosmos.svg";
|
||||||
|
import UploadIcon from "../../../images/Upload_16x16.svg";
|
||||||
|
import * as Constants from "../../Common/Constants";
|
||||||
|
import { DocumentsGridMetrics, KeyCodes } from "../../Common/Constants";
|
||||||
|
import { createDocument } from "../../Common/dataAccess/createDocument";
|
||||||
|
import { deleteDocument } from "../../Common/dataAccess/deleteDocument";
|
||||||
|
import { queryDocuments } from "../../Common/dataAccess/queryDocuments";
|
||||||
|
import { readDocument } from "../../Common/dataAccess/readDocument";
|
||||||
|
import { updateDocument } from "../../Common/dataAccess/updateDocument";
|
||||||
|
import editable from "../../Common/EditableUtility";
|
||||||
|
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
|
||||||
|
import * as HeadersUtility from "../../Common/HeadersUtility";
|
||||||
|
import { Splitter, SplitterBounds, SplitterDirection } from "../../Common/Splitter";
|
||||||
|
import * as DataModels from "../../Contracts/DataModels";
|
||||||
|
import * as ViewModels from "../../Contracts/ViewModels";
|
||||||
|
import { Action } from "../../Shared/Telemetry/TelemetryConstants";
|
||||||
|
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
||||||
|
import { userContext } from "../../UserContext";
|
||||||
|
import { logConsoleError } from "../../Utils/NotificationConsoleUtils";
|
||||||
|
import * as QueryUtils from "../../Utils/QueryUtils";
|
||||||
|
import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent";
|
||||||
|
import Explorer from "../Explorer";
|
||||||
|
import { AccessibleVerticalList } from "../Tree/AccessibleVerticalList";
|
||||||
|
import DocumentId from "../Tree/DocumentId";
|
||||||
|
import { useSelectedNode } from "../useSelectedNode";
|
||||||
|
import template from "./DocumentsTab.html";
|
||||||
|
import TabsBase from "./TabsBase";
|
||||||
|
|
||||||
|
export default class DocumentsTab extends TabsBase {
|
||||||
|
public readonly html = template;
|
||||||
|
public selectedDocumentId: ko.Observable<DocumentId>;
|
||||||
|
public selectedDocumentContent: ViewModels.Editable<string>;
|
||||||
|
public initialDocumentContent: ko.Observable<string>;
|
||||||
|
public documentContentsGridId: string;
|
||||||
|
public documentContentsContainerId: string;
|
||||||
|
public filterContent: ko.Observable<string>;
|
||||||
|
public appliedFilter: ko.Observable<string>;
|
||||||
|
public lastFilterContents: ko.ObservableArray<string>;
|
||||||
|
public isFilterExpanded: ko.Observable<boolean>;
|
||||||
|
public isFilterCreated: ko.Observable<boolean>;
|
||||||
|
public applyFilterButton: ViewModels.Button;
|
||||||
|
public isEditorDirty: ko.Computed<boolean>;
|
||||||
|
public editorState: ko.Observable<ViewModels.DocumentExplorerState>;
|
||||||
|
public newDocumentButton: ViewModels.Button;
|
||||||
|
public saveNewDocumentButton: ViewModels.Button;
|
||||||
|
public saveExisitingDocumentButton: ViewModels.Button;
|
||||||
|
public discardNewDocumentChangesButton: ViewModels.Button;
|
||||||
|
public discardExisitingDocumentChangesButton: ViewModels.Button;
|
||||||
|
public deleteExisitingDocumentButton: ViewModels.Button;
|
||||||
|
public displayedError: ko.Observable<string>;
|
||||||
|
public accessibleDocumentList: AccessibleVerticalList;
|
||||||
|
public dataContentsGridScrollHeight: ko.Observable<string>;
|
||||||
|
public isPreferredApiMongoDB: boolean;
|
||||||
|
public shouldShowEditor: ko.Computed<boolean>;
|
||||||
|
public splitter: Splitter;
|
||||||
|
public showPartitionKey: boolean;
|
||||||
|
public idHeader: string;
|
||||||
|
|
||||||
|
// TODO need to refactor
|
||||||
|
public partitionKey: DataModels.PartitionKey;
|
||||||
|
public partitionKeyPropertyHeader: string;
|
||||||
|
public partitionKeyProperty: string;
|
||||||
|
public documentIds: ko.ObservableArray<DocumentId>;
|
||||||
|
|
||||||
|
private _documentsIterator: QueryIterator<ItemDefinition & Resource>;
|
||||||
|
private _resourceTokenPartitionKey: string;
|
||||||
|
|
||||||
|
constructor(options: ViewModels.DocumentsTabOptions) {
|
||||||
|
super(options);
|
||||||
|
this.isPreferredApiMongoDB = userContext.apiType === "Mongo" || options.isPreferredApiMongoDB;
|
||||||
|
|
||||||
|
this.idHeader = this.isPreferredApiMongoDB ? "_id" : "id";
|
||||||
|
|
||||||
|
this.documentContentsGridId = `documentContentsGrid${this.tabId}`;
|
||||||
|
this.documentContentsContainerId = `documentContentsContainer${this.tabId}`;
|
||||||
|
this.editorState = ko.observable<ViewModels.DocumentExplorerState>(
|
||||||
|
ViewModels.DocumentExplorerState.noDocumentSelected
|
||||||
|
);
|
||||||
|
this.selectedDocumentId = ko.observable<DocumentId>();
|
||||||
|
this.selectedDocumentContent = editable.observable<string>("");
|
||||||
|
this.initialDocumentContent = ko.observable<string>("");
|
||||||
|
this.partitionKey = options.partitionKey || (this.collection && this.collection.partitionKey);
|
||||||
|
this._resourceTokenPartitionKey = options.resourceTokenPartitionKey;
|
||||||
|
this.documentIds = options.documentIds;
|
||||||
|
|
||||||
|
this.partitionKeyPropertyHeader =
|
||||||
|
(this.collection && this.collection.partitionKeyPropertyHeader) || this._getPartitionKeyPropertyHeader();
|
||||||
|
this.partitionKeyProperty = !!this.partitionKeyPropertyHeader
|
||||||
|
? this.partitionKeyPropertyHeader.replace(/[/]+/g, ".").substr(1).replace(/[']+/g, "")
|
||||||
|
: null;
|
||||||
|
|
||||||
|
this.isFilterExpanded = ko.observable<boolean>(false);
|
||||||
|
this.isFilterCreated = ko.observable<boolean>(true);
|
||||||
|
this.filterContent = ko.observable<string>("");
|
||||||
|
this.appliedFilter = ko.observable<string>("");
|
||||||
|
this.displayedError = ko.observable<string>("");
|
||||||
|
this.lastFilterContents = ko.observableArray<string>([
|
||||||
|
'WHERE c.id = "foo"',
|
||||||
|
"ORDER BY c._ts DESC",
|
||||||
|
'WHERE c.id = "foo" ORDER BY c._ts DESC',
|
||||||
|
]);
|
||||||
|
|
||||||
|
this.dataContentsGridScrollHeight = ko.observable<string>(null);
|
||||||
|
|
||||||
|
// initialize splitter only after template has been loaded so dom elements are accessible
|
||||||
|
super.onTemplateReady((isTemplateReady: boolean) => {
|
||||||
|
if (isTemplateReady) {
|
||||||
|
const tabContainer: HTMLElement = document.getElementById("content");
|
||||||
|
const splitterBounds: SplitterBounds = {
|
||||||
|
min: Constants.DocumentsGridMetrics.DocumentEditorMinWidthRatio * tabContainer.clientWidth,
|
||||||
|
max: Constants.DocumentsGridMetrics.DocumentEditorMaxWidthRatio * tabContainer.clientWidth,
|
||||||
|
};
|
||||||
|
this.splitter = new Splitter({
|
||||||
|
splitterId: "h_splitter2",
|
||||||
|
leftId: this.documentContentsContainerId,
|
||||||
|
bounds: splitterBounds,
|
||||||
|
direction: SplitterDirection.Vertical,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.accessibleDocumentList = new AccessibleVerticalList(this.documentIds());
|
||||||
|
this.accessibleDocumentList.setOnSelect(
|
||||||
|
(selectedDocument: DocumentId) => selectedDocument && selectedDocument.click()
|
||||||
|
);
|
||||||
|
this.selectedDocumentId.subscribe((newSelectedDocumentId: DocumentId) =>
|
||||||
|
this.accessibleDocumentList.updateCurrentItem(newSelectedDocumentId)
|
||||||
|
);
|
||||||
|
this.documentIds.subscribe((newDocuments: DocumentId[]) => {
|
||||||
|
this.accessibleDocumentList.updateItemList(newDocuments);
|
||||||
|
if (newDocuments.length > 0) {
|
||||||
|
this.dataContentsGridScrollHeight(
|
||||||
|
newDocuments.length * DocumentsGridMetrics.IndividualRowHeight + DocumentsGridMetrics.BufferHeight + "px"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
this.dataContentsGridScrollHeight(
|
||||||
|
DocumentsGridMetrics.IndividualRowHeight + DocumentsGridMetrics.BufferHeight + "px"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.isEditorDirty = ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.noDocumentSelected:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentNoEdits:
|
||||||
|
return false;
|
||||||
|
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentValid:
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentInvalid:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyInvalid:
|
||||||
|
return true;
|
||||||
|
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid:
|
||||||
|
return (
|
||||||
|
this.selectedDocumentContent.getEditableOriginalValue() !==
|
||||||
|
this.selectedDocumentContent.getEditableCurrentValue()
|
||||||
|
);
|
||||||
|
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.newDocumentButton = {
|
||||||
|
enabled: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.noDocumentSelected:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentNoEdits:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
|
||||||
|
visible: ko.computed<boolean>(() => {
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.saveNewDocumentButton = {
|
||||||
|
enabled: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentValid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
|
||||||
|
visible: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentValid:
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentInvalid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.discardNewDocumentChangesButton = {
|
||||||
|
enabled: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentValid:
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentInvalid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
|
||||||
|
visible: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentValid:
|
||||||
|
case ViewModels.DocumentExplorerState.newDocumentInvalid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.saveExisitingDocumentButton = {
|
||||||
|
enabled: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
|
||||||
|
visible: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentNoEdits:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyInvalid:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.discardExisitingDocumentChangesButton = {
|
||||||
|
enabled: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyInvalid:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
|
||||||
|
visible: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentNoEdits:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyInvalid:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.deleteExisitingDocumentButton = {
|
||||||
|
enabled: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentNoEdits:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyInvalid:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
|
||||||
|
visible: ko.computed<boolean>(() => {
|
||||||
|
switch (this.editorState()) {
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentNoEdits:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyInvalid:
|
||||||
|
case ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.applyFilterButton = {
|
||||||
|
enabled: ko.computed<boolean>(() => {
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
|
||||||
|
visible: ko.computed<boolean>(() => {
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
this.buildCommandBarOptions();
|
||||||
|
this.shouldShowEditor = ko.computed<boolean>(() => {
|
||||||
|
const documentHasContent: boolean =
|
||||||
|
this.selectedDocumentContent() != null && this.selectedDocumentContent().length > 0;
|
||||||
|
const isNewDocument: boolean =
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.newDocumentValid ||
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.newDocumentInvalid;
|
||||||
|
|
||||||
|
return documentHasContent || isNewDocument;
|
||||||
|
});
|
||||||
|
this.selectedDocumentContent.subscribe((newContent: string) => this._onEditorContentChange(newContent));
|
||||||
|
|
||||||
|
this.showPartitionKey = this._shouldShowPartitionKey();
|
||||||
|
}
|
||||||
|
|
||||||
|
private _shouldShowPartitionKey(): boolean {
|
||||||
|
if (!this.collection) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.collection.partitionKey) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.collection.partitionKey.systemKey && this.isPreferredApiMongoDB) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public onShowFilterClick(): Q.Promise<any> {
|
||||||
|
this.isFilterCreated(true);
|
||||||
|
this.isFilterExpanded(true);
|
||||||
|
|
||||||
|
$(".filterDocExpanded").addClass("active");
|
||||||
|
$("#content").addClass("active");
|
||||||
|
$(".querydropdown").focus();
|
||||||
|
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
public onHideFilterClick(): Q.Promise<any> {
|
||||||
|
this.isFilterExpanded(false);
|
||||||
|
|
||||||
|
$(".filterDocExpanded").removeClass("active");
|
||||||
|
$("#content").removeClass("active");
|
||||||
|
$(".queryButton").focus();
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
public onCloseButtonKeyDown = (source: any, event: KeyboardEvent): boolean => {
|
||||||
|
if (event.keyCode === KeyCodes.Enter || event.keyCode === KeyCodes.Space) {
|
||||||
|
this.onHideFilterClick();
|
||||||
|
event.stopPropagation();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
public async refreshDocumentsGrid(): Promise<void> {
|
||||||
|
// clear documents grid
|
||||||
|
this.documentIds([]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// reset iterator
|
||||||
|
this._documentsIterator = this.createIterator();
|
||||||
|
// load documents
|
||||||
|
await this.loadNextPage();
|
||||||
|
// collapse filter
|
||||||
|
this.appliedFilter(this.filterContent());
|
||||||
|
this.isFilterExpanded(false);
|
||||||
|
document.getElementById("errorStatusIcon")?.focus();
|
||||||
|
} catch (error) {
|
||||||
|
window.alert(getErrorMessage(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public onRefreshButtonKeyDown = (source: any, event: KeyboardEvent): boolean => {
|
||||||
|
if (event.keyCode === KeyCodes.Enter || event.keyCode === KeyCodes.Space) {
|
||||||
|
this.refreshDocumentsGrid();
|
||||||
|
event.stopPropagation();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
public onDocumentIdClick(clickedDocumentId: DocumentId): Q.Promise<any> {
|
||||||
|
if (this.editorState() !== ViewModels.DocumentExplorerState.noDocumentSelected) {
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentNoEdits);
|
||||||
|
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
public onNewDocumentClick = (): Q.Promise<any> => {
|
||||||
|
if (this.isEditorDirty() && !this._isIgnoreDirtyEditor()) {
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
this.selectedDocumentId(null);
|
||||||
|
|
||||||
|
const defaultDocument: string = this.renderObjectForEditor({ id: "replace_with_new_document_id" }, null, 4);
|
||||||
|
this.initialDocumentContent(defaultDocument);
|
||||||
|
this.selectedDocumentContent.setBaseline(defaultDocument);
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.newDocumentValid);
|
||||||
|
|
||||||
|
return Q();
|
||||||
|
};
|
||||||
|
|
||||||
|
public onSaveNewDocumentClick = (): Promise<any> => {
|
||||||
|
this.isExecutionError(false);
|
||||||
|
const startKey: number = TelemetryProcessor.traceStart(Action.CreateDocument, {
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
});
|
||||||
|
const document = JSON.parse(this.selectedDocumentContent());
|
||||||
|
this.isExecuting(true);
|
||||||
|
return createDocument(this.collection, document)
|
||||||
|
.then(
|
||||||
|
(savedDocument: any) => {
|
||||||
|
const value: string = this.renderObjectForEditor(savedDocument || {}, null, 4);
|
||||||
|
this.selectedDocumentContent.setBaseline(value);
|
||||||
|
this.initialDocumentContent(value);
|
||||||
|
const partitionKeyValueArray = extractPartitionKey(
|
||||||
|
savedDocument,
|
||||||
|
this.partitionKey as PartitionKeyDefinition
|
||||||
|
);
|
||||||
|
const partitionKeyValue = partitionKeyValueArray && partitionKeyValueArray[0];
|
||||||
|
let id = new DocumentId(this, savedDocument, partitionKeyValue);
|
||||||
|
let ids = this.documentIds();
|
||||||
|
ids.push(id);
|
||||||
|
|
||||||
|
this.selectedDocumentId(id);
|
||||||
|
this.documentIds(ids);
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentNoEdits);
|
||||||
|
TelemetryProcessor.traceSuccess(
|
||||||
|
Action.CreateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
this.isExecutionError(true);
|
||||||
|
const errorMessage = getErrorMessage(error);
|
||||||
|
window.alert(errorMessage);
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.CreateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: errorMessage,
|
||||||
|
errorStack: getErrorStack(error),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.finally(() => this.isExecuting(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
public onRevertNewDocumentClick = (): Q.Promise<any> => {
|
||||||
|
this.initialDocumentContent("");
|
||||||
|
this.selectedDocumentContent("");
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.noDocumentSelected);
|
||||||
|
|
||||||
|
return Q();
|
||||||
|
};
|
||||||
|
|
||||||
|
public onSaveExisitingDocumentClick = (): Promise<any> => {
|
||||||
|
const selectedDocumentId = this.selectedDocumentId();
|
||||||
|
const documentContent = JSON.parse(this.selectedDocumentContent());
|
||||||
|
|
||||||
|
const partitionKeyValueArray = extractPartitionKey(documentContent, this.partitionKey as PartitionKeyDefinition);
|
||||||
|
const partitionKeyValue = partitionKeyValueArray && partitionKeyValueArray[0];
|
||||||
|
|
||||||
|
selectedDocumentId.partitionKeyValue = partitionKeyValue;
|
||||||
|
|
||||||
|
this.isExecutionError(false);
|
||||||
|
const startKey: number = TelemetryProcessor.traceStart(Action.UpdateDocument, {
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
});
|
||||||
|
this.isExecuting(true);
|
||||||
|
return updateDocument(this.collection, selectedDocumentId, documentContent)
|
||||||
|
.then(
|
||||||
|
(updatedDocument: any) => {
|
||||||
|
const value: string = this.renderObjectForEditor(updatedDocument || {}, null, 4);
|
||||||
|
this.selectedDocumentContent.setBaseline(value);
|
||||||
|
this.initialDocumentContent(value);
|
||||||
|
this.documentIds().forEach((documentId: DocumentId) => {
|
||||||
|
if (documentId.rid === updatedDocument._rid) {
|
||||||
|
documentId.id(updatedDocument.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentNoEdits);
|
||||||
|
TelemetryProcessor.traceSuccess(
|
||||||
|
Action.UpdateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
this.isExecutionError(true);
|
||||||
|
const errorMessage = getErrorMessage(error);
|
||||||
|
window.alert(errorMessage);
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.UpdateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: errorMessage,
|
||||||
|
errorStack: getErrorStack(error),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.finally(() => this.isExecuting(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
public onRevertExisitingDocumentClick = (): Q.Promise<any> => {
|
||||||
|
this.selectedDocumentContent.setBaseline(this.initialDocumentContent());
|
||||||
|
this.initialDocumentContent.valueHasMutated();
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentNoEdits);
|
||||||
|
|
||||||
|
return Q();
|
||||||
|
};
|
||||||
|
|
||||||
|
public onDeleteExisitingDocumentClick = async (): Promise<void> => {
|
||||||
|
const selectedDocumentId = this.selectedDocumentId();
|
||||||
|
const msg = !this.isPreferredApiMongoDB
|
||||||
|
? "Are you sure you want to delete the selected item ?"
|
||||||
|
: "Are you sure you want to delete the selected document ?";
|
||||||
|
|
||||||
|
if (window.confirm(msg)) {
|
||||||
|
await this._deleteDocument(selectedDocumentId);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public onValidDocumentEdit(): Q.Promise<any> {
|
||||||
|
if (
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.newDocumentInvalid ||
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.newDocumentValid
|
||||||
|
) {
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.newDocumentValid);
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid);
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
public onInvalidDocumentEdit(): Q.Promise<any> {
|
||||||
|
if (
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.newDocumentInvalid ||
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.newDocumentValid
|
||||||
|
) {
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.newDocumentInvalid);
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.exisitingDocumentNoEdits ||
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.exisitingDocumentDirtyValid
|
||||||
|
) {
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentDirtyInvalid);
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
public onTabClick(): void {
|
||||||
|
super.onTabClick();
|
||||||
|
this.collection && this.collection.selectedSubnodeKind(ViewModels.CollectionTabKind.Documents);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async onActivate(): Promise<void> {
|
||||||
|
super.onActivate();
|
||||||
|
|
||||||
|
if (!this._documentsIterator) {
|
||||||
|
try {
|
||||||
|
this._documentsIterator = this.createIterator();
|
||||||
|
await this.loadNextPage();
|
||||||
|
} catch (error) {
|
||||||
|
if (this.onLoadStartKey != null && this.onLoadStartKey != undefined) {
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.Tab,
|
||||||
|
{
|
||||||
|
databaseName: this.collection.databaseId,
|
||||||
|
collectionName: this.collection.id(),
|
||||||
|
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: getErrorMessage(error),
|
||||||
|
errorStack: getErrorStack(error),
|
||||||
|
},
|
||||||
|
this.onLoadStartKey
|
||||||
|
);
|
||||||
|
this.onLoadStartKey = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _isIgnoreDirtyEditor = (): boolean => {
|
||||||
|
var msg: string = "Changes will be lost. Do you want to continue?";
|
||||||
|
return window.confirm(msg);
|
||||||
|
};
|
||||||
|
|
||||||
|
protected __deleteDocument(documentId: DocumentId): Promise<void> {
|
||||||
|
return deleteDocument(this.collection, documentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _deleteDocument(selectedDocumentId: DocumentId): Promise<void> {
|
||||||
|
this.isExecutionError(false);
|
||||||
|
const startKey: number = TelemetryProcessor.traceStart(Action.DeleteDocument, {
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
});
|
||||||
|
this.isExecuting(true);
|
||||||
|
return this.__deleteDocument(selectedDocumentId)
|
||||||
|
.then(
|
||||||
|
() => {
|
||||||
|
this.documentIds.remove((documentId: DocumentId) => documentId.rid === selectedDocumentId.rid);
|
||||||
|
this.selectedDocumentContent("");
|
||||||
|
this.selectedDocumentId(null);
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.noDocumentSelected);
|
||||||
|
TelemetryProcessor.traceSuccess(
|
||||||
|
Action.DeleteDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
this.isExecutionError(true);
|
||||||
|
console.error(error);
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.DeleteDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: getErrorMessage(error),
|
||||||
|
errorStack: getErrorStack(error),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.finally(() => this.isExecuting(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
public createIterator(): QueryIterator<ItemDefinition & Resource> {
|
||||||
|
let filters = this.lastFilterContents();
|
||||||
|
const filter: string = this.filterContent().trim();
|
||||||
|
const query: string = this.buildQuery(filter);
|
||||||
|
let options: any = {};
|
||||||
|
options.enableCrossPartitionQuery = HeadersUtility.shouldEnableCrossPartitionKey();
|
||||||
|
|
||||||
|
if (this._resourceTokenPartitionKey) {
|
||||||
|
options.partitionKey = this._resourceTokenPartitionKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
return queryDocuments(this.collection.databaseId, this.collection.id(), query, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async selectDocument(documentId: DocumentId): Promise<void> {
|
||||||
|
this.selectedDocumentId(documentId);
|
||||||
|
const content = await readDocument(this.collection, documentId);
|
||||||
|
this.initDocumentEditor(documentId, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
public loadNextPage(): Q.Promise<any> {
|
||||||
|
this.isExecuting(true);
|
||||||
|
this.isExecutionError(false);
|
||||||
|
return this._loadNextPageInternal()
|
||||||
|
.then(
|
||||||
|
(documentsIdsResponse = []) => {
|
||||||
|
const currentDocuments = this.documentIds();
|
||||||
|
const currentDocumentsRids = currentDocuments.map((currentDocument) => currentDocument.rid);
|
||||||
|
const nextDocumentIds = documentsIdsResponse
|
||||||
|
// filter documents already loaded in observable
|
||||||
|
.filter((d: any) => {
|
||||||
|
return currentDocumentsRids.indexOf(d._rid) < 0;
|
||||||
|
})
|
||||||
|
// map raw response to view model
|
||||||
|
.map((rawDocument: any) => {
|
||||||
|
const partitionKeyValue = rawDocument._partitionKeyValue;
|
||||||
|
return new DocumentId(this, rawDocument, partitionKeyValue);
|
||||||
|
});
|
||||||
|
|
||||||
|
const merged = currentDocuments.concat(nextDocumentIds);
|
||||||
|
this.documentIds(merged);
|
||||||
|
if (this.onLoadStartKey != null && this.onLoadStartKey != undefined) {
|
||||||
|
TelemetryProcessor.traceSuccess(
|
||||||
|
Action.Tab,
|
||||||
|
{
|
||||||
|
databaseName: this.collection.databaseId,
|
||||||
|
collectionName: this.collection.id(),
|
||||||
|
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
},
|
||||||
|
this.onLoadStartKey
|
||||||
|
);
|
||||||
|
this.onLoadStartKey = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
this.isExecutionError(true);
|
||||||
|
const errorMessage = getErrorMessage(error);
|
||||||
|
logConsoleError(errorMessage);
|
||||||
|
if (this.onLoadStartKey != null && this.onLoadStartKey != undefined) {
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.Tab,
|
||||||
|
{
|
||||||
|
databaseName: this.collection.databaseId,
|
||||||
|
collectionName: this.collection.id(),
|
||||||
|
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: errorMessage,
|
||||||
|
errorStack: getErrorStack(error),
|
||||||
|
},
|
||||||
|
this.onLoadStartKey
|
||||||
|
);
|
||||||
|
this.onLoadStartKey = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.finally(() => this.isExecuting(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
public onLoadMoreKeyInput = (source: any, event: KeyboardEvent): void => {
|
||||||
|
if (event.key === " " || event.key === "Enter") {
|
||||||
|
const focusElement = document.getElementById(this.documentContentsGridId);
|
||||||
|
this.loadNextPage();
|
||||||
|
focusElement && focusElement.focus();
|
||||||
|
event.stopPropagation();
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected _loadNextPageInternal(): Q.Promise<DataModels.DocumentId[]> {
|
||||||
|
return Q(this._documentsIterator.fetchNext().then((response) => response.resources));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _onEditorContentChange(newContent: string) {
|
||||||
|
try {
|
||||||
|
let parsed: any = JSON.parse(newContent);
|
||||||
|
this.onValidDocumentEdit();
|
||||||
|
} catch (e) {
|
||||||
|
this.onInvalidDocumentEdit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public initDocumentEditor(documentId: DocumentId, documentContent: any): Q.Promise<any> {
|
||||||
|
if (documentId) {
|
||||||
|
const content: string = this.renderObjectForEditor(documentContent, null, 4);
|
||||||
|
this.selectedDocumentContent.setBaseline(content);
|
||||||
|
this.initialDocumentContent(content);
|
||||||
|
const newState = documentId
|
||||||
|
? ViewModels.DocumentExplorerState.exisitingDocumentNoEdits
|
||||||
|
: ViewModels.DocumentExplorerState.newDocumentValid;
|
||||||
|
this.editorState(newState);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Q();
|
||||||
|
}
|
||||||
|
|
||||||
|
public buildQuery(filter: string): string {
|
||||||
|
return QueryUtils.buildDocumentsQuery(filter, this.partitionKeyProperty, this.partitionKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getTabsButtons(): CommandButtonComponentProps[] {
|
||||||
|
const buttons: CommandButtonComponentProps[] = [];
|
||||||
|
const label = !this.isPreferredApiMongoDB ? "New Item" : "New Document";
|
||||||
|
if (this.newDocumentButton.visible()) {
|
||||||
|
buttons.push({
|
||||||
|
iconSrc: NewDocumentIcon,
|
||||||
|
iconAlt: label,
|
||||||
|
onCommandClick: this.onNewDocumentClick,
|
||||||
|
commandButtonLabel: label,
|
||||||
|
ariaLabel: label,
|
||||||
|
hasPopup: false,
|
||||||
|
disabled: !this.newDocumentButton.enabled(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.saveNewDocumentButton.visible()) {
|
||||||
|
const label = "Save";
|
||||||
|
buttons.push({
|
||||||
|
iconSrc: SaveIcon,
|
||||||
|
iconAlt: label,
|
||||||
|
onCommandClick: this.onSaveNewDocumentClick,
|
||||||
|
commandButtonLabel: label,
|
||||||
|
ariaLabel: label,
|
||||||
|
hasPopup: false,
|
||||||
|
disabled: !this.saveNewDocumentButton.enabled(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.discardNewDocumentChangesButton.visible()) {
|
||||||
|
const label = "Discard";
|
||||||
|
buttons.push({
|
||||||
|
iconSrc: DiscardIcon,
|
||||||
|
iconAlt: label,
|
||||||
|
onCommandClick: this.onRevertNewDocumentClick,
|
||||||
|
commandButtonLabel: label,
|
||||||
|
ariaLabel: label,
|
||||||
|
hasPopup: false,
|
||||||
|
disabled: !this.discardNewDocumentChangesButton.enabled(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.saveExisitingDocumentButton.visible()) {
|
||||||
|
const label = "Update";
|
||||||
|
buttons.push({
|
||||||
|
iconSrc: SaveIcon,
|
||||||
|
iconAlt: label,
|
||||||
|
onCommandClick: this.onSaveExisitingDocumentClick,
|
||||||
|
commandButtonLabel: label,
|
||||||
|
ariaLabel: label,
|
||||||
|
hasPopup: false,
|
||||||
|
disabled: !this.saveExisitingDocumentButton.enabled(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.discardExisitingDocumentChangesButton.visible()) {
|
||||||
|
const label = "Discard";
|
||||||
|
buttons.push({
|
||||||
|
iconSrc: DiscardIcon,
|
||||||
|
iconAlt: label,
|
||||||
|
onCommandClick: this.onRevertExisitingDocumentClick,
|
||||||
|
commandButtonLabel: label,
|
||||||
|
ariaLabel: label,
|
||||||
|
hasPopup: false,
|
||||||
|
disabled: !this.discardExisitingDocumentChangesButton.enabled(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.deleteExisitingDocumentButton.visible()) {
|
||||||
|
const label = "Delete";
|
||||||
|
buttons.push({
|
||||||
|
iconSrc: DeleteDocumentIcon,
|
||||||
|
iconAlt: label,
|
||||||
|
onCommandClick: this.onDeleteExisitingDocumentClick,
|
||||||
|
commandButtonLabel: label,
|
||||||
|
ariaLabel: label,
|
||||||
|
hasPopup: false,
|
||||||
|
disabled: !this.deleteExisitingDocumentButton.enabled(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.isPreferredApiMongoDB) {
|
||||||
|
buttons.push(DocumentsTab._createUploadButton(this.collection.container));
|
||||||
|
}
|
||||||
|
|
||||||
|
return buttons;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected buildCommandBarOptions(): void {
|
||||||
|
ko.computed(() =>
|
||||||
|
ko.toJSON([
|
||||||
|
this.newDocumentButton.visible,
|
||||||
|
this.newDocumentButton.enabled,
|
||||||
|
this.saveNewDocumentButton.visible,
|
||||||
|
this.saveNewDocumentButton.enabled,
|
||||||
|
this.discardNewDocumentChangesButton.visible,
|
||||||
|
this.discardNewDocumentChangesButton.enabled,
|
||||||
|
this.saveExisitingDocumentButton.visible,
|
||||||
|
this.saveExisitingDocumentButton.enabled,
|
||||||
|
this.discardExisitingDocumentChangesButton.visible,
|
||||||
|
this.discardExisitingDocumentChangesButton.enabled,
|
||||||
|
this.deleteExisitingDocumentButton.visible,
|
||||||
|
this.deleteExisitingDocumentButton.enabled,
|
||||||
|
])
|
||||||
|
).subscribe(() => this.updateNavbarWithTabsButtons());
|
||||||
|
this.updateNavbarWithTabsButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getPartitionKeyPropertyHeader(): string {
|
||||||
|
return (
|
||||||
|
(this.partitionKey &&
|
||||||
|
this.partitionKey.paths &&
|
||||||
|
this.partitionKey.paths.length > 0 &&
|
||||||
|
this.partitionKey.paths[0]) ||
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static _createUploadButton(container: Explorer): CommandButtonComponentProps {
|
||||||
|
const label = "Upload Item";
|
||||||
|
return {
|
||||||
|
iconSrc: UploadIcon,
|
||||||
|
iconAlt: label,
|
||||||
|
onCommandClick: () => {
|
||||||
|
const selectedCollection: ViewModels.Collection = useSelectedNode.getState().findSelectedCollection();
|
||||||
|
selectedCollection && container.openUploadItemsPanePane();
|
||||||
|
},
|
||||||
|
commandButtonLabel: label,
|
||||||
|
ariaLabel: label,
|
||||||
|
hasPopup: true,
|
||||||
|
disabled: useSelectedNode.getState().isDatabaseNodeOrNoneSelected(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
import * as ko from "knockout";
|
|
||||||
import React from "react";
|
|
||||||
import "react-splitter-layout/lib/index.css";
|
|
||||||
import * as DataModels from "../../Contracts/DataModels";
|
|
||||||
import * as ViewModels from "../../Contracts/ViewModels";
|
|
||||||
import DocumentsTabContent from "./DocumentsTabContent";
|
|
||||||
import TabsBase from "./TabsBase";
|
|
||||||
|
|
||||||
export default class DocumentsTab extends TabsBase {
|
|
||||||
public documentContentsGridId: string;
|
|
||||||
public documentContentsContainerId: string;
|
|
||||||
public displayedError: ko.Observable<string>;
|
|
||||||
public partitionKey: DataModels.PartitionKey;
|
|
||||||
public partitionKeyPropertyHeader: string;
|
|
||||||
public partitionKeyProperty: string;
|
|
||||||
public _resourceTokenPartitionKey: string;
|
|
||||||
|
|
||||||
constructor(options: ViewModels.DocumentsTabOptions) {
|
|
||||||
super(options);
|
|
||||||
this.documentContentsGridId = `documentContentsGrid${this.tabId}`;
|
|
||||||
this.documentContentsContainerId = `documentContentsContainer${this.tabId}`;
|
|
||||||
this.partitionKey = options.partitionKey || (this.collection && this.collection.partitionKey);
|
|
||||||
this._resourceTokenPartitionKey = options.resourceTokenPartitionKey;
|
|
||||||
|
|
||||||
this.partitionKeyPropertyHeader =
|
|
||||||
(this.collection && this.collection.partitionKeyPropertyHeader) || this._getPartitionKeyPropertyHeader();
|
|
||||||
this.partitionKeyProperty = this.partitionKeyPropertyHeader
|
|
||||||
? this.partitionKeyPropertyHeader.replace(/[/]+/g, ".").substr(1).replace(/[']+/g, "")
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
this.displayedError = ko.observable<string>("");
|
|
||||||
}
|
|
||||||
|
|
||||||
public onTabClick(): void {
|
|
||||||
super.onTabClick();
|
|
||||||
this.collection && this.collection.selectedSubnodeKind(ViewModels.CollectionTabKind.Documents);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected buildCommandBarOptions(): void {
|
|
||||||
this.updateNavbarWithTabsButtons();
|
|
||||||
}
|
|
||||||
|
|
||||||
private _getPartitionKeyPropertyHeader(): string {
|
|
||||||
return this.partitionKey?.paths?.[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
render(): JSX.Element {
|
|
||||||
return <DocumentsTabContent {...this} />;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,793 +0,0 @@
|
|||||||
import { extractPartitionKey, PartitionKeyDefinition } from "@azure/cosmos";
|
|
||||||
import {
|
|
||||||
DetailsList,
|
|
||||||
DetailsListLayoutMode,
|
|
||||||
IColumn,
|
|
||||||
IIconProps,
|
|
||||||
Image,
|
|
||||||
List,
|
|
||||||
PrimaryButton,
|
|
||||||
SelectionMode,
|
|
||||||
Stack,
|
|
||||||
Text,
|
|
||||||
TextField,
|
|
||||||
} from "@fluentui/react";
|
|
||||||
import * as React from "react";
|
|
||||||
import SplitterLayout from "react-splitter-layout";
|
|
||||||
import CloseIcon from "../../../images/close-black.svg";
|
|
||||||
import DeleteDocumentIcon from "../../../images/DeleteDocument.svg";
|
|
||||||
import DiscardIcon from "../../../images/discard.svg";
|
|
||||||
import DocumentWaterMark from "../../../images/DocumentWaterMark.svg";
|
|
||||||
import NewDocumentIcon from "../../../images/NewDocument.svg";
|
|
||||||
import SaveIcon from "../../../images/save-cosmos.svg";
|
|
||||||
import UploadIcon from "../../../images/Upload_16x16.svg";
|
|
||||||
import { Resource } from "../../../src/Contracts/DataModels";
|
|
||||||
import * as NotificationConsoleUtils from "../../../src/Utils/NotificationConsoleUtils";
|
|
||||||
import { Areas } from "../../Common/Constants";
|
|
||||||
import { createDocument as createSqlDocuments } from "../../Common/dataAccess/createDocument";
|
|
||||||
import { deleteDocument as deleteSqlDocument } from "../../Common/dataAccess/deleteDocument";
|
|
||||||
import { queryDocuments as querySqlDocuments } from "../../Common/dataAccess/queryDocuments";
|
|
||||||
import { readDocument } from "../../Common/dataAccess/readDocument";
|
|
||||||
import { updateDocument as updateSqlDocuments } from "../../Common/dataAccess/updateDocument";
|
|
||||||
import { getEntityName } from "../../Common/DocumentUtility";
|
|
||||||
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
|
|
||||||
import * as HeadersUtility from "../../Common/HeadersUtility";
|
|
||||||
import { logError } from "../../Common/Logger";
|
|
||||||
import { createDocument, deleteDocument, queryDocuments, updateDocument } from "../../Common/MongoProxyClient";
|
|
||||||
import * as ViewModels from "../../Contracts/ViewModels";
|
|
||||||
import { Action } from "../../Shared/Telemetry/TelemetryConstants";
|
|
||||||
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
|
||||||
import { userContext } from "../../UserContext";
|
|
||||||
import * as QueryUtils from "../../Utils/QueryUtils";
|
|
||||||
import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent";
|
|
||||||
import { EditorReact } from "../Controls/Editor/EditorReact";
|
|
||||||
import { useCommandBar } from "../Menus/CommandBar/CommandBarComponentAdapter";
|
|
||||||
import DocumentId from "../Tree/DocumentId";
|
|
||||||
import ObjectId from "../Tree/ObjectId";
|
|
||||||
import { useSelectedNode } from "../useSelectedNode";
|
|
||||||
import DocumentsTab from "./DocumentsTab";
|
|
||||||
import {
|
|
||||||
assignTabButtonVisibility,
|
|
||||||
formatDocumentContent,
|
|
||||||
formatSqlDocumentContent,
|
|
||||||
getDocumentItems,
|
|
||||||
getFilterPlaceholder,
|
|
||||||
getFilterSuggestions,
|
|
||||||
getfilterText,
|
|
||||||
getPartitionKeyDefinition,
|
|
||||||
hasShardKeySpecified,
|
|
||||||
IDocumentsTabContentState,
|
|
||||||
imageProps,
|
|
||||||
} from "./DocumentTabUtils";
|
|
||||||
|
|
||||||
const filterIcon: IIconProps = { iconName: "Filter" };
|
|
||||||
let newDocumentButton = assignTabButtonVisibility(true, true);
|
|
||||||
let saveNewDocumentButton = assignTabButtonVisibility(false, true);
|
|
||||||
let discardNewDocumentChangesButton = assignTabButtonVisibility(false, false);
|
|
||||||
let saveExisitingDocumentButton = assignTabButtonVisibility(false, false);
|
|
||||||
let discardExisitingDocumentChangesButton = assignTabButtonVisibility(false, false);
|
|
||||||
let deleteExisitingDocumentButton = assignTabButtonVisibility(false, false);
|
|
||||||
|
|
||||||
export default class DocumentsTabContent extends React.Component<DocumentsTab, IDocumentsTabContentState> {
|
|
||||||
public initialDocumentContent: string;
|
|
||||||
|
|
||||||
constructor(props: DocumentsTab) {
|
|
||||||
super(props);
|
|
||||||
const isPreferredApiMongoDB = userContext.apiType === "Mongo";
|
|
||||||
|
|
||||||
const columns: IColumn[] = [
|
|
||||||
{
|
|
||||||
key: "_id",
|
|
||||||
name: isPreferredApiMongoDB ? "_id" : "id",
|
|
||||||
minWidth: 50,
|
|
||||||
maxWidth: 100,
|
|
||||||
isResizable: true,
|
|
||||||
isCollapsible: true,
|
|
||||||
data: "string",
|
|
||||||
onRender: (item: DocumentId) => {
|
|
||||||
return (
|
|
||||||
<div onClick={() => this.handleRow(item)} className="documentIdItem">
|
|
||||||
{isPreferredApiMongoDB ? item.id() : item.id}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
isPadded: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "column2",
|
|
||||||
name: props.partitionKeyPropertyHeader,
|
|
||||||
minWidth: 50,
|
|
||||||
maxWidth: 100,
|
|
||||||
isResizable: true,
|
|
||||||
isCollapsible: true,
|
|
||||||
data: "number",
|
|
||||||
onRender: (item: DocumentId) => {
|
|
||||||
return (
|
|
||||||
<div onClick={() => this.handleRow(item)} className="documentIdItem">
|
|
||||||
{isPreferredApiMongoDB ? item.partitionKeyValue : item._partitionKeyValue}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
this.initialDocumentContent = `{ \n ${
|
|
||||||
isPreferredApiMongoDB ? '"_id"' : '"id"'
|
|
||||||
}: "replace_with_new_document_id" \n }`;
|
|
||||||
|
|
||||||
this.state = {
|
|
||||||
columns: columns,
|
|
||||||
isModalSelection: false,
|
|
||||||
isCompactMode: false,
|
|
||||||
announcedMessage: undefined,
|
|
||||||
isSuggestionVisible: false,
|
|
||||||
filter: "",
|
|
||||||
isFilterOptionVisible: true,
|
|
||||||
isEditorVisible: false,
|
|
||||||
documentContent: this.initialDocumentContent,
|
|
||||||
documentIds: [],
|
|
||||||
documentSqlIds: [],
|
|
||||||
isEditorContentEdited: false,
|
|
||||||
isAllDocumentsVisible: false,
|
|
||||||
selectedSqlDocumentContent: this.initialDocumentContent,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
componentDidMount(): void {
|
|
||||||
this.props.isExecuting(true);
|
|
||||||
this.updateTabButton();
|
|
||||||
if (userContext.apiType === "Mongo") {
|
|
||||||
this.queryDocumentsData();
|
|
||||||
} else {
|
|
||||||
this.querySqlDocumentsData();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public buildQuery(filter: string): string {
|
|
||||||
return QueryUtils.buildDocumentsQuery(filter, this.props.partitionKeyProperty, this.props.partitionKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
private querySqlDocumentsData = async (): Promise<void> => {
|
|
||||||
this.props.isExecuting(true);
|
|
||||||
this.props.isExecutionError(false);
|
|
||||||
const { filter } = this.state;
|
|
||||||
const query: string = this.buildQuery(filter);
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const options: any = {};
|
|
||||||
options.enableCrossPartitionQuery = HeadersUtility.shouldEnableCrossPartitionKey();
|
|
||||||
if (this.props._resourceTokenPartitionKey) {
|
|
||||||
options.partitionKey = this.props._resourceTokenPartitionKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const sqlQuery = querySqlDocuments(this.props.collection.databaseId, this.props.collection.id(), query, options);
|
|
||||||
const querySqlDocumentsData = await sqlQuery.fetchNext();
|
|
||||||
this.setState({ documentSqlIds: querySqlDocumentsData.resources?.length ? querySqlDocumentsData.resources : [] });
|
|
||||||
} catch (error) {
|
|
||||||
this.props.isExecutionError(true);
|
|
||||||
const errorMessage = getErrorMessage(error);
|
|
||||||
NotificationConsoleUtils.logConsoleError(errorMessage);
|
|
||||||
} finally {
|
|
||||||
this.props.isExecuting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
private queryDocumentsData = async (): Promise<void> => {
|
|
||||||
this.props.isExecuting(true);
|
|
||||||
this.props.isExecutionError(false);
|
|
||||||
try {
|
|
||||||
const { filter } = this.state;
|
|
||||||
const query: string = filter || "{}";
|
|
||||||
const queryDocumentsData = await queryDocuments(
|
|
||||||
this.props.collection.databaseId,
|
|
||||||
this.props.collection as ViewModels.Collection,
|
|
||||||
true,
|
|
||||||
query,
|
|
||||||
undefined
|
|
||||||
);
|
|
||||||
if (queryDocumentsData) {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const nextDocumentIds = queryDocumentsData.documents.map((rawDocument: any) => {
|
|
||||||
const partitionKeyValue = rawDocument._partitionKeyValue;
|
|
||||||
return new DocumentId(this.props as DocumentsTab, rawDocument, partitionKeyValue);
|
|
||||||
});
|
|
||||||
this.setState({ documentIds: nextDocumentIds });
|
|
||||||
}
|
|
||||||
if (this.props.onLoadStartKey !== undefined) {
|
|
||||||
TelemetryProcessor.traceSuccess(
|
|
||||||
Action.Tab,
|
|
||||||
{
|
|
||||||
databaseName: this.props.collection.databaseId,
|
|
||||||
collectionName: this.props.collection.id(),
|
|
||||||
dataExplorerArea: Areas.Tab,
|
|
||||||
tabTitle: this.props.tabTitle(),
|
|
||||||
},
|
|
||||||
this.props.onLoadStartKey
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (this.props.onLoadStartKey !== undefined) {
|
|
||||||
TelemetryProcessor.traceFailure(
|
|
||||||
Action.Tab,
|
|
||||||
{
|
|
||||||
databaseName: this.props.collection.databaseId,
|
|
||||||
collectionName: this.props.collection.id(),
|
|
||||||
dataExplorerArea: Areas.Tab,
|
|
||||||
tabTitle: this.props.tabTitle(),
|
|
||||||
error: getErrorMessage(error),
|
|
||||||
errorStack: getErrorStack(error),
|
|
||||||
},
|
|
||||||
this.props.onLoadStartKey
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
this.props.isExecuting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
private handleRow = (row: DocumentId | Resource): void => {
|
|
||||||
if (this.state.isEditorContentEdited) {
|
|
||||||
this.props.collection.container.showOkCancelModalDialog(
|
|
||||||
"Are you sure you want to continue?",
|
|
||||||
"Your unsaved changes will be lost.",
|
|
||||||
"Okay",
|
|
||||||
() => {
|
|
||||||
this.handleRowContent(row);
|
|
||||||
this.setState({ isEditorContentEdited: false });
|
|
||||||
return;
|
|
||||||
},
|
|
||||||
"Cancel",
|
|
||||||
undefined
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
this.handleRowContent(row);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
private handleRowContent = (row: DocumentId | Resource): void => {
|
|
||||||
userContext.apiType === "Mongo"
|
|
||||||
? this.updateContent(row as DocumentId, formatDocumentContent(row as DocumentId))
|
|
||||||
: this.updateSqlContent(row as Resource);
|
|
||||||
this.setDefaultUpdateTabButtonVisibility();
|
|
||||||
};
|
|
||||||
|
|
||||||
private updateContent = (row: DocumentId, formattedDocumentContent: string): void => {
|
|
||||||
this.setState(
|
|
||||||
{
|
|
||||||
documentContent: formattedDocumentContent,
|
|
||||||
isEditorVisible: true,
|
|
||||||
selectedDocumentId: row,
|
|
||||||
},
|
|
||||||
() => {
|
|
||||||
this.updateTabButton();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
private updateSqlContent = async (row: Resource): Promise<void> => {
|
|
||||||
const selectedDocumentId: DocumentId = new DocumentId(this.props as DocumentsTab, row, row._partitionKeyValue);
|
|
||||||
|
|
||||||
const content = await readDocument(this.props.collection, selectedDocumentId);
|
|
||||||
const formattedDocumentContent = formatSqlDocumentContent((content as unknown) as Resource);
|
|
||||||
this.setState(
|
|
||||||
{
|
|
||||||
documentContent: formattedDocumentContent,
|
|
||||||
isEditorVisible: true,
|
|
||||||
selectedSqlDocumentContent: formattedDocumentContent,
|
|
||||||
selectedSqlDocumentId: selectedDocumentId,
|
|
||||||
},
|
|
||||||
() => {
|
|
||||||
this.updateTabButton();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
private handleFilter = (): void => {
|
|
||||||
userContext.apiType === "Mongo" ? this.queryDocumentsData() : this.querySqlDocumentsData();
|
|
||||||
this.setState({
|
|
||||||
isSuggestionVisible: false,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
async updateSqlDocument(): Promise<void> {
|
|
||||||
const { isExecutionError, isExecuting, collection } = this.props;
|
|
||||||
const { documentContent, selectedSqlDocumentId } = this.state;
|
|
||||||
isExecutionError(false);
|
|
||||||
const startKey: number = this.getStartKey(Action.UpdateDocument);
|
|
||||||
try {
|
|
||||||
isExecuting(true);
|
|
||||||
const updateSqlDocumentRes = await updateSqlDocuments(
|
|
||||||
collection as ViewModels.Collection,
|
|
||||||
selectedSqlDocumentId,
|
|
||||||
JSON.parse(documentContent)
|
|
||||||
);
|
|
||||||
if (updateSqlDocumentRes) {
|
|
||||||
this.setTraceSuccess(Action.UpdateDocument, startKey);
|
|
||||||
this.querySqlDocumentsData();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
NotificationConsoleUtils.logConsoleError(getErrorMessage(error));
|
|
||||||
this.setTraceFail(Action.UpdateDocument, startKey, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async updateMongoDocument(): Promise<void> {
|
|
||||||
const { selectedDocumentId, documentContent, documentIds } = this.state;
|
|
||||||
const { isExecutionError, isExecuting, collection, partitionKey, partitionKeyProperty } = this.props;
|
|
||||||
isExecutionError(false);
|
|
||||||
isExecuting(true);
|
|
||||||
const startKey: number = this.getStartKey(Action.UpdateDocument);
|
|
||||||
try {
|
|
||||||
const updatedDocument = await updateDocument(
|
|
||||||
collection.databaseId,
|
|
||||||
collection as ViewModels.Collection,
|
|
||||||
selectedDocumentId,
|
|
||||||
documentContent
|
|
||||||
);
|
|
||||||
|
|
||||||
documentIds.forEach((documentId: DocumentId) => {
|
|
||||||
if (documentId.rid === updatedDocument._rid) {
|
|
||||||
const partitionKeyArray = extractPartitionKey(
|
|
||||||
updatedDocument,
|
|
||||||
getPartitionKeyDefinition(partitionKey, partitionKeyProperty) as PartitionKeyDefinition
|
|
||||||
);
|
|
||||||
const partitionKeyValue = partitionKeyArray && partitionKeyArray[0];
|
|
||||||
const id = new ObjectId(this.props as DocumentsTab, updatedDocument, partitionKeyValue);
|
|
||||||
documentId.id(id.id());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
this.setTraceSuccess(Action.UpdateDocument, startKey);
|
|
||||||
this.setState({ isEditorContentEdited: false });
|
|
||||||
} catch (error) {
|
|
||||||
NotificationConsoleUtils.logConsoleError(getErrorMessage(error));
|
|
||||||
this.setTraceFail(Action.UpdateDocument, startKey, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected getTabsButtons(): CommandButtonComponentProps[] {
|
|
||||||
const buttons: CommandButtonComponentProps[] = [];
|
|
||||||
const label = `New ${getEntityName()}`;
|
|
||||||
if (newDocumentButton.visible) {
|
|
||||||
buttons.push({
|
|
||||||
iconSrc: NewDocumentIcon,
|
|
||||||
iconAlt: label,
|
|
||||||
onCommandClick: this.onNewDocumentClick,
|
|
||||||
commandButtonLabel: label,
|
|
||||||
ariaLabel: label,
|
|
||||||
hasPopup: false,
|
|
||||||
disabled: !newDocumentButton.enabled,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (saveNewDocumentButton.visible) {
|
|
||||||
const label = "Save";
|
|
||||||
buttons.push({
|
|
||||||
iconSrc: SaveIcon,
|
|
||||||
iconAlt: label,
|
|
||||||
onCommandClick: this.onSaveNewDocumentClick,
|
|
||||||
commandButtonLabel: label,
|
|
||||||
ariaLabel: label,
|
|
||||||
hasPopup: false,
|
|
||||||
disabled: !saveNewDocumentButton.enabled,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (discardNewDocumentChangesButton.visible) {
|
|
||||||
const label = "Discard";
|
|
||||||
buttons.push({
|
|
||||||
iconSrc: DiscardIcon,
|
|
||||||
iconAlt: label,
|
|
||||||
onCommandClick: this.onRevertNewDocumentClick,
|
|
||||||
commandButtonLabel: label,
|
|
||||||
ariaLabel: label,
|
|
||||||
hasPopup: false,
|
|
||||||
disabled: !discardNewDocumentChangesButton.enabled,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (saveExisitingDocumentButton.visible) {
|
|
||||||
const label = "Update";
|
|
||||||
buttons.push({
|
|
||||||
...this,
|
|
||||||
updateMongoDocument: this.updateMongoDocument,
|
|
||||||
updateSqlDocument: this.updateSqlDocument,
|
|
||||||
setState: this.setState,
|
|
||||||
iconSrc: SaveIcon,
|
|
||||||
iconAlt: label,
|
|
||||||
onCommandClick: this.onSaveExisitingDocumentClick,
|
|
||||||
commandButtonLabel: label,
|
|
||||||
ariaLabel: label,
|
|
||||||
hasPopup: false,
|
|
||||||
disabled: !saveExisitingDocumentButton.enabled,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (discardExisitingDocumentChangesButton.visible) {
|
|
||||||
const label = "Discard";
|
|
||||||
buttons.push({
|
|
||||||
...this,
|
|
||||||
setState: this.setState,
|
|
||||||
iconSrc: DiscardIcon,
|
|
||||||
iconAlt: label,
|
|
||||||
onCommandClick: this.onRevertExisitingDocumentClick,
|
|
||||||
commandButtonLabel: label,
|
|
||||||
ariaLabel: label,
|
|
||||||
hasPopup: false,
|
|
||||||
disabled: !discardExisitingDocumentChangesButton.enabled,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (deleteExisitingDocumentButton.visible) {
|
|
||||||
const label = "Delete";
|
|
||||||
buttons.push({
|
|
||||||
...this,
|
|
||||||
setState: this.setState,
|
|
||||||
iconSrc: DeleteDocumentIcon,
|
|
||||||
iconAlt: label,
|
|
||||||
onCommandClick: this.onDeleteExisitingDocumentClick,
|
|
||||||
commandButtonLabel: label,
|
|
||||||
ariaLabel: label,
|
|
||||||
hasPopup: false,
|
|
||||||
disabled: !deleteExisitingDocumentButton.enabled,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (userContext.apiType !== "Mongo") {
|
|
||||||
const { collection } = this.props;
|
|
||||||
const label = "Upload Item";
|
|
||||||
buttons.push({
|
|
||||||
iconSrc: UploadIcon,
|
|
||||||
iconAlt: label,
|
|
||||||
onCommandClick: () => {
|
|
||||||
const selectedCollection: ViewModels.Collection = useSelectedNode.getState().findSelectedCollection();
|
|
||||||
selectedCollection && collection.container.openUploadItemsPanePane();
|
|
||||||
},
|
|
||||||
commandButtonLabel: label,
|
|
||||||
ariaLabel: label,
|
|
||||||
hasPopup: true,
|
|
||||||
disabled: useSelectedNode.getState().isDatabaseNodeOrNoneSelected(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return buttons;
|
|
||||||
}
|
|
||||||
|
|
||||||
private onSaveExisitingDocumentClick(): void {
|
|
||||||
userContext.apiType === "Mongo" ? this.updateMongoDocument() : this.updateSqlDocument();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async onDeleteExisitingDocumentClick(): Promise<void> {
|
|
||||||
const confirmationMessage = `Are you sure you want to delete the selected ${getEntityName()} ?`;
|
|
||||||
const { isExecuting, collection } = this.props;
|
|
||||||
const startKey: number = this.getStartKey(Action.DeleteDocument);
|
|
||||||
this.props.collection.container.showOkCancelModalDialog(
|
|
||||||
confirmationMessage,
|
|
||||||
`This ${getEntityName()} will be deleted immediately. You can't undo this action`,
|
|
||||||
"Delete",
|
|
||||||
async () => {
|
|
||||||
try {
|
|
||||||
isExecuting(true);
|
|
||||||
if (userContext.apiType === "Mongo") {
|
|
||||||
await deleteDocument(
|
|
||||||
collection.databaseId,
|
|
||||||
collection as ViewModels.Collection,
|
|
||||||
this.state.selectedDocumentId
|
|
||||||
);
|
|
||||||
this.queryDocumentsData();
|
|
||||||
} else {
|
|
||||||
const { selectedSqlDocumentId } = this.state;
|
|
||||||
await deleteSqlDocument(collection as ViewModels.Collection, selectedSqlDocumentId);
|
|
||||||
this.querySqlDocumentsData();
|
|
||||||
}
|
|
||||||
this.setTraceSuccess(Action.DeleteDocument, startKey);
|
|
||||||
this.setState({ isEditorVisible: false });
|
|
||||||
} catch (error) {
|
|
||||||
this.setTraceFail(Action.DeleteDocument, startKey, error);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"Cancel",
|
|
||||||
undefined
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private onRevertExisitingDocumentClick(): void {
|
|
||||||
const { selectedDocumentId, selectedSqlDocumentContent } = this.state;
|
|
||||||
const documentContent =
|
|
||||||
userContext.apiType === "Mongo" ? formatDocumentContent(selectedDocumentId) : selectedSqlDocumentContent;
|
|
||||||
this.setState({
|
|
||||||
documentContent: documentContent,
|
|
||||||
});
|
|
||||||
discardExisitingDocumentChangesButton = assignTabButtonVisibility(true, false);
|
|
||||||
saveExisitingDocumentButton = assignTabButtonVisibility(true, false);
|
|
||||||
this.updateTabButton();
|
|
||||||
}
|
|
||||||
|
|
||||||
private onNewDocumentClick = () => {
|
|
||||||
newDocumentButton = assignTabButtonVisibility(true, false);
|
|
||||||
saveNewDocumentButton = assignTabButtonVisibility(true, true);
|
|
||||||
discardNewDocumentChangesButton = assignTabButtonVisibility(true, true);
|
|
||||||
saveExisitingDocumentButton = assignTabButtonVisibility(false, false);
|
|
||||||
discardExisitingDocumentChangesButton = assignTabButtonVisibility(false, false);
|
|
||||||
deleteExisitingDocumentButton = assignTabButtonVisibility(false, false);
|
|
||||||
|
|
||||||
this.updateTabButton();
|
|
||||||
this.setState({
|
|
||||||
documentContent: this.initialDocumentContent,
|
|
||||||
isEditorVisible: true,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
private onSaveNewDocumentClick = () => {
|
|
||||||
if (userContext.apiType === "Mongo") {
|
|
||||||
this.onSaveNewMongoDocumentClick();
|
|
||||||
} else {
|
|
||||||
this.onSaveSqlNewMongoDocumentClick();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
public onSaveSqlNewMongoDocumentClick = async (): Promise<void> => {
|
|
||||||
const { isExecutionError, isExecuting, collection } = this.props;
|
|
||||||
isExecutionError(false);
|
|
||||||
const startKey: number = this.getStartKey(Action.CreateDocument);
|
|
||||||
const document = JSON.parse(this.state.documentContent);
|
|
||||||
isExecuting(true);
|
|
||||||
try {
|
|
||||||
const savedDocument = await createSqlDocuments(collection, document);
|
|
||||||
if (savedDocument) {
|
|
||||||
const formattedDocumentContent = formatSqlDocumentContent((savedDocument as unknown) as Resource);
|
|
||||||
this.setState({ documentContent: formattedDocumentContent });
|
|
||||||
this.setDefaultUpdateTabButtonVisibility();
|
|
||||||
this.setTraceSuccess(Action.CreateDocument, startKey);
|
|
||||||
}
|
|
||||||
this.querySqlDocumentsData();
|
|
||||||
} catch (error) {
|
|
||||||
NotificationConsoleUtils.logConsoleError(getErrorMessage(error));
|
|
||||||
this.setTraceFail(Action.CreateDocument, startKey, error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
private setDefaultUpdateTabButtonVisibility = (): void => {
|
|
||||||
newDocumentButton = assignTabButtonVisibility(true, true);
|
|
||||||
saveNewDocumentButton = assignTabButtonVisibility(false, false);
|
|
||||||
discardNewDocumentChangesButton = assignTabButtonVisibility(false, false);
|
|
||||||
saveExisitingDocumentButton = assignTabButtonVisibility(true, false);
|
|
||||||
discardExisitingDocumentChangesButton = assignTabButtonVisibility(true, false);
|
|
||||||
deleteExisitingDocumentButton = assignTabButtonVisibility(true, true);
|
|
||||||
this.updateTabButton();
|
|
||||||
};
|
|
||||||
|
|
||||||
public onSaveNewMongoDocumentClick = async (): Promise<void> => {
|
|
||||||
const parsedDocumentContent = JSON.parse(this.state.documentContent);
|
|
||||||
const {
|
|
||||||
partitionKey,
|
|
||||||
partitionKeyProperty,
|
|
||||||
displayedError,
|
|
||||||
isExecutionError,
|
|
||||||
isExecuting,
|
|
||||||
collection,
|
|
||||||
} = this.props;
|
|
||||||
displayedError("");
|
|
||||||
const startKey: number = this.getStartKey(Action.CreateDocument);
|
|
||||||
if (
|
|
||||||
partitionKeyProperty &&
|
|
||||||
partitionKeyProperty !== "_id" &&
|
|
||||||
!hasShardKeySpecified(parsedDocumentContent, partitionKey, partitionKeyProperty)
|
|
||||||
) {
|
|
||||||
const message = `The document is lacking the shard property: ${partitionKeyProperty}`;
|
|
||||||
displayedError(message);
|
|
||||||
this.setTraceFail(Action.CreateDocument, startKey, message);
|
|
||||||
logError("Failed to save new document: Document shard key not defined", "MongoDocumentsTab");
|
|
||||||
throw new Error("Document without shard key");
|
|
||||||
}
|
|
||||||
isExecutionError(false);
|
|
||||||
isExecuting(true);
|
|
||||||
try {
|
|
||||||
const savedDocument = await createDocument(
|
|
||||||
collection.databaseId,
|
|
||||||
collection as ViewModels.Collection,
|
|
||||||
partitionKeyProperty,
|
|
||||||
parsedDocumentContent
|
|
||||||
);
|
|
||||||
if (savedDocument) {
|
|
||||||
this.handleLoadMoreDocument();
|
|
||||||
this.setDefaultUpdateTabButtonVisibility();
|
|
||||||
this.setTraceSuccess(Action.CreateDocument, startKey);
|
|
||||||
}
|
|
||||||
this.setState({ isEditorContentEdited: false });
|
|
||||||
this.queryDocumentsData();
|
|
||||||
} catch (error) {
|
|
||||||
window.alert(getErrorMessage(error));
|
|
||||||
this.setTraceFail(Action.CreateDocument, startKey, error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
private getStartKey = (action: number): number => {
|
|
||||||
const startKey: number = TelemetryProcessor.traceStart(action, {
|
|
||||||
dataExplorerArea: Areas.Tab,
|
|
||||||
tabTitle: this.props.tabTitle(),
|
|
||||||
});
|
|
||||||
return startKey;
|
|
||||||
};
|
|
||||||
|
|
||||||
private setTraceSuccess = (action: number, startKey: number): void => {
|
|
||||||
const { isExecuting, tabTitle } = this.props;
|
|
||||||
TelemetryProcessor.traceSuccess(
|
|
||||||
action,
|
|
||||||
{
|
|
||||||
dataExplorerArea: Areas.Tab,
|
|
||||||
tabTitle: tabTitle(),
|
|
||||||
},
|
|
||||||
startKey
|
|
||||||
);
|
|
||||||
isExecuting(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
private setTraceFail = (action: number, startKey: number, error: Error | string): void => {
|
|
||||||
const { isExecuting, tabTitle, isExecutionError } = this.props;
|
|
||||||
TelemetryProcessor.traceFailure(
|
|
||||||
action,
|
|
||||||
{
|
|
||||||
dataExplorerArea: Areas.Tab,
|
|
||||||
tabTitle: tabTitle(),
|
|
||||||
error: getErrorMessage(error),
|
|
||||||
errorStack: getErrorStack(error),
|
|
||||||
},
|
|
||||||
startKey
|
|
||||||
);
|
|
||||||
isExecuting(false);
|
|
||||||
isExecutionError(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
private onRevertNewDocumentClick = () => {
|
|
||||||
newDocumentButton = assignTabButtonVisibility(true, true);
|
|
||||||
saveNewDocumentButton = assignTabButtonVisibility(true, false);
|
|
||||||
discardNewDocumentChangesButton = assignTabButtonVisibility(true, false);
|
|
||||||
|
|
||||||
this.updateTabButton();
|
|
||||||
this.setState({
|
|
||||||
isEditorVisible: false,
|
|
||||||
isEditorContentEdited: false,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
private onRenderCell = (item: { value: string }): JSX.Element => {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className="documentTabSuggestions"
|
|
||||||
onClick={() =>
|
|
||||||
this.setState({
|
|
||||||
filter: item.value,
|
|
||||||
isSuggestionVisible: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Text>{item.value}</Text>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
private handleLoadMoreDocument = (): void => {
|
|
||||||
userContext.apiType === "Mongo" ? this.queryDocumentsData() : this.querySqlDocumentsData();
|
|
||||||
this.setState({
|
|
||||||
isSuggestionVisible: false,
|
|
||||||
isAllDocumentsVisible: true,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
private updateTabButton = (): void => {
|
|
||||||
useCommandBar.getState().setContextButtons(this.getTabsButtons());
|
|
||||||
};
|
|
||||||
|
|
||||||
private getKey(item: DocumentId): string {
|
|
||||||
return item.rid;
|
|
||||||
}
|
|
||||||
|
|
||||||
private handleDocumentContentChange = (newContent: string): void => {
|
|
||||||
if (saveExisitingDocumentButton.visible && newContent !== this.state.documentContent) {
|
|
||||||
saveExisitingDocumentButton = assignTabButtonVisibility(true, true);
|
|
||||||
discardExisitingDocumentChangesButton = assignTabButtonVisibility(true, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.setState(
|
|
||||||
{
|
|
||||||
documentContent: newContent,
|
|
||||||
isEditorContentEdited: true,
|
|
||||||
},
|
|
||||||
() => {
|
|
||||||
this.updateTabButton();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
public render(): JSX.Element {
|
|
||||||
const {
|
|
||||||
columns,
|
|
||||||
isCompactMode,
|
|
||||||
isSuggestionVisible,
|
|
||||||
filter,
|
|
||||||
isFilterOptionVisible,
|
|
||||||
isEditorVisible,
|
|
||||||
documentContent,
|
|
||||||
documentIds,
|
|
||||||
documentSqlIds,
|
|
||||||
isAllDocumentsVisible,
|
|
||||||
} = this.state;
|
|
||||||
const isPreferredApiMongoDB = userContext.apiType === "Mongo";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{isFilterOptionVisible && (
|
|
||||||
<>
|
|
||||||
<div>
|
|
||||||
<Stack horizontal verticalFill wrap>
|
|
||||||
{!isPreferredApiMongoDB && <Text className="queryText">SELECT * FROM c</Text>}
|
|
||||||
<TextField
|
|
||||||
iconProps={filterIcon}
|
|
||||||
placeholder={getFilterPlaceholder(isPreferredApiMongoDB)}
|
|
||||||
className={isPreferredApiMongoDB ? "documentTabSearchBar" : "documentSqlTabSearchBar"}
|
|
||||||
onFocus={() => this.setState({ isSuggestionVisible: true })}
|
|
||||||
onChange={(_event, newInput?: string) => {
|
|
||||||
this.setState({ filter: newInput });
|
|
||||||
}}
|
|
||||||
value={filter}
|
|
||||||
/>
|
|
||||||
<PrimaryButton text="Apply Filter" onClick={this.handleFilter} className="documentTabFiltetButton" />
|
|
||||||
<Image
|
|
||||||
src={CloseIcon}
|
|
||||||
alt="Close icon"
|
|
||||||
{...imageProps}
|
|
||||||
onClick={() => this.setState({ isFilterOptionVisible: false })}
|
|
||||||
/>
|
|
||||||
</Stack>
|
|
||||||
</div>
|
|
||||||
{isSuggestionVisible && (
|
|
||||||
<div className={isPreferredApiMongoDB ? "filterSuggestions" : "filterSuggestions sqlFilterSuggestions"}>
|
|
||||||
<List items={getFilterSuggestions(isPreferredApiMongoDB)} onRenderCell={this.onRenderCell} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{!isFilterOptionVisible && (
|
|
||||||
<Stack horizontal verticalFill wrap className="documentTabNoFilterView">
|
|
||||||
<Text className="noFilterText">{getfilterText(isPreferredApiMongoDB, filter)}</Text>
|
|
||||||
<PrimaryButton text="Edit Filter" onClick={() => this.setState({ isFilterOptionVisible: true })} />
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
<div className="splitterWrapper" onClick={() => this.setState({ isSuggestionVisible: false })}>
|
|
||||||
<SplitterLayout primaryIndex={0} secondaryInitialSize={1000}>
|
|
||||||
<div className="leftSplitter">
|
|
||||||
<DetailsList
|
|
||||||
items={getDocumentItems(isPreferredApiMongoDB, documentIds, documentSqlIds, isAllDocumentsVisible)}
|
|
||||||
compact={isCompactMode}
|
|
||||||
columns={columns}
|
|
||||||
selectionMode={SelectionMode.none}
|
|
||||||
getKey={this.getKey}
|
|
||||||
setKey="none"
|
|
||||||
layoutMode={DetailsListLayoutMode.justified}
|
|
||||||
isHeaderVisible={true}
|
|
||||||
/>
|
|
||||||
<Text onClick={this.handleLoadMoreDocument} className="documentLoadMore" block={true}>
|
|
||||||
Load More
|
|
||||||
</Text>
|
|
||||||
</div>
|
|
||||||
{isEditorVisible ? (
|
|
||||||
<div className="react-editor">
|
|
||||||
<EditorReact
|
|
||||||
language={"json"}
|
|
||||||
content={documentContent}
|
|
||||||
isReadOnly={false}
|
|
||||||
ariaLabel={"Document json"}
|
|
||||||
onContentChanged={this.handleDocumentContentChange}
|
|
||||||
lineNumbers="on"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="documentTabWatermark">
|
|
||||||
<Image src={DocumentWaterMark} alt="Document watermark" />
|
|
||||||
<Text className="documentCreateText">Create new or work with existing document(s).</Text>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</SplitterLayout>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
import * as ko from "knockout";
|
|
||||||
import { PartitionKey, Resource } from "../../../src/Contracts/DataModels";
|
|
||||||
import DocumentId from "../Tree/DocumentId";
|
|
||||||
import * as DocumentTabUtils from "./DocumentTabUtils";
|
|
||||||
|
|
||||||
describe("DocumentTabUtils", () => {
|
|
||||||
describe("getfilterText()", () => {
|
|
||||||
it("Should return filter if isPreferredApiMongoDB is true and filter is applied ", () => {
|
|
||||||
const filteredText: string = DocumentTabUtils.getfilterText(true, `{"_id": "foo"}`);
|
|
||||||
expect(filteredText).toBe(`Filter : {"_id": "foo"}`);
|
|
||||||
});
|
|
||||||
it("Should return `No filter applied` if isPreferredApiMongoDB is true and filter is not applied ", () => {
|
|
||||||
const filteredText: string = DocumentTabUtils.getfilterText(true, "");
|
|
||||||
expect(filteredText).toBe("No filter applied");
|
|
||||||
});
|
|
||||||
it("Should return `Select * from C` with filter if isPreferredApiMongoDB is false and filter is applied ", () => {
|
|
||||||
const filteredText: string = DocumentTabUtils.getfilterText(false, `WHERE c.id = "foo"`);
|
|
||||||
expect(filteredText).toBe(`Select * from C WHERE c.id = "foo"`);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("formatDocumentContent()", () => {
|
|
||||||
const fakeDocumentData = {} as DocumentId;
|
|
||||||
fakeDocumentData.partitionKeyProperty = "test";
|
|
||||||
fakeDocumentData.id = ko.observable("id");
|
|
||||||
|
|
||||||
it("should return formatted content with new line each property.", () => {
|
|
||||||
fakeDocumentData.partitionKeyValue = "partitionValue";
|
|
||||||
const formattedContent: string = DocumentTabUtils.formatDocumentContent(fakeDocumentData);
|
|
||||||
expect(formattedContent).toBe(`{\n"_id":"id",\n"test":"partitionValue"\n}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return formatted content with empty partitionKeyValue when partitionKeyValue is undefined.", () => {
|
|
||||||
fakeDocumentData.partitionKeyValue = undefined;
|
|
||||||
const formattedContent: string = DocumentTabUtils.formatDocumentContent(fakeDocumentData);
|
|
||||||
expect(formattedContent).toBe(`{\n"_id":"id",\n"test":""\n}`);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("formatSqlDocumentContent()", () => {
|
|
||||||
const fakeDocumentData = {} as Resource;
|
|
||||||
it("should return formatted content with new line each property.", () => {
|
|
||||||
fakeDocumentData.id = "testId";
|
|
||||||
fakeDocumentData._rid = "testRid";
|
|
||||||
fakeDocumentData._self = "testSelf";
|
|
||||||
fakeDocumentData._ts = "testTs";
|
|
||||||
fakeDocumentData._etag = "testEtag";
|
|
||||||
fakeDocumentData._attachments = "testAttachments";
|
|
||||||
fakeDocumentData._partitionKey = "testPartitionKey";
|
|
||||||
|
|
||||||
const formattedContent: string = DocumentTabUtils.formatSqlDocumentContent(fakeDocumentData);
|
|
||||||
expect(formattedContent).toBe(
|
|
||||||
`{\n"id":"testId",\n"_rid":"testRid",\n"_self":"testSelf",\n"_ts":"testTs",\n"_etag":"testEtag",\n"_attachments":"testAttachments",\n"_partitionKey":"testPartitionKey"\n}`
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return formatted content with empty value when key value is undefined.", () => {
|
|
||||||
fakeDocumentData.id = undefined;
|
|
||||||
fakeDocumentData._rid = undefined;
|
|
||||||
fakeDocumentData._self = undefined;
|
|
||||||
fakeDocumentData._ts = undefined;
|
|
||||||
fakeDocumentData._etag = undefined;
|
|
||||||
fakeDocumentData._attachments = undefined;
|
|
||||||
fakeDocumentData._partitionKey = undefined;
|
|
||||||
const formattedContent: string = DocumentTabUtils.formatSqlDocumentContent(fakeDocumentData);
|
|
||||||
expect(formattedContent).toBe(
|
|
||||||
`{\n"id":"",\n"_rid":"",\n"_self":"",\n"_ts":"",\n"_etag":"",\n"_attachments":"",\n"_partitionKey":""\n}`
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
describe("getPartitionKeyDefinition()", () => {
|
|
||||||
const partitionKey = {} as PartitionKey;
|
|
||||||
partitionKey.kind = "Hash";
|
|
||||||
partitionKey.version = 1;
|
|
||||||
partitionKey.systemKey = true;
|
|
||||||
const partitionKeyProperty = "testPartitionKey";
|
|
||||||
|
|
||||||
it("should return formatted partitionKey with formatted path.", () => {
|
|
||||||
partitionKey.paths = ["test"];
|
|
||||||
const formattedPartitionKey = DocumentTabUtils.getPartitionKeyDefinition(partitionKey, partitionKeyProperty);
|
|
||||||
expect(formattedPartitionKey).toEqual({ kind: "Hash", version: 1, systemKey: true, paths: ["test"] });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return partitionKey with undefined paths if paths is undefined.", () => {
|
|
||||||
partitionKey.paths = undefined;
|
|
||||||
const formattedPartitionKey = DocumentTabUtils.getPartitionKeyDefinition(partitionKey, partitionKeyProperty);
|
|
||||||
expect(formattedPartitionKey).toEqual({ kind: "Hash", version: 1, systemKey: true, paths: undefined });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,10 +1,33 @@
|
|||||||
|
import { extractPartitionKey, PartitionKeyDefinition } from "@azure/cosmos";
|
||||||
|
import * as ko from "knockout";
|
||||||
|
import Q from "q";
|
||||||
|
import * as Constants from "../../Common/Constants";
|
||||||
|
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
|
||||||
|
import * as Logger from "../../Common/Logger";
|
||||||
|
import {
|
||||||
|
createDocument,
|
||||||
|
deleteDocument,
|
||||||
|
queryDocuments,
|
||||||
|
readDocument,
|
||||||
|
updateDocument,
|
||||||
|
} from "../../Common/MongoProxyClient";
|
||||||
|
import MongoUtility from "../../Common/MongoUtility";
|
||||||
|
import * as DataModels from "../../Contracts/DataModels";
|
||||||
import * as ViewModels from "../../Contracts/ViewModels";
|
import * as ViewModels from "../../Contracts/ViewModels";
|
||||||
|
import { Action } from "../../Shared/Telemetry/TelemetryConstants";
|
||||||
|
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
||||||
|
import DocumentId from "../Tree/DocumentId";
|
||||||
|
import ObjectId from "../Tree/ObjectId";
|
||||||
import DocumentsTab from "./DocumentsTab";
|
import DocumentsTab from "./DocumentsTab";
|
||||||
|
|
||||||
export default class MongoDocumentsTab extends DocumentsTab {
|
export default class MongoDocumentsTab extends DocumentsTab {
|
||||||
public collection: ViewModels.Collection;
|
public collection: ViewModels.Collection;
|
||||||
|
private continuationToken: string;
|
||||||
|
|
||||||
constructor(options: ViewModels.DocumentsTabOptions) {
|
constructor(options: ViewModels.DocumentsTabOptions) {
|
||||||
super(options);
|
super(options);
|
||||||
|
this.lastFilterContents = ko.observableArray<string>(['{"id":"foo"}', "{ qty: { $gte: 20 } }"]);
|
||||||
|
|
||||||
if (this.partitionKeyProperty && ~this.partitionKeyProperty.indexOf(`"`)) {
|
if (this.partitionKeyProperty && ~this.partitionKeyProperty.indexOf(`"`)) {
|
||||||
this.partitionKeyProperty = this.partitionKeyProperty.replace(/["]+/g, "");
|
this.partitionKeyProperty = this.partitionKeyProperty.replace(/["]+/g, "");
|
||||||
}
|
}
|
||||||
@@ -15,7 +38,279 @@ export default class MongoDocumentsTab extends DocumentsTab {
|
|||||||
this.partitionKeyPropertyHeader = "/" + this.partitionKeyProperty;
|
this.partitionKeyPropertyHeader = "/" + this.partitionKeyProperty;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.isFilterExpanded = ko.observable<boolean>(true);
|
||||||
super.buildCommandBarOptions.bind(this);
|
super.buildCommandBarOptions.bind(this);
|
||||||
super.buildCommandBarOptions();
|
super.buildCommandBarOptions();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public onSaveNewDocumentClick = (): Promise<any> => {
|
||||||
|
const documentContent = JSON.parse(this.selectedDocumentContent());
|
||||||
|
this.displayedError("");
|
||||||
|
const startKey: number = TelemetryProcessor.traceStart(Action.CreateDocument, {
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (
|
||||||
|
this.partitionKeyProperty &&
|
||||||
|
this.partitionKeyProperty !== "_id" &&
|
||||||
|
!this._hasShardKeySpecified(documentContent)
|
||||||
|
) {
|
||||||
|
const message = `The document is lacking the shard property: ${this.partitionKeyProperty}`;
|
||||||
|
this.displayedError(message);
|
||||||
|
let that = this;
|
||||||
|
setTimeout(() => {
|
||||||
|
that.displayedError("");
|
||||||
|
}, Constants.ClientDefaults.errorNotificationTimeoutMs);
|
||||||
|
this.isExecutionError(true);
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.CreateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: message,
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
Logger.logError("Failed to save new document: Document shard key not defined", "MongoDocumentsTab");
|
||||||
|
throw new Error("Document without shard key");
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isExecutionError(false);
|
||||||
|
this.isExecuting(true);
|
||||||
|
return createDocument(this.collection.databaseId, this.collection, this.partitionKeyProperty, documentContent)
|
||||||
|
.then(
|
||||||
|
(savedDocument: any) => {
|
||||||
|
let partitionKeyArray = extractPartitionKey(
|
||||||
|
savedDocument,
|
||||||
|
this._getPartitionKeyDefinition() as PartitionKeyDefinition
|
||||||
|
);
|
||||||
|
|
||||||
|
let partitionKeyValue = partitionKeyArray && partitionKeyArray[0];
|
||||||
|
|
||||||
|
let id = new ObjectId(this, savedDocument, partitionKeyValue);
|
||||||
|
let ids = this.documentIds();
|
||||||
|
ids.push(id);
|
||||||
|
delete savedDocument._self;
|
||||||
|
|
||||||
|
let value: string = this.renderObjectForEditor(savedDocument || {}, null, 4);
|
||||||
|
this.selectedDocumentContent.setBaseline(value);
|
||||||
|
|
||||||
|
this.selectedDocumentId(id);
|
||||||
|
this.documentIds(ids);
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentNoEdits);
|
||||||
|
TelemetryProcessor.traceSuccess(
|
||||||
|
Action.CreateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
this.isExecutionError(true);
|
||||||
|
const errorMessage = getErrorMessage(error);
|
||||||
|
window.alert(errorMessage);
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.CreateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: errorMessage,
|
||||||
|
errorStack: getErrorStack(error),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.finally(() => this.isExecuting(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
public onSaveExisitingDocumentClick = (): Promise<any> => {
|
||||||
|
const selectedDocumentId = this.selectedDocumentId();
|
||||||
|
const documentContent = this.selectedDocumentContent();
|
||||||
|
this.isExecutionError(false);
|
||||||
|
this.isExecuting(true);
|
||||||
|
const startKey: number = TelemetryProcessor.traceStart(Action.UpdateDocument, {
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
});
|
||||||
|
|
||||||
|
return updateDocument(this.collection.databaseId, this.collection, selectedDocumentId, documentContent)
|
||||||
|
.then(
|
||||||
|
(updatedDocument: any) => {
|
||||||
|
let value: string = this.renderObjectForEditor(updatedDocument || {}, null, 4);
|
||||||
|
this.selectedDocumentContent.setBaseline(value);
|
||||||
|
|
||||||
|
this.documentIds().forEach((documentId: DocumentId) => {
|
||||||
|
if (documentId.rid === updatedDocument._rid) {
|
||||||
|
const partitionKeyArray = extractPartitionKey(
|
||||||
|
updatedDocument,
|
||||||
|
this._getPartitionKeyDefinition() as PartitionKeyDefinition
|
||||||
|
);
|
||||||
|
|
||||||
|
let partitionKeyValue = partitionKeyArray && partitionKeyArray[0];
|
||||||
|
|
||||||
|
const id = new ObjectId(this, updatedDocument, partitionKeyValue);
|
||||||
|
documentId.id(id.id());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.exisitingDocumentNoEdits);
|
||||||
|
TelemetryProcessor.traceSuccess(
|
||||||
|
Action.UpdateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
this.isExecutionError(true);
|
||||||
|
const errorMessage = getErrorMessage(error);
|
||||||
|
window.alert(errorMessage);
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.UpdateDocument,
|
||||||
|
{
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: errorMessage,
|
||||||
|
errorStack: getErrorStack(error),
|
||||||
|
},
|
||||||
|
startKey
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.finally(() => this.isExecuting(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
public buildQuery(filter: string): string {
|
||||||
|
return filter || "{}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public async selectDocument(documentId: DocumentId): Promise<void> {
|
||||||
|
this.selectedDocumentId(documentId);
|
||||||
|
const content = await readDocument(this.collection.databaseId, this.collection, documentId);
|
||||||
|
this.initDocumentEditor(documentId, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
public loadNextPage(): Q.Promise<any> {
|
||||||
|
this.isExecuting(true);
|
||||||
|
this.isExecutionError(false);
|
||||||
|
const filter: string = this.filterContent().trim();
|
||||||
|
const query: string = this.buildQuery(filter);
|
||||||
|
|
||||||
|
return Q(queryDocuments(this.collection.databaseId, this.collection, true, query, this.continuationToken))
|
||||||
|
.then(
|
||||||
|
({ continuationToken, documents }) => {
|
||||||
|
this.continuationToken = continuationToken;
|
||||||
|
let currentDocuments = this.documentIds();
|
||||||
|
const currentDocumentsRids = currentDocuments.map((currentDocument) => currentDocument.rid);
|
||||||
|
const nextDocumentIds = documents
|
||||||
|
.filter((d: any) => {
|
||||||
|
return currentDocumentsRids.indexOf(d._rid) < 0;
|
||||||
|
})
|
||||||
|
.map((rawDocument: any) => {
|
||||||
|
const partitionKeyValue = rawDocument._partitionKeyValue;
|
||||||
|
return new DocumentId(this, rawDocument, partitionKeyValue);
|
||||||
|
});
|
||||||
|
|
||||||
|
const merged = currentDocuments.concat(nextDocumentIds);
|
||||||
|
|
||||||
|
this.documentIds(merged);
|
||||||
|
currentDocuments = this.documentIds();
|
||||||
|
if (this.filterContent().length > 0 && currentDocuments.length > 0) {
|
||||||
|
currentDocuments[0].click();
|
||||||
|
} else {
|
||||||
|
this.selectedDocumentContent("");
|
||||||
|
this.selectedDocumentId(null);
|
||||||
|
this.editorState(ViewModels.DocumentExplorerState.noDocumentSelected);
|
||||||
|
}
|
||||||
|
if (this.onLoadStartKey != null && this.onLoadStartKey != undefined) {
|
||||||
|
TelemetryProcessor.traceSuccess(
|
||||||
|
Action.Tab,
|
||||||
|
{
|
||||||
|
databaseName: this.collection.databaseId,
|
||||||
|
collectionName: this.collection.id(),
|
||||||
|
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
},
|
||||||
|
this.onLoadStartKey
|
||||||
|
);
|
||||||
|
this.onLoadStartKey = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(error: any) => {
|
||||||
|
if (this.onLoadStartKey != null && this.onLoadStartKey != undefined) {
|
||||||
|
TelemetryProcessor.traceFailure(
|
||||||
|
Action.Tab,
|
||||||
|
{
|
||||||
|
databaseName: this.collection.databaseId,
|
||||||
|
collectionName: this.collection.id(),
|
||||||
|
|
||||||
|
dataExplorerArea: Constants.Areas.Tab,
|
||||||
|
tabTitle: this.tabTitle(),
|
||||||
|
error: getErrorMessage(error),
|
||||||
|
errorStack: getErrorStack(error),
|
||||||
|
},
|
||||||
|
this.onLoadStartKey
|
||||||
|
);
|
||||||
|
this.onLoadStartKey = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.finally(() => this.isExecuting(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected _onEditorContentChange(newContent: string) {
|
||||||
|
try {
|
||||||
|
if (
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.newDocumentValid ||
|
||||||
|
this.editorState() === ViewModels.DocumentExplorerState.newDocumentInvalid
|
||||||
|
) {
|
||||||
|
let parsed: any = JSON.parse(newContent);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mongo uses BSON format for _id, trying to parse it as JSON blocks normal flow in an edit
|
||||||
|
this.onValidDocumentEdit();
|
||||||
|
} catch (e) {
|
||||||
|
this.onInvalidDocumentEdit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Renders a Javascript object to be displayed inside Monaco Editor */
|
||||||
|
public renderObjectForEditor(value: any, replacer: any, space: string | number): string {
|
||||||
|
return MongoUtility.tojson(value, null, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _hasShardKeySpecified(document: any): boolean {
|
||||||
|
return Boolean(extractPartitionKey(document, this._getPartitionKeyDefinition() as PartitionKeyDefinition));
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getPartitionKeyDefinition(): DataModels.PartitionKey {
|
||||||
|
let partitionKey: DataModels.PartitionKey = this.partitionKey;
|
||||||
|
|
||||||
|
if (
|
||||||
|
this.partitionKey &&
|
||||||
|
this.partitionKey.paths &&
|
||||||
|
this.partitionKey.paths.length &&
|
||||||
|
this.partitionKey.paths.length > 0 &&
|
||||||
|
this.partitionKey.paths[0].indexOf("$v") > -1
|
||||||
|
) {
|
||||||
|
// Convert BsonSchema2 to /path format
|
||||||
|
partitionKey = {
|
||||||
|
kind: partitionKey.kind,
|
||||||
|
paths: ["/" + this.partitionKeyProperty.replace(/\./g, "/")],
|
||||||
|
version: partitionKey.version,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return partitionKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected __deleteDocument(documentId: DocumentId): Promise<void> {
|
||||||
|
return deleteDocument(this.collection.databaseId, this.collection, documentId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -137,14 +137,13 @@ export default class QueryTablesTab extends TabsBase {
|
|||||||
useSidePanel
|
useSidePanel
|
||||||
.getState()
|
.getState()
|
||||||
.openSidePanel(
|
.openSidePanel(
|
||||||
"Add Table Row",
|
"Add Table Entity",
|
||||||
<AddTableEntityPanel
|
<AddTableEntityPanel
|
||||||
tableDataClient={this.tableDataClient}
|
tableDataClient={this.tableDataClient}
|
||||||
queryTablesTab={this}
|
queryTablesTab={this}
|
||||||
tableEntityListViewModel={this.tableEntityListViewModel()}
|
tableEntityListViewModel={this.tableEntityListViewModel()}
|
||||||
cassandraApiClient={new CassandraAPIDataClient()}
|
cassandraApiClient={new CassandraAPIDataClient()}
|
||||||
/>,
|
/>
|
||||||
"700px"
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -158,8 +157,7 @@ export default class QueryTablesTab extends TabsBase {
|
|||||||
queryTablesTab={this}
|
queryTablesTab={this}
|
||||||
tableEntityListViewModel={this.tableEntityListViewModel()}
|
tableEntityListViewModel={this.tableEntityListViewModel()}
|
||||||
cassandraApiClient={new CassandraAPIDataClient()}
|
cassandraApiClient={new CassandraAPIDataClient()}
|
||||||
/>,
|
/>
|
||||||
"700px"
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -571,8 +571,8 @@ export default class Collection implements ViewModels.Collection {
|
|||||||
};
|
};
|
||||||
|
|
||||||
public onSettingsClick = async (): Promise<void> => {
|
public onSettingsClick = async (): Promise<void> => {
|
||||||
useSelectedNode.getState().setSelectedNode(this);
|
|
||||||
await this.loadOffer();
|
await this.loadOffer();
|
||||||
|
useSelectedNode.getState().setSelectedNode(this);
|
||||||
this.selectedSubnodeKind(ViewModels.CollectionTabKind.Settings);
|
this.selectedSubnodeKind(ViewModels.CollectionTabKind.Settings);
|
||||||
TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, {
|
TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, {
|
||||||
description: "Settings node",
|
description: "Settings node",
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ export default class Database implements ViewModels.Database {
|
|||||||
this.isOfferRead = false;
|
this.isOfferRead = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public onSettingsClick = (): void => {
|
public onSettingsClick = () => {
|
||||||
useSelectedNode.getState().setSelectedNode(this);
|
useSelectedNode.getState().setSelectedNode(this);
|
||||||
this.selectedSubnodeKind(ViewModels.CollectionTabKind.DatabaseSettings);
|
this.selectedSubnodeKind(ViewModels.CollectionTabKind.DatabaseSettings);
|
||||||
TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, {
|
TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, {
|
||||||
@@ -193,8 +193,6 @@ export default class Database implements ViewModels.Database {
|
|||||||
//merge collections
|
//merge collections
|
||||||
this.addCollectionsToList(collectionVMs);
|
this.addCollectionsToList(collectionVMs);
|
||||||
this.deleteCollectionsFromList(deltaCollections.toDelete);
|
this.deleteCollectionsFromList(deltaCollections.toDelete);
|
||||||
|
|
||||||
useDatabases.getState().updateDatabase(this);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async openAddCollection(database: Database): Promise<void> {
|
public async openAddCollection(database: Database): Promise<void> {
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ export default class DocumentId {
|
|||||||
public partitionKeyValue: any;
|
public partitionKeyValue: any;
|
||||||
public stringPartitionKeyValue: string;
|
public stringPartitionKeyValue: string;
|
||||||
public isDirty: ko.Observable<boolean>;
|
public isDirty: ko.Observable<boolean>;
|
||||||
public _partitionKeyValue: string;
|
|
||||||
|
|
||||||
constructor(container: DocumentsTab, data: any, partitionKeyValue: any) {
|
constructor(container: DocumentsTab, data: any, partitionKeyValue: any) {
|
||||||
this.container = container;
|
this.container = container;
|
||||||
@@ -28,6 +27,13 @@ export default class DocumentId {
|
|||||||
this.isDirty = ko.observable(false);
|
this.isDirty = ko.observable(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public click() {
|
||||||
|
if (!this.container.isEditorDirty() || window.confirm("Your unsaved changes will be lost.")) {
|
||||||
|
this.loadDocument();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
public partitionKeyHeader(): Object {
|
public partitionKeyHeader(): Object {
|
||||||
if (!this.partitionKeyProperty) {
|
if (!this.partitionKeyProperty) {
|
||||||
return undefined;
|
return undefined;
|
||||||
@@ -58,4 +64,8 @@ export default class DocumentId {
|
|||||||
|
|
||||||
return JSON.stringify(partitionKeyValue);
|
return JSON.stringify(partitionKeyValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async loadDocument(): Promise<void> {
|
||||||
|
await this.container.selectDocument(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as ko from "knockout";
|
import * as ko from "knockout";
|
||||||
import DocumentsTab from "../Tabs/DocumentsTab";
|
|
||||||
import DocumentId from "./DocumentId";
|
import DocumentId from "./DocumentId";
|
||||||
|
import DocumentsTab from "../Tabs/DocumentsTab";
|
||||||
|
|
||||||
export default class ObjectId extends DocumentId {
|
export default class ObjectId extends DocumentId {
|
||||||
constructor(container: DocumentsTab, data: any, partitionKeyValue: any) {
|
constructor(container: DocumentsTab, data: any, partitionKeyValue: any) {
|
||||||
|
|||||||
@@ -1,722 +0,0 @@
|
|||||||
import { Callout, DirectionalHint, ICalloutProps, ILinkProps, Link, Stack, Text } from "@fluentui/react";
|
|
||||||
import * as React from "react";
|
|
||||||
import CosmosDBIcon from "../../../images/Azure-Cosmos-DB.svg";
|
|
||||||
import DeleteIcon from "../../../images/delete.svg";
|
|
||||||
import GalleryIcon from "../../../images/GalleryIcon.svg";
|
|
||||||
import FileIcon from "../../../images/notebook/file-cosmos.svg";
|
|
||||||
import CopyIcon from "../../../images/notebook/Notebook-copy.svg";
|
|
||||||
import NewNotebookIcon from "../../../images/notebook/Notebook-new.svg";
|
|
||||||
import NotebookIcon from "../../../images/notebook/Notebook-resource.svg";
|
|
||||||
import PublishIcon from "../../../images/notebook/publish_content.svg";
|
|
||||||
import RefreshIcon from "../../../images/refresh-cosmos.svg";
|
|
||||||
import CollectionIcon from "../../../images/tree-collection.svg";
|
|
||||||
import { Areas } from "../../Common/Constants";
|
|
||||||
import { isPublicInternetAccessAllowed } from "../../Common/DatabaseAccountUtility";
|
|
||||||
import * as DataModels from "../../Contracts/DataModels";
|
|
||||||
import * as ViewModels from "../../Contracts/ViewModels";
|
|
||||||
import { useSidePanel } from "../../hooks/useSidePanel";
|
|
||||||
import { useTabs } from "../../hooks/useTabs";
|
|
||||||
import { LocalStorageUtility, StorageKey } from "../../Shared/StorageUtility";
|
|
||||||
import { Action, ActionModifiers, Source } from "../../Shared/Telemetry/TelemetryConstants";
|
|
||||||
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
|
||||||
import { userContext } from "../../UserContext";
|
|
||||||
import { isServerlessAccount } from "../../Utils/CapabilityUtils";
|
|
||||||
import * as GitHubUtils from "../../Utils/GitHubUtils";
|
|
||||||
import * as ResourceTreeContextMenuButtonFactory from "../ContextMenuButtonFactory";
|
|
||||||
import { AccordionComponent, AccordionItemComponent } from "../Controls/Accordion/AccordionComponent";
|
|
||||||
import { TreeComponent, TreeNode, TreeNodeMenuItem } from "../Controls/TreeComponent/TreeComponent";
|
|
||||||
import Explorer from "../Explorer";
|
|
||||||
import { useCommandBar } from "../Menus/CommandBar/CommandBarComponentAdapter";
|
|
||||||
import { mostRecentActivity } from "../MostRecentActivity/MostRecentActivity";
|
|
||||||
import { NotebookContentItem, NotebookContentItemType } from "../Notebook/NotebookContentItem";
|
|
||||||
import { NotebookUtil } from "../Notebook/NotebookUtil";
|
|
||||||
import { useNotebook } from "../Notebook/useNotebook";
|
|
||||||
import { GitHubReposPanel } from "../Panes/GitHubReposPanel/GitHubReposPanel";
|
|
||||||
import TabsBase from "../Tabs/TabsBase";
|
|
||||||
import { useDatabases } from "../useDatabases";
|
|
||||||
import { useSelectedNode } from "../useSelectedNode";
|
|
||||||
import StoredProcedure from "./StoredProcedure";
|
|
||||||
import Trigger from "./Trigger";
|
|
||||||
import UserDefinedFunction from "./UserDefinedFunction";
|
|
||||||
|
|
||||||
export const MyNotebooksTitle = "My Notebooks";
|
|
||||||
export const GitHubReposTitle = "GitHub repos";
|
|
||||||
|
|
||||||
interface ResourceTreeProps {
|
|
||||||
container: Explorer;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ResourceTree: React.FC<ResourceTreeProps> = ({ container }: ResourceTreeProps): JSX.Element => {
|
|
||||||
const databases = useDatabases((state) => state.databases);
|
|
||||||
const {
|
|
||||||
isNotebookEnabled,
|
|
||||||
myNotebooksContentRoot,
|
|
||||||
galleryContentRoot,
|
|
||||||
gitHubNotebooksContentRoot,
|
|
||||||
updateNotebookItem,
|
|
||||||
} = useNotebook();
|
|
||||||
const { activeTab, refreshActiveTab } = useTabs();
|
|
||||||
const showScriptNodes = userContext.apiType === "SQL" || userContext.apiType === "Gremlin";
|
|
||||||
const pseudoDirPath = "PsuedoDir";
|
|
||||||
|
|
||||||
const buildGalleryCallout = (): JSX.Element => {
|
|
||||||
if (
|
|
||||||
LocalStorageUtility.hasItem(StorageKey.GalleryCalloutDismissed) &&
|
|
||||||
LocalStorageUtility.getEntryBoolean(StorageKey.GalleryCalloutDismissed)
|
|
||||||
) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const calloutProps: ICalloutProps = {
|
|
||||||
calloutMaxWidth: 350,
|
|
||||||
ariaLabel: "New gallery",
|
|
||||||
role: "alertdialog",
|
|
||||||
gapSpace: 0,
|
|
||||||
target: ".galleryHeader",
|
|
||||||
directionalHint: DirectionalHint.leftTopEdge,
|
|
||||||
onDismiss: () => {
|
|
||||||
LocalStorageUtility.setEntryBoolean(StorageKey.GalleryCalloutDismissed, true);
|
|
||||||
},
|
|
||||||
setInitialFocus: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
const openGalleryProps: ILinkProps = {
|
|
||||||
onClick: () => {
|
|
||||||
LocalStorageUtility.setEntryBoolean(StorageKey.GalleryCalloutDismissed, true);
|
|
||||||
container.openGallery();
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Callout {...calloutProps}>
|
|
||||||
<Stack tokens={{ childrenGap: 10, padding: 20 }}>
|
|
||||||
<Text variant="xLarge" block>
|
|
||||||
New gallery
|
|
||||||
</Text>
|
|
||||||
<Text block>
|
|
||||||
Sample notebooks are now combined in gallery. View and try out samples provided by Microsoft and other
|
|
||||||
contributors.
|
|
||||||
</Text>
|
|
||||||
<Link {...openGalleryProps}>Open gallery</Link>
|
|
||||||
</Stack>
|
|
||||||
</Callout>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildNotebooksTree = (): TreeNode => {
|
|
||||||
const notebooksTree: TreeNode = {
|
|
||||||
label: undefined,
|
|
||||||
isExpanded: true,
|
|
||||||
children: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
if (galleryContentRoot) {
|
|
||||||
notebooksTree.children.push(buildGalleryNotebooksTree());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (myNotebooksContentRoot) {
|
|
||||||
notebooksTree.children.push(buildMyNotebooksTree());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (container.notebookManager?.gitHubOAuthService.isLoggedIn()) {
|
|
||||||
// collapse all other notebook nodes
|
|
||||||
notebooksTree.children.forEach((node) => (node.isExpanded = false));
|
|
||||||
notebooksTree.children.push(buildGitHubNotebooksTree());
|
|
||||||
}
|
|
||||||
|
|
||||||
return notebooksTree;
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildGalleryNotebooksTree = (): TreeNode => {
|
|
||||||
return {
|
|
||||||
label: "Gallery",
|
|
||||||
iconSrc: GalleryIcon,
|
|
||||||
className: "notebookHeader galleryHeader",
|
|
||||||
onClick: () => container.openGallery(),
|
|
||||||
isSelected: () => activeTab?.tabKind === ViewModels.CollectionTabKind.Gallery,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildMyNotebooksTree = (): TreeNode => {
|
|
||||||
const myNotebooksTree: TreeNode = buildNotebookDirectoryNode(
|
|
||||||
myNotebooksContentRoot,
|
|
||||||
(item: NotebookContentItem) => {
|
|
||||||
container.openNotebook(item).then((hasOpened) => {
|
|
||||||
if (hasOpened) {
|
|
||||||
mostRecentActivity.notebookWasItemOpened(userContext.databaseAccount?.id, item);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
myNotebooksTree.isExpanded = true;
|
|
||||||
myNotebooksTree.isAlphaSorted = true;
|
|
||||||
// Remove "Delete" menu item from context menu
|
|
||||||
myNotebooksTree.contextMenu = myNotebooksTree.contextMenu.filter((menuItem) => menuItem.label !== "Delete");
|
|
||||||
return myNotebooksTree;
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildGitHubNotebooksTree = (): TreeNode => {
|
|
||||||
const gitHubNotebooksTree: TreeNode = buildNotebookDirectoryNode(
|
|
||||||
gitHubNotebooksContentRoot,
|
|
||||||
(item: NotebookContentItem) => {
|
|
||||||
container.openNotebook(item).then((hasOpened) => {
|
|
||||||
if (hasOpened) {
|
|
||||||
mostRecentActivity.notebookWasItemOpened(userContext.databaseAccount?.id, item);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
gitHubNotebooksTree.contextMenu = [
|
|
||||||
{
|
|
||||||
label: "Manage GitHub settings",
|
|
||||||
onClick: () =>
|
|
||||||
useSidePanel
|
|
||||||
.getState()
|
|
||||||
.openSidePanel(
|
|
||||||
"Manage GitHub settings",
|
|
||||||
<GitHubReposPanel
|
|
||||||
explorer={container}
|
|
||||||
gitHubClientProp={container.notebookManager.gitHubClient}
|
|
||||||
junoClientProp={container.notebookManager.junoClient}
|
|
||||||
/>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Disconnect from GitHub",
|
|
||||||
onClick: () => {
|
|
||||||
TelemetryProcessor.trace(Action.NotebooksGitHubDisconnect, ActionModifiers.Mark, {
|
|
||||||
dataExplorerArea: Areas.Notebook,
|
|
||||||
});
|
|
||||||
container.notebookManager?.gitHubOAuthService.logout();
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
gitHubNotebooksTree.isExpanded = true;
|
|
||||||
gitHubNotebooksTree.isAlphaSorted = true;
|
|
||||||
|
|
||||||
return gitHubNotebooksTree;
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildChildNodes = (
|
|
||||||
container: Explorer,
|
|
||||||
item: NotebookContentItem,
|
|
||||||
onFileClick: (item: NotebookContentItem) => void
|
|
||||||
): TreeNode[] => {
|
|
||||||
if (!item || !item.children) {
|
|
||||||
return [];
|
|
||||||
} else {
|
|
||||||
return item.children.map((item) => {
|
|
||||||
const result =
|
|
||||||
item.type === NotebookContentItemType.Directory
|
|
||||||
? buildNotebookDirectoryNode(item, onFileClick)
|
|
||||||
: buildNotebookFileNode(item, onFileClick);
|
|
||||||
result.timestamp = item.timestamp;
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildNotebookFileNode = (
|
|
||||||
item: NotebookContentItem,
|
|
||||||
onFileClick: (item: NotebookContentItem) => void
|
|
||||||
): TreeNode => {
|
|
||||||
return {
|
|
||||||
label: item.name,
|
|
||||||
iconSrc: NotebookUtil.isNotebookFile(item.path) ? NotebookIcon : FileIcon,
|
|
||||||
className: "notebookHeader",
|
|
||||||
onClick: () => onFileClick(item),
|
|
||||||
isSelected: () => {
|
|
||||||
return (
|
|
||||||
activeTab &&
|
|
||||||
activeTab.tabKind === ViewModels.CollectionTabKind.NotebookV2 &&
|
|
||||||
/* TODO Redesign Tab interface so that resource tree doesn't need to know about NotebookV2Tab.
|
|
||||||
NotebookV2Tab could be dynamically imported, but not worth it to just get this type right.
|
|
||||||
*/
|
|
||||||
(activeTab as any).notebookPath() === item.path
|
|
||||||
);
|
|
||||||
},
|
|
||||||
contextMenu: createFileContextMenu(container, item),
|
|
||||||
data: item,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const createFileContextMenu = (container: Explorer, item: NotebookContentItem): TreeNodeMenuItem[] => {
|
|
||||||
let items: TreeNodeMenuItem[] = [
|
|
||||||
{
|
|
||||||
label: "Rename",
|
|
||||||
iconSrc: NotebookIcon,
|
|
||||||
onClick: () => container.renameNotebook(item),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Delete",
|
|
||||||
iconSrc: DeleteIcon,
|
|
||||||
onClick: () => {
|
|
||||||
container.showOkCancelModalDialog(
|
|
||||||
"Confirm delete",
|
|
||||||
`Are you sure you want to delete "${item.name}"`,
|
|
||||||
"Delete",
|
|
||||||
() => container.deleteNotebookFile(item),
|
|
||||||
"Cancel",
|
|
||||||
undefined
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Copy to ...",
|
|
||||||
iconSrc: CopyIcon,
|
|
||||||
onClick: () => copyNotebook(container, item),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Download",
|
|
||||||
iconSrc: NotebookIcon,
|
|
||||||
onClick: () => container.downloadFile(item),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
if (item.type === NotebookContentItemType.Notebook) {
|
|
||||||
items.push({
|
|
||||||
label: "Publish to gallery",
|
|
||||||
iconSrc: PublishIcon,
|
|
||||||
onClick: async () => {
|
|
||||||
TelemetryProcessor.trace(Action.NotebooksGalleryClickPublishToGallery, ActionModifiers.Mark, {
|
|
||||||
source: Source.ResourceTreeMenu,
|
|
||||||
});
|
|
||||||
|
|
||||||
const content = await container.readFile(item);
|
|
||||||
if (content) {
|
|
||||||
await container.publishNotebook(item.name, content);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// "Copy to ..." isn't needed if github locations are not available
|
|
||||||
if (!container.notebookManager?.gitHubOAuthService.isLoggedIn()) {
|
|
||||||
items = items.filter((item) => item.label !== "Copy to ...");
|
|
||||||
}
|
|
||||||
|
|
||||||
return items;
|
|
||||||
};
|
|
||||||
|
|
||||||
const copyNotebook = async (container: Explorer, item: NotebookContentItem) => {
|
|
||||||
const content = await container.readFile(item);
|
|
||||||
if (content) {
|
|
||||||
container.copyNotebook(item.name, content);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const createDirectoryContextMenu = (container: Explorer, item: NotebookContentItem): TreeNodeMenuItem[] => {
|
|
||||||
let items: TreeNodeMenuItem[] = [
|
|
||||||
{
|
|
||||||
label: "Refresh",
|
|
||||||
iconSrc: RefreshIcon,
|
|
||||||
onClick: () => loadSubitems(item),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Delete",
|
|
||||||
iconSrc: DeleteIcon,
|
|
||||||
onClick: () => {
|
|
||||||
container.showOkCancelModalDialog(
|
|
||||||
"Confirm delete",
|
|
||||||
`Are you sure you want to delete "${item.name}?"`,
|
|
||||||
"Delete",
|
|
||||||
() => container.deleteNotebookFile(item),
|
|
||||||
"Cancel",
|
|
||||||
undefined
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Rename",
|
|
||||||
iconSrc: NotebookIcon,
|
|
||||||
onClick: () => container.renameNotebook(item),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "New Directory",
|
|
||||||
iconSrc: NewNotebookIcon,
|
|
||||||
onClick: () => container.onCreateDirectory(item),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "New Notebook",
|
|
||||||
iconSrc: NewNotebookIcon,
|
|
||||||
onClick: () => container.onNewNotebookClicked(item),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Upload File",
|
|
||||||
iconSrc: NewNotebookIcon,
|
|
||||||
onClick: () => container.openUploadFilePanel(item),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// For GitHub paths remove "Delete", "Rename", "New Directory", "Upload File"
|
|
||||||
if (GitHubUtils.fromContentUri(item.path)) {
|
|
||||||
items = items.filter(
|
|
||||||
(item) =>
|
|
||||||
item.label !== "Delete" &&
|
|
||||||
item.label !== "Rename" &&
|
|
||||||
item.label !== "New Directory" &&
|
|
||||||
item.label !== "Upload File"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return items;
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildNotebookDirectoryNode = (
|
|
||||||
item: NotebookContentItem,
|
|
||||||
onFileClick: (item: NotebookContentItem) => void
|
|
||||||
): TreeNode => {
|
|
||||||
return {
|
|
||||||
label: item.name,
|
|
||||||
iconSrc: undefined,
|
|
||||||
className: "notebookHeader",
|
|
||||||
isAlphaSorted: true,
|
|
||||||
isLeavesParentsSeparate: true,
|
|
||||||
onClick: () => {
|
|
||||||
if (!item.children) {
|
|
||||||
loadSubitems(item);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
isSelected: () => {
|
|
||||||
return (
|
|
||||||
activeTab &&
|
|
||||||
activeTab.tabKind === ViewModels.CollectionTabKind.NotebookV2 &&
|
|
||||||
/* TODO Redesign Tab interface so that resource tree doesn't need to know about NotebookV2Tab.
|
|
||||||
NotebookV2Tab could be dynamically imported, but not worth it to just get this type right.
|
|
||||||
*/
|
|
||||||
(activeTab as any).notebookPath() === item.path
|
|
||||||
);
|
|
||||||
},
|
|
||||||
contextMenu: item.path !== pseudoDirPath ? createDirectoryContextMenu(container, item) : undefined,
|
|
||||||
data: item,
|
|
||||||
children: buildChildNodes(container, item, onFileClick),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildDataTree = (): TreeNode => {
|
|
||||||
const databaseTreeNodes: TreeNode[] = databases.map((database: ViewModels.Database) => {
|
|
||||||
const databaseNode: TreeNode = {
|
|
||||||
label: database.id(),
|
|
||||||
iconSrc: CosmosDBIcon,
|
|
||||||
isExpanded: false,
|
|
||||||
className: "databaseHeader",
|
|
||||||
children: [],
|
|
||||||
isSelected: () => useSelectedNode.getState().isDataNodeSelected(database.id()),
|
|
||||||
contextMenu: ResourceTreeContextMenuButtonFactory.createDatabaseContextMenu(container, database.id()),
|
|
||||||
onClick: async (isExpanded) => {
|
|
||||||
useSelectedNode.getState().setSelectedNode(database);
|
|
||||||
// Rewritten version of expandCollapseDatabase():
|
|
||||||
if (isExpanded) {
|
|
||||||
database.collapseDatabase();
|
|
||||||
} else {
|
|
||||||
if (databaseNode.children?.length === 0) {
|
|
||||||
databaseNode.isLoading = true;
|
|
||||||
}
|
|
||||||
await database.expandDatabase();
|
|
||||||
}
|
|
||||||
databaseNode.isLoading = false;
|
|
||||||
useCommandBar.getState().setContextButtons([]);
|
|
||||||
refreshActiveTab((tab: TabsBase) => tab.collection?.databaseId === database.id());
|
|
||||||
},
|
|
||||||
onContextMenuOpen: () => useSelectedNode.getState().setSelectedNode(database),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (database.isDatabaseShared()) {
|
|
||||||
databaseNode.children.push({
|
|
||||||
label: "Scale",
|
|
||||||
isSelected: () =>
|
|
||||||
useSelectedNode
|
|
||||||
.getState()
|
|
||||||
.isDataNodeSelected(database.id(), undefined, [ViewModels.CollectionTabKind.DatabaseSettingsV2]),
|
|
||||||
onClick: database.onSettingsClick.bind(database),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find collections
|
|
||||||
database
|
|
||||||
.collections()
|
|
||||||
.forEach((collection: ViewModels.Collection) =>
|
|
||||||
databaseNode.children.push(buildCollectionNode(database, collection))
|
|
||||||
);
|
|
||||||
|
|
||||||
database.collections.subscribe((collections: ViewModels.Collection[]) => {
|
|
||||||
collections.forEach((collection: ViewModels.Collection) =>
|
|
||||||
databaseNode.children.push(buildCollectionNode(database, collection))
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
return databaseNode;
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
label: undefined,
|
|
||||||
isExpanded: true,
|
|
||||||
children: databaseTreeNodes,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildCollectionNode = (database: ViewModels.Database, collection: ViewModels.Collection): TreeNode => {
|
|
||||||
const children: TreeNode[] = [];
|
|
||||||
children.push({
|
|
||||||
label: collection.getLabel(),
|
|
||||||
onClick: () => {
|
|
||||||
collection.openTab();
|
|
||||||
// push to most recent
|
|
||||||
mostRecentActivity.collectionWasOpened(userContext.databaseAccount?.id, collection);
|
|
||||||
},
|
|
||||||
isSelected: () =>
|
|
||||||
useSelectedNode
|
|
||||||
.getState()
|
|
||||||
.isDataNodeSelected(collection.databaseId, collection.id(), [
|
|
||||||
ViewModels.CollectionTabKind.Documents,
|
|
||||||
ViewModels.CollectionTabKind.Graph,
|
|
||||||
]),
|
|
||||||
contextMenu: ResourceTreeContextMenuButtonFactory.createCollectionContextMenuButton(container, collection),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (isNotebookEnabled && userContext.apiType === "Mongo" && isPublicInternetAccessAllowed()) {
|
|
||||||
children.push({
|
|
||||||
label: "Schema (Preview)",
|
|
||||||
onClick: collection.onSchemaAnalyzerClick.bind(collection),
|
|
||||||
isSelected: () =>
|
|
||||||
useSelectedNode
|
|
||||||
.getState()
|
|
||||||
.isDataNodeSelected(collection.databaseId, collection.id(), [ViewModels.CollectionTabKind.SchemaAnalyzer]),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (userContext.apiType !== "Cassandra" || !isServerlessAccount()) {
|
|
||||||
children.push({
|
|
||||||
label: database.isDatabaseShared() || isServerlessAccount() ? "Settings" : "Scale & Settings",
|
|
||||||
onClick: collection.onSettingsClick.bind(collection),
|
|
||||||
isSelected: () =>
|
|
||||||
useSelectedNode
|
|
||||||
.getState()
|
|
||||||
.isDataNodeSelected(collection.databaseId, collection.id(), [
|
|
||||||
ViewModels.CollectionTabKind.CollectionSettingsV2,
|
|
||||||
]),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const schemaNode: TreeNode = buildSchemaNode(collection);
|
|
||||||
if (schemaNode) {
|
|
||||||
children.push(schemaNode);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showScriptNodes) {
|
|
||||||
children.push(buildStoredProcedureNode(collection));
|
|
||||||
children.push(buildUserDefinedFunctionsNode(collection));
|
|
||||||
children.push(buildTriggerNode(collection));
|
|
||||||
}
|
|
||||||
|
|
||||||
// This is a rewrite of showConflicts
|
|
||||||
const showConflicts =
|
|
||||||
userContext?.databaseAccount?.properties.enableMultipleWriteLocations &&
|
|
||||||
collection.rawDataModel &&
|
|
||||||
!!collection.rawDataModel.conflictResolutionPolicy;
|
|
||||||
|
|
||||||
if (showConflicts) {
|
|
||||||
children.push({
|
|
||||||
label: "Conflicts",
|
|
||||||
onClick: collection.onConflictsClick.bind(collection),
|
|
||||||
isSelected: () =>
|
|
||||||
useSelectedNode
|
|
||||||
.getState()
|
|
||||||
.isDataNodeSelected(collection.databaseId, collection.id(), [ViewModels.CollectionTabKind.Conflicts]),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
label: collection.id(),
|
|
||||||
iconSrc: CollectionIcon,
|
|
||||||
isExpanded: false,
|
|
||||||
children: children,
|
|
||||||
className: "collectionHeader",
|
|
||||||
contextMenu: ResourceTreeContextMenuButtonFactory.createCollectionContextMenuButton(container, collection),
|
|
||||||
onClick: () => {
|
|
||||||
// Rewritten version of expandCollapseCollection
|
|
||||||
useSelectedNode.getState().setSelectedNode(collection);
|
|
||||||
useCommandBar.getState().setContextButtons([]);
|
|
||||||
refreshActiveTab(
|
|
||||||
(tab: TabsBase) =>
|
|
||||||
tab.collection?.id() === collection.id() && tab.collection.databaseId === collection.databaseId
|
|
||||||
);
|
|
||||||
},
|
|
||||||
onExpanded: () => {
|
|
||||||
if (showScriptNodes) {
|
|
||||||
collection.loadStoredProcedures();
|
|
||||||
collection.loadUserDefinedFunctions();
|
|
||||||
collection.loadTriggers();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
isSelected: () => useSelectedNode.getState().isDataNodeSelected(collection.databaseId, collection.id()),
|
|
||||||
onContextMenuOpen: () => useSelectedNode.getState().setSelectedNode(collection),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildStoredProcedureNode = (collection: ViewModels.Collection): TreeNode => {
|
|
||||||
return {
|
|
||||||
label: "Stored Procedures",
|
|
||||||
children: collection.storedProcedures().map((sp: StoredProcedure) => ({
|
|
||||||
label: sp.id(),
|
|
||||||
onClick: sp.open.bind(sp),
|
|
||||||
isSelected: () =>
|
|
||||||
useSelectedNode
|
|
||||||
.getState()
|
|
||||||
.isDataNodeSelected(collection.databaseId, collection.id(), [
|
|
||||||
ViewModels.CollectionTabKind.StoredProcedures,
|
|
||||||
]),
|
|
||||||
contextMenu: ResourceTreeContextMenuButtonFactory.createStoreProcedureContextMenuItems(container, sp),
|
|
||||||
})),
|
|
||||||
onClick: () => {
|
|
||||||
collection.selectedSubnodeKind(ViewModels.CollectionTabKind.StoredProcedures);
|
|
||||||
refreshActiveTab(
|
|
||||||
(tab: TabsBase) =>
|
|
||||||
tab.collection?.id() === collection.id() && tab.collection.databaseId === collection.databaseId
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildUserDefinedFunctionsNode = (collection: ViewModels.Collection): TreeNode => {
|
|
||||||
return {
|
|
||||||
label: "User Defined Functions",
|
|
||||||
children: collection.userDefinedFunctions().map((udf: UserDefinedFunction) => ({
|
|
||||||
label: udf.id(),
|
|
||||||
onClick: udf.open.bind(udf),
|
|
||||||
isSelected: () =>
|
|
||||||
useSelectedNode
|
|
||||||
.getState()
|
|
||||||
.isDataNodeSelected(collection.databaseId, collection.id(), [
|
|
||||||
ViewModels.CollectionTabKind.UserDefinedFunctions,
|
|
||||||
]),
|
|
||||||
contextMenu: ResourceTreeContextMenuButtonFactory.createUserDefinedFunctionContextMenuItems(container, udf),
|
|
||||||
})),
|
|
||||||
onClick: () => {
|
|
||||||
collection.selectedSubnodeKind(ViewModels.CollectionTabKind.UserDefinedFunctions);
|
|
||||||
refreshActiveTab(
|
|
||||||
(tab: TabsBase) =>
|
|
||||||
tab.collection?.id() === collection.id() && tab.collection.databaseId === collection.databaseId
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildTriggerNode = (collection: ViewModels.Collection): TreeNode => {
|
|
||||||
return {
|
|
||||||
label: "Triggers",
|
|
||||||
children: collection.triggers().map((trigger: Trigger) => ({
|
|
||||||
label: trigger.id(),
|
|
||||||
onClick: trigger.open.bind(trigger),
|
|
||||||
isSelected: () =>
|
|
||||||
useSelectedNode
|
|
||||||
.getState()
|
|
||||||
.isDataNodeSelected(collection.databaseId, collection.id(), [ViewModels.CollectionTabKind.Triggers]),
|
|
||||||
contextMenu: ResourceTreeContextMenuButtonFactory.createTriggerContextMenuItems(container, trigger),
|
|
||||||
})),
|
|
||||||
onClick: () => {
|
|
||||||
collection.selectedSubnodeKind(ViewModels.CollectionTabKind.Triggers);
|
|
||||||
refreshActiveTab(
|
|
||||||
(tab: TabsBase) =>
|
|
||||||
tab.collection?.id() === collection.id() && tab.collection.databaseId === collection.databaseId
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildSchemaNode = (collection: ViewModels.Collection): TreeNode => {
|
|
||||||
if (collection.analyticalStorageTtl() === undefined) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!collection.schema || !collection.schema.fields) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
label: "Schema",
|
|
||||||
children: getSchemaNodes(collection.schema.fields),
|
|
||||||
onClick: () => {
|
|
||||||
collection.selectedSubnodeKind(ViewModels.CollectionTabKind.Schema);
|
|
||||||
refreshActiveTab((tab: TabsBase) => tab.collection && tab.collection.rid === collection.rid);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const getSchemaNodes = (fields: DataModels.IDataField[]): TreeNode[] => {
|
|
||||||
const schema: any = {};
|
|
||||||
|
|
||||||
//unflatten
|
|
||||||
fields.forEach((field: DataModels.IDataField) => {
|
|
||||||
const path: string[] = field.path.split(".");
|
|
||||||
const fieldProperties = [field.dataType.name, `HasNulls: ${field.hasNulls}`];
|
|
||||||
let current: any = {};
|
|
||||||
path.forEach((name: string, pathIndex: number) => {
|
|
||||||
if (pathIndex === 0) {
|
|
||||||
if (schema[name] === undefined) {
|
|
||||||
if (pathIndex === path.length - 1) {
|
|
||||||
schema[name] = fieldProperties;
|
|
||||||
} else {
|
|
||||||
schema[name] = {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
current = schema[name];
|
|
||||||
} else {
|
|
||||||
if (current[name] === undefined) {
|
|
||||||
if (pathIndex === path.length - 1) {
|
|
||||||
current[name] = fieldProperties;
|
|
||||||
} else {
|
|
||||||
current[name] = {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
current = current[name];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const traverse = (obj: any): TreeNode[] => {
|
|
||||||
const children: TreeNode[] = [];
|
|
||||||
|
|
||||||
if (obj !== undefined && !Array.isArray(obj) && typeof obj === "object") {
|
|
||||||
Object.entries(obj).forEach(([key, value]) => {
|
|
||||||
children.push({ label: key, children: traverse(value) });
|
|
||||||
});
|
|
||||||
} else if (Array.isArray(obj)) {
|
|
||||||
return [{ label: obj[0] }, { label: obj[1] }];
|
|
||||||
}
|
|
||||||
|
|
||||||
return children;
|
|
||||||
};
|
|
||||||
|
|
||||||
return traverse(schema);
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadSubitems = async (item: NotebookContentItem): Promise<void> => {
|
|
||||||
const updatedItem = await container.notebookManager?.notebookContentClient?.updateItemChildren(item);
|
|
||||||
updateNotebookItem(updatedItem);
|
|
||||||
};
|
|
||||||
|
|
||||||
const dataRootNode = buildDataTree();
|
|
||||||
|
|
||||||
if (isNotebookEnabled) {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<AccordionComponent>
|
|
||||||
<AccordionItemComponent title={"DATA"} isExpanded={!gitHubNotebooksContentRoot}>
|
|
||||||
<TreeComponent className="dataResourceTree" rootNode={dataRootNode} />
|
|
||||||
</AccordionItemComponent>
|
|
||||||
<AccordionItemComponent title={"NOTEBOOKS"}>
|
|
||||||
<TreeComponent className="notebookResourceTree" rootNode={buildNotebooksTree()} />
|
|
||||||
</AccordionItemComponent>
|
|
||||||
</AccordionComponent>
|
|
||||||
|
|
||||||
{buildGalleryCallout()}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return <TreeComponent className="dataResourceTree" rootNode={dataRootNode} />;
|
|
||||||
};
|
|
||||||
@@ -16,9 +16,10 @@ import { Areas } from "../../Common/Constants";
|
|||||||
import { isPublicInternetAccessAllowed } from "../../Common/DatabaseAccountUtility";
|
import { isPublicInternetAccessAllowed } from "../../Common/DatabaseAccountUtility";
|
||||||
import * as DataModels from "../../Contracts/DataModels";
|
import * as DataModels from "../../Contracts/DataModels";
|
||||||
import * as ViewModels from "../../Contracts/ViewModels";
|
import * as ViewModels from "../../Contracts/ViewModels";
|
||||||
|
import { GitHubOAuthService } from "../../GitHub/GitHubOAuthService";
|
||||||
import { useSidePanel } from "../../hooks/useSidePanel";
|
import { useSidePanel } from "../../hooks/useSidePanel";
|
||||||
import { useTabs } from "../../hooks/useTabs";
|
import { useTabs } from "../../hooks/useTabs";
|
||||||
import { IPinnedRepo } from "../../Juno/JunoClient";
|
import { IPinnedRepo, JunoClient } from "../../Juno/JunoClient";
|
||||||
import { LocalStorageUtility, StorageKey } from "../../Shared/StorageUtility";
|
import { LocalStorageUtility, StorageKey } from "../../Shared/StorageUtility";
|
||||||
import { Action, ActionModifiers, Source } from "../../Shared/Telemetry/TelemetryConstants";
|
import { Action, ActionModifiers, Source } from "../../Shared/Telemetry/TelemetryConstants";
|
||||||
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
|
||||||
@@ -55,6 +56,8 @@ export class ResourceTreeAdapter implements ReactAdapter {
|
|||||||
public galleryContentRoot: NotebookContentItem;
|
public galleryContentRoot: NotebookContentItem;
|
||||||
public myNotebooksContentRoot: NotebookContentItem;
|
public myNotebooksContentRoot: NotebookContentItem;
|
||||||
public gitHubNotebooksContentRoot: NotebookContentItem;
|
public gitHubNotebooksContentRoot: NotebookContentItem;
|
||||||
|
public junoClient: JunoClient;
|
||||||
|
public gitHubOAuthService: GitHubOAuthService;
|
||||||
|
|
||||||
public constructor(private container: Explorer) {
|
public constructor(private container: Explorer) {
|
||||||
this.parameters = ko.observable(Date.now());
|
this.parameters = ko.observable(Date.now());
|
||||||
@@ -71,6 +74,8 @@ export class ResourceTreeAdapter implements ReactAdapter {
|
|||||||
|
|
||||||
useDatabases.subscribe(() => this.triggerRender());
|
useDatabases.subscribe(() => this.triggerRender());
|
||||||
this.triggerRender();
|
this.triggerRender();
|
||||||
|
this.junoClient = new JunoClient();
|
||||||
|
this.gitHubOAuthService = new GitHubOAuthService(this.junoClient);
|
||||||
}
|
}
|
||||||
|
|
||||||
private traceMyNotebookTreeInfo() {
|
private traceMyNotebookTreeInfo() {
|
||||||
@@ -634,7 +639,7 @@ export class ResourceTreeAdapter implements ReactAdapter {
|
|||||||
<GitHubReposPanel
|
<GitHubReposPanel
|
||||||
explorer={this.container}
|
explorer={this.container}
|
||||||
gitHubClientProp={this.container.notebookManager.gitHubClient}
|
gitHubClientProp={this.container.notebookManager.gitHubClient}
|
||||||
junoClientProp={this.container.notebookManager.junoClient}
|
junoClientProp={this.junoClient}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { shallow } from "enzyme";
|
||||||
|
import React from "react";
|
||||||
|
import * as DataModels from "../../Contracts/DataModels";
|
||||||
|
import * as ViewModels from "../../Contracts/ViewModels";
|
||||||
|
import { TreeComponent, TreeComponentProps, TreeNode } from "../Controls/TreeComponent/TreeComponent";
|
||||||
|
import Explorer from "../Explorer";
|
||||||
|
import { useDatabases } from "../useDatabases";
|
||||||
|
import ResourceTokenCollection from "./ResourceTokenCollection";
|
||||||
|
import { ResourceTreeAdapterForResourceToken } from "./ResourceTreeAdapterForResourceToken";
|
||||||
|
|
||||||
|
describe("Resource tree for resource token", () => {
|
||||||
|
const mockContainer = {} as Explorer;
|
||||||
|
const resourceTree = new ResourceTreeAdapterForResourceToken(mockContainer);
|
||||||
|
const mockCollection = {
|
||||||
|
_rid: "fakeRid",
|
||||||
|
_self: "fakeSelf",
|
||||||
|
id: "fakeId",
|
||||||
|
} as DataModels.Collection;
|
||||||
|
const mockResourceTokenCollection: ViewModels.CollectionBase = new ResourceTokenCollection(
|
||||||
|
mockContainer,
|
||||||
|
"fakeDatabaseId",
|
||||||
|
mockCollection
|
||||||
|
);
|
||||||
|
useDatabases.setState({ resourceTokenCollection: mockResourceTokenCollection });
|
||||||
|
|
||||||
|
it("should render", () => {
|
||||||
|
const rootNode: TreeNode = resourceTree.buildCollectionNode();
|
||||||
|
const props: TreeComponentProps = {
|
||||||
|
rootNode,
|
||||||
|
className: "dataResourceTree",
|
||||||
|
};
|
||||||
|
const wrapper = shallow(<TreeComponent {...props} />);
|
||||||
|
expect(wrapper).toMatchSnapshot();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,18 +1,45 @@
|
|||||||
import React from "react";
|
import * as ko from "knockout";
|
||||||
|
import * as React from "react";
|
||||||
import CollectionIcon from "../../../images/tree-collection.svg";
|
import CollectionIcon from "../../../images/tree-collection.svg";
|
||||||
|
import { ReactAdapter } from "../../Bindings/ReactBindingHandler";
|
||||||
import * as ViewModels from "../../Contracts/ViewModels";
|
import * as ViewModels from "../../Contracts/ViewModels";
|
||||||
import { useTabs } from "../../hooks/useTabs";
|
import { useTabs } from "../../hooks/useTabs";
|
||||||
import { userContext } from "../../UserContext";
|
import { userContext } from "../../UserContext";
|
||||||
import { TreeComponent, TreeNode } from "../Controls/TreeComponent/TreeComponent";
|
import { TreeComponent, TreeNode } from "../Controls/TreeComponent/TreeComponent";
|
||||||
|
import Explorer from "../Explorer";
|
||||||
import { useCommandBar } from "../Menus/CommandBar/CommandBarComponentAdapter";
|
import { useCommandBar } from "../Menus/CommandBar/CommandBarComponentAdapter";
|
||||||
import { mostRecentActivity } from "../MostRecentActivity/MostRecentActivity";
|
import { mostRecentActivity } from "../MostRecentActivity/MostRecentActivity";
|
||||||
|
import { NotebookContentItem } from "../Notebook/NotebookContentItem";
|
||||||
import { useDatabases } from "../useDatabases";
|
import { useDatabases } from "../useDatabases";
|
||||||
import { useSelectedNode } from "../useSelectedNode";
|
import { useSelectedNode } from "../useSelectedNode";
|
||||||
|
|
||||||
export const ResourceTokenTree: React.FC = (): JSX.Element => {
|
export class ResourceTreeAdapterForResourceToken implements ReactAdapter {
|
||||||
const collection = useDatabases((state) => state.resourceTokenCollection);
|
public parameters: ko.Observable<number>;
|
||||||
|
public myNotebooksContentRoot: NotebookContentItem;
|
||||||
|
|
||||||
const buildCollectionNode = (): TreeNode => {
|
public constructor(private container: Explorer) {
|
||||||
|
this.parameters = ko.observable(Date.now());
|
||||||
|
|
||||||
|
useDatabases.subscribe(
|
||||||
|
() => this.triggerRender(),
|
||||||
|
(state) => state.resourceTokenCollection
|
||||||
|
);
|
||||||
|
useSelectedNode.subscribe(() => this.triggerRender());
|
||||||
|
useTabs.subscribe(
|
||||||
|
() => this.triggerRender(),
|
||||||
|
(state) => state.activeTab
|
||||||
|
);
|
||||||
|
|
||||||
|
this.triggerRender();
|
||||||
|
}
|
||||||
|
|
||||||
|
public renderComponent(): JSX.Element {
|
||||||
|
const dataRootNode = this.buildCollectionNode();
|
||||||
|
return <TreeComponent className="dataResourceTree" rootNode={dataRootNode} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
public buildCollectionNode(): TreeNode {
|
||||||
|
const collection: ViewModels.CollectionBase = useDatabases.getState().resourceTokenCollection;
|
||||||
if (!collection) {
|
if (!collection) {
|
||||||
return {
|
return {
|
||||||
label: undefined,
|
label: undefined,
|
||||||
@@ -59,7 +86,9 @@ export const ResourceTokenTree: React.FC = (): JSX.Element => {
|
|||||||
isExpanded: true,
|
isExpanded: true,
|
||||||
children: [collectionNode],
|
children: [collectionNode],
|
||||||
};
|
};
|
||||||
};
|
}
|
||||||
|
|
||||||
return <TreeComponent className="dataResourceTree" rootNode={buildCollectionNode()} />;
|
public triggerRender() {
|
||||||
};
|
window.requestAnimationFrame(() => this.parameters(Date.now()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||||
|
|
||||||
|
exports[`Resource tree for resource token should render 1`] = `
|
||||||
|
<div
|
||||||
|
className="treeComponent dataResourceTree"
|
||||||
|
role="tree"
|
||||||
|
>
|
||||||
|
<TreeNodeComponent
|
||||||
|
generation={0}
|
||||||
|
node={
|
||||||
|
Object {
|
||||||
|
"children": Array [
|
||||||
|
Object {
|
||||||
|
"children": Array [
|
||||||
|
Object {
|
||||||
|
"isSelected": [Function],
|
||||||
|
"label": "Items",
|
||||||
|
"onClick": [Function],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"className": "collectionHeader",
|
||||||
|
"iconSrc": "",
|
||||||
|
"isExpanded": true,
|
||||||
|
"isSelected": [Function],
|
||||||
|
"label": "fakeId",
|
||||||
|
"onClick": [Function],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"isExpanded": true,
|
||||||
|
"label": undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paddingLeft={0}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
@@ -2,7 +2,6 @@ import _ from "underscore";
|
|||||||
import create, { UseStore } from "zustand";
|
import create, { UseStore } from "zustand";
|
||||||
import * as Constants from "../Common/Constants";
|
import * as Constants from "../Common/Constants";
|
||||||
import * as ViewModels from "../Contracts/ViewModels";
|
import * as ViewModels from "../Contracts/ViewModels";
|
||||||
import { userContext } from "../UserContext";
|
|
||||||
import { useSelectedNode } from "./useSelectedNode";
|
import { useSelectedNode } from "./useSelectedNode";
|
||||||
|
|
||||||
interface DatabasesState {
|
interface DatabasesState {
|
||||||
@@ -20,8 +19,6 @@ interface DatabasesState {
|
|||||||
loadDatabaseOffers: () => Promise<void>;
|
loadDatabaseOffers: () => Promise<void>;
|
||||||
isFirstResourceCreated: () => boolean;
|
isFirstResourceCreated: () => boolean;
|
||||||
findSelectedDatabase: () => ViewModels.Database;
|
findSelectedDatabase: () => ViewModels.Database;
|
||||||
validateDatabaseId: (id: string) => boolean;
|
|
||||||
validateCollectionId: (databaseId: string, collectionId: string) => Promise<boolean>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useDatabases: UseStore<DatabasesState> = create((set, get) => ({
|
export const useDatabases: UseStore<DatabasesState> = create((set, get) => ({
|
||||||
@@ -132,17 +129,4 @@ export const useDatabases: UseStore<DatabasesState> = create((set, get) => ({
|
|||||||
|
|
||||||
return selectedNode.collection?.database;
|
return selectedNode.collection?.database;
|
||||||
},
|
},
|
||||||
validateDatabaseId: (id: string): boolean => {
|
|
||||||
return !get().databases.some((database) => database.id() === id);
|
|
||||||
},
|
|
||||||
validateCollectionId: async (databaseId: string, collectionId: string): Promise<boolean> => {
|
|
||||||
const database = get().databases.find((db) => db.id() === databaseId);
|
|
||||||
// For a new tables account, database is undefined when creating the first table
|
|
||||||
if (!database && userContext.apiType === "Tables") {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
await database.loadCollections();
|
|
||||||
return !database.collections().some((collection) => collection.id() === collectionId);
|
|
||||||
},
|
|
||||||
}));
|
}));
|
||||||
|
|||||||
23
src/Index.ts
Normal file
23
src/Index.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import "../less/index.less";
|
||||||
|
import "./Libs/jquery";
|
||||||
|
|
||||||
|
import * as ko from "knockout";
|
||||||
|
|
||||||
|
class Index {
|
||||||
|
public navigationSelection: ko.Observable<string>;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.navigationSelection = ko.observable("quickstart");
|
||||||
|
}
|
||||||
|
|
||||||
|
public quickstart_click() {
|
||||||
|
this.navigationSelection("quickstart");
|
||||||
|
}
|
||||||
|
|
||||||
|
public explorer_click() {
|
||||||
|
this.navigationSelection("explorer");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var index = new Index();
|
||||||
|
ko.applyBindings(index);
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import React, { useState } from "react";
|
|
||||||
import ReactDOM from "react-dom";
|
|
||||||
import Arrow from "../images/Arrow.svg";
|
|
||||||
import CosmosDB_20170829 from "../images/CosmosDB_20170829.svg";
|
|
||||||
import Explorer from "../images/Explorer.svg";
|
|
||||||
import Feedback from "../images/Feedback.svg";
|
|
||||||
import Quickstart from "../images/Quickstart.svg";
|
|
||||||
import "../less/index.less";
|
|
||||||
|
|
||||||
const Index = (): JSX.Element => {
|
|
||||||
const [navigationSelection, setNavigationSelection] = useState("quickstart");
|
|
||||||
|
|
||||||
const quickstart_click = () => {
|
|
||||||
setNavigationSelection("quickstart");
|
|
||||||
};
|
|
||||||
|
|
||||||
const explorer_click = () => {
|
|
||||||
setNavigationSelection("explorer");
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<React.Fragment>
|
|
||||||
<header className="header HeaderBg">
|
|
||||||
<div className="items">
|
|
||||||
<img className="DocDBicon" src={CosmosDB_20170829} alt="Azure Cosmos DB" />
|
|
||||||
<a className="createdocdbacnt" href="https://aka.ms/documentdbcreate" rel="noreferrer" target="_blank">
|
|
||||||
Create an Azure Cosmos DB account <img className="rightarrowimg" src={Arrow} alt="" />
|
|
||||||
</a>
|
|
||||||
<span className="title">Azure Cosmos DB Emulator</span>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
<nav className="fixedleftpane">
|
|
||||||
<div
|
|
||||||
id="Quickstart"
|
|
||||||
onClick={quickstart_click}
|
|
||||||
className={navigationSelection === "quickstart" ? "topSelected" : ""}
|
|
||||||
>
|
|
||||||
<img id="imgiconwidth1" src={Quickstart} alt="Open Quick Start" />
|
|
||||||
<span className="menuQuickStart">Quickstart</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="Explorer" onClick={explorer_click} className={navigationSelection === "explorer" ? "topSelected" : ""}>
|
|
||||||
<img id="imgiconwidth1" src={Explorer} alt="Open Data Explorer" />
|
|
||||||
<span className="menuExplorer">Explorer</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<a className="feedbackstyle" href="https://aka.ms/cosmosdbfeedback?subject=Cosmos%20DB%20Emulator%20Feedback">
|
|
||||||
<img id="imgiconwidth1" src={Feedback} alt="Report Issue" />
|
|
||||||
<span className="menuExplorer">Report Issue</span>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
{navigationSelection === "quickstart" && (
|
|
||||||
<iframe name="quickstart" className="iframe" src="quickstart.html"></iframe>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{navigationSelection === "explorer" && (
|
|
||||||
<iframe name="explorer" className="iframe" src="explorer.html?platform=Emulator"></iframe>
|
|
||||||
)}
|
|
||||||
</React.Fragment>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
ReactDOM.render(<Index />, document.getElementById("root"));
|
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
"CosmosD4Details": "General Purpose Cosmos Compute with 4 vCPUs, 16 GB Memory",
|
"CosmosD4Details": "General Purpose Cosmos Compute with 4 vCPUs, 16 GB Memory",
|
||||||
"CosmosD8Details": "General Purpose Cosmos Compute with 8 vCPUs, 32 GB Memory",
|
"CosmosD8Details": "General Purpose Cosmos Compute with 8 vCPUs, 32 GB Memory",
|
||||||
"CosmosD16Details": "General Purpose Cosmos Compute with 16 vCPUs, 64 GB Memory",
|
"CosmosD16Details": "General Purpose Cosmos Compute with 16 vCPUs, 64 GB Memory",
|
||||||
"ApproximateCost": "Approximate Cost Per Hour",
|
"Cost": "Cost",
|
||||||
"CostText": "Hourly cost of the dedicated gateway resource depends on the SKU selection, number of instances per region, and number of regions.",
|
"CostText": "Hourly cost of the dedicated gateway resource depends on the SKU selection, number of instances per region, and number of regions.",
|
||||||
"ConnectionString": "Connection String",
|
"ConnectionString": "Connection String",
|
||||||
"ConnectionStringText": "To use the dedicated gateway, use the connection string shown in ",
|
"ConnectionStringText": "To use the dedicated gateway, use the connection string shown in ",
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import "../less/TableStyles/fulldatatables.less";
|
|||||||
import "../less/TableStyles/queryBuilder.less";
|
import "../less/TableStyles/queryBuilder.less";
|
||||||
import "../less/tree.less";
|
import "../less/tree.less";
|
||||||
import { CollapsedResourceTree } from "./Common/CollapsedResourceTree";
|
import { CollapsedResourceTree } from "./Common/CollapsedResourceTree";
|
||||||
import { ResourceTreeContainer } from "./Common/ResourceTreeContainer";
|
import { ResourceTree } from "./Common/ResourceTree";
|
||||||
import "./Explorer/Controls/Accordion/AccordionComponent.less";
|
import "./Explorer/Controls/Accordion/AccordionComponent.less";
|
||||||
import "./Explorer/Controls/CollapsiblePanel/CollapsiblePanelComponent.less";
|
import "./Explorer/Controls/CollapsiblePanel/CollapsiblePanelComponent.less";
|
||||||
import { Dialog } from "./Explorer/Controls/Dialog";
|
import { Dialog } from "./Explorer/Controls/Dialog";
|
||||||
@@ -84,11 +84,7 @@ const App: React.FunctionComponent = () => {
|
|||||||
<div id="resourcetree" data-test="resourceTreeId" className="resourceTree">
|
<div id="resourcetree" data-test="resourceTreeId" className="resourceTree">
|
||||||
<div className="collectionsTreeWithSplitter">
|
<div className="collectionsTreeWithSplitter">
|
||||||
{/* Collections Tree Expanded - Start */}
|
{/* Collections Tree Expanded - Start */}
|
||||||
<ResourceTreeContainer
|
<ResourceTree toggleLeftPaneExpanded={toggleLeftPaneExpanded} isLeftPaneExpanded={isLeftPaneExpanded} />
|
||||||
container={explorer}
|
|
||||||
toggleLeftPaneExpanded={toggleLeftPaneExpanded}
|
|
||||||
isLeftPaneExpanded={isLeftPaneExpanded}
|
|
||||||
/>
|
|
||||||
{/* Collections Tree Expanded - End */}
|
{/* Collections Tree Expanded - End */}
|
||||||
{/* Collections Tree Collapsed - Start */}
|
{/* Collections Tree Collapsed - Start */}
|
||||||
<CollapsedResourceTree
|
<CollapsedResourceTree
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ export type Features = {
|
|||||||
readonly enableTtl: boolean;
|
readonly enableTtl: boolean;
|
||||||
readonly executeSproc: boolean;
|
readonly executeSproc: boolean;
|
||||||
readonly enableAadDataPlane: boolean;
|
readonly enableAadDataPlane: boolean;
|
||||||
readonly enableKOResourceTree: boolean;
|
|
||||||
readonly hostedDataExplorer: boolean;
|
readonly hostedDataExplorer: boolean;
|
||||||
readonly junoEndpoint?: string;
|
readonly junoEndpoint?: string;
|
||||||
readonly livyEndpoint?: string;
|
readonly livyEndpoint?: string;
|
||||||
@@ -27,6 +26,8 @@ export type Features = {
|
|||||||
readonly pr?: string;
|
readonly pr?: string;
|
||||||
readonly showMinRUSurvey: boolean;
|
readonly showMinRUSurvey: boolean;
|
||||||
readonly ttl90Days: boolean;
|
readonly ttl90Days: boolean;
|
||||||
|
readonly mongoProxyEndpoint: string;
|
||||||
|
readonly mongoProxyFeatures: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function extractFeatures(given = new URLSearchParams(window.location.search)): Features {
|
export function extractFeatures(given = new URLSearchParams(window.location.search)): Features {
|
||||||
@@ -57,9 +58,10 @@ export function extractFeatures(given = new URLSearchParams(window.location.sear
|
|||||||
enableSDKoperations: "true" === get("enablesdkoperations"),
|
enableSDKoperations: "true" === get("enablesdkoperations"),
|
||||||
enableSpark: "true" === get("enablespark"),
|
enableSpark: "true" === get("enablespark"),
|
||||||
enableTtl: "true" === get("enablettl"),
|
enableTtl: "true" === get("enablettl"),
|
||||||
enableKOResourceTree: "true" === get("enablekoresourcetree"),
|
|
||||||
executeSproc: "true" === get("dataexplorerexecutesproc"),
|
executeSproc: "true" === get("dataexplorerexecutesproc"),
|
||||||
hostedDataExplorer: "true" === get("hosteddataexplorerenabled"),
|
hostedDataExplorer: "true" === get("hosteddataexplorerenabled"),
|
||||||
|
mongoProxyEndpoint: get("mongoproxyendpoint"),
|
||||||
|
mongoProxyFeatures: get("mongoproxyfeatures"),
|
||||||
junoEndpoint: get("junoendpoint"),
|
junoEndpoint: get("junoendpoint"),
|
||||||
livyEndpoint: get("livyendpoint"),
|
livyEndpoint: get("livyendpoint"),
|
||||||
notebookBasePath: get("notebookbasepath"),
|
notebookBasePath: get("notebookbasepath"),
|
||||||
@@ -74,3 +76,7 @@ export function extractFeatures(given = new URLSearchParams(window.location.sear
|
|||||||
partitionKeyDefault: "true" === get("partitionkeytest"),
|
partitionKeyDefault: "true" === get("partitionkeytest"),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function hasFlag(value: string, flag: string): boolean {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,12 +4,7 @@ import { armRequestWithoutPolling } from "../../Utils/arm/request";
|
|||||||
import { selfServeTraceFailure, selfServeTraceStart, selfServeTraceSuccess } from "../SelfServeTelemetryProcessor";
|
import { selfServeTraceFailure, selfServeTraceStart, selfServeTraceSuccess } from "../SelfServeTelemetryProcessor";
|
||||||
import { RefreshResult } from "../SelfServeTypes";
|
import { RefreshResult } from "../SelfServeTypes";
|
||||||
import SqlX from "./SqlX";
|
import SqlX from "./SqlX";
|
||||||
import {
|
import { SqlxServiceResource, UpdateDedicatedGatewayRequestParameters } from "./SqlxTypes";
|
||||||
FetchPricesResponse,
|
|
||||||
RegionsResponse,
|
|
||||||
SqlxServiceResource,
|
|
||||||
UpdateDedicatedGatewayRequestParameters,
|
|
||||||
} from "./SqlxTypes";
|
|
||||||
|
|
||||||
const apiVersion = "2021-04-01-preview";
|
const apiVersion = "2021-04-01-preview";
|
||||||
|
|
||||||
@@ -133,67 +128,3 @@ export const refreshDedicatedGatewayProvisioning = async (): Promise<RefreshResu
|
|||||||
return { isUpdateInProgress: false, updateInProgressMessageTKey: undefined };
|
return { isUpdateInProgress: false, updateInProgressMessageTKey: undefined };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getGeneralPath = (subscriptionId: string, resourceGroup: string, name: string): string => {
|
|
||||||
return `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.DocumentDB/databaseAccounts/${name}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getReadRegions = async (): Promise<Array<string>> => {
|
|
||||||
try {
|
|
||||||
const readRegions = new Array<string>();
|
|
||||||
|
|
||||||
const response = await armRequestWithoutPolling<RegionsResponse>({
|
|
||||||
host: configContext.ARM_ENDPOINT,
|
|
||||||
path: getGeneralPath(userContext.subscriptionId, userContext.resourceGroup, userContext.databaseAccount.name),
|
|
||||||
method: "GET",
|
|
||||||
apiVersion: "2021-04-01-preview",
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.result.location !== undefined) {
|
|
||||||
readRegions.push(response.result.location.replace(" ", "").toLowerCase());
|
|
||||||
} else {
|
|
||||||
for (const location of response.result.locations) {
|
|
||||||
readRegions.push(location.locationName.replace(" ", "").toLowerCase());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return readRegions;
|
|
||||||
} catch (err) {
|
|
||||||
return new Array<string>();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getFetchPricesPathForRegion = (subscriptionId: string): string => {
|
|
||||||
return `/subscriptions/${subscriptionId}/providers/Microsoft.CostManagement/fetchPrices`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getPriceMap = async (regions: Array<string>): Promise<Map<string, Map<string, number>>> => {
|
|
||||||
try {
|
|
||||||
const priceMap = new Map<string, Map<string, number>>();
|
|
||||||
|
|
||||||
for (const region of regions) {
|
|
||||||
const regionPriceMap = new Map<string, number>();
|
|
||||||
|
|
||||||
const response = await armRequestWithoutPolling<FetchPricesResponse>({
|
|
||||||
host: configContext.ARM_ENDPOINT,
|
|
||||||
path: getFetchPricesPathForRegion(userContext.subscriptionId),
|
|
||||||
method: "POST",
|
|
||||||
apiVersion: "2020-01-01-preview",
|
|
||||||
queryParams: {
|
|
||||||
filter:
|
|
||||||
"armRegionName eq '" +
|
|
||||||
region +
|
|
||||||
"' and serviceFamily eq 'Databases' and productName eq 'Azure Cosmos DB Dedicated Gateway - General Purpose'",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const item of response.result.Items) {
|
|
||||||
regionPriceMap.set(item.skuName, item.retailPrice);
|
|
||||||
}
|
|
||||||
priceMap.set(region, regionPriceMap);
|
|
||||||
}
|
|
||||||
|
|
||||||
return priceMap;
|
|
||||||
} catch (err) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -16,13 +16,11 @@ import { BladeType, generateBladeLink } from "../SelfServeUtils";
|
|||||||
import {
|
import {
|
||||||
deleteDedicatedGatewayResource,
|
deleteDedicatedGatewayResource,
|
||||||
getCurrentProvisioningState,
|
getCurrentProvisioningState,
|
||||||
getPriceMap,
|
|
||||||
getReadRegions,
|
|
||||||
refreshDedicatedGatewayProvisioning,
|
refreshDedicatedGatewayProvisioning,
|
||||||
updateDedicatedGatewayResource,
|
updateDedicatedGatewayResource,
|
||||||
} from "./SqlX.rp";
|
} from "./SqlX.rp";
|
||||||
|
|
||||||
const costPerHourDefaultValue: Description = {
|
const costPerHourValue: Description = {
|
||||||
textTKey: "CostText",
|
textTKey: "CostText",
|
||||||
type: DescriptionType.Text,
|
type: DescriptionType.Text,
|
||||||
link: {
|
link: {
|
||||||
@@ -55,10 +53,7 @@ const CosmosD16s = "Cosmos.D16s";
|
|||||||
|
|
||||||
const onSKUChange = (newValue: InputType, currentValues: Map<string, SmartUiInput>): Map<string, SmartUiInput> => {
|
const onSKUChange = (newValue: InputType, currentValues: Map<string, SmartUiInput>): Map<string, SmartUiInput> => {
|
||||||
currentValues.set("sku", { value: newValue });
|
currentValues.set("sku", { value: newValue });
|
||||||
currentValues.set("costPerHour", {
|
currentValues.set("costPerHour", { value: costPerHourValue });
|
||||||
value: calculateCost(newValue as string, currentValues.get("instances").value as number),
|
|
||||||
});
|
|
||||||
|
|
||||||
return currentValues;
|
return currentValues;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -84,11 +79,6 @@ const onNumberOfInstancesChange = (
|
|||||||
} else {
|
} else {
|
||||||
currentValues.set("warningBanner", undefined);
|
currentValues.set("warningBanner", undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
currentValues.set("costPerHour", {
|
|
||||||
value: calculateCost(currentValues.get("sku").value as string, newValue as number),
|
|
||||||
});
|
|
||||||
|
|
||||||
return currentValues;
|
return currentValues;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -121,11 +111,6 @@ const onEnableDedicatedGatewayChange = (
|
|||||||
} as Description,
|
} as Description,
|
||||||
hidden: false,
|
hidden: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
currentValues.set("costPerHour", {
|
|
||||||
value: calculateCost(baselineValues.get("sku").value as string, baselineValues.get("instances").value as number),
|
|
||||||
hidden: false,
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
currentValues.set("warningBanner", {
|
currentValues.set("warningBanner", {
|
||||||
value: {
|
value: {
|
||||||
@@ -137,8 +122,6 @@ const onEnableDedicatedGatewayChange = (
|
|||||||
} as Description,
|
} as Description,
|
||||||
hidden: false,
|
hidden: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
currentValues.set("costPerHour", { value: costPerHourDefaultValue, hidden: true });
|
|
||||||
}
|
}
|
||||||
const sku = currentValues.get("sku");
|
const sku = currentValues.get("sku");
|
||||||
const instances = currentValues.get("instances");
|
const instances = currentValues.get("instances");
|
||||||
@@ -154,6 +137,7 @@ const onEnableDedicatedGatewayChange = (
|
|||||||
disabled: dedicatedGatewayOriginallyEnabled,
|
disabled: dedicatedGatewayOriginallyEnabled,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
currentValues.set("costPerHour", { value: costPerHourValue, hidden: hideAttributes });
|
||||||
currentValues.set("connectionString", {
|
currentValues.set("connectionString", {
|
||||||
value: connectionStringValue,
|
value: connectionStringValue,
|
||||||
hidden: !newValue || !dedicatedGatewayOriginallyEnabled,
|
hidden: !newValue || !dedicatedGatewayOriginallyEnabled,
|
||||||
@@ -193,40 +177,6 @@ const NumberOfInstancesDropdownInfo: Info = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const ApproximateCostDropDownInfo: Info = {
|
|
||||||
messageTKey: "CostText",
|
|
||||||
link: {
|
|
||||||
href: "https://aka.ms/cosmos-db-dedicated-gateway-pricing",
|
|
||||||
textTKey: "DedicatedGatewayPricing",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let priceMap: Map<string, Map<string, number>>;
|
|
||||||
let regions: Array<string>;
|
|
||||||
|
|
||||||
const calculateCost = (skuName: string, instanceCount: number): Description => {
|
|
||||||
try {
|
|
||||||
let costPerHour = 0;
|
|
||||||
for (const region of regions) {
|
|
||||||
const incrementalCost = priceMap.get(region).get(skuName.replace("Cosmos.", ""));
|
|
||||||
if (incrementalCost === undefined) {
|
|
||||||
throw new Error("Value not found in map.");
|
|
||||||
}
|
|
||||||
costPerHour += incrementalCost;
|
|
||||||
}
|
|
||||||
|
|
||||||
costPerHour *= instanceCount;
|
|
||||||
costPerHour = Math.round(costPerHour * 100) / 100;
|
|
||||||
|
|
||||||
return {
|
|
||||||
textTKey: `${costPerHour} USD`,
|
|
||||||
type: DescriptionType.Text,
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
return costPerHourDefaultValue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
@IsDisplayable()
|
@IsDisplayable()
|
||||||
@RefreshOptions({ retryIntervalInMs: 20000 })
|
@RefreshOptions({ retryIntervalInMs: 20000 })
|
||||||
export default class SqlX extends SelfServeBaseClass {
|
export default class SqlX extends SelfServeBaseClass {
|
||||||
@@ -324,15 +274,12 @@ export default class SqlX extends SelfServeBaseClass {
|
|||||||
hidden: true,
|
hidden: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
regions = await getReadRegions();
|
|
||||||
priceMap = await getPriceMap(regions);
|
|
||||||
|
|
||||||
const response = await getCurrentProvisioningState();
|
const response = await getCurrentProvisioningState();
|
||||||
if (response.status && response.status !== "Deleting") {
|
if (response.status && response.status !== "Deleting") {
|
||||||
defaults.set("enableDedicatedGateway", { value: true });
|
defaults.set("enableDedicatedGateway", { value: true });
|
||||||
defaults.set("sku", { value: response.sku, disabled: true });
|
defaults.set("sku", { value: response.sku, disabled: true });
|
||||||
defaults.set("instances", { value: response.instances, disabled: false });
|
defaults.set("instances", { value: response.instances, disabled: false });
|
||||||
defaults.set("costPerHour", { value: calculateCost(response.sku, response.instances) });
|
defaults.set("costPerHour", { value: costPerHourValue });
|
||||||
defaults.set("connectionString", {
|
defaults.set("connectionString", {
|
||||||
value: connectionStringValue,
|
value: connectionStringValue,
|
||||||
hidden: false,
|
hidden: false,
|
||||||
@@ -391,9 +338,8 @@ export default class SqlX extends SelfServeBaseClass {
|
|||||||
})
|
})
|
||||||
instances: number;
|
instances: number;
|
||||||
|
|
||||||
@PropertyInfo(ApproximateCostDropDownInfo)
|
|
||||||
@Values({
|
@Values({
|
||||||
labelTKey: "ApproximateCost",
|
labelTKey: "Cost",
|
||||||
isDynamicDescription: true,
|
isDynamicDescription: true,
|
||||||
})
|
})
|
||||||
costPerHour: string;
|
costPerHour: string;
|
||||||
|
|||||||
@@ -29,23 +29,3 @@ export type UpdateDedicatedGatewayRequestProperties = {
|
|||||||
instanceCount: number;
|
instanceCount: number;
|
||||||
serviceType: string;
|
serviceType: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type FetchPricesResponse = {
|
|
||||||
Items: Array<PriceItem>;
|
|
||||||
NextPageLink: string | undefined;
|
|
||||||
Count: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PriceItem = {
|
|
||||||
retailPrice: number;
|
|
||||||
skuName: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type RegionsResponse = {
|
|
||||||
locations: Array<RegionItem>;
|
|
||||||
location: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type RegionItem = {
|
|
||||||
locationName: string;
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -2,17 +2,14 @@ import create, { UseStore } from "zustand";
|
|||||||
|
|
||||||
export interface SidePanelState {
|
export interface SidePanelState {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
panelWidth: string;
|
|
||||||
panelContent?: JSX.Element;
|
panelContent?: JSX.Element;
|
||||||
headerText?: string;
|
headerText?: string;
|
||||||
openSidePanel: (headerText: string, panelContent: JSX.Element, panelWidth?: string, onClose?: () => void) => void;
|
openSidePanel: (headerText: string, panelContent: JSX.Element, onClose?: () => void) => void;
|
||||||
closeSidePanel: () => void;
|
closeSidePanel: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useSidePanel: UseStore<SidePanelState> = create((set) => ({
|
export const useSidePanel: UseStore<SidePanelState> = create((set) => ({
|
||||||
isOpen: false,
|
isOpen: false,
|
||||||
panelWidth: "440px",
|
openSidePanel: (headerText, panelContent) => set((state) => ({ ...state, headerText, panelContent, isOpen: true })),
|
||||||
openSidePanel: (headerText, panelContent, panelWidth = "440px") =>
|
|
||||||
set((state) => ({ ...state, headerText, panelContent, panelWidth, isOpen: true })),
|
|
||||||
closeSidePanel: () => set((state) => ({ ...state, isOpen: false })),
|
closeSidePanel: () => set((state) => ({ ...state, isOpen: false })),
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -8,7 +8,54 @@
|
|||||||
|
|
||||||
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
|
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<header class="header HeaderBg">
|
||||||
|
<div class="items">
|
||||||
|
<img class="DocDBicon" src="/CosmosDB_20170829.svg" alt="Azure Cosmos DB" />
|
||||||
|
<a class="createdocdbacnt" href="https://aka.ms/documentdbcreate" target="_blank">
|
||||||
|
Create an Azure Cosmos DB account <img class="rightarrowimg" src="/Arrow.svg" alt="" />
|
||||||
|
</a>
|
||||||
|
<span class="title">Azure Cosmos DB Emulator</span>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<nav class="fixedleftpane">
|
||||||
|
<div
|
||||||
|
id="Quickstart"
|
||||||
|
data-bind="click: quickstart_click, css:{ topSelected: navigationSelection() === 'quickstart' }"
|
||||||
|
>
|
||||||
|
<img id="imgiconwidth1" src="/Quickstart.svg" alt="Open Quick Start" />
|
||||||
|
<span class="menuQuickStart">Quickstart</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="Explorer" data-bind="click: explorer_click, css:{ topSelected: navigationSelection() === 'explorer' }">
|
||||||
|
<img id="imgiconwidth1" src="/Explorer.svg" alt="Open Data Explorer" />
|
||||||
|
<span class="menuExplorer">Explorer</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<a class="feedbackstyle" href="https://aka.ms/cosmosdbfeedback?subject=Cosmos%20DB%20Emulator%20Feedback">
|
||||||
|
<img id="imgiconwidth1" src="/Feedback.svg" alt="Report Issue" />
|
||||||
|
<span class="menuExplorer">Report Issue</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<iframe
|
||||||
|
name="quickstart"
|
||||||
|
class="iframe"
|
||||||
|
src="quickstart.html"
|
||||||
|
data-bind="visible: navigationSelection() === 'quickstart'"
|
||||||
|
>
|
||||||
|
</iframe>
|
||||||
|
|
||||||
|
<iframe
|
||||||
|
name="explorer"
|
||||||
|
class="iframe"
|
||||||
|
src="explorer.html?platform=Emulator"
|
||||||
|
data-bind="visible: navigationSelection() === 'explorer'"
|
||||||
|
>
|
||||||
|
</iframe>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,17 +1,18 @@
|
|||||||
import { jest } from "@jest/globals";
|
import { jest } from "@jest/globals";
|
||||||
import "expect-playwright";
|
import "expect-playwright";
|
||||||
|
import { safeClick } from "../utils/safeClick";
|
||||||
import { generateUniqueName } from "../utils/shared";
|
import { generateUniqueName } from "../utils/shared";
|
||||||
import { waitForExplorer } from "../utils/waitForExplorer";
|
|
||||||
jest.setTimeout(120000);
|
jest.setTimeout(120000);
|
||||||
|
|
||||||
test("Cassandra keyspace and table CRUD", async () => {
|
test("Cassandra keyspace and table CRUD", async () => {
|
||||||
const keyspaceId = generateUniqueName("keyspace");
|
const keyspaceId = generateUniqueName("keyspace");
|
||||||
const tableId = generateUniqueName("table");
|
const tableId = generateUniqueName("table");
|
||||||
page.setDefaultTimeout(50000);
|
|
||||||
|
|
||||||
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-cassandra-runner");
|
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-cassandra-runner");
|
||||||
await page.waitForSelector("iframe");
|
await page.waitForSelector("iframe");
|
||||||
const explorer = await waitForExplorer();
|
const explorer = page.frame({
|
||||||
|
name: "explorer",
|
||||||
|
});
|
||||||
|
|
||||||
await explorer.click('[data-test="New Table"]');
|
await explorer.click('[data-test="New Table"]');
|
||||||
await explorer.click('[aria-label="Keyspace id"]');
|
await explorer.click('[aria-label="Keyspace id"]');
|
||||||
@@ -19,9 +20,9 @@ test("Cassandra keyspace and table CRUD", async () => {
|
|||||||
await explorer.click('[aria-label="addCollection-tableId"]');
|
await explorer.click('[aria-label="addCollection-tableId"]');
|
||||||
await explorer.fill('[aria-label="addCollection-tableId"]', tableId);
|
await explorer.fill('[aria-label="addCollection-tableId"]', tableId);
|
||||||
await explorer.click("#sidePanelOkButton");
|
await explorer.click("#sidePanelOkButton");
|
||||||
await explorer.click(`.nodeItem >> text=${keyspaceId}`);
|
await safeClick(explorer, `.nodeItem >> text=${keyspaceId}`);
|
||||||
await explorer.click(`[data-test="${tableId}"] [aria-label="More"]`);
|
await safeClick(explorer, `[data-test="${tableId}"] [aria-label="More"]`);
|
||||||
await explorer.click('button[role="menuitem"]:has-text("Delete Table")');
|
await safeClick(explorer, 'button[role="menuitem"]:has-text("Delete Table")');
|
||||||
await explorer.fill('text=* Confirm by typing the table id >> input[type="text"]', tableId);
|
await explorer.fill('text=* Confirm by typing the table id >> input[type="text"]', tableId);
|
||||||
await explorer.click('[aria-label="OK"]');
|
await explorer.click('[aria-label="OK"]');
|
||||||
await explorer.click(`[data-test="${keyspaceId}"] [aria-label="More"]`);
|
await explorer.click(`[data-test="${keyspaceId}"] [aria-label="More"]`);
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
import { jest } from "@jest/globals";
|
import { jest } from "@jest/globals";
|
||||||
import "expect-playwright";
|
import "expect-playwright";
|
||||||
|
import { safeClick } from "../utils/safeClick";
|
||||||
import { generateDatabaseNameWithTimestamp, generateUniqueName } from "../utils/shared";
|
import { generateDatabaseNameWithTimestamp, generateUniqueName } from "../utils/shared";
|
||||||
import { waitForExplorer } from "../utils/waitForExplorer";
|
|
||||||
jest.setTimeout(240000);
|
jest.setTimeout(240000);
|
||||||
|
|
||||||
test("Graph CRUD", async () => {
|
test("Graph CRUD", async () => {
|
||||||
const databaseId = generateDatabaseNameWithTimestamp();
|
const databaseId = generateDatabaseNameWithTimestamp();
|
||||||
const containerId = generateUniqueName("container");
|
const containerId = generateUniqueName("container");
|
||||||
page.setDefaultTimeout(50000);
|
|
||||||
|
|
||||||
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-gremlin-runner");
|
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-gremlin-runner");
|
||||||
const explorer = await waitForExplorer();
|
await page.waitForSelector("iframe");
|
||||||
|
const explorer = page.frame({
|
||||||
|
name: "explorer",
|
||||||
|
});
|
||||||
|
|
||||||
// Create new database and graph
|
// Create new database and graph
|
||||||
await explorer.click('[data-test="New Graph"]');
|
await explorer.click('[data-test="New Graph"]');
|
||||||
@@ -18,11 +20,11 @@ test("Graph CRUD", async () => {
|
|||||||
await explorer.fill('[aria-label="Graph id"]', containerId);
|
await explorer.fill('[aria-label="Graph id"]', containerId);
|
||||||
await explorer.fill('[aria-label="Partition key"]', "/pk");
|
await explorer.fill('[aria-label="Partition key"]', "/pk");
|
||||||
await explorer.click("#sidePanelOkButton");
|
await explorer.click("#sidePanelOkButton");
|
||||||
await explorer.click(`.nodeItem >> text=${databaseId}`);
|
await safeClick(explorer, `.nodeItem >> text=${databaseId}`);
|
||||||
await explorer.click(`.nodeItem >> text=${containerId}`);
|
await safeClick(explorer, `.nodeItem >> text=${containerId}`);
|
||||||
// Delete database and graph
|
// Delete database and graph
|
||||||
await explorer.click(`[data-test="${containerId}"] [aria-label="More"]`);
|
await safeClick(explorer, `[data-test="${containerId}"] [aria-label="More"]`);
|
||||||
await explorer.click('button[role="menuitem"]:has-text("Delete Graph")');
|
await safeClick(explorer, 'button[role="menuitem"]:has-text("Delete Graph")');
|
||||||
await explorer.fill('text=* Confirm by typing the graph id >> input[type="text"]', containerId);
|
await explorer.fill('text=* Confirm by typing the graph id >> input[type="text"]', containerId);
|
||||||
await explorer.click('[aria-label="OK"]');
|
await explorer.click('[aria-label="OK"]');
|
||||||
await explorer.click(`[data-test="${databaseId}"] [aria-label="More"]`);
|
await explorer.click(`[data-test="${databaseId}"] [aria-label="More"]`);
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
import { jest } from "@jest/globals";
|
import { jest } from "@jest/globals";
|
||||||
import "expect-playwright";
|
import "expect-playwright";
|
||||||
|
import { safeClick } from "../utils/safeClick";
|
||||||
import { generateDatabaseNameWithTimestamp, generateUniqueName } from "../utils/shared";
|
import { generateDatabaseNameWithTimestamp, generateUniqueName } from "../utils/shared";
|
||||||
import { waitForExplorer } from "../utils/waitForExplorer";
|
|
||||||
jest.setTimeout(240000);
|
jest.setTimeout(240000);
|
||||||
|
|
||||||
test("Mongo CRUD", async () => {
|
test("Mongo CRUD", async () => {
|
||||||
const databaseId = generateDatabaseNameWithTimestamp();
|
const databaseId = generateDatabaseNameWithTimestamp();
|
||||||
const containerId = generateUniqueName("container");
|
const containerId = generateUniqueName("container");
|
||||||
page.setDefaultTimeout(50000);
|
|
||||||
|
|
||||||
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-mongo-runner");
|
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-mongo-runner");
|
||||||
const explorer = await waitForExplorer();
|
await page.waitForSelector("iframe");
|
||||||
|
const explorer = page.frame({
|
||||||
|
name: "explorer",
|
||||||
|
});
|
||||||
|
|
||||||
// Create new database and collection
|
// Create new database and collection
|
||||||
await explorer.click('[data-test="New Collection"]');
|
await explorer.click('[data-test="New Collection"]');
|
||||||
@@ -18,10 +20,10 @@ test("Mongo CRUD", async () => {
|
|||||||
await explorer.fill('[aria-label="Collection id"]', containerId);
|
await explorer.fill('[aria-label="Collection id"]', containerId);
|
||||||
await explorer.fill('[aria-label="Shard key"]', "/pk");
|
await explorer.fill('[aria-label="Shard key"]', "/pk");
|
||||||
await explorer.click("#sidePanelOkButton");
|
await explorer.click("#sidePanelOkButton");
|
||||||
await explorer.click(`.nodeItem >> text=${databaseId}`);
|
await safeClick(explorer, `.nodeItem >> text=${databaseId}`);
|
||||||
await explorer.click(`.nodeItem >> text=${containerId}`);
|
await safeClick(explorer, `.nodeItem >> text=${containerId}`);
|
||||||
// Create indexing policy
|
// Create indexing policy
|
||||||
await explorer.click(".nodeItem >> text=Settings");
|
await safeClick(explorer, ".nodeItem >> text=Settings");
|
||||||
await explorer.click('button[role="tab"]:has-text("Indexing Policy")');
|
await explorer.click('button[role="tab"]:has-text("Indexing Policy")');
|
||||||
await explorer.click('[aria-label="Index Field Name 0"]');
|
await explorer.click('[aria-label="Index Field Name 0"]');
|
||||||
await explorer.fill('[aria-label="Index Field Name 0"]', "foo");
|
await explorer.fill('[aria-label="Index Field Name 0"]', "foo");
|
||||||
@@ -32,8 +34,8 @@ test("Mongo CRUD", async () => {
|
|||||||
await explorer.click('[aria-label="Delete index Button"]');
|
await explorer.click('[aria-label="Delete index Button"]');
|
||||||
await explorer.click('[data-test="Save"]');
|
await explorer.click('[data-test="Save"]');
|
||||||
// Delete database and collection
|
// Delete database and collection
|
||||||
await explorer.click(`[data-test="${containerId}"] [aria-label="More"]`);
|
await safeClick(explorer, `[data-test="${containerId}"] [aria-label="More"]`);
|
||||||
await explorer.click('button[role="menuitem"]:has-text("Delete Collection")');
|
await safeClick(explorer, 'button[role="menuitem"]:has-text("Delete Collection")');
|
||||||
await explorer.fill('text=* Confirm by typing the collection id >> input[type="text"]', containerId);
|
await explorer.fill('text=* Confirm by typing the collection id >> input[type="text"]', containerId);
|
||||||
await explorer.click('[aria-label="OK"]');
|
await explorer.click('[aria-label="OK"]');
|
||||||
await explorer.click(`[data-test="${databaseId}"] [aria-label="More"]`);
|
await explorer.click(`[data-test="${databaseId}"] [aria-label="More"]`);
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
import { jest } from "@jest/globals";
|
import { jest } from "@jest/globals";
|
||||||
import "expect-playwright";
|
import "expect-playwright";
|
||||||
|
import { safeClick } from "../utils/safeClick";
|
||||||
import { generateDatabaseNameWithTimestamp, generateUniqueName } from "../utils/shared";
|
import { generateDatabaseNameWithTimestamp, generateUniqueName } from "../utils/shared";
|
||||||
import { waitForExplorer } from "../utils/waitForExplorer";
|
|
||||||
jest.setTimeout(240000);
|
jest.setTimeout(240000);
|
||||||
|
|
||||||
test("Mongo CRUD", async () => {
|
test("Mongo CRUD", async () => {
|
||||||
const databaseId = generateDatabaseNameWithTimestamp();
|
const databaseId = generateDatabaseNameWithTimestamp();
|
||||||
const containerId = generateUniqueName("container");
|
const containerId = generateUniqueName("container");
|
||||||
page.setDefaultTimeout(50000);
|
|
||||||
|
|
||||||
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-mongo32-runner");
|
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-mongo32-runner");
|
||||||
const explorer = await waitForExplorer();
|
await page.waitForSelector("iframe");
|
||||||
|
const explorer = page.frame({
|
||||||
|
name: "explorer",
|
||||||
|
});
|
||||||
|
|
||||||
// Create new database and collection
|
// Create new database and collection
|
||||||
await explorer.click('[data-test="New Collection"]');
|
await explorer.click('[data-test="New Collection"]');
|
||||||
@@ -18,11 +20,11 @@ test("Mongo CRUD", async () => {
|
|||||||
await explorer.fill('[aria-label="Collection id"]', containerId);
|
await explorer.fill('[aria-label="Collection id"]', containerId);
|
||||||
await explorer.fill('[aria-label="Shard key"]', "pk");
|
await explorer.fill('[aria-label="Shard key"]', "pk");
|
||||||
await explorer.click("#sidePanelOkButton");
|
await explorer.click("#sidePanelOkButton");
|
||||||
explorer.click(`.nodeItem >> text=${databaseId}`);
|
await safeClick(explorer, `.nodeItem >> text=${databaseId}`);
|
||||||
explorer.click(`.nodeItem >> text=${containerId}`);
|
await safeClick(explorer, `.nodeItem >> text=${containerId}`);
|
||||||
// Delete database and collection
|
// Delete database and collection
|
||||||
explorer.click(`[data-test="${containerId}"] [aria-label="More"]`);
|
await safeClick(explorer, `[data-test="${containerId}"] [aria-label="More"]`);
|
||||||
explorer.click('button[role="menuitem"]:has-text("Delete Collection")');
|
await safeClick(explorer, 'button[role="menuitem"]:has-text("Delete Collection")');
|
||||||
await explorer.fill('text=* Confirm by typing the collection id >> input[type="text"]', containerId);
|
await explorer.fill('text=* Confirm by typing the collection id >> input[type="text"]', containerId);
|
||||||
await explorer.click('[aria-label="OK"]');
|
await explorer.click('[aria-label="OK"]');
|
||||||
await explorer.click(`[data-test="${databaseId}"] [aria-label="More"]`);
|
await explorer.click(`[data-test="${databaseId}"] [aria-label="More"]`);
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { jest } from "@jest/globals";
|
|||||||
import "expect-playwright";
|
import "expect-playwright";
|
||||||
import fs from "fs";
|
import fs from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import { waitForExplorer } from "../utils/waitForExplorer";
|
|
||||||
jest.setTimeout(240000);
|
jest.setTimeout(240000);
|
||||||
|
|
||||||
const filename = "GettingStarted.ipynb";
|
const filename = "GettingStarted.ipynb";
|
||||||
@@ -12,7 +11,10 @@ fs.copyFileSync(path.join(__dirname, filename), path.join(__dirname, fileToUploa
|
|||||||
|
|
||||||
test("Notebooks", async () => {
|
test("Notebooks", async () => {
|
||||||
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-sql-runner");
|
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-sql-runner");
|
||||||
const explorer = await waitForExplorer();
|
await page.waitForSelector("iframe");
|
||||||
|
const explorer = page.frame({
|
||||||
|
name: "explorer",
|
||||||
|
});
|
||||||
// Upload and Delete Notebook
|
// Upload and Delete Notebook
|
||||||
await explorer.click('[data-test="My Notebooks"] [aria-label="More"]');
|
await explorer.click('[data-test="My Notebooks"] [aria-label="More"]');
|
||||||
await explorer.click('button[role="menuitem"]:has-text("Upload File")');
|
await explorer.click('button[role="menuitem"]:has-text("Upload File")');
|
||||||
|
|||||||
@@ -1,24 +1,27 @@
|
|||||||
import { jest } from "@jest/globals";
|
import { jest } from "@jest/globals";
|
||||||
import "expect-playwright";
|
import "expect-playwright";
|
||||||
|
import { safeClick } from "../utils/safeClick";
|
||||||
import { generateUniqueName } from "../utils/shared";
|
import { generateUniqueName } from "../utils/shared";
|
||||||
import { waitForExplorer } from "../utils/waitForExplorer";
|
|
||||||
jest.setTimeout(120000);
|
jest.setTimeout(120000);
|
||||||
|
|
||||||
test("SQL CRUD", async () => {
|
test("SQL CRUD", async () => {
|
||||||
const databaseId = generateUniqueName("db");
|
const databaseId = generateUniqueName("db");
|
||||||
const containerId = generateUniqueName("container");
|
const containerId = generateUniqueName("container");
|
||||||
page.setDefaultTimeout(50000);
|
|
||||||
|
|
||||||
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-sql-runner");
|
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-sql-runner");
|
||||||
const explorer = await waitForExplorer();
|
await page.waitForSelector("iframe");
|
||||||
|
const explorer = page.frame({
|
||||||
|
name: "explorer",
|
||||||
|
});
|
||||||
|
|
||||||
await explorer.click('[data-test="New Container"]');
|
await explorer.click('[data-test="New Container"]');
|
||||||
await explorer.fill('[aria-label="New database id"]', databaseId);
|
await explorer.fill('[aria-label="New database id"]', databaseId);
|
||||||
await explorer.fill('[aria-label="Container id"]', containerId);
|
await explorer.fill('[aria-label="Container id"]', containerId);
|
||||||
await explorer.fill('[aria-label="Partition key"]', "/pk");
|
await explorer.fill('[aria-label="Partition key"]', "/pk");
|
||||||
await explorer.click("#sidePanelOkButton");
|
await explorer.click("#sidePanelOkButton");
|
||||||
await explorer.click(`.nodeItem >> text=${databaseId}`);
|
await safeClick(explorer, `.nodeItem >> text=${databaseId}`);
|
||||||
await explorer.click(`[data-test="${containerId}"] [aria-label="More"]`);
|
await safeClick(explorer, `[data-test="${containerId}"] [aria-label="More"]`);
|
||||||
await explorer.click('button[role="menuitem"]:has-text("Delete Container")');
|
await safeClick(explorer, 'button[role="menuitem"]:has-text("Delete Container")');
|
||||||
await explorer.fill('text=* Confirm by typing the container id >> input[type="text"]', containerId);
|
await explorer.fill('text=* Confirm by typing the container id >> input[type="text"]', containerId);
|
||||||
await explorer.click('[aria-label="OK"]');
|
await explorer.click('[aria-label="OK"]');
|
||||||
await explorer.click(`[data-test="${databaseId}"] [aria-label="More"]`);
|
await explorer.click(`[data-test="${databaseId}"] [aria-label="More"]`);
|
||||||
|
|||||||
@@ -1,24 +1,25 @@
|
|||||||
import { jest } from "@jest/globals";
|
import { jest } from "@jest/globals";
|
||||||
import "expect-playwright";
|
import "expect-playwright";
|
||||||
|
import { safeClick } from "../utils/safeClick";
|
||||||
import { generateUniqueName } from "../utils/shared";
|
import { generateUniqueName } from "../utils/shared";
|
||||||
import { waitForExplorer } from "../utils/waitForExplorer";
|
|
||||||
|
|
||||||
jest.setTimeout(120000);
|
jest.setTimeout(120000);
|
||||||
|
|
||||||
test("Tables CRUD", async () => {
|
test("Tables CRUD", async () => {
|
||||||
const tableId = generateUniqueName("table");
|
const tableId = generateUniqueName("table");
|
||||||
page.setDefaultTimeout(50000);
|
|
||||||
|
|
||||||
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-tables-runner");
|
await page.goto("https://localhost:1234/testExplorer.html?accountName=portal-tables-runner");
|
||||||
const explorer = await waitForExplorer();
|
await page.waitForSelector("iframe");
|
||||||
|
const explorer = page.frame({
|
||||||
|
name: "explorer",
|
||||||
|
});
|
||||||
|
|
||||||
await page.waitForSelector('text="Querying databases"', { state: "detached" });
|
|
||||||
await explorer.click('[data-test="New Table"]');
|
await explorer.click('[data-test="New Table"]');
|
||||||
await explorer.fill('[aria-label="Table id"]', tableId);
|
await explorer.fill('[aria-label="Table id"]', tableId);
|
||||||
await explorer.click("#sidePanelOkButton");
|
await explorer.click("#sidePanelOkButton");
|
||||||
await explorer.click(`[data-test="TablesDB"]`);
|
await safeClick(explorer, `[data-test="TablesDB"]`);
|
||||||
await explorer.click(`[data-test="${tableId}"] [aria-label="More"]`);
|
await safeClick(explorer, `[data-test="${tableId}"] [aria-label="More"]`);
|
||||||
await explorer.click('button[role="menuitem"]:has-text("Delete Table")');
|
await safeClick(explorer, 'button[role="menuitem"]:has-text("Delete Table")');
|
||||||
await explorer.fill('text=* Confirm by typing the table id >> input[type="text"]', tableId);
|
await explorer.fill('text=* Confirm by typing the table id >> input[type="text"]', tableId);
|
||||||
await explorer.click('[aria-label="OK"]');
|
await explorer.click('[aria-label="OK"]');
|
||||||
await expect(explorer).not.toHaveText(".dataResourceTree", tableId);
|
await expect(explorer).not.toHaveText(".dataResourceTree", tableId);
|
||||||
|
|||||||
11
test/utils/safeClick.ts
Normal file
11
test/utils/safeClick.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { Frame } from "playwright";
|
||||||
|
|
||||||
|
export async function safeClick(page: Frame, selector: string): Promise<void> {
|
||||||
|
// TODO: Remove. Playwright does this for you... mostly.
|
||||||
|
// But our knockout+react setup sometimes leaves dom nodes detached and even playwright can't recover.
|
||||||
|
// Resource tree is particually bad.
|
||||||
|
// Ideally this should only be added as a last resort
|
||||||
|
await page.waitForSelector(selector);
|
||||||
|
await page.waitForTimeout(5000);
|
||||||
|
await page.click(selector);
|
||||||
|
}
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { Frame } from "playwright";
|
|
||||||
|
|
||||||
export const waitForExplorer = async (): Promise<Frame> => {
|
|
||||||
await page.waitForSelector("iframe");
|
|
||||||
await page.waitForTimeout(5000);
|
|
||||||
return page.frame({
|
|
||||||
name: "explorer",
|
|
||||||
});
|
|
||||||
};
|
|
||||||
@@ -26,6 +26,7 @@
|
|||||||
"./src/Common/ObjectCache.ts",
|
"./src/Common/ObjectCache.ts",
|
||||||
"./src/Common/OfferUtility.test.ts",
|
"./src/Common/OfferUtility.test.ts",
|
||||||
"./src/Common/OfferUtility.ts",
|
"./src/Common/OfferUtility.ts",
|
||||||
|
"./src/Common/ResourceTree.tsx",
|
||||||
"./src/Common/Splitter.ts",
|
"./src/Common/Splitter.ts",
|
||||||
"./src/Common/ThemeUtility.ts",
|
"./src/Common/ThemeUtility.ts",
|
||||||
"./src/Common/UrlUtility.ts",
|
"./src/Common/UrlUtility.ts",
|
||||||
@@ -83,6 +84,7 @@
|
|||||||
"./src/Explorer/Tree/AccessibleVerticalList.ts",
|
"./src/Explorer/Tree/AccessibleVerticalList.ts",
|
||||||
"./src/GitHub/GitHubConnector.ts",
|
"./src/GitHub/GitHubConnector.ts",
|
||||||
"./src/HostedExplorerChildFrame.ts",
|
"./src/HostedExplorerChildFrame.ts",
|
||||||
|
"./src/Index.ts",
|
||||||
"./src/Platform/Hosted/Authorization.ts",
|
"./src/Platform/Hosted/Authorization.ts",
|
||||||
"./src/Platform/Hosted/Components/MeControl.test.tsx",
|
"./src/Platform/Hosted/Components/MeControl.test.tsx",
|
||||||
"./src/Platform/Hosted/Components/MeControl.tsx",
|
"./src/Platform/Hosted/Components/MeControl.tsx",
|
||||||
@@ -140,7 +142,7 @@
|
|||||||
"./src/userContext.test.ts",
|
"./src/userContext.test.ts",
|
||||||
"src/Common/EntityValue.tsx",
|
"src/Common/EntityValue.tsx",
|
||||||
"./src/Platform/Hosted/Components/SwitchAccount.tsx",
|
"./src/Platform/Hosted/Components/SwitchAccount.tsx",
|
||||||
"./src/Platform/Hosted/Components/SwitchSubscription.tsx"
|
"./src/Platform/Hosted/Components/SwitchSubscription.tsx",
|
||||||
],
|
],
|
||||||
"include": [
|
"include": [
|
||||||
"src/CellOutputViewer/transforms/**/*",
|
"src/CellOutputViewer/transforms/**/*",
|
||||||
@@ -166,4 +168,4 @@
|
|||||||
"src/Terminal/**/*",
|
"src/Terminal/**/*",
|
||||||
"src/Utils/arm/**/*"
|
"src/Utils/arm/**/*"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -198,7 +198,7 @@ module.exports = function (_env = {}, argv = {}) {
|
|||||||
mode: mode,
|
mode: mode,
|
||||||
entry: {
|
entry: {
|
||||||
main: "./src/Main.tsx",
|
main: "./src/Main.tsx",
|
||||||
index: "./src/Index.tsx",
|
index: "./src/Index.ts",
|
||||||
quickstart: "./src/quickstart.ts",
|
quickstart: "./src/quickstart.ts",
|
||||||
hostedExplorer: "./src/HostedExplorer.tsx",
|
hostedExplorer: "./src/HostedExplorer.tsx",
|
||||||
testExplorer: "./test/testExplorer/TestExplorer.ts",
|
testExplorer: "./test/testExplorer/TestExplorer.ts",
|
||||||
@@ -264,6 +264,17 @@ module.exports = function (_env = {}, argv = {}) {
|
|||||||
"Access-Control-Allow-Methods": "*",
|
"Access-Control-Allow-Methods": "*",
|
||||||
},
|
},
|
||||||
proxy: {
|
proxy: {
|
||||||
|
"/api/mongo": {
|
||||||
|
target: "https://juno-test2.documents-dev.windows-int.net/api/mongo/test",
|
||||||
|
changeOrigin: true,
|
||||||
|
logLevel: "debug",
|
||||||
|
bypass: (req, res) => {
|
||||||
|
if (req.method === "OPTIONS") {
|
||||||
|
res.statusCode = 200;
|
||||||
|
res.send();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
"/api": {
|
"/api": {
|
||||||
target: "https://main.documentdb.ext.azure.com",
|
target: "https://main.documentdb.ext.azure.com",
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
|
|||||||
Reference in New Issue
Block a user