EditorView.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. /**
  2. * @file
  3. * An abstract Backbone View that controls an in-place editor.
  4. */
  5. (function ($, Backbone, Drupal) {
  6. 'use strict';
  7. Drupal.quickedit.EditorView = Backbone.View.extend(/** @lends Drupal.quickedit.EditorView# */{
  8. /**
  9. * A base implementation that outlines the structure for in-place editors.
  10. *
  11. * Specific in-place editor implementations should subclass (extend) this
  12. * View and override whichever method they deem necessary to override.
  13. *
  14. * Typically you would want to override this method to set the
  15. * originalValue attribute in the FieldModel to such a value that your
  16. * in-place editor can revert to the original value when necessary.
  17. *
  18. * @example
  19. * <caption>If you override this method, you should call this
  20. * method (the parent class' initialize()) first.</caption>
  21. * Drupal.quickedit.EditorView.prototype.initialize.call(this, options);
  22. *
  23. * @constructs
  24. *
  25. * @augments Backbone.View
  26. *
  27. * @param {object} options
  28. * An object with the following keys:
  29. * @param {Drupal.quickedit.EditorModel} options.model
  30. * The in-place editor state model.
  31. * @param {Drupal.quickedit.FieldModel} options.fieldModel
  32. * The field model.
  33. *
  34. * @see Drupal.quickedit.EditorModel
  35. * @see Drupal.quickedit.editors.plain_text
  36. */
  37. initialize: function (options) {
  38. this.fieldModel = options.fieldModel;
  39. this.listenTo(this.fieldModel, 'change:state', this.stateChange);
  40. },
  41. /**
  42. * @inheritdoc
  43. */
  44. remove: function () {
  45. // The el property is the field, which should not be removed. Remove the
  46. // pointer to it, then call Backbone.View.prototype.remove().
  47. this.setElement();
  48. Backbone.View.prototype.remove.call(this);
  49. },
  50. /**
  51. * Returns the edited element.
  52. *
  53. * For some single cardinality fields, it may be necessary or useful to
  54. * not in-place edit (and hence decorate) the DOM element with the
  55. * data-quickedit-field-id attribute (which is the field's wrapper), but a
  56. * specific element within the field's wrapper.
  57. * e.g. using a WYSIWYG editor on a body field should happen on the DOM
  58. * element containing the text itself, not on the field wrapper.
  59. *
  60. * @return {jQuery}
  61. * A jQuery-wrapped DOM element.
  62. *
  63. * @see Drupal.quickedit.editors.plain_text
  64. */
  65. getEditedElement: function () {
  66. return this.$el;
  67. },
  68. /**
  69. *
  70. * @return {object}
  71. * Returns 3 Quick Edit UI settings that depend on the in-place editor:
  72. * - Boolean padding: indicates whether padding should be applied to the
  73. * edited element, to guarantee legibility of text.
  74. * - Boolean unifiedToolbar: provides the in-place editor with the ability
  75. * to insert its own toolbar UI into Quick Edit's tightly integrated
  76. * toolbar.
  77. * - Boolean fullWidthToolbar: indicates whether Quick Edit's tightly
  78. * integrated toolbar should consume the full width of the element,
  79. * rather than being just long enough to accommodate a label.
  80. */
  81. getQuickEditUISettings: function () {
  82. return {padding: false, unifiedToolbar: false, fullWidthToolbar: false, popup: false};
  83. },
  84. /**
  85. * Determines the actions to take given a change of state.
  86. *
  87. * @param {Drupal.quickedit.FieldModel} fieldModel
  88. * The quickedit `FieldModel` that holds the state.
  89. * @param {string} state
  90. * The state of the associated field. One of
  91. * {@link Drupal.quickedit.FieldModel.states}.
  92. */
  93. stateChange: function (fieldModel, state) {
  94. var from = fieldModel.previous('state');
  95. var to = state;
  96. switch (to) {
  97. case 'inactive':
  98. // An in-place editor view will not yet exist in this state, hence
  99. // this will never be reached. Listed for sake of completeness.
  100. break;
  101. case 'candidate':
  102. // Nothing to do for the typical in-place editor: it should not be
  103. // visible yet. Except when we come from the 'invalid' state, then we
  104. // clean up.
  105. if (from === 'invalid') {
  106. this.removeValidationErrors();
  107. }
  108. break;
  109. case 'highlighted':
  110. // Nothing to do for the typical in-place editor: it should not be
  111. // visible yet.
  112. break;
  113. case 'activating':
  114. // The user has indicated he wants to do in-place editing: if
  115. // something needs to be loaded (CSS/JavaScript/server data/…), then
  116. // do so at this stage, and once the in-place editor is ready,
  117. // set the 'active' state. A "loading" indicator will be shown in the
  118. // UI for as long as the field remains in this state.
  119. var loadDependencies = function (callback) {
  120. // Do the loading here.
  121. callback();
  122. };
  123. loadDependencies(function () {
  124. fieldModel.set('state', 'active');
  125. });
  126. break;
  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: function () {
  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: function () {
  170. var fieldModel = this.fieldModel;
  171. var editorModel = this.model;
  172. var backstageId = 'quickedit_backstage-' + this.fieldModel.id.replace(/[\/\[\]\_\s]/g, '-');
  173. function fillAndSubmitForm(value) {
  174. var $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. var 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. var self = this;
  198. Drupal.quickedit.util.form.load(formOptions, function (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. var $backstage = $(Drupal.theme('quickeditBackstage', {id: backstageId})).appendTo('body');
  203. // Hidden forms are stuffed into the backstage container for this field.
  204. var $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. var $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: function () {
  253. var $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: function () {
  268. this.getEditedElement()
  269. .removeClass('quickedit-validation-error')
  270. .next('.quickedit-validation-errors')
  271. .remove();
  272. }
  273. });
  274. }(jQuery, Backbone, Drupal));