inlinedform.js 2.0 KB

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