summaryrefslogtreecommitdiffstatshomepage
path: root/core/misc/dialog/off-canvas/js/off-canvas.js
blob: fbe99525fda0421df1a3021a7514485458a4028d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/**
 * @file
 * Drupal's off-canvas library.
 */

(($, Drupal, debounce, displace) => {
  /**
   * Off-canvas dialog implementation using jQuery Dialog.
   *
   * Transforms the regular dialogs created using Drupal.dialog when the dialog
   * element equals '#drupal-off-canvas' into a side-loading dialog.
   *
   * @namespace
   */
  Drupal.offCanvas = {
    /**
     * Storage for position information about the tray.
     *
     * @type {?String}
     */
    position: null,

    /**
     * The minimum height of the tray when opened at the top of the page.
     *
     * @type {Number}
     */
    minimumHeight: 30,

    /**
     * The minimum width to use body displace needs to match the width at which
     * the tray will be 100% width. @see core/misc/dialog/off-canvas.css
     *
     * @type {Number}
     */
    minDisplaceWidth: 768,

    /**
     * Wrapper used to position off-canvas dialog.
     *
     * @type {jQuery}
     */
    $mainCanvasWrapper: $('[data-off-canvas-main-canvas]'),

    /**
     * Determines if an element is an off-canvas dialog.
     *
     * @param {jQuery} $element
     *   The dialog element.
     *
     * @return {boolean}
     *   True this is currently an off-canvas dialog.
     */
    isOffCanvas($element) {
      return $element[0].id === 'drupal-off-canvas';
    },

    /**
     * Remove off-canvas dialog events.
     *
     * @param {jQuery} $element
     *   The target element.
     */
    removeOffCanvasEvents($element) {
      $element.off('.off-canvas');
      $(document).off('.off-canvas');
      $(window).off('.off-canvas');
    },

    /**
     * Handler fired before an off-canvas dialog has been opened.
     *
     * @param {Object} settings
     *   Settings related to the composition of the dialog.
     *
     * @return {undefined}
     */
    beforeCreate({ settings, $element }) {
      // Clean up previous dialog event handlers.
      Drupal.offCanvas.removeOffCanvasEvents($element);

      $('body').addClass('js-off-canvas-dialog-open');
      // @see http://api.jqueryui.com/position/
      settings.position = {
        my: 'left top',
        at: `${Drupal.offCanvas.getEdge()} top`,
        of: window,
      };

      /**
       * Applies initial height and with to dialog based depending on position.
       * @see http://api.jqueryui.com/dialog for all dialog options.
       */
      const position = settings.drupalOffCanvasPosition;
      const height = position === 'side' ? $(window).height() : settings.height;
      const width = position === 'side' ? settings.width : '100%';
      settings.height = height;
      settings.width = width;
    },

    /**
     * Handler fired after an off-canvas dialog has been closed.
     *
     * @return {undefined}
     */
    beforeClose({ $element }) {
      $('body').removeClass('js-off-canvas-dialog-open');
      // Remove all *.off-canvas events
      Drupal.offCanvas.removeOffCanvasEvents($element);
      Drupal.offCanvas.resetPadding();
    },

    /**
     * Handler fired when an off-canvas dialog has been opened.
     *
     * @param {jQuery} $element
     *   The off-canvas dialog element.
     * @param {Object} settings
     *   Settings related to the composition of the dialog.
     *
     * @return {undefined}
     */
    afterCreate({ $element, settings }) {
      const eventData = { settings, $element, offCanvasDialog: this };

      $element
        .on(
          'dialogContentResize.off-canvas',
          eventData,
          Drupal.offCanvas.handleDialogResize,
        )
        .on(
          'dialogContentResize.off-canvas',
          eventData,
          Drupal.offCanvas.bodyPadding,
        );

      Drupal.offCanvas
        .getContainer($element)
        .attr(`data-offset-${Drupal.offCanvas.getEdge()}`, '');

      $(window)
        .on(
          'resize.off-canvas',
          eventData,
          debounce(Drupal.offCanvas.resetSize, 100, true),
        )
        .trigger('resize.off-canvas');
    },

    /**
     * Toggle classes based on title existence.
     * Called with Drupal.offCanvas.afterCreate.
     *
     * @param {Object} settings
     *   Settings related to the composition of the dialog.
     *
     * @return {undefined}
     */
    render({ settings }) {
      $(
        '.ui-dialog-off-canvas, .ui-dialog-off-canvas .ui-dialog-titlebar',
      ).toggleClass('ui-dialog-empty-title', !settings.title);
      $('.ui-dialog-off-canvas').attr('id', 'drupal-off-canvas-wrapper');
    },

    /**
     * Adjusts the dialog on resize.
     *
     * @param {jQuery.Event} event
     *   The event triggered.
     * @param {object} event.data
     *   Data attached to the event.
     */
    handleDialogResize(event) {
      const $element = event.data.$element;
      const $container = Drupal.offCanvas.getContainer($element);

      const $offsets = $container.find(
        '> :not(#drupal-off-canvas, .ui-resizable-handle)',
      );
      let offset = 0;

      // Let scroll element take all the height available.
      $element[0].style.height = 'auto';
      const modalHeight = $container.height();

      $offsets.each((i, e) => {
        offset += $(e).outerHeight();
      });

      // Take internal padding into account.
      const scrollOffset = $element.outerHeight() - $element.height();
      $element.height(modalHeight - offset - scrollOffset);
    },

    /**
     * Resets the size of the dialog.
     *
     * @param {jQuery.Event} event
     *   The event triggered.
     * @param {object} event.data
     *   Data attached to the event.
     */
    resetSize(event) {
      const $element = event.data.$element;
      const container = Drupal.offCanvas.getContainer($element);
      const position = event.data.settings.drupalOffCanvasPosition;

      // Only remove the `data-offset-*` attribute if the value previously
      // exists and the orientation is changing.
      if (Drupal.offCanvas.position && Drupal.offCanvas.position !== position) {
        container.removeAttr(`data-offset-${Drupal.offCanvas.position}`);
      }
      // Set a minimum height on $element
      if (position === 'top') {
        $element[0].style.minHeight = `${Drupal.offCanvas.minimumHeight}px`;
      }

      displace();

      const offsets = displace.offsets;

      const topPosition =
        position === 'side' && offsets.top !== 0 ? `+${offsets.top}` : '';
      const adjustedOptions = {
        // @see http://api.jqueryui.com/position/
        position: {
          my: `${Drupal.offCanvas.getEdge()} top`,
          at: `${Drupal.offCanvas.getEdge()} top${topPosition}`,
          of: window,
        },
      };

      const height =
        position === 'side'
          ? `${$(window).height() - (offsets.top + offsets.bottom)}px`
          : event.data.settings.height;

      Object.assign(container[0].style, {
        position: 'fixed',
        height: Number.isNaN(parseFloat(height))
          ? height
          : `${parseFloat(height)}px`,
      });

      $element.dialog('option', adjustedOptions);

      $element
        ?.get(0)
        ?.dispatchEvent(
          new CustomEvent('dialogContentResize', { bubbles: true }),
        );

      Drupal.offCanvas.position = position;
    },

    /**
     * Adjusts the body padding when the dialog is resized.
     *
     * @param {jQuery.Event} event
     *   The event triggered.
     * @param {object} event.data
     *   Data attached to the event.
     */
    bodyPadding(event) {
      const position = event.data.settings.drupalOffCanvasPosition;
      if (
        position === 'side' &&
        $('body').outerWidth() < Drupal.offCanvas.minDisplaceWidth
      ) {
        return;
      }
      Drupal.offCanvas.resetPadding();
      const $element = event.data.$element;
      const $container = Drupal.offCanvas.getContainer($element);
      const mainCanvasWrapper = Drupal.offCanvas.$mainCanvasWrapper[0];

      const width = $container.outerWidth();
      const mainCanvasPadding =
        window.getComputedStyle(mainCanvasWrapper)[
          `padding-${Drupal.offCanvas.getEdge()}`
        ];

      if (position === 'side' && width !== mainCanvasPadding) {
        mainCanvasWrapper.style[`padding-${Drupal.offCanvas.getEdge()}`] =
          `${width}px`;

        $container.attr(`data-offset-${Drupal.offCanvas.getEdge()}`, width);
        $container.attr('data-offset-top', 0);
        displace();
      }

      const height = $container.outerHeight();
      if (position === 'top') {
        mainCanvasWrapper.style.paddingTop = `${height}px`;
        $container.attr('data-offset-top', height);
        $container.attr(`data-offset-${Drupal.offCanvas.getEdge()}`, 0);
        displace();
      }
    },

    /**
     * The HTML element that surrounds the dialog.
     * @param {HTMLElement} $element
     *   The dialog element.
     *
     * @return {HTMLElement}
     *   The containing element.
     */
    getContainer($element) {
      return $element.dialog('widget');
    },

    /**
     * The edge of the screen that the dialog should appear on.
     *
     * @return {string}
     *   The edge the tray will be shown on, left or right.
     */
    getEdge() {
      return document.documentElement.dir === 'rtl' ? 'left' : 'right';
    },

    /**
     * Resets main canvas wrapper and toolbar padding / margin.
     */
    resetPadding() {
      Drupal.offCanvas.$mainCanvasWrapper[0].style[
        `padding-${Drupal.offCanvas.getEdge()}`
      ] = 0;
      Drupal.offCanvas.$mainCanvasWrapper[0].style.paddingTop = 0;
      displace();
    },
  };

  /**
   * Attaches off-canvas dialog behaviors.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches event listeners for off-canvas dialogs.
   */
  Drupal.behaviors.offCanvasEvents = {
    attach: () => {
      if (!once('off-canvas', 'html').length) {
        return;
      }

      window.addEventListener('dialog:beforecreate', (e) => {
        const $element = $(e.target);
        if (Drupal.offCanvas.isOffCanvas($element)) {
          Drupal.offCanvas.beforeCreate({
            $element,
            settings: e.settings,
          });
        }
      });

      window.addEventListener('dialog:aftercreate', (e) => {
        const $element = $(e.target);
        if (Drupal.offCanvas.isOffCanvas($element)) {
          Drupal.offCanvas.render({
            $element,
            dialog: e.dialog,
            settings: e.settings,
          });
          Drupal.offCanvas.afterCreate({
            $element,
            settings: e.settings,
          });
        }
      });

      window.addEventListener('dialog:beforeclose', (e) => {
        const $element = $(e.target);
        if (Drupal.offCanvas.isOffCanvas($element)) {
          Drupal.offCanvas.beforeClose({
            $element,
          });
        }
      });
    },
  };
})(jQuery, Drupal, Drupal.debounce, Drupal.displace);