3 * A Backbone View that provides an entity level toolbar.
6 (function ($, _, Backbone, Drupal, debounce) {
7 Drupal.quickedit.EntityToolbarView = Backbone.View.extend(/** @lends Drupal.quickedit.EntityToolbarView# */{
12 _fieldToolbarRoot: null,
20 'click button.action-save': 'onClickSave',
21 'click button.action-cancel': 'onClickCancel',
22 mouseenter: 'onMouseenter',
30 * @augments Backbone.View
32 * @param {object} options
33 * Options to construct the view.
34 * @param {Drupal.quickedit.AppModel} options.appModel
35 * A quickedit `AppModel` to use in the view.
39 this.appModel = options.appModel;
40 this.$entity = $(this.model.get('el'));
42 // Rerender whenever the entity state changes.
43 this.listenTo(this.model, 'change:isActive change:isDirty change:state', this.render);
44 // Also rerender whenever a different field is highlighted or activated.
45 this.listenTo(this.appModel, 'change:highlightedField change:activeField', this.render);
46 // Rerender when a field of the entity changes state.
47 this.listenTo(this.model.get('fields'), 'change:state', this.fieldStateChange);
49 // Reposition the entity toolbar as the viewport and the position within
50 // the viewport changes.
51 $(window).on('resize.quickedit scroll.quickedit drupalViewportOffsetChange.quickedit', debounce($.proxy(this.windowChangeHandler, this), 150));
53 // Adjust the fence placement within which the entity toolbar may be
55 $(document).on('drupalViewportOffsetChange.quickedit', (event, offsets) => {
57 that.$fence.css(offsets);
61 // Set the entity toolbar DOM element as the el for this view.
62 const $toolbar = this.buildToolbarEl();
63 this.setElement($toolbar);
64 this._fieldToolbarRoot = $toolbar.find('.quickedit-toolbar-field').get(0);
73 * @return {Drupal.quickedit.EntityToolbarView}
74 * The entity toolbar view.
77 if (this.model.get('isActive')) {
78 // If the toolbar container doesn't exist, create it.
79 const $body = $('body');
80 if ($body.children('#quickedit-entity-toolbar').length === 0) {
81 $body.append(this.$el);
83 // The fence will define a area on the screen that the entity toolbar
84 // will be position within.
85 if ($body.children('#quickedit-toolbar-fence').length === 0) {
86 this.$fence = $(Drupal.theme('quickeditEntityToolbarFence'))
87 .css(Drupal.displace())
90 // Adds the entity title to the toolbar.
93 // Show the save and cancel buttons.
95 // If render is being called and the toolbar is already visible, just
100 // The save button text and state varies with the state of the entity
102 const $button = this.$el.find('.quickedit-button.action-save');
103 const isDirty = this.model.get('isDirty');
104 // Adjust the save button according to the state of the model.
105 switch (this.model.get('state')) {
106 // Quick editing is active, but no field is being edited.
108 // The saving throbber is not managed by AJAX system. The
109 // EntityToolbarView manages this visual element.
111 .removeClass('action-saving icon-throbber icon-end')
112 .text(Drupal.t('Save'))
113 .removeAttr('disabled')
114 .attr('aria-hidden', !isDirty);
117 // The changes to the fields of the entity are being committed.
120 .addClass('action-saving icon-throbber icon-end')
121 .text(Drupal.t('Saving'))
122 .attr('disabled', 'disabled');
126 $button.attr('aria-hidden', true);
137 // Remove additional DOM elements controlled by this View.
138 this.$fence.remove();
140 // Stop listening to additional events.
141 $(window).off('resize.quickedit scroll.quickedit drupalViewportOffsetChange.quickedit');
142 $(document).off('drupalViewportOffsetChange.quickedit');
144 Backbone.View.prototype.remove.call(this);
148 * Repositions the entity toolbar on window scroll and resize.
150 * @param {jQuery.Event} event
151 * The scroll or resize event.
153 windowChangeHandler(event) {
158 * Determines the actions to take given a change of state.
160 * @param {Drupal.quickedit.FieldModel} model
161 * The `FieldModel` model.
162 * @param {string} state
163 * The state of the associated field. One of
164 * {@link Drupal.quickedit.FieldModel.states}.
166 fieldStateChange(model, state) {
179 * Uses the jQuery.ui.position() method to position the entity toolbar.
181 * @param {HTMLElement} [element]
182 * The element against which the entity toolbar is positioned.
185 clearTimeout(this.timer);
188 // Vary the edge of the positioning according to the direction of language
190 const edge = (document.documentElement.dir === 'rtl') ? 'right' : 'left';
191 // A time unit to wait until the entity toolbar is repositioned.
193 // Determines what check in the series of checks below should be
196 // When positioned against an active field that has padding, we should
197 // ignore that padding when positioning the toolbar, to not unnecessarily
198 // move the toolbar horizontally, which feels annoying.
199 let horizontalPadding = 0;
202 let highlightedField;
203 // There are several elements in the page that the entity toolbar might be
204 // positioned against. They are considered below in a priority order.
208 // Position against a specific element.
213 // Position against a form container.
214 activeField = Drupal.quickedit.app.model.get('activeField');
215 of = activeField && activeField.editorView && activeField.editorView.$formContainer && activeField.editorView.$formContainer.find('.quickedit-form');
219 // Position against an active field.
220 of = activeField && activeField.editorView && activeField.editorView.getEditedElement();
221 if (activeField && activeField.editorView && activeField.editorView.getQuickEditUISettings().padding) {
222 horizontalPadding = 5;
227 // Position against a highlighted field.
228 highlightedField = Drupal.quickedit.app.model.get('highlightedField');
229 of = highlightedField && highlightedField.editorView && highlightedField.editorView.getEditedElement();
234 var fieldModels = this.model.get('fields').models;
235 var topMostPosition = 1000000;
236 var topMostField = null;
237 // Position against the topmost field.
238 for (let i = 0; i < fieldModels.length; i++) {
239 const pos = fieldModels[i].get('el').getBoundingClientRect().top;
240 if (pos < topMostPosition) {
241 topMostPosition = pos;
242 topMostField = fieldModels[i];
245 of = topMostField.get('el');
249 // Prepare to check the next possible element to position against.
254 * Refines the positioning algorithm of jquery.ui.position().
256 * Invoked as the 'using' callback of jquery.ui.position() in
260 * The view the positions will be calculated from.
261 * @param {object} suggested
262 * A hash of top and left values for the position that should be set. It
263 * can be forwarded to .css() or .animate().
264 * @param {object} info
265 * The position and dimensions of both the 'my' element and the 'of'
266 * elements, as well as calculations to their relative position. This
267 * object contains the following properties:
268 * @param {object} info.element
269 * A hash that contains information about the HTML element that will be
270 * positioned. Also known as the 'my' element.
271 * @param {object} info.target
272 * A hash that contains information about the HTML element that the
273 * 'my' element will be positioned against. Also known as the 'of'
276 function refinePosition(view, suggested, info) {
277 // Determine if the pointer should be on the top or bottom.
278 const isBelow = suggested.top > info.target.top;
279 info.element.element.toggleClass('quickedit-toolbar-pointer-top', isBelow);
280 // Don't position the toolbar past the first or last editable field if
281 // the entity is the target.
282 if (view.$entity[0] === info.target.element[0]) {
283 // Get the first or last field according to whether the toolbar is
284 // above or below the entity.
285 const $field = view.$entity.find('.quickedit-editable').eq((isBelow) ? -1 : 0);
286 if ($field.length > 0) {
287 suggested.top = (isBelow) ? ($field.offset().top + $field.outerHeight(true)) : $field.offset().top - info.element.element.outerHeight(true);
290 // Don't let the toolbar go outside the fence.
291 const fenceTop = view.$fence.offset().top;
292 const fenceHeight = view.$fence.height();
293 const toolbarHeight = info.element.element.outerHeight(true);
294 if (suggested.top < fenceTop) {
295 suggested.top = fenceTop;
297 else if ((suggested.top + toolbarHeight) > (fenceTop + fenceHeight)) {
298 suggested.top = fenceTop + fenceHeight - toolbarHeight;
300 // Position the toolbar.
301 info.element.element.css({
302 left: Math.floor(suggested.left),
303 top: Math.floor(suggested.top),
308 * Calls the jquery.ui.position() method on the $el of this view.
310 function positionToolbar() {
313 my: `${edge} bottom`,
314 // Move the toolbar 1px towards the start edge of the 'of' element,
315 // plus any horizontal padding that may have been added to the
316 // element that is being added, to prevent unwanted horizontal
318 at: `${edge}+${1 + horizontalPadding} top`,
320 collision: 'flipfit',
321 using: refinePosition.bind(null, that),
324 // Resize the toolbar to match the dimensions of the field, up to a
325 // maximum width that is equal to 90% of the field's width.
327 'max-width': (document.documentElement.clientWidth < 450) ? document.documentElement.clientWidth : 450,
328 // Set a minimum width of 240px for the entity toolbar, or the width
329 // of the client if it is less than 240px, so that the toolbar
330 // never folds up into a squashed and jumbled mess.
331 'min-width': (document.documentElement.clientWidth < 240) ? document.documentElement.clientWidth : 240,
336 // Uses the jQuery.ui.position() method. Use a timeout to move the toolbar
337 // only after the user has focused on an editable for 250ms. This prevents
338 // the toolbar from jumping around the screen.
339 this.timer = setTimeout(() => {
340 // Render the position in the next execution cycle, so that animations
341 // on the field have time to process. This is not strictly speaking, a
342 // guarantee that all animations will be finished, but it's a simple
343 // way to get better positioning without too much additional code.
344 _.defer(positionToolbar);
349 * Set the model state to 'saving' when the save button is clicked.
351 * @param {jQuery.Event} event
355 event.stopPropagation();
356 event.preventDefault();
358 this.model.set('state', 'committing');
362 * Sets the model state to candidate when the cancel button is clicked.
364 * @param {jQuery.Event} event
367 onClickCancel(event) {
368 event.preventDefault();
369 this.model.set('state', 'deactivating');
373 * Clears the timeout that will eventually reposition the entity toolbar.
375 * Without this, it may reposition itself, away from the user's cursor!
377 * @param {jQuery.Event} event
380 onMouseenter(event) {
381 clearTimeout(this.timer);
385 * Builds the entity toolbar HTML; attaches to DOM; sets starting position.
388 * The toolbar element.
391 const $toolbar = $(Drupal.theme('quickeditEntityToolbar', {
392 id: 'quickedit-entity-toolbar',
396 .find('.quickedit-toolbar-entity')
397 // Append the "ops" toolgroup into the toolbar.
398 .prepend(Drupal.theme('quickeditToolgroup', {
402 label: Drupal.t('Save'),
404 classes: 'action-save quickedit-button icon',
410 label: Drupal.t('Close'),
411 classes: 'action-cancel quickedit-button icon icon-close icon-only',
416 // Give the toolbar a sensible starting position so that it doesn't
417 // animate on to the screen from a far off corner.
420 left: this.$entity.offset().left,
421 top: this.$entity.offset().top,
428 * Returns the DOM element that fields will attach their toolbars to.
431 * The DOM element that fields will attach their toolbars to.
434 return this._fieldToolbarRoot;
438 * Generates a state-dependent label for the entity toolbar.
443 const entityLabel = this.model.get('label');
445 // Label of an active field, if it exists.
446 const activeField = Drupal.quickedit.app.model.get('activeField');
447 const activeFieldLabel = activeField && activeField.get('metadata').label;
448 // Label of a highlighted field, if it exists.
449 const highlightedField = Drupal.quickedit.app.model.get('highlightedField');
450 const highlightedFieldLabel = highlightedField && highlightedField.get('metadata').label;
451 // The label is constructed in a priority order.
452 if (activeFieldLabel) {
453 label = Drupal.theme('quickeditEntityToolbarLabel', {
455 fieldLabel: activeFieldLabel,
458 else if (highlightedFieldLabel) {
459 label = Drupal.theme('quickeditEntityToolbarLabel', {
461 fieldLabel: highlightedFieldLabel,
465 // @todo Add XSS regression test coverage in https://www.drupal.org/node/2547437
466 label = Drupal.checkPlain(entityLabel);
470 .find('.quickedit-toolbar-label')
475 * Adds classes to a toolgroup.
477 * @param {string} toolgroup
479 * @param {string} classes
480 * A string of space-delimited class names that will be applied to the
481 * wrapping element of the toolbar group.
483 addClass(toolgroup, classes) {
484 this._find(toolgroup).addClass(classes);
488 * Removes classes from a toolgroup.
490 * @param {string} toolgroup
492 * @param {string} classes
493 * A string of space-delimited class names that will be removed from the
494 * wrapping element of the toolbar group.
496 removeClass(toolgroup, classes) {
497 this._find(toolgroup).removeClass(classes);
503 * @param {string} toolgroup
507 * The toolgroup DOM element.
510 return this.$el.find(`.quickedit-toolbar .quickedit-toolgroup.${toolgroup}`);
516 * @param {string} toolgroup
520 this.$el.removeClass('quickedit-animate-invisible');
524 }(jQuery, _, Backbone, Drupal, Drupal.debounce));