inlinedform.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. enabledOnClick: false,
  67. }
  68. );
  69. // submit on click outside
  70. document.addEventListener('click', function(evt) {
  71. const openedForm = currentlyOpenedForm.get();
  72. const isClickOutside = $(evt.target).closest('.js-inlined-form').length === 0;
  73. if (openedForm && isClickOutside) {
  74. $('.js-inlined-form button[type=submit]').click();
  75. openedForm.close();
  76. }
  77. }, true);