Commit 9c1fcd90 authored by Himanshu Kapoor's avatar Himanshu Kapoor Committed by Enrique Alcántara

Trigger unsaved changes warning in snippets

On navigations, if there are any unsaved changes in the snippet,
trigger a onbeforeunload event to confirm user navigation.
parent cb0bfc12
......@@ -56,6 +56,7 @@ export default {
blob: {},
fileName: '',
content: '',
originalContent: '',
isContentLoading: true,
isUpdating: false,
newSnippet: false,
......@@ -97,7 +98,24 @@ export default {
return `${this.isProjectSnippet ? 'project' : 'personal'}_snippet_description`;
},
},
created() {
window.addEventListener('beforeunload', this.onBeforeUnload);
},
destroyed() {
window.removeEventListener('beforeunload', this.onBeforeUnload);
},
methods: {
onBeforeUnload(e = {}) {
const returnValue = __('Are you sure you want to lose unsaved changes?');
if (!this.hasChanges()) return undefined;
Object.assign(e, { returnValue });
return returnValue;
},
hasChanges() {
return this.content !== this.originalContent;
},
updateFileName(newName) {
this.fileName = newName;
},
......@@ -125,7 +143,9 @@ export default {
axios
.get(url)
.then(res => {
this.originalContent = res.data;
this.content = res.data;
this.isContentLoading = false;
})
.catch(e => this.flashAPIFailure(e));
......@@ -172,6 +192,7 @@ export default {
if (errors.length) {
this.flashAPIFailure(errors[0]);
} else {
this.originalContent = this.content;
redirectTo(baseObj.snippet.webUrl);
}
})
......
---
title: Trigger unsaved changes warning in snippets on navigating away
merge_request: 34640
author:
type: added
......@@ -307,6 +307,16 @@ describe('Snippet Edit app', () => {
});
});
it('makes sure there are no unsaved changes in the snippet', () => {
createComponent();
clickSubmitBtn();
return waitForPromises().then(() => {
expect(wrapper.vm.originalContent).toBe(wrapper.vm.content);
expect(wrapper.vm.hasChanges()).toBe(false);
});
});
it.each`
newSnippet | projectPath | mutationName
${true} | ${rawProjectPathMock} | ${'CreateSnippetMutation with projectPath'}
......@@ -419,5 +429,33 @@ describe('Snippet Edit app', () => {
expect(resolveMutate).toHaveBeenCalledWith(updateMutationPayload());
});
});
describe('on before unload', () => {
let event;
let returnValueSetter;
beforeEach(() => {
createComponent();
event = new Event('beforeunload');
returnValueSetter = jest.spyOn(event, 'returnValue', 'set');
});
it('does not prevent page navigation if there are no changes to the snippet content', () => {
window.dispatchEvent(event);
expect(returnValueSetter).not.toHaveBeenCalled();
});
it('prevents page navigation if there are some changes in the snippet content', () => {
wrapper.setData({ content: 'new content' });
window.dispatchEvent(event);
expect(returnValueSetter).toHaveBeenCalledWith(
'Are you sure you want to lose unsaved changes?',
);
});
});
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment