inlinedform.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // A inlined form is used to provide a quick edition of single field for a given
  2. // document. Clicking on a edit button should display the form to edit the field
  3. // value. The form can then be submited, or just closed.
  4. //
  5. // When the form is closed we save non-submitted values in memory to avoid any
  6. // data loss.
  7. //
  8. // Usage:
  9. //
  10. // +inlineForm
  11. // // the content when the form is open
  12. // else
  13. // // the content when the form is close (optional)
  14. // We can only have one inlined form element opened at a time
  15. // XXX Could we avoid using a global here ? This is used in Mousetrap
  16. // keyboard.js
  17. var currentlyOpenedForm = new ReactiveVar(null);
  18. BlazeComponent.extendComponent({
  19. template: function() {
  20. return 'inlinedForm';
  21. },
  22. mixins: function() {
  23. return [Mixins.CachedValue];
  24. },
  25. onCreated: function() {
  26. this.isOpen = new ReactiveVar(false);
  27. },
  28. onDestroyed: function() {
  29. currentlyOpenedForm.set(null);
  30. },
  31. open: function() {
  32. // Close currently opened form, if any
  33. EscapeActions.executeUpTo('inlinedForm');
  34. this.isOpen.set(true);
  35. currentlyOpenedForm.set(this);
  36. },
  37. close: function() {
  38. this.saveValue();
  39. this.isOpen.set(false);
  40. currentlyOpenedForm.set(null);
  41. },
  42. getValue: function() {
  43. var input = this.find('textarea,input[type=text]');
  44. return this.isOpen.get() && input && input.value;
  45. },
  46. saveValue: function() {
  47. this.callFirstWith(this, 'setCache', this.getValue());
  48. },
  49. events: function() {
  50. return [{
  51. 'click .js-close-inlined-form': this.close,
  52. 'click .js-open-inlined-form': this.open,
  53. // Pressing Ctrl+Enter should submit the form
  54. 'keydown form textarea': function(evt) {
  55. if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) {
  56. this.find('button[type=submit]').click();
  57. }
  58. },
  59. // Close the inlined form when after its submission
  60. submit: function() {
  61. var self = this;
  62. // XXX Swith to an arrow function here when we'll have ES6
  63. if (this.currentData().autoclose !== false) {
  64. Tracker.afterFlush(function() {
  65. self.close();
  66. self.callFirstWith(self, 'resetCache');
  67. });
  68. }
  69. }
  70. }];
  71. }
  72. }).register('inlinedForm');
  73. // Press escape to close the currently opened inlinedForm
  74. EscapeActions.register('inlinedForm',
  75. function() { currentlyOpenedForm.get().close(); },
  76. function() { return currentlyOpenedForm.get() !== null; }, {
  77. noClickEscapeOn: '.js-inlined-form'
  78. }
  79. );