dialog.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Open simple dialogs on top of an editor. Relies on dialog.css.
  2. (function() {
  3. function dialogDiv(cm, template, bottom) {
  4. var wrap = cm.getWrapperElement();
  5. var dialog;
  6. dialog = wrap.appendChild(document.createElement("div"));
  7. if (bottom) {
  8. dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
  9. } else {
  10. dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
  11. }
  12. dialog.innerHTML = template;
  13. return dialog;
  14. }
  15. CodeMirror.defineExtension("openDialog", function(template, callback, options) {
  16. var dialog = dialogDiv(this, template, options && options.bottom);
  17. var closed = false, me = this;
  18. function close() {
  19. if (closed) return;
  20. closed = true;
  21. dialog.parentNode.removeChild(dialog);
  22. }
  23. var inp = dialog.getElementsByTagName("input")[0], button;
  24. if (inp) {
  25. CodeMirror.on(inp, "keydown", function(e) {
  26. if (e.keyCode == 13 || e.keyCode == 27) {
  27. CodeMirror.e_stop(e);
  28. close();
  29. me.focus();
  30. if (e.keyCode == 13) callback(inp.value);
  31. }
  32. });
  33. inp.focus();
  34. CodeMirror.on(inp, "blur", close);
  35. } else if (button = dialog.getElementsByTagName("button")[0]) {
  36. CodeMirror.on(button, "click", function() {
  37. close();
  38. me.focus();
  39. });
  40. button.focus();
  41. CodeMirror.on(button, "blur", close);
  42. }
  43. return close;
  44. });
  45. CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
  46. var dialog = dialogDiv(this, template, options && options.bottom);
  47. var buttons = dialog.getElementsByTagName("button");
  48. var closed = false, me = this, blurring = 1;
  49. function close() {
  50. if (closed) return;
  51. closed = true;
  52. dialog.parentNode.removeChild(dialog);
  53. me.focus();
  54. }
  55. buttons[0].focus();
  56. for (var i = 0; i < buttons.length; ++i) {
  57. var b = buttons[i];
  58. (function(callback) {
  59. CodeMirror.on(b, "click", function(e) {
  60. CodeMirror.e_preventDefault(e);
  61. close();
  62. if (callback) callback(me);
  63. });
  64. })(callbacks[i]);
  65. CodeMirror.on(b, "blur", function() {
  66. --blurring;
  67. setTimeout(function() { if (blurring <= 0) close(); }, 200);
  68. });
  69. CodeMirror.on(b, "focus", function() { ++blurring; });
  70. }
  71. });
  72. })();