EditorView.es6.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /**
  2. * @file
  3. * An abstract Backbone View that controls an in-place editor.
  4. */
  5. (function ($, Backbone, Drupal) {
  6. Drupal.quickedit.EditorView = Backbone.View.extend(/** @lends Drupal.quickedit.EditorView# */{
  7. /**
  8. * A base implementation that outlines the structure for in-place editors.
  9. *
  10. * Specific in-place editor implementations should subclass (extend) this
  11. * View and override whichever method they deem necessary to override.
  12. *
  13. * Typically you would want to override this method to set the
  14. * originalValue attribute in the FieldModel to such a value that your
  15. * in-place editor can revert to the original value when necessary.
  16. *
  17. * @example
  18. * <caption>If you override this method, you should call this
  19. * method (the parent class' initialize()) first.</caption>
  20. * Drupal.quickedit.EditorView.prototype.initialize.call(this, options);
  21. *
  22. * @constructs
  23. *
  24. * @augments Backbone.View
  25. *
  26. * @param {object} options
  27. * An object with the following keys:
  28. * @param {Drupal.quickedit.EditorModel} options.model
  29. * The in-place editor state model.
  30. * @param {Drupal.quickedit.FieldModel} options.fieldModel
  31. * The field model.
  32. *
  33. * @see Drupal.quickedit.EditorModel
  34. * @see Drupal.quickedit.editors.plain_text
  35. */
  36. initialize(options) {
  37. this.fieldModel = options.fieldModel;
  38. this.listenTo(this.fieldModel, 'change:state', this.stateChange);
  39. },
  40. /**
  41. * @inheritdoc
  42. */
  43. remove() {
  44. // The el property is the field, which should not be removed. Remove the
  45. // pointer to it, then call Backbone.View.prototype.remove().
  46. this.setElement();
  47. Backbone.View.prototype.remove.call(this);
  48. },
  49. /**
  50. * Returns the edited element.
  51. *
  52. * For some single cardinality fields, it may be necessary or useful to
  53. * not in-place edit (and hence decorate) the DOM element with the
  54. * data-quickedit-field-id attribute (which is the field's wrapper), but a
  55. * specific element within the field's wrapper.
  56. * e.g. using a WYSIWYG editor on a body field should happen on the DOM
  57. * element containing the text itself, not on the field wrapper.
  58. *
  59. * @return {jQuery}
  60. * A jQuery-wrapped DOM element.
  61. *
  62. * @see Drupal.quickedit.editors.plain_text
  63. */
  64. getEditedElement() {
  65. return this.$el;
  66. },
  67. /**
  68. *
  69. * @return {object}
  70. * Returns 3 Quick Edit UI settings that depend on the in-place editor:
  71. * - Boolean padding: indicates whether padding should be applied to the
  72. * edited element, to guarantee legibility of text.
  73. * - Boolean unifiedToolbar: provides the in-place editor with the ability
  74. * to insert its own toolbar UI into Quick Edit's tightly integrated
  75. * toolbar.
  76. * - Boolean fullWidthToolbar: indicates whether Quick Edit's tightly
  77. * integrated toolbar should consume the full width of the element,
  78. * rather than being just long enough to accommodate a label.
  79. */
  80. getQuickEditUISettings() {
  81. return { padding: false, unifiedToolbar: false, fullWidthToolbar: false, popup: false };
  82. },
  83. /**
  84. * Determines the actions to take given a change of state.
  85. *
  86. * @param {Drupal.quickedit.FieldModel} fieldModel
  87. * The quickedit `FieldModel` that holds the state.
  88. * @param {string} state
  89. * The state of the associated field. One of
  90. * {@link Drupal.quickedit.FieldModel.states}.
  91. */
  92. stateChange(fieldModel, state) {
  93. const from = fieldModel.previous('state');
  94. const to = state;
  95. switch (to) {
  96. case 'inactive':
  97. // An in-place editor view will not yet exist in this state, hence
  98. // this will never be reached. Listed for sake of completeness.
  99. break;
  100. case 'candidate':
  101. // Nothing to do for the typical in-place editor: it should not be
  102. // visible yet. Except when we come from the 'invalid' state, then we
  103. // clean up.
  104. if (from === 'invalid') {
  105. this.removeValidationErrors();
  106. }
  107. break;
  108. case 'highlighted':
  109. // Nothing to do for the typical in-place editor: it should not be
  110. // visible yet.
  111. break;
  112. case 'activating': {
  113. // The user has indicated he wants to do in-place editing: if
  114. // something needs to be loaded (CSS/JavaScript/server data/…), then
  115. // do so at this stage, and once the in-place editor is ready,
  116. // set the 'active' state. A "loading" indicator will be shown in the
  117. // UI for as long as the field remains in this state.
  118. const loadDependencies = function (callback) {
  119. // Do the loading here.
  120. callback();
  121. };
  122. loadDependencies(() => {
  123. fieldModel.set('state', 'active');
  124. });
  125. break;
  126. }
  127. case 'active':
  128. // The user can now actually use the in-place editor.
  129. break;
  130. case 'changed':
  131. // Nothing to do for the typical in-place editor. The UI will show an
  132. // indicator that the field has changed.
  133. break;
  134. case 'saving':
  135. // When the user has indicated he wants to save his changes to this
  136. // field, this state will be entered. If the previous saving attempt
  137. // resulted in validation errors, the previous state will be
  138. // 'invalid'. Clean up those validation errors while the user is
  139. // saving.
  140. if (from === 'invalid') {
  141. this.removeValidationErrors();
  142. }
  143. this.save();
  144. break;
  145. case 'saved':
  146. // Nothing to do for the typical in-place editor. Immediately after
  147. // being saved, a field will go to the 'candidate' state, where it
  148. // should no longer be visible (after all, the field will then again
  149. // just be a *candidate* to be in-place edited).
  150. break;
  151. case 'invalid':
  152. // The modified field value was attempted to be saved, but there were
  153. // validation errors.
  154. this.showValidationErrors();
  155. break;
  156. }
  157. },
  158. /**
  159. * Reverts the modified value to the original, before editing started.
  160. */
  161. revert() {
  162. // A no-op by default; each editor should implement reverting itself.
  163. // Note that if the in-place editor does not cause the FieldModel's
  164. // element to be modified, then nothing needs to happen.
  165. },
  166. /**
  167. * Saves the modified value in the in-place editor for this field.
  168. */
  169. save() {
  170. const fieldModel = this.fieldModel;
  171. const editorModel = this.model;
  172. const backstageId = `quickedit_backstage-${this.fieldModel.id.replace(/[/[\]_\s]/g, '-')}`;
  173. function fillAndSubmitForm(value) {
  174. const $form = $(`#${backstageId}`).find('form');
  175. // Fill in the value in any <input> that isn't hidden or a submit
  176. // button.
  177. $form.find(':input[type!="hidden"][type!="submit"]:not(select)')
  178. // Don't mess with the node summary.
  179. .not('[name$="\\[summary\\]"]').val(value);
  180. // Submit the form.
  181. $form.find('.quickedit-form-submit').trigger('click.quickedit');
  182. }
  183. const formOptions = {
  184. fieldID: this.fieldModel.get('fieldID'),
  185. $el: this.$el,
  186. nocssjs: true,
  187. other_view_modes: fieldModel.findOtherViewModes(),
  188. // Reset an existing entry for this entity in the PrivateTempStore (if
  189. // any) when saving the field. Logically speaking, this should happen in
  190. // a separate request because this is an entity-level operation, not a
  191. // field-level operation. But that would require an additional request,
  192. // that might not even be necessary: it is only when a user saves a
  193. // first changed field for an entity that this needs to happen:
  194. // precisely now!
  195. reset: !this.fieldModel.get('entity').get('inTempStore'),
  196. };
  197. const self = this;
  198. Drupal.quickedit.util.form.load(formOptions, (form, ajax) => {
  199. // Create a backstage area for storing forms that are hidden from view
  200. // (hence "backstage" — since the editing doesn't happen in the form, it
  201. // happens "directly" in the content, the form is only used for saving).
  202. const $backstage = $(Drupal.theme('quickeditBackstage', { id: backstageId })).appendTo('body');
  203. // Hidden forms are stuffed into the backstage container for this field.
  204. const $form = $(form).appendTo($backstage);
  205. // Disable the browser's HTML5 validation; we only care about server-
  206. // side validation. (Not disabling this will actually cause problems
  207. // because browsers don't like to set HTML5 validation errors on hidden
  208. // forms.)
  209. $form.prop('novalidate', true);
  210. const $submit = $form.find('.quickedit-form-submit');
  211. self.formSaveAjax = Drupal.quickedit.util.form.ajaxifySaving(formOptions, $submit);
  212. function removeHiddenForm() {
  213. Drupal.quickedit.util.form.unajaxifySaving(self.formSaveAjax);
  214. delete self.formSaveAjax;
  215. $backstage.remove();
  216. }
  217. // Successfully saved.
  218. self.formSaveAjax.commands.quickeditFieldFormSaved = function (ajax, response, status) {
  219. removeHiddenForm();
  220. // First, transition the state to 'saved'.
  221. fieldModel.set('state', 'saved');
  222. // Second, set the 'htmlForOtherViewModes' attribute, so that when
  223. // this field is rerendered, the change can be propagated to other
  224. // instances of this field, which may be displayed in different view
  225. // modes.
  226. fieldModel.set('htmlForOtherViewModes', response.other_view_modes);
  227. // Finally, set the 'html' attribute on the field model. This will
  228. // cause the field to be rerendered.
  229. fieldModel.set('html', response.data);
  230. };
  231. // Unsuccessfully saved; validation errors.
  232. self.formSaveAjax.commands.quickeditFieldFormValidationErrors = function (ajax, response, status) {
  233. removeHiddenForm();
  234. editorModel.set('validationErrors', response.data);
  235. fieldModel.set('state', 'invalid');
  236. };
  237. // The quickeditFieldForm AJAX command is only called upon loading the
  238. // form for the first time, and when there are validation errors in the
  239. // form; Form API then marks which form items have errors. This is
  240. // useful for the form-based in-place editor, but pointless for any
  241. // other: the form itself won't be visible at all anyway! So, we just
  242. // ignore it.
  243. self.formSaveAjax.commands.quickeditFieldForm = function () {};
  244. fillAndSubmitForm(editorModel.get('currentValue'));
  245. });
  246. },
  247. /**
  248. * Shows validation error messages.
  249. *
  250. * Should be called when the state is changed to 'invalid'.
  251. */
  252. showValidationErrors() {
  253. const $errors = $('<div class="quickedit-validation-errors"></div>')
  254. .append(this.model.get('validationErrors'));
  255. this.getEditedElement()
  256. .addClass('quickedit-validation-error')
  257. .after($errors);
  258. },
  259. /**
  260. * Cleans up validation error messages.
  261. *
  262. * Should be called when the state is changed to 'candidate' or 'saving'. In
  263. * the case of the latter: the user has modified the value in the in-place
  264. * editor again to attempt to save again. In the case of the latter: the
  265. * invalid value was discarded.
  266. */
  267. removeValidationErrors() {
  268. this.getEditedElement()
  269. .removeClass('quickedit-validation-error')
  270. .next('.quickedit-validation-errors')
  271. .remove();
  272. },
  273. });
  274. }(jQuery, Backbone, Drupal));