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