Debian Codegraph @

packages/popper/src/modifiers/offset.js

raw
1 import isNumeric from '../utils/isNumeric';
2 import getClientRect from '../utils/getClientRect';
3 import find from '../utils/find';
4
5 /**
6 * Converts a string containing value + unit into a px value number
7 * @function
8 * @memberof {modifiers~offset}
9 * @private
10 * @argument {String} str - Value + unit string
11 * @argument {String} measurement - `height` or `width`
12 * @argument {Object} popperOffsets
13 * @argument {Object} referenceOffsets
14 * @returns {Number|String}
15 * Value in pixels, or original string if no values were extracted
16 */
17 export function toValue(str, measurement, popperOffsets, referenceOffsets) {
18 // separate value from unit
19 const split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
20 const value = +split[1];
21 const unit = split[2];
22
23 // If it's not a number it's an operator, I guess
24 if (!value) {
25 return str;
26 }
27
28 if (unit.indexOf('%') === 0) {
29 let element;
30 switch (unit) {
31 case '%p':
32 element = popperOffsets;
33 break;
34 case '%':
35 case '%r':
36 default:
37 element = referenceOffsets;
38 }
39
40 const rect = getClientRect(element);
41 return rect[measurement] / 100 * value;
42 } else if (unit === 'vh' || unit === 'vw') {
43 // if is a vh or vw, we calculate the size based on the viewport
44 let size;
45 if (unit === 'vh') {
46 size = Math.max(
47 document.documentElement.clientHeight,
48 window.innerHeight || 0
49 );
50 } else {
51 size = Math.max(
52 document.documentElement.clientWidth,
53 window.innerWidth || 0
54 );
55 }
56 return size / 100 * value;
57 } else {
58 // if is an explicit pixel unit, we get rid of the unit and keep the value
59 // if is an implicit unit, it's px, and we return just the value
60 return value;
61 }
62 }
63
64 /**
65 * Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
66 * @function
67 * @memberof {modifiers~offset}
68 * @private
69 * @argument {String} offset
70 * @argument {Object} popperOffsets
71 * @argument {Object} referenceOffsets
72 * @argument {String} basePlacement
73 * @returns {Array} a two cells array with x and y offsets in numbers
74 */
75 export function parseOffset(
76 offset,
77 popperOffsets,
78 referenceOffsets,
79 basePlacement
80 ) {
81 const offsets = [0, 0];
82
83 // Use height if placement is left or right and index is 0 otherwise use width
84 // in this way the first offset will use an axis and the second one
85 // will use the other one
86 const useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
87
88 // Split the offset string to obtain a list of values and operands
89 // The regex addresses values with the plus or minus sign in front (+10, -20, etc)
90 const fragments = offset.split(/(\+|\-)/).map(frag => frag.trim());
91
92 // Detect if the offset string contains a pair of values or a single one
93 // they could be separated by comma or space
94 const divider = fragments.indexOf(
95 find(fragments, frag => frag.search(/,|\s/) !== -1)
96 );
97
98 if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
99 console.warn(
100 'Offsets separated by white space(s) are deprecated, use a comma (,) instead.'
101 );
102 }
103
104 // If divider is found, we divide the list of values and operands to divide
105 // them by ofset X and Y.
106 const splitRegex = /\s*,\s*|\s+/;
107 let ops = divider !== -1
108 ? [
109 fragments
110 .slice(0, divider)
111 .concat([fragments[divider].split(splitRegex)[0]]),
112 [fragments[divider].split(splitRegex)[1]].concat(
113 fragments.slice(divider + 1)
114 ),
115 ]
116 : [fragments];
117
118 // Convert the values with units to absolute pixels to allow our computations
119 ops = ops.map((op, index) => {
120 // Most of the units rely on the orientation of the popper
121 const measurement = (index === 1 ? !useHeight : useHeight)
122 ? 'height'
123 : 'width';
124 let mergeWithPrevious = false;
125 return (
126 op
127 // This aggregates any `+` or `-` sign that aren't considered operators
128 // e.g.: 10 + +5 => [10, +, +5]
129 .reduce((a, b) => {
130 if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
131 a[a.length - 1] = b;
132 mergeWithPrevious = true;
133 return a;
134 } else if (mergeWithPrevious) {
135 a[a.length - 1] += b;
136 mergeWithPrevious = false;
137 return a;
138 } else {
139 return a.concat(b);
140 }
141 }, [])
142 // Here we convert the string values into number values (in px)
143 .map(str => toValue(str, measurement, popperOffsets, referenceOffsets))
144 );
145 });
146
147 // Loop trough the offsets arrays and execute the operations
148 ops.forEach((op, index) => {
149 op.forEach((frag, index2) => {
150 if (isNumeric(frag)) {
151 offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
152 }
153 });
154 });
155 return offsets;
156 }
157
158 /**
159 * @function
160 * @memberof Modifiers
161 * @argument {Object} data - The data object generated by update method
162 * @argument {Object} options - Modifiers configuration and options
163 * @argument {Number|String} options.offset=0
164 * The offset value as described in the modifier description
165 * @returns {Object} The data object, properly modified
166 */
167 export default function offset(data, { offset }) {
168 const { placement, offsets: { popper, reference } } = data;
169 const basePlacement = placement.split('-')[0];
170
171 let offsets;
172 if (isNumeric(+offset)) {
173 offsets = [+offset, 0];
174 } else {
175 offsets = parseOffset(offset, popper, reference, basePlacement);
176 }
177
178 if (basePlacement === 'left') {
179 popper.top += offsets[0];
180 popper.left -= offsets[1];
181 } else if (basePlacement === 'right') {
182 popper.top += offsets[0];
183 popper.left += offsets[1];
184 } else if (basePlacement === 'top') {
185 popper.left += offsets[0];
186 popper.top -= offsets[1];
187 } else if (basePlacement === 'bottom') {
188 popper.left += offsets[0];
189 popper.top += offsets[1];
190 }
191
192 data.popper = popper;
193 return data;
194 }