3 * A Backbone View that controls the overall "in-place editing application".
5 * @see Drupal.quickedit.AppModel
8 (function ($, _, Backbone, Drupal) {
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.
21 Drupal.quickedit.AppView = Backbone.View.extend(/** @lends Drupal.quickedit.AppView# */{
26 * @augments Backbone.View
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
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'];
46 this.listenTo(options.entitiesCollection, 'change:state', this.appStateChange);
47 this.listenTo(options.entitiesCollection, 'change:isActive', this.enforceSingleActiveEntity);
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);
61 * Handles setup/teardown and state changes when the active entity changes.
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}.
69 appStateChange: function (entityModel, state) {
71 var entityToolbarView;
75 // First, create an entity toolbar view.
76 entityToolbarView = new Drupal.quickedit.EntityToolbarView({
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);
87 // Third, transition the entity to the 'opening' state, which will
88 // transition all fields from 'inactive' to 'candidate'.
90 entityModel.set('state', 'opening');
95 entityToolbarView = entityModel.toolbarView;
96 // First, tear down the in-place editors.
97 entityModel.get('fields').each(function (fieldModel) {
98 app.teardownEditor(fieldModel);
100 // Second, tear down the entity toolbar view.
101 if (entityToolbarView) {
102 entityToolbarView.remove();
103 delete entityModel.toolbarView;
105 // A page reload may be necessary to re-instate the original HTML of
106 // the edited fields.
116 * Accepts or reject editor (Editor) state changes.
118 * This is what ensures that the app is in control of what happens.
120 * @param {string} from
121 * The previous 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.
130 * Whether the editor change was accepted or rejected.
132 acceptEditorStateChange: function (from, to, context, fieldModel) {
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') {
142 // Handling of edit mode state changes is more granular.
144 // In general, enforce the states sequence. Disallow going back from a
145 // "later" state to an "earlier" state, except in explicitly allowed
147 if (!Drupal.quickedit.FieldModel.followsStateSequence(from, to)) {
149 // Allow: activating/active -> candidate.
150 // Necessary to stop editing a field.
151 if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') {
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') {
159 // Allow: highlighted -> candidate.
160 // Necessary to stop highlighting a field.
161 else if (from === 'highlighted' && to === 'candidate') {
164 // Allow: saved -> candidate.
165 // Necessary when successfully saved a field.
166 else if (from === 'saved' && to === 'candidate') {
169 // Allow: invalid -> saving.
170 // Necessary to be able to save a corrected, invalid field.
171 else if (from === 'invalid' && to === 'saving') {
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') {
183 // If it's not against the general principle, then here are more
184 // disallowed cases to check.
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');
204 else if (activeFieldState === 'changed' || activeFieldState === 'invalid') {
205 activeField.set('state', 'saving');
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);
219 // Do not reject: the field is either in the 'candidate' or
220 // 'highlighted' state and we allow it to enter the 'activating'
224 // Reject going from activating/active to candidate because of a
226 else if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') {
227 if (context && context.reason === 'mouseleave') {
231 // When attempting to stop editing a changed/invalid property, ask for
233 else if ((from === 'changed' || from === 'invalid') && to === 'candidate') {
234 if (context && context.reason === 'mouseleave') {
238 // Check whether the transition has been confirmed?
239 if (context && context.confirmed) {
251 * Sets up the in-place editor for the given field.
253 * Must happen before the fieldModel's state is changed to 'candidate'.
255 * @param {Drupal.quickedit.FieldModel} fieldModel
256 * The field for which an in-place editor must be set up.
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')),
270 fieldModel: fieldModel
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,
279 $editedElement: $(editorView.getEditedElement()),
280 editorView: editorView,
281 entityModel: entityModel
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()),
289 editorView: editorView
292 // Track these three views in FieldModel so that we can tear them down
294 fieldModel.editorView = editorView;
295 fieldModel.toolbarView = toolbarView;
296 fieldModel.decorationView = decorationView;
300 * Tears down the in-place editor for the given field.
302 * Must happen after the fieldModel's state is changed to 'inactive'.
304 * @param {Drupal.quickedit.FieldModel} fieldModel
305 * The field for which an in-place editor must be torn down.
307 teardownEditor: function (fieldModel) {
308 // Early-return if this field was not yet decorated.
309 if (typeof fieldModel.editorView === 'undefined') {
313 // Unbind event handlers; remove toolbar element; delete toolbar view.
314 fieldModel.toolbarView.remove();
315 delete fieldModel.toolbarView;
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;
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;
329 * Asks the user to confirm whether he wants to stop editing via a modal.
331 * @param {Drupal.quickedit.EntityModel} entityModel
332 * An instance of the EntityModel class.
334 * @see Drupal.quickedit.AppView#acceptEditorStateChange
336 confirmEntityDeactivation: function (entityModel) {
340 function closeDiscardDialog(action) {
341 discardDialog.close(action);
342 // The active modal has been removed.
343 that.model.set('activeModal', null);
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});
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
355 if (entityModel.get('reload')) {
357 entityModel.set('reload', false);
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',
371 text: Drupal.t('Save'),
373 closeDiscardDialog('save');
378 text: Drupal.t('Discard changes'),
380 closeDiscardDialog('discard');
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();
391 close: function (event) {
392 // Automatically destroy the DOM element that was used for the
394 $(event.target).remove();
397 this.model.set('activeModal', discardDialog);
399 discardDialog.showModal();
404 * Reacts to field state changes; tracks global state.
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}.
412 editorStateChange: function (fieldModel, state) {
413 var from = fieldModel.previous('state');
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);
420 else if (this.model.get('highlightedField') === fieldModel && to === 'candidate') {
421 this.model.set('highlightedField', null);
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);
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();
433 this.model.set('activeField', null);
438 * Render an updated field (a field whose 'html' attribute changed).
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.
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();
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();
460 // Replace the old content with the new content.
461 $fieldWrapper.replaceWith(html);
463 // Attach behaviors again to the modified piece of HTML; this will
464 // create a new field model and call rerenderedFieldToCandidate() with
466 Drupal.attachBehaviors($context.get(0));
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');
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
488 fieldModel.set('state', 'inactive', {reason: 'rerender'});
500 * Propagates changes to an updated field to all instances of that field.
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.
512 * @see Drupal.quickedit.AppView#renderUpdatedField
514 propagateUpdatedField: function (updatedField, html, options) {
515 // Don't propagate field updates that themselves were caused by
517 if (options.propagation) {
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) {
532 // If this other instance of the field has the same view mode, we can
534 else if (field.getViewMode() === updatedField.getViewMode()) {
535 field.set('html', updatedField.get('html'));
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.
543 if (field.getViewMode() in htmlForOtherViewModes) {
544 field.set('html', htmlForOtherViewModes[field.getViewMode()], {propagation: true});
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.
554 * This happens when a field was modified, saved and hence rerendered.
556 * @param {Drupal.quickedit.FieldModel} fieldModel
557 * A field that was just added to the collection of fields.
559 rerenderedFieldToCandidate: function (fieldModel) {
560 var activeEntity = Drupal.quickedit.collections.entities.findWhere({isActive: true});
562 // Early-return if there is no active entity.
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');
575 * EntityModel Collection change handler.
577 * Handler is called `change:isActive` and enforces a single active entity.
579 * @param {Drupal.quickedit.EntityModel} changedEntityModel
580 * The entityModel instance whose active state has changed.
582 enforceSingleActiveEntity: function (changedEntityModel) {
583 // When an entity is deactivated, we don't need to enforce anything.
584 if (changedEntityModel.get('isActive') === false) {
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;
593 .each(function (entityModel) {
594 entityModel.set('state', 'deactivating');
600 }(jQuery, _, Backbone, Drupal));