save command refactor - moved to defining component

This commit is contained in:
Jan Prochazka 2021-04-08 07:58:06 +02:00
parent b553dbb6b9
commit c48b058b9d
9 changed files with 238 additions and 170 deletions

View File

@ -110,11 +110,7 @@ export abstract class GridDisplay {
} }
reload() { reload() {
this.setCache(cache => ({ this.setCache(reloadDataCacheFunc);
// ...cache,
...createGridCache(),
refreshTime: new Date().getTime(),
}));
} }
includeInColumnSet(field: keyof GridConfigColumns, uniqueName: string, isIncluded: boolean) { includeInColumnSet(field: keyof GridConfigColumns, uniqueName: string, isIncluded: boolean) {
@ -586,3 +582,11 @@ export abstract class GridDisplay {
})); }));
} }
} }
export function reloadDataCacheFunc(cache: GridCache): GridCache {
return {
// ...cache,
...createGridCache(),
refreshTime: new Date().getTime(),
};
}

View File

@ -128,34 +128,6 @@
// $: console.log('GRIDER', grider); // $: console.log('GRIDER', grider);
// $: if (onChangeGrider) onChangeGrider(grider); // $: if (onChangeGrider) onChangeGrider(grider);
async function handleConfirmChange(changeSet) {
const resp = await axiosInstance.request({
url: 'database-connections/update-collection',
method: 'post',
params: {
conid,
database,
},
data: { changeSet },
});
const { errorMessage } = resp.data || {};
if (errorMessage) {
showModal(ErrorMessageModal, { title: 'Error when saving', message: errorMessage });
} else {
dispatchChangeSet({ type: 'reset', value: createChangeSet() });
display.reload();
}
}
function handleSave() {
const json = changeSetState && changeSetState.value;
showModal(ConfirmNoSqlModal, {
json,
onConfirm: () => handleConfirmChange(json),
engine: display.engine,
});
}
function exportGrid() { function exportGrid() {
const initialValues: any = {}; const initialValues: any = {};
initialValues.sourceStorageType = 'query'; initialValues.sourceStorageType = 'query';
@ -219,5 +191,4 @@
bind:loadedRows bind:loadedRows
frameSelection={!!macroPreview} frameSelection={!!macroPreview}
{grider} {grider}
onSave={handleSave}
/> />

View File

@ -12,18 +12,6 @@
onClick: () => getCurrentDataGrid().refresh(), onClick: () => getCurrentDataGrid().refresh(),
}); });
registerCommand({
id: 'dataGrid.save',
group: 'save',
category: 'Data grid',
name: 'Save',
// keyText: 'Ctrl+S',
toolbar: true,
icon: 'icon save',
testEnabled: () => getCurrentDataGrid()?.getGrider()?.allowSave,
onClick: () => getCurrentDataGrid().save(),
});
registerCommand({ registerCommand({
id: 'dataGrid.revertRowChanges', id: 'dataGrid.revertRowChanges',
category: 'Data grid', category: 'Data grid',
@ -261,7 +249,6 @@
export let onReferenceSourceChanged = undefined; export let onReferenceSourceChanged = undefined;
export let onReferenceClick = undefined; export let onReferenceClick = undefined;
// export let onSelectedCellsPublishedChanged = undefined; // export let onSelectedCellsPublishedChanged = undefined;
export let onSave;
export let focusOnVisible = false; export let focusOnVisible = false;
export let onExportGrid = null; export let onExportGrid = null;
export let onOpenQuery = null; export let onOpenQuery = null;
@ -303,10 +290,6 @@
display.reload(); display.reload();
} }
export function save() {
if (onSave) onSave();
}
export function getGrider() { export function getGrider() {
return grider; return grider;
} }
@ -491,10 +474,6 @@
editJsonRowDocument(grider, rowIndex); editJsonRowDocument(grider, rowIndex);
} }
// export function getGeneralAllowSave() {
// return generalAllowSave;
// }
$: autofillMarkerCell = $: autofillMarkerCell =
selectedCells && selectedCells.length > 0 && _.uniq(selectedCells.map(x => x[0])).length == 1 selectedCells && selectedCells.length > 0 && _.uniq(selectedCells.map(x => x[0])).length == 1
? [_.max(selectedCells.map(x => x[0])), _.max(selectedCells.map(x => x[1]))] ? [_.max(selectedCells.map(x => x[0])), _.max(selectedCells.map(x => x[1]))]
@ -994,12 +973,12 @@
// if (action.mode == 'save') setTimeout(handleSave, 0); // if (action.mode == 'save') setTimeout(handleSave, 0);
return {}; return {};
} }
case 'shouldSave': { // case 'shouldSave': {
return { // return {
...state, // ...state,
shouldSave: true, // shouldSave: true,
}; // };
} // }
} }
return {}; return {};
}, {}); }, {});
@ -1019,7 +998,7 @@
{ command: 'dataGrid.switchToJson', hideDisabled: true }, { command: 'dataGrid.switchToJson', hideDisabled: true },
{ command: 'dataGrid.editJsonDocument', hideDisabled: true }, { command: 'dataGrid.editJsonDocument', hideDisabled: true },
{ divider: true }, { divider: true },
{ command: 'dataGrid.save' }, { placeTag: 'save' },
{ command: 'dataGrid.revertRowChanges' }, { command: 'dataGrid.revertRowChanges' },
{ command: 'dataGrid.revertAllChanges' }, { command: 'dataGrid.revertAllChanges' },
{ command: 'dataGrid.deleteSelectedRows' }, { command: 'dataGrid.deleteSelectedRows' },

View File

@ -102,35 +102,6 @@
// $: console.log('GRIDER', grider); // $: console.log('GRIDER', grider);
// $: if (onChangeGrider) onChangeGrider(grider); // $: if (onChangeGrider) onChangeGrider(grider);
async function handleConfirmSql(sql) {
const resp = await axiosInstance.request({
url: 'database-connections/query-data',
method: 'post',
params: {
conid,
database,
},
data: { sql },
});
const { errorMessage } = resp.data || {};
if (errorMessage) {
showModal(ErrorMessageModal, { title: 'Error when saving', message: errorMessage });
} else {
dispatchChangeSet({ type: 'reset', value: createChangeSet() });
display.reload();
}
}
function handleSave() {
const script = changeSetToSql(changeSetState && changeSetState.value, display.dbinfo);
const sql = scriptToSql(display.driver, script);
showModal(ConfirmSqlModal, {
sql,
onConfirm: () => handleConfirmSql(sql),
engine: display.engine,
});
}
function exportGrid() { function exportGrid() {
const initialValues: any = {}; const initialValues: any = {};
initialValues.sourceStorageType = 'query'; initialValues.sourceStorageType = 'query';
@ -196,5 +167,4 @@
bind:selectedCellsPublished bind:selectedCellsPublished
frameSelection={!!macroPreview} frameSelection={!!macroPreview}
{grider} {grider}
onSave={handleSave}
/> />

View File

@ -10,16 +10,16 @@
onClick: () => getCurrentDataForm().switchToTable(), onClick: () => getCurrentDataForm().switchToTable(),
}); });
registerCommand({ // registerCommand({
id: 'dataForm.save', // id: 'dataForm.save',
group: 'save', // group: 'save',
category: 'Data form', // category: 'Data form',
name: 'Save', // name: 'Save',
toolbar: true, // toolbar: true,
icon: 'icon save', // icon: 'icon save',
testEnabled: () => getCurrentDataForm()?.getFormer()?.allowSave, // testEnabled: () => getCurrentDataForm()?.getFormer()?.allowSave,
onClick: () => getCurrentDataForm().save(), // onClick: () => getCurrentDataForm().save(),
}); // });
registerCommand({ registerCommand({
id: 'dataForm.copyToClipboard', id: 'dataForm.copyToClipboard',
@ -164,7 +164,7 @@
import axiosInstance from '../utility/axiosInstance'; import axiosInstance from '../utility/axiosInstance';
import { copyTextToClipboard } from '../utility/clipboard'; import { copyTextToClipboard } from '../utility/clipboard';
import contextMenu from '../utility/contextMenu'; import contextMenu, { getContextMenu, registerMenu } from '../utility/contextMenu';
import createActivator, { getActiveComponent } from '../utility/createActivator'; import createActivator, { getActiveComponent } from '../utility/createActivator';
import createReducer from '../utility/createReducer'; import createReducer from '../utility/createReducer';
import keycodes from '../utility/keycodes'; import keycodes from '../utility/keycodes';
@ -181,7 +181,6 @@
export let isLoading; export let isLoading;
export let former; export let former;
export let formDisplay; export let formDisplay;
export let onSave;
export let onNavigate; export let onNavigate;
let wrapperHeight = 1; let wrapperHeight = 1;
@ -228,14 +227,14 @@
})); }));
} }
export function save() { // export function save() {
if ($inplaceEditorState.cell) { // if ($inplaceEditorState.cell) {
// @ts-ignore // // @ts-ignore
dispatchInsplaceEditor({ type: 'shouldSave' }); // dispatchInsplaceEditor({ type: 'shouldSave' });
return; // return;
} // }
if (onSave) onSave(); // if (onSave) onSave();
} // }
export function setNull() { export function setNull() {
if (isDataCell(currentCell)) { if (isDataCell(currentCell)) {
@ -332,36 +331,35 @@
// if (action.mode == 'save') setTimeout(handleSave, 0); // if (action.mode == 'save') setTimeout(handleSave, 0);
return {}; return {};
} }
case 'shouldSave': { // case 'shouldSave': {
return { // return {
...state, // ...state,
shouldSave: true, // shouldSave: true,
}; // };
} // }
} }
return {}; return {};
}, {}); }, {});
function createMenu() { registerMenu(
return [ { command: 'dataForm.switchToTable' },
{ command: 'dataForm.switchToTable' }, { command: 'dataForm.copyToClipboard' },
{ command: 'dataForm.copyToClipboard' }, { divider: true },
{ divider: true }, { command: 'dataForm.filterSelected' },
{ command: 'dataForm.filterSelected' }, { command: 'dataForm.addToFilter' },
{ command: 'dataForm.addToFilter' }, { divider: true },
{ divider: true }, { placeTag: 'save' },
{ command: 'dataForm.save' }, { command: 'dataForm.revertRowChanges' },
{ command: 'dataForm.revertRowChanges' }, { command: 'dataForm.setNull' },
{ command: 'dataForm.setNull' }, { divider: true },
{ divider: true }, { command: 'dataForm.undo' },
{ command: 'dataForm.undo' }, { command: 'dataForm.redo' },
{ command: 'dataForm.redo' }, { divider: true },
{ divider: true }, { command: 'dataForm.goToFirst' },
{ command: 'dataForm.goToFirst' }, { command: 'dataForm.goToPrevious' },
{ command: 'dataForm.goToPrevious' }, { command: 'dataForm.goToNext' },
{ command: 'dataForm.goToNext' }, { command: 'dataForm.goToLast' }
{ command: 'dataForm.goToLast' }, );
]; const menu = getContextMenu();
}
function handleKeyDown(event) { function handleKeyDown(event) {
if ($inplaceEditorState.cell) return; if ($inplaceEditorState.cell) return;
@ -437,7 +435,7 @@
</script> </script>
<div class="outer"> <div class="outer">
<div class="wrapper" use:contextMenu={createMenu} bind:clientHeight={wrapperHeight}> <div class="wrapper" use:contextMenu={menu} bind:clientHeight={wrapperHeight}>
{#each columnChunks as chunk, chunkIndex} {#each columnChunks as chunk, chunkIndex}
<table on:mousedown={handleTableMouseDown}> <table on:mousedown={handleTableMouseDown}>
{#each chunk as col, rowIndex} {#each chunk as col, rowIndex}

View File

@ -131,34 +131,34 @@
$: if (onReferenceSourceChanged && rowData) onReferenceSourceChanged([rowData], loadedTime); $: if (onReferenceSourceChanged && rowData) onReferenceSourceChanged([rowData], loadedTime);
async function handleConfirmSql(sql) { // async function handleConfirmSql(sql) {
const resp = await axiosInstance.request({ // const resp = await axiosInstance.request({
url: 'database-connections/query-data', // url: 'database-connections/query-data',
method: 'post', // method: 'post',
params: { // params: {
conid, // conid,
database, // database,
}, // },
data: { sql }, // data: { sql },
}); // });
const { errorMessage } = resp.data || {}; // const { errorMessage } = resp.data || {};
if (errorMessage) { // if (errorMessage) {
showModal(ErrorMessageModal, { title: 'Error when saving', message: errorMessage }); // showModal(ErrorMessageModal, { title: 'Error when saving', message: errorMessage });
} else { // } else {
dispatchChangeSet({ type: 'reset', value: createChangeSet() }); // dispatchChangeSet({ type: 'reset', value: createChangeSet() });
formDisplay.reload(); // formDisplay.reload();
} // }
} // }
function handleSave() { // function handleSave() {
const script = changeSetToSql(changeSetState && changeSetState.value, formDisplay.dbinfo); // const script = changeSetToSql(changeSetState && changeSetState.value, formDisplay.dbinfo);
const sql = scriptToSql(formDisplay.driver, script); // const sql = scriptToSql(formDisplay.driver, script);
showModal(ConfirmSqlModal, { // showModal(ConfirmSqlModal, {
sql, // sql,
onConfirm: () => handleConfirmSql(sql), // onConfirm: () => handleConfirmSql(sql),
engine: formDisplay.engine, // engine: formDisplay.engine,
}); // });
} // }
</script> </script>
<FormView <FormView
@ -167,6 +167,5 @@
isLoading={isLoadingData} isLoading={isLoadingData}
{allRowCount} {allRowCount}
{rowCountBefore} {rowCountBefore}
onSave={handleSave}
onNavigate={handleNavigate} onNavigate={handleNavigate}
/> />

View File

@ -1,6 +1,20 @@
<script lang="ts" context="module"> <script lang="ts" context="module">
const getCurrentEditor = () => getActiveComponent('CollectionDataTab');
export const matchingProps = ['conid', 'database', 'schemaName', 'pureName']; export const matchingProps = ['conid', 'database', 'schemaName', 'pureName'];
export const allowAddToFavorites = props => true; export const allowAddToFavorites = props => true;
registerCommand({
id: 'collectionTable.save',
group: 'save',
category: 'Collection data',
name: 'Save',
// keyText: 'Ctrl+S',
toolbar: true,
icon: 'icon save',
testEnabled: () => getCurrentEditor()?.canSave(),
onClick: () => getCurrentEditor().save(),
});
</script> </script>
<script lang="ts"> <script lang="ts">
@ -13,6 +27,7 @@
createGridConfig, createGridConfig,
TableFormViewDisplay, TableFormViewDisplay,
CollectionGridDisplay, CollectionGridDisplay,
changeSetContainsChanges,
} from 'dbgate-datalib'; } from 'dbgate-datalib';
import { findEngineDriver } from 'dbgate-tools'; import { findEngineDriver } from 'dbgate-tools';
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
@ -22,6 +37,13 @@
import { useCollectionInfo, useConnectionInfo } from '../utility/metadataLoaders'; import { useCollectionInfo, useConnectionInfo } from '../utility/metadataLoaders';
import { extensions } from '../stores'; import { extensions } from '../stores';
import CollectionJsonView from '../jsonview/CollectionJsonView.svelte'; import CollectionJsonView from '../jsonview/CollectionJsonView.svelte';
import createActivator, { getActiveComponent } from '../utility/createActivator';
import axiosInstance from '../utility/axiosInstance';
import { showModal } from '../modals/modalTools';
import ErrorMessageModal from '../modals/ErrorMessageModal.svelte';
import ConfirmNoSqlModal from '../modals/ConfirmNoSqlModal.svelte';
import registerCommand from '../commands/registerCommand';
import { registerMenu } from '../utility/contextMenu';
export let tabid; export let tabid;
export let conid; export let conid;
@ -31,6 +53,8 @@
let loadedRows; let loadedRows;
export const activator = createActivator('CollectionDataTab', true);
const config = useGridConfig(tabid); const config = useGridConfig(tabid);
const cache = writable(createGridCache()); const cache = writable(createGridCache());
@ -58,6 +82,40 @@
) )
: null; : null;
// $: console.log('LOADED ROWS MONGO', loadedRows); // $: console.log('LOADED ROWS MONGO', loadedRows);
async function handleConfirmChange(changeSet) {
const resp = await axiosInstance.request({
url: 'database-connections/update-collection',
method: 'post',
params: {
conid,
database,
},
data: { changeSet },
});
const { errorMessage } = resp.data || {};
if (errorMessage) {
showModal(ErrorMessageModal, { title: 'Error when saving', message: errorMessage });
} else {
dispatchChangeSet({ type: 'reset', value: createChangeSet() });
display?.reload();
}
}
export function canSave() {
return changeSetContainsChanges($changeSetStore?.value);
}
export function save() {
const json = $changeSetStore?.value;
showModal(ConfirmNoSqlModal, {
json,
onConfirm: () => handleConfirmChange(json),
engine: display.engine,
});
}
registerMenu({ command: 'collectionTable.save', tag: 'save' });
</script> </script>
<DataGrid <DataGrid

View File

@ -1,5 +1,22 @@
<script lang="ts" context="module">
const getCurrentEditor = () => getActiveComponent('FreeTableTab');
registerCommand({
id: 'freeTable.save',
group: 'save',
category: 'Table data',
name: 'Save',
// keyText: 'Ctrl+S',
toolbar: true,
icon: 'icon save',
testEnabled: () => getCurrentEditor() != null,
onClick: () => getCurrentEditor().save(),
});
</script>
<script lang="ts"> <script lang="ts">
import { createFreeTableModel, runMacro } from 'dbgate-datalib'; import { createFreeTableModel, runMacro } from 'dbgate-datalib';
import registerCommand from '../commands/registerCommand';
import DataGrid from '../datagrid/DataGrid.svelte'; import DataGrid from '../datagrid/DataGrid.svelte';
import ErrorInfo from '../elements/ErrorInfo.svelte'; import ErrorInfo from '../elements/ErrorInfo.svelte';
import LoadingInfo from '../elements/LoadingInfo.svelte'; import LoadingInfo from '../elements/LoadingInfo.svelte';
@ -10,6 +27,8 @@
import useEditorData from '../query/useEditorData'; import useEditorData from '../query/useEditorData';
import axiosInstance from '../utility/axiosInstance'; import axiosInstance from '../utility/axiosInstance';
import { changeTab } from '../utility/common'; import { changeTab } from '../utility/common';
import { registerMenu } from '../utility/contextMenu';
import createActivator, { getActiveComponent } from '../utility/createActivator';
import createUndoReducer from '../utility/createUndoReducer'; import createUndoReducer from '../utility/createUndoReducer';
import useGridConfig from '../utility/useGridConfig'; import useGridConfig from '../utility/useGridConfig';
@ -18,6 +37,8 @@
export let archiveFolder; export let archiveFolder;
export let archiveFile; export let archiveFile;
export const activator = createActivator('FreeTableTab', true);
const config = useGridConfig(tabid); const config = useGridConfig(tabid);
const [modelState, dispatchModel] = createUndoReducer(createFreeTableModel()); const [modelState, dispatchModel] = createUndoReducer(createFreeTableModel());
@ -37,7 +58,7 @@
$: setEditorData($modelState.value); $: setEditorData($modelState.value);
function handleSave() { export function save() {
showModal(SaveArchiveModal, { showModal(SaveArchiveModal, {
folder: archiveFolder, folder: archiveFolder,
file: archiveFile, file: archiveFile,
@ -58,6 +79,8 @@
const newModel = runMacro(macro, params, $modelState.value, false, cells); const newModel = runMacro(macro, params, $modelState.value, false, cells);
dispatchModel({ type: 'set', value: newModel }); dispatchModel({ type: 'set', value: newModel });
} }
registerMenu({ command: 'freeTable.save', tag: 'save' });
</script> </script>
{#if isLoading} {#if isLoading}
@ -70,7 +93,6 @@
setConfig={config.update} setConfig={config.update}
modelState={$modelState} modelState={$modelState}
{dispatchModel} {dispatchModel}
onSave={handleSave}
focusOnVisible focusOnVisible
gridCoreComponent={FreeTableGridCore} gridCoreComponent={FreeTableGridCore}
freeTableColumn freeTableColumn

View File

@ -1,4 +1,18 @@
<script lang="ts" context="module"> <script lang="ts" context="module">
const getCurrentEditor = () => getActiveComponent('TableDataTab');
registerCommand({
id: 'tableData.save',
group: 'save',
category: 'Table data',
name: 'Save',
// keyText: 'Ctrl+S',
toolbar: true,
icon: 'icon save',
testEnabled: () => getCurrentEditor()?.canSave(),
onClick: () => getCurrentEditor().save(),
});
export const matchingProps = ['conid', 'database', 'schemaName', 'pureName']; export const matchingProps = ['conid', 'database', 'schemaName', 'pureName'];
export const allowAddToFavorites = props => true; export const allowAddToFavorites = props => true;
</script> </script>
@ -8,6 +22,8 @@
import TableDataGrid from '../datagrid/TableDataGrid.svelte'; import TableDataGrid from '../datagrid/TableDataGrid.svelte';
import useGridConfig from '../utility/useGridConfig'; import useGridConfig from '../utility/useGridConfig';
import { import {
changeSetContainsChanges,
changeSetToSql,
createChangeSet, createChangeSet,
createGridCache, createGridCache,
createGridConfig, createGridConfig,
@ -15,9 +31,20 @@
TableGridDisplay, TableGridDisplay,
} from 'dbgate-datalib'; } from 'dbgate-datalib';
import { findEngineDriver } from 'dbgate-tools'; import { findEngineDriver } from 'dbgate-tools';
import { reloadDataCacheFunc } from 'dbgate-datalib';
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import createUndoReducer from '../utility/createUndoReducer'; import createUndoReducer from '../utility/createUndoReducer';
import invalidateCommands from '../commands/invalidateCommands'; import invalidateCommands from '../commands/invalidateCommands';
import axiosInstance from '../utility/axiosInstance';
import { showModal } from '../modals/modalTools';
import ErrorMessageModal from '../modals/ErrorMessageModal.svelte';
import { useConnectionInfo, useDatabaseInfo } from '../utility/metadataLoaders';
import { scriptToSql } from 'dbgate-sqltree';
import { extensions } from '../stores';
import ConfirmSqlModal from '../modals/ConfirmSqlModal.svelte';
import createActivator, { getActiveComponent } from '../utility/createActivator';
import registerCommand from '../commands/registerCommand';
import { registerMenu } from '../utility/contextMenu';
export let tabid; export let tabid;
export let conid; export let conid;
@ -25,15 +52,55 @@
export let schemaName; export let schemaName;
export let pureName; export let pureName;
export const activator = createActivator('TableDataTab', true);
const config = useGridConfig(tabid); const config = useGridConfig(tabid);
const cache = writable(createGridCache()); const cache = writable(createGridCache());
const dbinfo = useDatabaseInfo({ conid, database });
$: connection = useConnectionInfo({ conid });
const [changeSetStore, dispatchChangeSet] = createUndoReducer(createChangeSet()); const [changeSetStore, dispatchChangeSet] = createUndoReducer(createChangeSet());
async function handleConfirmSql(sql) {
const resp = await axiosInstance.request({
url: 'database-connections/query-data',
method: 'post',
params: {
conid,
database,
},
data: { sql },
});
const { errorMessage } = resp.data || {};
if (errorMessage) {
showModal(ErrorMessageModal, { title: 'Error when saving', message: errorMessage });
} else {
dispatchChangeSet({ type: 'reset', value: createChangeSet() });
cache.update(reloadDataCacheFunc);
}
}
export function save() {
const driver = findEngineDriver($connection, $extensions);
const script = changeSetToSql($changeSetStore?.value, $dbinfo);
const sql = scriptToSql(driver, script);
showModal(ConfirmSqlModal, {
sql,
onConfirm: () => handleConfirmSql(sql),
engine: driver.engine,
});
}
export function canSave() {
return changeSetContainsChanges($changeSetStore?.value);
}
$: { $: {
$changeSetStore; $changeSetStore;
invalidateCommands(); invalidateCommands();
} }
registerMenu({ command: 'tableData.save', tag: 'save' });
</script> </script>
<TableDataGrid <TableDataGrid