[ui] Warn users when they leave an edited but unsaved variable page (#14665)

* Warning on attempt to leave

* Lintfix

* Only router.off once

* Dont warn on transition when only updating queryparams

* Remove double-push and queryparam-only issues, thanks @lgfa29

* Acceptance tests

* Changelog
This commit is contained in:
Phil Renaud 2022-09-23 16:53:40 -04:00 committed by GitHub
parent a28e1bcc1e
commit 497bd02169
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 133 additions and 4 deletions

3
.changelog/14665.txt Normal file
View File

@ -0,0 +1,3 @@
```release-note:improvement
ui: warn a user before they leave a Variables form page with unsaved information
```

View File

@ -1,7 +1,7 @@
// @ts-check
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { action, computed } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { trimPath } from '../helpers/trim-path';
@ -12,6 +12,7 @@ import MutableArray from '@ember/array/mutable';
import { A } from '@ember/array';
import { stringifyObject } from 'nomad-ui/helpers/stringify-object';
import notifyConflict from 'nomad-ui/utils/notify-conflict';
import isEqual from 'lodash.isequal';
const EMPTY_KV = {
key: '',
@ -43,6 +44,7 @@ export default class VariableFormComponent extends Component {
constructor() {
super(...arguments);
set(this, 'path', this.args.model.path);
this.addExitHandler();
}
@action
@ -93,7 +95,7 @@ export default class VariableFormComponent extends Component {
if (!this.args.model?.isNew) {
keyValues.pushObject(copy(EMPTY_KV));
}
this.keyValues = keyValues;
set(this, 'keyValues', keyValues);
this.JSONItems = stringifyObject([
this.keyValues.reduce((acc, { key, value }) => {
@ -182,7 +184,7 @@ export default class VariableFormComponent extends Component {
if (!nonEmptyItems.length) {
throw new Error('Please provide at least one key/value pair.');
} else {
this.keyValues = nonEmptyItems;
set(this, 'keyValues', nonEmptyItems);
}
if (this.args.model?.isNew) {
@ -206,6 +208,7 @@ export default class VariableFormComponent extends Component {
destroyOnClick: false,
timeout: 5000,
});
this.removeExitHandler();
this.router.transitionTo('variables.variable', this.args.model.id);
} catch (error) {
notifyConflict(this)(error);
@ -326,4 +329,60 @@ export default class VariableFormComponent extends Component {
this.args.model.pathLinkedEntities?.task
);
}
//#region Unsaved Changes Confirmation
hasRemovedExitHandler = false;
@computed(
'args.model.{keyValues,path}',
'keyValues.@each.{key,value}',
'path'
)
get hasUserModifiedAttributes() {
const compactedBasicKVs = this.keyValues
.map((kv) => ({ key: kv.key, value: kv.value }))
.filter((kv) => kv.key || kv.value);
const compactedPassedKVs = this.args.model.keyValues.filter(
(kv) => kv.key || kv.value
);
const unequal =
!isEqual(compactedBasicKVs, compactedPassedKVs) ||
!isEqual(this.path, this.args.model.path);
return unequal;
}
addExitHandler() {
this.router.on('routeWillChange', this, this.confirmExit);
}
removeExitHandler() {
if (!this.hasRemovedExitHandler) {
this.router.off('routeWillChange', this, this.confirmExit);
this.hasRemovedExitHandler = true;
}
}
confirmExit(transition) {
if (transition.isAborted || transition.queryParamsOnly) return;
if (this.hasUserModifiedAttributes) {
if (
!confirm(
'Your variable has unsaved changes. Are you sure you want to leave?'
)
) {
transition.abort();
} else {
this.removeExitHandler();
}
}
}
willDestroy() {
super.willDestroy(...arguments);
this.removeExitHandler();
}
//#endregion Unsaved Changes Confirmation
}

View File

@ -11,7 +11,7 @@
Edit
{{this.model.path}}
<Toggle
data-test-memory-toggle
data-test-json-toggle
@isActive={{eq this.view "json"}}
@onToggle={{action this.toggleView}}
title="JSON"

View File

@ -590,6 +590,73 @@ module('Acceptance | variables', function (hooks) {
// Reset Token
window.localStorage.nomadTokenSecret = null;
});
test('warns you if you try to leave with an unsaved form', async function (assert) {
// Arrange Test Set-up
allScenarios.variableTestCluster(server);
const variablesToken = server.db.tokens.find(VARIABLE_TOKEN_ID);
window.localStorage.nomadTokenSecret = variablesToken.secretId;
const originalWindowConfirm = window.confirm;
let confirmFired = false;
let leave = true;
window.confirm = function () {
confirmFired = true;
return leave;
};
// End Test Set-up
await Variables.visitConflicting();
document.querySelector('[data-test-var-key]').value = ''; // clear current input
await typeIn('[data-test-var-key]', 'buddy');
await typeIn('[data-test-var-value]', 'pal');
await click('[data-test-gutter-link="jobs"]');
assert.ok(confirmFired, 'Confirm fired when leaving with unsaved form');
assert.equal(
currentURL(),
'/jobs?namespace=*',
'Opted to leave, ended up on desired page'
);
// Reset checks
confirmFired = false;
leave = false;
await Variables.visitConflicting();
document.querySelector('[data-test-var-key]').value = ''; // clear current input
await typeIn('[data-test-var-key]', 'buddy');
await typeIn('[data-test-var-value]', 'pal');
await click('[data-test-gutter-link="jobs"]');
assert.ok(confirmFired, 'Confirm fired when leaving with unsaved form');
assert.equal(
currentURL(),
'/variables/var/Auto-conflicting%20Variable@default/edit',
'Opted to stay, did not leave page'
);
// Reset checks
confirmFired = false;
await Variables.visitConflicting();
document.querySelector('[data-test-var-key]').value = ''; // clear current input
await typeIn('[data-test-var-key]', 'buddy');
await typeIn('[data-test-var-value]', 'pal');
await click('[data-test-json-toggle]');
assert.notOk(
confirmFired,
'Confirm did not fire when only transitioning queryParams'
);
assert.equal(
currentURL(),
'/variables/var/Auto-conflicting%20Variable@default/edit?view=json',
'Stayed on page, queryParams changed'
);
// Reset Token
window.localStorage.nomadTokenSecret = null;
// Restore the original window.confirm implementation
window.confirm = originalWindowConfirm;
});
});
module('delete flow', function () {