AppView.es6.js 25 KB

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