AppView.es6.js 23 KB

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