2020-10-02 15:10:00 +00:00
|
|
|
/**
|
|
|
|
* Importer manages an import files to Grist tables
|
|
|
|
* TODO: hidden tables should be also deleted on page refresh, error...
|
|
|
|
*/
|
|
|
|
// tslint:disable:no-console
|
|
|
|
|
2021-11-09 20:03:12 +00:00
|
|
|
import {GristDoc} from 'app/client/components/GristDoc';
|
2020-10-02 15:10:00 +00:00
|
|
|
import {buildParseOptionsForm, ParseOptionValues} from 'app/client/components/ParseOptions';
|
2021-11-09 20:03:12 +00:00
|
|
|
import {PluginScreen} from 'app/client/components/PluginScreen';
|
|
|
|
import {FocusLayer} from 'app/client/lib/FocusLayer';
|
2020-10-02 15:10:00 +00:00
|
|
|
import {ImportSourceElement} from 'app/client/lib/ImportSourceElement';
|
2021-08-03 10:34:05 +00:00
|
|
|
import {fetchURL, isDriveUrl, selectFiles, uploadFiles} from 'app/client/lib/uploads';
|
2020-10-02 15:10:00 +00:00
|
|
|
import {reportError} from 'app/client/models/AppModel';
|
2021-11-09 20:03:12 +00:00
|
|
|
import {ColumnRec, ViewFieldRec, ViewSectionRec} from 'app/client/models/DocModel';
|
|
|
|
import {SortedRowSet} from 'app/client/models/rowset';
|
|
|
|
import {buildHighlightedCode} from 'app/client/ui/CodeHighlight';
|
|
|
|
import {openFilePicker} from 'app/client/ui/FileDialog';
|
2020-10-02 15:10:00 +00:00
|
|
|
import {bigBasicButton, bigPrimaryButton} from 'app/client/ui2018/buttons';
|
|
|
|
import {colors, testId, vars} from 'app/client/ui2018/cssVars';
|
|
|
|
import {icon} from 'app/client/ui2018/icons';
|
2021-11-09 20:03:12 +00:00
|
|
|
import {IOptionFull, linkSelect, menu, menuDivider, menuItem, multiSelect} from 'app/client/ui2018/menus';
|
2021-08-05 15:12:46 +00:00
|
|
|
import {cssModalButtons, cssModalTitle} from 'app/client/ui2018/modals';
|
2021-11-09 20:03:12 +00:00
|
|
|
import {loadingSpinner} from 'app/client/ui2018/loaders';
|
|
|
|
import {openFormulaEditor} from 'app/client/widgets/FieldEditor';
|
2021-12-13 09:11:18 +00:00
|
|
|
import {DataSourceTransformed, DestId, ImportResult, ImportTableResult, MergeOptions,
|
|
|
|
MergeOptionsMap, MergeStrategy, NEW_TABLE, SKIP_TABLE,
|
|
|
|
TransformColumn, TransformRule, TransformRuleMap} from 'app/common/ActiveDocAPI';
|
2021-11-09 20:03:12 +00:00
|
|
|
import {DisposableWithEvents} from 'app/common/DisposableWithEvents';
|
|
|
|
import {byteString} from 'app/common/gutil';
|
2021-09-30 08:19:22 +00:00
|
|
|
import {FetchUrlOptions, UploadResult} from 'app/common/uploads';
|
2020-10-02 15:10:00 +00:00
|
|
|
import {ParseOptions, ParseOptionSchema} from 'app/plugin/FileParserAPI';
|
2021-11-09 20:03:12 +00:00
|
|
|
import {Computed, dom, DomContents, fromKo, Holder, IDisposable, MultiHolder, MutableObsArray, obsArray, Observable,
|
2021-09-15 06:12:34 +00:00
|
|
|
styled} from 'grainjs';
|
2021-11-09 20:03:12 +00:00
|
|
|
import {labeledSquareCheckbox} from 'app/client/ui2018/checkbox';
|
|
|
|
import {ACCESS_DENIED, AUTH_INTERRUPTED, canReadPrivateFiles, getGoogleCodeForReading} from 'app/client/ui/googleAuth';
|
2021-10-08 06:32:59 +00:00
|
|
|
import debounce = require('lodash/debounce');
|
2020-10-02 15:10:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
// We expect a function for creating the preview GridView, to avoid the need to require the
|
|
|
|
// GridView module here. That brings many dependencies, making a simple test fixture difficult.
|
|
|
|
type CreatePreviewFunc = (vs: ViewSectionRec) => GridView;
|
2021-10-08 06:32:59 +00:00
|
|
|
type GridView = IDisposable & {viewPane: HTMLElement, sortedRows: SortedRowSet, listenTo: (...args: any[]) => void};
|
2020-10-02 15:10:00 +00:00
|
|
|
|
|
|
|
export interface SourceInfo {
|
2021-10-08 06:32:59 +00:00
|
|
|
// The source table id.
|
2020-10-02 15:10:00 +00:00
|
|
|
hiddenTableId: string;
|
|
|
|
uploadFileIndex: number;
|
|
|
|
origTableName: string;
|
|
|
|
sourceSection: ViewSectionRec;
|
2021-10-08 06:32:59 +00:00
|
|
|
// A viewsection containing transform (formula) columns pointing to the original source columns.
|
|
|
|
transformSection: Observable<ViewSectionRec|null>;
|
|
|
|
// The destination table id.
|
2020-10-02 15:10:00 +00:00
|
|
|
destTableId: Observable<DestId>;
|
2021-10-08 06:32:59 +00:00
|
|
|
// True if there is at least one request in progress to create a new transform section.
|
|
|
|
isLoadingSection: Observable<boolean>;
|
|
|
|
// Reference to last promise for the GenImporterView action (which creates `transformSection`).
|
|
|
|
lastGenImporterViewPromise: Promise<any>|null;
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
2021-10-08 06:32:59 +00:00
|
|
|
|
|
|
|
interface MergeOptionsStateMap {
|
|
|
|
[hiddenTableId: string]: MergeOptionsState|undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
// UI state of merge options for a SourceInfo.
|
2021-09-15 06:12:34 +00:00
|
|
|
interface MergeOptionsState {
|
2021-10-08 06:32:59 +00:00
|
|
|
updateExistingRecords: Observable<boolean>;
|
|
|
|
mergeCols: MutableObsArray<string>;
|
|
|
|
mergeStrategy: Observable<MergeStrategy>;
|
|
|
|
hasInvalidMergeCols: Observable<boolean>;
|
2021-09-15 06:12:34 +00:00
|
|
|
}
|
2020-10-02 15:10:00 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Importer manages an import files to Grist tables and shows Preview
|
|
|
|
*/
|
2021-11-09 20:03:12 +00:00
|
|
|
export class Importer extends DisposableWithEvents {
|
2020-10-02 15:10:00 +00:00
|
|
|
/**
|
|
|
|
* Imports using the given plugin importer, or the built-in file-picker when null is passed in.
|
|
|
|
*/
|
|
|
|
public static async selectAndImport(
|
2021-08-03 10:34:05 +00:00
|
|
|
gristDoc: GristDoc,
|
|
|
|
imports: ImportSourceElement[],
|
|
|
|
importSourceElem: ImportSourceElement|null,
|
|
|
|
createPreview: CreatePreviewFunc
|
2020-10-02 15:10:00 +00:00
|
|
|
) {
|
|
|
|
// In case of using built-in file picker we want to get upload result before instantiating Importer
|
|
|
|
// because if the user dismisses the dialog without picking a file,
|
|
|
|
// there is no good way to detect this and dispose Importer.
|
|
|
|
let uploadResult: UploadResult|null = null;
|
|
|
|
if (!importSourceElem) {
|
|
|
|
// Use the built-in file picker. On electron, it uses the native file selector (without
|
|
|
|
// actually uploading anything), which is why this requires a slightly different flow.
|
|
|
|
const files: File[] = await openFilePicker({multiple: true});
|
|
|
|
// Important to fork first before trying to import, so we end up uploading to a
|
|
|
|
// consistent doc worker.
|
|
|
|
await gristDoc.forkIfNeeded();
|
|
|
|
const label = files.map(f => f.name).join(', ');
|
|
|
|
const size = files.reduce((acc, f) => acc + f.size, 0);
|
|
|
|
const app = gristDoc.app.topAppModel.appObs.get();
|
|
|
|
const progress = app ? app.notifier.createProgressIndicator(label, byteString(size)) : null;
|
|
|
|
const onProgress = (percent: number) => progress && progress.setProgress(percent);
|
|
|
|
try {
|
|
|
|
onProgress(0);
|
|
|
|
uploadResult = await uploadFiles(files, {docWorkerUrl: gristDoc.docComm.docWorkerUrl,
|
|
|
|
sizeLimit: 'import'}, onProgress);
|
|
|
|
onProgress(100);
|
|
|
|
} finally {
|
|
|
|
if (progress) {
|
|
|
|
progress.dispose();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-08-03 10:34:05 +00:00
|
|
|
// HACK: The url plugin does not support importing from google drive, and we don't want to
|
|
|
|
// ask a user for permission to access all his files (needed to download a single file from an URL).
|
|
|
|
// So to have a nice user experience, we will switch to the built-in google drive plugin and allow
|
|
|
|
// user to chose a file manually.
|
|
|
|
// Suggestion for the future is:
|
|
|
|
// (1) ask the user for the greater permission,
|
|
|
|
// (2) detect when the permission is not granted, and open the picker-based plugin in that case.
|
|
|
|
try {
|
|
|
|
// Importer disposes itself when its dialog is closed, so we do not take ownership of it.
|
|
|
|
await Importer.create(null, gristDoc, importSourceElem, createPreview).pickAndUploadSource(uploadResult);
|
|
|
|
} catch(err1) {
|
|
|
|
// If the url was a Google Drive Url, run the google drive plugin.
|
|
|
|
if (!(err1 instanceof GDriveUrlNotSupported)) {
|
|
|
|
reportError(err1);
|
|
|
|
} else {
|
|
|
|
const gdrivePlugin = imports.find((p) => p.plugin.definition.id === 'builtIn/gdrive' && p !== importSourceElem);
|
|
|
|
if (!gdrivePlugin) {
|
|
|
|
reportError(err1);
|
|
|
|
} else {
|
|
|
|
try {
|
|
|
|
await Importer.create(null, gristDoc, gdrivePlugin, createPreview).pickAndUploadSource(uploadResult);
|
|
|
|
} catch(err2) {
|
|
|
|
reportError(err2);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private _docComm = this._gristDoc.docComm;
|
|
|
|
private _uploadResult?: UploadResult;
|
|
|
|
|
2021-08-05 15:12:46 +00:00
|
|
|
private _screen: PluginScreen;
|
2021-10-08 06:32:59 +00:00
|
|
|
private _mergeOptions: MergeOptionsStateMap = {};
|
2020-10-02 15:10:00 +00:00
|
|
|
private _parseOptions = Observable.create<ParseOptions>(this, {});
|
|
|
|
private _sourceInfoArray = Observable.create<SourceInfo[]>(this, []);
|
|
|
|
private _sourceInfoSelected = Observable.create<SourceInfo|null>(this, null);
|
|
|
|
|
2021-11-09 20:03:12 +00:00
|
|
|
// Holder for the column mapping formula editor.
|
|
|
|
private readonly _formulaEditorHolder = Holder.create(this);
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
private _previewViewSection: Observable<ViewSectionRec|null> =
|
|
|
|
Computed.create(this, this._sourceInfoSelected, (use, info) => {
|
|
|
|
if (!info) { return null; }
|
2021-10-08 06:32:59 +00:00
|
|
|
|
|
|
|
const isLoading = use(info.isLoadingSection);
|
|
|
|
if (isLoading) { return null; }
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
const viewSection = use(info.transformSection);
|
|
|
|
return viewSection && !use(viewSection._isDeleted) ? viewSection : null;
|
|
|
|
});
|
|
|
|
|
2021-10-08 06:32:59 +00:00
|
|
|
// True if there is at least one request in progress to generate an import diff.
|
|
|
|
private _isLoadingDiff = Observable.create(this, false);
|
|
|
|
// Promise for the most recent generateImportDiff action.
|
|
|
|
private _lastGenImportDiffPromise: Promise<any>|null = null;
|
|
|
|
|
2021-11-19 05:35:01 +00:00
|
|
|
private _debouncedUpdateDiff = debounce(this._updateDiff, 1000, {leading: true, trailing: true});
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Flag that is set when _updateImportDiff is called, and unset when _debouncedUpdateDiff begins executing.
|
|
|
|
*
|
|
|
|
* This is a workaround until Lodash's next release, which supports checking if a debounced function is
|
|
|
|
* pending. We need to know if more debounced calls are pending so that we can decide to take down the
|
|
|
|
* loading spinner over the preview table, or leave it up until all scheduled calls settle.
|
|
|
|
*/
|
|
|
|
private _hasScheduledDiffUpdate = false;
|
2021-10-08 06:32:59 +00:00
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
// destTables is a list of options for import destinations, and includes all tables in the
|
2021-12-13 09:11:18 +00:00
|
|
|
// document, plus two values: to import as a new table, and to skip a table.
|
2020-10-02 15:10:00 +00:00
|
|
|
private _destTables = Computed.create<Array<IOptionFull<DestId>>>(this, (use) => [
|
2021-12-13 09:11:18 +00:00
|
|
|
{value: NEW_TABLE, label: 'New Table'},
|
|
|
|
...(use(this._sourceInfoArray).length > 1 ? [{value: SKIP_TABLE, label: 'Skip'}] : []),
|
2020-10-02 15:10:00 +00:00
|
|
|
...use(this._gristDoc.docModel.allTableIds.getObservable()).map((t) => ({value: t, label: t})),
|
|
|
|
]);
|
|
|
|
|
2021-11-09 20:03:12 +00:00
|
|
|
// Source column labels for the selected import source, keyed by column id.
|
|
|
|
private _sourceColLabelsById = Computed.create(this, this._sourceInfoSelected, (use, info) => {
|
|
|
|
if (!info || use(info.sourceSection._isDeleted)) { return null; }
|
|
|
|
|
|
|
|
const fields = use(use(info.sourceSection.viewFields).getObservable());
|
|
|
|
return new Map(fields.map(f => [use(use(f.column).colId), use(use(f.column).label)]));
|
|
|
|
});
|
|
|
|
|
|
|
|
// List of destination fields that aren't mapped to a source column.
|
|
|
|
private _unmatchedFields = Computed.create(this, this._sourceInfoSelected, (use, info) => {
|
|
|
|
if (!info) { return null; }
|
|
|
|
|
|
|
|
const transformSection = use(info.transformSection);
|
|
|
|
if (!transformSection || use(transformSection._isDeleted)) { return null; }
|
|
|
|
|
|
|
|
const fields = use(use(transformSection.viewFields).getObservable());
|
|
|
|
return fields
|
|
|
|
.filter(f => use(use(f.column).formula).trim() === '')
|
|
|
|
.map(f => f.column().label());
|
|
|
|
});
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
// null tells to use the built-in file picker.
|
|
|
|
constructor(private _gristDoc: GristDoc, private _importSourceElem: ImportSourceElement|null,
|
|
|
|
private _createPreview: CreatePreviewFunc) {
|
|
|
|
super();
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen = PluginScreen.create(this, _importSourceElem?.importSource.label || "Import from file");
|
2021-10-08 06:32:59 +00:00
|
|
|
|
|
|
|
this.onDispose(() => {
|
|
|
|
this._resetImportDiffState();
|
|
|
|
});
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Get new import sources and update the current one.
|
|
|
|
*/
|
|
|
|
public async pickAndUploadSource(uploadResult: UploadResult|null) {
|
|
|
|
try {
|
|
|
|
if (!this._importSourceElem) {
|
|
|
|
// Use upload result if it was passed in or the built-in file picker.
|
|
|
|
// On electron, it uses the native file selector (without actually uploading anything),
|
|
|
|
// which is why this requires a slightly different flow.
|
|
|
|
uploadResult = uploadResult || await selectFiles({docWorkerUrl: this._docComm.docWorkerUrl,
|
|
|
|
multiple: true, sizeLimit: 'import'});
|
|
|
|
} else {
|
|
|
|
const plugin = this._importSourceElem.plugin;
|
2021-08-05 15:12:46 +00:00
|
|
|
const handle = this._screen.renderPlugin(plugin);
|
2020-10-02 15:10:00 +00:00
|
|
|
const importSource = await this._importSourceElem.importSourceStub.getImportSource(handle);
|
|
|
|
plugin.removeRenderTarget(handle);
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen.renderSpinner();
|
2021-08-03 10:34:05 +00:00
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
if (importSource) {
|
|
|
|
// If data has been picked, upload it.
|
|
|
|
const item = importSource.item;
|
|
|
|
if (item.kind === "fileList") {
|
|
|
|
const files = item.files.map(({content, name}) => new File([content], name));
|
|
|
|
uploadResult = await uploadFiles(files, {docWorkerUrl: this._docComm.docWorkerUrl,
|
|
|
|
sizeLimit: 'import'});
|
2021-08-03 10:34:05 +00:00
|
|
|
} else if (item.kind === "url") {
|
2021-09-30 08:19:22 +00:00
|
|
|
if (isDriveUrl(item.url)) {
|
|
|
|
uploadResult = await this._fetchFromDrive(item.url);
|
|
|
|
} else {
|
2021-08-03 10:34:05 +00:00
|
|
|
uploadResult = await fetchURL(this._docComm, item.url);
|
|
|
|
}
|
|
|
|
} else {
|
2021-04-26 21:54:09 +00:00
|
|
|
throw new Error(`Import source of kind ${(item as any).kind} are not yet supported!`);
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (err) {
|
2021-09-30 08:19:22 +00:00
|
|
|
if (err instanceof CancelledError) {
|
|
|
|
await this._cancelImport();
|
|
|
|
return;
|
|
|
|
}
|
2021-08-03 10:34:05 +00:00
|
|
|
if (err instanceof GDriveUrlNotSupported) {
|
|
|
|
await this._cancelImport();
|
|
|
|
throw err;
|
|
|
|
}
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen.renderError(err.message);
|
2020-10-02 15:10:00 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (uploadResult) {
|
|
|
|
this._uploadResult = uploadResult;
|
|
|
|
await this._reImport(uploadResult);
|
|
|
|
} else {
|
|
|
|
await this._cancelImport();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getPrimaryViewSection(tableId: string): ViewSectionRec {
|
|
|
|
const tableModel = this._gristDoc.getTableModel(tableId);
|
|
|
|
const viewRow = tableModel.tableMetaRow.primaryView.peek();
|
|
|
|
return viewRow.viewSections.peek().peek()[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getSectionByRef(sectionRef: number): ViewSectionRec {
|
|
|
|
return this._gristDoc.docModel.viewSections.getRowModel(sectionRef);
|
|
|
|
}
|
|
|
|
|
2021-10-08 06:32:59 +00:00
|
|
|
private async _updateTransformSection(sourceInfo: SourceInfo) {
|
|
|
|
this._resetImportDiffState();
|
|
|
|
|
|
|
|
sourceInfo.isLoadingSection.set(true);
|
|
|
|
sourceInfo.transformSection.set(null);
|
|
|
|
|
|
|
|
const genImporterViewPromise = this._gristDoc.docData.sendAction(
|
|
|
|
['GenImporterView', sourceInfo.hiddenTableId, sourceInfo.destTableId.get(), null]);
|
|
|
|
sourceInfo.lastGenImporterViewPromise = genImporterViewPromise;
|
|
|
|
const transformSectionRef = await genImporterViewPromise;
|
|
|
|
|
|
|
|
// If the request is superseded by a newer request, or the Importer is disposed, do nothing.
|
|
|
|
if (this.isDisposed() || sourceInfo.lastGenImporterViewPromise !== genImporterViewPromise) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, update the transform section for `sourceInfo`.
|
2020-10-02 15:10:00 +00:00
|
|
|
sourceInfo.transformSection.set(this._gristDoc.docModel.viewSections.getRowModel(transformSectionRef));
|
2021-10-08 06:32:59 +00:00
|
|
|
sourceInfo.isLoadingSection.set(false);
|
2021-11-19 05:35:01 +00:00
|
|
|
|
|
|
|
// Change the active section to the transform section, so that formula autocomplete works.
|
|
|
|
this._gristDoc.viewModel.activeSectionId(transformSectionRef);
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private _getTransformedDataSource(upload: UploadResult): DataSourceTransformed {
|
|
|
|
const transforms: TransformRuleMap[] = upload.files.map((file, i) => this._createTransformRuleMap(i));
|
|
|
|
return {uploadId: upload.uploadId, transforms};
|
|
|
|
}
|
|
|
|
|
2021-10-04 16:14:14 +00:00
|
|
|
private _getMergeOptionMaps(upload: UploadResult): MergeOptionsMap[] {
|
|
|
|
return upload.files.map((_file, i) => this._createMergeOptionsMap(i));
|
2021-09-15 06:12:34 +00:00
|
|
|
}
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
private _createTransformRuleMap(uploadFileIndex: number): TransformRuleMap {
|
|
|
|
const result: TransformRuleMap = {};
|
|
|
|
for (const sourceInfo of this._sourceInfoArray.get()) {
|
|
|
|
if (sourceInfo.uploadFileIndex === uploadFileIndex) {
|
|
|
|
result[sourceInfo.origTableName] = this._createTransformRule(sourceInfo);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2021-10-04 16:14:14 +00:00
|
|
|
private _createMergeOptionsMap(uploadFileIndex: number): MergeOptionsMap {
|
|
|
|
const result: MergeOptionsMap = {};
|
|
|
|
for (const sourceInfo of this._sourceInfoArray.get()) {
|
|
|
|
if (sourceInfo.uploadFileIndex === uploadFileIndex) {
|
|
|
|
result[sourceInfo.origTableName] = this._getMergeOptionsForSource(sourceInfo);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
private _createTransformRule(sourceInfo: SourceInfo): TransformRule {
|
2021-10-08 06:32:59 +00:00
|
|
|
const transformSection = sourceInfo.transformSection.get();
|
|
|
|
if (!transformSection) {
|
|
|
|
throw new Error(`Table ${sourceInfo.hiddenTableId} is missing transform section`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const transformFields = transformSection.viewFields().peek();
|
2020-10-02 15:10:00 +00:00
|
|
|
const sourceFields = sourceInfo.sourceSection.viewFields().peek();
|
|
|
|
|
|
|
|
const destTableId: DestId = sourceInfo.destTableId.get();
|
|
|
|
return {
|
|
|
|
destTableId,
|
|
|
|
destCols: transformFields.map<TransformColumn>((field) => ({
|
|
|
|
label: field.label(),
|
|
|
|
colId: destTableId ? field.colId() : null, // if inserting into new table, colId isnt defined
|
|
|
|
type: field.column().type(),
|
|
|
|
formula: field.column().formula()
|
|
|
|
})),
|
|
|
|
sourceCols: sourceFields.map((field) => field.colId())
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-10-04 16:14:14 +00:00
|
|
|
private _getMergeOptionsForSource(sourceInfo: SourceInfo): MergeOptions|undefined {
|
|
|
|
const mergeOptions = this._mergeOptions[sourceInfo.hiddenTableId];
|
|
|
|
if (!mergeOptions) { return undefined; }
|
|
|
|
|
|
|
|
const {updateExistingRecords, mergeCols, mergeStrategy} = mergeOptions;
|
|
|
|
return {
|
|
|
|
mergeCols: updateExistingRecords.get() ? mergeCols.get() : [],
|
|
|
|
mergeStrategy: mergeStrategy.get()
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
private _getHiddenTableIds(): string[] {
|
|
|
|
return this._sourceInfoArray.get().map((t: SourceInfo) => t.hiddenTableId);
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _reImport(upload: UploadResult) {
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen.renderSpinner();
|
2021-10-08 06:32:59 +00:00
|
|
|
this._resetImportDiffState();
|
2020-10-02 15:10:00 +00:00
|
|
|
try {
|
2021-10-08 06:32:59 +00:00
|
|
|
const parseOptions = {...this._parseOptions.get(), NUM_ROWS: 0};
|
2020-10-02 15:10:00 +00:00
|
|
|
const importResult: ImportResult = await this._docComm.importFiles(
|
|
|
|
this._getTransformedDataSource(upload), parseOptions, this._getHiddenTableIds());
|
|
|
|
|
|
|
|
this._parseOptions.set(importResult.options);
|
|
|
|
|
|
|
|
this._sourceInfoArray.set(importResult.tables.map((info: ImportTableResult) => ({
|
|
|
|
hiddenTableId: info.hiddenTableId,
|
|
|
|
uploadFileIndex: info.uploadFileIndex,
|
|
|
|
origTableName: info.origTableName,
|
|
|
|
sourceSection: this._getPrimaryViewSection(info.hiddenTableId)!,
|
|
|
|
transformSection: Observable.create(null, this._getSectionByRef(info.transformSectionRef)),
|
2021-12-13 09:11:18 +00:00
|
|
|
destTableId: Observable.create<DestId>(null, info.destTableId ?? NEW_TABLE),
|
2021-10-08 06:32:59 +00:00
|
|
|
isLoadingSection: Observable.create(null, false),
|
|
|
|
lastGenImporterViewPromise: null
|
2020-10-02 15:10:00 +00:00
|
|
|
})));
|
|
|
|
|
|
|
|
if (this._sourceInfoArray.get().length === 0) {
|
|
|
|
throw new Error("No data was imported");
|
|
|
|
}
|
|
|
|
|
2021-09-15 06:12:34 +00:00
|
|
|
this._mergeOptions = {};
|
|
|
|
this._getHiddenTableIds().forEach(tableId => {
|
|
|
|
this._mergeOptions[tableId] = {
|
|
|
|
updateExistingRecords: Observable.create(null, false),
|
|
|
|
mergeCols: obsArray(),
|
|
|
|
mergeStrategy: Observable.create(null, {type: 'replace-with-nonblank-source'}),
|
2021-10-08 06:32:59 +00:00
|
|
|
hasInvalidMergeCols: Observable.create(null, false),
|
2021-09-15 06:12:34 +00:00
|
|
|
};
|
|
|
|
});
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
// Select the first sourceInfo to show in preview.
|
|
|
|
this._sourceInfoSelected.set(this._sourceInfoArray.get()[0] || null);
|
|
|
|
|
|
|
|
this._renderMain(upload);
|
|
|
|
|
|
|
|
} catch (e) {
|
|
|
|
console.warn("Import failed", e);
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen.renderError(e.message);
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-15 06:12:34 +00:00
|
|
|
private async _maybeFinishImport(upload: UploadResult) {
|
|
|
|
const isConfigValid = this._validateImportConfiguration();
|
|
|
|
if (!isConfigValid) { return; }
|
|
|
|
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen.renderSpinner();
|
2021-10-08 06:32:59 +00:00
|
|
|
this._resetImportDiffState();
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
const parseOptions = {...this._parseOptions.get(), NUM_ROWS: 0};
|
2021-10-04 16:14:14 +00:00
|
|
|
const mergeOptionMaps = this._getMergeOptionMaps(upload);
|
2021-09-15 06:12:34 +00:00
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
const importResult: ImportResult = await this._docComm.finishImportFiles(
|
2021-10-04 16:14:14 +00:00
|
|
|
this._getTransformedDataSource(upload), this._getHiddenTableIds(), {mergeOptionMaps, parseOptions});
|
2020-10-02 15:10:00 +00:00
|
|
|
|
2021-12-13 09:11:18 +00:00
|
|
|
if (importResult.tables[0]?.hiddenTableId) {
|
2020-10-02 15:10:00 +00:00
|
|
|
const tableRowModel = this._gristDoc.docModel.dataTables[importResult.tables[0].hiddenTableId].tableMetaRow;
|
|
|
|
await this._gristDoc.openDocPage(tableRowModel.primaryViewId());
|
|
|
|
}
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen.close();
|
2020-10-02 15:10:00 +00:00
|
|
|
this.dispose();
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _cancelImport() {
|
2021-10-08 06:32:59 +00:00
|
|
|
this._resetImportDiffState();
|
2021-11-09 20:03:12 +00:00
|
|
|
// Formula editor cleanup needs to happen before the hidden tables are removed.
|
|
|
|
this._formulaEditorHolder.dispose();
|
2021-10-08 06:32:59 +00:00
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
if (this._uploadResult) {
|
|
|
|
await this._docComm.cancelImportFiles(
|
|
|
|
this._getTransformedDataSource(this._uploadResult), this._getHiddenTableIds());
|
|
|
|
}
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen.close();
|
2020-10-02 15:10:00 +00:00
|
|
|
this.dispose();
|
|
|
|
}
|
|
|
|
|
2021-09-15 06:12:34 +00:00
|
|
|
private _resetTableMergeOptions(tableId: string) {
|
|
|
|
this._mergeOptions[tableId]?.mergeCols.set([]);
|
|
|
|
}
|
|
|
|
|
|
|
|
private _validateImportConfiguration(): boolean {
|
|
|
|
let isValid = true;
|
|
|
|
|
|
|
|
const selectedSourceInfo = this._sourceInfoSelected.get();
|
|
|
|
if (!selectedSourceInfo) { return isValid; } // No configuration to validate.
|
|
|
|
|
|
|
|
const mergeOptions = this._mergeOptions[selectedSourceInfo.hiddenTableId];
|
|
|
|
if (!mergeOptions) { return isValid; } // No configuration to validate.
|
|
|
|
|
2021-11-09 20:03:12 +00:00
|
|
|
const destTableId = selectedSourceInfo.destTableId.get();
|
2021-09-15 06:12:34 +00:00
|
|
|
const {updateExistingRecords, mergeCols, hasInvalidMergeCols} = mergeOptions;
|
2021-11-09 20:03:12 +00:00
|
|
|
|
|
|
|
// Check that at least one merge column was selected (if merging into an existing table).
|
|
|
|
if (destTableId !== null && updateExistingRecords.get() && mergeCols.get().length === 0) {
|
2021-09-15 06:12:34 +00:00
|
|
|
hasInvalidMergeCols.set(true);
|
|
|
|
isValid = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return isValid;
|
|
|
|
}
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
private _buildModalTitle(rightElement?: DomContents) {
|
|
|
|
const title = this._importSourceElem ? this._importSourceElem.importSource.label : 'Import from file';
|
|
|
|
return cssModalHeader(cssModalTitle(title), rightElement);
|
|
|
|
}
|
|
|
|
|
2021-10-08 06:32:59 +00:00
|
|
|
/**
|
|
|
|
* Triggers an update of the import diff in the preview table. When called in quick succession,
|
|
|
|
* only the most recent call will result in an update being made to the preview table.
|
|
|
|
*
|
2021-11-19 05:35:01 +00:00
|
|
|
* @param {SourceInfo} info The source to update the diff for.
|
|
|
|
*/
|
|
|
|
private async _updateImportDiff(info: SourceInfo) {
|
|
|
|
this._hasScheduledDiffUpdate = true;
|
|
|
|
this._isLoadingDiff.set(true);
|
|
|
|
await this._debouncedUpdateDiff(info);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* NOTE: This method should not be called directly. Instead, use _updateImportDiff above, which
|
|
|
|
* wraps this method and calls a debounced version of it.
|
|
|
|
*
|
|
|
|
* Triggers an update of the import diff in the preview table. When called in quick succession,
|
|
|
|
* only the most recent call will result in an update being made to the preview table.
|
2021-10-08 06:32:59 +00:00
|
|
|
*
|
|
|
|
* @param {SourceInfo} info The source to update the diff for.
|
|
|
|
*/
|
|
|
|
private async _updateDiff(info: SourceInfo) {
|
2021-11-19 05:35:01 +00:00
|
|
|
// Reset the flag tracking scheduled updates since the debounced update has started.
|
|
|
|
this._hasScheduledDiffUpdate = false;
|
2021-10-08 06:32:59 +00:00
|
|
|
|
2021-11-19 05:35:01 +00:00
|
|
|
const mergeOptions = this._mergeOptions[info.hiddenTableId]!;
|
2021-10-08 06:32:59 +00:00
|
|
|
if (!mergeOptions.updateExistingRecords.get() || mergeOptions.mergeCols.get().length === 0) {
|
|
|
|
// We can simply disable document comparison mode when merging isn't configured.
|
|
|
|
this._gristDoc.comparison = null;
|
|
|
|
} else {
|
|
|
|
// Request a diff of the current source and wait for a response.
|
|
|
|
const genImportDiffPromise = this._docComm.generateImportDiff(info.hiddenTableId,
|
|
|
|
this._createTransformRule(info), this._getMergeOptionsForSource(info)!);
|
|
|
|
this._lastGenImportDiffPromise = genImportDiffPromise;
|
|
|
|
const diff = await genImportDiffPromise;
|
|
|
|
|
|
|
|
// If the request is superseded by a newer request, or the Importer is disposed, do nothing.
|
|
|
|
if (this.isDisposed() || genImportDiffPromise !== this._lastGenImportDiffPromise) { return; }
|
|
|
|
|
|
|
|
// Otherwise, put the document in comparison mode with the diff data.
|
|
|
|
this._gristDoc.comparison = diff;
|
|
|
|
}
|
|
|
|
|
2021-11-19 05:35:01 +00:00
|
|
|
// If more updates where scheduled since we started the update, leave the loading spinner up.
|
|
|
|
if (!this._hasScheduledDiffUpdate) {
|
|
|
|
this._isLoadingDiff.set(false);
|
|
|
|
}
|
2021-10-08 06:32:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Resets all state variables related to diffs to their default values.
|
|
|
|
*/
|
|
|
|
private _resetImportDiffState() {
|
|
|
|
this._cancelPendingDiffRequests();
|
|
|
|
this._gristDoc.comparison = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Effectively cancels all pending diff requests by causing their fulfilled promises to
|
|
|
|
* be ignored by their attached handlers. Since we can't natively cancel the promises, this
|
|
|
|
* is functionally equivalent to canceling the outstanding requests.
|
|
|
|
*/
|
|
|
|
private _cancelPendingDiffRequests() {
|
2021-11-19 05:35:01 +00:00
|
|
|
this._debouncedUpdateDiff.cancel();
|
2021-10-08 06:32:59 +00:00
|
|
|
this._lastGenImportDiffPromise = null;
|
2021-11-19 05:35:01 +00:00
|
|
|
this._hasScheduledDiffUpdate = false;
|
2021-10-08 06:32:59 +00:00
|
|
|
this._isLoadingDiff.set(false);
|
|
|
|
}
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
// The importer state showing import in progress, with a list of tables, and a preview.
|
|
|
|
private _renderMain(upload: UploadResult) {
|
|
|
|
const schema = this._parseOptions.get().SCHEMA;
|
2021-11-09 20:03:12 +00:00
|
|
|
const content = cssContainer(
|
|
|
|
dom.autoDispose(this._formulaEditorHolder),
|
|
|
|
{tabIndex: '-1'},
|
2020-10-02 15:10:00 +00:00
|
|
|
this._buildModalTitle(
|
|
|
|
schema ? cssActionLink(cssLinkIcon('Settings'), 'Import options',
|
|
|
|
testId('importer-options-link'),
|
|
|
|
dom.on('click', () => this._renderParseOptions(schema, upload))
|
|
|
|
) : null,
|
|
|
|
),
|
|
|
|
cssPreviewWrapper(
|
|
|
|
cssTableList(
|
|
|
|
dom.forEach(this._sourceInfoArray, (info) => {
|
|
|
|
const destTableId = Computed.create(null, (use) => use(info.destTableId))
|
2021-10-08 06:32:59 +00:00
|
|
|
.onWrite(async (destId) => {
|
2021-11-09 20:03:12 +00:00
|
|
|
// Prevent changing destination of un-selected sources if current configuration is invalid.
|
|
|
|
if (info !== this._sourceInfoSelected.get() && !this._validateImportConfiguration()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-10-08 06:32:59 +00:00
|
|
|
info.destTableId.set(destId);
|
2021-09-15 06:12:34 +00:00
|
|
|
this._resetTableMergeOptions(info.hiddenTableId);
|
2021-12-13 09:11:18 +00:00
|
|
|
if (destId !== SKIP_TABLE) {
|
|
|
|
await this._updateTransformSection(info);
|
|
|
|
}
|
2021-09-15 06:12:34 +00:00
|
|
|
});
|
2020-10-02 15:10:00 +00:00
|
|
|
return cssTableInfo(
|
|
|
|
dom.autoDispose(destTableId),
|
|
|
|
cssTableLine(cssToFrom('From'),
|
|
|
|
cssTableSource(getSourceDescription(info, upload), testId('importer-from'))),
|
|
|
|
cssTableLine(cssToFrom('To'), linkSelect<DestId>(destTableId, this._destTables)),
|
|
|
|
cssTableInfo.cls('-selected', (use) => use(this._sourceInfoSelected) === info),
|
2021-10-08 06:32:59 +00:00
|
|
|
dom.on('click', async () => {
|
2021-11-09 20:03:12 +00:00
|
|
|
// Ignore click if source is already selected.
|
|
|
|
if (info === this._sourceInfoSelected.get()) { return; }
|
|
|
|
|
|
|
|
// Prevent changing selected source if current configuration is invalid.
|
|
|
|
if (!this._validateImportConfiguration()) { return; }
|
2021-10-08 06:32:59 +00:00
|
|
|
|
|
|
|
this._cancelPendingDiffRequests();
|
2021-09-15 06:12:34 +00:00
|
|
|
this._sourceInfoSelected.set(info);
|
2021-10-08 06:32:59 +00:00
|
|
|
await this._updateDiff(info);
|
2021-09-15 06:12:34 +00:00
|
|
|
}),
|
2020-10-02 15:10:00 +00:00
|
|
|
testId('importer-source'),
|
|
|
|
);
|
|
|
|
}),
|
|
|
|
),
|
2021-10-08 06:32:59 +00:00
|
|
|
dom.maybe(this._sourceInfoSelected, (info) => {
|
|
|
|
const {mergeCols, updateExistingRecords, hasInvalidMergeCols} = this._mergeOptions[info.hiddenTableId]!;
|
|
|
|
|
2021-11-09 20:03:12 +00:00
|
|
|
return cssConfigAndPreview(
|
2021-11-19 05:35:01 +00:00
|
|
|
dom.maybe(info.destTableId, () => cssConfigColumn(
|
|
|
|
dom.maybe(info.transformSection, section => {
|
|
|
|
const updateRecordsListener = updateExistingRecords.addListener(async () => {
|
|
|
|
await this._updateImportDiff(info);
|
|
|
|
});
|
|
|
|
|
|
|
|
return [
|
|
|
|
cssMergeOptions(
|
2021-11-09 20:03:12 +00:00
|
|
|
cssMergeOptionsToggle(labeledSquareCheckbox(
|
|
|
|
updateExistingRecords,
|
|
|
|
'Update existing records',
|
|
|
|
dom.autoDispose(updateRecordsListener),
|
|
|
|
testId('importer-update-existing-records')
|
|
|
|
)),
|
|
|
|
dom.maybe(updateExistingRecords, () => {
|
|
|
|
const mergeColsListener = mergeCols.addListener(async val => {
|
|
|
|
// Reset the error state of the multiSelect on change.
|
|
|
|
if (val.length !== 0 && hasInvalidMergeCols.get()) {
|
|
|
|
hasInvalidMergeCols.set(false);
|
|
|
|
}
|
|
|
|
await this._updateImportDiff(info);
|
|
|
|
});
|
|
|
|
|
|
|
|
return [
|
|
|
|
cssMergeOptionsMessage(
|
|
|
|
'Merge rows that match these fields:',
|
|
|
|
testId('importer-merge-fields-message')
|
|
|
|
),
|
|
|
|
multiSelect(
|
|
|
|
mergeCols,
|
|
|
|
section.viewFields().peek().map(f => ({label: f.label(), value: f.colId()})) ?? [],
|
|
|
|
{
|
|
|
|
placeholder: 'Select fields to match on',
|
|
|
|
error: hasInvalidMergeCols
|
|
|
|
},
|
|
|
|
dom.autoDispose(mergeColsListener),
|
|
|
|
testId('importer-merge-fields-select')
|
|
|
|
)
|
|
|
|
];
|
|
|
|
})
|
2021-11-19 05:35:01 +00:00
|
|
|
),
|
|
|
|
dom.domComputed(this._unmatchedFields, fields =>
|
|
|
|
fields && fields.length > 0 ?
|
|
|
|
cssUnmatchedFields(
|
|
|
|
dom('div',
|
|
|
|
cssGreenText(
|
|
|
|
`${fields.length} unmatched ${fields.length > 1 ? 'fields' : 'field'}`
|
|
|
|
),
|
|
|
|
' in import:'
|
2021-11-09 20:03:12 +00:00
|
|
|
),
|
2021-11-19 05:35:01 +00:00
|
|
|
cssUnmatchedFieldsList(fields.join(', ')),
|
|
|
|
testId('importer-unmatched-fields')
|
|
|
|
) : null
|
|
|
|
),
|
|
|
|
cssColumnMatchOptions(
|
|
|
|
dom.forEach(fromKo(section.viewFields().getObservable()), field => cssColumnMatchRow(
|
|
|
|
cssColumnMatchIcon('ImportArrow'),
|
|
|
|
cssSourceAndDestination(
|
|
|
|
cssDestinationFieldRow(
|
|
|
|
cssDestinationFieldLabel(
|
|
|
|
dom.text(field.label),
|
|
|
|
),
|
|
|
|
cssDestinationFieldSettings(
|
|
|
|
icon('Dots'),
|
|
|
|
menu(
|
|
|
|
() => {
|
|
|
|
const sourceColId = field.origCol().id();
|
|
|
|
const sourceColIdsAndLabels = [...this._sourceColLabelsById.get()!.entries()];
|
|
|
|
return [
|
2021-11-09 20:03:12 +00:00
|
|
|
menuItem(
|
2021-11-19 05:35:01 +00:00
|
|
|
() => this._gristDoc.clearColumns([sourceColId]),
|
|
|
|
'Skip',
|
2021-11-09 20:03:12 +00:00
|
|
|
testId('importer-column-match-menu-item')
|
|
|
|
),
|
2021-11-19 05:35:01 +00:00
|
|
|
menuDivider(),
|
|
|
|
...sourceColIdsAndLabels.map(([id, label]) =>
|
|
|
|
menuItem(
|
|
|
|
() => this._setColumnFormula(sourceColId, '$' + id),
|
|
|
|
label,
|
|
|
|
testId('importer-column-match-menu-item')
|
|
|
|
),
|
|
|
|
),
|
|
|
|
testId('importer-column-match-menu'),
|
|
|
|
];
|
|
|
|
},
|
|
|
|
{ placement: 'right-start' },
|
|
|
|
),
|
|
|
|
testId('importer-column-match-destination-settings')
|
2021-11-09 20:03:12 +00:00
|
|
|
),
|
2021-11-19 05:35:01 +00:00
|
|
|
testId('importer-column-match-destination')
|
2021-11-09 20:03:12 +00:00
|
|
|
),
|
2021-11-19 05:35:01 +00:00
|
|
|
dom.domComputed(use => dom.create(
|
|
|
|
this._buildColMappingFormula.bind(this),
|
|
|
|
use(field.column),
|
|
|
|
(elem: Element) => this._activateFormulaEditor(elem, field),
|
|
|
|
'Skip'
|
|
|
|
)),
|
|
|
|
testId('importer-column-match-source-destination'),
|
|
|
|
)
|
|
|
|
)),
|
|
|
|
testId('importer-column-match-options'),
|
|
|
|
)
|
|
|
|
];
|
|
|
|
}),
|
|
|
|
)),
|
2021-11-09 20:03:12 +00:00
|
|
|
cssPreviewColumn(
|
|
|
|
cssSectionHeader('Preview'),
|
|
|
|
dom.domComputed(use => {
|
|
|
|
const previewSection = use(this._previewViewSection);
|
|
|
|
if (use(this._isLoadingDiff) || !previewSection) {
|
2021-11-19 05:35:01 +00:00
|
|
|
return cssPreviewSpinner(loadingSpinner(), testId('importer-preview-spinner'));
|
2021-11-09 20:03:12 +00:00
|
|
|
}
|
2021-10-08 06:32:59 +00:00
|
|
|
|
2021-11-09 20:03:12 +00:00
|
|
|
const gridView = this._createPreview(previewSection);
|
|
|
|
|
|
|
|
// When changes are made to the preview table, update the import diff.
|
|
|
|
gridView.listenTo(gridView.sortedRows, 'rowNotify', async () => {
|
|
|
|
// If we aren't showing a diff, there is no need to do anything.
|
|
|
|
if (!info.destTableId || !updateExistingRecords.get() || mergeCols.get().length === 0) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, update the diff and rebuild the preview table.
|
|
|
|
await this._updateImportDiff(info);
|
|
|
|
});
|
|
|
|
|
|
|
|
return cssPreviewGrid(
|
2021-12-13 09:11:18 +00:00
|
|
|
dom.maybe(use1 => SKIP_TABLE === use1(info.destTableId),
|
|
|
|
() => cssOverlay(testId("importer-preview-overlay"))),
|
2021-11-09 20:03:12 +00:00
|
|
|
dom.autoDispose(gridView),
|
|
|
|
gridView.viewPane,
|
|
|
|
testId('importer-preview'),
|
|
|
|
);
|
|
|
|
})
|
|
|
|
)
|
|
|
|
);
|
2020-10-02 15:10:00 +00:00
|
|
|
}),
|
|
|
|
),
|
|
|
|
cssModalButtons(
|
|
|
|
bigPrimaryButton('Import',
|
2021-09-15 06:12:34 +00:00
|
|
|
dom.on('click', () => this._maybeFinishImport(upload)),
|
2021-12-13 09:11:18 +00:00
|
|
|
dom.boolAttr('disabled', use => {
|
|
|
|
return use(this._previewViewSection) === null ||
|
|
|
|
use(this._sourceInfoArray).every(i => use(i.destTableId) === SKIP_TABLE);
|
|
|
|
}),
|
2020-10-02 15:10:00 +00:00
|
|
|
testId('modal-confirm'),
|
|
|
|
),
|
|
|
|
bigBasicButton('Cancel',
|
|
|
|
dom.on('click', () => this._cancelImport()),
|
|
|
|
testId('modal-cancel'),
|
|
|
|
),
|
|
|
|
),
|
2021-11-09 20:03:12 +00:00
|
|
|
);
|
|
|
|
this._addFocusLayer(content);
|
|
|
|
this._screen.render(content, {fullscreen: true});
|
|
|
|
}
|
|
|
|
|
|
|
|
private _addFocusLayer(container: HTMLElement) {
|
|
|
|
dom.autoDisposeElem(container, new FocusLayer({
|
|
|
|
defaultFocusElem: container,
|
|
|
|
allowFocus: (elem) => (elem !== document.body),
|
|
|
|
onDefaultFocus: () => this.trigger('importer_focus'),
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Updates the formula on column `colRef` to `formula`.
|
|
|
|
*/
|
|
|
|
private async _setColumnFormula(colRef: number, formula: string): Promise<void> {
|
|
|
|
return this._gristDoc.docModel.columns.sendTableAction(
|
|
|
|
['UpdateRecord', colRef, { formula, isFormula: true }]
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Opens a formula editor for `field` over `refElem`.
|
|
|
|
*/
|
|
|
|
private _activateFormulaEditor(refElem: Element, field: ViewFieldRec) {
|
|
|
|
// TODO: Set active section to hidden table section, so editor autocomplete is accurate.
|
|
|
|
const editorHolder = openFormulaEditor({
|
|
|
|
gristDoc: this._gristDoc,
|
|
|
|
field,
|
|
|
|
refElem,
|
|
|
|
setupCleanup: this._setupFormulaEditorCleanup.bind(this),
|
|
|
|
});
|
|
|
|
this._formulaEditorHolder.autoDispose(editorHolder);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Called by _activateFormulaEditor to initialize cleanup
|
|
|
|
* code for when the formula editor is closed. Registers and
|
|
|
|
* unregisters callbacks for saving edits when the editor loses
|
|
|
|
* focus.
|
|
|
|
*/
|
|
|
|
private _setupFormulaEditorCleanup(
|
|
|
|
owner: MultiHolder, _doc: GristDoc, field: ViewFieldRec, _saveEdit: () => Promise<unknown>
|
|
|
|
) {
|
|
|
|
const saveEdit = () => _saveEdit().catch(reportError);
|
|
|
|
|
|
|
|
// Whenever focus returns to the dialog, close the editor by saving the value.
|
|
|
|
this.on('importer_focus', saveEdit);
|
|
|
|
|
|
|
|
owner.onDispose(() => {
|
|
|
|
this.off('importer_focus', saveEdit);
|
|
|
|
field.editingFormula(false);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Builds an editable formula component that is displayed
|
|
|
|
* in the column mapping section of Importer. On click, opens
|
|
|
|
* an editor for the formula for `column`.
|
|
|
|
*/
|
|
|
|
private _buildColMappingFormula(_owner: MultiHolder, column: ColumnRec, buildEditor: (e: Element) => void,
|
|
|
|
placeholder: string) {
|
|
|
|
const formatFormula = (formula: string) => {
|
|
|
|
const sourceColLabels = this._sourceColLabelsById.get();
|
|
|
|
if (!sourceColLabels) { return formula; }
|
|
|
|
|
|
|
|
formula = formula.trim();
|
|
|
|
if (formula.startsWith('$') && sourceColLabels.has(formula.slice(1))) {
|
|
|
|
// For simple formulas that only reference a source column id, show the source column label.
|
|
|
|
return sourceColLabels.get(formula.slice(1))!;
|
|
|
|
}
|
|
|
|
|
|
|
|
return formula;
|
|
|
|
};
|
|
|
|
|
|
|
|
return cssFieldFormula(use => formatFormula(use(column.formula)), {placeholder, maxLines: 1},
|
|
|
|
dom.cls('disabled'),
|
|
|
|
{tabIndex: '-1'},
|
|
|
|
dom.on('focus', (_ev, elem) => buildEditor(elem)),
|
|
|
|
testId('importer-column-match-formula'),
|
|
|
|
);
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// The importer state showing parse options that may be changed.
|
|
|
|
private _renderParseOptions(schema: ParseOptionSchema[], upload: UploadResult) {
|
2021-08-05 15:12:46 +00:00
|
|
|
this._screen.render([
|
2020-10-02 15:10:00 +00:00
|
|
|
this._buildModalTitle(),
|
|
|
|
dom.create(buildParseOptionsForm, schema, this._parseOptions.get() as ParseOptionValues,
|
|
|
|
(p: ParseOptions) => {
|
|
|
|
this._parseOptions.set(p);
|
|
|
|
this._reImport(upload).catch((err) => reportError(err));
|
|
|
|
},
|
|
|
|
() => { this._renderMain(upload); },
|
|
|
|
)
|
|
|
|
]);
|
|
|
|
}
|
2021-09-30 08:19:22 +00:00
|
|
|
|
|
|
|
private async _fetchFromDrive(itemUrl: string) {
|
|
|
|
// First we will assume that this is public file, so no need to ask for permissions.
|
|
|
|
try {
|
|
|
|
return await fetchURL(this._docComm, itemUrl);
|
|
|
|
} catch(err) {
|
|
|
|
// It is not a public file or the file id in the url is wrong,
|
|
|
|
// but we have no way to check it, so we assume that it is private file
|
|
|
|
// and ask the user for the permission (if we are configured to do so)
|
|
|
|
if (canReadPrivateFiles()) {
|
|
|
|
const options: FetchUrlOptions = {};
|
|
|
|
try {
|
|
|
|
// Request for authorization code from Google.
|
|
|
|
const code = await getGoogleCodeForReading(this);
|
|
|
|
options.googleAuthorizationCode = code;
|
|
|
|
} catch(permError) {
|
|
|
|
if (permError?.message === ACCESS_DENIED) {
|
|
|
|
// User declined to give us full readonly permission, fallback to GoogleDrive plugin
|
|
|
|
// or cancel import if GoogleDrive plugin is not configured.
|
|
|
|
throw new GDriveUrlNotSupported(itemUrl);
|
|
|
|
} else if(permError?.message === AUTH_INTERRUPTED) {
|
|
|
|
// User closed the window - we assume he doesn't want to continue.
|
|
|
|
throw new CancelledError();
|
|
|
|
} else {
|
|
|
|
// Some other error happened during authentication, report to user.
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Download file from private drive, if it fails, report the error to user.
|
|
|
|
return await fetchURL(this._docComm, itemUrl, options);
|
|
|
|
} else {
|
|
|
|
// We are not allowed to ask for full readonly permission, fallback to GoogleDrive plugin.
|
|
|
|
throw new GDriveUrlNotSupported(itemUrl);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
|
|
|
|
2021-09-30 08:19:22 +00:00
|
|
|
// Used for switching from URL plugin to Google drive plugin.
|
2021-08-03 10:34:05 +00:00
|
|
|
class GDriveUrlNotSupported extends Error {
|
|
|
|
constructor(public url: string) {
|
|
|
|
super(`This url ${url} is not supported`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-30 08:19:22 +00:00
|
|
|
// Used to cancel import (close the dialog without any error).
|
|
|
|
class CancelledError extends Error {
|
|
|
|
}
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
function getSourceDescription(sourceInfo: SourceInfo, upload: UploadResult) {
|
2021-04-26 21:54:09 +00:00
|
|
|
const origName = upload.files[sourceInfo.uploadFileIndex].origName;
|
2021-12-07 23:52:14 +00:00
|
|
|
return sourceInfo.origTableName ? `${sourceInfo.origTableName} - ${origName}` : origName;
|
2020-10-02 15:10:00 +00:00
|
|
|
}
|
|
|
|
|
2021-11-09 20:03:12 +00:00
|
|
|
const cssContainer = styled('div', `
|
|
|
|
height: 100%;
|
|
|
|
display: flex;
|
|
|
|
flex-direction: column;
|
|
|
|
outline: unset;
|
|
|
|
`);
|
|
|
|
|
2020-10-02 15:10:00 +00:00
|
|
|
const cssActionLink = styled('div', `
|
|
|
|
display: inline-flex;
|
|
|
|
align-items: center;
|
|
|
|
cursor: pointer;
|
|
|
|
color: ${colors.lightGreen};
|
|
|
|
--icon-color: ${colors.lightGreen};
|
|
|
|
&:hover {
|
|
|
|
color: ${colors.darkGreen};
|
|
|
|
--icon-color: ${colors.darkGreen};
|
|
|
|
}
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssLinkIcon = styled(icon, `
|
|
|
|
flex: none;
|
|
|
|
margin-right: 4px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssModalHeader = styled('div', `
|
|
|
|
display: flex;
|
|
|
|
align-items: center;
|
|
|
|
justify-content: space-between;
|
|
|
|
margin-bottom: 16px;
|
|
|
|
& > .${cssModalTitle.className} {
|
|
|
|
margin-bottom: 0px;
|
|
|
|
}
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssPreviewWrapper = styled('div', `
|
2021-11-09 20:03:12 +00:00
|
|
|
display: flex;
|
|
|
|
flex-direction: column;
|
|
|
|
flex-grow: 1;
|
2020-10-02 15:10:00 +00:00
|
|
|
overflow-y: auto;
|
|
|
|
`);
|
|
|
|
|
|
|
|
// This partly duplicates cssSectionHeader from HomeLeftPane.ts
|
|
|
|
const cssSectionHeader = styled('div', `
|
|
|
|
margin-bottom: 8px;
|
|
|
|
color: ${colors.slate};
|
|
|
|
text-transform: uppercase;
|
|
|
|
font-weight: 500;
|
|
|
|
font-size: ${vars.xsmallFontSize};
|
|
|
|
letter-spacing: 1px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssTableList = styled('div', `
|
2021-11-09 20:03:12 +00:00
|
|
|
max-height: 50%;
|
|
|
|
column-gap: 32px;
|
2020-10-02 15:10:00 +00:00
|
|
|
display: flex;
|
|
|
|
flex-flow: row wrap;
|
|
|
|
margin-bottom: 16px;
|
|
|
|
align-items: flex-start;
|
2021-11-09 20:03:12 +00:00
|
|
|
overflow-y: auto;
|
2020-10-02 15:10:00 +00:00
|
|
|
`);
|
|
|
|
|
|
|
|
const cssTableInfo = styled('div', `
|
|
|
|
padding: 4px 8px;
|
|
|
|
margin: 4px 0px;
|
2021-11-09 20:03:12 +00:00
|
|
|
width: 300px;
|
2020-10-02 15:10:00 +00:00
|
|
|
border-radius: 3px;
|
|
|
|
border: 1px solid ${colors.darkGrey};
|
|
|
|
&:hover, &-selected {
|
|
|
|
background-color: ${colors.mediumGrey};
|
|
|
|
}
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssTableLine = styled('div', `
|
|
|
|
display: flex;
|
|
|
|
align-items: center;
|
|
|
|
margin: 4px 0;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssToFrom = styled('span', `
|
|
|
|
flex: none;
|
|
|
|
margin-right: 8px;
|
|
|
|
color: ${colors.slate};
|
|
|
|
text-transform: uppercase;
|
|
|
|
font-weight: 500;
|
|
|
|
font-size: ${vars.xsmallFontSize};
|
|
|
|
letter-spacing: 1px;
|
|
|
|
width: 40px;
|
|
|
|
text-align: right;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssTableSource = styled('div', `
|
2021-11-09 20:03:12 +00:00
|
|
|
overflow: hidden;
|
|
|
|
white-space: nowrap;
|
|
|
|
text-overflow: ellipsis;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssConfigAndPreview = styled('div', `
|
|
|
|
display: flex;
|
|
|
|
gap: 32px;
|
|
|
|
flex-grow: 1;
|
|
|
|
height: 0px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssConfigColumn = styled('div', `
|
|
|
|
width: 300px;
|
|
|
|
padding-right: 8px;
|
|
|
|
display: flex;
|
|
|
|
flex-direction: column;
|
|
|
|
overflow-y: auto;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssPreviewColumn = styled('div', `
|
|
|
|
display: flex;
|
|
|
|
flex-direction: column;
|
|
|
|
flex-grow: 1;
|
2020-10-02 15:10:00 +00:00
|
|
|
`);
|
|
|
|
|
2021-10-08 06:32:59 +00:00
|
|
|
const cssPreview = styled('div', `
|
2020-10-02 15:10:00 +00:00
|
|
|
display: flex;
|
2021-11-09 20:03:12 +00:00
|
|
|
flex-grow: 1;
|
2021-10-08 06:32:59 +00:00
|
|
|
`);
|
|
|
|
|
|
|
|
const cssPreviewSpinner = styled(cssPreview, `
|
|
|
|
align-items: center;
|
|
|
|
justify-content: center;
|
|
|
|
`);
|
|
|
|
|
2021-12-13 09:11:18 +00:00
|
|
|
const cssOverlay = styled('div', `
|
|
|
|
position: absolute;
|
|
|
|
top: 0px;
|
|
|
|
left: 0px;
|
|
|
|
height: 100%;
|
|
|
|
width: 100%;
|
|
|
|
z-index: 10;
|
|
|
|
background: ${colors.mediumGrey};
|
|
|
|
`);
|
|
|
|
|
2021-10-08 06:32:59 +00:00
|
|
|
const cssPreviewGrid = styled(cssPreview, `
|
2020-10-02 15:10:00 +00:00
|
|
|
border: 1px solid ${colors.darkGrey};
|
2021-12-13 09:11:18 +00:00
|
|
|
position: relative;
|
2020-10-02 15:10:00 +00:00
|
|
|
`);
|
2021-09-15 06:12:34 +00:00
|
|
|
|
|
|
|
const cssMergeOptions = styled('div', `
|
|
|
|
margin-bottom: 16px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssMergeOptionsToggle = styled('div', `
|
|
|
|
margin-bottom: 8px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssMergeOptionsMessage = styled('div', `
|
|
|
|
color: ${colors.slate};
|
|
|
|
margin-bottom: 8px;
|
|
|
|
`);
|
2021-11-09 20:03:12 +00:00
|
|
|
|
|
|
|
const cssColumnMatchOptions = styled('div', `
|
|
|
|
display: flex;
|
|
|
|
flex-direction: column;
|
|
|
|
gap: 20px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssColumnMatchRow = styled('div', `
|
|
|
|
display: flex;
|
|
|
|
align-items: center;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssFieldFormula = styled(buildHighlightedCode, `
|
|
|
|
flex: auto;
|
|
|
|
cursor: pointer;
|
|
|
|
margin-top: 1px;
|
|
|
|
padding-left: 4px;
|
|
|
|
--icon-color: ${colors.lightGreen};
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssColumnMatchIcon = styled(icon, `
|
|
|
|
flex-shrink: 0;
|
|
|
|
width: 20px;
|
|
|
|
height: 32px;
|
|
|
|
background-color: ${colors.darkGrey};
|
|
|
|
margin-right: 4px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssDestinationFieldRow = styled('div', `
|
|
|
|
align-items: center;
|
|
|
|
display: flex;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssSourceAndDestination = styled('div', `
|
|
|
|
min-width: 0;
|
|
|
|
display: flex;
|
|
|
|
flex-direction: column;
|
|
|
|
flex-grow: 1;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssDestinationFieldLabel = styled('div', `
|
|
|
|
overflow: hidden;
|
|
|
|
white-space: nowrap;
|
|
|
|
text-overflow: ellipsis;
|
|
|
|
padding-left: 4px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssDestinationFieldSettings = styled('div', `
|
|
|
|
flex: none;
|
|
|
|
margin: 0 4px 0 auto;
|
|
|
|
height: 24px;
|
|
|
|
width: 24px;
|
|
|
|
padding: 4px;
|
|
|
|
line-height: 0px;
|
|
|
|
border-radius: 3px;
|
|
|
|
cursor: pointer;
|
|
|
|
--icon-color: ${colors.slate};
|
|
|
|
|
|
|
|
&:hover, &.weasel-popup-open {
|
|
|
|
background-color: ${colors.mediumGrey};
|
|
|
|
}
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssUnmatchedFields = styled('div', `
|
|
|
|
margin-bottom: 16px;
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssUnmatchedFieldsList = styled('div', `
|
|
|
|
white-space: nowrap;
|
|
|
|
text-overflow: ellipsis;
|
|
|
|
overflow: hidden;
|
|
|
|
padding-right: 16px;
|
|
|
|
color: ${colors.slate};
|
|
|
|
`);
|
|
|
|
|
|
|
|
const cssGreenText = styled('span', `
|
|
|
|
color: ${colors.lightGreen};
|
|
|
|
`);
|