1
0

dialog.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
  27. if (e.keyCode == 13 || e.keyCode == 27) {
  28. CodeMirror.e_stop(e);
  29. close();
  30. me.focus();
  31. if (e.keyCode == 13) callback(inp.value);
  32. }
  33. });
  34. if (options && options.onKeyUp) {
  35. CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
  36. }
  37. if (options && options.value) inp.value = options.value;
  38. inp.focus();
  39. CodeMirror.on(inp, "blur", close);
  40. } else if (button = dialog.getElementsByTagName("button")[0]) {
  41. CodeMirror.on(button, "click", function() {
  42. close();
  43. me.focus();
  44. });
  45. button.focus();
  46. CodeMirror.on(button, "blur", close);
  47. }
  48. return close;
  49. });
  50. CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
  51. var dialog = dialogDiv(this, template, options && options.bottom);
  52. var buttons = dialog.getElementsByTagName("button");
  53. var closed = false, me = this, blurring = 1;
  54. function close() {
  55. if (closed) return;
  56. closed = true;
  57. dialog.parentNode.removeChild(dialog);
  58. me.focus();
  59. }
  60. buttons[0].focus();
  61. for (var i = 0; i < buttons.length; ++i) {
  62. var b = buttons[i];
  63. (function(callback) {
  64. CodeMirror.on(b, "click", function(e) {
  65. CodeMirror.e_preventDefault(e);
  66. close();
  67. if (callback) callback(me);
  68. });
  69. })(callbacks[i]);
  70. CodeMirror.on(b, "blur", function() {
  71. --blurring;
  72. setTimeout(function() { if (blurring <= 0) close(); }, 200);
  73. });
  74. CodeMirror.on(b, "focus", function() { ++blurring; });
  75. }
  76. });
  77. })();