Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Undo / redo behavior on LG resources #1813

Merged
merged 20 commits into from
Jan 21, 2020
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,18 @@ describe('test all reducer handlers', () => {
expect(result.dialogs[0]).toBe('test dialogs');
});
it('test updateLgTemplate reducer', () => {
const result = reducer({}, { type: ActionTypes.UPDATE_LG_SUCCESS, payload: { response: mockResponse } });
expect(result.lgFiles[0]).toBe('test lgFiles');
const result = reducer(
{ lgFiles: [{ id: 'common.lg', content: 'test lgFiles' }] },
{
type: ActionTypes.UPDATE_LG_SUCCESS,
payload: {
id: 'common.lg',
content: ` # bfdactivity-003038
- You said '@{turn.activity.text}'`,
},
}
);
expect(result.lgFiles[0].templates.length).toBe(1);
});

it('test getStorageFileSuccess reducer', () => {
Expand Down
36 changes: 26 additions & 10 deletions Composer/packages/client/src/ShellApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,17 @@ const FileTargetTypes = {
export const ShellApi: React.FC = () => {
const { state, actions } = useContext(StoreContext);

const { dialogs, schemas, lgFiles, luFiles, designPageLocation, focusPath, breadcrumb, botName } = state;
const {
dialogs,
schemas,
lgFiles,
luFiles,
designPageLocation,
focusPath,
breadcrumb,
botName,
externalUpdate,
} = state;
const updateDialog = actions.updateDialog;
const updateLuFile = actions.updateLuFile; //if debounced, error can't pass to form
const updateLgFile = actions.updateLgFile;
Expand Down Expand Up @@ -279,6 +289,17 @@ export const ShellApi: React.FC = () => {
apiClient.apiCall('reset', nextState, window.frames[VISUAL_EDITOR]);
}

function resetDataAll(externalUpdate?) {
if (window.frames[VISUAL_EDITOR]) {
const editorWindow = window.frames[VISUAL_EDITOR];
apiClient.apiCall('reset', { ...getState(VISUAL_EDITOR), externalUpdate }, editorWindow);
}
if (window.frames[FORM_EDITOR]) {
const editorWindow = window.frames[FORM_EDITOR];
apiClient.apiCall('reset', { ...getState(FORM_EDITOR), externalUpdate }, editorWindow);
}
}

useEffect(() => {
apiClient.connect();

Expand Down Expand Up @@ -324,18 +345,13 @@ export const ShellApi: React.FC = () => {
}); // this is intented to reconstruct everytime store is refresh

useEffect(() => {
if (window.frames[VISUAL_EDITOR]) {
const editorWindow = window.frames[VISUAL_EDITOR];
apiClient.apiCall('reset', getState(VISUAL_EDITOR), editorWindow);
}
resetDataAll();
}, [dialogs, lgFiles, luFiles, focusPath, selected, focused, promptTab]);

//reset the date if the data is not updated by editor
useEffect(() => {
if (window.frames[FORM_EDITOR]) {
const editorWindow = window.frames[FORM_EDITOR];
apiClient.apiCall('reset', getState(FORM_EDITOR), editorWindow);
}
}, [dialogs, lgFiles, luFiles, focusPath, selected, focused, promptTab]);
resetDataAll(externalUpdate);
}, [externalUpdate]);

useEffect(() => {
const schemaError = get(schemas, 'diagnostics', []);
Expand Down
1 change: 1 addition & 0 deletions Composer/packages/client/src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export enum ActionTypes {
GET_ENDPOINT_SUCCESS = 'GET_ENDPOINT_SUCCESS', // remote publish
ONBOARDING_ADD_COACH_MARK_REF = 'ONBOARDING_ADD_COACH_MARK_REF',
ONBOARDING_SET_COMPLETE = 'ONBOARDING_SET_COMPLETE',
RECORD_EXTERNAL_UPDATE = 'RECORD_EXTERNAL_UPDATE',
lei9444 marked this conversation as resolved.
Show resolved Hide resolved
}

export const Tips = {
Expand Down
13 changes: 10 additions & 3 deletions Composer/packages/client/src/store/action/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import clonedeep from 'lodash/cloneDeep';
import reject from 'lodash/reject';
import { DialogInfo } from '@bfc/indexers';
import debounce from 'lodash/debounce';
import { ExternalUpdate, UpdateScope, UpdateAction } from '@bfc/shared';

import { ActionCreator, State } from '../types';
import { undoable, Pick } from '../middlewares/undo';
Expand All @@ -15,6 +16,7 @@ import { Store } from './../types';
import httpClient from './../../utils/httpUtil';
import { setError } from './error';
import { fetchProject } from './project';
import { recordExternalUpdate } from './shell';

const pickDialog: Pick = (state: State, args: any[], isStackEmpty) => {
const id = args[0];
Expand Down Expand Up @@ -112,20 +114,25 @@ export const debouncedUpdateDialog = debounce(async (store, id, content) => {
}
}, 500);

export const updateDialogBase: ActionCreator = (store, { id, content }) => {
export const updateDialogBase: ActionCreator = (store, { id, content }, externalUpdate?: ExternalUpdate) => {
lei9444 marked this conversation as resolved.
Show resolved Hide resolved
store.dispatch({ type: ActionTypes.UPDATE_DIALOG, payload: { id, content } });
recordExternalUpdate(store, externalUpdate);
debouncedUpdateDialog(store, id, content);
};

export const updateDialog: ActionCreator = undoable(
updateDialogBase,
(state: State, args: any[], isEmpty) => {
const externalUpdate = {
scope: UpdateScope.DialogFile,
action: UpdateAction.UndoRedo,
};
if (isEmpty) {
const id = state.designPageLocation.dialogId;
const dialog = state.dialogs.find(dialog => dialog.id === id);
return [{ id, content: dialog ? dialog.content : {} }];
return [{ id, content: dialog ? dialog.content : {} }, externalUpdate];
} else {
return args;
return [{ ...args[0] }, externalUpdate];
}
},
updateDialogBase,
Expand Down
66 changes: 48 additions & 18 deletions Composer/packages/client/src/store/action/lg.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,58 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import clonedeep from 'lodash/cloneDeep';
import debounce from 'lodash/debounce';
import { ExternalUpdate, UpdateScope, UpdateAction } from '@bfc/shared';

import { ActionTypes } from '../../constants';
import httpClient from '../../utils/httpUtil';
import * as lgUtil from '../../utils/lgUtil';
import { ActionCreator } from '../types';
import { undoable } from '../middlewares/undo';
import { ActionCreator, State } from '../types';

import { ActionTypes } from './../../constants';
import httpClient from './../../utils/httpUtil';
import { fetchProject } from './project';
import { setError } from './error';
import { recordExternalUpdate } from './shell';

export const updateLgFile: ActionCreator = async ({ dispatch }, { id, content }) => {
//remove editor's debounce and add it to action
export const debouncedUpdateLg = debounce(async (store, id, content) => {
try {
const response = await httpClient.put(`/projects/opened/lgFiles/${id}`, { id, content });
dispatch({
type: ActionTypes.UPDATE_LG_SUCCESS,
payload: { response },
});
await httpClient.put(`/projects/opened/lgFiles/${id}`, { id, content });
} catch (err) {
dispatch({
type: ActionTypes.UPDATE_LG_FAILURE,
payload: null,
error: err,
setError(store, {
message: err.response && err.response.data.message ? err.response.data.message : err,
summary: 'UPDATE LG ERROR',
});
//if update lg error, do a full refresh.
fetchProject(store);
}
}, 500);

export const updateLgFile: ActionCreator = async (store, { id, content }, externalUpdate?: ExternalUpdate) => {
store.dispatch({ type: ActionTypes.UPDATE_LG_SUCCESS, payload: { id, content } });
recordExternalUpdate(store, externalUpdate);
debouncedUpdateLg(store, id, content);
};

export const undoableUpdateLgFile = undoable(
updateLgFile,
(state: State, args: any[], isEmpty) => {
const externalUpdate = {
scope: UpdateScope.LgFile,
action: UpdateAction.UndoRedo,
};
if (isEmpty) {
const id = args[0].id;
const content = clonedeep(state.lgFiles.find(lgFile => lgFile.id === id)?.content);
return [{ id, content }, externalUpdate];
} else {
return [{ ...args[0] }, externalUpdate];
}
},
updateLgFile,
updateLgFile
);

export const createLgFile: ActionCreator = async ({ dispatch }, { id, content }) => {
try {
const response = await httpClient.post(`/projects/opened/lgFiles`, { id, content });
Expand Down Expand Up @@ -57,25 +87,25 @@ export const removeLgFile: ActionCreator = async ({ dispatch }, { id }) => {

export const updateLgTemplate: ActionCreator = async (store, { file, templateName, template }) => {
const newContent = lgUtil.updateTemplate(file.content, templateName, template);
return await updateLgFile(store, { id: file.id, content: newContent });
return await undoableUpdateLgFile(store, { id: file.id, content: newContent });
};

export const createLgTemplate: ActionCreator = async (store, { file, template }) => {
const newContent = lgUtil.addTemplate(file.content, template);
return await updateLgFile(store, { id: file.id, content: newContent });
return await undoableUpdateLgFile(store, { id: file.id, content: newContent });
};

export const removeLgTemplate: ActionCreator = async (store, { file, templateName }) => {
const newContent = lgUtil.removeTemplate(file.content, templateName);
return await updateLgFile(store, { id: file.id, content: newContent });
return await undoableUpdateLgFile(store, { id: file.id, content: newContent });
};

export const removeLgTemplates: ActionCreator = async (store, { file, templateNames }) => {
const newContent = lgUtil.removeTemplates(file.content, templateNames);
return await updateLgFile(store, { id: file.id, content: newContent });
return await undoableUpdateLgFile(store, { id: file.id, content: newContent });
};

export const copyLgTemplate: ActionCreator = async (store, { file, fromTemplateName, toTemplateName }) => {
const newContent = lgUtil.copyTemplate(file.content, fromTemplateName, toTemplateName);
return await updateLgFile(store, { id: file.id, content: newContent });
return await undoableUpdateLgFile(store, { id: file.id, content: newContent });
};
2 changes: 2 additions & 0 deletions Composer/packages/client/src/store/action/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ActionCreator } from './../types';
import { ActionTypes } from './../../constants';
import { updateBreadcrumb, navigateTo, checkUrl, getUrlSearch, BreadcrumbUpdateType } from './../../utils/navigation';
import { debouncedUpdateDialog } from './dialog';
import { debouncedUpdateLg } from './lg';

export const setDesignPageLocation: ActionCreator = (
{ dispatch },
Expand All @@ -25,6 +26,7 @@ export const navTo: ActionCreator = ({ getState }, dialogId, breadcrumb = []) =>
if (checkUrl(currentUri, state.designPageLocation)) return;
//if dialog change we should flush some debounced functions
debouncedUpdateDialog.flush();
debouncedUpdateLg.flush();
navigateTo(currentUri, { state: { breadcrumb } });
};

Expand Down
14 changes: 14 additions & 0 deletions Composer/packages/client/src/store/action/shell.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { ExternalUpdate } from '@bfc/shared';

import { ActionTypes } from '../../constants';
import { ActionCreator } from '../types';

export const recordExternalUpdate: ActionCreator = async ({ dispatch }, externalUpdate: ExternalUpdate) => {
dispatch({
type: ActionTypes.RECORD_EXTERNAL_UPDATE,
payload: { externalUpdate },
});
};
1 change: 1 addition & 0 deletions Composer/packages/client/src/store/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ const initialState: State = {
coachMarkRefs: {},
},
clipboardActions: [],
externalUpdate: undefined,
};

interface StoreContextValue {
Expand Down
23 changes: 21 additions & 2 deletions Composer/packages/client/src/store/reducer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import get from 'lodash/get';
import set from 'lodash/set';
import { dialogIndexer } from '@bfc/indexers';
import { SensitiveProperties } from '@bfc/shared';
import { Diagnostic, DiagnosticSeverity, LgTemplate, lgIndexer } from '@bfc/indexers';

import { ActionTypes, FileTypes } from '../../constants';
import { DialogSetting, ReducerFunc } from '../types';
Expand Down Expand Up @@ -105,8 +106,21 @@ const createDialogSuccess: ReducerFunc = (state, { response }) => {
return state;
};

const updateLgTemplate: ReducerFunc = (state, { response }) => {
state.lgFiles = response.data.lgFiles;
const updateLgTemplate: ReducerFunc = (state, { id, content }) => {
state.lgFiles = state.lgFiles.map(lgFile => {
if (lgFile.id === id) {
const { check, parse } = lgIndexer;
const diagnostics = check(content, id);
let templates: LgTemplate[] = [];
try {
templates = parse(content, id);
} catch (err) {
diagnostics.push(new Diagnostic(err.message, id, DiagnosticSeverity.Error));
}
return { ...lgFile, templates, diagnostics };
}
return lgFile;
});
return state;
};

Expand Down Expand Up @@ -281,6 +295,10 @@ const noOp: ReducerFunc = state => {
return state;
};

const recordExternalUpdate: ReducerFunc = (state, { externalUpdate }) => {
return (state.externalUpdate = externalUpdate);
};

export const reducer = createReducer({
[ActionTypes.GET_PROJECT_SUCCESS]: getProjectSuccess,
[ActionTypes.GET_PROJECT_FAILURE]: noOp,
Expand Down Expand Up @@ -334,4 +352,5 @@ export const reducer = createReducer({
[ActionTypes.ONBOARDING_ADD_COACH_MARK_REF]: onboardingAddCoachMarkRef,
[ActionTypes.ONBOARDING_SET_COMPLETE]: onboardingSetComplete,
[ActionTypes.EDITOR_CLIPBOARD]: setClipboardActions,
[ActionTypes.RECORD_EXTERNAL_UPDATE]: recordExternalUpdate,
});
3 changes: 2 additions & 1 deletion Composer/packages/client/src/store/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// TODO: remove this once we can expand the types
/* eslint-disable @typescript-eslint/no-explicit-any */
import React from 'react';
import { PromptTab, BotSchemas, ProjectTemplate } from '@bfc/shared';
import { PromptTab, BotSchemas, ProjectTemplate, ExternalUpdate } from '@bfc/shared';
import { DialogInfo, LgFile, LuFile } from '@bfc/indexers';

import { CreationFlowStatus, BotStatus } from '../constants';
Expand Down Expand Up @@ -90,6 +90,7 @@ export interface State {
complete: boolean;
};
clipboardActions: any[];
externalUpdate?: ExternalUpdate;
}

export type ReducerFunc<T = any> = (state: State, payload: T) => State;
Expand Down
5 changes: 4 additions & 1 deletion Composer/packages/extensions/obiformeditor/src/Form/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { WidgetProps, FieldProps, ObjectFieldTemplateProps } from '@bfcomposer/r
import { ShellData, EditorSchema, ShellApi, OBISchema } from '@bfc/shared';

export interface FormContext
extends Pick<ShellData, 'luFiles' | 'lgFiles' | 'currentDialog' | 'focusedEvent' | 'focusedSteps' | 'focusedTab'> {
extends Pick<
ShellData,
'luFiles' | 'lgFiles' | 'currentDialog' | 'focusedEvent' | 'focusedSteps' | 'focusedTab' | 'externalUpdate'
> {
editorSchema: EditorSchema;
shellApi: ShellApi;
rootId: string;
Expand Down
Loading