|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * |
| 4 | + * Copyright IBM Corp. 2019 |
| 5 | + * |
| 6 | + * This source code is licensed under the Apache-2.0 license found in the |
| 7 | + * LICENSE file in the root directory of this source tree. |
| 8 | + */ |
| 9 | + |
| 10 | +/** |
| 11 | + * @param {object} config Plugin configuration. |
| 12 | + * @returns {Plugin} A Flatpickr plugin to put adjust the position of calendar dropdown. |
| 13 | + */ |
| 14 | +export default config => fp => { |
| 15 | + /** |
| 16 | + * Adjusts the floating meun position after Flatpicker sets it. |
| 17 | + */ |
| 18 | + const handlePreCalendarPosition = () => { |
| 19 | + Promise.resolve().then(() => { |
| 20 | + const { |
| 21 | + calendarContainer, |
| 22 | + config: fpConfig, |
| 23 | + _positionElement: positionElement, |
| 24 | + } = fp; |
| 25 | + const { appendTo } = fpConfig; |
| 26 | + const { |
| 27 | + left: containerLeft, |
| 28 | + top: containerTop, |
| 29 | + } = appendTo.getBoundingClientRect(); |
| 30 | + const { |
| 31 | + left: refLeft, |
| 32 | + bottom: refBottom, |
| 33 | + } = positionElement.getBoundingClientRect(); |
| 34 | + if ( |
| 35 | + (appendTo !== appendTo.ownerDocument.body || |
| 36 | + containerLeft !== 0 || |
| 37 | + containerTop !== 0) && |
| 38 | + appendTo.ownerDocument.defaultView |
| 39 | + .getComputedStyle(appendTo) |
| 40 | + .getPropertyValue('position') === 'static' |
| 41 | + ) { |
| 42 | + throw new Error( |
| 43 | + 'Floating menu container must not have `position:static`.' |
| 44 | + ); |
| 45 | + } |
| 46 | + // `2` for negative mergin on calendar dropdown |
| 47 | + calendarContainer.style.top = `${refBottom - containerTop + 2}px`; |
| 48 | + calendarContainer.style.left = `${refLeft - containerLeft}px`; |
| 49 | + }); |
| 50 | + }; |
| 51 | + |
| 52 | + /** |
| 53 | + * Registers this Flatpickr plugin. |
| 54 | + */ |
| 55 | + const register = () => { |
| 56 | + fp.loadedPlugins.push('carbonFlatpickrAppendToPlugin'); |
| 57 | + }; |
| 58 | + |
| 59 | + return { |
| 60 | + appendTo: config.appendTo, |
| 61 | + onReady: register, |
| 62 | + onPreCalendarPosition: handlePreCalendarPosition, |
| 63 | + }; |
| 64 | +}; |
0 commit comments