inlinedform.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. currentlyOpenedForm = new ReactiveVar(null);
  16. InlinedForm = BlazeComponent.extendComponent({
  17. template: function() {
  18. return 'inlinedForm';
  19. },
  20. onCreated: function() {
  21. this.isOpen = new ReactiveVar(false);
  22. },
  23. onDestroyed: function() {
  24. currentlyOpenedForm.set(null);
  25. },
  26. open: function() {
  27. // Close currently opened form, if any
  28. EscapeActions.executeUpTo('inlinedForm');
  29. this.isOpen.set(true);
  30. currentlyOpenedForm.set(this);
  31. },
  32. close: function() {
  33. this.isOpen.set(false);
  34. currentlyOpenedForm.set(null);
  35. },
  36. getValue: function() {
  37. var input = this.find('textarea,input[type=text]');
  38. return this.isOpen.get() && input && input.value;
  39. },
  40. events: function() {
  41. return [{
  42. 'click .js-close-inlined-form': this.close,
  43. 'click .js-open-inlined-form': this.open,
  44. // Pressing Ctrl+Enter should submit the form
  45. 'keydown form textarea': function(evt) {
  46. if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) {
  47. this.find('button[type=submit]').click();
  48. }
  49. },
  50. // Close the inlined form when after its submission
  51. submit: function() {
  52. if (this.currentData().autoclose !== false) {
  53. Tracker.afterFlush(() => {
  54. this.close();
  55. });
  56. }
  57. }
  58. }];
  59. }
  60. }).register('inlinedForm');
  61. // Press escape to close the currently opened inlinedForm
  62. EscapeActions.register('inlinedForm',
  63. function() { currentlyOpenedForm.get().close(); },
  64. function() { return currentlyOpenedForm.get() !== null; }, {
  65. noClickEscapeOn: '.js-inlined-form'
  66. }
  67. );