fix(editor): Add back prompt requesting to save unsaved changes (no-changelog) (#10190)

This commit is contained in:
Alex Grozav 2024-07-25 18:44:26 +03:00 committed by GitHub
parent bfc8e1b56f
commit fa7bc452b7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 156 additions and 137 deletions

View file

@ -0,0 +1,3 @@
export function getSaveChangesModal() {
return cy.get('.el-overlay').contains('Save changes before leaving?');
}

View file

@ -0,0 +1,26 @@
import { WorkflowsPage as WorkflowsPageClass } from '../pages/workflows';
import { WorkflowPage as WorkflowPageClass } from '../pages/workflow';
import { EDIT_FIELDS_SET_NODE_NAME } from '../constants';
import { getSaveChangesModal } from '../composables/modals/save-changes-modal';
const WorkflowsPage = new WorkflowsPageClass();
const WorkflowPage = new WorkflowPageClass();
describe('Workflows', () => {
beforeEach(() => {
cy.visit(WorkflowsPage.url);
});
it('should ask to save unsaved changes before leaving route', () => {
WorkflowsPage.getters.newWorkflowButtonCard().should('be.visible');
WorkflowsPage.getters.newWorkflowButtonCard().click();
cy.createFixtureWorkflow('Test_workflow_1.json', 'Empty State Card Workflow');
WorkflowPage.actions.addNodeToCanvas(EDIT_FIELDS_SET_NODE_NAME);
cy.getByTestId('project-home-menu-item').click();
getSaveChangesModal().should('be.visible');
});
});

View file

@ -61,6 +61,7 @@ export default defineComponent({
next(); next();
return; return;
} }
if (this.uiStore.stateIsDirty) { if (this.uiStore.stateIsDirty) {
const confirmModal = await this.confirm( const confirmModal = await this.confirm(
this.$locale.baseText('generic.unsavedWork.confirmMessage.message'), this.$locale.baseText('generic.unsavedWork.confirmMessage.message'),

View file

@ -4,13 +4,12 @@ import type { IConnection, Workflow } from 'n8n-workflow';
import { NodeConnectionType } from 'n8n-workflow'; import { NodeConnectionType } from 'n8n-workflow';
import { useCanvasOperations } from '@/composables/useCanvasOperations'; import { useCanvasOperations } from '@/composables/useCanvasOperations';
import type { CanvasNode } from '@/types'; import type { CanvasNode } from '@/types';
import type { ICredentialsResponse, INodeUi, IWorkflowDb, XYPosition } from '@/Interface'; import type { ICredentialsResponse, INodeUi, IWorkflowDb } from '@/Interface';
import { RemoveNodeCommand } from '@/models/history'; import { RemoveNodeCommand } from '@/models/history';
import { useWorkflowsStore } from '@/stores/workflows.store'; import { useWorkflowsStore } from '@/stores/workflows.store';
import { useUIStore } from '@/stores/ui.store'; import { useUIStore } from '@/stores/ui.store';
import { useHistoryStore } from '@/stores/history.store'; import { useHistoryStore } from '@/stores/history.store';
import { useNDVStore } from '@/stores/ndv.store'; import { useNDVStore } from '@/stores/ndv.store';
import { ref } from 'vue';
import { import {
createTestNode, createTestNode,
createTestWorkflowObject, createTestWorkflowObject,
@ -49,7 +48,6 @@ describe('useCanvasOperations', () => {
let canvasOperations: ReturnType<typeof useCanvasOperations>; let canvasOperations: ReturnType<typeof useCanvasOperations>;
let workflowHelpers: ReturnType<typeof useWorkflowHelpers>; let workflowHelpers: ReturnType<typeof useWorkflowHelpers>;
const lastClickPosition = ref<XYPosition>([450, 450]);
const router = useRouter(); const router = useRouter();
beforeEach(async () => { beforeEach(async () => {
@ -77,7 +75,7 @@ describe('useCanvasOperations', () => {
workflowsStore.resetState(); workflowsStore.resetState();
workflowHelpers.initState(workflow); workflowHelpers.initState(workflow);
canvasOperations = useCanvasOperations({ router, lastClickPosition }); canvasOperations = useCanvasOperations({ router });
vi.clearAllMocks(); vi.clearAllMocks();
}); });
@ -135,7 +133,7 @@ describe('useCanvasOperations', () => {
mockNodeTypeDescription({ name: 'type' }), mockNodeTypeDescription({ name: 'type' }),
); );
expect(result.position).toEqual([460, 460]); // Default last click position expect(result.position).toEqual([0, 0]); // Default last click position
}); });
it('should create node with provided position when position is provided', () => { it('should create node with provided position when position is provided', () => {

View file

@ -87,8 +87,7 @@ import type {
} from 'n8n-workflow'; } from 'n8n-workflow';
import { deepCopy, NodeConnectionType, NodeHelpers, TelemetryHelpers } from 'n8n-workflow'; import { deepCopy, NodeConnectionType, NodeHelpers, TelemetryHelpers } from 'n8n-workflow';
import { v4 as uuid } from 'uuid'; import { v4 as uuid } from 'uuid';
import type { Ref } from 'vue'; import { computed, nextTick, ref } from 'vue';
import { computed, nextTick } from 'vue';
import type { useRouter } from 'vue-router'; import type { useRouter } from 'vue-router';
import { useClipboard } from '@/composables/useClipboard'; import { useClipboard } from '@/composables/useClipboard';
import { isPresent } from '../utils/typesUtils'; import { isPresent } from '../utils/typesUtils';
@ -108,13 +107,7 @@ type AddNodeOptions = {
isAutoAdd?: boolean; isAutoAdd?: boolean;
}; };
export function useCanvasOperations({ export function useCanvasOperations({ router }: { router: ReturnType<typeof useRouter> }) {
router,
lastClickPosition,
}: {
router: ReturnType<typeof useRouter>;
lastClickPosition: Ref<XYPosition>;
}) {
const rootStore = useRootStore(); const rootStore = useRootStore();
const workflowsStore = useWorkflowsStore(); const workflowsStore = useWorkflowsStore();
const credentialsStore = useCredentialsStore(); const credentialsStore = useCredentialsStore();
@ -136,6 +129,8 @@ export function useCanvasOperations({
const externalHooks = useExternalHooks(); const externalHooks = useExternalHooks();
const clipboard = useClipboard(); const clipboard = useClipboard();
const lastClickPosition = ref<XYPosition>([0, 0]);
const preventOpeningNDV = !!localStorage.getItem('NodeView.preventOpeningNDV'); const preventOpeningNDV = !!localStorage.getItem('NodeView.preventOpeningNDV');
const editableWorkflow = computed(() => workflowsStore.workflow); const editableWorkflow = computed(() => workflowsStore.workflow);
@ -1698,6 +1693,7 @@ export function useCanvasOperations({
} }
return { return {
lastClickPosition,
editableWorkflow, editableWorkflow,
editableWorkflowObject, editableWorkflowObject,
triggerNodes, triggerNodes,

View file

@ -1,5 +1,6 @@
import { import {
HTTP_REQUEST_NODE_TYPE, HTTP_REQUEST_NODE_TYPE,
MODAL_CANCEL,
MODAL_CONFIRM, MODAL_CONFIRM,
PLACEHOLDER_EMPTY_WORKFLOW_ID, PLACEHOLDER_EMPTY_WORKFLOW_ID,
PLACEHOLDER_FILLED_AT_EXECUTION_TIME, PLACEHOLDER_FILLED_AT_EXECUTION_TIME,
@ -66,6 +67,8 @@ import { useTelemetry } from '@/composables/useTelemetry';
import { useProjectsStore } from '@/stores/projects.store'; import { useProjectsStore } from '@/stores/projects.store';
import { useTagsStore } from '@/stores/tags.store'; import { useTagsStore } from '@/stores/tags.store';
import useWorkflowsEEStore from '@/stores/workflows.ee.store'; import useWorkflowsEEStore from '@/stores/workflows.ee.store';
import { useNpsSurveyStore } from '@/stores/npsSurvey.store';
import type { NavigationGuardNext } from 'vue-router';
type ResolveParameterOptions = { type ResolveParameterOptions = {
targetItem?: TargetItem; targetItem?: TargetItem;
@ -1055,6 +1058,52 @@ export function useWorkflowHelpers(options: { router: ReturnType<typeof useRoute
} }
} }
async function promptSaveUnsavedWorkflowChanges(
next: NavigationGuardNext,
{
confirm = async () => true,
cancel = async () => {},
}: {
confirm?: () => Promise<boolean>;
cancel?: () => Promise<void>;
} = {},
) {
if (uiStore.stateIsDirty) {
const npsSurveyStore = useNpsSurveyStore();
const confirmModal = await message.confirm(
i18n.baseText('generic.unsavedWork.confirmMessage.message'),
{
title: i18n.baseText('generic.unsavedWork.confirmMessage.headline'),
type: 'warning',
confirmButtonText: i18n.baseText('generic.unsavedWork.confirmMessage.confirmButtonText'),
cancelButtonText: i18n.baseText('generic.unsavedWork.confirmMessage.cancelButtonText'),
showClose: true,
},
);
if (confirmModal === MODAL_CONFIRM) {
const saved = await saveCurrentWorkflow({}, false);
if (saved) {
await npsSurveyStore.fetchPromptsData();
}
uiStore.stateIsDirty = false;
const goToNext = await confirm();
if (goToNext) {
next();
}
} else if (confirmModal === MODAL_CANCEL) {
await cancel();
uiStore.stateIsDirty = false;
next();
}
} else {
next();
}
}
function initState(workflowData: IWorkflowDb) { function initState(workflowData: IWorkflowDb) {
workflowsStore.addWorkflow(workflowData); workflowsStore.addWorkflow(workflowData);
workflowsStore.setActive(workflowData.active || false); workflowsStore.setActive(workflowData.active || false);
@ -1107,6 +1156,7 @@ export function useWorkflowHelpers(options: { router: ReturnType<typeof useRoute
updateNodePositions, updateNodePositions,
removeForeignCredentialsFromWorkflow, removeForeignCredentialsFromWorkflow,
getWorkflowProjectRole, getWorkflowProjectRole,
promptSaveUnsavedWorkflowChanges,
initState, initState,
}; };
} }

View file

@ -9,7 +9,7 @@ import {
ref, ref,
useCssModule, useCssModule,
} from 'vue'; } from 'vue';
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import WorkflowCanvas from '@/components/canvas/WorkflowCanvas.vue'; import WorkflowCanvas from '@/components/canvas/WorkflowCanvas.vue';
import { useNodeTypesStore } from '@/stores/nodeTypes.store'; import { useNodeTypesStore } from '@/stores/nodeTypes.store';
import { useUIStore } from '@/stores/ui.store'; import { useUIStore } from '@/stores/ui.store';
@ -42,10 +42,8 @@ import {
EnterpriseEditionFeature, EnterpriseEditionFeature,
MAIN_HEADER_TABS, MAIN_HEADER_TABS,
MANUAL_CHAT_TRIGGER_NODE_TYPE, MANUAL_CHAT_TRIGGER_NODE_TYPE,
MODAL_CANCEL,
MODAL_CONFIRM, MODAL_CONFIRM,
NODE_CREATOR_OPEN_SOURCES, NODE_CREATOR_OPEN_SOURCES,
PLACEHOLDER_EMPTY_WORKFLOW_ID,
START_NODE_TYPE, START_NODE_TYPE,
STICKY_NODE_TYPE, STICKY_NODE_TYPE,
VALID_WORKFLOW_IMPORT_URL_REGEX, VALID_WORKFLOW_IMPORT_URL_REGEX,
@ -136,8 +134,6 @@ const templatesStore = useTemplatesStore();
const canvasEventBus = createEventBus(); const canvasEventBus = createEventBus();
const lastClickPosition = ref<XYPosition>([0, 0]);
const { runWorkflow, stopCurrentExecution, stopWaitingForWebhook } = useRunWorkflow({ router }); const { runWorkflow, stopCurrentExecution, stopWaitingForWebhook } = useRunWorkflow({ router });
const { const {
updateNodePosition, updateNodePosition,
@ -171,7 +167,8 @@ const {
initializeWorkspace, initializeWorkspace,
editableWorkflow, editableWorkflow,
editableWorkflowObject, editableWorkflowObject,
} = useCanvasOperations({ router, lastClickPosition }); lastClickPosition,
} = useCanvasOperations({ router });
const { applyExecutionData } = useExecutionDebugging(); const { applyExecutionData } = useExecutionDebugging();
useClipboard({ onPaste: onClipboardPaste }); useClipboard({ onPaste: onClipboardPaste });
@ -1372,66 +1369,6 @@ function registerCustomActions() {
// }); // });
} }
/**
* Routing
*/
onBeforeRouteLeave(async (to, from, next) => {
const toNodeViewTab = getNodeViewTab(to);
if (
toNodeViewTab === MAIN_HEADER_TABS.EXECUTIONS ||
from.name === VIEWS.TEMPLATE_IMPORT ||
(toNodeViewTab === MAIN_HEADER_TABS.WORKFLOW && from.name === VIEWS.EXECUTION_DEBUG)
) {
next();
return;
}
if (uiStore.stateIsDirty && !isReadOnlyEnvironment.value) {
const confirmModal = await message.confirm(
i18n.baseText('generic.unsavedWork.confirmMessage.message'),
{
title: i18n.baseText('generic.unsavedWork.confirmMessage.headline'),
type: 'warning',
confirmButtonText: i18n.baseText('generic.unsavedWork.confirmMessage.confirmButtonText'),
cancelButtonText: i18n.baseText('generic.unsavedWork.confirmMessage.cancelButtonText'),
showClose: true,
},
);
if (confirmModal === MODAL_CONFIRM) {
// Make sure workflow id is empty when leaving the editor
workflowsStore.setWorkflowId(PLACEHOLDER_EMPTY_WORKFLOW_ID);
const saved = await workflowHelpers.saveCurrentWorkflow({}, false);
if (saved) {
await npsSurveyStore.fetchPromptsData();
}
uiStore.stateIsDirty = false;
if (from.name === VIEWS.NEW_WORKFLOW) {
// Replace the current route with the new workflow route
// before navigating to the new route when saving new workflow.
await router.replace({
name: VIEWS.WORKFLOW,
params: { name: workflowId.value },
});
await router.push(to);
} else {
next();
}
} else if (confirmModal === MODAL_CANCEL) {
workflowsStore.setWorkflowId(PLACEHOLDER_EMPTY_WORKFLOW_ID);
resetWorkspace();
uiStore.stateIsDirty = false;
next();
}
} else {
next();
}
});
/** /**
* Lifecycle * Lifecycle
*/ */

View file

@ -414,61 +414,6 @@ export default defineComponent({
ContextMenu, ContextMenu,
LazySetupWorkflowCredentialsButton, LazySetupWorkflowCredentialsButton,
}, },
async beforeRouteLeave(to, from, next) {
if (
getNodeViewTab(to) === MAIN_HEADER_TABS.EXECUTIONS ||
from.name === VIEWS.TEMPLATE_IMPORT ||
(getNodeViewTab(to) === MAIN_HEADER_TABS.WORKFLOW && from.name === VIEWS.EXECUTION_DEBUG)
) {
next();
return;
}
if (this.uiStore.stateIsDirty && !this.readOnlyEnv) {
const confirmModal = await this.confirm(
this.$locale.baseText('generic.unsavedWork.confirmMessage.message'),
{
title: this.$locale.baseText('generic.unsavedWork.confirmMessage.headline'),
type: 'warning',
confirmButtonText: this.$locale.baseText(
'generic.unsavedWork.confirmMessage.confirmButtonText',
),
cancelButtonText: this.$locale.baseText(
'generic.unsavedWork.confirmMessage.cancelButtonText',
),
showClose: true,
},
);
if (confirmModal === MODAL_CONFIRM) {
// Make sure workflow id is empty when leaving the editor
this.workflowsStore.setWorkflowId(PLACEHOLDER_EMPTY_WORKFLOW_ID);
const saved = await this.workflowHelpers.saveCurrentWorkflow({}, false);
if (saved) {
await this.npsSurveyStore.fetchPromptsData();
}
this.uiStore.stateIsDirty = false;
if (from.name === VIEWS.NEW_WORKFLOW) {
// Replace the current route with the new workflow route
// before navigating to the new route when saving new workflow.
await this.$router.replace({
name: VIEWS.WORKFLOW,
params: { name: this.currentWorkflow },
});
await this.$router.push(to);
} else {
next();
}
} else if (confirmModal === MODAL_CANCEL) {
this.workflowsStore.setWorkflowId(PLACEHOLDER_EMPTY_WORKFLOW_ID);
this.resetWorkspace();
this.uiStore.stateIsDirty = false;
next();
}
} else {
next();
}
},
setup() { setup() {
const nodeViewRootRef = ref<HTMLElement | null>(null); const nodeViewRootRef = ref<HTMLElement | null>(null);
const nodeViewRef = ref<HTMLElement | null>(null); const nodeViewRef = ref<HTMLElement | null>(null);

View file

@ -1,17 +1,80 @@
<script lang="ts" setup> <script lang="ts" setup>
import { useLocalStorage } from '@vueuse/core'; import { useLocalStorage } from '@vueuse/core';
import { watch } from 'vue'; import { computed, watch } from 'vue';
import { useRouter } from 'vue-router'; import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
import NodeViewV1 from '@/views/NodeView.vue'; import NodeViewV1 from '@/views/NodeView.vue';
import NodeViewV2 from '@/views/NodeView.v2.vue'; import NodeViewV2 from '@/views/NodeView.v2.vue';
import { getNodeViewTab } from '@/utils/canvasUtils';
import { MAIN_HEADER_TABS, PLACEHOLDER_EMPTY_WORKFLOW_ID, VIEWS } from '@/constants';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { useWorkflowHelpers } from '@/composables/useWorkflowHelpers';
import { useCanvasOperations } from '@/composables/useCanvasOperations';
import { useSourceControlStore } from '@/stores/sourceControl.store';
const workflowsStore = useWorkflowsStore();
const sourceControlStore = useSourceControlStore();
const router = useRouter(); const router = useRouter();
const route = useRoute();
const workflowHelpers = useWorkflowHelpers({ router });
const { resetWorkspace } = useCanvasOperations({ router });
const nodeViewVersion = useLocalStorage('NodeView.version', '1'); const nodeViewVersion = useLocalStorage('NodeView.version', '1');
const workflowId = computed<string>(() => route.params.name as string);
const isReadOnlyEnvironment = computed(() => {
return sourceControlStore.preferences.branchReadOnly;
});
watch(nodeViewVersion, () => { watch(nodeViewVersion, () => {
router.go(0); router.go(0);
}); });
/**
* Routing
*/
onBeforeRouteLeave(async (to, from, next) => {
const toNodeViewTab = getNodeViewTab(to);
if (
toNodeViewTab === MAIN_HEADER_TABS.EXECUTIONS ||
from.name === VIEWS.TEMPLATE_IMPORT ||
(toNodeViewTab === MAIN_HEADER_TABS.WORKFLOW && from.name === VIEWS.EXECUTION_DEBUG) ||
isReadOnlyEnvironment.value
) {
next();
return;
}
await workflowHelpers.promptSaveUnsavedWorkflowChanges(next, {
async confirm() {
// Make sure workflow id is empty when leaving the editor
workflowsStore.setWorkflowId(PLACEHOLDER_EMPTY_WORKFLOW_ID);
if (from.name === VIEWS.NEW_WORKFLOW) {
// Replace the current route with the new workflow route
// before navigating to the new route when saving new workflow.
await router.replace({
name: VIEWS.WORKFLOW,
params: { name: workflowId.value },
});
await router.push(to);
return false;
}
return true;
},
async cancel() {
workflowsStore.setWorkflowId(PLACEHOLDER_EMPTY_WORKFLOW_ID);
resetWorkspace();
},
});
});
</script> </script>
<template> <template>