How to use within method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

useFocusWithin-test.internal.js

Source: useFocusWithin-test.internal.js Github

copy
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @emails react-core
8 */
9
10'use strict';
11
12import {createEventTarget, setPointerEvent} from 'dom-event-testing-library';
13
14let React;
15let ReactFeatureFlags;
16let ReactDOM;
17let useFocusWithin;
18let ReactTestRenderer;
19let act;
20let Scheduler;
21
22function initializeModules(hasPointerEvents) {
23  setPointerEvent(hasPointerEvents);
24  jest.resetModules();
25  ReactFeatureFlags = require('shared/ReactFeatureFlags');
26  ReactFeatureFlags.enableScopeAPI = true;
27  ReactFeatureFlags.enableCreateEventHandleAPI = true;
28  React = require('react');
29  ReactDOM = require('react-dom');
30  ReactTestRenderer = require('react-test-renderer');
31  Scheduler = require('scheduler');
32  act = ReactTestRenderer.unstable_concurrentAct;
33
34  // TODO: This import throws outside of experimental mode. Figure out better
35  // strategy for gated imports.
36  if (__EXPERIMENTAL__) {
37    useFocusWithin = require('react-interactions/events/focus').useFocusWithin;
38  }
39}
40
41const forcePointerEvents = true;
42const table = [[forcePointerEvents], [!forcePointerEvents]];
43
44describe.each(table)(`useFocus`, hasPointerEvents => {
45  let container;
46  let container2;
47
48  beforeEach(() => {
49    initializeModules(hasPointerEvents);
50    container = document.createElement('div');
51    document.body.appendChild(container);
52    container2 = document.createElement('div');
53    document.body.appendChild(container2);
54  });
55
56  afterEach(() => {
57    ReactDOM.render(null, container);
58    document.body.removeChild(container);
59    document.body.removeChild(container2);
60    container = null;
61    container2 = null;
62  });
63
64  describe('disabled', () => {
65    let onFocusWithinChange, onFocusWithinVisibleChange, ref;
66
67    const componentInit = () => {
68      onFocusWithinChange = jest.fn();
69      onFocusWithinVisibleChange = jest.fn();
70      ref = React.createRef();
71      const Component = () => {
72        const focusWithinRef = useFocusWithin(ref, {
73          disabled: true,
74          onFocusWithinChange,
75          onFocusWithinVisibleChange,
76        });
77        return <div ref={focusWithinRef} />;
78      };
79      ReactDOM.render(<Component />, container);
80      Scheduler.unstable_flushAll();
81    };
82
83    // @gate experimental
84    it('prevents custom events being dispatched', () => {
85      componentInit();
86      const target = createEventTarget(ref.current);
87      target.focus();
88      target.blur();
89      expect(onFocusWithinChange).not.toBeCalled();
90      expect(onFocusWithinVisibleChange).not.toBeCalled();
91    });
92  });
93
94  describe('onFocusWithinChange', () => {
95    let onFocusWithinChange, ref, innerRef, innerRef2;
96
97    const Component = ({show}) => {
98      const focusWithinRef = useFocusWithin(ref, {
99        onFocusWithinChange,
100      });
101      return (
102        <div ref={focusWithinRef}>
103          {show && <input ref={innerRef} />}
104          <div ref={innerRef2} />
105        </div>
106      );
107    };
108
109    const componentInit = () => {
110      onFocusWithinChange = jest.fn();
111      ref = React.createRef();
112      innerRef = React.createRef();
113      innerRef2 = React.createRef();
114      ReactDOM.render(<Component show={true} />, container);
115      Scheduler.unstable_flushAll();
116    };
117
118    // @gate experimental
119    it('is called after "blur" and "focus" events on focus target', () => {
120      componentInit();
121      const target = createEventTarget(ref.current);
122      target.focus();
123      expect(onFocusWithinChange).toHaveBeenCalledTimes(1);
124      expect(onFocusWithinChange).toHaveBeenCalledWith(true);
125      target.blur({relatedTarget: container});
126      expect(onFocusWithinChange).toHaveBeenCalledTimes(2);
127      expect(onFocusWithinChange).toHaveBeenCalledWith(false);
128    });
129
130    // @gate experimental
131    it('is called after "blur" and "focus" events on descendants', () => {
132      componentInit();
133      const target = createEventTarget(innerRef.current);
134      target.focus();
135      expect(onFocusWithinChange).toHaveBeenCalledTimes(1);
136      expect(onFocusWithinChange).toHaveBeenCalledWith(true);
137      target.blur({relatedTarget: container});
138      expect(onFocusWithinChange).toHaveBeenCalledTimes(2);
139      expect(onFocusWithinChange).toHaveBeenCalledWith(false);
140    });
141
142    // @gate experimental
143    it('is only called once when focus moves within and outside the subtree', () => {
144      componentInit();
145      const node = ref.current;
146      const innerNode1 = innerRef.current;
147      const innerNode2 = innerRef.current;
148      const target = createEventTarget(node);
149      const innerTarget1 = createEventTarget(innerNode1);
150      const innerTarget2 = createEventTarget(innerNode2);
151
152      // focus shifts into subtree
153      innerTarget1.focus();
154      expect(onFocusWithinChange).toHaveBeenCalledTimes(1);
155      expect(onFocusWithinChange).toHaveBeenCalledWith(true);
156      // focus moves around subtree
157      innerTarget1.blur({relatedTarget: innerNode2});
158      innerTarget2.focus();
159      innerTarget2.blur({relatedTarget: node});
160      target.focus();
161      target.blur({relatedTarget: innerNode1});
162      expect(onFocusWithinChange).toHaveBeenCalledTimes(1);
163      // focus shifts outside subtree
164      innerTarget1.blur({relatedTarget: container});
165      expect(onFocusWithinChange).toHaveBeenCalledTimes(2);
166      expect(onFocusWithinChange).toHaveBeenCalledWith(false);
167    });
168  });
169
170  describe('onFocusWithinVisibleChange', () => {
171    let onFocusWithinVisibleChange, ref, innerRef, innerRef2;
172
173    const Component = ({show}) => {
174      const focusWithinRef = useFocusWithin(ref, {
175        onFocusWithinVisibleChange,
176      });
177      return (
178        <div ref={focusWithinRef}>
179          {show && <input ref={innerRef} />}
180          <div ref={innerRef2} />
181        </div>
182      );
183    };
184
185    const componentInit = () => {
186      onFocusWithinVisibleChange = jest.fn();
187      ref = React.createRef();
188      innerRef = React.createRef();
189      innerRef2 = React.createRef();
190      ReactDOM.render(<Component show={true} />, container);
191      Scheduler.unstable_flushAll();
192    };
193
194    // @gate experimental
195    it('is called after "focus" and "blur" on focus target if keyboard was used', () => {
196      componentInit();
197      const target = createEventTarget(ref.current);
198      const containerTarget = createEventTarget(container);
199      // use keyboard first
200      containerTarget.keydown({key: 'Tab'});
201      target.focus();
202      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(1);
203      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(true);
204      target.blur({relatedTarget: container});
205      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(2);
206      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(false);
207    });
208
209    // @gate experimental
210    it('is called after "focus" and "blur" on descendants if keyboard was used', () => {
211      componentInit();
212      const innerTarget = createEventTarget(innerRef.current);
213      const containerTarget = createEventTarget(container);
214      // use keyboard first
215      containerTarget.keydown({key: 'Tab'});
216      innerTarget.focus();
217      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(1);
218      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(true);
219      innerTarget.blur({relatedTarget: container});
220      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(2);
221      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(false);
222    });
223
224    // @gate experimental
225    it('is called if non-keyboard event is dispatched on target previously focused with keyboard', () => {
226      componentInit();
227      const node = ref.current;
228      const innerNode1 = innerRef.current;
229      const innerNode2 = innerRef2.current;
230
231      const target = createEventTarget(node);
232      const innerTarget1 = createEventTarget(innerNode1);
233      const innerTarget2 = createEventTarget(innerNode2);
234      // use keyboard first
235      target.focus();
236      target.keydown({key: 'Tab'});
237      target.blur({relatedTarget: innerNode1});
238      innerTarget1.focus();
239      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(1);
240      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(true);
241      // then use pointer on the next target, focus should no longer be visible
242      innerTarget2.pointerdown();
243      innerTarget1.blur({relatedTarget: innerNode2});
244      innerTarget2.focus();
245      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(2);
246      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(false);
247      // then use keyboard again
248      innerTarget2.keydown({key: 'Tab', shiftKey: true});
249      innerTarget2.blur({relatedTarget: innerNode1});
250      innerTarget1.focus();
251      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(3);
252      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(true);
253      // then use pointer on the target, focus should no longer be visible
254      innerTarget1.pointerdown();
255      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(4);
256      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(false);
257      // onFocusVisibleChange should not be called again
258      innerTarget1.blur({relatedTarget: container});
259      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(4);
260    });
261
262    // @gate experimental
263    it('is not called after "focus" and "blur" events without keyboard', () => {
264      componentInit();
265      const innerTarget = createEventTarget(innerRef.current);
266      innerTarget.pointerdown();
267      innerTarget.pointerup();
268      innerTarget.blur({relatedTarget: container});
269      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(0);
270    });
271
272    // @gate experimental
273    it('is only called once when focus moves within and outside the subtree', () => {
274      componentInit();
275      const node = ref.current;
276      const innerNode1 = innerRef.current;
277      const innerNode2 = innerRef2.current;
278      const target = createEventTarget(node);
279      const innerTarget1 = createEventTarget(innerNode1);
280      const innerTarget2 = createEventTarget(innerNode2);
281
282      // focus shifts into subtree
283      innerTarget1.focus();
284      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(1);
285      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(true);
286      // focus moves around subtree
287      innerTarget1.blur({relatedTarget: innerNode2});
288      innerTarget2.focus();
289      innerTarget2.blur({relatedTarget: node});
290      target.focus();
291      target.blur({relatedTarget: innerNode1});
292      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(1);
293      // focus shifts outside subtree
294      innerTarget1.blur({relatedTarget: container});
295      expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(2);
296      expect(onFocusWithinVisibleChange).toHaveBeenCalledWith(false);
297    });
298  });
299
300  // @gate experimental
301  it('should correctly handle focus visibility when typing into an input', () => {
302    const onFocusWithinVisibleChange = jest.fn();
303    const ref = React.createRef();
304    const inputRef = React.createRef();
305    const Component = () => {
306      const focusWithinRef = useFocusWithin(ref, {
307        onFocusWithinVisibleChange,
308      });
309      return (
310        <div ref={focusWithinRef}>
311          <input ref={inputRef} type="text" />
312        </div>
313      );
314    };
315    act(() => {
316      ReactDOM.render(<Component />, container);
317    });
318
319    const target = createEventTarget(inputRef.current);
320    // focus the target
321    target.pointerdown();
322    target.focus();
323    target.keydown({key: 'a'});
324    expect(onFocusWithinVisibleChange).toHaveBeenCalledTimes(0);
325  });
326
327  describe('onBeforeBlurWithin', () => {
328    let onBeforeBlurWithin, onAfterBlurWithin, ref, innerRef, innerRef2;
329
330    beforeEach(() => {
331      onBeforeBlurWithin = jest.fn();
332      onAfterBlurWithin = jest.fn(e => {
333        e.persist();
334      });
335      ref = React.createRef();
336      innerRef = React.createRef();
337      innerRef2 = React.createRef();
338    });
339
340    // @gate experimental
341    it('is called after a focused element is unmounted', () => {
342      const Component = ({show}) => {
343        const focusWithinRef = useFocusWithin(ref, {
344          onBeforeBlurWithin,
345          onAfterBlurWithin,
346        });
347        return (
348          <div ref={focusWithinRef}>
349            {show && <input ref={innerRef} />}
350            <div ref={innerRef2} />
351          </div>
352        );
353      };
354
355      ReactDOM.render(<Component show={true} />, container);
356      Scheduler.unstable_flushAll();
357
358      const inner = innerRef.current;
359      const target = createEventTarget(inner);
360      target.keydown({key: 'Tab'});
361      target.focus();
362      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
363      expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
364      ReactDOM.render(<Component show={false} />, container);
365      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
366      expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
367      expect(onAfterBlurWithin).toHaveBeenCalledWith(
368        expect.objectContaining({relatedTarget: inner}),
369      );
370    });
371
372    // @gate experimental
373    it('is called after a nested focused element is unmounted', () => {
374      const Component = ({show}) => {
375        const focusWithinRef = useFocusWithin(ref, {
376          onBeforeBlurWithin,
377          onAfterBlurWithin,
378        });
379        return (
380          <div ref={focusWithinRef}>
381            {show && (
382              <div>
383                <input ref={innerRef} />
384              </div>
385            )}
386            <div ref={innerRef2} />
387          </div>
388        );
389      };
390
391      ReactDOM.render(<Component show={true} />, container);
392      Scheduler.unstable_flushAll();
393
394      const inner = innerRef.current;
395      const target = createEventTarget(inner);
396      target.keydown({key: 'Tab'});
397      target.focus();
398      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
399      expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
400      ReactDOM.render(<Component show={false} />, container);
401      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
402      expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
403      expect(onAfterBlurWithin).toHaveBeenCalledWith(
404        expect.objectContaining({relatedTarget: inner}),
405      );
406    });
407
408    // @gate experimental
409    it('is called after many elements are unmounted', () => {
410      const buttonRef = React.createRef();
411      const inputRef = React.createRef();
412
413      const Component = ({show}) => {
414        const focusWithinRef = useFocusWithin(ref, {
415          onBeforeBlurWithin,
416          onAfterBlurWithin,
417        });
418        return (
419          <div ref={focusWithinRef}>
420            {show && <button>Press me!</button>}
421            {show && <button>Press me!</button>}
422            {show && <input ref={inputRef} />}
423            {show && <button>Press me!</button>}
424            {!show && <button ref={buttonRef}>Press me!</button>}
425            {show && <button>Press me!</button>}
426            <button>Press me!</button>
427            <button>Press me!</button>
428          </div>
429        );
430      };
431
432      ReactDOM.render(<Component show={true} />, container);
433      Scheduler.unstable_flushAll();
434
435      inputRef.current.focus();
436      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
437      expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
438      ReactDOM.render(<Component show={false} />, container);
439      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
440      expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
441    });
442
443    // @gate experimental
444    it('is called after a nested focused element is unmounted (with scope query)', () => {
445      const TestScope = React.unstable_Scope;
446      const testScopeQuery = (type, props) => true;
447      let targetNodes;
448      let targetNode;
449
450      const Component = ({show}) => {
451        const scopeRef = React.useRef(null);
452        const focusWithinRef = useFocusWithin(scopeRef, {
453          onBeforeBlurWithin(event) {
454            const scope = scopeRef.current;
455            targetNode = innerRef.current;
456            targetNodes = scope.DO_NOT_USE_queryAllNodes(testScopeQuery);
457          },
458        });
459
460        return (
461          <TestScope ref={focusWithinRef}>
462            {show && <input ref={innerRef} />}
463          </TestScope>
464        );
465      };
466
467      ReactDOM.render(<Component show={true} />, container);
468      Scheduler.unstable_flushAll();
469
470      const inner = innerRef.current;
471      const target = createEventTarget(inner);
472      target.keydown({key: 'Tab'});
473      target.focus();
474      ReactDOM.render(<Component show={false} />, container);
475      Scheduler.unstable_flushAll();
476      expect(targetNodes).toEqual([targetNode]);
477    });
478
479    // @gate experimental
480    it('is called after a focused suspended element is hidden', () => {
481      const Suspense = React.Suspense;
482      let suspend = false;
483      let resolve;
484      const promise = new Promise(resolvePromise => (resolve = resolvePromise));
485
486      function Child() {
487        if (suspend) {
488          throw promise;
489        } else {
490          return <input ref={innerRef} />;
491        }
492      }
493
494      const Component = ({show}) => {
495        const focusWithinRef = useFocusWithin(ref, {
496          onBeforeBlurWithin,
497          onAfterBlurWithin,
498        });
499
500        return (
501          <div ref={focusWithinRef}>
502            <Suspense fallback="Loading...">
503              <Child />
504            </Suspense>
505          </div>
506        );
507      };
508
509      const root = ReactDOM.createRoot(container2);
510
511      act(() => {
512        root.render(<Component />);
513      });
514      jest.runAllTimers();
515      expect(container2.innerHTML).toBe('<div><input></div>');
516
517      const inner = innerRef.current;
518      const target = createEventTarget(inner);
519      target.keydown({key: 'Tab'});
520      target.focus();
521      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
522      expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
523
524      suspend = true;
525      act(() => {
526        root.render(<Component />);
527      });
528      jest.runAllTimers();
529      expect(container2.innerHTML).toBe(
530        '<div><input style="display: none;">Loading...</div>',
531      );
532      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
533      expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
534      resolve();
535    });
536
537    // @gate experimental
538    it('is called after a focused suspended element is hidden then shown', () => {
539      const Suspense = React.Suspense;
540      let suspend = false;
541      let resolve;
542      const promise = new Promise(resolvePromise => (resolve = resolvePromise));
543      const buttonRef = React.createRef();
544
545      function Child() {
546        if (suspend) {
547          throw promise;
548        } else {
549          return <input ref={innerRef} />;
550        }
551      }
552
553      const Component = ({show}) => {
554        const focusWithinRef = useFocusWithin(ref, {
555          onBeforeBlurWithin,
556          onAfterBlurWithin,
557        });
558
559        return (
560          <div ref={focusWithinRef}>
561            <Suspense fallback={<button ref={buttonRef}>Loading...</button>}>
562              <Child />
563            </Suspense>
564          </div>
565        );
566      };
567
568      const root = ReactDOM.createRoot(container2);
569
570      act(() => {
571        root.render(<Component />);
572      });
573      jest.runAllTimers();
574
575      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
576      expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
577
578      suspend = true;
579      act(() => {
580        root.render(<Component />);
581      });
582      jest.runAllTimers();
583      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
584      expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
585
586      act(() => {
587        root.render(<Component />);
588      });
589      jest.runAllTimers();
590      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(0);
591      expect(onAfterBlurWithin).toHaveBeenCalledTimes(0);
592
593      buttonRef.current.focus();
594      suspend = false;
595      act(() => {
596        root.render(<Component />);
597      });
598      jest.runAllTimers();
599      expect(onBeforeBlurWithin).toHaveBeenCalledTimes(1);
600      expect(onAfterBlurWithin).toHaveBeenCalledTimes(1);
601
602      resolve();
603    });
604  });
605});
606
Full Screen

position.js

Source: position.js Github

copy
1/*!
2 * jQuery UI Position 1.12.1
3 * http://jqueryui.com
4 *
5 * Copyright jQuery Foundation and other contributors
6 * Released under the MIT license.
7 * http://jquery.org/license
8 *
9 * http://api.jqueryui.com/position/
10 */
11
12//>>label: Position
13//>>group: Core
14//>>description: Positions elements relative to other elements.
15//>>docs: http://api.jqueryui.com/position/
16//>>demos: http://jqueryui.com/position/
17
18( function( factory ) {
19	if ( typeof define === "function" && define.amd ) {
20
21		// AMD. Register as an anonymous module.
22		define( [ "jquery", "./version" ], factory );
23	} else {
24
25		// Browser globals
26		factory( jQuery );
27	}
28}( function( $ ) {
29( function() {
30var cachedScrollbarWidth,
31	max = Math.max,
32	abs = Math.abs,
33	rhorizontal = /left|center|right/,
34	rvertical = /top|center|bottom/,
35	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
36	rposition = /^\w+/,
37	rpercent = /%$/,
38	_position = $.fn.position;
39
40function getOffsets( offsets, width, height ) {
41	return [
42		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
43		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
44	];
45}
46
47function parseCss( element, property ) {
48	return parseInt( $.css( element, property ), 10 ) || 0;
49}
50
51function getDimensions( elem ) {
52	var raw = elem[ 0 ];
53	if ( raw.nodeType === 9 ) {
54		return {
55			width: elem.width(),
56			height: elem.height(),
57			offset: { top: 0, left: 0 }
58		};
59	}
60	if ( $.isWindow( raw ) ) {
61		return {
62			width: elem.width(),
63			height: elem.height(),
64			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
65		};
66	}
67	if ( raw.preventDefault ) {
68		return {
69			width: 0,
70			height: 0,
71			offset: { top: raw.pageY, left: raw.pageX }
72		};
73	}
74	return {
75		width: elem.outerWidth(),
76		height: elem.outerHeight(),
77		offset: elem.offset()
78	};
79}
80
81$.position = {
82	scrollbarWidth: function() {
83		if ( cachedScrollbarWidth !== undefined ) {
84			return cachedScrollbarWidth;
85		}
86		var w1, w2,
87			div = $( "<div " +
88				"style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" +
89				"<div style='height:100px;width:auto;'></div></div>" ),
90			innerDiv = div.children()[ 0 ];
91
92		$( "body" ).append( div );
93		w1 = innerDiv.offsetWidth;
94		div.css( "overflow", "scroll" );
95
96		w2 = innerDiv.offsetWidth;
97
98		if ( w1 === w2 ) {
99			w2 = div[ 0 ].clientWidth;
100		}
101
102		div.remove();
103
104		return ( cachedScrollbarWidth = w1 - w2 );
105	},
106	getScrollInfo: function( within ) {
107		var overflowX = within.isWindow || within.isDocument ? "" :
108				within.element.css( "overflow-x" ),
109			overflowY = within.isWindow || within.isDocument ? "" :
110				within.element.css( "overflow-y" ),
111			hasOverflowX = overflowX === "scroll" ||
112				( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
113			hasOverflowY = overflowY === "scroll" ||
114				( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
115		return {
116			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
117			height: hasOverflowX ? $.position.scrollbarWidth() : 0
118		};
119	},
120	getWithinInfo: function( element ) {
121		var withinElement = $( element || window ),
122			isWindow = $.isWindow( withinElement[ 0 ] ),
123			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
124			hasOffset = !isWindow && !isDocument;
125		return {
126			element: withinElement,
127			isWindow: isWindow,
128			isDocument: isDocument,
129			offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
130			scrollLeft: withinElement.scrollLeft(),
131			scrollTop: withinElement.scrollTop(),
132			width: withinElement.outerWidth(),
133			height: withinElement.outerHeight()
134		};
135	}
136};
137
138$.fn.position = function( options ) {
139	if ( !options || !options.of ) {
140		return _position.apply( this, arguments );
141	}
142
143	// Make a copy, we don't want to modify arguments
144	options = $.extend( {}, options );
145
146	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
147		target = $( options.of ),
148		within = $.position.getWithinInfo( options.within ),
149		scrollInfo = $.position.getScrollInfo( within ),
150		collision = ( options.collision || "flip" ).split( " " ),
151		offsets = {};
152
153	dimensions = getDimensions( target );
154	if ( target[ 0 ].preventDefault ) {
155
156		// Force left top to allow flipping
157		options.at = "left top";
158	}
159	targetWidth = dimensions.width;
160	targetHeight = dimensions.height;
161	targetOffset = dimensions.offset;
162
163	// Clone to reuse original targetOffset later
164	basePosition = $.extend( {}, targetOffset );
165
166	// Force my and at to have valid horizontal and vertical positions
167	// if a value is missing or invalid, it will be converted to center
168	$.each( [ "my", "at" ], function() {
169		var pos = ( options[ this ] || "" ).split( " " ),
170			horizontalOffset,
171			verticalOffset;
172
173		if ( pos.length === 1 ) {
174			pos = rhorizontal.test( pos[ 0 ] ) ?
175				pos.concat( [ "center" ] ) :
176				rvertical.test( pos[ 0 ] ) ?
177					[ "center" ].concat( pos ) :
178					[ "center", "center" ];
179		}
180		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
181		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
182
183		// Calculate offsets
184		horizontalOffset = roffset.exec( pos[ 0 ] );
185		verticalOffset = roffset.exec( pos[ 1 ] );
186		offsets[ this ] = [
187			horizontalOffset ? horizontalOffset[ 0 ] : 0,
188			verticalOffset ? verticalOffset[ 0 ] : 0
189		];
190
191		// Reduce to just the positions without the offsets
192		options[ this ] = [
193			rposition.exec( pos[ 0 ] )[ 0 ],
194			rposition.exec( pos[ 1 ] )[ 0 ]
195		];
196	} );
197
198	// Normalize collision option
199	if ( collision.length === 1 ) {
200		collision[ 1 ] = collision[ 0 ];
201	}
202
203	if ( options.at[ 0 ] === "right" ) {
204		basePosition.left += targetWidth;
205	} else if ( options.at[ 0 ] === "center" ) {
206		basePosition.left += targetWidth / 2;
207	}
208
209	if ( options.at[ 1 ] === "bottom" ) {
210		basePosition.top += targetHeight;
211	} else if ( options.at[ 1 ] === "center" ) {
212		basePosition.top += targetHeight / 2;
213	}
214
215	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
216	basePosition.left += atOffset[ 0 ];
217	basePosition.top += atOffset[ 1 ];
218
219	return this.each( function() {
220		var collisionPosition, using,
221			elem = $( this ),
222			elemWidth = elem.outerWidth(),
223			elemHeight = elem.outerHeight(),
224			marginLeft = parseCss( this, "marginLeft" ),
225			marginTop = parseCss( this, "marginTop" ),
226			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
227				scrollInfo.width,
228			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
229				scrollInfo.height,
230			position = $.extend( {}, basePosition ),
231			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
232
233		if ( options.my[ 0 ] === "right" ) {
234			position.left -= elemWidth;
235		} else if ( options.my[ 0 ] === "center" ) {
236			position.left -= elemWidth / 2;
237		}
238
239		if ( options.my[ 1 ] === "bottom" ) {
240			position.top -= elemHeight;
241		} else if ( options.my[ 1 ] === "center" ) {
242			position.top -= elemHeight / 2;
243		}
244
245		position.left += myOffset[ 0 ];
246		position.top += myOffset[ 1 ];
247
248		collisionPosition = {
249			marginLeft: marginLeft,
250			marginTop: marginTop
251		};
252
253		$.each( [ "left", "top" ], function( i, dir ) {
254			if ( $.ui.position[ collision[ i ] ] ) {
255				$.ui.position[ collision[ i ] ][ dir ]( position, {
256					targetWidth: targetWidth,
257					targetHeight: targetHeight,
258					elemWidth: elemWidth,
259					elemHeight: elemHeight,
260					collisionPosition: collisionPosition,
261					collisionWidth: collisionWidth,
262					collisionHeight: collisionHeight,
263					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
264					my: options.my,
265					at: options.at,
266					within: within,
267					elem: elem
268				} );
269			}
270		} );
271
272		if ( options.using ) {
273
274			// Adds feedback as second argument to using callback, if present
275			using = function( props ) {
276				var left = targetOffset.left - position.left,
277					right = left + targetWidth - elemWidth,
278					top = targetOffset.top - position.top,
279					bottom = top + targetHeight - elemHeight,
280					feedback = {
281						target: {
282							element: target,
283							left: targetOffset.left,
284							top: targetOffset.top,
285							width: targetWidth,
286							height: targetHeight
287						},
288						element: {
289							element: elem,
290							left: position.left,
291							top: position.top,
292							width: elemWidth,
293							height: elemHeight
294						},
295						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
296						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
297					};
298				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
299					feedback.horizontal = "center";
300				}
301				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
302					feedback.vertical = "middle";
303				}
304				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
305					feedback.important = "horizontal";
306				} else {
307					feedback.important = "vertical";
308				}
309				options.using.call( this, props, feedback );
310			};
311		}
312
313		elem.offset( $.extend( position, { using: using } ) );
314	} );
315};
316
317$.ui.position = {
318	fit: {
319		left: function( position, data ) {
320			var within = data.within,
321				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
322				outerWidth = within.width,
323				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
324				overLeft = withinOffset - collisionPosLeft,
325				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
326				newOverRight;
327
328			// Element is wider than within
329			if ( data.collisionWidth > outerWidth ) {
330
331				// Element is initially over the left side of within
332				if ( overLeft > 0 && overRight <= 0 ) {
333					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
334						withinOffset;
335					position.left += overLeft - newOverRight;
336
337				// Element is initially over right side of within
338				} else if ( overRight > 0 && overLeft <= 0 ) {
339					position.left = withinOffset;
340
341				// Element is initially over both left and right sides of within
342				} else {
343					if ( overLeft > overRight ) {
344						position.left = withinOffset + outerWidth - data.collisionWidth;
345					} else {
346						position.left = withinOffset;
347					}
348				}
349
350			// Too far left -> align with left edge
351			} else if ( overLeft > 0 ) {
352				position.left += overLeft;
353
354			// Too far right -> align with right edge
355			} else if ( overRight > 0 ) {
356				position.left -= overRight;
357
358			// Adjust based on position and margin
359			} else {
360				position.left = max( position.left - collisionPosLeft, position.left );
361			}
362		},
363		top: function( position, data ) {
364			var within = data.within,
365				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
366				outerHeight = data.within.height,
367				collisionPosTop = position.top - data.collisionPosition.marginTop,
368				overTop = withinOffset - collisionPosTop,
369				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
370				newOverBottom;
371
372			// Element is taller than within
373			if ( data.collisionHeight > outerHeight ) {
374
375				// Element is initially over the top of within
376				if ( overTop > 0 && overBottom <= 0 ) {
377					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
378						withinOffset;
379					position.top += overTop - newOverBottom;
380
381				// Element is initially over bottom of within
382				} else if ( overBottom > 0 && overTop <= 0 ) {
383					position.top = withinOffset;
384
385				// Element is initially over both top and bottom of within
386				} else {
387					if ( overTop > overBottom ) {
388						position.top = withinOffset + outerHeight - data.collisionHeight;
389					} else {
390						position.top = withinOffset;
391					}
392				}
393
394			// Too far up -> align with top
395			} else if ( overTop > 0 ) {
396				position.top += overTop;
397
398			// Too far down -> align with bottom edge
399			} else if ( overBottom > 0 ) {
400				position.top -= overBottom;
401
402			// Adjust based on position and margin
403			} else {
404				position.top = max( position.top - collisionPosTop, position.top );
405			}
406		}
407	},
408	flip: {
409		left: function( position, data ) {
410			var within = data.within,
411				withinOffset = within.offset.left + within.scrollLeft,
412				outerWidth = within.width,
413				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
414				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
415				overLeft = collisionPosLeft - offsetLeft,
416				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
417				myOffset = data.my[ 0 ] === "left" ?
418					-data.elemWidth :
419					data.my[ 0 ] === "right" ?
420						data.elemWidth :
421						0,
422				atOffset = data.at[ 0 ] === "left" ?
423					data.targetWidth :
424					data.at[ 0 ] === "right" ?
425						-data.targetWidth :
426						0,
427				offset = -2 * data.offset[ 0 ],
428				newOverRight,
429				newOverLeft;
430
431			if ( overLeft < 0 ) {
432				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
433					outerWidth - withinOffset;
434				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
435					position.left += myOffset + atOffset + offset;
436				}
437			} else if ( overRight > 0 ) {
438				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
439					atOffset + offset - offsetLeft;
440				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
441					position.left += myOffset + atOffset + offset;
442				}
443			}
444		},
445		top: function( position, data ) {
446			var within = data.within,
447				withinOffset = within.offset.top + within.scrollTop,
448				outerHeight = within.height,
449				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
450				collisionPosTop = position.top - data.collisionPosition.marginTop,
451				overTop = collisionPosTop - offsetTop,
452				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
453				top = data.my[ 1 ] === "top",
454				myOffset = top ?
455					-data.elemHeight :
456					data.my[ 1 ] === "bottom" ?
457						data.elemHeight :
458						0,
459				atOffset = data.at[ 1 ] === "top" ?
460					data.targetHeight :
461					data.at[ 1 ] === "bottom" ?
462						-data.targetHeight :
463						0,
464				offset = -2 * data.offset[ 1 ],
465				newOverTop,
466				newOverBottom;
467			if ( overTop < 0 ) {
468				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
469					outerHeight - withinOffset;
470				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
471					position.top += myOffset + atOffset + offset;
472				}
473			} else if ( overBottom > 0 ) {
474				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
475					offset - offsetTop;
476				if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
477					position.top += myOffset + atOffset + offset;
478				}
479			}
480		}
481	},
482	flipfit: {
483		left: function() {
484			$.ui.position.flip.left.apply( this, arguments );
485			$.ui.position.fit.left.apply( this, arguments );
486		},
487		top: function() {
488			$.ui.position.flip.top.apply( this, arguments );
489			$.ui.position.fit.top.apply( this, arguments );
490		}
491	}
492};
493
494} )();
495
496return $.ui.position;
497
498} ) );
499
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)