inlinedform.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. {
  44. 'click .js-close-inlined-form': this.close,
  45. 'click .js-open-inlined-form': this.open,
  46. // Pressing Ctrl+Enter should submit the form
  47. 'keydown form textarea'(evt) {
  48. if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) {
  49. this.find('button[type=submit]').click();
  50. }
  51. },
  52. // Close the inlined form when after its submission
  53. submit() {
  54. if (this.currentData().autoclose !== false) {
  55. Tracker.afterFlush(() => {
  56. this.close();
  57. });
  58. }
  59. },
  60. },
  61. ];
  62. },
  63. }).register('inlinedForm');
  64. // Press escape to close the currently opened inlinedForm
  65. EscapeActions.register(
  66. 'inlinedForm',
  67. () => {
  68. currentlyOpenedForm.get().close();
  69. },
  70. () => {
  71. return currentlyOpenedForm.get() !== null;
  72. },
  73. {
  74. enabledOnClick: false,
  75. },
  76. );
  77. // submit on click outside
  78. //document.addEventListener('click', function(evt) {
  79. // const openedForm = currentlyOpenedForm.get();
  80. // const isClickOutside = $(evt.target).closest('.js-inlined-form').length === 0;
  81. // if (openedForm && isClickOutside) {
  82. // $('.js-inlined-form button[type=submit]').click();
  83. // openedForm.close();
  84. // }
  85. //}, true);