var ACTIVE, Promise, React, TransitionAssistant, TutorDialog, UnsavedStateMixin, _, moment;
ACTIVE = [];
_ = require('underscore');
Promise = require('es6-promise').Promise;
moment = require('moment');
React = require('react');
TutorDialog = require('./tutor-dialog');
UnsavedStateMixin = {
componentWillMount: function() {
return ACTIVE.push(this);
},
componentWillUnmount: function() {
return ACTIVE.splice(ACTIVE.indexOf(this), 1);
},
_cannotTransition: function() {
return typeof this.hasUnsavedState === "function" ? this.hasUnsavedState() : void 0;
},
_unsavedMessages: function() {
return (typeof this.unsavedStateMessages === "function" ? this.unsavedStateMessages() : void 0) || [this.constructor.displayName + " has unsaved data"];
}
};
TransitionAssistant = {
canTransition: function() {
return !_.any(ACTIVE, function(c) {
return c._cannotTransition();
});
},
unsavedMessages: function() {
return _.flatten(_.invoke(ACTIVE, '_unsavedMessages'), 1);
},
checkTransitionStateTo: function(destination) {
return new Promise((function(_this) {
return function(onOk, onCancel) {
var body, i, message;
if (_this.canTransition()) {
return onOk();
} else {
body = React.createElement("div", null, (function() {
var j, len, ref, results;
ref = this.unsavedMessages();
results = [];
for (i = j = 0, len = ref.length; j < len; i = ++j) {
message = ref[i];
results.push(React.createElement("p", {
"key": i
}, message));
}
return results;
}).call(_this));
return TutorDialog.show({
title: "Proceed to " + destination + " ?",
body: body
}).then(function() {
_this.lastCancel = moment();
return onOk();
}, onCancel);
}
};
})(this));
},
wasJustApproved: function() {
return this.lastCancel && this.lastCancel.isBefore(moment().add(1, 'second'));
},
startMonitoring: function() {
delete this.startMonitoring;
return window.onbeforeunload = (function(_this) {
return function() {
if (!(_this.canTransition() || _this.wasJustApproved())) {
return _this.unsavedMessages().join("\n");
}
};
})(this);
}
};
module.exports = {
UnsavedStateMixin: UnsavedStateMixin,
TransitionAssistant: TransitionAssistant
};
|