comparison core/modules/quickedit/js/views/AppView.es6.js @ 4:a9cd425dd02b

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