Upstream `isElementInViewport` from MobileFrontend
[lhc/web/wiklou.git] / tests / qunit / suites / resources / mediawiki / mediawiki.viewport.test.js
1 ( function ( mw, $ ) {
2
3 // Simulate square element with 20px long edges placed at (20, 20) on the page
4 var
5 DEFAULT_VIEWPORT = {
6 top: 0,
7 left: 0,
8 right: 100,
9 bottom: 100
10 };
11
12 QUnit.module( 'mediawiki.viewport', QUnit.newMwEnvironment( {
13 setup: function () {
14 this.el = $( '<div />' )
15 .appendTo( '#qunit-fixture' )
16 .width( 20 )
17 .height( 20 )
18 .offset( {
19 top: 20,
20 left: 20
21 } )
22 .get( 0 );
23 this.sandbox.stub( mw.viewport, 'makeViewportFromWindow' )
24 .returns( DEFAULT_VIEWPORT );
25 }
26 } ) );
27
28 QUnit.test( 'isElementInViewport', 6, function ( assert ) {
29 var viewport = $.extend( {}, DEFAULT_VIEWPORT );
30 assert.ok( mw.viewport.isElementInViewport( this.el, viewport ),
31 'It should return true when the element is fully enclosed in the viewport' );
32
33 viewport.right = 20;
34 viewport.bottom = 20;
35 assert.ok( mw.viewport.isElementInViewport( this.el, viewport ),
36 'It should return true when only the top-left of the element is within the viewport' );
37
38 viewport.top = 40;
39 viewport.left = 40;
40 viewport.right = 50;
41 viewport.bottom = 50;
42 assert.ok( mw.viewport.isElementInViewport( this.el, viewport ),
43 'It should return true when only the bottom-right is within the viewport' );
44
45 viewport.top = 30;
46 viewport.left = 30;
47 viewport.right = 35;
48 viewport.bottom = 35;
49 assert.ok( mw.viewport.isElementInViewport( this.el, viewport ),
50 'It should return true when the element encapsulates the viewport' );
51
52 viewport.top = 0;
53 viewport.left = 0;
54 viewport.right = 19;
55 viewport.bottom = 19;
56 assert.notOk( mw.viewport.isElementInViewport( this.el, viewport ),
57 'It should return false when the element is not within the viewport' );
58
59 assert.ok( mw.viewport.isElementInViewport( this.el ),
60 'It should default to the window object if no viewport is given' );
61 } );
62
63 QUnit.test( 'isElementCloseToViewport', 3, function ( assert ) {
64 var
65 viewport = {
66 top: 90,
67 left: 90,
68 right: 100,
69 bottom: 100
70 },
71 distantElement = $( '<div />' )
72 .appendTo( '#qunit-fixture' )
73 .width( 20 )
74 .height( 20 )
75 .offset( {
76 top: 220,
77 left: 20
78 } )
79 .get( 0 );
80
81 assert.ok( mw.viewport.isElementCloseToViewport( this.el, 60, viewport ),
82 'It should return true when the element is within the given threshold away' );
83 assert.notOk( mw.viewport.isElementCloseToViewport( this.el, 20, viewport ),
84 'It should return false when the element is further than the given threshold away' );
85 assert.notOk( mw.viewport.isElementCloseToViewport( distantElement ),
86 'It should default to a threshold of 50px and the window\'s viewport' );
87 } );
88
89 }( mediaWiki, jQuery ) );