AppView.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /**
  2. * @file
  3. * A Backbone View that controls the overall "in-place editing application".
  4. *
  5. * @see Drupal.quickedit.AppModel
  6. */
  7. (function ($, _, Backbone, Drupal) {
  8. 'use strict';
  9. // Indicates whether the page should be reloaded after in-place editing has
  10. // shut down. A page reload is necessary to re-instate the original HTML of
  11. // the edited fields if in-place editing has been canceled and one or more of
  12. // the entity's fields were saved to PrivateTempStore: one of them may have
  13. // been changed to the empty value and hence may have been rerendered as the
  14. // empty string, which makes it impossible for Quick Edit to know where to
  15. // restore the original HTML.
  16. var reload = false;
  17. Drupal.quickedit.AppView = Backbone.View.extend(/** @lends Drupal.quickedit.AppView# */{
  18. /**
  19. * @constructs
  20. *
  21. * @augments Backbone.View
  22. *
  23. * @param {object} options
  24. * An object with the following keys:
  25. * @param {Drupal.quickedit.AppModel} options.model
  26. * The application state model.
  27. * @param {Drupal.quickedit.EntityCollection} options.entitiesCollection
  28. * All on-page entities.
  29. * @param {Drupal.quickedit.FieldCollection} options.fieldsCollection
  30. * All on-page fields
  31. */
  32. initialize: function (options) {
  33. // AppView's configuration for handling states.
  34. // @see Drupal.quickedit.FieldModel.states
  35. this.activeFieldStates = ['activating', 'active'];
  36. this.singleFieldStates = ['highlighted', 'activating', 'active'];
  37. this.changedFieldStates = ['changed', 'saving', 'saved', 'invalid'];
  38. this.readyFieldStates = ['candidate', 'highlighted'];
  39. // Track app state.
  40. this.listenTo(options.entitiesCollection, 'change:state', this.appStateChange);
  41. this.listenTo(options.entitiesCollection, 'change:isActive', this.enforceSingleActiveEntity);
  42. // Track app state.
  43. this.listenTo(options.fieldsCollection, 'change:state', this.editorStateChange);
  44. // Respond to field model HTML representation change events.
  45. this.listenTo(options.fieldsCollection, 'change:html', this.renderUpdatedField);
  46. this.listenTo(options.fieldsCollection, 'change:html', this.propagateUpdatedField);
  47. // Respond to addition.
  48. this.listenTo(options.fieldsCollection, 'add', this.rerenderedFieldToCandidate);
  49. // Respond to destruction.
  50. this.listenTo(options.fieldsCollection, 'destroy', this.teardownEditor);
  51. },
  52. /**
  53. * Handles setup/teardown and state changes when the active entity changes.
  54. *
  55. * @param {Drupal.quickedit.EntityModel} entityModel
  56. * An instance of the EntityModel class.
  57. * @param {string} state
  58. * The state of the associated field. One of
  59. * {@link Drupal.quickedit.EntityModel.states}.
  60. */
  61. appStateChange: function (entityModel, state) {
  62. var app = this;
  63. var entityToolbarView;
  64. switch (state) {
  65. case 'launching':
  66. reload = false;
  67. // First, create an entity toolbar view.
  68. entityToolbarView = new Drupal.quickedit.EntityToolbarView({
  69. model: entityModel,
  70. appModel: this.model
  71. });
  72. entityModel.toolbarView = entityToolbarView;
  73. // Second, set up in-place editors.
  74. // They must be notified of state changes, hence this must happen
  75. // while the associated fields are still in the 'inactive' state.
  76. entityModel.get('fields').each(function (fieldModel) {
  77. app.setupEditor(fieldModel);
  78. });
  79. // Third, transition the entity to the 'opening' state, which will
  80. // transition all fields from 'inactive' to 'candidate'.
  81. _.defer(function () {
  82. entityModel.set('state', 'opening');
  83. });
  84. break;
  85. case 'closed':
  86. entityToolbarView = entityModel.toolbarView;
  87. // First, tear down the in-place editors.
  88. entityModel.get('fields').each(function (fieldModel) {
  89. app.teardownEditor(fieldModel);
  90. });
  91. // Second, tear down the entity toolbar view.
  92. if (entityToolbarView) {
  93. entityToolbarView.remove();
  94. delete entityModel.toolbarView;
  95. }
  96. // A page reload may be necessary to re-instate the original HTML of
  97. // the edited fields.
  98. if (reload) {
  99. reload = false;
  100. location.reload();
  101. }
  102. break;
  103. }
  104. },
  105. /**
  106. * Accepts or reject editor (Editor) state changes.
  107. *
  108. * This is what ensures that the app is in control of what happens.
  109. *
  110. * @param {string} from
  111. * The previous state.
  112. * @param {string} to
  113. * The new state.
  114. * @param {null|object} context
  115. * The context that is trying to trigger the state change.
  116. * @param {Drupal.quickedit.FieldModel} fieldModel
  117. * The fieldModel to which this change applies.
  118. *
  119. * @return {bool}
  120. * Whether the editor change was accepted or rejected.
  121. */
  122. acceptEditorStateChange: function (from, to, context, fieldModel) {
  123. var accept = true;
  124. // If the app is in view mode, then reject all state changes except for
  125. // those to 'inactive'.
  126. if (context && (context.reason === 'stop' || context.reason === 'rerender')) {
  127. if (from === 'candidate' && to === 'inactive') {
  128. accept = true;
  129. }
  130. }
  131. // Handling of edit mode state changes is more granular.
  132. else {
  133. // In general, enforce the states sequence. Disallow going back from a
  134. // "later" state to an "earlier" state, except in explicitly allowed
  135. // cases.
  136. if (!Drupal.quickedit.FieldModel.followsStateSequence(from, to)) {
  137. accept = false;
  138. // Allow: activating/active -> candidate.
  139. // Necessary to stop editing a field.
  140. if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') {
  141. accept = true;
  142. }
  143. // Allow: changed/invalid -> candidate.
  144. // Necessary to stop editing a field when it is changed or invalid.
  145. else if ((from === 'changed' || from === 'invalid') && to === 'candidate') {
  146. accept = true;
  147. }
  148. // Allow: highlighted -> candidate.
  149. // Necessary to stop highlighting a field.
  150. else if (from === 'highlighted' && to === 'candidate') {
  151. accept = true;
  152. }
  153. // Allow: saved -> candidate.
  154. // Necessary when successfully saved a field.
  155. else if (from === 'saved' && to === 'candidate') {
  156. accept = true;
  157. }
  158. // Allow: invalid -> saving.
  159. // Necessary to be able to save a corrected, invalid field.
  160. else if (from === 'invalid' && to === 'saving') {
  161. accept = true;
  162. }
  163. // Allow: invalid -> activating.
  164. // Necessary to be able to correct a field that turned out to be
  165. // invalid after the user already had moved on to the next field
  166. // (which we explicitly allow to have a fluent UX).
  167. else if (from === 'invalid' && to === 'activating') {
  168. accept = true;
  169. }
  170. }
  171. // If it's not against the general principle, then here are more
  172. // disallowed cases to check.
  173. if (accept) {
  174. var activeField;
  175. var activeFieldState;
  176. // Ensure only one field (editor) at a time is active … but allow a
  177. // user to hop from one field to the next, even if we still have to
  178. // start saving the field that is currently active: assume it will be
  179. // valid, to allow for a fluent UX. (If it turns out to be invalid,
  180. // this block of code also handles that.)
  181. if ((this.readyFieldStates.indexOf(from) !== -1 || from === 'invalid') && this.activeFieldStates.indexOf(to) !== -1) {
  182. activeField = this.model.get('activeField');
  183. if (activeField && activeField !== fieldModel) {
  184. activeFieldState = activeField.get('state');
  185. // Allow the state change. If the state of the active field is:
  186. // - 'activating' or 'active': change it to 'candidate'
  187. // - 'changed' or 'invalid': change it to 'saving'
  188. // - 'saving' or 'saved': don't do anything.
  189. if (this.activeFieldStates.indexOf(activeFieldState) !== -1) {
  190. activeField.set('state', 'candidate');
  191. }
  192. else if (activeFieldState === 'changed' || activeFieldState === 'invalid') {
  193. activeField.set('state', 'saving');
  194. }
  195. // If the field that's being activated is in fact already in the
  196. // invalid state (which can only happen because above we allowed
  197. // the user to move on to another field to allow for a fluent UX;
  198. // we assumed it would be saved successfully), then we shouldn't
  199. // allow the field to enter the 'activating' state, instead, we
  200. // simply change the active editor. All guarantees and
  201. // assumptions for this field still hold!
  202. if (from === 'invalid') {
  203. this.model.set('activeField', fieldModel);
  204. accept = false;
  205. }
  206. // Do not reject: the field is either in the 'candidate' or
  207. // 'highlighted' state and we allow it to enter the 'activating'
  208. // state!
  209. }
  210. }
  211. // Reject going from activating/active to candidate because of a
  212. // mouseleave.
  213. else if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') {
  214. if (context && context.reason === 'mouseleave') {
  215. accept = false;
  216. }
  217. }
  218. // When attempting to stop editing a changed/invalid property, ask for
  219. // confirmation.
  220. else if ((from === 'changed' || from === 'invalid') && to === 'candidate') {
  221. if (context && context.reason === 'mouseleave') {
  222. accept = false;
  223. }
  224. else {
  225. // Check whether the transition has been confirmed?
  226. if (context && context.confirmed) {
  227. accept = true;
  228. }
  229. }
  230. }
  231. }
  232. }
  233. return accept;
  234. },
  235. /**
  236. * Sets up the in-place editor for the given field.
  237. *
  238. * Must happen before the fieldModel's state is changed to 'candidate'.
  239. *
  240. * @param {Drupal.quickedit.FieldModel} fieldModel
  241. * The field for which an in-place editor must be set up.
  242. */
  243. setupEditor: function (fieldModel) {
  244. // Get the corresponding entity toolbar.
  245. var entityModel = fieldModel.get('entity');
  246. var entityToolbarView = entityModel.toolbarView;
  247. // Get the field toolbar DOM root from the entity toolbar.
  248. var fieldToolbarRoot = entityToolbarView.getToolbarRoot();
  249. // Create in-place editor.
  250. var editorName = fieldModel.get('metadata').editor;
  251. var editorModel = new Drupal.quickedit.EditorModel();
  252. var editorView = new Drupal.quickedit.editors[editorName]({
  253. el: $(fieldModel.get('el')),
  254. model: editorModel,
  255. fieldModel: fieldModel
  256. });
  257. // Create in-place editor's toolbar for this field — stored inside the
  258. // entity toolbar, the entity toolbar will position itself appropriately
  259. // above (or below) the edited element.
  260. var toolbarView = new Drupal.quickedit.FieldToolbarView({
  261. el: fieldToolbarRoot,
  262. model: fieldModel,
  263. $editedElement: $(editorView.getEditedElement()),
  264. editorView: editorView,
  265. entityModel: entityModel
  266. });
  267. // Create decoration for edited element: padding if necessary, sets
  268. // classes on the element to style it according to the current state.
  269. var decorationView = new Drupal.quickedit.FieldDecorationView({
  270. el: $(editorView.getEditedElement()),
  271. model: fieldModel,
  272. editorView: editorView
  273. });
  274. // Track these three views in FieldModel so that we can tear them down
  275. // correctly.
  276. fieldModel.editorView = editorView;
  277. fieldModel.toolbarView = toolbarView;
  278. fieldModel.decorationView = decorationView;
  279. },
  280. /**
  281. * Tears down the in-place editor for the given field.
  282. *
  283. * Must happen after the fieldModel's state is changed to 'inactive'.
  284. *
  285. * @param {Drupal.quickedit.FieldModel} fieldModel
  286. * The field for which an in-place editor must be torn down.
  287. */
  288. teardownEditor: function (fieldModel) {
  289. // Early-return if this field was not yet decorated.
  290. if (typeof fieldModel.editorView === 'undefined') {
  291. return;
  292. }
  293. // Unbind event handlers; remove toolbar element; delete toolbar view.
  294. fieldModel.toolbarView.remove();
  295. delete fieldModel.toolbarView;
  296. // Unbind event handlers; delete decoration view. Don't remove the element
  297. // because that would remove the field itself.
  298. fieldModel.decorationView.remove();
  299. delete fieldModel.decorationView;
  300. // Unbind event handlers; delete editor view. Don't remove the element
  301. // because that would remove the field itself.
  302. fieldModel.editorView.remove();
  303. delete fieldModel.editorView;
  304. },
  305. /**
  306. * Asks the user to confirm whether he wants to stop editing via a modal.
  307. *
  308. * @param {Drupal.quickedit.EntityModel} entityModel
  309. * An instance of the EntityModel class.
  310. *
  311. * @see Drupal.quickedit.AppView#acceptEditorStateChange
  312. */
  313. confirmEntityDeactivation: function (entityModel) {
  314. var that = this;
  315. var discardDialog;
  316. function closeDiscardDialog(action) {
  317. discardDialog.close(action);
  318. // The active modal has been removed.
  319. that.model.set('activeModal', null);
  320. // If the targetState is saving, the field must be saved, then the
  321. // entity must be saved.
  322. if (action === 'save') {
  323. entityModel.set('state', 'committing', {confirmed: true});
  324. }
  325. else {
  326. entityModel.set('state', 'deactivating', {confirmed: true});
  327. // Editing has been canceled and the changes will not be saved. Mark
  328. // the page for reload if the entityModel declares that it requires
  329. // a reload.
  330. if (entityModel.get('reload')) {
  331. reload = true;
  332. entityModel.set('reload', false);
  333. }
  334. }
  335. }
  336. // Only instantiate if there isn't a modal instance visible yet.
  337. if (!this.model.get('activeModal')) {
  338. var $unsavedChanges = $('<div>' + Drupal.t('You have unsaved changes') + '</div>');
  339. discardDialog = Drupal.dialog($unsavedChanges.get(0), {
  340. title: Drupal.t('Discard changes?'),
  341. dialogClass: 'quickedit-discard-modal',
  342. resizable: false,
  343. buttons: [
  344. {
  345. text: Drupal.t('Save'),
  346. click: function () {
  347. closeDiscardDialog('save');
  348. },
  349. primary: true
  350. },
  351. {
  352. text: Drupal.t('Discard changes'),
  353. click: function () {
  354. closeDiscardDialog('discard');
  355. }
  356. }
  357. ],
  358. // Prevent this modal from being closed without the user making a
  359. // choice as per http://stackoverflow.com/a/5438771.
  360. closeOnEscape: false,
  361. create: function () {
  362. $(this).parent().find('.ui-dialog-titlebar-close').remove();
  363. },
  364. beforeClose: false,
  365. close: function (event) {
  366. // Automatically destroy the DOM element that was used for the
  367. // dialog.
  368. $(event.target).remove();
  369. }
  370. });
  371. this.model.set('activeModal', discardDialog);
  372. discardDialog.showModal();
  373. }
  374. },
  375. /**
  376. * Reacts to field state changes; tracks global state.
  377. *
  378. * @param {Drupal.quickedit.FieldModel} fieldModel
  379. * The `fieldModel` holding the state.
  380. * @param {string} state
  381. * The state of the associated field. One of
  382. * {@link Drupal.quickedit.FieldModel.states}.
  383. */
  384. editorStateChange: function (fieldModel, state) {
  385. var from = fieldModel.previous('state');
  386. var to = state;
  387. // Keep track of the highlighted field in the global state.
  388. if (_.indexOf(this.singleFieldStates, to) !== -1 && this.model.get('highlightedField') !== fieldModel) {
  389. this.model.set('highlightedField', fieldModel);
  390. }
  391. else if (this.model.get('highlightedField') === fieldModel && to === 'candidate') {
  392. this.model.set('highlightedField', null);
  393. }
  394. // Keep track of the active field in the global state.
  395. if (_.indexOf(this.activeFieldStates, to) !== -1 && this.model.get('activeField') !== fieldModel) {
  396. this.model.set('activeField', fieldModel);
  397. }
  398. else if (this.model.get('activeField') === fieldModel && to === 'candidate') {
  399. // Discarded if it transitions from a changed state to 'candidate'.
  400. if (from === 'changed' || from === 'invalid') {
  401. fieldModel.editorView.revert();
  402. }
  403. this.model.set('activeField', null);
  404. }
  405. },
  406. /**
  407. * Render an updated field (a field whose 'html' attribute changed).
  408. *
  409. * @param {Drupal.quickedit.FieldModel} fieldModel
  410. * The FieldModel whose 'html' attribute changed.
  411. * @param {string} html
  412. * The updated 'html' attribute.
  413. * @param {object} options
  414. * An object with the following keys:
  415. * @param {bool} options.propagation
  416. * Whether this change to the 'html' attribute occurred because of the
  417. * propagation of changes to another instance of this field.
  418. */
  419. renderUpdatedField: function (fieldModel, html, options) {
  420. // Get data necessary to rerender property before it is unavailable.
  421. var $fieldWrapper = $(fieldModel.get('el'));
  422. var $context = $fieldWrapper.parent();
  423. var renderField = function () {
  424. // Destroy the field model; this will cause all attached views to be
  425. // destroyed too, and removal from all collections in which it exists.
  426. fieldModel.destroy();
  427. // Replace the old content with the new content.
  428. $fieldWrapper.replaceWith(html);
  429. // Attach behaviors again to the modified piece of HTML; this will
  430. // create a new field model and call rerenderedFieldToCandidate() with
  431. // it.
  432. Drupal.attachBehaviors($context.get(0));
  433. };
  434. // When propagating the changes of another instance of this field, this
  435. // field is not being actively edited and hence no state changes are
  436. // necessary. So: only update the state of this field when the rerendering
  437. // of this field happens not because of propagation, but because it is
  438. // being edited itself.
  439. if (!options.propagation) {
  440. // Deferred because renderUpdatedField is reacting to a field model
  441. // change event, and we want to make sure that event fully propagates
  442. // before making another change to the same model.
  443. _.defer(function () {
  444. // First set the state to 'candidate', to allow all attached views to
  445. // clean up all their "active state"-related changes.
  446. fieldModel.set('state', 'candidate');
  447. // Similarly, the above .set() call's change event must fully
  448. // propagate before calling it again.
  449. _.defer(function () {
  450. // Set the field's state to 'inactive', to enable the updating of
  451. // its DOM value.
  452. fieldModel.set('state', 'inactive', {reason: 'rerender'});
  453. renderField();
  454. });
  455. });
  456. }
  457. else {
  458. renderField();
  459. }
  460. },
  461. /**
  462. * Propagates changes to an updated field to all instances of that field.
  463. *
  464. * @param {Drupal.quickedit.FieldModel} updatedField
  465. * The FieldModel whose 'html' attribute changed.
  466. * @param {string} html
  467. * The updated 'html' attribute.
  468. * @param {object} options
  469. * An object with the following keys:
  470. * @param {bool} options.propagation
  471. * Whether this change to the 'html' attribute occurred because of the
  472. * propagation of changes to another instance of this field.
  473. *
  474. * @see Drupal.quickedit.AppView#renderUpdatedField
  475. */
  476. propagateUpdatedField: function (updatedField, html, options) {
  477. // Don't propagate field updates that themselves were caused by
  478. // propagation.
  479. if (options.propagation) {
  480. return;
  481. }
  482. var htmlForOtherViewModes = updatedField.get('htmlForOtherViewModes');
  483. Drupal.quickedit.collections.fields
  484. // Find all instances of fields that display the same logical field
  485. // (same entity, same field, just a different instance and maybe a
  486. // different view mode).
  487. .where({logicalFieldID: updatedField.get('logicalFieldID')})
  488. .forEach(function (field) {
  489. // Ignore the field that was already updated.
  490. if (field === updatedField) {
  491. return;
  492. }
  493. // If this other instance of the field has the same view mode, we can
  494. // update it easily.
  495. else if (field.getViewMode() === updatedField.getViewMode()) {
  496. field.set('html', updatedField.get('html'));
  497. }
  498. // If this other instance of the field has a different view mode, and
  499. // that is one of the view modes for which a re-rendered version is
  500. // available (and that should be the case unless this field was only
  501. // added to the page after editing of the updated field began), then
  502. // use that view mode's re-rendered version.
  503. else {
  504. if (field.getViewMode() in htmlForOtherViewModes) {
  505. field.set('html', htmlForOtherViewModes[field.getViewMode()], {propagation: true});
  506. }
  507. }
  508. });
  509. },
  510. /**
  511. * If the new in-place editable field is for the entity that's currently
  512. * being edited, then transition it to the 'candidate' state.
  513. *
  514. * This happens when a field was modified, saved and hence rerendered.
  515. *
  516. * @param {Drupal.quickedit.FieldModel} fieldModel
  517. * A field that was just added to the collection of fields.
  518. */
  519. rerenderedFieldToCandidate: function (fieldModel) {
  520. var activeEntity = Drupal.quickedit.collections.entities.findWhere({isActive: true});
  521. // Early-return if there is no active entity.
  522. if (!activeEntity) {
  523. return;
  524. }
  525. // If the field's entity is the active entity, make it a candidate.
  526. if (fieldModel.get('entity') === activeEntity) {
  527. this.setupEditor(fieldModel);
  528. fieldModel.set('state', 'candidate');
  529. }
  530. },
  531. /**
  532. * EntityModel Collection change handler.
  533. *
  534. * Handler is called `change:isActive` and enforces a single active entity.
  535. *
  536. * @param {Drupal.quickedit.EntityModel} changedEntityModel
  537. * The entityModel instance whose active state has changed.
  538. */
  539. enforceSingleActiveEntity: function (changedEntityModel) {
  540. // When an entity is deactivated, we don't need to enforce anything.
  541. if (changedEntityModel.get('isActive') === false) {
  542. return;
  543. }
  544. // This entity was activated; deactivate all other entities.
  545. changedEntityModel.collection.chain()
  546. .filter(function (entityModel) {
  547. return entityModel.get('isActive') === true && entityModel !== changedEntityModel;
  548. })
  549. .each(function (entityModel) {
  550. entityModel.set('state', 'deactivating');
  551. });
  552. }
  553. });
  554. }(jQuery, _, Backbone, Drupal));