Caret/js/ui/dialog.js

89 lines
2.2 KiB
JavaScript
Raw Normal View History

define([
"editor",
"util/dom2"
], function(editor) {
return function(text, buttons, callback) {
if (typeof buttons == "function" || typeof buttons == "undefined") {
callback = buttons;
buttons = ["ok"];
}
var modal = document.find("template#dialog").content.cloneNode(true).find(".modal-overlay");
var buttonRow = modal.find(".button-row");
var message = modal.find(".text");
message.innerHTML = text;
document.body.append(modal);
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
console.log(e.keyCode);
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);
}
})
}
2013-09-04 23:36:33 +00:00
modal.onkeydown = onKeyDown;
modal.onkeypress = onKeyPress;
2013-09-04 23:36:33 +00:00
var clickButton = function() {
modal.remove();
try {
var value = JSON.parse(this.value);
if (callback) callback(value);
} catch (err) {
//do nothing
}
editor.focus();
};
buttons.forEach(function(options) {
var button = document.createElement("button");
if (typeof options == "string") {
options = {
label: options,
value: options
}
}
button.innerHTML = options.label;
2013-09-24 22:35:15 +00:00
button.value = JSON.stringify(options.value);
if (options.focus) {
button.className = "default";
}
buttonRow.append(button);
button.on("click", clickButton);
});
2013-09-04 23:36:33 +00:00
2013-10-08 18:15:52 +00:00
var button = modal.find("button.default");
if (!button) button = modal.find("button");
button.focus();
2013-09-04 23:36:33 +00:00
}
});