Caret/js/ui/dialog.js

90 lines
2.2 KiB
JavaScript
Raw Normal View History

define([
"editor",
2014-01-22 16:37:28 +00:00
"util/template!templates/dialog.html",
"util/dom2"
2014-01-22 16:37:28 +00:00
], function(editor, inflate) {
2014-02-27 06:34:02 +00:00
/*
You can call dialog() to present a modal, since alert() isn't allowed.
Currently, your callback will be passed the value set for the button pressed. Form support is coming.
*/
return function(text, buttons, callback) {
if (typeof buttons == "function" || typeof buttons == "undefined") {
callback = buttons;
buttons = ["ok"];
}
2014-01-22 16:37:28 +00:00
buttons = buttons.map(function(options) {
if (typeof options == "string") {
return {
label: options,
value: options
};
}
return options;
});
2014-01-22 16:37:28 +00:00
var modal = inflate.get("templates/dialog.html", {
text: text,
buttons: buttons
});
document.body.append(modal);
2014-01-22 16:37:28 +00:00
var defaultButton = modal.find("button.default");
if (!defaultButton) defaultButton = modal.find("button");
defaultButton.focus();
var onKeyDown = function(e) {
2013-09-04 23:36:33 +00:00
e.stopPropagation();
e.stopImmediatePropagation();
if (e.ctrlKey || e.metaKey || e.shiftKey) {
e.preventDefault();
}
2013-09-06 16:33:05 +00:00
//check escape
if (e.keyCode == 27) {
modal.remove();
editor.focus();
2013-09-06 16:33:05 +00:00
if (callback) callback();
}
2013-09-04 23:36:33 +00:00
};
var onKeyPress = function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
//allow Enter to trigger clicks
if (e.keyCode != 13) {
e.preventDefault();
}
buttons.forEach(function(options) {
if (typeof options == "string") return;
if (options.shortcut && options.shortcut == String.fromCharCode(e.charCode)) {
modal.remove();
editor.focus();
if (callback) callback(options.value);
}
2014-02-27 06:34:02 +00:00
});
}
2013-09-04 23:36:33 +00:00
2014-01-22 16:37:28 +00:00
var clickButton = function(e) {
var target = e.target;
if (!target.matches("button")) return;
modal.remove();
try {
2014-01-22 16:37:28 +00:00
var value = JSON.parse(target.value);
if (callback) callback(value);
} catch (err) {
//do nothing
}
editor.focus();
};
2014-01-22 16:37:28 +00:00
modal.onkeydown = onKeyDown;
modal.onkeypress = onKeyPress;
modal.onclick = clickButton;
2013-09-04 23:36:33 +00:00
2014-02-27 06:34:02 +00:00
};
});