code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * mobile event unit tests */ (function($){ var libName = "jquery.mobile.event.js", absFn = Math.abs, originalEventFn = $.Event.prototype.originalEvent, preventDefaultFn = $.Event.prototype.preventDefault, events = ("touchstart touchmove touchend orientationchange tap taphold " + "swipe swipeleft swiperight scrollstart scrollstop").split( " " ); module(libName, { setup: function(){ // ensure bindings are removed $.each(events + "vmouseup vmousedown".split(" "), function(i, name){ $("#qunit-fixture").unbind(); }); //NOTE unmock Math.abs = absFn; $.Event.prototype.originalEvent = originalEventFn; $.Event.prototype.preventDefault = preventDefaultFn; // make sure the event objects respond to touches to simulate // the collections existence in non touch enabled test browsers $.Event.prototype.touches = [{pageX: 1, pageY: 1 }]; $($.mobile.pageContainer).unbind( "throttledresize" ); } }); $.testHelper.excludeFileProtocol(function(){ test( "new events defined on the jquery object", function(){ $.each(events, function( i, name ) { delete $.fn[name]; same($.fn[name], undefined); }); $.testHelper.reloadLib(libName); $.each(events, function( i, name ) { ok($.fn[name] !== undefined, name + " is not undefined"); }); }); }); asyncTest( "defined event functions bind a closure when passed", function(){ expect( 1 ); $('#qunit-fixture').bind(events[0], function(){ ok(true, "event fired"); start(); }); $('#qunit-fixture').trigger(events[0]); }); asyncTest( "defined event functions trigger the event with no arguments", function(){ expect( 1 ); $('#qunit-fixture').bind('touchstart', function(){ ok(true, "event fired"); start(); }); $('#qunit-fixture').touchstart(); }); test( "defining event functions sets the attrFn to true", function(){ $.each(events, function(i, name){ ok($.attrFn[name], "attribute function is true"); }); }); test( "scrollstart enabled defaults to true", function(){ $.event.special.scrollstart.enabled = false; $.testHelper.reloadLib(libName); ok($.event.special.scrollstart.enabled, "scrollstart enabled"); }); asyncTest( "scrollstart setup binds a function that returns when its disabled", function(){ expect( 1 ); $.event.special.scrollstart.enabled = false; $( "#qunit-fixture" ).bind("scrollstart", function(){ ok(false, "scrollstart fired"); }); $( "#qunit-fixture" ).bind("touchmove", function(){ ok(true, "touchmove fired"); start(); }); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "scrollstart setup binds a function that triggers scroll start when enabled", function(){ $.event.special.scrollstart.enabled = true; $( "#qunit-fixture" ).bind("scrollstart", function(){ ok(true, "scrollstart fired"); start(); }); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "scrollstart setup binds a function that triggers scroll stop after 50 ms", function(){ var triggered = false; $.event.special.scrollstart.enabled = true; $( "#qunit-fixture" ).bind("scrollstop", function(){ triggered = true; }); ok(!triggered, "not triggered"); $( "#qunit-fixture" ).trigger("touchmove"); setTimeout(function(){ ok(triggered, "triggered"); start(); }, 50); }); var forceTouchSupport = function(){ $.support.touch = true; $.testHelper.reloadLib(libName); //mock originalEvent information $.Event.prototype.originalEvent = { touches: [{ 'pageX' : 0 }, { 'pageY' : 0 }] }; }; asyncTest( "long press fires tap hold after 750 ms", function(){ var taphold = false; forceTouchSupport(); $( "#qunit-fixture" ).bind("taphold", function(){ taphold = true; }); $( "#qunit-fixture" ).trigger("vmousedown"); setTimeout(function(){ ok(taphold); start(); }, 751); }); //NOTE used to simulate movement when checked //TODO find a better way ... var mockAbs = function(value){ Math.abs = function(){ return value; }; }; asyncTest( "move prevents taphold", function(){ expect( 1 ); var taphold = false; forceTouchSupport(); mockAbs(100); //NOTE record taphold event $( "#qunit-fixture" ).bind("taphold", function(){ ok(false, "taphold fired"); taphold = true; }); //NOTE start the touch events $( "#qunit-fixture" ).trigger("vmousedown"); //NOTE fire touchmove to push back taphold setTimeout(function(){ $( "#qunit-fixture" ).trigger("vmousecancel"); }, 100); //NOTE verify that the taphold hasn't been fired // with the normal timing setTimeout(function(){ ok(!taphold, "taphold not fired"); start(); }, 751); }); asyncTest( "tap event fired without movement", function(){ expect( 1 ); var tap = false, checkTap = function(){ ok(true, "tap fired"); }; forceTouchSupport(); //NOTE record the tap event $( "#qunit-fixture" ).bind("tap", checkTap); $( "#qunit-fixture" ).trigger("vmousedown"); $( "#qunit-fixture" ).trigger("vmouseup"); $( "#qunit-fixture" ).trigger("vclick"); setTimeout(function(){ start(); }, 400); }); asyncTest( "tap event not fired when there is movement", function(){ expect( 1 ); var tap = false; forceTouchSupport(); //NOTE record tap event $( "#qunit-fixture" ).bind("tap", function(){ ok(false, "tap fired"); tap = true; }); //NOTE make sure movement is recorded mockAbs(100); //NOTE start and move right away $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchmove"); //NOTE end touch sequence after 20 ms setTimeout(function(){ $( "#qunit-fixture" ).trigger("touchend"); }, 20); setTimeout(function(){ ok(!tap, "not tapped"); start(); }, 40); }); asyncTest( "tap event propagates up DOM tree", function(){ var tap = 0, $qf = $( "#qunit-fixture" ), $doc = $( document ), docTapCB = function(){ same(++tap, 2, "document tap callback called once after #qunit-fixture callback"); }; $qf.bind( "tap", function() { same(++tap, 1, "#qunit-fixture tap callback called once"); }); $doc.bind( "tap", docTapCB ); $qf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered twice, once for // #qunit-fixture, and a second time for document. same( tap, 2, "final tap callback count is 2" ); $doc.unbind( "tap", docTapCB ); start(); }); asyncTest( "stopPropagation() prevents tap from propagating up DOM tree", function(){ var tap = 0, $qf = $( "#qunit-fixture" ), $doc = $( document ), docTapCB = function(){ ok(false, "tap should NOT be triggered on document"); }; $qf.bind( "tap", function(e) { same(++tap, 1, "tap callback 1 triggered once on #qunit-fixture"); e.stopPropagation(); }) .bind( "tap", function(e) { same(++tap, 2, "tap callback 2 triggered once on #qunit-fixture"); }); $doc.bind( "tap", docTapCB); $qf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered twice. same( tap, 2, "final tap count is 2" ); $doc.unbind( "tap", docTapCB ); start(); }); asyncTest( "stopImmediatePropagation() prevents tap propagation and execution of 2nd handler", function(){ var tap = 0, $cf = $( "#qunit-fixture" ); $doc = $( document ), docTapCB = function(){ ok(false, "tap should NOT be triggered on document"); }; // Bind 2 tap callbacks on qunit-fixture. Only the first // one should ever be called. $cf.bind( "tap", function(e) { same(++tap, 1, "tap callback 1 triggered once on #qunit-fixture"); e.stopImmediatePropagation(); }) .bind( "tap", function(e) { ok(false, "tap callback 2 should NOT be triggered on #qunit-fixture"); }); $doc.bind( "tap", docTapCB); $cf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered once. same( tap, 1, "final tap count is 1" ); $doc.unbind( "tap", docTapCB ); start(); }); var swipeTimedTest = function(opts){ var swipe = false; forceTouchSupport(); $( "#qunit-fixture" ).bind('swipe', function(){ swipe = true; }); //NOTE bypass the trigger source check $.Event.prototype.originalEvent = { touches: false }; $( "#qunit-fixture" ).trigger("touchstart"); //NOTE make sure the coordinates are calculated within range // to be registered as a swipe mockAbs(opts.coordChange); setTimeout(function(){ $( "#qunit-fixture" ).trigger("touchmove"); $( "#qunit-fixture" ).trigger("touchend"); }, opts.timeout + 100); setTimeout(function(){ same(swipe, opts.expected, "swipe expected"); start(); }, opts.timeout + 200); stop(); }; test( "swipe fired when coordinate change in less than a second", function(){ swipeTimedTest({ timeout: 10, coordChange: 35, expected: true }); }); test( "swipe not fired when coordinate change takes more than a second", function(){ swipeTimedTest({ timeout: 1000, coordChange: 35, expected: false }); }); test( "swipe not fired when coordinate change <= 30", function(){ swipeTimedTest({ timeout: 1000, coordChange: 30, expected: false }); }); test( "swipe not fired when coordinate change >= 75", function(){ swipeTimedTest({ timeout: 1000, coordChange: 75, expected: false }); }); asyncTest( "scrolling prevented when coordinate change > 10", function(){ expect( 1 ); forceTouchSupport(); // ensure the swipe custome event is setup $( "#qunit-fixture" ).bind('swipe', function(){}); //NOTE bypass the trigger source check $.Event.prototype.originalEvent = { touches: false }; $.Event.prototype.preventDefault = function(){ ok(true, "prevent default called"); start(); }; mockAbs(11); $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "move handler returns when touchstart has been fired since touchstop", function(){ expect( 1 ); // bypass triggered event check $.Event.prototype.originalEvent = { touches: false }; forceTouchSupport(); // ensure the swipe custome event is setup $( "#qunit-fixture" ).bind('swipe', function(){}); $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchend"); $( "#qunit-fixture" ).bind("touchmove", function(){ ok(true, "touchmove bound functions are fired"); start(); }); Math.abs = function(){ ok(false, "shouldn't compare coordinates"); }; $( "#qunit-fixture" ).trigger("touchmove"); }); var nativeSupportTest = function(opts){ $.support.orientation = opts.orientationSupport; same($.event.special.orientationchange[opts.method](), opts.returnValue); }; test( "orientation change setup should do nothing when natively supported", function(){ nativeSupportTest({ method: 'setup', orientationSupport: true, returnValue: false }); }); test( "orientation change setup should bind resize when not supported natively", function(){ nativeSupportTest({ method: 'setup', orientationSupport: false, returnValue: undefined //NOTE result of bind function call }); }); test( "orientation change teardown should do nothing when natively supported", function(){ nativeSupportTest({ method: 'teardown', orientationSupport: true, returnValue: false }); }); test( "orientation change teardown should unbind resize when not supported natively", function(){ nativeSupportTest({ method: 'teardown', orientationSupport: false, returnValue: undefined //NOTE result of unbind function call }); }); /* The following 4 tests are async so that the throttled event triggers don't interfere with subsequent tests */ asyncTest( "throttledresize event proxies resize events", function(){ $( window ).one( "throttledresize", function(){ ok( true, "throttledresize called"); start(); }); $( window ).trigger( "resize" ); }); asyncTest( "throttledresize event prevents resize events from firing more frequently than 250ms", function(){ var called = 0; $(window).bind( "throttledresize", function(){ called++; }); // NOTE 250 ms * 3 = 750ms which is plenty of time // for the events to trigger before the next test, but // not so much time that the second resize will be triggered // before the call to same() is made $.testHelper.sequence([ function(){ $(window).trigger( "resize" ).trigger( "resize" ); }, // verify that only one throttled resize was called after 250ms function(){ same( called, 1 ); }, function(){ start(); } ], 250); }); asyncTest( "throttledresize event promises that a held call will execute only once after throttled timeout", function(){ var called = 0; expect( 2 ); $.testHelper.eventSequence( "throttledresize", [ // ignore the first call $.noop, function(){ ok( true, "second throttled resize should run" ); }, function(timedOut){ ok( timedOut, "third throttled resize should not run"); start(); } ]); $.mobile.pageContainer .trigger( "resize" ) .trigger( "resize" ) .trigger( "resize" ); }); asyncTest( "mousedown mouseup and click events should add a which when its not defined", function() { var whichDefined = function( event ){ same(event.which, 1); }; $( document ).bind( "vclick", whichDefined); $( document ).trigger( "click" ); $( document ).bind( "vmousedown", whichDefined); $( document ).trigger( "mousedown" ); $( document ).bind( "vmouseup", function( event ){ same(event.which, 1); start(); }); $( document ).trigger( "mouseup" ); }); })(jQuery);
JavaScript
/* * mobile dialog unit tests */ (function($){ module('jquery.mobile.fieldContain.js'); test( "Field container contains appropriate css styles", function(){ ok($('#test-fieldcontain').hasClass('ui-field-contain ui-body ui-br'), 'A fieldcontain element must contain styles "ui-field-contain ui-body ui-br"'); }); test( "Field container will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-field-contain").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-field-contain").length, "enhancements applied" ); }); })(jQuery);
JavaScript
/* * mobile buttonMarkup tests */ (function($){ module("jquery.mobile.buttonMarkup.js"); test( "control group buttons should be enhanced inside a footer", function(){ var group, linkCount; group = $("#control-group-footer"); linkCount = group.find( "a" ).length; same( group.find("a.ui-btn").length, linkCount, "all 4 links should be buttons"); same( group.find("a > span.ui-corner-left").length, 1, "only 1 left cornered button"); same( group.find("a > span.ui-corner-right").length, 1, "only 1 right cornered button"); same( group.find("a > span:not(.ui-corner-left):not(.ui-corner-right)").length, linkCount - 2, "only 2 buttons are cornered"); }); test( "control group buttons should respect theme-related data attributes", function(){ var group = $("#control-group-content"); ok(!group.find('[data-shadow=false]').hasClass("ui-shadow"), "buttons with data-shadow=false should not have the ui-shadow class"); ok(!group.find('[data-corners=false]').hasClass("ui-btn-corner-all"), "buttons with data-corners=false should not have the ui-btn-corner-all class"); ok(!group.find('[data-iconshadow=false] .ui-icon').hasClass("ui-icon-shadow"), "buttons with data-iconshadow=false should not have the ui-icon-shadow class on their icons"); }); // Test for issue #3046 and #3054: test( "mousedown on SVG elements should not throw an exception", function(){ var svg = $("#embedded-svg"), success = true, rect; ok(svg.length > 0, "found embedded svg document" ); if ( svg.length > 0 ) { rect = $( "rect", svg ); ok(rect.length > 0, "found rect" ); try { rect.trigger("mousedown"); } catch ( ex ) { success = false; } ok( success, "mousedown executed without exception"); } }); })(jQuery);
JavaScript
/* * mobile listview unit tests */ // TODO split out into seperate test files (function( $ ){ module( "Collapsible section", {}); asyncTest( "The page should enhanced correctly", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-test" ); }, function() { var $page = $( "#basic-collapsible-test" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible" ), ".ui-collapsible class added to collapsible elements" ); ok($page.find( ".ui-content >:eq(0) >:header" ).hasClass( "ui-collapsible-heading" ), ".ui-collapsible-heading class added to collapsible heading" ); ok($page.find( ".ui-content >:eq(0) > div" ).hasClass( "ui-collapsible-content" ), ".ui-collapsible-content class added to collapsible content" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible-collapsed" ), ".ui-collapsible-collapsed added to collapsed elements" ); ok(!$page.find( ".ui-content >:eq(1)" ).hasClass( "ui-collapsible-collapsed" ), ".ui-collapsible-collapsed not added to expanded elements" ); ok($page.find( ".ui-collapsible.ui-collapsible-collapsed" ).find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top ui-corner-bottom" ), "Collapsible header button should have class ui-corner-all" ); start(); } ]); }); asyncTest( "Expand/Collapse", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-test" ); }, function() { ok($( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); $( "#basic-collapsible-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok(!$( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be expanded after click"); $( "#basic-collapsible-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok($( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); start(); } ]); }); module( "Collapsible set", {}); asyncTest( "The page should enhanced correctly", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { var $page = $( "#basic-collapsible-set-test" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible-set" ), ".ui-collapsible-set class added to collapsible set" ); ok($page.find( ".ui-content >:eq(0) > div" ).hasClass( "ui-collapsible" ), ".ui-collapsible class added to collapsible elements" ); $page.find( ".ui-collapsible-set" ).each(function() { var $this = $( this ); ok($this.find( ".ui-collapsible" ).first().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top" ), "First collapsible header button should have class ui-corner-top" ); ok($this.find( ".ui-collapsible" ).last().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-bottom" ), "Last collapsible header button should have class ui-corner-bottom" ); }); start(); } ]); }); asyncTest( "Collapsible set with only one collapsible", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-set-with-lonely-collapsible-test" ); }, function() { var $page = $( "#collapsible-set-with-lonely-collapsible-test" ); $page.find( ".ui-collapsible-set" ).each(function() { var $this = $( this ); ok($this.find( ".ui-collapsible" ).first().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top" ), "First collapsible header button should have class ui-corner-top" ); ok($this.find( ".ui-collapsible" ).last().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-bottom" ), "Last collapsible header button should have class ui-corner-bottom" ); }); start(); } ]); }); asyncTest( "Section expanded by default", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { equals($( "#basic-collapsible-set-test .ui-content >:eq(0) .ui-collapsible-collapsed" ).length, 2, "There should be 2 section collapsed" ); ok(!$( "#basic-collapsible-set-test .ui-content >:eq(0) >:eq(1)" ).hasClass( "ui-collapsible-collapsed" ), "Section B should be expanded" ); start(); } ]); }); asyncTest( "Expand/Collapse", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { ok($( "#basic-collapsible-set-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); $( "#basic-collapsible-set-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok(!$( "#basic-collapsible-set-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be expanded after click"); $( "#basic-collapsible-set-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok($( "#basic-collapsible-set-test .ui-collapsible" ).hasClass( "ui-collapsible-collapsed" ), "All collapsible should be collapsed"); start(); } ]); }); module( "Theming", {}); asyncTest( "Collapsible", 6, function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-with-theming" ); }, function() { var collapsibles = $.mobile.activePage.find( ".ui-collapsible" ); ok( collapsibles.eq(0).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-a" ), "Heading of first collapsible should have class ui-btn-up-a"); ok( !collapsibles.eq(0).find( ".ui-collapsible-content" ).hasClass( "ui-btn-up-a" ), "Content of first collapsible should NOT have class ui-btn-up-a"); ok( collapsibles.eq(1).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-b" ), "Heading of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(1).find( ".ui-collapsible-content" ).hasClass( "ui-body-b" ), "Content of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(2).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-c" ), "Heading of third collapsible should have class ui-btn-up-c"); ok( collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-body-c" ), "Content of third collapsible should have class ui-btn-up-c"); start(); } ]); }); asyncTest( "Collapsible Set", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-set-with-theming" ); }, function() { var collapsibles = $.mobile.activePage.find( ".ui-collapsible" ); ok( collapsibles.eq(0).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-a" ), "Heading of first collapsible should have class ui-btn-up-a"); ok( !collapsibles.eq(0).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of first collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(0).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of first collapsible should NOT have class ui-btn-up-d"); ok( collapsibles.eq(1).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-b" ), "Heading of second collapsible should have class ui-btn-up-b"); ok( !collapsibles.eq(1).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-c,.ui-body-d" ), "Content of second collapsible should NOT have class ui-btn-up-[a,c,d]"); ok( collapsibles.eq(1).find( ".ui-collapsible-content" ).hasClass( "ui-body-b" ), "Content of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(2).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-d" ), "Heading of third collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(2).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of third collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of third collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-collapsible-content-collapsed" ), "Content of third collapsible should NOT have class ui-collapsible-content-collapsed"); ok( collapsibles.eq(3).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-d" ), "Heading of fourth collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(3).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of fourth collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(3).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of fourth collapsible should have class ui-btn-up-d"); start(); } ]); }); })( jQuery );
JavaScript
// load testswarm agent (function() { var url = window.location.search; url = decodeURIComponent( url.slice( url.indexOf("swarmURL=") + 9 ) ); if ( !url || url.indexOf("http") !== 0 ) { return; } document.write("<scr" + "ipt src='http://swarm.jquery.org/js/inject.js?" + (new Date).getTime() + "'></scr" + "ipt>"); })();
JavaScript
/* * mobile media unit tests */ (function($){ var cssFn = $.fn.css, widthFn = $.fn.width; // make sure original definitions are reset module('jquery.mobile.media.js', { setup: function(){ $(document).trigger('mobileinit.htmlclass'); }, teardown: function(){ $.fn.css = cssFn; $.fn.width = widthFn; } }); test( "media query check returns true when the position is absolute", function(){ $.fn.css = function(){ return "absolute"; }; same($.mobile.media("screen 1"), true); }); test( "media query check returns false when the position is not absolute", function(){ $.fn.css = function(){ return "not absolute"; }; same($.mobile.media("screen 2"), false); }); test( "media query check is cached", function(){ $.fn.css = function(){ return "absolute"; }; same($.mobile.media("screen 3"), true); $.fn.css = function(){ return "not absolute"; }; same($.mobile.media("screen 3"), true); }); })(jQuery);
JavaScript
/* * mobile page unit tests */ (function($){ var libName = 'jquery.mobile.page.sections.js', themedefault = $.mobile.page.prototype.options.theme, keepNative = $.mobile.page.prototype.options.keepNative; module(libName, { setup: function() { $.mobile.page.prototype.options.keepNative = keepNative; } }); var eventStack = [], etargets = [], cEvents=[], cTargets=[]; $( document ).bind( "pagebeforecreate pagecreate", function( e ){ eventStack.push( e.type ); etargets.push( e.target ); }); $("#c").live( "pagebeforecreate", function( e ){ cEvents.push( e.type ); cTargets.push( e.target ); return false; }); test( "pagecreate event fires when page is created", function(){ ok( eventStack[0] === "pagecreate" || eventStack[1] === "pagecreate" ); }); test( "pagebeforecreate event fires when page is created", function(){ ok( eventStack[0] === "pagebeforecreate" || eventStack[1] === "pagebeforecreate" ); }); test( "pagebeforecreate fires before pagecreate", function(){ ok( eventStack[0] === "pagebeforecreate" ); }); test( "target of pagebeforecreate event was div #a", function(){ ok( $( etargets[0] ).is("#a") ); }); test( "target of pagecreate event was div #a" , function(){ ok( $( etargets[0] ).is("#a") ); }); test( "page element has ui-page class" , function(){ ok( $( "#a" ).hasClass( "ui-page" ) ); }); test( "page element has default body theme when not overidden" , function(){ ok( $( "#a" ).hasClass( "ui-body-" + themedefault ) ); }); test( "B page has non-default theme matching its data-theme attr" , function(){ $( "#b" ).page(); var btheme = $( "#b" ).jqmData( "theme" ); ok( $( "#b" ).hasClass( "ui-body-" + btheme ) ); }); test( "Binding to pagebeforecreate and returning false prevents pagecreate event from firing" , function(){ $("#c").page(); ok( cEvents[0] === "pagebeforecreate" ); ok( !cTargets[1] ); }); test( "Binding to pagebeforecreate and returning false prevents classes from being applied to page" , function(){ ok( !$( "#b" ).hasClass( "ui-body-" + themedefault ) ); ok( !$( "#b" ).hasClass( "ui-page" ) ); }); test( "keepNativeSelector returns the default where keepNative is not different", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = pageProto.options.keepNativeDefault; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); }); test( "keepNativeSelector returns the default where keepNative is empty, undefined, whitespace", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = ""; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); pageProto.options.keepNative = undefined; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); pageProto.options.keepNative = " "; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); }); test( "keepNativeSelector returns a selector joined with the default", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = "foo, bar"; same(pageProto.keepNativeSelector(), "foo, bar, " + pageProto.options.keepNativeDefault); }); })(jQuery);
JavaScript
$(function() { var Runner = function( ) { var self = this; $.extend( self, { frame: window.frames[ "testFrame" ], testTimeout: 3 * 60 * 1000, $frameElem: $( "#testFrame" ), assertionResultPrefix: "assertion result for test:", onTimeout: QUnit.start, onFrameLoad: function() { // establish a timeout for a given suite in case of async tests hanging self.testTimer = setTimeout( self.onTimeout, self.testTimeout ); // it might be a redirect with query params for push state // tests skip this call and expect another if( !self.frame.QUnit ) { self.$frameElem.one( "load", self.onFrameLoad ); return; } // when the QUnit object reports done in the iframe // run the onFrameDone method self.frame.QUnit.done = self.onFrameDone; self.frame.QUnit.testDone = self.onTestDone; }, onTestDone: function( result ) { QUnit.ok( !(result.failed > 0), result.name ); self.recordAssertions( result.total - result.failed, result.name ); }, onFrameDone: function( failed, passed, total, runtime ){ // make sure we don't time out the tests clearTimeout( self.testTimer ); // TODO decipher actual cause of multiple test results firing twice // clear the done call to prevent early completion of other test cases self.frame.QUnit.done = $.noop; self.frame.QUnit.testDone = $.noop; // hide the extra assertions made to propogate the count // to the suite level test self.hideAssertionResults(); // continue on to the next suite QUnit.start(); }, recordAssertions: function( count, parentTest ) { for( var i = 0; i < count; i++ ) { ok( true, self.assertionResultPrefix + parentTest ); } }, hideAssertionResults: function() { $( "li:not([id]):contains('" + self.assertionResultPrefix + "')" ).hide(); }, exec: function( data ) { var template = self.$frameElem.attr( "data-src" ); $.each( data.testPages, function(i, dir) { QUnit.asyncTest( dir, function() { self.dir = dir; self.$frameElem.one( "load", self.onFrameLoad ); self.$frameElem.attr( "src", template.replace("{{testdir}}", dir) ); }); }); // having defined all suite level tests let QUnit run QUnit.start(); } }); }; // prevent qunit from starting the test suite until all tests are defined QUnit.begin = function( ) { this.config.autostart = false; }; // get the test directories $.get( "ls.php", (new Runner()).exec ); });
JavaScript
/* * mobile init tests */ (function($){ test( "page element is generated when not present in initial markup", function(){ ok( $( ".ui-page" ).length, 1 ); }); })(jQuery);
JavaScript
/* * mobile init tests */ (function($){ var mobilePage = undefined, libName = 'jquery.mobile.init.js', coreLib = 'jquery.mobile.core.js', extendFn = $.extend, setGradeA = function(value) { $.mobile.gradeA = function(){ return value; }; }, reloadCoreNSandInit = function(){ $.testHelper.reloadLib(coreLib); $.testHelper.reloadLib("jquery.setNamespace.js"); $.testHelper.reloadLib(libName); }; module(libName, { setup: function(){ // NOTE reset for gradeA tests $('html').removeClass('ui-mobile'); // TODO add post reload callback $('.ui-loader').remove(); }, teardown: function(){ $.extend = extendFn; // NOTE reset for showPageLoadingMsg/hidePageLoadingMsg tests $('.ui-loader').remove(); // clear the classes added by reloading the init $("html").attr('class', ''); } }); // NOTE important to use $.fn.one here to make sure library reloads don't fire // the event before the test check below $(document).one("mobileinit", function(){ mobilePage = $.mobile.page; }); // NOTE for the following two tests see index html for the binding test( "mobile.page is available when mobile init is fired", function(){ ok( mobilePage !== undefined, "$.mobile.page is defined" ); }); $.testHelper.excludeFileProtocol(function(){ asyncTest( "loading the init library triggers mobilinit on the document", function(){ var initFired = false; expect( 1 ); $(window.document).one('mobileinit', function(event){ initFired = true; }); $.testHelper.reloadLib(libName); setTimeout(function(){ ok(initFired, "init fired"); start(); }, 1000); }); test( "enhancments are skipped when the browser is not grade A", function(){ setGradeA(false); $.testHelper.reloadLib(libName); //NOTE easiest way to check for enhancements, not the most obvious ok(!$("html").hasClass("ui-mobile"), "html elem doesn't have class ui-mobile"); }); test( "enhancments are added when the browser is grade A", function(){ setGradeA(true); $.testHelper.reloadLib(libName); ok($("html").hasClass("ui-mobile"), "html elem has class mobile"); }); asyncTest( "useFastClick is configurable via mobileinit", function(){ $(document).one( "mobileinit", function(){ $.mobile.useFastClick = false; start(); }); $.testHelper.reloadLib(libName); same( $.mobile.useFastClick, false , "fast click is set to false after init" ); $.mobile.useFastClick = true; }); var findFirstPage = function() { return $(":jqmData(role='page')").first(); }; test( "active page and start page should be set to the fist page in the selected set", function(){ expect( 2 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); same($.mobile.firstPage[0], firstPage[0]); same($.mobile.activePage[0], firstPage[0]); }); test( "mobile viewport class is defined on the first page's parent", function(){ expect( 1 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); ok(firstPage.parent().hasClass("ui-mobile-viewport"), "first page has viewport"); }); test( "mobile page container is the first page's parent", function(){ expect( 1 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); same($.mobile.pageContainer[0], firstPage.parent()[0]); }); asyncTest( "hashchange triggered on document ready with single argument: true", function(){ $.testHelper.sequence([ function(){ location.hash = "#foo"; }, // delay the bind until the first hashchange function(){ $(window).one("hashchange", function(ev, arg){ same(arg, true); start(); }); }, function(){ $.testHelper.reloadLib(libName); } ], 1000); }); test( "pages without a data-url attribute have it set to their id", function(){ same($("#foo").jqmData('url'), "foo"); }); test( "pages with a data-url attribute are left with the original value", function(){ same($("#bar").jqmData('url'), "bak"); }); asyncTest( "showPageLoadingMsg doesn't add the dialog to the page when loading message is false", function(){ expect( 1 ); $.mobile.loadingMessage = false; $.mobile.showPageLoadingMsg(); setTimeout(function(){ ok(!$(".ui-loader").length, "no ui-loader element"); start(); }, 500); }); asyncTest( "hidePageLoadingMsg doesn't add the dialog to the page when loading message is false", function(){ expect( 1 ); $.mobile.loadingMessage = true; $.mobile.hidePageLoadingMsg(); setTimeout(function(){ same($(".ui-loading").length, 0, "page should not be in the loading state"); start(); }, 500); }); asyncTest( "showPageLoadingMsg adds the dialog to the page when loadingMessage is true", function(){ expect( 1 ); $.mobile.loadingMessage = true; $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loading").length, 1, "page should be in the loading state"); start(); }, 500); }); asyncTest( "page loading should contain default loading message", function(){ expect( 1 ); reloadCoreNSandInit(); $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "loading"); start(); }, 500); }); asyncTest( "page loading should contain custom loading message", function(){ $.mobile.loadingMessage = "foo"; $.testHelper.reloadLib(libName); $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "foo"); start(); }, 500); }); asyncTest( "page loading should contain custom loading message when set during runtime", function(){ $.mobile.loadingMessage = "bar"; $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "bar"); start(); }, 500); }); // NOTE: the next two tests work on timeouts that assume a page will be created within 2 seconds // it'd be great to get these using a more reliable callback or event asyncTest( "page does auto-initialize at domready when autoinitialize option is true (default) ", function(){ $( "<div />", { "data-nstest-role": "page", "id": "autoinit-on" } ).prependTo( "body" ) $(document).one("mobileinit", function(){ $.mobile.autoInitializePage = true; }); location.hash = ""; reloadCoreNSandInit(); setTimeout(function(){ same( $( "#autoinit-on.ui-page" ).length, 1 ); start(); }, 2000); }); asyncTest( "page does not initialize at domready when autoinitialize option is false ", function(){ $(document).one("mobileinit", function(){ $.mobile.autoInitializePage = false; }); $( "<div />", { "data-nstest-role": "page", "id": "autoinit-off" } ).prependTo( "body" ) location.hash = ""; reloadCoreNSandInit(); setTimeout(function(){ same( $( "#autoinit-off.ui-page" ).length, 0 ); $(document).bind("mobileinit", function(){ $.mobile.autoInitializePage = true; }); reloadCoreNSandInit(); start(); }, 2000); }); }); })(jQuery);
JavaScript
/* * mobile dialog unit tests */ (function($) { module( "jquery.mobile.dialog.js", { setup: function() { $.mobile.page.prototype.options.contentTheme = "d"; } }); asyncTest( "dialog hash is added when the dialog is opened and removed when closed", function() { expect( 2 ); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#foo-dialog-link" ).click(); }, function() { var fooDialog = $( "#foo-dialog" ); // make sure the dialog came up ok( /&ui-state=dialog/.test(location.hash), "ui-state=dialog =~ location.hash", "dialog open" ); // close the dialog $( ".ui-dialog" ).dialog( "close" ); }, function() { ok( !/&ui-state=dialog/.test(location.hash), "ui-state=dialog !~ location.hash" ); start(); } ]); }); asyncTest( "dialog element with no theming", function() { expect(4); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-a" ).click(); }, function() { var dialog = $( "#dialog-a" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-c" ), "Expected explicit theme ui-body-c" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-" + $.mobile.page.prototype.options.contentTheme ), "Expect content to inherit from $.mobile.page.prototype.options.contentTheme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); asyncTest( "dialog element with data-theme", function() { // Reset fallback theme for content $.mobile.page.prototype.options.contentTheme = null; expect(5); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-b" ).click(); }, function() { var dialog = $( "#dialog-b" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-e" ), "Expected explicit theme ui-body-e" ); ok( !dialog.hasClass( "ui-overlay-b" ), "Expected no theme ui-overlay-b" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-e" ), "Expect content to inherit from data-theme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); asyncTest( "dialog element with data-theme & data-overlay-theme", function() { expect(5); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-c" ).click(); }, function() { var dialog = $( "#dialog-c" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-e" ), "Expected explicit theme ui-body-e" ); ok( dialog.hasClass( "ui-overlay-b" ), "Expected explicit theme ui-overlay-b" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-" + $.mobile.page.prototype.options.contentTheme ), "Expect content to inherit from $.mobile.page.prototype.options.contentTheme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); })( jQuery );
JavaScript
//set namespace for unit test markp $( document ).bind( "mobileinit", function(){ $.mobile.ns = "nstest-"; });
JavaScript
/* * mobile core unit tests */ (function($){ var libName = "jquery.mobile.core.js", setGradeA = function(value, version) { $.support.mediaquery = value; $.mobile.browser.ie = version; }, extendFn = $.extend; module(libName, { setup: function(){ // NOTE reset for gradeA tests $('html').removeClass('ui-mobile'); // NOTE reset for pageLoading tests $('.ui-loader').remove(); }, teardown: function(){ $.extend = extendFn; } }); $.testHelper.excludeFileProtocol(function(){ test( "grade A browser either supports media queries or is IE 7+", function(){ setGradeA(false, 6); $.testHelper.reloadLib(libName); ok(!$.mobile.gradeA()); setGradeA(true, 8); $.testHelper.reloadLib(libName); ok($.mobile.gradeA()); }); }); function clearNSNormalizeDictionary() { var dict = $.mobile.nsNormalizeDict; for ( var prop in dict ) { delete dict[ prop ]; } } test( "$.mobile.nsNormalize works properly with namespace defined (test default)", function(){ // Start with a fresh namespace property cache, just in case // the previous test mucked with namespaces. clearNSNormalizeDictionary(); equal($.mobile.nsNormalize("foo"), "nstestFoo", "appends ns and initcaps"); equal($.mobile.nsNormalize("fooBar"), "nstestFooBar", "leaves capped strings intact"); equal($.mobile.nsNormalize("foo-bar"), "nstestFooBar", "changes dashed strings"); equal($.mobile.nsNormalize("foo-bar-bak"), "nstestFooBarBak", "changes multiple dashed strings"); // Reset the namespace property cache for the next test. clearNSNormalizeDictionary(); }); test( "$.mobile.nsNormalize works properly with an empty namespace", function(){ var realNs = $.mobile.ns; $.mobile.ns = ""; // Start with a fresh namespace property cache, just in case // the previous test mucked with namespaces. clearNSNormalizeDictionary(); equal($.mobile.nsNormalize("foo"), "foo", "leaves uncapped and undashed"); equal($.mobile.nsNormalize("fooBar"), "fooBar", "leaves capped strings intact"); equal($.mobile.nsNormalize("foo-bar"), "fooBar", "changes dashed strings"); equal($.mobile.nsNormalize("foo-bar-bak"), "fooBarBak", "changes multiple dashed strings"); $.mobile.ns = realNs; // Reset the namespace property cache for the next test. clearNSNormalizeDictionary(); }); //data tests test( "$.fn.jqmData and $.fn.jqmRemoveData methods are working properly", function(){ var data; same( $("body").jqmData("foo", true), $("body"), "setting data returns the element" ); same( $("body").jqmData("foo"), true, "getting data returns the right value" ); same( $("body").data($.mobile.nsNormalize("foo")), true, "data was set using namespace" ); same( $("body").jqmData("foo", undefined), true, "getting data still returns the value if there's an undefined second arg" ); data = $.extend( {}, $("body").data() ); delete data[ $.expando ]; //discard the expando for that test same( data , { "nstestFoo": true }, "passing .data() no arguments returns a hash with all set properties" ); same( $("body").jqmData(), undefined, "passing no arguments returns undefined" ); same( $("body").jqmData(undefined), undefined, "passing a single undefined argument returns undefined" ); same( $("body").jqmData(undefined, undefined), undefined, "passing 2 undefined arguments returns undefined" ); same( $("body").jqmRemoveData("foo"), $("body"), "jqmRemoveData returns the element" ); same( $("body").jqmData("foo"), undefined, "jqmRemoveData properly removes namespaced data" ); }); test( "$.jqmData and $.jqmRemoveData methods are working properly", function(){ same( $.jqmData(document.body, "foo", true), true, "setting data returns the value" ); same( $.jqmData(document.body, "foo"), true, "getting data returns the right value" ); same( $.data(document.body, $.mobile.nsNormalize("foo")), true, "data was set using namespace" ); same( $.jqmData(document.body, "foo", undefined), true, "getting data still returns the value if there's an undefined second arg" ); same( $.jqmData(document.body), undefined, "passing no arguments returns undefined" ); same( $.jqmData(document.body, undefined), undefined, "passing a single undefined argument returns undefined" ); same( $.jqmData(document.body, undefined, undefined), undefined, "passing 2 undefined arguments returns undefined" ); same( $.jqmRemoveData(document.body, "foo"), undefined, "jqmRemoveData returns the undefined value" ); same( $("body").jqmData("foo"), undefined, "jqmRemoveData properly removes namespaced data" ); }); test( "addDependents works properly", function() { same( $("#parent").jqmData('dependents'), undefined ); $( "#parent" ).addDependents( $("#dependent") ); same( $("#parent").jqmData('dependents').length, 1 ); }); test( "removeWithDependents removes the parent element and ", function(){ $( "#parent" ).addDependents( $("#dependent") ); same($( "#parent, #dependent" ).length, 2); $( "#parent" ).removeWithDependents(); same($( "#parent, #dependent" ).length, 0); }); test( "$.fn.getEncodedText should return the encoded value where $.fn.text doesn't", function() { same( $("#encoded").text(), "foo>"); same( $("#encoded").getEncodedText(), "foo&gt;"); same( $("#unencoded").getEncodedText(), "foo"); }); })(jQuery);
JavaScript
/* * mobile core unit tests */ (function($){ var libName = "jquery.mobile.core.js", scrollTimeout = 20, // TODO expose timing as an attribute scrollStartEnabledTimeout = 150; module(libName, { setup: function(){ $("<div id='scroll-testing' style='height: 1000px'></div>").appendTo("body"); }, teardown: function(){ $("#scroll-testing").remove(); } }); var scrollUp = function( pos ){ $(window).scrollTop(1000); ok($(window).scrollTop() > 0, $(window).scrollTop()); $.mobile.silentScroll(pos); }; asyncTest( "silent scroll scrolls the page to the top by default", function(){ scrollUp(); setTimeout(function(){ same($(window).scrollTop(), 0); start(); }, scrollTimeout); }); asyncTest( "silent scroll scrolls the page to the passed y position", function(){ var pos = 10; scrollUp(pos); setTimeout(function(){ same($(window).scrollTop(), pos); start(); }, scrollTimeout); }); test( "silent scroll is async", function(){ scrollUp(); ok($(window).scrollTop() != 0, "scrolltop position should not be zero"); start(); }); asyncTest( "scrolling marks scrollstart as disabled for 150 ms", function(){ $.event.special.scrollstart.enabled = true; scrollUp(); ok(!$.event.special.scrollstart.enabled); setTimeout(function(){ ok($.event.special.scrollstart.enabled); start(); }, scrollStartEnabledTimeout); }); //TODO test that silentScroll is called on window load })(jQuery);
JavaScript
/* * mobile support unit tests */ $.testHelper.excludeFileProtocol(function(){ var prependToFn = $.fn.prependTo, libName = "jquery.mobile.support.js"; module(libName, { teardown: function(){ //NOTE undo any mocking $.fn.prependTo = prependToFn; } }); // NOTE following two tests have debatable value as they only // prevent property name changes and improper attribute checks test( "detects functionality from basic affirmative properties and attributes", function(){ // TODO expose properties for less brittle tests $.extend(window, { WebKitTransitionEvent: true, orientation: true, onorientationchange: true }); document.ontouchend = true; window.history.pushState = function(){}; window.history.replaceState = function(){}; $.mobile.media = function(){ return true; }; $.testHelper.reloadLib(libName); ok($.support.orientation); ok($.support.touch); ok($.support.cssTransitions); ok($.support.pushState); ok($.support.mediaquery); }); test( "detects functionality from basic negative properties and attributes (where possible)", function(){ delete window["orientation"]; delete document["ontouchend"]; $.testHelper.reloadLib(libName); ok(!$.support.orientation); ok(!$.support.touch); }); // NOTE mocks prependTo to simulate base href updates or lack thereof var mockBaseCheck = function( url ){ var prependToFn = $.fn.prependTo; $.fn.prependTo = function( selector ){ var result = prependToFn.call(this, selector); if(this[0].href && this[0].href.indexOf("testurl") != -1) result = [{href: url}]; return result; }; }; test( "detects dynamic base tag when new base element added and base href updates", function(){ mockBaseCheck(location.protocol + '//' + location.host + location.pathname + "ui-dir/"); $.testHelper.reloadLib(libName); ok($.support.dynamicBaseTag); }); test( "detects no dynamic base tag when new base element added and base href unchanged", function(){ mockBaseCheck('testurl'); $.testHelper.reloadLib(libName); ok(!$.support.dynamicBaseTag); }); test( "jQM's IE browser check properly detects IE versions", function(){ $.testHelper.reloadLib(libName); //here we're just comparing our version to what the conditional compilation finds var ie = !!$.browser.msie, //get a boolean version = parseInt( $.browser.version, 10), jqmdetectedver = $.mobile.browser.ie; if( ie ){ same(version, jqmdetectedver, "It's IE and the version is correct"); } else{ same(ie, jqmdetectedver, "It's not IE"); } }); //TODO propExists testing, refactor propExists into mockable method //TODO scrollTop testing, refactor scrollTop logic into mockable method });
JavaScript
/* * mobile navigation unit tests */ (function($){ var siteDirectory = location.pathname.replace(/[^/]+$/, ""); module('jquery.mobile.navigation.js', { setup: function(){ if ( location.hash ) { stop(); $(document).one("pagechange", function() { start(); } ); location.hash = ""; } } }); test( "path.get method is working properly", function(){ window.location.hash = "foo"; same($.mobile.path.get(), "foo", "get method returns location.hash minus hash character"); same($.mobile.path.get( "#foo/bar/baz.html" ), "foo/bar/", "get method with hash arg returns path with no filename or hash prefix"); same($.mobile.path.get( "#foo/bar/baz.html/" ), "foo/bar/baz.html/", "last segment of hash is retained if followed by a trailing slash"); }); test( "path.isPath method is working properly", function(){ ok(!$.mobile.path.isPath('bar'), "anything without a slash is not a path"); ok($.mobile.path.isPath('bar/'), "anything with a slash is a path"); ok($.mobile.path.isPath('/bar'), "anything with a slash is a path"); ok($.mobile.path.isPath('a/r'), "anything with a slash is a path"); ok($.mobile.path.isPath('/'), "anything with a slash is a path"); }); test( "path.getFilePath method is working properly", function(){ same($.mobile.path.getFilePath("foo.html" + "&" + $.mobile.subPageUrlKey ), "foo.html", "returns path without sub page key"); }); test( "path.set method is working properly", function(){ $.mobile.urlHistory.ignoreNextHashChange = false; $.mobile.path.set("foo"); same("foo", window.location.hash.replace(/^#/,""), "sets location.hash properly"); }); test( "path.makeUrlAbsolute is working properly", function(){ var mua = $.mobile.path.makeUrlAbsolute, p1 = "http://jqm.com/", p2 = "http://jqm.com/?foo=1&bar=2", p3 = "http://jqm.com/#spaz", p4 = "http://jqm.com/?foo=1&bar=2#spaz", p5 = "http://jqm.com/test.php", p6 = "http://jqm.com/test.php?foo=1&bar=2", p7 = "http://jqm.com/test.php#spaz", p8 = "http://jqm.com/test.php?foo=1&bar=2#spaz", p9 = "http://jqm.com/dir1/dir2/", p10 = "http://jqm.com/dir1/dir2/?foo=1&bar=2", p11 = "http://jqm.com/dir1/dir2/#spaz", p12 = "http://jqm.com/dir1/dir2/?foo=1&bar=2#spaz", p13 = "http://jqm.com/dir1/dir2/test.php", p14 = "http://jqm.com/dir1/dir2/test.php?foo=1&bar=2", p15 = "http://jqm.com/dir1/dir2/test.php#spaz", p16 = "http://jqm.com/dir1/dir2/test.php?foo=1&bar=2#spaz"; // Test URL conversion against an absolute URL to the site root. // directory tests same( mua( "http://jqm.com/", p1 ), "http://jqm.com/", "absolute root - absolute root" ); same( mua( "//jqm.com/", p1 ), "http://jqm.com/", "protocol relative root - absolute root" ); same( mua( "/", p1 ), "http://jqm.com/", "site relative root - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "absolute root with query - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "protocol relative root with query - absolute root" ); same( mua( "/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "site relative root with query - absolute root" ); same( mua( "?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "query relative - absolute root" ); same( mua( "http://jqm.com/#spaz", p1 ), "http://jqm.com/#spaz", "absolute root with fragment - absolute root" ); same( mua( "//jqm.com/#spaz", p1 ), "http://jqm.com/#spaz", "protocol relative root with fragment - absolute root" ); same( mua( "/#spaz", p1 ), "http://jqm.com/#spaz", "site relative root with fragment - absolute root" ); same( mua( "#spaz", p1 ), "http://jqm.com/#spaz", "fragment relative - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "absolute root with query and fragment - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "protocol relative root with query and fragment - absolute root" ); same( mua( "/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "site relative root with query and fragment - absolute root" ); same( mua( "?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "query relative and fragment - absolute root" ); // file tests same( mua( "http://jqm.com/test.php", p1 ), "http://jqm.com/test.php", "absolute file at root - absolute root" ); same( mua( "//jqm.com/test.php", p1 ), "http://jqm.com/test.php", "protocol relative file at root - absolute root" ); same( mua( "/test.php", p1 ), "http://jqm.com/test.php", "site relative file at root - absolute root" ); same( mua( "test.php", p1 ), "http://jqm.com/test.php", "document relative file at root - absolute root" ); same( mua( "http://jqm.com/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "absolute file at root with query - absolute root" ); same( mua( "//jqm.com/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "protocol relative file at root with query - absolute root" ); same( mua( "/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "site relative file at root with query - absolute root" ); same( mua( "test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "document relative file at root with query - absolute root" ); same( mua( "http://jqm.com/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "absolute file at root with fragment - absolute root" ); same( mua( "//jqm.com/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "protocol relative file at root with fragment - absolute root" ); same( mua( "/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "site relative file at root with fragment - absolute root" ); same( mua( "test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "file at root with fragment - absolute root" ); same( mua( "http://jqm.com/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "absolute file at root with query and fragment - absolute root" ); same( mua( "//jqm.com/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "protocol relative file at root with query and fragment - absolute root" ); same( mua( "/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "site relative file at root with query and fragment - absolute root" ); same( mua( "test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "query relative file at root fragment - absolute root" ); // Test URL conversion against an absolute URL to a file at the site root. same( mua( "http://jqm.com/", p5 ), "http://jqm.com/", "absolute root - absolute root" ); same( mua( "//jqm.com/", p5 ), "http://jqm.com/", "protocol relative root - absolute root" ); same( mua( "/", p5 ), "http://jqm.com/", "site relative root - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "absolute root with query - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "protocol relative root with query - absolute root" ); same( mua( "/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "site relative root with query - absolute root" ); same( mua( "?foo=1&bar=2", p5 ), "http://jqm.com/test.php?foo=1&bar=2", "query relative - absolute root" ); same( mua( "http://jqm.com/#spaz", p5 ), "http://jqm.com/#spaz", "absolute root with fragment - absolute root" ); same( mua( "//jqm.com/#spaz", p5 ), "http://jqm.com/#spaz", "protocol relative root with fragment - absolute root" ); same( mua( "/#spaz", p5 ), "http://jqm.com/#spaz", "site relative root with fragment - absolute root" ); same( mua( "#spaz", p5 ), "http://jqm.com/test.php#spaz", "fragment relative - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "absolute root with query and fragment - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "protocol relative root with query and fragment - absolute root" ); same( mua( "/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "site relative root with query and fragment - absolute root" ); same( mua( "?foo=1&bar=2#spaz", p5 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "query relative and fragment - absolute root" ); }); // https://github.com/jquery/jquery-mobile/issues/2362 test( "ipv6 host support", function(){ // http://www.ietf.org/rfc/rfc2732.txt ipv6 examples for tests // most definitely not comprehensive var ipv6_1 = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html", ipv6_2 = "http://[1080:0:0:0:8:800:200C:417A]/index.html", ipv6_3 = "http://[3ffe:2a00:100:7031::1]", ipv6_4 = "http://[1080::8:800:200C:417A]/foo", ipv6_5 = "http://[::192.9.5.5]/ipng", ipv6_6 = "http://[::FFFF:129.144.52.38]:80/index.html", ipv6_7 = "http://[2010:836B:4179::836B:4179]", fromIssue = "http://[3fff:cafe:babe::]:443/foo"; same( $.mobile.path.parseUrl(ipv6_1).host, "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80"); same( $.mobile.path.parseUrl(ipv6_1).hostname, "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]"); same( $.mobile.path.parseUrl(ipv6_2).host, "[1080:0:0:0:8:800:200C:417A]"); same( $.mobile.path.parseUrl(ipv6_3).host, "[3ffe:2a00:100:7031::1]"); same( $.mobile.path.parseUrl(ipv6_4).host, "[1080::8:800:200C:417A]"); same( $.mobile.path.parseUrl(ipv6_5).host, "[::192.9.5.5]"); same( $.mobile.path.parseUrl(ipv6_6).host, "[::FFFF:129.144.52.38]:80"); same( $.mobile.path.parseUrl(ipv6_6).hostname, "[::FFFF:129.144.52.38]"); same( $.mobile.path.parseUrl(ipv6_7).host, "[2010:836B:4179::836B:4179]"); same( $.mobile.path.parseUrl(fromIssue).host, "[3fff:cafe:babe::]:443"); same( $.mobile.path.parseUrl(fromIssue).hostname, "[3fff:cafe:babe::]"); }); test( "path.clean is working properly", function(){ var localroot = location.protocol + "//" + location.host + location.pathname, remoteroot = "http://google.com/", fakepath = "#foo/bar/baz.html", pathWithParam = localroot + "bar?baz=" + localroot, localpath = localroot + fakepath, remotepath = remoteroot + fakepath; same( $.mobile.path.clean( localpath ), location.pathname + fakepath, "removes location protocol, host, and portfrom same-domain path"); same( $.mobile.path.clean( remotepath ), remotepath, "does nothing to an external domain path"); same( $.mobile.path.clean( pathWithParam ), location.pathname + "bar?baz=" + localroot, "doesn't remove params with localroot value"); }); test( "path.stripHash is working properly", function(){ same( $.mobile.path.stripHash( "#bar" ), "bar", "returns a hash without the # prefix"); }); test( "path.hasProtocol is working properly", function(){ same( $.mobile.path.hasProtocol( "tel:5559999" ), true, "value in tel protocol format has protocol" ); same( $.mobile.path.hasProtocol( location.href ), true, "location href has protocol" ); same( $.mobile.path.hasProtocol( "foo/bar/baz.html" ), false, "simple directory path has no protocol" ); same( $.mobile.path.hasProtocol( "file://foo/bar/baz.html" ), true, "simple directory path with file:// has protocol" ); }); test( "path.isRelativeUrl is working properly", function(){ same( $.mobile.path.isRelativeUrl("http://company.com/"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("http://company.com/test.php"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/test.php"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/test.php"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("test.php"), true, "document relative url is relative" ); same( $.mobile.path.isRelativeUrl("http://company.com/dir1/dir2/test.php?foo=1&bar=2#frag"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/dir1/dir2/test.php?foo=1&bar=2#frag"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/dir1/dir2/test.php?foo=1&bar=2#frag"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("dir1/dir2/test.php?foo=1&bar=2#frag"), true, "document relative path url is relative" ); same( $.mobile.path.isRelativeUrl("test.php?foo=1&bar=2#frag"), true, "document relative file url is relative" ); same( $.mobile.path.isRelativeUrl("?foo=1&bar=2#frag"), true, "query relative url is relative" ); same( $.mobile.path.isRelativeUrl("#frag"), true, "fragments are relative" ); }); test( "path.isExternal is working properly", function(){ same( $.mobile.path.isExternal( location.href ), false, "same domain is not external" ); same( $.mobile.path.isExternal( "http://example.com" ), true, "example.com is external" ); same($.mobile.path.isExternal("mailto:"), true, "mailto protocol"); same($.mobile.path.isExternal("http://foo.com"), true, "http protocol"); same($.mobile.path.isExternal("http://www.foo.com"), true, "http protocol with www"); same($.mobile.path.isExternal("tel:16178675309"), true, "tel protocol"); same($.mobile.path.isExternal("foo.html"), false, "filename"); same($.mobile.path.isExternal("foo/foo/foo.html"), false, "file path"); same($.mobile.path.isExternal("../../index.html"), false, "relative parent path"); same($.mobile.path.isExternal("/foo"), false, "root-relative path"); same($.mobile.path.isExternal("foo"), false, "simple string"); same($.mobile.path.isExternal("#foo"), false, "local id reference"); }); test( "path.cleanHash", function(){ same( $.mobile.path.cleanHash( "#anything/atall?akjfdjjf" ), "anything/atall", "removes query param"); same( $.mobile.path.cleanHash( "#nothing/atall" ), "nothing/atall", "removes query param"); }); })(jQuery);
JavaScript
/* * mobile navigation path unit tests */ (function($){ var url = $.mobile.path.parseUrl( location.href ), home = location.href.replace( url.domain, "" ); var testPageLoad = function(testPageAnchorSelector, expectedTextValue){ expect( 2 ); $.testHelper.pageSequence([ function(){ // reset before each test, all tests expect original page // for relative urls $.testHelper.openPage( "#" + home); }, // open our test page function(){ $.testHelper.openPage("#pathing-tests"); }, // navigate to the linked page function(){ var page = $.mobile.activePage; // check that the reset page isn't still open equal("", page.find(".reset-value").text()); //click he test page link to execute the path page.find("a" + testPageAnchorSelector).click(); }, // verify that the page has changed and the expected text value is present function(){ same($.mobile.activePage.find(".test-value").text(), expectedTextValue); start(); } ]); }; // all of these alterations assume location.pathname will be a directory // this is required to prevent the tests breaking in a subdirectory // TODO could potentially be fragile since the tests could be running while // the urls are being updated $(function(){ $("a.site-rel").each(function(i, elem){ var $elem = $(elem); $elem.attr("href", location.pathname + $(elem).attr("href")); }); $('a.protocol-rel').each(function(i, elem){ var $elem = $(elem); $elem.attr("href", "//" + location.host + location.pathname + $(elem).attr("href")); }); $('a.absolute').each(function(i, elem){ var $elem = $(elem); $elem.attr("href", location.protocol + "//" + location.host + location.pathname + $(elem).attr("href")); }); }); //Doc relative tests module("document relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#doc-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#doc-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#doc-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#doc-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#doc-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#doc-rel-test-six", "doc rel test six"); }); // Site relative tests // NOTE does not test root path or non nested references module("site relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#site-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#site-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#site-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#site-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#site-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#site-rel-test-six", "doc rel test six"); }); // Protocol relative tests // NOTE does not test root path or non nested references module("protocol relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#protocol-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#protocol-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#protocol-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#protocol-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#protocol-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#protocol-rel-test-six", "doc rel test six"); }); // absolute tests // NOTE does not test root path or non nested references module("abolute paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#absolute-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#absolute-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#absolute-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#absolute-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#absolute-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#absolute-test-six", "doc rel test six"); }); })(jQuery);
JavaScript
(function($) { asyncTest( "dialog ui-state should be part of the hash", function(){ $.testHelper.sequence([ function() { // open the test page $.mobile.activePage.find( "a" ).click(); }, function() { // verify that the hash contains the dialogHashKey ok( location.hash.search($.mobile.dialogHashKey) >= 0 ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile navigation base tag unit tests */ (function($){ var baseDir = $.mobile.path.parseUrl($("base").attr("href")).directory, contentDir = $.mobile.path.makePathAbsolute("../content/", baseDir); module('jquery.mobile.navigation.js - base tag', { setup: function(){ if ( location.hash ) { stop(); $(document).one("pagechange", function() { start(); } ); location.hash = ""; } } }); asyncTest( "can navigate between internal and external pages", function(){ $.testHelper.pageSequence([ function(){ // Navigate from default internal page to another internal page. $.testHelper.openPage( "#internal-page-2" ); }, function(){ // Verify that we are on the 2nd internal page. $.testHelper.assertUrlLocation({ push: location.pathname + "#internal-page-2", hash: "internal-page-2", report: "navigate to internal page" }); // Navigate to a page that is in the base directory. Note that the application // document and this new page are *NOT* in the same directory. $("#internal-page-2 .bp1").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-1.html", report: "navigate from internal page to page in base directory" }); // Navigate to another page in the same directory as the current page. $("#base-page-1 .bp2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-2.html", report: "navigate from base directory page to another base directory page" }); // Navigate to another page in a directory that is the sibling of the base. $("#base-page-2 .cp1").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "navigate from base directory page to a page in a different directory hierarchy" }); // Navigate to another page in a directory that is the sibling of the base. $("#content-page-1 .cp2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-2.html", report: "navigate to another page within the same non-base directory hierarchy" }); // Navigate to an internal page. $("#content-page-2 .ip1").click(); }, function(){ // Verify that we are on the expected page. // the hash based nav result (hash:) is dictate by the fact that #internal-page-1 // is the original root page element $.testHelper.assertUrlLocation({ hashOrPush: location.pathname + location.search, report: "navigate from a page in a non-base directory to an internal page" }); // Try calling changePage() directly with a relative path. $.mobile.changePage("base-page-1.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-1.html", report: "call changePage() with a filename (no path)" }); // Try calling changePage() directly with a relative path. $.mobile.changePage("../content/content-page-1.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "call changePage() with a relative path containing up-level references" }); // Try calling changePage() with an id $.mobile.changePage("content-page-2.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-2.html", report: "call changePage() with a relative path should resolve relative to current page" }); // test that an internal page works $("a.ip2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hash: "internal-page-2", push: location.pathname + "#internal-page-2", report: "call changePage() with a page id" }); // Try calling changePage() with an id $.mobile.changePage("internal-page-1"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hash: "internal-page-2", push: location.pathname + "#internal-page-2", report: "calling changePage() with a page id that is not prefixed with '#' should not change page" }); // Previous load should have failed and left us on internal-page-2. start(); } ]); }); asyncTest( "internal form with no action submits to document URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage( "#internal-no-action-form-page" ); }, function(){ $( "#internal-no-action-form-page form" ).eq( 0 ).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: location.pathname + "?foo=1&bar=2", report: "hash should match document url and not base url" }); start(); } ]); }); asyncTest( "external page form with no action submits to external page URL", function(){ $.testHelper.pageSequence([ function(){ // Go to an external page that has a form. $("#internal-page-1 .cp1").click(); }, function(){ // Make sure we actually navigated to the external page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "should be on content-page-1.html" }); // Now submit the form in the external page. $("#content-page-1 form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html?foo=1&bar=2", report: "hash should match page url and not document url" }); start(); }]); }); })(jQuery);
JavaScript
/* * mobile navigation unit tests */ (function($){ // TODO move siteDirectory over to the nav path helper var changePageFn = $.mobile.changePage, originalTitle = document.title, originalLinkBinding = $.mobile.linkBindingEnabled, siteDirectory = location.pathname.replace( /[^/]+$/, "" ), home = $.mobile.path.parseUrl(location.pathname).directory, navigateTestRoot = function(){ $.testHelper.openPage( "#" + location.pathname + location.search ); }; module('jquery.mobile.navigation.js', { setup: function(){ $.mobile.changePage = changePageFn; document.title = originalTitle; var pageReset = function( hash ) { hash = hash || ""; stop(); $(document).one( "pagechange", function() { start(); }); location.hash = "#" + hash; }; // force the page reset for hash based tests if ( location.hash && !$.support.pushState ) { pageReset(); } // force the page reset for all pushstate tests if ( $.support.pushState ) { pageReset( home ); } $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; $.Event.prototype.which = undefined; $.mobile.linkBindingEnabled = originalLinkBinding; } }); asyncTest( "window.history.back() from external to internal page", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ ok( $.mobile.activePage[0] === $( "#active-state-page1" )[ 0 ], "successful navigation to internal page." ); //location.hash = siteDirectory + "external.html"; $.mobile.changePage("external.html"); }, function(){ ok( $.mobile.activePage[0] !== $( "#active-state-page1" )[ 0 ], "successful navigation to external page." ); window.history.back(); }, function(){ ok( $.mobile.activePage[0] === $( "#active-state-page1" )[ 0 ], "successful navigation back to internal page." ); start(); } ]); }); asyncTest( "external page is removed from the DOM after pagehide", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external-test is *NOT* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 0 ); start(); } ]); }); asyncTest( "preventDefault on pageremove event can prevent external page from being removed from the DOM", function(){ var preventRemoval = true, removeCallback = function( e ) { if ( preventRemoval ) { e.preventDefault(); } }; $( document ).bind( "pageremove", removeCallback ); $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external-test *IS* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 1 ); // Switch back to the page again! $.mobile.changePage( "external.html" ); }, // page is still present and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); // Now turn off our removal prevention. preventRemoval = false; window.history.back(); }, // external-test is *NOT* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 0 ); $( document ).unbind( "pageremove", removeCallback ); start(); } ]); }); asyncTest( "external page is cached in the DOM after pagehide", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "cached-external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test-cached" ).length, 1 ); window.history.back(); }, // external test page is cached in the dom after transitioning away function(){ same( $( "#external-test-cached" ).length, 1 ); start(); } ]); }); asyncTest( "external page is cached in the DOM after pagehide when option is set globally", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.page.prototype.options.domCache = true; $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external test page is cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 1 ); $.mobile.page.prototype.options.domCache = false; $( "#external-test" ).remove(); start(); }]); }); asyncTest( "page last scroll distance is remembered while navigating to and from pages", function(){ $.testHelper.pageSequence([ function(){ $( "body" ).height( $( window ).height() + 500 ); $.mobile.changePage( "external.html" ); }, function(){ // wait for the initial scroll to 0 setTimeout( function() { window.scrollTo( 0, 300 ); same( $(window).scrollTop(), 300, "scrollTop is 300 after setting it" ); }, 300); // wait for the scrollstop to fire and for the scroll to be // recorded 100 ms afterward (see changes made to handle hash // scrolling in some browsers) setTimeout( navigateTestRoot, 500 ); }, function(){ history.back(); }, function(){ // Give the silentScroll function some time to kick in. setTimeout(function() { same( $(window).scrollTop(), 300, "scrollTop is 300 after returning to the page" ); $( "body" ).height( "" ); start(); }, 300 ); } ]); }); asyncTest( "forms with data attribute ajax set to false will not call changePage", function(){ var called = false; var newChangePage = function(){ called = true; }; $.testHelper.sequence([ // avoid initial page load triggering changePage early function(){ $.mobile.changePage = newChangePage; $('#non-ajax-form').one('submit', function(event){ ok(true, 'submit callbacks are fired'); event.preventDefault(); }).submit(); }, function(){ ok(!called, "change page should not be called"); start(); }], 1000); }); asyncTest( "forms with data attribute ajax not set or set to anything but false will call changePage", function(){ var called = 0, newChangePage = function(){ called++; }; $.testHelper.sequence([ // avoid initial page load triggering changePage early function(){ $.mobile.changePage = newChangePage; $('#ajax-form, #rand-ajax-form').submit(); }, function(){ ok(called >= 2, "change page should be called at least twice"); start(); }], 300); }); asyncTest( "anchors with no href attribute will do nothing when clicked", function(){ var fired = false; $(window).bind("hashchange.temp", function(){ fired = true; }); $( "<a>test</a>" ).appendTo( $.mobile.firstPage ).click(); setTimeout(function(){ same(fired, false, "hash shouldn't change after click"); $(window).unbind("hashchange.temp"); start(); }, 500); }); test( "urlHistory is working properly", function(){ //urlHistory same( $.type( $.mobile.urlHistory.stack ), "array", "urlHistory.stack is an array" ); //preload the stack $.mobile.urlHistory.stack[0] = { url: "foo", transition: "bar" }; $.mobile.urlHistory.stack[1] = { url: "baz", transition: "shizam" }; $.mobile.urlHistory.stack[2] = { url: "shizoo", transition: "shizaah" }; //active index same( $.mobile.urlHistory.activeIndex , 0, "urlHistory.activeIndex is 0" ); //getActive same( $.type( $.mobile.urlHistory.getActive() ) , "object", "active item is an object" ); same( $.mobile.urlHistory.getActive().url , "foo", "active item has url foo" ); same( $.mobile.urlHistory.getActive().transition , "bar", "active item has transition bar" ); //get prev / next same( $.mobile.urlHistory.getPrev(), undefined, "urlHistory.getPrev() is undefined when active index is 0" ); $.mobile.urlHistory.activeIndex = 1; same( $.mobile.urlHistory.getPrev().url, "foo", "urlHistory.getPrev() has url foo when active index is 1" ); $.mobile.urlHistory.activeIndex = 0; same( $.mobile.urlHistory.getNext().url, "baz", "urlHistory.getNext() has url baz when active index is 0" ); //add new $.mobile.urlHistory.activeIndex = 2; $.mobile.urlHistory.addNew("test"); same( $.mobile.urlHistory.stack.length, 4, "urlHistory.addNew() adds an item after the active index" ); same( $.mobile.urlHistory.activeIndex, 3, "urlHistory.addNew() moves the activeIndex to the newly added item" ); //clearForward $.mobile.urlHistory.activeIndex = 0; $.mobile.urlHistory.clearForward(); same( $.mobile.urlHistory.stack.length, 1, "urlHistory.clearForward() clears the url stack after the active index" ); }); //url listening function testListening( prop ){ var stillListening = false; $(document).bind("pagebeforehide", function(){ stillListening = true; }); location.hash = "foozball"; setTimeout(function(){ ok( prop == stillListening, prop + " = false disables default hashchange event handler"); location.hash = ""; prop = true; start(); }, 1000); } asyncTest( "ability to disable our hash change event listening internally", function(){ testListening( ! $.mobile.urlHistory.ignoreNextHashChange ); }); asyncTest( "ability to disable our hash change event listening globally", function(){ testListening( $.mobile.hashListeningEnabled ); }); var testDataUrlHash = function( linkSelector, matches ) { $.testHelper.pageSequence([ function(){ window.location.hash = ""; }, function(){ $(linkSelector).click(); }, function(){ $.testHelper.assertUrlLocation( $.extend(matches, { report: "url or hash should match" }) ); start(); } ]); stop(); }; test( "when loading a page where data-url is not defined on a sub element hash defaults to the url", function(){ testDataUrlHash( "#non-data-url a", {hashOrPush: siteDirectory + "data-url-tests/non-data-url.html"} ); }); test( "data url works for nested paths", function(){ var url = "foo/bar.html"; testDataUrlHash( "#nested-data-url a", {hash: url, push: home + url} ); }); test( "data url works for single quoted paths and roles", function(){ var url = "foo/bar/single.html"; testDataUrlHash( "#single-quotes-data-url a", {hash: url, push: home + url} ); }); test( "data url works when role and url are reversed on the page element", function(){ var url = "foo/bar/reverse.html"; testDataUrlHash( "#reverse-attr-data-url a", {hash: url, push: home + url} ); }); asyncTest( "last entry choosen amongst multiple identical url history stack entries on hash change", function(){ // make sure the stack is clear after initial page load an any other delayed page loads // TODO better browser state management $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#dup-history-first"); }, function(){ $("#dup-history-first a").click(); }, function(){ $("#dup-history-second a:first").click(); }, function(){ $("#dup-history-first a").click(); }, function(){ $("#dup-history-second a:last").click(); }, function(){ $("#dup-history-dialog a:contains('Close')").click(); }, function(){ // fourth page (third index) in the stack to account for first page being hash manipulation, // the third page is dup-history-second which has two entries in history // the test is to make sure the index isn't 1 in this case, or the first entry for dup-history-second same($.mobile.urlHistory.activeIndex, 3, "should be the fourth page in the stack"); start(); }]); }); asyncTest( "going back from a page entered from a dialog skips the dialog and goes to the previous page", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#skip-dialog-first"); }, // transition to the dialog function(){ $("#skip-dialog-first a").click(); }, // transition to the second page function(){ $("#skip-dialog a").click(); }, // transition past the dialog via data-rel=back link on the second page function(){ $("#skip-dialog-second a").click(); }, // make sure we're at the first page and not the dialog function(){ $.testHelper.assertUrlLocation({ hash: "skip-dialog-first", push: home + "#skip-dialog-first", report: "should be the first page in the sequence" }); start(); }]); }); asyncTest( "going forward from a page entered from a dialog skips the dialog and goes to the next page", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#skip-dialog-first"); }, // transition to the dialog function(){ $("#skip-dialog-first a").click(); }, // transition to the second page function(){ $("#skip-dialog a").click(); }, // transition to back past the dialog function(){ window.history.back(); }, // transition to the second page past the dialog through history function(){ window.history.forward(); }, // make sure we're on the second page and not the dialog function(){ $.testHelper.assertUrlLocation({ hash: "skip-dialog-second", push: home + "#skip-dialog-second", report: "should be the second page after the dialog" }); start(); }]); }); asyncTest( "going back from a dialog triggered from a dialog should result in the first dialog ", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#nested-dialog-page"); }, // transition to the dialog function(){ $("#nested-dialog-page a").click(); }, // transition to the second dialog function(){ $("#nested-dialog-first a").click(); }, // transition to back to the first dialog function(){ window.history.back(); }, // make sure we're on first dialog function(){ same($(".ui-page-active")[0], $("#nested-dialog-first")[0], "should be the first dialog"); start(); }]); }); asyncTest( "loading a relative file path after an embeded page works", function(){ $.testHelper.pageSequence([ // transition second page function(){ $.testHelper.openPage("#relative-after-embeded-page-first"); }, // transition second page function(){ $("#relative-after-embeded-page-first a").click(); }, // transition to the relative ajax loaded page function(){ $("#relative-after-embeded-page-second a").click(); }, // make sure the page was loaded properly via ajax function(){ // data attribute intentionally left without namespace same($(".ui-page-active").data("other"), "for testing", "should be relative ajax loaded page"); start(); }]); }); asyncTest( "Page title updates properly when clicking back to previous page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#relative-after-embeded-page-first"); }, function(){ window.history.back(); }, function(){ same(document.title, "jQuery Mobile Navigation Test Suite"); start(); } ]); }); asyncTest( "Page title updates properly when clicking a link back to first page", function(){ var title = document.title; $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest1").click(); }, function(){ same(document.title, "Title Tag"); $.mobile.activePage.find("#title-check-link").click(); }, function(){ same(document.title, title); start(); } ]); }); asyncTest( "Page title updates properly from title tag when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest1").click(); }, function(){ same(document.title, "Title Tag"); start(); } ]); }); asyncTest( "Page title updates properly from data-title attr when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest2").click(); }, function(){ same(document.title, "Title Attr"); start(); } ]); }); asyncTest( "Page title updates properly from heading text in header when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest3").click(); }, function(){ same(document.title, "Title Heading"); start(); } ]); }); asyncTest( "Page links to the current active page result in the same active page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#self-link"); }, function(){ $("a[href='#self-link']").click(); }, function(){ same($.mobile.activePage[0], $("#self-link")[0], "self-link page is still the active page" ); start(); } ]); }); asyncTest( "links on subdirectory pages with query params append the params and load the page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#data-url-tests/non-data-url.html"); }, function(){ $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url has query params" }); ok($(".ui-page-active").jqmData("url").indexOf("?foo=bar") > -1, "the query params are in the data url"); start(); } ]); }); asyncTest( "identical query param link doesn't add additional set of query params", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#data-url-tests/non-data-url.html"); }, function(){ $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url has query params" }); $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url still has query params" }); start(); } ]); }); // Special handling inside navigation because query params must be applied to the hash // or absolute reference and dialogs apply extra information int the hash that must be removed asyncTest( "query param link from a dialog to itself should be a not add another dialog", function(){ var firstDialogLoc; $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#dialog-param-link"); }, // navigate to the subdirectory page with the query link function(){ $("#dialog-param-link a").click(); }, // navigate to the query param self reference link function(){ $("#dialog-param-link-page a").click(); }, // attempt to navigate to the same link function(){ // store the current hash for comparison (with one dialog hash key) firstDialogLoc = location.hash || location.href; $("#dialog-param-link-page a").click(); }, function(){ same(location.hash || location.href, firstDialogLoc, "additional dialog hash key not added"); start(); } ]); }); asyncTest( "query data passed as string to changePage is appended to URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.mobile.changePage( "form-tests/changepage-data.html", { data: "foo=1&bar=2" } ); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/changepage-data.html?foo=1&bar=2", report: "the hash or url still has query params" }); start(); } ]); }); asyncTest( "query data passed as object to changePage is appended to URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.mobile.changePage( "form-tests/changepage-data.html", { data: { foo: 3, bar: 4 } } ); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/changepage-data.html?foo=3&bar=4", report: "the hash or url still has query params" }); start(); } ]); }); asyncTest( "refresh of a dialog url should not duplicate page", function(){ $.testHelper.pageSequence([ // open our test page function(){ same($(".foo-class").length, 1, "should only have one instance of foo-class in the document"); location.hash = "#foo&ui-state=dialog"; }, function(){ $.testHelper.assertUrlLocation({ hash: "foo&ui-state=dialog", push: home + "#foo&ui-state=dialog", report: "hash should match what was loaded" }); same( $(".foo-class").length, 1, "should only have one instance of foo-class in the document" ); start(); } ]); }); asyncTest( "internal form with no action submits to document URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#internal-no-action-form-page"); }, function(){ $("#internal-no-action-form-page form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "?foo=1&bar=2", report: "hash should match what was loaded" }); start(); } ]); }); asyncTest( "external page containing form with no action submits to page URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#internal-no-action-form-page"); }, function(){ $("#internal-no-action-form-page a").eq(0).click(); }, function(){ $("#external-form-no-action-page form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/form-no-action.html?foo=1&bar=2", report: "hash should match page url and not document url" }); start(); } ]); }); asyncTest( "handling of active button state when navigating", 1, function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ $("#active-state-page2 a").eq(0).click(); }, function(){ ok(!$("#active-state-page1 a").hasClass( $.mobile.activeBtnClass ), "No button should not have class " + $.mobile.activeBtnClass ); start(); } ]); }); // issue 2444 https://github.com/jquery/jquery-mobile/issues/2444 // results from preventing spurious hash changes asyncTest( "dialog should return to its parent page when open and closed multiple times", function() { $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#default-trans-dialog"); }, function(){ $.mobile.activePage.find( "a" ).click(); }, function(){ window.history.back(); }, function(){ same( $.mobile.activePage[0], $( "#default-trans-dialog" )[0] ); $.mobile.activePage.find( "a" ).click(); }, function(){ window.history.back(); }, function(){ same( $.mobile.activePage[0], $( "#default-trans-dialog" )[0] ); start(); } ]); }); asyncTest( "clicks with middle mouse button are ignored", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage( "#odd-clicks-page" ); }, function() { $( "#right-or-middle-click" ).click(); }, // make sure the page is opening first without the mocked button click value // only necessary to prevent issues with test specific fixtures function() { same($.mobile.activePage[0], $("#odd-clicks-page-dest")[0]); $.testHelper.openPage( "#odd-clicks-page" ); // mock the which value to simulate a middle click $.Event.prototype.which = 2; }, function() { $( "#right-or-middle-click" ).click(); }, function( timeout ) { ok( timeout, "page event handler timed out due to ignored click" ); ok($.mobile.activePage[0] !== $("#odd-clicks-page-dest")[0], "pages are not the same"); start(); } ]); }); asyncTest( "disabling link binding disables navigation via links and highlighting", function() { $.mobile.linkBindingEnabled = false; $.testHelper.pageSequence([ function() { $.testHelper.openPage("#bar"); }, function() { $.mobile.activePage.find( "a" ).click(); }, function( timeout ) { ok( !$.mobile.activePage.find( "a" ).hasClass( $.mobile.activeBtnClass ), "vlick handler doesn't add the activebtn class" ); ok( timeout, "no page change was fired" ); start(); } ]); }); asyncTest( "handling of button active state when navigating by clicking back button", 1, function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ $("#active-state-page2 a").eq(1).click(); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ ok(!$("#active-state-page2 a").hasClass( $.mobile.activeBtnClass ), "No button should not have class " + $.mobile.activeBtnClass ); start(); } ]); }); asyncTest( "can navigate to dynamically injected page with dynamically injected link", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#inject-links-page"); }, function(){ var $ilpage = $( "#inject-links-page" ), $link = $( "<a href='#injected-test-page'>injected-test-page link</a>" ); // Make sure we actually navigated to the expected page. ok( $.mobile.activePage[ 0 ] == $ilpage[ 0 ], "navigated successfully to #inject-links-page" ); // Now dynamically insert a page. $ilpage.parent().append( "<div data-role='page' id='injected-test-page'>testing...</div>" ); // Now inject a link to this page dynamically and attempt to navigate // to the page we just inserted. $link.appendTo( $ilpage ).click(); }, function(){ // Make sure we actually navigated to the expected page. ok( $.mobile.activePage[ 0 ] == $( "#injected-test-page" )[ 0 ], "navigated successfully to #injected-test-page" ); start(); } ]); }); asyncTest( "application url with dialogHashKey loads application's first page", function(){ $.testHelper.pageSequence([ // open our test page function(){ // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "navigated successfully to #foo" ); // Now navigate to an hash that contains just a dialogHashKey. $.mobile.changePage("#" + $.mobile.dialogHashKey); }, function(){ // Make sure we actually navigated to the first page. ok( $.mobile.activePage[ 0 ] === $.mobile.firstPage[ 0 ], "navigated successfully to first-page" ); // Now make sure opening the page didn't result in page duplication. ok( $.mobile.firstPage.hasClass( "first-page" ), "first page has expected class" ); same( $( ".first-page" ).length, 1, "first page was not duplicated" ); start(); } ]); }); asyncTest( "navigate to non-existent internal page throws pagechangefailed", function(){ var pagechangefailed = false, pageChangeFailedCB = function( e ) { pagechangefailed = true; } $( document ).bind( "pagechangefailed", pageChangeFailedCB ); $.testHelper.pageSequence([ // open our test page function(){ // Make sure there's only one copy of the first-page in the DOM to begin with. ok( $.mobile.firstPage.hasClass( "first-page" ), "first page has expected class" ); same( $( ".first-page" ).length, 1, "first page was not duplicated" ); // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ var $foo = $( "#foo" ); ok( $.mobile.activePage[ 0 ] === $foo[ 0 ], "navigated successfully to #foo" ); same( pagechangefailed, false, "no page change failures" ); // Now navigate to a non-existent page. $foo.find( "#bad-internal-page-link" ).click(); }, function(){ // Make sure a pagechangefailed event was triggered. same( pagechangefailed, true, "pagechangefailed dispatched" ); // Make sure we didn't navigate away from #foo. ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "did not navigate away from #foo" ); // Now make sure opening the page didn't result in page duplication. same( $( ".first-page" ).length, 1, "first page was not duplicated" ); $( document ).unbind( "pagechangefailed", pageChangeFailedCB ); start(); } ]); }); asyncTest( "prefetched links with data rel dialog result in a dialog", function() { $.testHelper.pageSequence([ // open our test page function(){ // Navigate to any page except the first page of the application. $.testHelper.openPage("#prefetched-dialog-page"); }, function() { $("#prefetched-dialog-link").click(); }, function() { ok( $.mobile.activePage.is(".ui-dialog"), "prefetched page is rendered as a dialog" ); start(); } ]); }); asyncTest( "first page gets reloaded if pruned from the DOM", function(){ var hideCallbackTriggered = false; function hideCallback( e, data ) { var page = e.target; ok( ( page === $.mobile.firstPage[ 0 ] ), "hide called with prevPage set to firstPage"); if ( page === $.mobile.firstPage[ 0 ] ) { $( page ).remove(); } hideCallbackTriggered = true; } $(document).bind('pagehide', hideCallback); $.testHelper.pageSequence([ function(){ // Make sure the first page is actually in the DOM. ok( $.mobile.firstPage.parent().length !== 0, "first page is currently in the DOM" ); // Make sure the first page is the active page. ok( $.mobile.activePage[ 0 ] === $.mobile.firstPage[ 0 ], "first page is the active page" ); // Now make sure the first page has an id that we can use to reload it. ok( $.mobile.firstPage[ 0 ].id, "first page has an id" ); // Make sure there is only one first page in the DOM. same( $( ".first-page" ).length, 1, "only one instance of the first page in the DOM" ); // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ // Make sure the active page is #foo. ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "navigated successfully to #foo" ); // Make sure our hide callback was triggered. ok( hideCallbackTriggered, "hide callback was triggered" ); // Make sure the first page was actually pruned from the document. ok( $.mobile.firstPage.parent().length === 0, "first page was pruned from the DOM" ); same( $( ".first-page" ).length, 0, "no instance of the first page in the DOM" ); // Remove our hideCallback. $(document).unbind('pagehide', hideCallback); // Navigate back to the first page! $.testHelper.openPage( "#" + $.mobile.firstPage[0].id ); }, function(){ var firstPage = $( ".first-page" ); // We should only have one first page in the document at any time! same( firstPage.length, 1, "single instance of first page recreated in the DOM" ); // Make sure the first page in the DOM is actually a different DOM element than the original // one we started with. ok( $.mobile.firstPage[ 0 ] !== firstPage[ 0 ], "first page is a new DOM element"); // Make sure we actually navigated to the new first page. ok( $.mobile.activePage[ 0 ] === firstPage[ 0 ], "navigated successfully to new first-page"); // Reset the $.mobile.firstPage for subsequent tests. // XXX: Should we just get rid of the new one and restore the old? $.mobile.firstPage = $.mobile.activePage; start(); } ]); }); })(jQuery);
JavaScript
/* * mobile navigation unit tests */ (function($){ var perspective = "viewport-flip", transitioning = "ui-mobile-viewport-transitioning", animationCompleteFn = $.fn.animationComplete, //TODO centralize class names? transitionTypes = "in out fade slide flip reverse pop", isTransitioning = function(page){ return $.grep(transitionTypes.split(" "), function(className, i){ return page.hasClass(className); }).length > 0; }, isTransitioningIn = function(page){ return page.hasClass("in") && isTransitioning(page); }, //animationComplete callback queue callbackQueue = [], finishPageTransition = function(){ callbackQueue.pop()(); }, clearPageTransitionStack = function(){ stop(); var checkTransitionStack = function(){ if(callbackQueue.length>0) { setTimeout(function(){ finishPageTransition(); checkTransitionStack(); },0); } else { start(); } }; checkTransitionStack(); }, //wipe all urls clearUrlHistory = function(){ $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; }; module('jquery.mobile.navigation.js', { setup: function(){ //stub to prevent class removal $.fn.animationComplete = function(callback){ callbackQueue.unshift(callback); }; clearPageTransitionStack(); clearUrlHistory(); }, teardown: function(){ // unmock animation complete $.fn.animationComplete = animationCompleteFn; } }); test( "changePage applys perspective class to mobile viewport for flip", function(){ $("#foo > a").click(); ok($("body").hasClass(perspective), "has perspective class"); }); test( "changePage does not apply perspective class to mobile viewport for transitions other than flip", function(){ $("#bar > a").click(); ok(!$("body").hasClass(perspective), "doesn't have perspective class"); }); test( "changePage applys transition class to mobile viewport for default transition", function(){ $("#baz > a").click(); ok($("body").hasClass(transitioning), "has transitioning class"); }); test( "explicit transition preferred for page navigation reversal (ie back)", function(){ $("#fade-trans > a").click(); stop(); setTimeout(function(){ finishPageTransition(); $("#flip-trans > a").click(); setTimeout(function(){ finishPageTransition(); $("#fade-trans > a").click(); setTimeout(function(){ ok($("#flip-trans").hasClass("fade"), "has fade class"); start(); },0); },0); },0); }); test( "default transition is slide", function(){ $("#default-trans > a").click(); stop(); setTimeout(function(){ ok($("#no-trans").hasClass("slide"), "has slide class"); start(); },0); }); test( "changePage queues requests", function(){ var firstPage = $("#foo"), secondPage = $("#bar"); $.mobile.changePage(firstPage); $.mobile.changePage(secondPage); stop(); setTimeout(function(){ ok(isTransitioningIn(firstPage), "first page begins transition"); ok(!isTransitioningIn(secondPage), "second page doesn't transition yet"); finishPageTransition(); setTimeout(function(){ ok(!isTransitioningIn(firstPage), "first page transition should be complete"); ok(isTransitioningIn(secondPage), "second page should begin transitioning"); start(); },0); },0); }); test( "default transition is pop for a dialog", function(){ expect( 1 ); stop(); setTimeout(function(){ $("#default-trans-dialog > a").click(); ok($("#no-trans-dialog").hasClass("pop"), "expected the pop class to be present but instead was " + $("#no-trans-dialog").attr('class')); start(); }, 900); }); test( "animationComplete return value", function(){ $.fn.animationComplete = animationCompleteFn; equals($("#foo").animationComplete(function(){})[0], $("#foo")[0]); }); })(jQuery);
JavaScript
/* * mobile widget unit tests */ (function($){ module('jquery.mobile.widget.js'); test( "getting data from creation options", function(){ var expected = "bizzle"; $.mobile.widget.prototype.options = { "fooBar" : true }; $.mobile.widget.prototype.element = $("<div data-foo-bar=" + expected + ">"); same($.mobile.widget.prototype._getCreateOptions()["fooBar"], expected); }); test( "getting no data when the options are empty", function(){ var expected = {}; $.mobile.widget.prototype.options = {}; $.mobile.widget.prototype.element = $("<div data-foo-bar=" + expected + ">"); same($.mobile.widget.prototype._getCreateOptions(), expected); }); test( "getting no data when the element has none", function(){ var expected = {}; $.mobile.widget.prototype.options = { "fooBar" : true }; $.mobile.widget.prototype.element = $("<div>"); same($.mobile.widget.prototype._getCreateOptions(), expected); }); test( "elements embedded in sub page elements are excluded on create when they match the keep native selector", function() { // uses default keep native of data-role=none $("#enhance-prevented") .append('<label for="unenhanced">Text Input:</label><input type="text" name="name" id="unenhanced" value="" data-role="none" />') .trigger("create"); ok( !$("#unenhanced").hasClass( "ui-input-text" ), "doesn't have the ui input text class (unenhanced)"); }); test( "elements embedded in sub page elements are included on create when they don't match the keep native selector", function() { // uses default keep native of data-role=none $("#enhance-allowed") .append('<label for="enhanced">Text Input:</label><input type="text" name="name" id="enhanced" value=""/>') .trigger("create"); ok( $("#enhanced").hasClass( "ui-input-text" ), "has the ui input text class (unenhanced)"); }); })(jQuery);
JavaScript
/* * mobile widget unit tests */ (function($){ var widgetInitialized = false; module( 'jquery.mobile.widget.js' ); $( "#foo" ).live( 'pageinit', function(){ // ordering sensitive here, the value has to be set after the call // so that if the widget factory says that its not yet initialized, // which is an exception, the value won't be set $( "#foo-slider" ).slider( 'refresh' ); widgetInitialized = true; }); test( "page is enhanced before init is fired", function() { ok( widgetInitialized ); }); })( jQuery );
JavaScript
/* * mobile checkboxradio unit tests */ (function($){ module( 'jquery.mobile.forms.checkboxradio.js' ); test( "widget can be disabled and enabled", function(){ var input = $( "#checkbox-1" ), button = input.parent().find( ".ui-btn" ); input.checkboxradio( "disable" ); input.checkboxradio( "enable" ); ok( !input.attr( "disabled" ), "start input as enabled" ); ok( !input.parent().hasClass( "ui-disabled" ), "no disabled styles" ); ok( !input.attr( "checked" ), "not checked before click" ); button.trigger( "click" ); ok( input.attr( "checked" ), "checked after click" ); ok( button.hasClass( "ui-checkbox-on" ), "active styles after click" ); button.trigger( "click" ); input.checkboxradio( "disable" ); ok( input.attr( "disabled" ), "input disabled" ); ok( input.parent().hasClass( "ui-disabled" ), "disabled styles" ); ok( !input.attr( "checked" ), "not checked before click" ); button.trigger( "click" ); ok( !input.attr( "checked" ), "not checked after click" ); ok( !button.hasClass( "ui-checkbox-on" ), "no active styles after click" ); }); test( "clicking a checkbox within a controlgroup does not affect checkboxes with the same name in the same controlgroup", function(){ var input1 = $("#checkbox-31"); var button1 = input1.parent().find(".ui-btn"); var input2 = $("#checkbox-32"); var button2 = input2.parent().find(".ui-btn"); ok(!input1.attr("checked"), "input1 not checked before click"); ok(!input2.attr("checked"), "input2 not checked before click"); button1.trigger("click"); ok(input1.attr("checked"), "input1 checked after click on input1"); ok(!input2.attr("checked"), "input2 not checked after click on input1"); button2.trigger("click"); ok(input1.attr("checked"), "input1 not changed after click on input2"); ok(input2.attr("checked"), "input2 checked after click on input2"); }); asyncTest( "change events fired on checkbox for both check and uncheck", function(){ var $checkbox = $( "#checkbox-2" ), $checkboxLabel = $checkbox.parent().find( ".ui-btn" ); $checkbox.unbind( "change" ); expect( 1 ); $checkbox.one('change', function(){ ok( true, "change fired on click to check the box" ); }); $checkboxLabel.trigger( "click" ); //test above will be triggered twice, and the start here once $checkbox.one('change', function(){ start(); }); $checkboxLabel.trigger( "click" ); }); asyncTest( "radio button labels should update the active button class to last clicked and clear checked", function(){ var $radioBtns = $( '#radio-active-btn-test input' ), singleActiveAndChecked = function(){ same( $( "#radio-active-btn-test .ui-radio-on" ).length, 1, "there should be only one active button" ); same( $( "#radio-active-btn-test :checked" ).length, 1, "there should be only one checked" ); }; $.testHelper.sequence([ function(){ $radioBtns.last().siblings( 'label' ).click(); }, function(){ ok( $radioBtns.last().prop( 'checked' ) ); ok( $radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ), "last input label is an active button" ); ok( !$radioBtns.first().prop( 'checked' ) ); ok( !$radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ), "first input label is not active" ); singleActiveAndChecked(); $radioBtns.first().siblings( 'label' ).click(); }, function(){ ok( $radioBtns.first().prop( 'checked' )); ok( $radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ), "first input label is an active button" ); ok( !$radioBtns.last().prop( 'checked' )); ok( !$radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ), "last input label is not active" ); singleActiveAndChecked(); start(); } ], 500); }); test( "checkboxradio controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-checkbox").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-checkbox").length, "enhancements applied" ); }); $.mobile.page.prototype.options.keepNative = "input.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "checkboxradio elements in the keepNative set shouldn't be enhanced", function() { ok( !$("input.should-be-native").parent().is("div.ui-checkbox") ); }); asyncTest( "clicking the label triggers a click on the element", function() { var clicked = false; expect( 1 ); $( "#checkbox-click-triggered" ).one('click', function() { clicked = true; }); $.testHelper.sequence([ function() { $( "[for='checkbox-click-triggered']" ).click(); }, function() { ok(clicked, "click was fired on input"); start(); } ], 2000); }); })(jQuery);
JavaScript
/* * mobile slider unit tests */ (function($){ $.mobile.page.prototype.options.keepNative = "input.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "slider elements in the keepNative set shouldn't be enhanced", function() { same( $("input.should-be-native").siblings("div.ui-slider").length, 0 ); }); })( jQuery );
JavaScript
/* * mobile slider unit tests */ (function($){ var onChangeCnt = 0; window.onChangeCounter = function() { onChangeCnt++; } module('jquery.mobile.slider.js'); var keypressTest = function(opts){ var slider = $(opts.selector), val = window.parseFloat(slider.val()), handle = slider.siblings('.ui-slider').find('.ui-slider-handle'); expect( opts.keyCodes.length ); $.each(opts.keyCodes, function(i, elem){ // stub the keycode value and trigger the keypress $.Event.prototype.keyCode = $.mobile.keyCode[elem]; handle.trigger('keydown'); val += opts.increment; same(val, window.parseFloat(slider.val(), 10), "new value is " + opts.increment + " different"); }); }; test( "slider should move right with up, right, and page up keypress", function(){ keypressTest({ selector: '#range-slider-up', keyCodes: ['UP', 'RIGHT', 'PAGE_UP'], increment: 1 }); }); test( "slider should move left with down, left, and page down keypress", function(){ keypressTest({ selector: '#range-slider-down', keyCodes: ['DOWN', 'LEFT', 'PAGE_DOWN'], increment: -1 }); }); test( "slider should move to range minimum on end keypress", function(){ var selector = "#range-slider-end", initialVal = window.parseFloat($(selector).val(), 10), max = window.parseFloat($(selector).attr('max'), 10); keypressTest({ selector: selector, keyCodes: ['END'], increment: max - initialVal }); }); test( "slider should move to range minimum on end keypress", function(){ var selector = "#range-slider-home", initialVal = window.parseFloat($(selector).val(), 10); keypressTest({ selector: selector, keyCodes: ['HOME'], increment: 0 - initialVal }); }); test( "slider should move positive by steps on keypress", function(){ keypressTest({ selector: "#stepped", keyCodes: ['RIGHT'], increment: 10 }); }); test( "slider should move negative by steps on keypress", function(){ keypressTest({ selector: "#stepped", keyCodes: ['LEFT'], increment: -10 }); }); test( "slider should validate input value on blur", function(){ var slider = $("#range-slider-up"); slider.focus(); slider.val(200); same(slider.val(), "200"); slider.blur(); same(slider.val(), slider.attr('max')); }); test( "slider should not validate input on keyup", function(){ var slider = $("#range-slider-up"); slider.focus(); slider.val(200); same(slider.val(), "200"); slider.keyup(); same(slider.val(), "200"); }); test( "input type should degrade to number when slider is created", function(){ same($("#range-slider-up").attr( "type" ), "number"); }); // generic switch test function var sliderSwitchTest = function(opts){ var slider = $("#slider-switch"), handle = slider.siblings('.ui-slider').find('a'), switchValues = { 'off' : 0, 'on' : 1 }; // One for the select and one for the aria-valuenow expect( opts.keyCodes.length * 2 ); $.each(opts.keyCodes, function(i, elem){ // reset the values slider[0].selectedIndex = switchValues[opts.start]; handle.attr({'aria-valuenow' : opts.start }); // stub the keycode and trigger the event $.Event.prototype.keyCode = $.mobile.keyCode[elem]; handle.trigger('keydown'); same(handle.attr('aria-valuenow'), opts.finish, "handle value is " + opts.finish); same(slider[0].selectedIndex, switchValues[opts.finish], "select input has correct index"); }); }; test( "switch should select on with up, right, page up and end", function(){ sliderSwitchTest({ start: 'off', finish: 'on', keyCodes: ['UP', 'RIGHT', 'PAGE_UP', 'END'] }); }); test( "switch should select off with down, left, page down and home", function(){ sliderSwitchTest({ start: 'on', finish: 'off', keyCodes: ['DOWN', 'LEFT', 'PAGE_DOWN', 'HOME'] }); }); test( "onchange should not be called on create", function(){ equals(onChangeCnt, 0, "onChange should not have been called"); }); test( "onchange should be called onchange", function(){ onChangeCnt = 0; $( "#onchange" ).slider( "refresh", 50 ); equals(onChangeCnt, 1, "onChange should have been called once"); }); test( "slider controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-slider").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-slider").length, "enhancements applied" ); }); var createEvent = function( name, target, x, y ) { var event = $.Event( name ); event.target = target; event.pageX = x; event.pageY = y; return event; }; test( "toggle switch should fire one change event when clicked", function(){ var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, changeCount = 0, changeFunc = function( e ) { ok( control[0].selectedIndex !== currentValue, "change event should only be triggered if the value changes"); ++changeCount; }, event = null, offset = handle.offset(), currentValue = control[0].selectedIndex; control.bind( "change", changeFunc ); // The toggle switch actually updates on mousedown and mouseup events, so we go through // the motions of generating all the events that happen during a click to make sure that // during all of those events, the value only changes once. slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "click", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); control.unbind( "change", changeFunc ); ok( control[0].selectedIndex !== currentValue, "value did change"); same( changeCount, 1, "change event should be fired once during a click" ); }); var assertLeftCSS = function( obj, opts ) { var integerLeft, compare, css, threshold; css = obj.css('left'); threshold = opts.pxThreshold || 0; if( css.indexOf( "px" ) > -1 ) { // parse the actual pixel value returned by the left css value // and the pixels passed in for comparison integerLeft = Math.round( parseFloat( css.replace("px", "") ) ), compare = parseInt( opts.pixels.replace( "px", "" ), 10 ); // check that the pixel value provided is within a given threshold; default is 0px ok( compare >= integerLeft - threshold && compare <= integerLeft + threshold, opts.message ); } else { equal( css, opts.percent, opts.message ); } }; asyncTest( "toggle switch handle should snap in the old position if dragged less than half of the slider width, in the new position if dragged more than half of the slider width", function() { var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, width = handle.width(), offset = null; $.testHelper.sequence([ function() { // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging less than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + width - 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left + width - 20, offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left + width - 20, offset.top + 10 ) ); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle ends on the right side' }); // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging more than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); }, function() { assertLeftCSS(handle, { percent: '0%', pixels: '0px', message: 'handle ends on the left side' }); start(); } ], 500); }); asyncTest( "toggle switch handle should not move if user is dragging and value is changed", function() { var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, width = handle.width(), offset = null; $.testHelper.sequence([ function() { // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging more than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); }, function() { var min, max; if( handle.css('left').indexOf("%") > -1 ){ min = "0%"; max = "100%"; } else { min = "0px"; max = handle.parent().css( 'width' ); } notEqual(handle.css('left'), min, 'handle is not on the left side'); notEqual(handle.css('left'), max, 'handle is not on the right side'); // reset slider state so it is ready for other tests slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); start(); } ], 500); }); asyncTest( "toggle switch should refresh when disabled", function() { var control = $( "#slider-switch" ), handle = control.data( "slider" ).handle; $.testHelper.sequence([ function() { // set the initial value control.val('off').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '0%', pixels: '0px', message: 'handle starts on the left side' }); // disable and change value control.slider('disable'); control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css( 'width' ), message: 'handle ends on the right side' }); // reset slider state so it is ready for other tests control.slider('enable'); start(); } ], 500); }); })(jQuery);
JavaScript
/* * degradeInputs unit tests */ (function($){ module('jquery.mobile.slider.js'); test('keepNative elements should not be degraded', function() { same($('input#not-to-be-degraded').attr("type"), "range"); }); test('should degrade input type to a different type, as specified in page options', function(){ var degradeInputs = $.mobile.page.prototype.options.degradeInputs; expect( degradeInputs.length ); $.each(degradeInputs, function( oldType, newType ) { if (newType === false) { newType = oldType; } $('#test-container').html('<input type="' + oldType + '" />').trigger("create"); same($('#test-container input').attr("type"), newType); }); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var resetHash; resetHash = function(timeout){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); }; // https://github.com/jquery/jquery-mobile/issues/2181 asyncTest( "dialog sized select should alter the value of its parent select", function(){ var selectButton, value; $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached.html" ); }, function(){ selectButton = $( "#cached-page-select" ).siblings( 'a' ); selectButton.click(); }, function(){ ok( $.mobile.activePage.hasClass('ui-dialog'), "the dialog came up" ); var option = $.mobile.activePage.find( "li a" ).not(":contains('" + selectButton.text() + "')").last(); value = option.text(); option.click(); }, function(){ same( value, selectButton.text(), "the selected value is propogated back to the button text" ); start(); } ]); }); // https://github.com/jquery/jquery-mobile/issues/2181 asyncTest( "dialog sized select should prevent the removal of its parent page from the dom", function(){ var selectButton, parentPageId; expect( 2 ); $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached.html" ); }, function(){ selectButton = $.mobile.activePage.find( "#cached-page-select" ).siblings( 'a' ); parentPageId = $.mobile.activePage.attr( 'id' ); same( $("#" + parentPageId).length, 1, "establish the parent page exists" ); selectButton.click(); }, function(){ same( $( "#" + parentPageId).length, 1, "make sure parent page is still there after opening the dialog" ); $.mobile.activePage.find( "li a" ).last().click(); }, start ]); }); asyncTest( "dialog sized select shouldn't rebind its parent page remove handler when closing, if the parent page domCache option is true", function(){ expect( 3 ); $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached-dom-cache-true.html" ); }, function(){ $.mobile.activePage.find( "#domcache-page-select" ).siblings( 'a' ).click(); }, function(){ ok( $.mobile.activePage.hasClass('ui-dialog'), "the dialog came up" ); $.mobile.activePage.find( "li a" ).last().click(); }, function(){ ok( $.mobile.activePage.is( "#dialog-select-parent-domcache-test" ), "the dialog closed" ); $.mobile.changePage( $( "#default" ) ); }, function(){ same( $("#dialog-select-parent-domcache-test").length, 1, "make sure the select parent page is still cached in the dom after changing page" ); start(); } ]); }); asyncTest( "menupage is removed when the parent page is removed", function(){ var dialogCount = $(":jqmData(role='dialog')").length; $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "uncached-dom-cached-false.html" ); }, function(){ same( $(":jqmData(role='dialog')").length, dialogCount + 1 ); window.history.back(); }, function() { same( $(":jqmData(role='dialog')").length, dialogCount ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ module("jquery.mobile.forms.select native"); test( "native menu selections alter the button text", function(){ var select = $( "#native-select-choice-few" ), setAndCheck; setAndCheck = function(key){ var text; select.val( key ).selectmenu( 'refresh' ); text = select.find( "option[value='" + key + "']" ).text(); same( select.parent().find(".ui-btn-text").text(), text ); }; setAndCheck( 'rush' ); setAndCheck( 'standard' ); }); asyncTest( "selecting a value removes the related buttons down state", function(){ var select = $( "#native-select-choice-few" ); $.testHelper.sequence([ function() { // click the native menu parent button select.parent().trigger( 'vmousedown' ); }, function() { ok( select.parent().hasClass("ui-btn-down-c"), "button down class added" ); }, function() { // trigger a change on the select select.trigger( "change" ); }, function() { ok( !select.parent().hasClass("ui-btn-down-c"), "button down class removed" ); start(); } ], 300); }); // issue https://github.com/jquery/jquery-mobile/issues/2410 test( "adding options and refreshing a native select defaults the text", function() { var select = $( "#native-refresh" ), button = select.siblings( '.ui-btn-inner' ), text = "foo"; same(button.text(), "default"); select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu('refresh'); same(button.text(), text); }); // issue 2424 test( "native selects should provide open and close as a no-op", function() { // exception will prevent test success if undef $( "#native-refresh" ).selectmenu( 'open' ); $( "#native-refresh" ).selectmenu( 'close' ); ok( true ); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var libName = "jquery.mobile.forms.select.js", originalDefaultDialogTrans = $.mobile.defaultDialogTransition, originalDefTransitionHandler = $.mobile.defaultTransitionHandler, originalGetEncodedText = $.fn.getEncodedText, resetHash, closeDialog; resetHash = function(timeout){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); }; closeDialog = function(timeout){ $.mobile.activePage.find("li a").first().click(); }; module(libName, { teardown: function(){ $.mobile.defaultDialogTransition = originalDefaultDialogTrans; $.mobile.defaultTransitionHandler = originalDefTransitionHandler; $.fn.getEncodedText = originalGetEncodedText; window.encodedValueIsDefined = undefined; } }); asyncTest( "firing a click at least 400 ms later on the select screen overlay does close it", function(){ $.testHelper.sequence([ function(){ // bring up the smaller choice menu ok($("#select-choice-few-container a").length > 0, "there is in fact a button in the page"); $("#select-choice-few-container a").trigger("click"); }, function(){ //select the first menu item $("#select-choice-few-menu a:first").click(); }, function(){ same($("#select-choice-few-menu").parent(".ui-selectmenu-hidden").length, 1); start(); } ], 1000); }); asyncTest( "a large select menu should use the default dialog transition", function(){ var select; $.testHelper.pageSequence([ resetHash, function(timeout){ select = $("#select-choice-many-container-1 a"); //set to something else $.mobile.defaultTransitionHandler = $.testHelper.decorate({ fn: $.mobile.defaultTransitionHandler, before: function(name){ same(name, $.mobile.defaultDialogTransition); } }); // bring up the dialog select.trigger("click"); }, closeDialog, start ]); }); asyncTest( "custom select menu always renders screen from the left", function(){ var select; expect( 1 ); $.testHelper.sequence([ resetHash, function(){ select = $("ul#select-offscreen-menu"); $("#select-offscreen-container a").trigger("click"); }, function(){ ok(select.offset().left >= 30, "offset from the left is greater than or equal to 30px" ); start(); } ], 1000); }); asyncTest( "selecting an item from a dialog sized custom select menu leaves no dialog hash key", function(){ var dialogHashKey = "ui-state=dialog"; $.testHelper.pageSequence([ resetHash, function(timeout){ $("#select-choice-many-container-hash-check a").click(); }, function(){ ok(location.hash.indexOf(dialogHashKey) > -1); closeDialog(); }, function(){ same(location.hash.indexOf(dialogHashKey), -1); start(); } ]); }); asyncTest( "dialog sized select menu opened many times remains a dialog", function(){ var dialogHashKey = "ui-state=dialog", openDialogSequence = [ resetHash, function(){ $("#select-choice-many-container-many-clicks a").click(); }, function(){ ok(location.hash.indexOf(dialogHashKey) > -1, "hash should have the dialog hash key"); closeDialog(); } ], sequence = openDialogSequence.concat(openDialogSequence).concat([start]); $.testHelper.sequence(sequence, 1000); }); test( "make sure the label for the select gets the ui-select class", function(){ ok( $( "#native-select-choice-few-container label" ).hasClass( "ui-select" ), "created label has ui-select class" ); }); module("Non native menus", { setup: function() { $.mobile.selectmenu.prototype.options.nativeMenu = false; }, teardown: function() { $.mobile.selectmenu.prototype.options.nativeMenu = true; } }); asyncTest( "a large select option should not overflow", function(){ // https://github.com/jquery/jquery-mobile/issues/1338 var menu, select; $.testHelper.sequence([ resetHash, function(){ select = $("#select-long-option-label"); // bring up the dialog select.trigger("click"); }, function() { menu = $(".ui-selectmenu-list"); equal(menu.width(), menu.find("li:nth-child(2) .ui-btn-text").width(), "ui-btn-text element should not overflow"); start(); } ], 500); }); asyncTest( "using custom refocuses the button after close", function() { var select, button, triggered = false; expect( 1 ); $.testHelper.sequence([ resetHash, function() { select = $("#select-choice-focus-test"); button = select.find( "a" ); button.trigger( "click" ); }, function() { // NOTE this is called twice per triggered click button.focus(function() { triggered = true; }); $(".ui-selectmenu-screen:not(.ui-screen-hidden)").trigger("click"); }, function(){ ok(triggered, "focus is triggered"); start(); } ], 5000); }); asyncTest( "selected items are highlighted", function(){ $.testHelper.sequence([ resetHash, function(){ // bring up the smaller choice menu ok($("#select-choice-few-container a").length > 0, "there is in fact a button in the page"); $("#select-choice-few-container a").trigger("click"); }, function(){ var firstMenuChoice = $("#select-choice-few-menu li:first"); ok( firstMenuChoice.hasClass( $.mobile.activeBtnClass ), "default menu choice has the active button class" ); $("#select-choice-few-menu a:last").click(); }, function(){ // bring up the menu again $("#select-choice-few-container a").trigger("click"); }, function(){ var lastMenuChoice = $("#select-choice-few-menu li:last"); ok( lastMenuChoice.hasClass( $.mobile.activeBtnClass ), "previously slected item has the active button class" ); // close the dialog lastMenuChoice.find( "a" ).click(); }, start ], 1000); }); test( "enabling and disabling", function(){ var select = $( "select" ).first(), button; button = select.siblings( "a" ).first(); select.selectmenu( 'disable' ); same( select.attr('disabled'), "disabled", "select is disabled" ); ok( button.hasClass("ui-disabled"), "disabled class added" ); same( button.attr('aria-disabled'), "true", "select is disabled" ); same( select.selectmenu( 'option', 'disabled' ), true, "disbaled option set" ); select.selectmenu( 'enable' ); same( select.attr('disabled'), undefined, "select is disabled" ); ok( !button.hasClass("ui-disabled"), "disabled class added" ); same( button.attr('aria-disabled'), "false", "select is disabled" ); same( select.selectmenu( 'option', 'disabled' ), false, "disbaled option set" ); }); test( "adding options and refreshing a custom select defaults the text", function() { var select = $( "#custom-refresh" ), button = select.siblings( "a" ).find( ".ui-btn-inner" ), text = "foo"; same(button.text(), "default"); select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu( 'refresh' ); same(button.text(), text); }); asyncTest( "adding options and refreshing a custom select changes the options list", function(){ var select = $( "#custom-refresh-opts-list" ), button = select.siblings( "a" ).find( ".ui-btn-inner" ), text = "foo"; $.testHelper.sequence([ // bring up the dialog function() { button.click(); }, function() { same( $( ".ui-selectmenu.in ul" ).text(), "default" ); $( ".ui-selectmenu-screen" ).click(); }, function() { select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu( 'refresh' ); }, function() { button.click(); }, function() { same( $( ".ui-selectmenu.in ul" ).text(), text ); $( ".ui-selectmenu-screen" ).click(); }, start ], 500); }); test( "theme defined on select is used", function(){ var select = $("select#non-parent-themed"); ok( select.siblings( "a" ).hasClass("ui-btn-up-" + select.jqmData('theme'))); }); test( "select without theme defined inherits theme from parent", function() { var select = $("select#parent-themed"); ok( select .siblings( "a" ) .hasClass("ui-btn-up-" + select.parents(":jqmData(role='page')").jqmData('theme'))); }); // issue #2547 test( "custom select list item links have encoded option text values", function() { $( "#encoded-option" ).data( 'selectmenu' )._buildList(); same(window.encodedValueIsDefined, undefined); }); // issue #2547 test( "custom select list item links have unencoded option text values when using vanilla $.fn.text", function() { // undo our changes, undone in teardown $.fn.getEncodedText = $.fn.text; $( "#encoded-option" ).data( 'selectmenu' )._buildList(); same(window.encodedValueIsDefined, true); }); $.mobile.page.prototype.options.keepNative = "select.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "select elements in the keepNative set shouldn't be enhanced", function() { ok( !$("#keep-native").parent().is("div.ui-btn") ); }); asyncTest( "dialog size select title should match the label", function() { var $select = $( "#select-choice-many-1" ), $label = $select.parent().siblings( "label" ), $button = $select.siblings( "a" ); $.testHelper.pageSequence([ function() { $button.click(); }, function() { same($.mobile.activePage.find( ".ui-title" ).text(), $label.text()); window.history.back(); }, start ]); }); asyncTest( "dialog size select title should match the label when changed after the dialog markup is added to the DOM", function() { var $select = $( "#select-choice-many-1" ), $label = $select.parent().siblings( "label" ), $button = $select.siblings( "a" ); $label.text( "foo" ); $.testHelper.pageSequence([ function() { $label.text( "foo" ); $button.click(); }, function() { same($.mobile.activePage.find( ".ui-title" ).text(), $label.text()); window.history.back(); }, start ]); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var libName = "jquery.mobile.forms.select.js"; $(document).bind('mobileinit', function(){ $.mobile.selectmenu.prototype.options.nativeMenu = false; }); module(libName,{ setup: function(){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); } }); test( "selects marked with data-native-menu=true should use a div as their button", function(){ same($("#select-choice-native-container div.ui-btn").length, 1); }); test( "selects marked with data-native-menu=true should not have a custom menu", function(){ same($("#select-choice-native-container ul").length, 0); }); test( "selects marked with data-native-menu=true should sit inside the button", function(){ same($("#select-choice-native-container div.ui-btn select").length, 1); }); test( "select controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-select").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-select").length, "enhancements applied" ); }); })(jQuery);
JavaScript
/* * mobile checkboxradio unit tests */ (function($){ module( 'vertical controlgroup, no refresh' , { setup: function() { this.vcontrolgroup = $( "#vertical-controlgroup" ); } }); test( "vertical controlgroup classes", function() { var buttons = this.vcontrolgroup.find( ".ui-btn" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( !buttons.hasClass( "ui-btn-corner-all" ), "no button should have class 'ui-btn-corner-all'"); ok( buttons.first().hasClass( "ui-corner-top" ), "first button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last button should have class 'ui-corner-bottom'" ); }); module( 'vertical controlgroup, refresh', { setup: function() { this.vcontrolgroup = $( "#vertical-controlgroup" ); this.vcontrolgroup.find( ".ui-btn" ).show(); this.vcontrolgroup.controlgroup(); } }); test( "vertical controlgroup after first button was hidden", function() { //https://github.com/jquery/jquery-mobile/issues/1929 //We hide the first button and refresh this.vcontrolgroup.find( ".ui-btn" ).first().hide(); this.vcontrolgroup.controlgroup(); var buttons = this.vcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-top" ), "first visible button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last visible button should have class 'ui-corner-bottom'" ); }); test( "vertical controlgroup after last button was hidden", function() { //https://github.com/jquery/jquery-mobile/issues/1929 //We hide the last button and refresh this.vcontrolgroup.find( ".ui-btn" ).last().hide(); this.vcontrolgroup.controlgroup(); var buttons = this.vcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-top" ), "first visible button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last visible button should have class 'ui-corner-bottom'" ); }); module( 'horizontal controlgroup, no refresh', { setup: function() { this.hcontrolgroup = $( "#horizontal-controlgroup" ); } }); test( "horizontal controlgroup classes", function() { var buttons = this.hcontrolgroup.find( ".ui-btn" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( !buttons.hasClass( "ui-btn-corner-all" ), "no button should have class 'ui-btn-corner-all'"); ok( buttons.first().hasClass( "ui-corner-left" ), "first button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last button should have class 'ui-corner-right'" ); }); module( 'horizontal controlgroup, refresh', { setup: function() { this.hcontrolgroup = $( "#horizontal-controlgroup" ); this.hcontrolgroup.find( ".ui-btn" ).show(); this.hcontrolgroup.controlgroup(); } }); test( "horizontal controlgroup after first button was hidden", function() { //We hide the first button and refresh this.hcontrolgroup.find( ".ui-btn" ).first().hide(); this.hcontrolgroup.controlgroup(); var buttons = this.hcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-left" ), "first visible button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last visible button should have class 'ui-corner-right'" ); }); test( "horizontal controlgroup after last button was hidden", function() { //We hide the last button and refresh this.hcontrolgroup.find( ".ui-btn" ).last().hide(); this.hcontrolgroup.controlgroup(); var buttons = this.hcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-left" ), "first visible button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last visible button should have class 'ui-corner-right'" ); }); test( "controlgroups will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-controlgroup").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-controlgroup").length, "enhancements applied" ); }); })(jQuery);
JavaScript
(function(Perf) { var $listPage = $( "#list-page" ), firstCounter = 0; Perf.setCurrentRev(); Perf.pageLoadStart = Date.now(); $listPage.live( "pagebeforecreate", function() { if( firstCounter == 0 ) { Perf.pageCreateStart = Date.now(); firstCounter++; } }); $listPage.live( "pageinit", function( event ) { // if a child page init is fired ignore it, we only // want the top level page init event if( event.target !== $("#list-page")[0] ){ return; } Perf.pageLoadEnd = Date.now(); // report the time taken for a full app boot Perf.report({ datapoint: "fullboot", value: Perf.pageLoadEnd - Perf.pageLoadStart }); // record the time taken to load and enhance the page // start polling for a new revision Perf.report({ datapoint: "pageload", value: Perf.pageCreateStart - Perf.pageLoadStart, after: function() { Perf.poll(); } }); }); })(window.Perf);
JavaScript
window.Perf = (function($, Perf) { $.extend(Perf, { reportUrl: 'stats/', revUrl: 'stats/rev.php', // should be defined before report or poll are run currentRev: undefined, report: function( data, after ) { $.extend(data, { pathname: location.pathname, agent: this.agent(), agentFull: window.navigator.userAgent, agentVersion: this.agentVersion() }); $.post( this.reportUrl, data, after ); }, poll: function() { var self = this; setInterval(function() { $.get( self.revUrl, function( data ) { // if there's a new revision refresh or currentRev isn't being set if( self.currentRev && self.currentRev !== data ){ location.href = location.href; } }); }, 60000); }, setCurrentRev: function() { var self = this; $.get( self.revUrl, function( data ) { self.currentRev = data; }); }, agent: function() { var agent = window.navigator.userAgent; for( name in this.agents ) { if( agent.indexOf( this.agents[name] ) > -1 ) { return this.agents[name]; } } return agent; }, agentVersion: function() { var agent = window.navigator.userAgent; agent.search(this.vRegexs[this.agent()] || ""); return RegExp.$1 ? RegExp.$1 : "0.0"; }, agents: { ANDROID: "Android", WP: "Windows Phone OS", IPHONE: "iPhone OS", IPAD: "iPad; U; CPU OS", BLACKBERRY: "BlackBerry" }, vRegexs: {} }); Perf.vRegexs[Perf.agents.ANDROID] = /([0-9].[0-9])(.[0-9])?/; Perf.vRegexs[Perf.agents.WP] = /Windows Phone OS ([0-9].[0-9]);/; Perf.vRegexs[Perf.agents.IPHONE] = /iPhone OS ([0-9]_[0-9])/; Perf.vRegexs[Perf.agents.IPAD] = /iPad; U; CPU OS ([0-9]_[0-9])/; Perf.vRegexs[Perf.agents.BLACKBERRY] = /BlackBerry ([0-9]{4})/; return Perf; })(jQuery, window.Perf || {});
JavaScript
(function($) { // TODO this is entire thing sucks $(function() { var searchMap = (function() { var searchSplit, searchMap = {}; if ( !location.search ){ return searchMap; } searchSplit = location.search.replace(/^\?/, "").split( /&|;/ ); for( var i = 0; i < searchSplit.length; i++ ) { var kv = searchSplit[i].split(/=/); searchMap[ kv[0] ] = kv[1]; } return searchMap; })(); $.get("../", searchMap, function(data) { $.each(data, function( i, avg ) { var tablename = avg.point + " " + avg.agent + " " + avg.agent_version + " " + avg.pathname, $table = $( "table > caption:contains(" + tablename + ")").parent(); if( !$table.length ) { $table = $( "<table></table>", { "data-pathname": avg.pathname, "data-point": avg.point, "data-agent": avg.agent, "data-agent-version": avg.agent_version }); $table.append( "<caption>" + tablename + "</caption>"); $table.append( "<thead><tr></tr></thead>" ); $table.append( "<tbody><tr></tr></tbody>" ); } // TODO assume time ordering in the data set var $heading = $table.find("thead > tr > th:contains(" + avg.day + ")"); if( !$heading.length ) { $heading = $("<th></th>", { text: avg.day, scope: "column" }); $table.find("thead > tr").append($heading); } var $rowHeading = $table.find("tbody > tr > th:contains(" + avg.point + ")" ), $row = $table.find( "tbody > tr" ); if( !$rowHeading.length ) { $rowHeading = $("<th></th>", { text: avg.point, scope: "row" }); $row.append( $rowHeading ); } $row.append( "<td>" + avg.avg_value + "</td>" ); $("#tables").append($table); }); $("#tables table").visualize({ type: "bar", width: 400, height: 400 }).appendTo("#graphs"); }); }); })(jQuery);
JavaScript
/* * mobile support unit tests */ (function( $ ) { $.testHelper = { excludeFileProtocol: function(callback){ var message = "Tests require script reload and cannot be run via file: protocol"; if (location.protocol == "file:") { test(message, function(){ ok(false, message); }); } else { callback(); } }, // TODO prevent test suite loads when the browser doesn't support push state // and push-state false is defined. setPushStateFor: function( libs ) { if( $.support.pushState && location.search.indexOf( "push-state" ) >= 0 ) { $.support.pushState = false; } $.each(libs, function(i, l) { $( "<script>", { src: l }).appendTo("head"); }); }, reloads: {}, reloadLib: function(libName){ if(this.reloads[libName] === undefined) { this.reloads[libName] = { lib: $("script[src$='" + libName + "']"), count: 0 }; } var lib = this.reloads[libName].lib.clone(), src = lib.attr('src'); //NOTE append "cache breaker" to force reload lib.attr('src', src + "?" + this.reloads[libName].count++); $("body").append(lib); }, rerunQunit: function(){ var self = this; QUnit.init(); $("script:not([src*='.\/'])").each(function(i, elem){ var src = elem.src.split("/"); self.reloadLib(src[src.length - 1]); }); QUnit.start(); }, alterExtend: function(extraExtension){ var extendFn = $.extend; $.extend = function(object, extension){ // NOTE extend the object as normal var result = extendFn.apply(this, arguments); // NOTE add custom extensions result = extendFn(result, extraExtension); return result; }; }, hideActivePageWhenComplete: function() { if( $('#qunit-testresult').length > 0 ) { $('.ui-page-active').css('display', 'none'); } else { setTimeout($.testHelper.hideActivePageWhenComplete, 500); } }, openPage: function(hash){ location.href = location.href.split('#')[0] + hash; }, sequence: function(fns, interval){ $.each(fns, function(i, fn){ setTimeout(fn, i * interval); }); }, pageSequence: function(fns){ this.eventSequence("pagechange", fns); }, eventSequence: function(event, fns, timedOut){ var fn = fns.shift(), self = this; if( fn === undefined ) return; // if a pagechange or defined event is never triggered // continue in the sequence to alert possible failures var warnTimer = setTimeout(function(){ self.eventSequence(event, fns, true); }, 2000); // bind the recursive call to the event $.mobile.pageContainer.one(event, function(){ clearTimeout(warnTimer); // Let the current stack unwind before we fire off the next item in the sequence. // TODO setTimeout(self.pageSequence, 0, [fns, event]); setTimeout(function(){ self.eventSequence(event, fns); }, 0); }); // invoke the function which should, in some fashion, // trigger the defined event fn(timedOut); }, decorate: function(opts){ var thisVal = opts.self || window; return function(){ var returnVal; opts.before && opts.before.apply(thisVal, arguments); returnVal = opts.fn.apply(thisVal, arguments); opts.after && opts.after.apply(thisVal, arguments); return returnVal; }; }, assertUrlLocation: function( args ) { var parts = $.mobile.path.parseUrl( location.href ), pathnameOnward = location.href.replace( parts.domain, "" ); if( $.support.pushState ) { same( pathnameOnward, args.hashOrPush || args.push, args.report ); } else { same( parts.hash, "#" + (args.hashOrPush || args.hash), args.report ); } } }; })(jQuery);
JavaScript
//quick & dirty theme switcher, written to potentially work as a bookmarklet (function($){ $.themeswitcher = function(){ if( $('[data-'+ $.mobile.ns +'-url=themeswitcher]').length ){ return; } var themesDir = 'http://jquerymobile.com/test/css/themes/', themes = ['default','valencia'], currentPage = $.mobile.activePage, menuPage = $( '<div data-'+ $.mobile.ns +'url="themeswitcher" data-'+ $.mobile.ns +'role=\'dialog\' data-'+ $.mobile.ns +'theme=\'a\'>' + '<div data-'+ $.mobile.ns +'role=\'header\' data-'+ $.mobile.ns +'theme=\'b\'>' + '<div class=\'ui-title\'>Switch Theme:</div>'+ '</div>'+ '<div data-'+ $.mobile.ns +'role=\'content\' data-'+ $.mobile.ns +'theme=\'c\'><ul data-'+ $.mobile.ns +'role=\'listview\' data-'+ $.mobile.ns +'inset=\'true\'></ul></div>'+ '</div>' ) .appendTo( $.mobile.pageContainer ), menu = menuPage.find('ul'); //menu items $.each(themes, function( i ){ $('<li><a href="#" data-'+ $.mobile.ns +'rel="back">' + themes[ i ].charAt(0).toUpperCase() + themes[ i ].substr(1) + '</a></li>') .bind("vclick", function(){ addTheme( themes[i] ); menuPage.dialog( "close" ); return false; }) .appendTo(menu); }); //remover, adder function addTheme(theme){ $('head').append( '<link rel=\'stylesheet\' href=\''+ themesDir + theme +'/\' />' ); } //create page, listview menuPage.page(); }; })(jQuery);
JavaScript
//thx @elroyjetson for the code example // When map page opens get location and display map $('.page-map').live("pagecreate", function() { //boston :) var lat = 42.35843, lng = -71.059773; //try to get GPS coords if( navigator.geolocation ) { //redirect function for successful location function gpsSuccess(pos){ if( pos.coords ){ lat = pos.coords.latitude; lng = pos.coords.longitude; } else{ lat = pos.latitude; lng = pos.longitude; } } function gpsFail(){ //Geo-location is supported, but we failed to get your coordinates. Workaround here perhaps? } navigator.geolocation.getCurrentPosition(gpsSuccess, gpsFail, {enableHighAccuracy:true, maximumAge: 300000}); } /* if not supported, you might attempt to use google loader for lat,long $.getScript('http://www.google.com/jsapi?key=YOURAPIKEY',function(){ lat = google.loader.ClientLocation.latitude; lng = google.loader.ClientLocation.longitude; }); */ var latlng = new google.maps.LatLng(lat, lng); var myOptions = { zoom: 10, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions); });
JavaScript
/* * jQuery Mobile Framework : scrollview plugin * Copyright (c) 2010 Adobe Systems Incorporated - Kin Blas (jblas@adobe.com) * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. * Note: Code is in draft form and is subject to change */ (function($,window,document,undefined){ jQuery.widget( "mobile.scrollview", jQuery.mobile.widget, { options: { fps: 60, // Frames per second in msecs. direction: null, // "x", "y", or null for both. scrollDuration: 2000, // Duration of the scrolling animation in msecs. overshootDuration: 250, // Duration of the overshoot animation in msecs. snapbackDuration: 500, // Duration of the snapback animation in msecs. moveThreshold: 10, // User must move this many pixels in any direction to trigger a scroll. moveIntervalThreshold: 150, // Time between mousemoves must not exceed this threshold. scrollMethod: "translate", // "translate", "position", "scroll" startEventName: "scrollstart", updateEventName: "scrollupdate", stopEventName: "scrollstop", eventType: $.support.touch ? "touch" : "mouse", showScrollBars: true, pagingEnabled: false, delayedClickSelector: "a,input,textarea,select,button,.ui-btn", delayedClickEnabled: false }, _makePositioned: function($ele) { if ($ele.css("position") == "static") $ele.css("position", "relative"); }, _create: function() { this._$clip = $(this.element).addClass("ui-scrollview-clip"); var $child = this._$clip.children(); if ($child.length > 1) { $child = this._$clip.wrapInner("<div></div>").children(); } this._$view = $child.addClass("ui-scrollview-view"); this._$clip.css("overflow", this.options.scrollMethod === "scroll" ? "scroll" : "hidden"); this._makePositioned(this._$clip); this._$view.css("overflow", "hidden"); // Turn off our faux scrollbars if we are using native scrolling // to position the view. this.options.showScrollBars = this.options.scrollMethod === "scroll" ? false : this.options.showScrollBars; // We really don't need this if we are using a translate transformation // for scrolling. We set it just in case the user wants to switch methods // on the fly. this._makePositioned(this._$view); this._$view.css({ left: 0, top: 0 }); this._sx = 0; this._sy = 0; var direction = this.options.direction; this._hTracker = (direction !== "y") ? new MomentumTracker(this.options) : null; this._vTracker = (direction !== "x") ? new MomentumTracker(this.options) : null; this._timerInterval = 1000/this.options.fps; this._timerID = 0; var self = this; this._timerCB = function(){ self._handleMomentumScroll(); }; this._addBehaviors(); }, _startMScroll: function(speedX, speedY) { this._stopMScroll(); this._showScrollBars(); var keepGoing = false; var duration = this.options.scrollDuration; this._$clip.trigger(this.options.startEventName); var ht = this._hTracker; if (ht) { var c = this._$clip.width(); var v = this._$view.width(); ht.start(this._sx, speedX, duration, (v > c) ? -(v - c) : 0, 0); keepGoing = !ht.done(); } var vt = this._vTracker; if (vt) { var c = this._$clip.height(); var v = this._$view.height(); vt.start(this._sy, speedY, duration, (v > c) ? -(v - c) : 0, 0); keepGoing = keepGoing || !vt.done(); } if (keepGoing) this._timerID = setTimeout(this._timerCB, this._timerInterval); else this._stopMScroll(); }, _stopMScroll: function() { if (this._timerID) { this._$clip.trigger(this.options.stopEventName); clearTimeout(this._timerID); } this._timerID = 0; if (this._vTracker) this._vTracker.reset(); if (this._hTracker) this._hTracker.reset(); this._hideScrollBars(); }, _handleMomentumScroll: function() { var keepGoing = false; var v = this._$view; var x = 0, y = 0; var vt = this._vTracker; if (vt) { vt.update(); y = vt.getPosition(); keepGoing = !vt.done(); } var ht = this._hTracker; if (ht) { ht.update(); x = ht.getPosition(); keepGoing = keepGoing || !ht.done(); } this._setScrollPosition(x, y); this._$clip.trigger(this.options.updateEventName, [ { x: x, y: y } ]); if (keepGoing) this._timerID = setTimeout(this._timerCB, this._timerInterval); else this._stopMScroll(); }, _setScrollPosition: function(x, y) { this._sx = x; this._sy = y; var $v = this._$view; var sm = this.options.scrollMethod; switch (sm) { case "translate": setElementTransform($v, x + "px", y + "px"); break; case "position": $v.css({left: x + "px", top: y + "px"}); break; case "scroll": var c = this._$clip[0]; c.scrollLeft = -x; c.scrollTop = -y; break; } var $vsb = this._$vScrollBar; var $hsb = this._$hScrollBar; if ($vsb) { var $sbt = $vsb.find(".ui-scrollbar-thumb"); if (sm === "translate") setElementTransform($sbt, "0px", -y/$v.height() * $sbt.parent().height() + "px"); else $sbt.css("top", -y/$v.height()*100 + "%"); } if ($hsb) { var $sbt = $hsb.find(".ui-scrollbar-thumb"); if (sm === "translate") setElementTransform($sbt, -x/$v.width() * $sbt.parent().width() + "px", "0px"); else $sbt.css("left", -x/$v.width()*100 + "%"); } }, scrollTo: function(x, y, duration) { this._stopMScroll(); if (!duration) return this._setScrollPosition(x, y); x = -x; y = -y; var self = this; var start = getCurrentTime(); var efunc = $.easing["easeOutQuad"]; var sx = this._sx; var sy = this._sy; var dx = x - sx; var dy = y - sy; var tfunc = function(){ var elapsed = getCurrentTime() - start; if (elapsed >= duration) { self._timerID = 0; self._setScrollPosition(x, y); } else { var ec = efunc(elapsed/duration, elapsed, 0, 1, duration); self._setScrollPosition(sx + (dx * ec), sy + (dy * ec)); self._timerID = setTimeout(tfunc, self._timerInterval); } }; this._timerID = setTimeout(tfunc, this._timerInterval); }, getScrollPosition: function() { return { x: -this._sx, y: -this._sy }; }, _getScrollHierarchy: function() { var svh = []; this._$clip.parents(".ui-scrollview-clip").each(function(){ var d = $(this).jqmData("scrollview"); if (d) svh.unshift(d); }); return svh; }, _getAncestorByDirection: function(dir) { var svh = this._getScrollHierarchy(); var n = svh.length; while (0 < n--) { var sv = svh[n]; var svdir = sv.options.direction; if (!svdir || svdir == dir) return sv; } return null; }, _handleDragStart: function(e, ex, ey) { // Stop any scrolling of elements in our parent hierarcy. $.each(this._getScrollHierarchy(),function(i,sv){ sv._stopMScroll(); }); this._stopMScroll(); var c = this._$clip; var v = this._$view; if (this.options.delayedClickEnabled) { this._$clickEle = $(e.target).closest(this.options.delayedClickSelector); } this._lastX = ex; this._lastY = ey; this._doSnapBackX = false; this._doSnapBackY = false; this._speedX = 0; this._speedY = 0; this._directionLock = ""; this._didDrag = false; if (this._hTracker) { var cw = parseInt(c.css("width"), 10); var vw = parseInt(v.css("width"), 10); this._maxX = cw - vw; if (this._maxX > 0) this._maxX = 0; if (this._$hScrollBar) this._$hScrollBar.find(".ui-scrollbar-thumb").css("width", (cw >= vw ? "100%" : Math.floor(cw/vw*100)+ "%")); } if (this._vTracker) { var ch = parseInt(c.css("height"), 10); var vh = parseInt(v.css("height"), 10); this._maxY = ch - vh; if (this._maxY > 0) this._maxY = 0; if (this._$vScrollBar) this._$vScrollBar.find(".ui-scrollbar-thumb").css("height", (ch >= vh ? "100%" : Math.floor(ch/vh*100)+ "%")); } var svdir = this.options.direction; this._pageDelta = 0; this._pageSize = 0; this._pagePos = 0; if (this.options.pagingEnabled && (svdir === "x" || svdir === "y")) { this._pageSize = svdir === "x" ? cw : ch; this._pagePos = svdir === "x" ? this._sx : this._sy; this._pagePos -= this._pagePos % this._pageSize; } this._lastMove = 0; this._enableTracking(); // If we're using mouse events, we need to prevent the default // behavior to suppress accidental selection of text, etc. We // can't do this on touch devices because it will disable the // generation of "click" events. // // XXX: We should test if this has an effect on links! - kin if (this.options.eventType == "mouse" || this.options.delayedClickEnabled) e.preventDefault(); e.stopPropagation(); }, _propagateDragMove: function(sv, e, ex, ey, dir) { this._hideScrollBars(); this._disableTracking(); sv._handleDragStart(e,ex,ey); sv._directionLock = dir; sv._didDrag = this._didDrag; }, _handleDragMove: function(e, ex, ey) { this._lastMove = getCurrentTime(); var v = this._$view; var dx = ex - this._lastX; var dy = ey - this._lastY; var svdir = this.options.direction; if (!this._directionLock) { var x = Math.abs(dx); var y = Math.abs(dy); var mt = this.options.moveThreshold; if (x < mt && y < mt) { return false; } var dir = null; var r = 0; if (x < y && (x/y) < 0.5) { dir = "y"; } else if (x > y && (y/x) < 0.5) { dir = "x"; } if (svdir && dir && svdir != dir) { // This scrollview can't handle the direction the user // is attempting to scroll. Find an ancestor scrollview // that can handle the request. var sv = this._getAncestorByDirection(dir); if (sv) { this._propagateDragMove(sv, e, ex, ey, dir); return false; } } this._directionLock = svdir ? svdir : (dir ? dir : "none"); } var newX = this._sx; var newY = this._sy; if (this._directionLock !== "y" && this._hTracker) { var x = this._sx; this._speedX = dx; newX = x + dx; // Simulate resistance. this._doSnapBackX = false; if (newX > 0 || newX < this._maxX) { if (this._directionLock === "x") { var sv = this._getAncestorByDirection("x"); if (sv) { this._setScrollPosition(newX > 0 ? 0 : this._maxX, newY); this._propagateDragMove(sv, e, ex, ey, dir); return false; } } newX = x + (dx/2); this._doSnapBackX = true; } } if (this._directionLock !== "x" && this._vTracker) { var y = this._sy; this._speedY = dy; newY = y + dy; // Simulate resistance. this._doSnapBackY = false; if (newY > 0 || newY < this._maxY) { if (this._directionLock === "y") { var sv = this._getAncestorByDirection("y"); if (sv) { this._setScrollPosition(newX, newY > 0 ? 0 : this._maxY); this._propagateDragMove(sv, e, ex, ey, dir); return false; } } newY = y + (dy/2); this._doSnapBackY = true; } } if (this.options.pagingEnabled && (svdir === "x" || svdir === "y")) { if (this._doSnapBackX || this._doSnapBackY) this._pageDelta = 0; else { var opos = this._pagePos; var cpos = svdir === "x" ? newX : newY; var delta = svdir === "x" ? dx : dy; this._pageDelta = (opos > cpos && delta < 0) ? this._pageSize : ((opos < cpos && delta > 0) ? -this._pageSize : 0); } } this._didDrag = true; this._lastX = ex; this._lastY = ey; this._setScrollPosition(newX, newY); this._showScrollBars(); // Call preventDefault() to prevent touch devices from // scrolling the main window. // e.preventDefault(); return false; }, _handleDragStop: function(e) { var l = this._lastMove; var t = getCurrentTime(); var doScroll = l && (t - l) <= this.options.moveIntervalThreshold; var sx = (this._hTracker && this._speedX && doScroll) ? this._speedX : (this._doSnapBackX ? 1 : 0); var sy = (this._vTracker && this._speedY && doScroll) ? this._speedY : (this._doSnapBackY ? 1 : 0); var svdir = this.options.direction; if (this.options.pagingEnabled && (svdir === "x" || svdir === "y") && !this._doSnapBackX && !this._doSnapBackY) { var x = this._sx; var y = this._sy; if (svdir === "x") x = -this._pagePos + this._pageDelta; else y = -this._pagePos + this._pageDelta; this.scrollTo(x, y, this.options.snapbackDuration); } else if (sx || sy) this._startMScroll(sx, sy); else this._hideScrollBars(); this._disableTracking(); if (!this._didDrag && this.options.delayedClickEnabled && this._$clickEle.length) { this._$clickEle .trigger("mousedown") //.trigger("focus") .trigger("mouseup") .trigger("click"); } // If a view scrolled, then we need to absorb // the event so that links etc, underneath our // cursor/finger don't fire. return this._didDrag ? false : undefined; }, _enableTracking: function() { $(document).bind(this._dragMoveEvt, this._dragMoveCB); $(document).bind(this._dragStopEvt, this._dragStopCB); }, _disableTracking: function() { $(document).unbind(this._dragMoveEvt, this._dragMoveCB); $(document).unbind(this._dragStopEvt, this._dragStopCB); }, _showScrollBars: function() { var vclass = "ui-scrollbar-visible"; if (this._$vScrollBar) this._$vScrollBar.addClass(vclass); if (this._$hScrollBar) this._$hScrollBar.addClass(vclass); }, _hideScrollBars: function() { var vclass = "ui-scrollbar-visible"; if (this._$vScrollBar) this._$vScrollBar.removeClass(vclass); if (this._$hScrollBar) this._$hScrollBar.removeClass(vclass); }, _addBehaviors: function() { var self = this; if (this.options.eventType === "mouse") { this._dragStartEvt = "mousedown"; this._dragStartCB = function(e){ return self._handleDragStart(e, e.clientX, e.clientY); }; this._dragMoveEvt = "mousemove"; this._dragMoveCB = function(e){ return self._handleDragMove(e, e.clientX, e.clientY); }; this._dragStopEvt = "mouseup"; this._dragStopCB = function(e){ return self._handleDragStop(e); }; } else // "touch" { this._dragStartEvt = "touchstart"; this._dragStartCB = function(e) { var t = e.originalEvent.targetTouches[0]; return self._handleDragStart(e, t.pageX, t.pageY); }; this._dragMoveEvt = "touchmove"; this._dragMoveCB = function(e) { var t = e.originalEvent.targetTouches[0]; return self._handleDragMove(e, t.pageX, t.pageY); }; this._dragStopEvt = "touchend"; this._dragStopCB = function(e){ return self._handleDragStop(e); }; } this._$view.bind(this._dragStartEvt, this._dragStartCB); if (this.options.showScrollBars) { var $c = this._$clip; var prefix = "<div class=\"ui-scrollbar ui-scrollbar-"; var suffix = "\"><div class=\"ui-scrollbar-track\"><div class=\"ui-scrollbar-thumb\"></div></div></div>"; if (this._vTracker) { $c.append(prefix + "y" + suffix); this._$vScrollBar = $c.children(".ui-scrollbar-y"); } if (this._hTracker) { $c.append(prefix + "x" + suffix); this._$hScrollBar = $c.children(".ui-scrollbar-x"); } } } }); function setElementTransform($ele, x, y) { var v = "translate3d(" + x + "," + y + ", 0px)"; $ele.css({ "-moz-transform": v, "-webkit-transform": v, "transform": v }); } function MomentumTracker(options) { this.options = $.extend({}, options); this.easing = "easeOutQuad"; this.reset(); } var tstates = { scrolling: 0, overshot: 1, snapback: 2, done: 3 }; function getCurrentTime() { return (new Date()).getTime(); } $.extend(MomentumTracker.prototype, { start: function(pos, speed, duration, minPos, maxPos) { this.state = (speed != 0) ? ((pos < minPos || pos > maxPos) ? tstates.snapback : tstates.scrolling) : tstates.done; this.pos = pos; this.speed = speed; this.duration = (this.state == tstates.snapback) ? this.options.snapbackDuration : duration; this.minPos = minPos; this.maxPos = maxPos; this.fromPos = (this.state == tstates.snapback) ? this.pos : 0; this.toPos = (this.state == tstates.snapback) ? ((this.pos < this.minPos) ? this.minPos : this.maxPos) : 0; this.startTime = getCurrentTime(); }, reset: function() { this.state = tstates.done; this.pos = 0; this.speed = 0; this.minPos = 0; this.maxPos = 0; this.duration = 0; }, update: function() { var state = this.state; if (state == tstates.done) return this.pos; var duration = this.duration; var elapsed = getCurrentTime() - this.startTime; elapsed = elapsed > duration ? duration : elapsed; if (state == tstates.scrolling || state == tstates.overshot) { var dx = this.speed * (1 - $.easing[this.easing](elapsed/duration, elapsed, 0, 1, duration)); var x = this.pos + dx; var didOverShoot = (state == tstates.scrolling) && (x < this.minPos || x > this.maxPos); if (didOverShoot) x = (x < this.minPos) ? this.minPos : this.maxPos; this.pos = x; if (state == tstates.overshot) { if (elapsed >= duration) { this.state = tstates.snapback; this.fromPos = this.pos; this.toPos = (x < this.minPos) ? this.minPos : this.maxPos; this.duration = this.options.snapbackDuration; this.startTime = getCurrentTime(); elapsed = 0; } } else if (state == tstates.scrolling) { if (didOverShoot) { this.state = tstates.overshot; this.speed = dx / 2; this.duration = this.options.overshootDuration; this.startTime = getCurrentTime(); } else if (elapsed >= duration) this.state = tstates.done; } } else if (state == tstates.snapback) { if (elapsed >= duration) { this.pos = this.toPos; this.state = tstates.done; } else this.pos = this.fromPos + ((this.toPos - this.fromPos) * $.easing[this.easing](elapsed/duration, elapsed, 0, 1, duration)); } return this.pos; }, done: function() { return this.state == tstates.done; }, getPosition: function(){ return this.pos; } }); jQuery.widget( "mobile.scrolllistview", jQuery.mobile.scrollview, { options: { direction: "y" }, _create: function() { $.mobile.scrollview.prototype._create.call(this); // Cache the dividers so we don't have to search for them everytime the // view is scrolled. // // XXX: Note that we need to update this cache if we ever support lists // that can dynamically update their content. this._$dividers = this._$view.find(":jqmData(role='list-divider')"); this._lastDivider = null; }, _setScrollPosition: function(x, y) { // Let the view scroll like it normally does. $.mobile.scrollview.prototype._setScrollPosition.call(this, x, y); y = -y; // Find the dividers for the list. var $divs = this._$dividers; var cnt = $divs.length; var d = null; var dy = 0; var nd = null; for (var i = 0; i < cnt; i++) { nd = $divs.get(i); var t = nd.offsetTop; if (y >= t) { d = nd; dy = t; } else if (d) break; } // If we found a divider to move position it at the top of the // clip view. if (d) { var h = d.offsetHeight; var mxy = (d != nd) ? nd.offsetTop : (this._$view.get(0).offsetHeight); if (y + h >= mxy) y = (mxy - h) - dy; else y = y - dy; // XXX: Need to convert this over to using $().css() and supporting the non-transform case. var ld = this._lastDivider; if (ld && d != ld) { setElementTransform($(ld), 0, 0); } setElementTransform($(d), 0, y + "px"); this._lastDivider = d; } } }); })(jQuery,window,document); // End Component
JavaScript
function ResizePageContentHeight(page) { var $page = $(page), $content = $page.children( ".ui-content" ), hh = $page.children( ".ui-header" ).outerHeight() || 0, fh = $page.children( ".ui-footer" ).outerHeight() || 0, pt = parseFloat($content.css( "padding-top" )), pb = parseFloat($content.css( "padding-bottom" )), wh = window.innerHeight; $content.height(wh - (hh + fh) - (pt + pb)); } $( ":jqmData(role='page')" ).live( "pageshow", function(event) { var $page = $( this ); // For the demos that use this script, we want the content area of each // page to be scrollable in the 'y' direction. $page.find( ".ui-content" ).attr( "data-" + $.mobile.ns + "scroll", "y" ); // This code that looks for [data-scroll] will eventually be folded // into the jqm page processing code when scrollview support is "official" // instead of "experimental". $page.find( ":jqmData(scroll):not(.ui-scrollview-clip)" ).each(function () { var $this = $( this ); // XXX: Remove this check for ui-scrolllistview once we've // integrated list divider support into the main scrollview class. if ( $this.hasClass( "ui-scrolllistview" ) ) { $this.scrolllistview(); } else { var st = $this.jqmData( "scroll" ) + "", paging = st && st.search(/^[xy]p$/) != -1, dir = st && st.search(/^[xy]/) != -1 ? st.charAt(0) : null, opts = { direction: dir || undefined, paging: paging || undefined, scrollMethod: $this.jqmData("scroll-method") || undefined }; $this.scrollview( opts ); } }); // For the demos, we want to make sure the page being shown has a content // area that is sized to fit completely within the viewport. This should // also handle the case where pages are loaded dynamically. ResizePageContentHeight( event.target ); }); $( window ).bind( "orientationchange", function( event ) { ResizePageContentHeight( $( ".ui-page" ) ); });
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
/* * Copy of http://github.com/nje/jquery-tmpl/raw/master/jquery.tmpl.js at f827fb68417bc14ab9f6ae889421d5fea4cb2859 * jQuery Templating Plugin * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. */ (function( jQuery, undefined ){ var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = []; function newTmplItem( options, parentItem, fn, data ) { // Returns a template item data structure for a new rendered instance of a template (a 'template item'). // The content field is a hierarchical array of strings and nested items (to be // removed and replaced by nodes field of dom elements, once inserted in DOM). var newItem = { data: data || (parentItem ? parentItem.data : {}), _wrap: parentItem ? parentItem._wrap : null, tmpl: null, parent: parentItem || null, nodes: [], calls: tiCalls, nest: tiNest, wrap: tiWrap, html: tiHtml, update: tiUpdate }; if ( options ) { jQuery.extend( newItem, options, { nodes: [], parent: parentItem } ); } if ( fn ) { // Build the hierarchical content to be used during insertion into DOM newItem.tmpl = fn; newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem ); newItem.key = ++itemKey; // Keep track of new template item, until it is stored as jQuery Data on DOM element (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem; } return newItem; } // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core). jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems, parent = this.length === 1 && this[0].parentNode; appendToTmplItems = newTmplItems || {}; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); ret = this; } else { for ( i = 0, l = insert.length; i < l; i++ ) { cloneIndex = i; elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } cloneIndex = 0; ret = this.pushStack( ret, name, insert.selector ); } tmplItems = appendToTmplItems; appendToTmplItems = null; jQuery.tmpl.complete( tmplItems ); return ret; }; }); jQuery.fn.extend({ // Use first wrapped element as template markup. // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( data, options, parentItem ) { return jQuery.tmpl( this[0], data, options, parentItem ); }, // Find which rendered template item the first wrapped DOM element belongs to tmplItem: function() { return jQuery.tmplItem( this[0] ); }, // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template. template: function( name ) { return jQuery.template( name, this[0] ); }, domManip: function( args, table, callback, options ) { // This appears to be a bug in the appendTo, etc. implementation // it should be doing .call() instead of .apply(). See #6227 if ( args[0] && args[0].nodeType ) { var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem; while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {} if ( argsLength > 1 ) { dmArgs[0] = [jQuery.makeArray( args )]; } if ( tmplItem && cloneIndex ) { dmArgs[2] = function( fragClone ) { // Handler called by oldManip when rendered template has been inserted into DOM. jQuery.tmpl.afterManip( this, fragClone, callback ); }; } oldManip.apply( this, dmArgs ); } else { oldManip.apply( this, arguments ); } cloneIndex = 0; if ( !appendToTmplItems ) { jQuery.tmpl.complete( newTmplItems ); } return this; } }); jQuery.extend({ // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( tmpl, data, options, parentItem ) { var ret, topLevel = !parentItem; if ( topLevel ) { // This is a top-level tmpl call (not from a nested template using {{tmpl}}) parentItem = topTmplItem; tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level } else if ( !tmpl ) { // The template item is already associated with DOM - this is a refresh. // Re-evaluate rendered template for the parentItem tmpl = parentItem.tmpl; newTmplItems[parentItem.key] = parentItem; parentItem.nodes = []; if ( parentItem.wrapped ) { updateWrapped( parentItem, parentItem.wrapped ); } // Rebuild, without creating a new template item return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); } if ( !tmpl ) { return []; // Could throw... } if ( typeof data === "function" ) { data = data.call( parentItem || {} ); } if ( options && options.wrapped ) { updateWrapped( options, options.wrapped ); } ret = jQuery.isArray( data ) ? jQuery.map( data, function( dataItem ) { return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; }) : [ newTmplItem( options, parentItem, tmpl, data ) ]; return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; }, // Return rendered template item for an element. tmplItem: function( elem ) { var tmplItem; if ( elem instanceof jQuery ) { elem = elem[0]; } while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} return tmplItem || topTmplItem; }, // Set: // Use $.template( name, tmpl ) to cache a named template, // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc. // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration. // Get: // Use $.template( name ) to access a cached template. // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString ) // will return the compiled template, without adding a name reference. // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent // to $.template( null, templateString ) template: function( name, tmpl ) { if (tmpl) { // Compile template and associate with name if ( typeof tmpl === "string" ) { // This is an HTML string being passed directly in. tmpl = buildTmplFn( tmpl ) } else if ( tmpl instanceof jQuery ) { tmpl = tmpl[0] || {}; } if ( tmpl.nodeType ) { // If this is a template block, use cached copy, or generate tmpl function and cache. tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML )); } return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl; } // Return named compiled template return name ? (typeof name !== "string" ? jQuery.template( null, name ): (jQuery.template[name] || // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; }, encode: function( text ) { // Do HTML encoding replacing < > & and ' and " by corresponding entities. return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;"); } }); jQuery.extend( jQuery.tmpl, { tag: { "tmpl": { _default: { $2: "null" }, open: "if($notnull_1){_=_.concat($item.nest($1,$2));}" // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions) // This means that {{tmpl foo}} treats foo as a template (which IS a function). // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}. }, "wrap": { _default: { $2: "null" }, open: "$item.calls(_,$1,$2);_=[];", close: "call=$item.calls();_=call._.concat($item.wrap(call,_));" }, "each": { _default: { $2: "$index, $value" }, open: "if($notnull_1){$.each($1a,function($2){with(this){", close: "}});}" }, "if": { open: "if(($notnull_1) && $1a){", close: "}" }, "else": { _default: { $1: "true" }, open: "}else if(($notnull_1) && $1a){" }, "html": { // Unecoded expression evaluation. open: "if($notnull_1){_.push($1a);}" }, "=": { // Encoded expression evaluation. Abbreviated form is ${}. _default: { $1: "$data" }, open: "if($notnull_1){_.push($.encode($1a));}" }, "!": { // Comment tag. Skipped by parser open: "" } }, // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events complete: function( items ) { newTmplItems = {}; }, // Call this from code which overrides domManip, or equivalent // Manage cloning/storing template items etc. afterManip: function afterManip( elem, fragClone, callback ) { // Provides cloned fragment ready for fixup prior to and after insertion into DOM var content = fragClone.nodeType === 11 ? jQuery.makeArray(fragClone.childNodes) : fragClone.nodeType === 1 ? [fragClone] : []; // Return fragment to original caller (e.g. append) for DOM insertion callback.call( elem, fragClone ); // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data. storeTmplItems( content ); cloneIndex++; } }); //========================== Private helper functions, used by code above ========================== function build( tmplItem, nested, content ) { // Convert hierarchical content into flat string array // and finally return array of fragments ready for DOM insertion var frag, ret = content ? jQuery.map( content, function( item ) { return (typeof item === "string") ? // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM. (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) : // This is a child template item. Build nested template. build( item, tmplItem, item._ctnt ); }) : // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. tmplItem; if ( nested ) { return ret; } // top-level template ret = ret.join(""); // Support templates which have initial or final text nodes, or consist only of text // Also support HTML entities within the HTML markup. ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) { frag = jQuery( middle ).get(); storeTmplItems( frag ); if ( before ) { frag = unencode( before ).concat(frag); } if ( after ) { frag = frag.concat(unencode( after )); } }); return frag ? frag : unencode( ret ); } function unencode( text ) { // Use createElement, since createTextNode will not render HTML entities correctly var el = document.createElement( "div" ); el.innerHTML = text; return jQuery.makeArray(el.childNodes); } // Generate a reusable function that will serve to render a template against data function buildTmplFn( markup ) { return new Function("jQuery","$item", "var $=jQuery,call,_=[],$data=$item.data;" + // Introduce the data as local variables using with(){} "with($data){_.push('" + // Convert the template into pure JavaScript jQuery.trim(markup) .replace( /([\\'])/g, "\\$1" ) .replace( /[\r\t\n]/g, " " ) .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" ) .replace( /\{\{(\/?)(\w+|.)(?:\(((?:.(?!\}\}))*?)?\))?(?:\s+(.*?)?)?(\((.*?)\))?\s*\}\}/g, function( all, slash, type, fnargs, target, parens, args ) { var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect; if ( !tag ) { throw "Template command not found: " + type; } def = tag._default || []; if ( parens && !/\w$/.test(target)) { target += parens; parens = ""; } if ( target ) { target = unescape( target ); args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : ""); // Support for target being things like a.toLowerCase(); // In that case don't call with template item as 'this' pointer. Just evaluate... expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target; exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))"; } else { exprAutoFnDetect = expr = def.$1 || "null"; } fnargs = unescape( fnargs ); return "');" + tag[ slash ? "close" : "open" ] .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" ) .split( "$1a" ).join( exprAutoFnDetect ) .split( "$1" ).join( expr ) .split( "$2" ).join( fnargs ? fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) { params = params ? ("," + params + ")") : (parens ? ")" : ""); return params ? ("(" + name + ").call($item" + params) : all; }) : (def.$2||"") ) + "_.push('"; }) + "');}return _;" ); } function updateWrapped( options, wrapped ) { // Build the wrapped content. options._wrap = build( options, true, // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string. jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()] ).join(""); } function unescape( args ) { return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null; } function outerHtml( elem ) { var div = document.createElement("div"); div.appendChild( elem.cloneNode(true) ); return div.innerHTML; } // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance. function storeTmplItems( content ) { var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m; for ( i = 0, l = content.length; i < l; i++ ) { if ( (elem = content[i]).nodeType !== 1 ) { continue; } elems = elem.getElementsByTagName("*"); for ( m = elems.length - 1; m >= 0; m-- ) { processItemKey( elems[m] ); } processItemKey( elem ); } function processItemKey( el ) { var pntKey, pntNode = el, pntItem, tmplItem, key; // Ensure that each rendered template inserted into the DOM has its own template item, if ( (key = el.getAttribute( tmplItmAtt ))) { while ((pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { } if ( pntKey !== key ) { // The next ancestor with a _tmplitem expando is on a different key than this one. // So this is a top-level element within this template item pntNode = pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0); if ( !(tmplItem = newTmplItems[key]) ) { // The item is for wrapped content, and was copied from the temporary parent wrappedItem. tmplItem = wrappedItems[key]; tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true ); tmplItem.key = ++itemKey; newTmplItems[itemKey] = tmplItem; } if ( cloneIndex ) { cloneTmplItem( key ); } } el.removeAttribute( tmplItmAtt ); } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) { // This was a rendered element, cloned during append or appendTo etc. // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem. cloneTmplItem( tmplItem.key ); newTmplItems[tmplItem.key] = tmplItem; pntNode = jQuery.data( el.parentNode, "tmplItem" ); pntNode = pntNode ? pntNode.key : 0; } if ( tmplItem ) { pntItem = tmplItem; // Find the template item of the parent element. // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string) while ( pntItem && pntItem.key != pntNode ) { // Add this element as a top-level node for this rendered template item, as well as for any // ancestor items between this item and the item of its parent element pntItem.nodes.push( el ); pntItem = pntItem.parent; } // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering... delete tmplItem._ctnt; delete tmplItem._wrap; // Store template item as jQuery data on the element jQuery.data( el, "tmplItem", tmplItem ); } function cloneTmplItem( key ) { key = key + keySuffix; tmplItem = newClonedItems[key] = (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true )); } } } //---- Helper functions for template item ---- function tiCalls( content, tmpl, data, options ) { if ( !content ) { return stack.pop(); } stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options }); } function tiNest( tmpl, data, options ) { // nested template, using {{tmpl}} tag return jQuery.tmpl( jQuery.template( tmpl ), data, options, this ); } function tiWrap( call, wrapped ) { // nested template, using {{wrap}} tag var options = call.options || {}; options.wrapped = wrapped; // Apply the template, which may incorporate wrapped content, return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item ); } function tiHtml( filter, textOnly ) { var wrapped = this._wrap; return jQuery.map( jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ), function(e) { return textOnly ? e.innerText || e.textContent : e.outerHTML || outerHtml(e); }); } function tiUpdate() { var coll = this.nodes; jQuery.tmpl( null, null, null, this).insertBefore( coll[0] ); jQuery( coll ).remove(); } })( jQuery );
JavaScript
$(function() { var symbols = { "USD": "$", "EUR": "&euro;", "GBP": "&pound;", "Miles": "m", "Kilometer": "km", "inch": "\"", "centimeter": "cm" }; function list() { var ul = $( "#conversions" ).empty(), ulEdit = $( "#edit-conversions" ).empty(); $.each( all, function( index, conversion ) { // if last update was less then a minute ago, don't update if ( conversion.type === "currency" && !conversion.rate || conversion.updated && conversion.updated + 60000 < +new Date) { var self = conversion; var url = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + conversion.from + conversion.to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&diagnostics=true&callback=?"; $.getJSON( url, function( result ) { self.rate = parseFloat( result.query.results.row.rate ); $( "#term" ).keyup(); self.updated = +new Date; conversions.store(); }); } $( "#conversion-field" ).tmpl( conversion, { symbols: symbols }).appendTo( ul ); $( "#conversion-edit-field" ).tmpl( conversion, { symbols: symbols }).appendTo( ulEdit ); }); ul.add(ulEdit).listview("refresh"); $( "#term" ).keyup(); } var all = conversions.all(); $( "#term" ).keyup(function() { var value = this.value; $.each( all, function( index, conversion ) { $( "#" + conversion.from + conversion.to ).text( conversion.rate ? Math.ceil( value * conversion.rate * 100 ) / 100 : "Rate not available, yet." ); }); }).focus(); list(); $( "form" ).submit(function() { $( "#term" ).blur(); return false; }); $( "#add" ).click(function() { all.push({ type: "currency", from: $( "#currency-options-from" ).val(), to: $( "#currency-options-to" ).val() }); conversions.store(); list(); }); $( "#clear" ).click(function() { conversions.clear(); list(); return false; }); $( "#restore" ).click(function() { conversions.restore(); list(); return false; }); $( "#edit-conversions" ).click(function( event ) { var target = $( event.target ).closest( ".deletebutton" ); if ( target.length ) { conversions.remove( target.prev( "label" ).attr( "for" ) ); list(); } return false; }); });
JavaScript
(function() { var defaults = [ { type: "currency", from: "USD", to: "EUR" }, { type: "currency", from: "GBP", to: "EUR" } // TODO add back in as defaults once its possible to add other conversions, not just currencies /*, { type: "distance", from: "Miles", to: "Kilometer", rate: 1.609344 }, { type: "distance", from: "inch", to: "centimeter", rate: 2.54 }*/ ]; // TODO fallback to whatever else when localStorage isn't available function get() { return JSON.parse( localStorage.getItem( "conversions" ) ); } function set( value ) { localStorage.setItem( "conversions", JSON.stringify( value ) ); } var conversions = get( "conversions" ); if ( !conversions ) { conversions = defaults.slice(); set( conversions ); } window.conversions = { store: function() { set( conversions ); }, all: function() { return conversions; }, clear: function() { conversions.length = 0; this.store(); }, restore: function() { conversions.length = 0; $.extend( conversions, defaults ); this.store(); }, remove: function( tofrom ) { $.each( conversions, function( index, conversion ) { if ( ( conversion.from + conversion.to ) === tofrom ) { conversions.splice( index, 1 ); return false; } }); this.store(); } }; })();
JavaScript
/* * StringBuffer class */ function StringBuffer() { this.buffer = []; } StringBuffer.prototype.append = function append (string) { this.buffer.push(string); return this; }; StringBuffer.prototype.toString = function toString () { return this.buffer.join(""); }; /* * Strip html tags */ function stripTags (str) { return str.replace(/<[^>].*?>/g,""); } /* * Display json with better look */ function formatJson (str) { var tab = 0; var buf = new StringBuffer(); for (var i = 0; i < str.length; i++) { var char = str.charAt(i); if (char == '{' || char == '[') { tab++; char = char + "\n"; for (var j = 0; j < tab; j++) char = char + "\t"; } if (char == '}' || char == ']') { tab--; for (var j = 0; j < tab; j++) char = "\t" + char; char = "\n" + char; } if (char == ',') { char = char + "\n"; for (var j = 0; j < tab; j++) char = char + "\t"; } buf.append(char); } return buf.toString(); }
JavaScript
/*! * jQuery Mobile v1.0b2 * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ /*! * jQuery UI Widget @VERSION * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function( $, undefined ) { // jQuery 1.4+ if ( $.cleanData ) { var _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { $( elem ).triggerHandler( "remove" ); } _cleanData( elems ); }; } else { var _remove = $.fn.remove; $.fn.remove = function( selector, keepData ) { return this.each(function() { if ( !keepData ) { if ( !selector || $.filter( selector, [ this ] ).length ) { $( "*", this ).add( [ this ] ).each(function() { $( this ).triggerHandler( "remove" ); }); } } return _remove.call( $(this), selector, keepData ); }); }; } $.widget = function( name, base, prototype ) { var namespace = name.split( "." )[ 0 ], fullName; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName ] = function( elem ) { return !!$.data( elem, name ); }; $[ namespace ] = $[ namespace ] || {}; $[ namespace ][ name ] = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; var basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from // $.each( basePrototype, function( key, val ) { // if ( $.isPlainObject(val) ) { // basePrototype[ key ] = $.extend( {}, val ); // } // }); basePrototype.options = $.extend( true, {}, basePrototype.options ); $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { namespace: namespace, widgetName: name, widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, widgetBaseClass: fullName }, prototype ); $.widget.bridge( name, $[ namespace ][ name ] ); }; $.widget.bridge = function( name, object ) { $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.charAt( 0 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $.data( this, name ); if ( !instance ) { throw "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'"; } if ( !$.isFunction( instance[options] ) ) { throw "no such method '" + options + "' for " + name + " widget instance"; } var methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, name ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, name, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", options: { disabled: false }, _createWidget: function( options, element ) { // $.widget.bridge stores the plugin instance, but we do it anyway // so that it's stored even before the _create function runs $.data( element, this.widgetName, this ); this.element = $( element ); this.options = $.extend( true, {}, this.options, this._getCreateOptions(), options ); var self = this; this.element.bind( "remove." + this.widgetName, function() { self.destroy(); }); this._create(); this._trigger( "create" ); this._init(); }, _getCreateOptions: function() { var options = {}; if ( $.metadata ) { options = $.metadata.get( element )[ this.widgetName ]; } return options; }, _create: function() {}, _init: function() {}, destroy: function() { this.element .unbind( "." + this.widgetName ) .removeData( this.widgetName ); this.widget() .unbind( "." + this.widgetName ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetBaseClass + "-disabled " + "ui-state-disabled" ); }, widget: function() { return this.element; }, option: function( key, value ) { var options = key; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.extend( {}, this.options ); } if (typeof key === "string" ) { if ( value === undefined ) { return this.options[ key ]; } options = {}; options[ key ] = value; } this._setOptions( options ); return this; }, _setOptions: function( options ) { var self = this; $.each( options, function( key, value ) { self._setOption( key, value ); }); return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() [ value ? "addClass" : "removeClass"]( this.widgetBaseClass + "-disabled" + " " + "ui-state-disabled" ) .attr( "aria-disabled", value ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _trigger: function( type, event, data ) { var callback = this.options[ type ]; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); data = data || {}; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( event.originalEvent ) { for ( var i = $.event.props.length, prop; i; ) { prop = $.event.props[ --i ]; event[ prop ] = event.originalEvent[ prop ]; } } this.element.trigger( event, data ); return !( $.isFunction(callback) && callback.call( this.element[0], event, data ) === false || event.isDefaultPrevented() ); } }; })( jQuery ); /* * jQuery Mobile Framework : widget factory extentions for mobile * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.widget", { _getCreateOptions: function() { var elem = this.element, options = {}; $.each( this.options, function( option ) { var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) { return "-" + c.toLowerCase(); }) ); if ( value !== undefined ) { options[ option ] = value; } }); return options; } }); })( jQuery ); /* * jQuery Mobile Framework : resolution and CSS media query related helpers and behavior * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var $window = $( window ), $html = $( "html" ); /* $.mobile.media method: pass a CSS media type or query and get a bool return note: this feature relies on actual media query support for media queries, though types will work most anywhere examples: $.mobile.media('screen') //>> tests for screen media type $.mobile.media('screen and (min-width: 480px)') //>> tests for screen media type with window width > 480px $.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') //>> tests for webkit 2x pixel ratio (iPhone 4) */ $.mobile.media = (function() { // TODO: use window.matchMedia once at least one UA implements it var cache = {}, testDiv = $( "<div id='jquery-mediatest'>" ), fakeBody = $( "<body>" ).append( testDiv ); return function( query ) { if ( !( query in cache ) ) { var styleBlock = document.createElement( "style" ), cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }"; //must set type for IE! styleBlock.type = "text/css"; if ( styleBlock.styleSheet ){ styleBlock.styleSheet.cssText = cssrule; } else { styleBlock.appendChild( document.createTextNode(cssrule) ); } $html.prepend( fakeBody ).prepend( styleBlock ); cache[ query ] = testDiv.css( "position" ) === "absolute"; fakeBody.add( styleBlock ).remove(); } return cache[ query ]; }; })(); })(jQuery);/* * jQuery Mobile Framework : support tests * Copyright (c) jQuery Project * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. */ (function( $, undefined ) { var fakeBody = $( "<body>" ).prependTo( "html" ), fbCSS = fakeBody[ 0 ].style, vendors = [ "webkit", "moz", "o" ], webos = "palmGetResource" in window, //only used to rule out scrollTop bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB // thx Modernizr function propExists( prop ) { var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " ); for ( var v in props ){ if ( fbCSS[ v ] !== undefined ) { return true; } } } // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting ) function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/", base = $( "head base" ), fauxEle = null, href = "", link, rebase; if ( !base.length ) { base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" ); } else { href = base.attr( "href" ); } link = $( "<a href='testurl'></a>" ).prependTo( fakeBody ); rebase = link[ 0 ].href; base[ 0 ].href = href ? href : location.pathname; if ( fauxEle ) { fauxEle.remove(); } return rebase.indexOf( fauxBase ) === 0; } // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 // allows for inclusion of IE 6+, including Windows Mobile 7 $.mobile.browser = {}; $.mobile.browser.ie = (function() { var v = 3, div = document.createElement( "div" ), a = div.all || []; while ( div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->", a[ 0 ] ); return v > 4 ? v : !v; })(); $.extend( $.support, { orientation: "orientation" in window, touch: "ontouchend" in document, cssTransitions: "WebKitTransitionEvent" in window, pushState: !!history.pushState, mediaquery: $.mobile.media( "only all" ), cssPseudoElement: !!propExists( "content" ), boxShadow: !!propExists( "boxShadow" ) && !bb, scrollTop: ( "pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ] ) && !webos, dynamicBaseTag: baseTagTest(), // TODO: This is a weak test. We may want to beef this up later. eventCapture: "addEventListener" in document }); fakeBody.remove(); // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian) // or that generally work better browsing in regular http for full page refreshes (Opera Mini) // Note: This detection below is used as a last resort. // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible var nokiaLTE7_3 = (function(){ var ua = window.navigator.userAgent; //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older return ua.indexOf( "Nokia" ) > -1 && ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) && ua.indexOf( "AppleWebKit" ) > -1 && ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ ); })(); $.mobile.ajaxBlacklist = // BlackBerry browsers, pre-webkit window.blackberry && !window.WebKitPoint || // Opera Mini window.operamini && Object.prototype.toString.call( window.operamini ) === "[object OperaMini]" || // Symbian webkits pre 7.3 nokiaLTE7_3; // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices // to render the stylesheets when they're referenced before this script, as we'd recommend doing. // This simply reappends the CSS in place, which for some reason makes it apply if ( nokiaLTE7_3 ) { $(function() { $( "head link[rel=stylesheet]" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" ); }); } // For ruling out shadows via css if ( !$.support.boxShadow ) { $( "html" ).addClass( "ui-mobile-nosupport-boxshadow" ); } })( jQuery );/* * jQuery Mobile Framework : "mouse" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ // This plugin is an experiment for abstracting away the touch and mouse // events so that developers don't have to worry about which method of input // the device their document is loaded on supports. // // The idea here is to allow the developer to register listeners for the // basic mouse events, such as mousedown, mousemove, mouseup, and click, // and the plugin will take care of registering the correct listeners // behind the scenes to invoke the listener at the fastest possible time // for that device, while still retaining the order of event firing in // the traditional mouse environment, should multiple handlers be registered // on the same element for different events. // // The current version exposes the following virtual events to jQuery bind methods: // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel" (function( $, window, document, undefined ) { var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ), touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ), activeDocHandlers = {}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = $.support.eventCapture, $document = $( document ), nextTouchID = 1, lastTouchID = 0; $.vmouse = { moveDistanceThreshold: 10, clickDistanceThreshold: 10, resetTimerDuration: 1500 }; function getNativeEvent( event ) { while ( event && typeof event.originalEvent !== "undefined" ) { event = event.originalEvent; } return event; } function createVirtualEvent( event, eventType ) { var t = event.type, oe, props, ne, prop, ct, touch, i, j; event = $.Event(event); event.type = eventType; oe = event.originalEvent; props = $.event.props; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( oe ) { for ( i = props.length, prop; i; ) { prop = props[ --i ]; event[ prop ] = oe[ prop ]; } } if ( t.search(/^touch/) !== -1 ) { ne = getNativeEvent( oe ); t = ne.touches; ct = ne.changedTouches; touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined ); if ( touch ) { for ( j = 0, len = touchEventProps.length; j < len; j++){ prop = touchEventProps[ j ]; event[ prop ] = touch[ prop ]; } } } return event; } function getVirtualBindingFlags( element ) { var flags = {}, b, k; while ( element ) { b = $.data( element, dataPropertyName ); for ( k in b ) { if ( b[ k ] ) { flags[ k ] = flags.hasVirtualBinding = true; } } element = element.parentNode; } return flags; } function getClosestElementWithVirtualBinding( element, eventType ) { var b; while ( element ) { b = $.data( element, dataPropertyName ); if ( b && ( !eventType || b[ eventType ] ) ) { return element; } element = element.parentNode; } return null; } function enableTouchBindings() { blockTouchTriggers = false; } function disableTouchBindings() { blockTouchTriggers = true; } function enableMouseBindings() { lastTouchID = 0; clickBlockList.length = 0; blockMouseTriggers = false; // When mouse bindings are enabled, our // touch bindings are disabled. disableTouchBindings(); } function disableMouseBindings() { // When mouse bindings are disabled, our // touch bindings are enabled. enableTouchBindings(); } function startResetTimer() { clearResetTimer(); resetTimerID = setTimeout(function(){ resetTimerID = 0; enableMouseBindings(); }, $.vmouse.resetTimerDuration ); } function clearResetTimer() { if ( resetTimerID ){ clearTimeout( resetTimerID ); resetTimerID = 0; } } function triggerVirtualEvent( eventType, event, flags ) { var defaultPrevented = false, ve; if ( ( flags && flags[ eventType ] ) || ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) { ve = createVirtualEvent( event, eventType ); $( event.target).trigger( ve ); defaultPrevented = ve.isDefaultPrevented(); } return defaultPrevented; } function mouseEventCallback( event ) { var touchID = $.data(event.target, touchTargetPropertyName); if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ){ triggerVirtualEvent( "v" + event.type, event ); } } function handleTouchStart( event ) { var touches = getNativeEvent( event ).touches, target, flags; if ( touches && touches.length === 1 ) { target = event.target; flags = getVirtualBindingFlags( target ); if ( flags.hasVirtualBinding ) { lastTouchID = nextTouchID++; $.data( target, touchTargetPropertyName, lastTouchID ); clearResetTimer(); disableMouseBindings(); didScroll = false; var t = getNativeEvent( event ).touches[ 0 ]; startX = t.pageX; startY = t.pageY; triggerVirtualEvent( "vmouseover", event, flags ); triggerVirtualEvent( "vmousedown", event, flags ); } } } function handleScroll( event ) { if ( blockTouchTriggers ) { return; } if ( !didScroll ) { triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) ); } didScroll = true; startResetTimer(); } function handleTouchMove( event ) { if ( blockTouchTriggers ) { return; } var t = getNativeEvent( event ).touches[ 0 ], didCancel = didScroll, moveThreshold = $.vmouse.moveDistanceThreshold; didScroll = didScroll || ( Math.abs(t.pageX - startX) > moveThreshold || Math.abs(t.pageY - startY) > moveThreshold ), flags = getVirtualBindingFlags( event.target ); if ( didScroll && !didCancel ) { triggerVirtualEvent( "vmousecancel", event, flags ); } triggerVirtualEvent( "vmousemove", event, flags ); startResetTimer(); } function handleTouchEnd( event ) { if ( blockTouchTriggers ) { return; } disableTouchBindings(); var flags = getVirtualBindingFlags( event.target ), t; triggerVirtualEvent( "vmouseup", event, flags ); if ( !didScroll ) { if ( triggerVirtualEvent( "vclick", event, flags ) ) { // The target of the mouse events that follow the touchend // event don't necessarily match the target used during the // touch. This means we need to rely on coordinates for blocking // any click that is generated. t = getNativeEvent( event ).changedTouches[ 0 ]; clickBlockList.push({ touchID: lastTouchID, x: t.clientX, y: t.clientY }); // Prevent any mouse events that follow from triggering // virtual event notifications. blockMouseTriggers = true; } } triggerVirtualEvent( "vmouseout", event, flags); didScroll = false; startResetTimer(); } function hasVirtualBindings( ele ) { var bindings = $.data( ele, dataPropertyName ), k; if ( bindings ) { for ( k in bindings ) { if ( bindings[ k ] ) { return true; } } } return false; } function dummyMouseHandler(){} function getSpecialEventObject( eventType ) { var realType = eventType.substr( 1 ); return { setup: function( data, namespace ) { // If this is the first virtual mouse binding for this element, // add a bindings object to its data. if ( !hasVirtualBindings( this ) ) { $.data( this, dataPropertyName, {}); } // If setup is called, we know it is the first binding for this // eventType, so initialize the count for the eventType to zero. var bindings = $.data( this, dataPropertyName ); bindings[ eventType ] = true; // If this is the first virtual mouse event for this type, // register a global handler on the document. activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1; if ( activeDocHandlers[ eventType ] === 1 ) { $document.bind( realType, mouseEventCallback ); } // Some browsers, like Opera Mini, won't dispatch mouse/click events // for elements unless they actually have handlers registered on them. // To get around this, we register dummy handlers on the elements. $( this ).bind( realType, dummyMouseHandler ); // For now, if event capture is not supported, we rely on mouse handlers. if ( eventCaptureSupported ) { // If this is the first virtual mouse binding for the document, // register our touchstart handler on the document. activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1; if (activeDocHandlers[ "touchstart" ] === 1) { $document.bind( "touchstart", handleTouchStart ) .bind( "touchend", handleTouchEnd ) // On touch platforms, touching the screen and then dragging your finger // causes the window content to scroll after some distance threshold is // exceeded. On these platforms, a scroll prevents a click event from being // dispatched, and on some platforms, even the touchend is suppressed. To // mimic the suppression of the click event, we need to watch for a scroll // event. Unfortunately, some platforms like iOS don't dispatch scroll // events until *AFTER* the user lifts their finger (touchend). This means // we need to watch both scroll and touchmove events to figure out whether // or not a scroll happenens before the touchend event is fired. .bind( "touchmove", handleTouchMove ) .bind( "scroll", handleScroll ); } } }, teardown: function( data, namespace ) { // If this is the last virtual binding for this eventType, // remove its global handler from the document. --activeDocHandlers[ eventType ]; if ( !activeDocHandlers[ eventType ] ) { $document.unbind( realType, mouseEventCallback ); } if ( eventCaptureSupported ) { // If this is the last virtual mouse binding in existence, // remove our document touchstart listener. --activeDocHandlers[ "touchstart" ]; if ( !activeDocHandlers[ "touchstart" ] ) { $document.unbind( "touchstart", handleTouchStart ) .unbind( "touchmove", handleTouchMove ) .unbind( "touchend", handleTouchEnd ) .unbind( "scroll", handleScroll ); } } var $this = $( this ), bindings = $.data( this, dataPropertyName ); // teardown may be called when an element was // removed from the DOM. If this is the case, // jQuery core may have already stripped the element // of any data bindings so we need to check it before // using it. if ( bindings ) { bindings[ eventType ] = false; } // Unregister the dummy event handler. $this.unbind( realType, dummyMouseHandler ); // If this is the last virtual mouse binding on the // element, remove the binding data from the element. if ( !hasVirtualBindings( this ) ) { $this.removeData( dataPropertyName ); } } }; } // Expose our custom events to the jQuery bind/unbind mechanism. for ( var i = 0; i < virtualEventNames.length; i++ ){ $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] ); } // Add a capture click handler to block clicks. // Note that we require event capture support for this so if the device // doesn't support it, we punt for now and rely solely on mouse events. if ( eventCaptureSupported ) { document.addEventListener( "click", function( e ){ var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID; if ( cnt ) { x = e.clientX; y = e.clientY; threshold = $.vmouse.clickDistanceThreshold; // The idea here is to run through the clickBlockList to see if // the current click event is in the proximity of one of our // vclick events that had preventDefault() called on it. If we find // one, then we block the click. // // Why do we have to rely on proximity? // // Because the target of the touch event that triggered the vclick // can be different from the target of the click event synthesized // by the browser. The target of a mouse/click event that is syntehsized // from a touch event seems to be implementation specific. For example, // some browsers will fire mouse/click events for a link that is near // a touch event, even though the target of the touchstart/touchend event // says the user touched outside the link. Also, it seems that with most // browsers, the target of the mouse/click event is not calculated until the // time it is dispatched, so if you replace an element that you touched // with another element, the target of the mouse/click will be the new // element underneath that point. // // Aside from proximity, we also check to see if the target and any // of its ancestors were the ones that blocked a click. This is necessary // because of the strange mouse/click target calculation done in the // Android 2.1 browser, where if you click on an element, and there is a // mouse/click handler on one of its ancestors, the target will be the // innermost child of the touched element, even if that child is no where // near the point of touch. ele = target; while ( ele ) { for ( i = 0; i < cnt; i++ ) { o = clickBlockList[ i ]; touchID = 0; if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) || $.data( ele, touchTargetPropertyName ) === o.touchID ) { // XXX: We may want to consider removing matches from the block list // instead of waiting for the reset timer to fire. e.preventDefault(); e.stopPropagation(); return; } } ele = ele.parentNode; } } }, true); } })( jQuery, window, document ); /* * jQuery Mobile Framework : events * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { // add new event shortcuts $.each( ( "touchstart touchmove touchend orientationchange throttledresize " + "tap taphold swipe swipeleft swiperight scrollstart scrollstop" ).split( " " ), function( i, name ) { $.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; $.attrFn[ name ] = true; }); var supportTouch = $.support.touch, scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; function triggerCustomEvent( obj, eventType, event ) { var originalType = event.type; event.type = eventType; $.event.handle.call( obj, event ); event.type = originalType; } // also handles scrollstop $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this, $this = $( thisObject ), scrolling, timer; function trigger( event, state ) { scrolling = state; triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event ); } // iPhone triggers scroll after a small delay; use touchmove instead $this.bind( scrollEvent, function( event ) { if ( !$.event.special.scrollstart.enabled ) { return; } if ( !scrolling ) { trigger( event, true ); } clearTimeout( timer ); timer = setTimeout(function() { trigger( event, false ); }, 50 ); }); } }; // also handles taphold $.event.special.tap = { setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( "vmousedown", function( event ) { if ( event.which && event.which !== 1 ) { return false; } var touching = true, origTarget = event.target, origEvent = event.originalEvent, timer; function clearTapHandlers() { touching = false; clearTimeout(timer); $this.unbind( "vclick", clickHandler ) .unbind( "vmousecancel", clearTapHandlers ); } function clickHandler(event) { clearTapHandlers(); // ONLY trigger a 'tap' event if the start target is // the same as the stop target. if ( origTarget == event.target ) { triggerCustomEvent( thisObject, "tap", event ); } } $this.bind( "vmousecancel", clearTapHandlers ) .bind( "vclick", clickHandler ); timer = setTimeout(function() { if ( touching ) { triggerCustomEvent( thisObject, "taphold", event ); } }, 750 ); }); } }; // also handles swipeleft, swiperight $.event.special.swipe = { scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling. durationThreshold: 1000, // More time than this, and it isn't a swipe. horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this. verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this. setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( touchStartEvent, function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, start = { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ], origin: $( event.target ) }, stop; function moveHandler( event ) { if ( !start ) { return; } var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event; stop = { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ] }; // prevent scrolling if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) { event.preventDefault(); } } $this.bind( touchMoveEvent, moveHandler ) .one( touchStopEvent, function( event ) { $this.unbind( touchMoveEvent, moveHandler ); if ( start && stop ) { if ( stop.time - start.time < $.event.special.swipe.durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) { start.origin.trigger( "swipe" ) .trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" ); } } start = stop = undefined; }); }); } }; (function( $, window ) { // "Cowboy" Ben Alman var win = $( window ), special_event, get_orientation, last_orientation; $.event.special.orientationchange = special_event = { setup: function() { // If the event is supported natively, return false so that jQuery // will bind to the event using DOM methods. if ( $.support.orientation ) { return false; } // Get the current orientation to avoid initial double-triggering. last_orientation = get_orientation(); // Because the orientationchange event doesn't exist, simulate the // event by testing window dimensions on resize. win.bind( "throttledresize", handler ); }, teardown: function(){ // If the event is not supported natively, return false so that // jQuery will unbind the event using DOM methods. if ( $.support.orientation ) { return false; } // Because the orientationchange event doesn't exist, unbind the // resize event handler. win.unbind( "throttledresize", handler ); }, add: function( handleObj ) { // Save a reference to the bound event handler. var old_handler = handleObj.handler; handleObj.handler = function( event ) { // Modify event object, adding the .orientation property. event.orientation = get_orientation(); // Call the originally-bound event handler and return its result. return old_handler.apply( this, arguments ); }; } }; // If the event is not supported natively, this handler will be bound to // the window resize event to simulate the orientationchange event. function handler() { // Get the current orientation. var orientation = get_orientation(); if ( orientation !== last_orientation ) { // The orientation has changed, so trigger the orientationchange event. last_orientation = orientation; win.trigger( "orientationchange" ); } }; // Get the current page orientation. This method is exposed publicly, should it // be needed, as jQuery.event.special.orientationchange.orientation() $.event.special.orientationchange.orientation = get_orientation = function() { var elem = document.documentElement; return elem && elem.clientWidth / elem.clientHeight < 1.1 ? "portrait" : "landscape"; }; })( jQuery, window ); // throttled resize event (function() { $.event.special.throttledresize = { setup: function() { $( this ).bind( "resize", handler ); }, teardown: function(){ $( this ).unbind( "resize", handler ); } }; var throttle = 250, handler = function() { curr = ( new Date() ).getTime(); diff = curr - lastCall; if ( diff >= throttle ) { lastCall = curr; $( this ).trigger( "throttledresize" ); } else { if ( heldCall ) { clearTimeout( heldCall ); } // Promise a held call will still execute heldCall = setTimeout( handler, throttle - diff ); } }, lastCall = 0, heldCall, curr, diff; })(); $.each({ scrollstop: "scrollstart", taphold: "tap", swipeleft: "swipe", swiperight: "swipe" }, function( event, sourceEvent ) { $.event.special[ event ] = { setup: function() { $( this ).bind( sourceEvent, $.noop ); } }; }); })( jQuery, this ); /*! * jQuery hashchange event - v1.3 - 7/21/2010 * http://benalman.com/projects/jquery-hashchange-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function(val){ return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv $.browser.msie && !supports_onhashchange && (function(){ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function(){ if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function(){ iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function(){ try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this); /* * jQuery Mobile Framework : "page" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.page", $.mobile.widget, { options: { theme: "c", domCache: false }, _create: function() { var $elem = this.element, o = this.options; if ( this._trigger( "beforeCreate" ) === false ) { return; } $elem.addClass( "ui-page ui-body-" + o.theme ); } }); })( jQuery ); /*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { // jQuery.mobile configurable options $.extend( $.mobile, { // Namespace used framework-wide for data-attrs. Default is no namespace ns: "", // Define the url parameter used for referencing widget-generated sub-pages. // Translates to to example.html&ui-page=subpageIdentifier // hash segment before &ui-page= is used to make Ajax request subPageUrlKey: "ui-page", // Class assigned to page currently in view, and during transitions activePageClass: "ui-page-active", // Class used for "active" button state, from CSS framework activeBtnClass: "ui-btn-active", // Automatically handle clicks and form submissions through Ajax, when same-domain ajaxEnabled: true, // Automatically load and show pages based on location.hash hashListeningEnabled: true, // Set default page transition - 'none' for no transitions defaultPageTransition: "slide", // Minimum scroll distance that will be remembered when returning to a page minScrollBack: screen.height / 2, // Set default dialog transition - 'none' for no transitions defaultDialogTransition: "pop", // Show loading message during Ajax requests // if false, message will not appear, but loading classes will still be toggled on html el loadingMessage: "loading", // Error response message - appears when an Ajax page request fails pageLoadErrorMessage: "Error Loading Page", //automatically initialize the DOM when it's ready autoInitializePage: true, // Support conditions that must be met in order to proceed // default enhanced qualifications are media query support OR IE 7+ gradeA: function(){ return $.support.mediaquery || $.mobile.browser.ie && $.mobile.browser.ie >= 7; }, // TODO might be useful upstream in jquery itself ? keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, // COMMAND COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, // COMMAND_RIGHT NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91 // COMMAND }, // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value silentScroll: function( ypos ) { if ( $.type( ypos ) !== "number" ) { ypos = $.mobile.defaultHomeScroll; } // prevent scrollstart and scrollstop events $.event.special.scrollstart.enabled = false; setTimeout(function() { window.scrollTo( 0, ypos ); $( document ).trigger( "silentscroll", { x: 0, y: ypos }); }, 20 ); setTimeout(function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, // Take a data attribute property, prepend the namespace // and then camel case the attribute string nsNormalize: function( prop ) { if ( !prop ) { return; } return $.camelCase( $.mobile.ns + prop ); } }); // Mobile version of data and removeData and hasData methods // ensures all data is set and retrieved using jQuery Mobile's data namespace $.fn.jqmData = function( prop, value ) { return this.data( prop ? $.mobile.nsNormalize( prop ) : prop, value ); }; $.jqmData = function( elem, prop, value ) { return $.data( elem, $.mobile.nsNormalize( prop ), value ); }; $.fn.jqmRemoveData = function( prop ) { return this.removeData( $.mobile.nsNormalize( prop ) ); }; $.jqmRemoveData = function( elem, prop ) { return $.removeData( elem, $.mobile.nsNormalize( prop ) ); }; $.jqmHasData = function( elem, prop ) { return $.hasData( elem, $.mobile.nsNormalize( prop ) ); }; // Monkey-patching Sizzle to filter the :jqmData selector var oldFind = $.find; $.find = function( selector, context, ret, extra ) { selector = selector.replace(/:jqmData\(([^)]*)\)/g, "[data-" + ( $.mobile.ns || "" ) + "$1]"); return oldFind.call( this, selector, context, ret, extra ); }; $.extend( $.find, oldFind ); $.find.matches = function( expr, set ) { return $.find( expr, null, null, set ); }; $.find.matchesSelector = function( node, expr ) { return $.find( expr, null, null, [ node ] ).length > 0; }; })( jQuery, this ); /* * jQuery Mobile Framework : core utilities for auto ajax navigation, base tag mgmt, * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { //define vars for interal use var $window = $( window ), $html = $( 'html' ), $head = $( 'head' ), //url path helpers for use in relative url management path = { // This scary looking regular expression parses an absolute URL or its relative // variants (protocol, site, document, query, and hash), into the various // components (protocol, host, path, query, fragment, etc that make up the // URL as well as some other commonly used sub-parts. When used with RegExp.exec() // or String.match, it parses the URL into a results array that looks like this: // // [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content // [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread // [2]: http://jblas:password@mycompany.com:8080/mail/inbox // [3]: http://jblas:password@mycompany.com:8080 // [4]: http: // [5]: jblas:password@mycompany.com:8080 // [6]: jblas:password // [7]: jblas // [8]: password // [9]: mycompany.com:8080 // [10]: mycompany.com // [11]: 8080 // [12]: /mail/inbox // [13]: /mail/ // [14]: inbox // [15]: ?msg=1234&type=unread // [16]: #msg-content // urlParseRE: /^(((([^:\/#\?]+:)?(?:\/\/((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?]+)(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/, //Parse a URL into a structure that allows easy access to //all of the URL components by name. parseUrl: function( url ) { // If we're passed an object, we'll assume that it is // a parsed url object and just return it back to the caller. if ( $.type( url ) === "object" ) { return url; } var u = url || "", matches = path.urlParseRE.exec( url ), results; if ( matches ) { // Create an object that allows the caller to access the sub-matches // by name. Note that IE returns an empty string instead of undefined, // like all other browsers do, so we normalize everything so its consistent // no matter what browser we're running on. results = { href: matches[0] || "", hrefNoHash: matches[1] || "", hrefNoSearch: matches[2] || "", domain: matches[3] || "", protocol: matches[4] || "", authority: matches[5] || "", username: matches[7] || "", password: matches[8] || "", host: matches[9] || "", hostname: matches[10] || "", port: matches[11] || "", pathname: matches[12] || "", directory: matches[13] || "", filename: matches[14] || "", search: matches[15] || "", hash: matches[16] || "" }; } return results || {}; }, //Turn relPath into an asbolute path. absPath is //an optional absolute path which describes what //relPath is relative to. makePathAbsolute: function( relPath, absPath ) { if ( relPath && relPath.charAt( 0 ) === "/" ) { return relPath; } relPath = relPath || ""; absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : ""; var absStack = absPath ? absPath.split( "/" ) : [], relStack = relPath.split( "/" ); for ( var i = 0; i < relStack.length; i++ ) { var d = relStack[ i ]; switch ( d ) { case ".": break; case "..": if ( absStack.length ) { absStack.pop(); } break; default: absStack.push( d ); break; } } return "/" + absStack.join( "/" ); }, //Returns true if both urls have the same domain. isSameDomain: function( absUrl1, absUrl2 ) { return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain; }, //Returns true for any relative variant. isRelativeUrl: function( url ) { // All relative Url variants have one thing in common, no protocol. return path.parseUrl( url ).protocol === ""; }, //Returns true for an absolute url. isAbsoluteUrl: function( url ) { return path.parseUrl( url ).protocol !== ""; }, //Turn the specified realtive URL into an absolute one. This function //can handle all relative variants (protocol, site, document, query, fragment). makeUrlAbsolute: function( relUrl, absUrl ) { if ( !path.isRelativeUrl( relUrl ) ) { return relUrl; } var relObj = path.parseUrl( relUrl ), absObj = path.parseUrl( absUrl ), protocol = relObj.protocol || absObj.protocol, authority = relObj.authority || absObj.authority, hasPath = relObj.pathname !== "", pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ), search = relObj.search || ( !hasPath && absObj.search ) || "", hash = relObj.hash; return protocol + "//" + authority + pathname + search + hash; }, //Add search (aka query) params to the specified url. addSearchParams: function( url, params ) { var u = path.parseUrl( url ), p = ( typeof params === "object" ) ? $.param( params ) : params, s = u.search || "?"; return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" ); }, convertUrlToDataUrl: function( absUrl ) { var u = path.parseUrl( absUrl ); if ( path.isEmbeddedPage( u ) ) { // For embedded pages, remove the dialog hash key as in getFilePath(), // otherwise the Data Url won't match the id of the embedded Page. return u.hash.split( dialogHashKey )[0].replace( /^#/, "" ); } else if ( path.isSameDomain( u, documentBase ) ) { return u.hrefNoHash.replace( documentBase.domain, "" ); } return absUrl; }, //get path from current hash, or from a file path get: function( newPath ) { if( newPath === undefined ) { newPath = location.hash; } return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' ); }, //return the substring of a filepath before the sub-page key, for making a server request getFilePath: function( path ) { var splitkey = '&' + $.mobile.subPageUrlKey; return path && path.split( splitkey )[0].split( dialogHashKey )[0]; }, //set location hash to path set: function( path ) { location.hash = path; }, //test if a given url (string) is a path //NOTE might be exceptionally naive isPath: function( url ) { return ( /\// ).test( url ); }, //return a url path with the window's location protocol/hostname/pathname removed clean: function( url ) { return url.replace( documentBase.domain, "" ); }, //just return the url without an initial # stripHash: function( url ) { return url.replace( /^#/, "" ); }, //remove the preceding hash, any query params, and dialog notations cleanHash: function( hash ) { return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) ); }, //check whether a url is referencing the same domain, or an external domain or different protocol //could be mailto, etc isExternal: function( url ) { var u = path.parseUrl( url ); return u.protocol && u.domain !== documentUrl.domain ? true : false; }, hasProtocol: function( url ) { return ( /^(:?\w+:)/ ).test( url ); }, isEmbeddedPage: function( url ) { var u = path.parseUrl( url ); //if the path is absolute, then we need to compare the url against //both the documentUrl and the documentBase. The main reason for this //is that links embedded within external documents will refer to the //application document, whereas links embedded within the application //document will be resolved against the document base. if ( u.protocol !== "" ) { return ( u.hash && ( u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ) ) ); } return (/^#/).test( u.href ); } }, //will be defined when a link is clicked and given an active class $activeClickedLink = null, //urlHistory is purely here to make guesses at whether the back or forward button was clicked //and provide an appropriate transition urlHistory = { // Array of pages that are visited during a single page load. // Each has a url and optional transition, title, and pageUrl (which represents the file path, in cases where URL is obscured, such as dialogs) stack: [], //maintain an index number for the active page in the stack activeIndex: 0, //get active getActive: function() { return urlHistory.stack[ urlHistory.activeIndex ]; }, getPrev: function() { return urlHistory.stack[ urlHistory.activeIndex - 1 ]; }, getNext: function() { return urlHistory.stack[ urlHistory.activeIndex + 1 ]; }, // addNew is used whenever a new page is added addNew: function( url, transition, title, pageUrl ) { //if there's forward history, wipe it if( urlHistory.getNext() ) { urlHistory.clearForward(); } urlHistory.stack.push( {url : url, transition: transition, title: title, pageUrl: pageUrl } ); urlHistory.activeIndex = urlHistory.stack.length - 1; }, //wipe urls ahead of active index clearForward: function() { urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 ); }, directHashChange: function( opts ) { var back , forward, newActiveIndex; // check if url isp in history and if it's ahead or behind current page $.each( urlHistory.stack, function( i, historyEntry ) { //if the url is in the stack, it's a forward or a back if( opts.currentUrl === historyEntry.url ) { //define back and forward by whether url is older or newer than current page back = i < urlHistory.activeIndex; forward = !back; newActiveIndex = i; } }); // save new page index, null check to prevent falsey 0 result this.activeIndex = newActiveIndex !== undefined ? newActiveIndex : this.activeIndex; if( back ) { opts.isBack(); } else if( forward ) { opts.isForward(); } }, //disable hashchange event listener internally to ignore one change //toggled internally when location.hash is updated to match the url of a successful page load ignoreNextHashChange: false }, //define first selector to receive focus when a page is shown focusable = "[tabindex],a,button:visible,select:visible,input", //queue to hold simultanious page transitions pageTransitionQueue = [], //indicates whether or not page is in process of transitioning isPageTransitioning = false, //nonsense hash change key for dialogs, so they create a history entry dialogHashKey = "&ui-state=dialog", //existing base tag? $base = $head.children( "base" ), //tuck away the original document URL minus any fragment. documentUrl = path.parseUrl( location.href ), //if the document has an embedded base tag, documentBase is set to its //initial value. If a base tag does not exist, then we default to the documentUrl. documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), documentUrl.href ) ) : documentUrl, //cache the comparison once. documentBaseDiffers = ( documentUrl.hrefNoHash !== documentBase.hrefNoHash ); //base element management, defined depending on dynamic base tag support var base = $.support.dynamicBaseTag ? { //define base element, for use in routing asset urls that are referenced in Ajax-requested markup element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ), //set the generated BASE element's href attribute to a new page's base path set: function( href ) { base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) ); }, //set the generated BASE element's href attribute to a new page's base path reset: function() { base.element.attr( "href", documentBase.hrefNoHash ); } } : undefined; /* internal utility functions --------------------------------------*/ //direct focus to the page title, or otherwise first focusable element function reFocus( page ) { var lastClicked = page.jqmData( "lastClicked" ); if( lastClicked && lastClicked.length ) { lastClicked.focus(); } else { var pageTitle = page.find( ".ui-title:eq(0)" ); if( pageTitle.length ) { pageTitle.focus(); } else{ page.find( focusable ).eq( 0 ).focus(); } } } //remove active classes after page transition or error function removeActiveLinkClass( forceRemoval ) { if( !!$activeClickedLink && ( !$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval ) ) { $activeClickedLink.removeClass( $.mobile.activeBtnClass ); } $activeClickedLink = null; } function releasePageTransitionLock() { isPageTransitioning = false; if( pageTransitionQueue.length > 0 ) { $.mobile.changePage.apply( null, pageTransitionQueue.pop() ); } } //function for transitioning between two existing pages function transitionPages( toPage, fromPage, transition, reverse ) { //get current scroll distance var currScroll = $.support.scrollTop ? $window.scrollTop() : true, toScroll = toPage.data( "lastScroll" ) || $.mobile.defaultHomeScroll, screenHeight = getScreenHeight(); //if scrolled down, scroll to top if( currScroll ){ window.scrollTo( 0, $.mobile.defaultHomeScroll ); } //if the Y location we're scrolling to is less than 10px, let it go for sake of smoothness if( toScroll < $.mobile.minScrollBack ){ toScroll = 0; } if( fromPage ) { //set as data for returning to that spot fromPage .height( screenHeight + currScroll ) .jqmData( "lastScroll", currScroll ) .jqmData( "lastClicked", $activeClickedLink ); //trigger before show/hide events fromPage.data( "page" )._trigger( "beforehide", null, { nextPage: toPage } ); } toPage .height( screenHeight + toScroll ) .data( "page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } ); //clear page loader $.mobile.hidePageLoadingMsg(); //find the transition handler for the specified transition. If there //isn't one in our transitionHandlers dictionary, use the default one. //call the handler immediately to kick-off the transition. var th = $.mobile.transitionHandlers[transition || "none"] || $.mobile.defaultTransitionHandler, promise = th( transition, reverse, toPage, fromPage ); promise.done(function() { //reset toPage height bac toPage.height( "" ); //jump to top or prev scroll, sometimes on iOS the page has not rendered yet. if( toScroll ){ $.mobile.silentScroll( toScroll ); $( document ).one( "silentscroll", function() { reFocus( toPage ); } ); } else{ reFocus( toPage ); } //trigger show/hide events if( fromPage ) { fromPage.height("").data( "page" )._trigger( "hide", null, { nextPage: toPage } ); } //trigger pageshow, define prevPage as either fromPage or empty jQuery obj toPage.data( "page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } ); }); return promise; } //simply set the active page's minimum height to screen height, depending on orientation function getScreenHeight(){ var orientation = jQuery.event.special.orientationchange.orientation(), port = orientation === "portrait", winMin = port ? 480 : 320, screenHeight = port ? screen.availHeight : screen.availWidth, winHeight = Math.max( winMin, $( window ).height() ), pageMin = Math.min( screenHeight, winHeight ); return pageMin; } //simply set the active page's minimum height to screen height, depending on orientation function resetActivePageHeight(){ $( "." + $.mobile.activePageClass ).css( "min-height", getScreenHeight() ); } //shared page enhancements function enhancePage( $page, role ) { // If a role was specified, make sure the data-role attribute // on the page element is in sync. if( role ) { $page.attr( "data-" + $.mobile.ns + "role", role ); } //run page plugin $page.page(); } /* exposed $.mobile methods */ //animation complete callback $.fn.animationComplete = function( callback ) { if( $.support.cssTransitions ) { return $( this ).one( 'webkitAnimationEnd', callback ); } else{ // defer execution for consistency between webkit/non webkit setTimeout( callback, 0 ); return $( this ); } }; //update location.hash, with or without triggering hashchange event //TODO - deprecate this one at 1.0 $.mobile.updateHash = path.set; //expose path object on $.mobile $.mobile.path = path; //expose base object on $.mobile $.mobile.base = base; //url stack, useful when plugins need to be aware of previous pages viewed //TODO: deprecate this one at 1.0 $.mobile.urlstack = urlHistory.stack; //history stack $.mobile.urlHistory = urlHistory; //default non-animation transition handler $.mobile.noneTransitionHandler = function( name, reverse, $toPage, $fromPage ) { if ( $fromPage ) { $fromPage.removeClass( $.mobile.activePageClass ); } $toPage.addClass( $.mobile.activePageClass ); return $.Deferred().resolve( name, reverse, $toPage, $fromPage ).promise(); }; //default handler for unknown transitions $.mobile.defaultTransitionHandler = $.mobile.noneTransitionHandler; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { none: $.mobile.defaultTransitionHandler }; //enable cross-domain page support $.mobile.allowCrossDomainPages = false; //return the original document url $.mobile.getDocumentUrl = function(asParsedObject) { return asParsedObject ? $.extend( {}, documentUrl ) : documentUrl.href; }; //return the original document base url $.mobile.getDocumentBase = function(asParsedObject) { return asParsedObject ? $.extend( {}, documentBase ) : documentBase.href; }; // Load a page into the DOM. $.mobile.loadPage = function( url, options ) { // This function uses deferred notifications to let callers // know when the page is done loading, or if an error has occurred. var deferred = $.Deferred(), // The default loadPage options with overrides specified by // the caller. settings = $.extend( {}, $.mobile.loadPage.defaults, options ), // The DOM element for the page after it has been loaded. page = null, // If the reloadPage option is true, and the page is already // in the DOM, dupCachedPage will be set to the page element // so that it can be removed after the new version of the // page is loaded off the network. dupCachedPage = null, // determine the current base url findBaseWithDefault = function(){ var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) ); return closestBase || documentBase.hrefNoHash; }, // The absolute version of the URL passed into the function. This // version of the URL may contain dialog/subpage params in it. absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() ); // If the caller provided data, and we're using "get" request, // append the data to the URL. if ( settings.data && settings.type === "get" ) { absUrl = path.addSearchParams( absUrl, settings.data ); settings.data = undefined; } // The absolute version of the URL minus any dialog/subpage params. // In otherwords the real URL of the page to be loaded. var fileUrl = path.getFilePath( absUrl ), // The version of the Url actually stored in the data-url attribute of // the page. For embedded pages, it is just the id of the page. For pages // within the same domain as the document base, it is the site relative // path. For cross-domain pages (Phone Gap only) the entire absolute Url // used to load the page. dataUrl = path.convertUrlToDataUrl( absUrl ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // Check to see if the page already exists in the DOM. page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" ); // Reset base to the default document base. if ( base ) { base.reset(); } // If the page we are interested in is already in the DOM, // and the caller did not indicate that we should force a // reload of the file, we are done. Otherwise, track the // existing page as a duplicated. if ( page.length ) { if ( !settings.reloadPage ) { enhancePage( page, settings.role ); deferred.resolve( absUrl, options, page ); return deferred.promise(); } dupCachedPage = page; } if ( settings.showLoadMsg ) { // This configurable timeout allows cached pages a brief delay to load without showing a message var loadMsgDelay = setTimeout(function(){ $.mobile.showPageLoadingMsg(); }, settings.loadMsgDelay ), // Shared logic for clearing timeout and removing message. hideMsg = function(){ // Stop message show timer clearTimeout( loadMsgDelay ); // Hide loading message $.mobile.hidePageLoadingMsg(); }; } if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) { deferred.reject( absUrl, options ); } else { // Load the new page. $.ajax({ url: fileUrl, type: settings.type, data: settings.data, dataType: "html", success: function( html ) { //pre-parse html to check for a data-url, //use it as the new fileUrl, base path, etc var all = $( "<div></div>" ), //page title regexp newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1, // TODO handle dialogs again pageElemRegex = new RegExp( ".*(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>).*" ), dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" ); // data-url must be provided for the base tag so resource requests can be directed to the // correct url. loading into a temprorary element makes these requests immediately if( pageElemRegex.test( html ) && RegExp.$1 && dataUrlRegex.test( RegExp.$1 ) && RegExp.$1 ) { url = fileUrl = path.getFilePath( RegExp.$1 ); } else{ } if ( base ) { base.set( fileUrl ); } //workaround to allow scripts to execute when included in page divs all.get( 0 ).innerHTML = html; page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first(); //if page elem couldn't be found, create one and insert the body element's contents if( !page.length ){ page = $( "<div data-" + $.mobile.ns + "role='page'>" + html.split( /<\/?body[^>]*>/gmi )[1] + "</div>" ); } if ( newPageTitle && !page.jqmData( "title" ) ) { page.jqmData( "title", newPageTitle ); } //rewrite src and href attrs to use a base url if( !$.support.dynamicBaseTag ) { var newPath = path.get( fileUrl ); page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() { var thisAttr = $( this ).is( '[href]' ) ? 'href' : $(this).is('[src]') ? 'src' : 'action', thisUrl = $( this ).attr( thisAttr ); // XXX_jblas: We need to fix this so that it removes the document // base URL, and then prepends with the new page URL. //if full path exists and is same, chop it - helps IE out thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' ); if( !/^(\w+:|#|\/)/.test( thisUrl ) ) { $( this ).attr( thisAttr, newPath + thisUrl ); } }); } //append to page and enhance page .attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) ) .appendTo( settings.pageContainer ); // wait for page creation to leverage options defined on widget page.one('pagecreate', function(){ // when dom caching is not enabled bind to remove the page on hide if( !page.data("page").options.domCache ){ page.bind( "pagehide.remove", function(){ $(this).remove(); }); } }); enhancePage( page, settings.role ); // Enhancing the page may result in new dialogs/sub pages being inserted // into the DOM. If the original absUrl refers to a sub-page, that is the // real page we are interested in. if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) { page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" ); } //bind pageHide to removePage after it's hidden, if the page options specify to do so // Remove loading message. if ( settings.showLoadMsg ) { hideMsg(); } deferred.resolve( absUrl, options, page, dupCachedPage ); }, error: function() { //set base back to current path if( base ) { base.set( path.get() ); } // Remove loading message. if ( settings.showLoadMsg ) { // Remove loading message. hideMsg(); //show error message $( "<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>"+ $.mobile.pageLoadErrorMessage +"</h1></div>" ) .css({ "display": "block", "opacity": 0.96, "top": $window.scrollTop() + 100 }) .appendTo( settings.pageContainer ) .delay( 800 ) .fadeOut( 400, function() { $( this ).remove(); }); } deferred.reject( absUrl, options ); } }); } return deferred.promise(); }; $.mobile.loadPage.defaults = { type: "get", data: undefined, reloadPage: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. showLoadMsg: false, pageContainer: undefined, loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message. }; // Show a specific page in the page container. $.mobile.changePage = function( toPage, options ) { // XXX: REMOVE_BEFORE_SHIPPING_1.0 // This is temporary code that makes changePage() compatible with previous alpha versions. if ( typeof options !== "object" ) { var opts = null; // Map old-style call signature for form submit to the new options object format. if ( typeof toPage === "object" && toPage.url && toPage.type ) { opts = { type: toPage.type, data: toPage.data, forcePageLoad: true }; toPage = toPage.url; } // The arguments passed into the function need to be re-mapped // to the new options object format. var len = arguments.length; if ( len > 1 ) { var argNames = [ "transition", "reverse", "changeHash", "fromHashChange" ], i; for ( i = 1; i < len; i++ ) { var a = arguments[ i ]; if ( typeof a !== "undefined" ) { opts = opts || {}; opts[ argNames[ i - 1 ] ] = a; } } } // If an options object was created, then we know changePage() was called // with an old signature. if ( opts ) { return $.mobile.changePage( toPage, opts ); } } // XXX: REMOVE_BEFORE_SHIPPING_1.0 // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition to // service the request. if( isPageTransitioning ) { pageTransitionQueue.unshift( arguments ); return; } // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; var settings = $.extend( {}, $.mobile.changePage.defaults, options ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // If the caller passed us a url, call loadPage() // to make sure it is loaded into the DOM. We'll listen // to the promise object it returns so we know when // it is done loading or if an error ocurred. if ( typeof toPage == "string" ) { $.mobile.loadPage( toPage, settings ) .done(function( url, options, newPage, dupCachedPage ) { isPageTransitioning = false; options.duplicateCachedPage = dupCachedPage; $.mobile.changePage( newPage, options ); }) .fail(function( url, options ) { // XXX_jblas: Fire off changepagefailed notificaiton. isPageTransitioning = false; //clear out the active button state removeActiveLinkClass( true ); //release transition lock so navigation is free again releasePageTransitionLock(); settings.pageContainer.trigger("changepagefailed"); }); return; } // The caller passed us a real page DOM element. Update our // internal state and then trigger a transition to the page. var mpc = settings.pageContainer, fromPage = $.mobile.activePage, url = toPage.jqmData( "url" ), // The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path pageUrl = url, fileUrl = path.getFilePath( url ), active = urlHistory.getActive(), activeIsInitialPage = urlHistory.activeIndex === 0, historyDir = 0, pageTitle = document.title, isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog"; // Let listeners know we're about to change the current page. mpc.trigger( "beforechangepage" ); // If we are trying to transition to the same page that we are currently on ignore the request. // an illegal same page request is defined by the current page being the same as the url, as long as there's history // and toPage is not an array or object (those are allowed to be "same") // // XXX_jblas: We need to remove this at some point when we allow for transitions // to the same page. if( fromPage && fromPage[0] === toPage[0] ) { isPageTransitioning = false; mpc.trigger( "changepage" ); return; } // We need to make sure the page we are given has already been enhanced. enhancePage( toPage, settings.role ); // If the changePage request was sent from a hashChange event, check to see if the // page is already within the urlHistory stack. If so, we'll assume the user hit // the forward/back button and will try to match the transition accordingly. if( settings.fromHashChange ) { urlHistory.directHashChange({ currentUrl: url, isBack: function() { historyDir = -1; }, isForward: function() { historyDir = 1; } }); } // Kill the keyboard. // XXX_jblas: We need to stop crawling the entire document to kill focus. Instead, // we should be tracking focus with a live() handler so we already have // the element in hand at this point. // Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement // is undefined when we are in an IFrame. try { $( document.activeElement || "" ).add( "input:focus, textarea:focus, select:focus" ).blur(); } catch(e) {} // If we're displaying the page as a dialog, we don't want the url // for the dialog content to be used in the hash. Instead, we want // to append the dialogHashKey to the url of the current page. if ( isDialog && active ) { url = active.url + dialogHashKey; } // Set the location hash. if( settings.changeHash !== false && url ) { //disable hash listening temporarily urlHistory.ignoreNextHashChange = true; //update hash and history path.set( url ); } //if title element wasn't found, try the page div data attr too var newPageTitle = toPage.jqmData( "title" ) || toPage.children(":jqmData(role='header')").find(".ui-title" ).text(); if( !!newPageTitle && pageTitle == document.title ) { pageTitle = newPageTitle; } //add page to history stack if it's not back or forward if( !historyDir ) { urlHistory.addNew( url, settings.transition, pageTitle, pageUrl ); } //set page title document.title = urlHistory.getActive().title; //set "toPage" as activePage $.mobile.activePage = toPage; // Make sure we have a transition defined. settings.transition = settings.transition || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition ); // If we're navigating back in the URL history, set reverse accordingly. settings.reverse = settings.reverse || historyDir < 0; transitionPages( toPage, fromPage, settings.transition, settings.reverse ) .done(function() { removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } //remove initial build class (only present on first pageshow) $html.removeClass( "ui-mobile-rendering" ); releasePageTransitionLock(); // Let listeners know we're all done changing the current page. mpc.trigger( "changepage" ); }); }; $.mobile.changePage.defaults = { transition: undefined, reverse: false, changeHash: true, fromHashChange: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. duplicateCachedPage: undefined, pageContainer: undefined, showLoadMsg: true //loading message shows by default when pages are being fetched during changePage }; /* Event Bindings - hashchange, submit, and click */ function findClosestLink( ele ) { while ( ele ) { if ( ele.nodeName.toLowerCase() == "a" ) { break; } ele = ele.parentNode; } return ele; } // The base URL for any given element depends on the page it resides in. function getClosestBaseUrl( ele ) { // Find the closest page and extract out its url. var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ), base = documentBase.hrefNoHash; if ( !url || !path.isPath( url ) ) { url = base; } return path.makeUrlAbsolute( url, base); } //The following event bindings should be bound after mobileinit has been triggered //the following function is called in the init file $.mobile._registerInternalEvents = function(){ //bind to form submit events, handle with Ajax $( "form" ).live('submit', function( event ) { var $this = $( this ); if( !$.mobile.ajaxEnabled || $this.is( ":jqmData(ajax='false')" ) ) { return; } var type = $this.attr( "method" ), target = $this.attr( "target" ), url = $this.attr( "action" ); // If no action is specified, browsers default to using the // URL of the document containing the form. Since we dynamically // pull in pages from external documents, the form should submit // to the URL for the source document of the page containing // the form. if ( !url ) { // Get the @data-url for the page containing the form. url = getClosestBaseUrl( $this ); if ( url === documentBase.hrefNoHash ) { // The url we got back matches the document base, // which means the page must be an internal/embedded page, // so default to using the actual document url as a browser // would. url = documentUrl.hrefNoSearch; } } url = path.makeUrlAbsolute( url, getClosestBaseUrl($this) ); //external submits use regular HTTP if( path.isExternal( url ) || target ) { return; } $.mobile.changePage( url, { type: type && type.length && type.toLowerCase() || "get", data: $this.serialize(), transition: $this.jqmData( "transition" ), direction: $this.jqmData( "direction" ), reloadPage: true } ); event.preventDefault(); }); //add active state on vclick $( document ).bind( "vclick", function( event ) { var link = findClosestLink( event.target ); if ( link ) { if ( path.parseUrl( link.getAttribute( "href" ) || "#" ).hash !== "#" ) { $( link ).closest( ".ui-btn" ).not( ".ui-disabled" ).addClass( $.mobile.activeBtnClass ); $( "." + $.mobile.activePageClass + " .ui-btn" ).not( link ).blur(); } } }); // click routing - direct to HTTP or Ajax, accordingly $( document ).bind( "click", function( event ) { var link = findClosestLink( event.target ); if ( !link ) { return; } var $link = $( link ), //remove active link class if external (then it won't be there if you come back) httpCleanup = function(){ window.setTimeout( function() { removeActiveLinkClass( true ); }, 200 ); }; //if there's a data-rel=back attr, go back in history if( $link.is( ":jqmData(rel='back')" ) ) { window.history.back(); return false; } //if ajax is disabled, exit early if( !$.mobile.ajaxEnabled ){ httpCleanup(); //use default click handling return; } var baseUrl = getClosestBaseUrl( $link ), //get href, if defined, otherwise default to empty hash href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ); // XXX_jblas: Ideally links to application pages should be specified as // an url to the application document with a hash that is either // the site relative path or id to the page. But some of the // internal code that dynamically generates sub-pages for nested // lists and select dialogs, just write a hash in the link they // create. This means the actual URL path is based on whatever // the current value of the base tag is at the time this code // is called. For now we are just assuming that any url with a // hash in it is an application page reference. if ( href.search( "#" ) != -1 ) { href = href.replace( /[^#]*#/, "" ); if ( !href ) { //link was an empty hash meant purely //for interaction, so we ignore it. event.preventDefault(); return; } else if ( path.isPath( href ) ) { //we have apath so make it the href we want to load. href = path.makeUrlAbsolute( href, baseUrl ); } else { //we have a simple id so use the documentUrl as its base. href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash ); } } // Should we handle this link, or let the browser deal with it? var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ), // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. isCrossDomainPageLoad = ( $.mobile.allowCrossDomainPages && documentUrl.protocol === "file:" && href.search( /^https?:/ ) != -1 ), //check for protocol or rel and its not an embedded page //TODO overlap in logic from isExternal, rel=external check should be // moved into more comprehensive isExternalLink isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !isCrossDomainPageLoad ); $activeClickedLink = $link.closest( ".ui-btn" ); if( isExternal ) { httpCleanup(); //use default click handling return; } //use ajax var transition = $link.jqmData( "transition" ), direction = $link.jqmData( "direction" ), reverse = ( direction && direction === "reverse" ) || // deprecated - remove by 1.0 $link.jqmData( "back" ), //this may need to be more specific as we use data-rel more role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined; $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role } ); event.preventDefault(); }); //prefetch pages when anchors with data-prefetch are encountered $( ".ui-page" ).live( "pageshow.prefetch", function(){ var urls = []; $( this ).find( "a:jqmData(prefetch)" ).each(function(){ var url = $( this ).attr( "href" ); if ( url && $.inArray( url, urls ) === -1 ) { urls.push( url ); $.mobile.loadPage( url ); } }); } ); //hashchange event handler $window.bind( "hashchange", function( e, triggered ) { //find first page via hash var to = path.stripHash( location.hash ), //transition is false if it's the first page, undefined otherwise (and may be overridden by default) transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined; //if listening is disabled (either globally or temporarily), or it's a dialog hash if( !$.mobile.hashListeningEnabled || urlHistory.ignoreNextHashChange ) { urlHistory.ignoreNextHashChange = false; return; } // special case for dialogs if( urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 ) { // If current active page is not a dialog skip the dialog and continue // in the same direction if(!$.mobile.activePage.is( ".ui-dialog" )) { //determine if we're heading forward or backward and continue accordingly past //the current dialog urlHistory.directHashChange({ currentUrl: to, isBack: function() { window.history.back(); }, isForward: function() { window.history.forward(); } }); // prevent changepage return; } else { var setTo = function() { to = $.mobile.urlHistory.getActive().pageUrl; }; // if the current active page is a dialog and we're navigating // to a dialog use the dialog objected saved in the stack urlHistory.directHashChange({ currentUrl: to, isBack: setTo, isForward: setTo }); } } //if to is defined, load it if ( to ) { to = ( typeof to === "string" && !path.isPath( to ) ) ? ( '#' + to ) : to; $.mobile.changePage( to, { transition: transition, changeHash: false, fromHashChange: true } ); } //there's no hash, go to the first page in the dom else { $.mobile.changePage( $.mobile.firstPage, { transition: transition, changeHash: false, fromHashChange: true } ); } }); //set page min-heights to be device specific $( document ).bind( "pageshow", resetActivePageHeight ); $( window ).bind( "throttledresize", resetActivePageHeight ); };//_registerInternalEvents callback })( jQuery ); /*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { function css3TransitionHandler( name, reverse, $to, $from ) { var deferred = new $.Deferred(), reverseClass = reverse ? " reverse" : "", viewportClass = "ui-mobile-viewport-transitioning viewport-" + name, doneFunc = function() { $to.add( $from ).removeClass( "out in reverse " + name ); if ( $from ) { $from.removeClass( $.mobile.activePageClass ); } $to.parent().removeClass( viewportClass ); deferred.resolve( name, reverse, $to, $from ); }; $to.animationComplete( doneFunc ); $to.parent().addClass( viewportClass ); if ( $from ) { $from.addClass( name + " out" + reverseClass ); } $to.addClass( $.mobile.activePageClass + " " + name + " in" + reverseClass ); return deferred.promise(); } // Make our transition handler public. $.mobile.css3TransitionHandler = css3TransitionHandler; // If the default transition handler is the 'none' handler, replace it with our handler. if ( $.mobile.defaultTransitionHandler === $.mobile.noneTransitionHandler ) { $.mobile.defaultTransitionHandler = css3TransitionHandler; } })( jQuery, this ); /* * jQuery Mobile Framework : "degradeInputs" plugin - degrades inputs to another type after custom enhancements are made. * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.page.prototype.options.degradeInputs = { color: false, date: false, datetime: false, "datetime-local": false, email: false, month: false, number: false, range: "number", search: true, tel: false, time: false, url: false, week: false }; $.mobile.page.prototype.options.keepNative = ":jqmData(role='none'), :jqmData(role='nojs')"; //auto self-init widgets $( document ).bind( "pagecreate enhance", function( e ){ var page = $( e.target ).data( "page" ), o = page.options; // degrade inputs to avoid poorly implemented native functionality $( e.target ).find( "input" ).not( o.keepNative ).each(function() { var $this = $( this ), type = this.getAttribute( "type" ), optType = o.degradeInputs[ type ] || "text"; if ( o.degradeInputs[ type ] ) { $this.replaceWith( $( "<div>" ).html( $this.clone() ).html() .replace( /\s+type=["']?\w+['"]?/, " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\" " ) ); } }); }); })( jQuery );/* * jQuery Mobile Framework : "dialog" plugin. * Copyright (c) jQuery Project * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. */ (function( $, window, undefined ) { $.widget( "mobile.dialog", $.mobile.widget, { options: { closeBtnText : "Close", theme : "a", initSelector : ":jqmData(role='dialog')" }, _create: function() { var $el = this.element, pageTheme = $el.attr( "class" ).match( /ui-body-[a-z]/ ); if( pageTheme.length ){ $el.removeClass( pageTheme[ 0 ] ); } $el.addClass( "ui-body-" + this.options.theme ); // Class the markup for dialog styling // Set aria role $el.attr( "role", "dialog" ) .addClass( "ui-dialog" ) .find( ":jqmData(role='header')" ) .addClass( "ui-corner-top ui-overlay-shadow" ) .prepend( "<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "rel='back' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" ) .end() .find( ":jqmData(role='content'),:jqmData(role='footer')" ) .last() .addClass( "ui-corner-bottom ui-overlay-shadow" ); /* bind events - clicks and submits should use the closing transition that the dialog opened with unless a data-transition is specified on the link/form - if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally */ $el.bind( "vclick submit", function( event ) { var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ), active; if ( $target.length && !$target.jqmData( "transition" ) ) { active = $.mobile.urlHistory.getActive() || {}; $target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) ) .attr( "data-" + $.mobile.ns + "direction", "reverse" ); } }) .bind( "pagehide", function() { $( this ).find( "." + $.mobile.activeBtnClass ).removeClass( $.mobile.activeBtnClass ); }); }, // Close method goes back in history close: function() { window.history.back(); } }); //auto self-init widgets $( $.mobile.dialog.prototype.options.initSelector ).live( "pagecreate", function(){ $( this ).dialog(); }); })( jQuery, this ); /* * jQuery Mobile Framework : This plugin handles theming and layout of headers, footers, and content areas * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.page.prototype.options.backBtnText = "Back"; $.mobile.page.prototype.options.addBackBtn = false; $.mobile.page.prototype.options.backBtnTheme = null; $.mobile.page.prototype.options.headerTheme = "a"; $.mobile.page.prototype.options.footerTheme = "a"; $.mobile.page.prototype.options.contentTheme = null; $( ":jqmData(role='page'), :jqmData(role='dialog')" ).live( "pagecreate", function( e ) { var $page = $( this ), o = $page.data( "page" ).options, pageTheme = o.theme; $( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", this ).each(function() { var $this = $( this ), role = $this.jqmData( "role" ), theme = $this.jqmData( "theme" ), $headeranchors, leftbtn, rightbtn, backBtn; $this.addClass( "ui-" + role ); //apply theming and markup modifications to page,header,content,footer if ( role === "header" || role === "footer" ) { var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme; //add theme class $this.addClass( "ui-bar-" + thisTheme ); // Add ARIA role $this.attr( "role", role === "header" ? "banner" : "contentinfo" ); // Right,left buttons $headeranchors = $this.children( "a" ); leftbtn = $headeranchors.hasClass( "ui-btn-left" ); rightbtn = $headeranchors.hasClass( "ui-btn-right" ); if ( !leftbtn ) { leftbtn = $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length; } if ( !rightbtn ) { rightbtn = $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length; } // Auto-add back btn on pages beyond first view if ( o.addBackBtn && role === "header" && $( ".ui-page" ).length > 1 && $this.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) && !leftbtn ) { backBtn = $( "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" ).prependTo( $this ); // If theme is provided, override default inheritance backBtn.attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme ); } // Page title $this.children( "h1, h2, h3, h4, h5, h6" ) .addClass( "ui-title" ) // Regardless of h element number in src, it becomes h1 for the enhanced page .attr({ "tabindex": "0", "role": "heading", "aria-level": "1" }); } else if ( role === "content" ) { $this.addClass( "ui-body-" + ( theme || pageTheme || o.contentTheme ) ); // Add ARIA role $this.attr( "role", "main" ); } }); }); })( jQuery );/* * jQuery Mobile Framework : "collapsible" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.collapsible", $.mobile.widget, { options: { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsed: false, heading: ">:header,>legend", theme: null, iconTheme: "d", initSelector: ":jqmData(role='collapsible')" }, _create: function() { var $el = this.element, o = this.options, collapsibleContain = $el.addClass( "ui-collapsible-contain" ), collapsibleHeading = $el.find( o.heading ).eq( 0 ), collapsibleContent = collapsibleContain.wrapInner( "<div class='ui-collapsible-content'></div>" ).find( ".ui-collapsible-content" ), collapsibleParent = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ); // Replace collapsibleHeading if it's a legend if ( collapsibleHeading.is( "legend" ) ) { collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading ); collapsibleHeading.next().remove(); } collapsibleHeading //drop heading in before content .insertBefore( collapsibleContent ) //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( "<span class='ui-collapsible-heading-status'></span>" ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a:eq(0)" ) .buttonMarkup({ shadow: !collapsibleParent.length, corners: false, iconPos: "left", icon: "plus", theme: o.theme }) .find( ".ui-icon" ) .removeAttr( "class" ) .buttonMarkup({ shadow: true, corners: true, iconPos: "notext", icon: "plus", theme: o.iconTheme }); if ( !collapsibleParent.length ) { collapsibleHeading .find( "a:eq(0)" ) .addClass( "ui-corner-all" ) .find( ".ui-btn-inner" ) .addClass( "ui-corner-all" ); } else { if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .addClass( "ui-corner-bottom" ); } } //events collapsibleContain .bind( "collapse", function( event ) { if ( ! event.isDefaultPrevented() && $( event.target ).closest( ".ui-collapsible-contain" ).is( collapsibleContain ) ) { event.preventDefault(); collapsibleHeading .addClass( "ui-collapsible-heading-collapsed" ) .find( ".ui-collapsible-heading-status" ) .text( o.expandCueText ) .end() .find( ".ui-icon" ) .removeClass( "ui-icon-minus" ) .addClass( "ui-icon-plus" ); collapsibleContent.addClass( "ui-collapsible-content-collapsed" ).attr( "aria-hidden", true ); if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .addClass( "ui-corner-bottom" ); } } }) .bind( "expand", function( event ) { if ( !event.isDefaultPrevented() ) { event.preventDefault(); collapsibleHeading .removeClass( "ui-collapsible-heading-collapsed" ) .find( ".ui-collapsible-heading-status" ).text( o.collapseCueText ); collapsibleHeading.find( ".ui-icon" ).removeClass( "ui-icon-plus" ).addClass( "ui-icon-minus" ); collapsibleContent.removeClass( "ui-collapsible-content-collapsed" ).attr( "aria-hidden", false ); if ( collapsibleContain.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a:eq(0), .ui-btn-inner" ) .removeClass( "ui-corner-bottom" ); } } }) .trigger( o.collapsed ? "collapse" : "expand" ); // Close others in a set if ( collapsibleParent.length && !collapsibleParent.jqmData( "collapsiblebound" ) ) { collapsibleParent .jqmData( "collapsiblebound", true ) .bind( "expand", function( event ) { $( event.target ) .closest( ".ui-collapsible-contain" ) .siblings( ".ui-collapsible-contain" ) .trigger( "collapse" ); }); var set = collapsibleParent.children( ":jqmData(role='collapsible')" ); set.first() .find( "a:eq(0)" ) .addClass( "ui-corner-top" ) .find( ".ui-btn-inner" ) .addClass( "ui-corner-top" ); set.last().jqmData( "collapsible-last", true ); } collapsibleHeading .bind( "vclick", function( event ) { var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse"; collapsibleContain.trigger( type ); event.preventDefault(); }); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.collapsible.prototype.options.initSelector, e.target ).collapsible(); }); })( jQuery ); /* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.fieldcontain = function( options ) { return this.addClass( "ui-field-contain ui-body ui-br" ); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='fieldcontain')", e.target ).fieldcontain(); }); })( jQuery );/* * jQuery Mobile Framework : plugin for creating CSS grids * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.grid = function( options ) { return this.each(function() { var $this = $( this ), o = $.extend({ grid: null },options), $kids = $this.children(), gridCols = {solo:1, a:2, b:3, c:4, d:5}, grid = o.grid, iterator; if ( !grid ) { if ( $kids.length <= 5 ) { for ( var letter in gridCols ) { if ( gridCols[ letter ] === $kids.length ) { grid = letter; } } } else { grid = "a"; } } iterator = gridCols[grid]; $this.addClass( "ui-grid-" + grid ); $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" ); if ( iterator > 1 ) { $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" ); } if ( iterator > 2 ) { $kids.filter( ":nth-child(3n+3)" ).addClass( "ui-block-c" ); } if ( iterator > 3 ) { $kids.filter( ":nth-child(4n+4)" ).addClass( "ui-block-d" ); } if ( iterator > 4 ) { $kids.filter( ":nth-child(5n+5)" ).addClass( "ui-block-e" ); } }); }; })( jQuery );/* * jQuery Mobile Framework : "navbar" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.navbar", $.mobile.widget, { options: { iconpos: "top", grid: null, initSelector: ":jqmData(role='navbar')" }, _create: function(){ var $navbar = this.element, $navbtns = $navbar.find( "a" ), iconpos = $navbtns.filter( ":jqmData(icon)" ).length ? this.options.iconpos : undefined; $navbar.addClass( "ui-navbar" ) .attr( "role","navigation" ) .find( "ul" ) .grid({ grid: this.options.grid }); if ( !iconpos ) { $navbar.addClass( "ui-navbar-noicons" ); } $navbtns.buttonMarkup({ corners: false, shadow: false, iconpos: iconpos }); $navbar.delegate( "a", "vclick", function( event ) { $navbtns.not( ".ui-state-persist" ).removeClass( $.mobile.activeBtnClass ); $( this ).addClass( $.mobile.activeBtnClass ); }); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.navbar.prototype.options.initSelector, e.target ).navbar(); }); })( jQuery ); /* * jQuery Mobile Framework : "listview" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { //Keeps track of the number of lists per page UID //This allows support for multiple nested list in the same page //https://github.com/jquery/jquery-mobile/issues/1617 var listCountPerPage = {}; $.widget( "mobile.listview", $.mobile.widget, { options: { theme: "c", countTheme: "c", headerTheme: "b", dividerTheme: "b", splitIcon: "arrow-r", splitTheme: "b", inset: false, initSelector: ":jqmData(role='listview')" }, _create: function() { var t = this; // create listview markup t.element.addClass(function( i, orig ) { return orig + " ui-listview " + ( t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "" ); }); t.refresh(); }, _itemApply: function( $list, item ) { // TODO class has to be defined in markup item.find( ".ui-li-count" ) .addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme ) + " ui-btn-corner-all" ).end() .find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" ).end() .find( "p, dl" ).addClass( "ui-li-desc" ).end() .find( ">img:eq(0), .ui-link-inherit>img:eq(0)" ).addClass( "ui-li-thumb" ).each(function() { item.addClass( $(this).is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" ); }).end() .find( ".ui-li-aside" ).each(function() { var $this = $(this); $this.prependTo( $this.parent() ); //shift aside to front for css float }); }, _removeCorners: function( li, which ) { var top = "ui-corner-top ui-corner-tr ui-corner-tl", bot = "ui-corner-bottom ui-corner-br ui-corner-bl"; li = li.add( li.find( ".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb" ) ); if ( which === "top" ) { li.removeClass( top ); } else if ( which === "bottom" ) { li.removeClass( bot ); } else { li.removeClass( top + " " + bot ); } }, refresh: function( create ) { this.parentPage = this.element.closest( ".ui-page" ); this._createSubPages(); var o = this.options, $list = this.element, self = this, dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme, listsplittheme = $list.jqmData( "splittheme" ), listspliticon = $list.jqmData( "spliticon" ), li = $list.children( "li" ), counter = $.support.cssPseudoElement || !$.nodeName( $list[ 0 ], "ol" ) ? 0 : 1, item, itemClass, itemTheme, a, last, splittheme, countParent, icon; if ( counter ) { $list.find( ".ui-li-dec" ).remove(); } for ( var pos = 0, numli = li.length; pos < numli; pos++ ) { item = li.eq( pos ); itemClass = "ui-li"; // If we're creating the element, we update it regardless if ( create || !item.hasClass( "ui-li" ) ) { itemTheme = item.jqmData("theme") || o.theme; a = item.children( "a" ); if ( a.length ) { icon = item.jqmData("icon"); item.buttonMarkup({ wrapperEls: "div", shadow: false, corners: false, iconpos: "right", icon: a.length > 1 || icon === false ? false : icon || "arrow-r", theme: itemTheme }); a.first().addClass( "ui-link-inherit" ); if ( a.length > 1 ) { itemClass += " ui-li-has-alt"; last = a.last(); splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme; last.appendTo(item) .attr( "title", last.text() ) .addClass( "ui-li-link-alt" ) .empty() .buttonMarkup({ shadow: false, corners: false, theme: itemTheme, icon: false, iconpos: false }) .find( ".ui-btn-inner" ) .append( $( "<span />" ).buttonMarkup({ shadow: true, corners: true, theme: splittheme, iconpos: "notext", icon: listspliticon || last.jqmData( "icon" ) || o.splitIcon }) ); } } else if ( item.jqmData( "role" ) === "list-divider" ) { itemClass += " ui-li-divider ui-btn ui-bar-" + dividertheme; item.attr( "role", "heading" ); //reset counter when a divider heading is encountered if ( counter ) { counter = 1; } } else { itemClass += " ui-li-static ui-body-" + itemTheme; } } if ( o.inset ) { if ( pos === 0 ) { itemClass += " ui-corner-top"; item.add( item.find( ".ui-btn-inner" ) ) .find( ".ui-li-link-alt" ) .addClass( "ui-corner-tr" ) .end() .find( ".ui-li-thumb" ) .addClass( "ui-corner-tl" ); if ( item.next().next().length ) { self._removeCorners( item.next() ); } } if ( pos === li.length - 1 ) { itemClass += " ui-corner-bottom"; item.add( item.find( ".ui-btn-inner" ) ) .find( ".ui-li-link-alt" ) .addClass( "ui-corner-br" ) .end() .find( ".ui-li-thumb" ) .addClass( "ui-corner-bl" ); if ( item.prev().prev().length ) { self._removeCorners( item.prev() ); } else if ( item.prev().length ) { self._removeCorners( item.prev(), "bottom" ); } } } if ( counter && itemClass.indexOf( "ui-li-divider" ) < 0 ) { countParent = item.is( ".ui-li-static:first" ) ? item : item.find( ".ui-link-inherit" ); countParent.addClass( "ui-li-jsnumbering" ) .prepend( "<span class='ui-li-dec'>" + (counter++) + ". </span>" ); } item.add( item.children( ".ui-btn-inner" ) ).addClass( itemClass ); if ( !create ) { self._itemApply( $list, item ); } } }, //create a string for ID/subpage url creation _idStringEscape: function( str ) { return str.replace(/[^a-zA-Z0-9]/g, '-'); }, _createSubPages: function() { var parentList = this.element, parentPage = parentList.closest( ".ui-page" ), parentUrl = parentPage.jqmData( "url" ), parentId = parentUrl || parentPage[ 0 ][ $.expando ], parentListId = parentList.attr( "id" ), o = this.options, dns = "data-" + $.mobile.ns, self = this, persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ), hasSubPages; if ( typeof listCountPerPage[ parentId ] === "undefined" ) { listCountPerPage[ parentId ] = -1; } parentListId = parentListId || ++listCountPerPage[ parentId ]; $( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) { var self = this, list = $( this ), listId = list.attr( "id" ) || parentListId + "-" + i, parent = list.parent(), nodeEls = $( list.prevAll().toArray().reverse() ), nodeEls = nodeEls.length ? nodeEls : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ), title = nodeEls.first().text(),//url limits to first 30 chars of text id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId, theme = list.jqmData( "theme" ) || o.theme, countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme, newPage, anchor; //define hasSubPages for use in later removal hasSubPages = true; newPage = list.detach() .wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" ) .parent() .before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" ) .after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>") : "" ) .parent() .appendTo( $.mobile.pageContainer ); newPage.page(); anchor = parent.find('a:first'); if ( !anchor.length ) { anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() ); } anchor.attr( "href", "#" + id ); }).listview(); //on pagehide, remove any nested pages along with the parent page, as long as they aren't active if( hasSubPages && parentPage.data("page").options.domCache === false ){ var newRemove = function( e, ui ){ var nextPage = ui.nextPage, npURL; if( ui.nextPage ){ npURL = nextPage.jqmData( "url" ); if( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ){ self.childPages().remove(); parentPage.remove(); } } }; // unbind the original page remove and replace with our specialized version parentPage .unbind( "pagehide.remove" ) .bind( "pagehide.remove", newRemove); } }, // TODO sort out a better way to track sub pages of the listview this is brittle childPages: function(){ var parentUrl = this.parentPage.jqmData( "url" ); return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey +"')"); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.listview.prototype.options.initSelector, e.target ).listview(); }); })( jQuery ); /* * jQuery Mobile Framework : "listview" filter extension * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.mobile.listview.prototype.options.filter = false; $.mobile.listview.prototype.options.filterPlaceholder = "Filter items..."; $.mobile.listview.prototype.options.filterTheme = "c"; $( ":jqmData(role='listview')" ).live( "listviewcreate", function() { var list = $( this ), listview = list.data( "listview" ); if ( !listview.options.filter ) { return; } var wrapper = $( "<form>", { "class": "ui-listview-filter ui-bar-" + listview.options.filterTheme, "role": "search" }), search = $( "<input>", { placeholder: listview.options.filterPlaceholder }) .attr( "data-" + $.mobile.ns + "type", "search" ) .jqmData( "lastval", "" ) .bind( "keyup change", function() { var $this = $(this), val = this.value.toLowerCase(), listItems = null, lastval = $this.jqmData( "lastval" ) + "", childItems = false, itemtext = "", item; // Change val as lastval for next execution $this.jqmData( "lastval" , val ); change = val.replace( new RegExp( "^" + lastval ) , "" ); if ( val.length < lastval.length || change.length != ( val.length - lastval.length ) ) { // Removed chars or pasted something totaly different, check all items listItems = list.children(); } else { // Only chars added, not removed, only use visible subset listItems = list.children( ":not(.ui-screen-hidden)" ); } if ( val ) { // This handles hiding regular rows without the text we search for // and any list dividers without regular rows shown under it for ( var i = listItems.length - 1; i >= 0; i-- ) { item = $( listItems[ i ] ); itemtext = item.jqmData( "filtertext" ) || item.text(); if ( item.is( "li:jqmData(role=list-divider)" ) ) { item.toggleClass( "ui-filter-hidequeue" , !childItems ); // New bucket! childItems = false; } else if ( itemtext.toLowerCase().indexOf( val ) === -1 ) { //mark to be hidden item.toggleClass( "ui-filter-hidequeue" , true ); } else { // There"s a shown item in the bucket childItems = true; } } // Show items, not marked to be hidden listItems .filter( ":not(.ui-filter-hidequeue)" ) .toggleClass( "ui-screen-hidden", false ); // Hide items, marked to be hidden listItems .filter( ".ui-filter-hidequeue" ) .toggleClass( "ui-screen-hidden", true ) .toggleClass( "ui-filter-hidequeue", false ); } else { //filtervalue is empty => show all listItems.toggleClass( "ui-screen-hidden", false ); } }) .appendTo( wrapper ) .textinput(); if ( $( this ).jqmData( "inset" ) ) { wrapper.addClass( "ui-listview-filter-inset" ); } wrapper.bind( "submit", function() { return false; }) .insertBefore( list ); }); })( jQuery );/* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" ); }); })( jQuery );/* * jQuery Mobile Framework : "checkboxradio" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.checkboxradio", $.mobile.widget, { options: { theme: null, initSelector: "input[type='checkbox'],input[type='radio']" }, _create: function() { var self = this, input = this.element, // NOTE: Windows Phone could not find the label through a selector // filter works though. label = input.closest( "form,fieldset,:jqmData(role='page')" ).find( "label" ).filter( "[for='" + input[ 0 ].id + "']"), inputtype = input.attr( "type" ), checkedState = inputtype + "-on", uncheckedState = inputtype + "-off", icon = input.parents( ":jqmData(type='horizontal')" ).length ? undefined : uncheckedState, activeBtn = icon ? "" : " " + $.mobile.activeBtnClass, checkedClass = "ui-" + checkedState + activeBtn, uncheckedClass = "ui-" + uncheckedState, checkedicon = "ui-icon-" + checkedState, uncheckedicon = "ui-icon-" + uncheckedState; if ( inputtype !== "checkbox" && inputtype !== "radio" ) { return; } // Expose for other methods $.extend( this, { label: label, inputtype: inputtype, checkedClass: checkedClass, uncheckedClass: uncheckedClass, checkedicon: checkedicon, uncheckedicon: uncheckedicon }); // If there's no selected theme... if( !this.options.theme ) { this.options.theme = this.element.jqmData( "theme" ); } label.buttonMarkup({ theme: this.options.theme, icon: icon, shadow: false }); // Wrap the input + label in a div input.add( label ) .wrapAll( "<div class='ui-" + inputtype + "'></div>" ); label.bind({ vmouseover: function() { if ( $( this ).parent().is( ".ui-disabled" ) ) { return false; } }, vclick: function( event ) { if ( input.is( ":disabled" ) ) { event.preventDefault(); return; } self._cacheVals(); input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) ); // Input set for common radio buttons will contain all the radio // buttons, but will not for checkboxes. clearing the checked status // of other radios ensures the active button state is applied properly self._getInputSet().not( input ).prop( "checked", false ); self._updateAll(); return false; } }); input .bind({ vmousedown: function() { this._cacheVals(); }, vclick: function() { var $this = $(this); // Adds checked attribute to checked input when keyboard is used if ( $this.is( ":checked" ) ) { $this.prop( "checked", true); self._getInputSet().not($this).prop( "checked", false ); } else { $this.prop( "checked", false ); } self._updateAll(); }, focus: function() { label.addClass( "ui-focus" ); }, blur: function() { label.removeClass( "ui-focus" ); } }); this.refresh(); }, _cacheVals: function() { this._getInputSet().each(function() { var $this = $(this); $this.jqmData( "cacheVal", $this.is( ":checked" ) ); }); }, //returns either a set of radios with the same name attribute, or a single checkbox _getInputSet: function(){ if(this.inputtype == "checkbox") { return this.element; } return this.element.closest( "form,fieldset,:jqmData(role='page')" ) .find( "input[name='"+ this.element.attr( "name" ) +"'][type='"+ this.inputtype +"']" ); }, _updateAll: function() { var self = this; this._getInputSet().each(function() { var $this = $(this); if ( $this.is( ":checked" ) || self.inputtype === "checkbox" ) { $this.trigger( "change" ); } }) .checkboxradio( "refresh" ); }, refresh: function() { var input = this.element, label = this.label, icon = label.find( ".ui-icon" ); // input[0].checked expando doesn't always report the proper value // for checked='checked' if ( $( input[ 0 ] ).prop( "checked" ) ) { label.addClass( this.checkedClass ).removeClass( this.uncheckedClass ); icon.addClass( this.checkedicon ).removeClass( this.uncheckedicon ); } else { label.removeClass( this.checkedClass ).addClass( this.uncheckedClass ); icon.removeClass( this.checkedicon ).addClass( this.uncheckedicon ); } if ( input.is( ":disabled" ) ) { this.disable(); } else { this.enable(); } }, disable: function() { this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" ); }, enable: function() { this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.checkboxradio.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .checkboxradio(); }); })( jQuery ); /* * jQuery Mobile Framework : "button" plugin - links that proxy to native input/buttons * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.button", $.mobile.widget, { options: { theme: null, icon: null, iconpos: null, inline: null, corners: true, shadow: true, iconshadow: true, initSelector: "button, [type='button'], [type='submit'], [type='reset'], [type='image']" }, _create: function() { var $el = this.element, o = this.options, type; // Add ARIA role this.button = $( "<div></div>" ) .text( $el.text() || $el.val() ) .buttonMarkup({ theme: o.theme, icon: o.icon, iconpos: o.iconpos, inline: o.inline, corners: o.corners, shadow: o.shadow, iconshadow: o.iconshadow }) .insertBefore( $el ) .append( $el.addClass( "ui-btn-hidden" ) ); // Add hidden input during submit type = $el.attr( "type" ); if ( type !== "button" && type !== "reset" ) { $el.bind( "vclick", function() { var $buttonPlaceholder = $( "<input>", { type: "hidden", name: $el.attr( "name" ), value: $el.attr( "value" ) }) .insertBefore( $el ); // Bind to doc to remove after submit handling $( document ).submit(function(){ $buttonPlaceholder.remove(); }); }); } this.refresh(); }, enable: function() { this.element.attr( "disabled", false ); this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); }, refresh: function() { if ( this.element.attr( "disabled" ) ) { this.disable(); } else { this.enable(); } } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.button.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .button(); }); })( jQuery );/* * jQuery Mobile Framework : "slider" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { $.widget( "mobile.slider", $.mobile.widget, { options: { theme: null, trackTheme: null, disabled: false, initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')" }, _create: function() { // TODO: Each of these should have comments explain what they're for var self = this, control = this.element, parentTheme = control.parents( "[class*='ui-bar-'],[class*='ui-body-']" ).eq( 0 ), parentTheme = parentTheme.length ? parentTheme.attr( "class" ).match( /ui-(bar|body)-([a-z])/ )[ 2 ] : "c", theme = this.options.theme ? this.options.theme : parentTheme, trackTheme = this.options.trackTheme ? this.options.trackTheme : parentTheme, cType = control[ 0 ].nodeName.toLowerCase(), selectClass = ( cType == "select" ) ? "ui-slider-switch" : "", controlID = control.attr( "id" ), labelID = controlID + "-label", label = $( "[for='"+ controlID +"']" ).attr( "id", labelID ), val = function() { return cType == "input" ? parseFloat( control.val() ) : control[0].selectedIndex; }, min = cType == "input" ? parseFloat( control.attr( "min" ) ) : 0, max = cType == "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1, step = window.parseFloat( control.attr( "step" ) || 1 ), slider = $( "<div class='ui-slider " + selectClass + " ui-btn-down-" + trackTheme + " ui-btn-corner-all' role='application'></div>" ), handle = $( "<a href='#' class='ui-slider-handle'></a>" ) .appendTo( slider ) .buttonMarkup({ corners: true, theme: theme, shadow: true }) .attr({ "role": "slider", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": val(), "aria-valuetext": val(), "title": val(), "aria-labelledby": labelID }), options; $.extend( this, { slider: slider, handle: handle, dragging: false, beforeStart: null }); if ( cType == "select" ) { slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" ); options = control.find( "option" ); control.find( "option" ).each(function( i ) { var side = !i ? "b":"a", corners = !i ? "right" :"left", theme = !i ? " ui-btn-down-" + trackTheme :" ui-btn-active"; $( "<div class='ui-slider-labelbg ui-slider-labelbg-" + side + theme + " ui-btn-corner-" + corners + "'></div>" ) .prependTo( slider ); $( "<span class='ui-slider-label ui-slider-label-" + side + theme + " ui-btn-corner-" + corners + "' role='img'>" + $( this ).text() + "</span>" ) .prependTo( handle ); }); } label.addClass( "ui-slider" ); // monitor the input for updated values control.addClass( cType === "input" ? "ui-slider-input" : "ui-slider-switch" ) .change( function() { self.refresh( val(), true ); }) .keyup( function() { // necessary? self.refresh( val(), true, true ); }) .blur( function() { self.refresh( val(), true ); }); // prevent screen drag when slider activated $( document ).bind( "vmousemove", function( event ) { if ( self.dragging ) { self.refresh( event ); return false; } }); slider.bind( "vmousedown", function( event ) { self.dragging = true; if ( cType === "select" ) { self.beforeStart = control[0].selectedIndex; } self.refresh( event ); return false; }); slider.add( document ) .bind( "vmouseup", function() { if ( self.dragging ) { self.dragging = false; if ( cType === "select" ) { if ( self.beforeStart === control[ 0 ].selectedIndex ) { //tap occurred, but value didn't change. flip it! self.refresh( !self.beforeStart ? 1 : 0 ); } var curval = val(); var snapped = Math.round( curval / ( max - min ) * 100 ); handle .addClass( "ui-slider-handle-snapping" ) .css( "left", snapped + "%" ) .animationComplete( function() { handle.removeClass( "ui-slider-handle-snapping" ); }); } return false; } }); slider.insertAfter( control ); // NOTE force focus on handle this.handle .bind( "vmousedown", function() { $( this ).focus(); }) .bind( "vclick", false ); this.handle .bind( "keydown", function( event ) { var index = val(); if ( self.options.disabled ) { return; } // In all cases prevent the default and mark the handle as active switch ( event.keyCode ) { case $.mobile.keyCode.HOME: case $.mobile.keyCode.END: case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: event.preventDefault(); if ( !self._keySliding ) { self._keySliding = true; $( this ).addClass( "ui-state-active" ); } break; } // move the slider according to the keypress switch ( event.keyCode ) { case $.mobile.keyCode.HOME: self.refresh( min ); break; case $.mobile.keyCode.END: self.refresh( max ); break; case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: self.refresh( index + step ); break; case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: self.refresh( index - step ); break; } }) // remove active mark .keyup( function( event ) { if ( self._keySliding ) { self._keySliding = false; $( this ).removeClass( "ui-state-active" ); } }); this.refresh(undefined, undefined, true); }, refresh: function( val, isfromControl, preventInputUpdate ) { if ( this.options.disabled ) { return; } var control = this.element, percent, cType = control[0].nodeName.toLowerCase(), min = cType === "input" ? parseFloat( control.attr( "min" ) ) : 0, max = cType === "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length - 1; if ( typeof val === "object" ) { var data = val, // a slight tolerance helped get to the ends of the slider tol = 8; if ( !this.dragging || data.pageX < this.slider.offset().left - tol || data.pageX > this.slider.offset().left + this.slider.width() + tol ) { return; } percent = Math.round( ( ( data.pageX - this.slider.offset().left ) / this.slider.width() ) * 100 ); } else { if ( val == null ) { val = cType === "input" ? parseFloat( control.val() ) : control[0].selectedIndex; } percent = ( parseFloat( val ) - min ) / ( max - min ) * 100; } if ( isNaN( percent ) ) { return; } if ( percent < 0 ) { percent = 0; } if ( percent > 100 ) { percent = 100; } var newval = Math.round( ( percent / 100 ) * ( max - min ) ) + min; if ( newval < min ) { newval = min; } if ( newval > max ) { newval = max; } // Flip the stack of the bg colors if ( percent > 60 && cType === "select" ) { // TODO: Dead path? } this.handle.css( "left", percent + "%" ); this.handle.attr( { "aria-valuenow": cType === "input" ? newval : control.find( "option" ).eq( newval ).attr( "value" ), "aria-valuetext": cType === "input" ? newval : control.find( "option" ).eq( newval ).text(), title: newval }); // add/remove classes for flip toggle switch if ( cType === "select" ) { if ( newval === 0 ) { this.slider.addClass( "ui-slider-switch-a" ) .removeClass( "ui-slider-switch-b" ); } else { this.slider.addClass( "ui-slider-switch-b" ) .removeClass( "ui-slider-switch-a" ); } } if ( !preventInputUpdate ) { // update control"s value if ( cType === "input" ) { control.val( newval ); } else { control[ 0 ].selectedIndex = newval; } if ( !isfromControl ) { control.trigger( "change" ); } } }, enable: function() { this.element.attr( "disabled", false ); this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.slider.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .slider(); }); })( jQuery );/* * jQuery Mobile Framework : "textinput" plugin for text inputs, textareas * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.widget, { options: { theme: null, initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea" }, _create: function() { var input = this.element, o = this.options, theme = o.theme, themedParent, themeclass, themeLetter, focusedEl, clearbtn; if ( !theme ) { themedParent = this.element.closest( "[class*='ui-bar-'],[class*='ui-body-']" ); themeLetter = themedParent.length && /ui-(bar|body)-([a-z])/.exec( themedParent.attr( "class" ) ); theme = themeLetter && themeLetter[2] || "c"; } themeclass = " ui-body-" + theme; $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" ); input.addClass("ui-input-text ui-body-"+ o.theme ); focusedEl = input; // XXX: Temporary workaround for issue 785. Turn off autocorrect and // autocomplete since the popup they use can't be dismissed by // the user. Note that we test for the presence of the feature // by looking for the autocorrect property on the input element. if ( typeof input[0].autocorrect !== "undefined" ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. input[0].setAttribute( "autocorrect", "off" ); input[0].setAttribute( "autocomplete", "off" ); } //"search" input widget if ( input.is( "[type='search'],:jqmData(type='search')" ) ) { focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + "'></div>" ).parent(); clearbtn = $( "<a href='#' class='ui-input-clear' title='clear text'>clear text</a>" ) .tap(function( event ) { input.val( "" ).focus(); input.trigger( "change" ); clearbtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }) .appendTo( focusedEl ) .buttonMarkup({ icon: "delete", iconpos: "notext", corners: true, shadow: true }); function toggleClear() { if ( !input.val() ) { clearbtn.addClass( "ui-input-clear-hidden" ); } else { clearbtn.removeClass( "ui-input-clear-hidden" ); } } toggleClear(); input.keyup( toggleClear ) .focus( toggleClear ); } else { input.addClass( "ui-corner-all ui-shadow-inset" + themeclass ); } input.focus(function() { focusedEl.addClass( "ui-focus" ); }) .blur(function(){ focusedEl.removeClass( "ui-focus" ); }); // Autogrow if ( input.is( "textarea" ) ) { var extraLineHeight = 15, keyupTimeoutBuffer = 100, keyup = function() { var scrollHeight = input[ 0 ].scrollHeight, clientHeight = input[ 0 ].clientHeight; if ( clientHeight < scrollHeight ) { input.css({ height: (scrollHeight + extraLineHeight) }); } }, keyupTimeout; input.keyup(function() { clearTimeout( keyupTimeout ); keyupTimeout = setTimeout( keyup, keyupTimeoutBuffer ); }); } }, disable: function(){ ( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).addClass( "ui-disabled" ); }, enable: function(){ ( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.textinput.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .textinput(); }); })( jQuery ); /* * jQuery Mobile Framework : "selectmenu" plugin * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.selectmenu", $.mobile.widget, { options: { theme: null, disabled: false, icon: "arrow-d", iconpos: "right", inline: null, corners: true, shadow: true, iconshadow: true, menuPageTheme: "b", overlayTheme: "a", hidePlaceholderMenuItems: true, closeText: "Close", nativeMenu: true, initSelector: "select:not(:jqmData(role='slider'))" }, _create: function() { var self = this, o = this.options, select = this.element .wrap( "<div class='ui-select'>" ), selectID = select.attr( "id" ), label = $( "label[for='"+ selectID +"']" ).addClass( "ui-select" ), // IE throws an exception at options.item() function when // there is no selected item // select first in this case selectedIndex = select[ 0 ].selectedIndex == -1 ? 0 : select[ 0 ].selectedIndex, button = ( self.options.nativeMenu ? $( "<div/>" ) : $( "<a>", { "href": "#", "role": "button", "id": buttonId, "aria-haspopup": "true", "aria-owns": menuId }) ) .text( $( select[ 0 ].options.item( selectedIndex ) ).text() ) .insertBefore( select ) .buttonMarkup({ theme: o.theme, icon: o.icon, iconpos: o.iconpos, inline: o.inline, corners: o.corners, shadow: o.shadow, iconshadow: o.iconshadow }), // Multi select or not isMultiple = self.isMultiple = select[ 0 ].multiple; // Opera does not properly support opacity on select elements // In Mini, it hides the element, but not its text // On the desktop,it seems to do the opposite // for these reasons, using the nativeMenu option results in a full native select in Opera if ( o.nativeMenu && window.opera && window.opera.version ) { select.addClass( "ui-select-nativeonly" ); } //vars for non-native menus if ( !o.nativeMenu ) { var options = select.find("option"), buttonId = selectID + "-button", menuId = selectID + "-menu", thisPage = select.closest( ".ui-page" ), //button theme theme = /ui-btn-up-([a-z])/.exec( button.attr( "class" ) )[1], menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' data-" +$.mobile.ns + "theme='"+ o.menuPageTheme +"'>" + "<div data-" + $.mobile.ns + "role='header'>" + "<div class='ui-title'>" + label.text() + "</div>"+ "</div>"+ "<div data-" + $.mobile.ns + "role='content'></div>"+ "</div>" ) .appendTo( $.mobile.pageContainer ) .page(), menuPageContent = menuPage.find( ".ui-content" ), menuPageClose = menuPage.find( ".ui-header a" ), screen = $( "<div>", {"class": "ui-selectmenu-screen ui-screen-hidden"}) .appendTo( thisPage ), listbox = $("<div>", { "class": "ui-selectmenu ui-selectmenu-hidden ui-overlay-shadow ui-corner-all ui-body-" + o.overlayTheme + " " + $.mobile.defaultDialogTransition }) .insertAfter(screen), list = $( "<ul>", { "class": "ui-selectmenu-list", "id": menuId, "role": "listbox", "aria-labelledby": buttonId }) .attr( "data-" + $.mobile.ns + "theme", theme ) .appendTo( listbox ), header = $( "<div>", { "class": "ui-header ui-bar-" + theme }) .prependTo( listbox ), headerTitle = $( "<h1>", { "class": "ui-title" }) .appendTo( header ), headerClose = $( "<a>", { "text": o.closeText, "href": "#", "class": "ui-btn-left" }) .attr( "data-" + $.mobile.ns + "iconpos", "notext" ) .attr( "data-" + $.mobile.ns + "icon", "delete" ) .appendTo( header ) .buttonMarkup(), menuType; } // End non native vars // Add counter for multi selects if ( isMultiple ) { self.buttonCount = $( "<span>" ) .addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" ) .hide() .appendTo( button ); } // Disable if specified if ( o.disabled ) { this.disable(); } // Events on native select select.change(function() { self.refresh(); }); // Expose to other methods $.extend( self, { select: select, optionElems: options, selectID: selectID, label: label, buttonId: buttonId, menuId: menuId, thisPage: thisPage, button: button, menuPage: menuPage, menuPageContent: menuPageContent, screen: screen, listbox: listbox, list: list, menuType: menuType, header: header, headerClose: headerClose, headerTitle: headerTitle, placeholder: "" }); // Support for using the native select menu with a custom button if ( o.nativeMenu ) { select.appendTo( button ) .bind( "vmousedown", function() { // Add active class to button button.addClass( $.mobile.activeBtnClass ); }) .bind( "focus vmouseover", function() { button.trigger( "vmouseover" ); }) .bind( "vmousemove", function() { // Remove active class on scroll/touchmove button.removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur vmouseout", function() { button.trigger( "vmouseout" ) .removeClass( $.mobile.activeBtnClass ); }); } else { // Create list from select, update state self.refresh(); select.attr( "tabindex", "-1" ) .focus(function() { $(this).blur(); button.focus(); }); // Button events button.bind( "vclick keydown" , function( event ) { if ( event.type == "vclick" || event.keyCode && ( event.keyCode === $.mobile.keyCode.ENTER || event.keyCode === $.mobile.keyCode.SPACE ) ) { self.open(); event.preventDefault(); } }); // Events for list items list.attr( "role", "listbox" ) .delegate( ".ui-li>a", "focusin", function() { $( this ).attr( "tabindex", "0" ); }) .delegate( ".ui-li>a", "focusout", function() { $( this ).attr( "tabindex", "-1" ); }) .delegate( "li:not(.ui-disabled, .ui-li-divider)", "vclick", function( event ) { var $this = $( this ), // index of option tag to be selected oldIndex = select[ 0 ].selectedIndex, newIndex = $this.jqmData( "option-index" ), option = self.optionElems[ newIndex ]; // toggle selected status on the tag for multi selects option.selected = isMultiple ? !option.selected : true; // toggle checkbox class for multiple selects if ( isMultiple ) { $this.find( ".ui-icon" ) .toggleClass( "ui-icon-checkbox-on", option.selected ) .toggleClass( "ui-icon-checkbox-off", !option.selected ); } // trigger change if value changed if ( isMultiple || oldIndex !== newIndex ) { select.trigger( "change" ); } //hide custom select for single selects only if ( !isMultiple ) { self.close(); } event.preventDefault(); }) //keyboard events for menu items .keydown(function( event ) { var target = $( event.target ), li = target.closest( "li" ), prev, next; // switch logic based on which key was pressed switch ( event.keyCode ) { // up or left arrow keys case 38: prev = li.prev(); // if there's a previous option, focus it if ( prev.length ) { target .blur() .attr( "tabindex", "-1" ); prev.find( "a" ).first().focus(); } return false; break; // down or right arrow keys case 40: next = li.next(); // if there's a next option, focus it if ( next.length ) { target .blur() .attr( "tabindex", "-1" ); next.find( "a" ).first().focus(); } return false; break; // If enter or space is pressed, trigger click case 13: case 32: target.trigger( "vclick" ); return false; break; } }); // button refocus ensures proper height calculation // by removing the inline style and ensuring page inclusion self.menuPage.bind( "pagehide", function(){ self.list.appendTo( self.listbox ); self._focusButton(); }); // Events on "screen" overlay screen.bind( "vclick", function( event ) { self.close(); }); // Close button on small overlays self.headerClose.click(function() { if ( self.menuType == "overlay" ) { self.close(); return false; } }); } }, _buildList: function() { var self = this, o = this.options, placeholder = this.placeholder, optgroups = [], lis = [], dataIcon = self.isMultiple ? "checkbox-off" : "false"; self.list.empty().filter( ".ui-listview" ).listview( "destroy" ); // Populate menu with options from select element self.select.find( "option" ).each(function( i ) { var $this = $( this ), $parent = $this.parent(), text = $this.text(), anchor = "<a href='#'>"+ text +"</a>", classes = [], extraAttrs = []; // Are we inside an optgroup? if ( $parent.is( "optgroup" ) ) { var optLabel = $parent.attr( "label" ); // has this optgroup already been built yet? if ( $.inArray( optLabel, optgroups ) === -1 ) { lis.push( "<li data-" + $.mobile.ns + "role='list-divider'>"+ optLabel +"</li>" ); optgroups.push( optLabel ); } } // Find placeholder text // TODO: Are you sure you want to use getAttribute? ^RW if ( !this.getAttribute( "value" ) || text.length == 0 || $this.jqmData( "placeholder" ) ) { if ( o.hidePlaceholderMenuItems ) { classes.push( "ui-selectmenu-placeholder" ); } placeholder = self.placeholder = text; } // support disabled option tags if ( this.disabled ) { classes.push( "ui-disabled" ); extraAttrs.push( "aria-disabled='true'" ); } lis.push( "<li data-" + $.mobile.ns + "option-index='" + i + "' data-" + $.mobile.ns + "icon='"+ dataIcon +"' class='"+ classes.join(" ") + "' " + extraAttrs.join(" ") +">"+ anchor +"</li>" ) }); self.list.html( lis.join(" ") ); self.list.find( "li" ) .attr({ "role": "option", "tabindex": "-1" }) .first().attr( "tabindex", "0" ); // Hide header close link for single selects if ( !this.isMultiple ) { this.headerClose.hide(); } // Hide header if it's not a multiselect and there's no placeholder if ( !this.isMultiple && !placeholder.length ) { this.header.hide(); } else { this.headerTitle.text( this.placeholder ); } // Now populated, create listview self.list.listview(); }, refresh: function( forceRebuild ) { var self = this, select = this.element, isMultiple = this.isMultiple, options = this.optionElems = select.find( "option" ), selected = options.filter( ":selected" ), // return an array of all selected index's indicies = selected.map(function() { return options.index( this ); }).get(); if ( !self.options.nativeMenu && ( forceRebuild || select[0].options.length != self.list.find( "li" ).length ) ) { self._buildList(); } self.button.find( ".ui-btn-text" ) .text(function() { if ( !isMultiple ) { return selected.text(); } return selected.length ? selected.map(function() { return $( this ).text(); }).get().join( ", " ) : self.placeholder; }); // multiple count inside button if ( isMultiple ) { self.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length ); } if ( !self.options.nativeMenu ) { self.list.find( "li:not(.ui-li-divider)" ) .removeClass( $.mobile.activeBtnClass ) .attr( "aria-selected", false ) .each(function( i ) { if ( $.inArray( i, indicies ) > -1 ) { var item = $( this ).addClass( $.mobile.activeBtnClass ); // Aria selected attr item.find( "a" ).attr( "aria-selected", true ); // Multiple selects: add the "on" checkbox state to the icon if ( isMultiple ) { item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" ); } } }); } }, open: function() { if ( this.options.disabled || this.options.nativeMenu ) { return; } var self = this, menuHeight = self.list.parent().outerHeight(), menuWidth = self.list.parent().outerWidth(), scrollTop = $( window ).scrollTop(), btnOffset = self.button.offset().top, screenHeight = window.innerHeight, screenWidth = window.innerWidth; //add active class to button self.button.addClass( $.mobile.activeBtnClass ); //remove after delay setTimeout(function() { self.button.removeClass( $.mobile.activeBtnClass ); }, 300); function focusMenuItem() { self.list.find( ".ui-btn-active" ).focus(); } if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) { // prevent the parent page from being removed from the DOM, // otherwise the results of selecting a list item in the dialog // fall into a black hole self.thisPage.unbind( "pagehide.remove" ); //for webos (set lastscroll using button offset) if ( scrollTop == 0 && btnOffset > screenHeight ) { self.thisPage.one( "pagehide", function() { $( this ).jqmData( "lastScroll", btnOffset ); }); } self.menuPage.one( "pageshow", function() { // silentScroll() is called whenever a page is shown to restore // any previous scroll position the page may have had. We need to // wait for the "silentscroll" event before setting focus to avoid // the browser"s "feature" which offsets rendering to make sure // whatever has focus is in view. $( window ).one( "silentscroll", function() { focusMenuItem(); }); self.isOpen = true; }); self.menuType = "page"; self.menuPageContent.append( self.list ); $.mobile.changePage( self.menuPage, { transition: $.mobile.defaultDialogTransition }); } else { self.menuType = "overlay"; self.screen.height( $(document).height() ) .removeClass( "ui-screen-hidden" ); // Try and center the overlay over the button var roomtop = btnOffset - scrollTop, roombot = scrollTop + screenHeight - btnOffset, halfheight = menuHeight / 2, maxwidth = parseFloat( self.list.parent().css( "max-width" ) ), newtop, newleft; if ( roomtop > menuHeight / 2 && roombot > menuHeight / 2 ) { newtop = btnOffset + ( self.button.outerHeight() / 2 ) - halfheight; } else { // 30px tolerance off the edges newtop = roomtop > roombot ? scrollTop + screenHeight - menuHeight - 30 : scrollTop + 30; } // If the menuwidth is smaller than the screen center is if ( menuWidth < maxwidth ) { newleft = ( screenWidth - menuWidth ) / 2; } else { //otherwise insure a >= 30px offset from the left newleft = self.button.offset().left + self.button.outerWidth() / 2 - menuWidth / 2; // 30px tolerance off the edges if ( newleft < 30 ) { newleft = 30; } else if ( ( newleft + menuWidth ) > screenWidth ) { newleft = screenWidth - menuWidth - 30; } } self.listbox.append( self.list ) .removeClass( "ui-selectmenu-hidden" ) .css({ top: newtop, left: newleft }) .addClass( "in" ); focusMenuItem(); // duplicate with value set in page show for dialog sized selects self.isOpen = true; } }, _focusButton : function(){ var self = this; setTimeout(function() { self.button.focus(); }, 40); }, close: function() { if ( this.options.disabled || !this.isOpen || this.options.nativeMenu ) { return; } var self = this; if ( self.menuType == "page" ) { // rebind the page remove that was unbound in the open function // to allow for the parent page removal from actions other than the use // of a dialog sized custom select self.thisPage.bind( "pagehide.remove", function(){ $(this).remove(); }); // doesn't solve the possible issue with calling change page // where the objects don't define data urls which prevents dialog key // stripping - changePage has incoming refactor window.history.back(); } else{ self.screen.addClass( "ui-screen-hidden" ); self.listbox.addClass( "ui-selectmenu-hidden" ).removeAttr( "style" ).removeClass( "in" ); self.list.appendTo( self.listbox ); self._focusButton(); } // allow the dialog to be closed again this.isOpen = false; }, disable: function() { this.element.attr( "disabled", true ); this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); }, enable: function() { this.element.attr( "disabled", false ); this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.selectmenu.prototype.options.initSelector, e.target ) .not( ":jqmData(role='none'), :jqmData(role='nojs')" ) .selectmenu(); }); })( jQuery ); /* * jQuery Mobile Framework : plugin for making button-like links * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ ( function( $, undefined ) { $.fn.buttonMarkup = function( options ) { return this.each( function() { var el = $( this ), o = $.extend( {}, $.fn.buttonMarkup.defaults, el.jqmData(), options ), // Classes Defined innerClass = "ui-btn-inner", buttonClass, iconClass, themedParent, wrap; if ( attachEvents ) { attachEvents(); } // if not, try to find closest theme container if ( !o.theme ) { themedParent = el.closest( "[class*='ui-bar-'],[class*='ui-body-']" ); o.theme = themedParent.length ? /ui-(bar|body)-([a-z])/.exec( themedParent.attr( "class" ) )[2] : "c"; } buttonClass = "ui-btn ui-btn-up-" + o.theme; if ( o.inline ) { buttonClass += " ui-btn-inline"; } if ( o.icon ) { o.icon = "ui-icon-" + o.icon; o.iconpos = o.iconpos || "left"; iconClass = "ui-icon " + o.icon; if ( o.iconshadow ) { iconClass += " ui-icon-shadow"; } } if ( o.iconpos ) { buttonClass += " ui-btn-icon-" + o.iconpos; if ( o.iconpos == "notext" && !el.attr( "title" ) ) { el.attr( "title", el.text() ); } } if ( o.corners ) { buttonClass += " ui-btn-corner-all"; innerClass += " ui-btn-corner-all"; } if ( o.shadow ) { buttonClass += " ui-shadow"; } el.attr( "data-" + $.mobile.ns + "theme", o.theme ) .addClass( buttonClass ); wrap = ( "<D class='" + innerClass + "'><D class='ui-btn-text'></D>" + ( o.icon ? "<span class='" + iconClass + "'></span>" : "" ) + "</D>" ).replace( /D/g, o.wrapperEls ); el.wrapInner( wrap ); }); }; $.fn.buttonMarkup.defaults = { corners: true, shadow: true, iconshadow: true, wrapperEls: "span" }; function closestEnabledButton( element ) { while ( element ) { var $ele = $( element ); if ( $ele.hasClass( "ui-btn" ) && !$ele.hasClass( "ui-disabled" ) ) { break; } element = element.parentNode; } return element; } var attachEvents = function() { $( document ).bind( { "vmousedown": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme ); } }, "vmousecancel vmouseup": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme ); } }, "vmouseover focus": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme ); } }, "vmouseout blur": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-hover-" + theme ).addClass( "ui-btn-up-" + theme ); } } }); attachEvents = null; }; //links in bars, or those with data-role become buttons //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target ) .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" ) .buttonMarkup(); }); })( jQuery ); /* * jQuery Mobile Framework: "controlgroup" plugin - corner-rounding for groups of buttons, checks, radios, etc * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.fn.controlgroup = function( options ) { return this.each(function() { var $el = $( this ), o = $.extend({ direction: $el.jqmData( "type" ) || "vertical", shadow: false, excludeInvisible: true }, options ), groupheading = $el.find( ">legend" ), flCorners = o.direction == "horizontal" ? [ "ui-corner-left", "ui-corner-right" ] : [ "ui-corner-top", "ui-corner-bottom" ], type = $el.find( "input:eq(0)" ).attr( "type" ); // Replace legend with more stylable replacement div if ( groupheading.length ) { $el.wrapInner( "<div class='ui-controlgroup-controls'></div>" ); $( "<div role='heading' class='ui-controlgroup-label'>" + groupheading.html() + "</div>" ).insertBefore( $el.children(0) ); groupheading.remove(); } $el.addClass( "ui-corner-all ui-controlgroup ui-controlgroup-" + o.direction ); // TODO: This should be moved out to the closure // otherwise it is redefined each time controlgroup() is called function flipClasses( els ) { els.removeClass( "ui-btn-corner-all ui-shadow" ) .eq( 0 ).addClass( flCorners[ 0 ] ) .end() .filter( ":last" ).addClass( flCorners[ 1 ] ).addClass( "ui-controlgroup-last" ); } flipClasses( $el.find( ".ui-btn" + ( o.excludeInvisible ? ":visible" : "" ) ) ); flipClasses( $el.find( ".ui-btn-inner" ) ); if ( o.shadow ) { $el.addClass( "ui-shadow" ); } }); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='controlgroup')", e.target ).controlgroup({ excludeInvisible: false }); }); })(jQuery);/* * jQuery Mobile Framework : "fieldcontain" plugin - simple class additions to make form row separators * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ){ //links within content areas $( e.target ) .find( "a" ) .not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" ) .addClass( "ui-link" ); }); })( jQuery );/* * jQuery Mobile Framework : "fixHeaderFooter" plugin - on-demand positioning for headers,footers * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var slideDownClass = "ui-header-fixed ui-fixed-inline fade", slideUpClass = "ui-footer-fixed ui-fixed-inline fade", slideDownSelector = ".ui-header:jqmData(position='fixed')", slideUpSelector = ".ui-footer:jqmData(position='fixed')"; $.fn.fixHeaderFooter = function( options ) { if ( !$.support.scrollTop ) { return this; } return this.each(function() { var $this = $( this ); if ( $this.jqmData( "fullscreen" ) ) { $this.addClass( "ui-page-fullscreen" ); } // Should be slidedown $this.find( slideDownSelector ).addClass( slideDownClass ); // Should be slideup $this.find( slideUpSelector ).addClass( slideUpClass ); }); }; // single controller for all showing,hiding,toggling $.mobile.fixedToolbars = (function() { if ( !$.support.scrollTop ) { return; } var stickyFooter, delayTimer, currentstate = "inline", autoHideMode = false, showDelay = 100, ignoreTargets = "a,input,textarea,select,button,label,.ui-header-fixed,.ui-footer-fixed", toolbarSelector = ".ui-header-fixed:first, .ui-footer-fixed:not(.ui-footer-duplicate):last", // for storing quick references to duplicate footers supportTouch = $.support.touch, touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", stateBefore = null, scrollTriggered = false, touchToggleEnabled = true; function showEventCallback( event ) { // An event that affects the dimensions of the visual viewport has // been triggered. If the header and/or footer for the current page are in overlay // mode, we want to hide them, and then fire off a timer to show them at a later // point. Events like a resize can be triggered continuously during a scroll, on // some platforms, so the timer is used to delay the actual positioning until the // flood of events have subsided. // // If we are in autoHideMode, we don't do anything because we know the scroll // callbacks for the plugin will fire off a show when the scrolling has stopped. if ( !autoHideMode && currentstate === "overlay" ) { if ( !delayTimer ) { $.mobile.fixedToolbars.hide( true ); } $.mobile.fixedToolbars.startShowTimer(); } } $(function() { var $document = $( document ), $window = $( window ); $document .bind( "vmousedown", function( event ) { if ( touchToggleEnabled ) { stateBefore = currentstate; } }) .bind( "vclick", function( event ) { if ( touchToggleEnabled ) { if ( $(event.target).closest( ignoreTargets ).length ) { return; } if ( !scrollTriggered ) { $.mobile.fixedToolbars.toggle( stateBefore ); stateBefore = null; } } }) .bind( "silentscroll", showEventCallback ); // The below checks first for a $(document).scrollTop() value, and if zero, binds scroll events to $(window) instead. // If the scrollTop value is actually zero, both will return zero anyway. // // Works with $(document), not $(window) : Opera Mobile (WinMO phone; kinda broken anyway) // Works with $(window), not $(document) : IE 7/8 // Works with either $(window) or $(document) : Chrome, FF 3.6/4, Android 1.6/2.1, iOS // Needs work either way : BB5, Opera Mobile (iOS) ( ( $document.scrollTop() === 0 ) ? $window : $document ) .bind( "scrollstart", function( event ) { scrollTriggered = true; if ( stateBefore === null ) { stateBefore = currentstate; } // We only enter autoHideMode if the headers/footers are in // an overlay state or the show timer was started. If the // show timer is set, clear it so the headers/footers don't // show up until after we're done scrolling. var isOverlayState = stateBefore == "overlay"; autoHideMode = isOverlayState || !!delayTimer; if ( autoHideMode ) { $.mobile.fixedToolbars.clearShowTimer(); if ( isOverlayState ) { $.mobile.fixedToolbars.hide( true ); } } }) .bind( "scrollstop", function( event ) { if ( $( event.target ).closest( ignoreTargets ).length ) { return; } scrollTriggered = false; if ( autoHideMode ) { $.mobile.fixedToolbars.startShowTimer(); autoHideMode = false; } stateBefore = null; }); $window.bind( "resize", showEventCallback ); }); // 1. Before page is shown, check for duplicate footer // 2. After page is shown, append footer to new page $( ".ui-page" ) .live( "pagebeforeshow", function( event, ui ) { var page = $( event.target ), footer = page.find( ":jqmData(role='footer')" ), id = footer.data( "id" ), prevPage = ui.prevPage, prevFooter = prevPage && prevPage.find( ":jqmData(role='footer')" ), prevFooterMatches = prevFooter.length && prevFooter.jqmData( "id" ) === id; if ( id && prevFooterMatches ) { stickyFooter = footer; setTop( stickyFooter.removeClass( "fade in out" ).appendTo( $.mobile.pageContainer ) ); } }) .live( "pageshow", function( event, ui ) { var $this = $( this ); if ( stickyFooter && stickyFooter.length ) { setTimeout(function() { setTop( stickyFooter.appendTo( $this ).addClass( "fade" ) ); stickyFooter = null; }, 500); } $.mobile.fixedToolbars.show( true, this ); }); // When a collapsiable is hidden or shown we need to trigger the fixed toolbar to reposition itself (#1635) $( ".ui-collapsible-contain" ).live( "collapse expand", showEventCallback ); // element.getBoundingClientRect() is broken in iOS 3.2.1 on the iPad. The // coordinates inside of the rect it returns don't have the page scroll position // factored out of it like the other platforms do. To get around this, // we'll just calculate the top offset the old fashioned way until core has // a chance to figure out how to handle this situation. // // TODO: We'll need to get rid of getOffsetTop() once a fix gets folded into core. function getOffsetTop( ele ) { var top = 0, op, body; if ( ele ) { body = document.body; op = ele.offsetParent; top = ele.offsetTop; while ( ele && ele != body ) { top += ele.scrollTop || 0; if ( ele == op ) { top += op.offsetTop; op = ele.offsetParent; } ele = ele.parentNode; } } return top; } function setTop( el ) { var fromTop = $(window).scrollTop(), thisTop = getOffsetTop( el[ 0 ] ), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead. thisCSStop = el.css( "top" ) == "auto" ? 0 : parseFloat(el.css( "top" )), screenHeight = window.innerHeight, thisHeight = el.outerHeight(), useRelative = el.parents( ".ui-page:not(.ui-page-fullscreen)" ).length, relval; if ( el.is( ".ui-header-fixed" ) ) { relval = fromTop - thisTop + thisCSStop; if ( relval < thisTop ) { relval = 0; } return el.css( "top", useRelative ? relval : fromTop ); } else { // relval = -1 * (thisTop - (fromTop + screenHeight) + thisCSStop + thisHeight); // if ( relval > thisTop ) { relval = 0; } relval = fromTop + screenHeight - thisHeight - (thisTop - thisCSStop ); return el.css( "top", useRelative ? relval : fromTop + screenHeight - thisHeight ); } } // Exposed methods return { show: function( immediately, page ) { $.mobile.fixedToolbars.clearShowTimer(); currentstate = "overlay"; var $ap = page ? $( page ) : ( $.mobile.activePage ? $.mobile.activePage : $( ".ui-page-active" ) ); return $ap.children( toolbarSelector ).each(function() { var el = $( this ), fromTop = $( window ).scrollTop(), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead. thisTop = getOffsetTop( el[ 0 ] ), screenHeight = window.innerHeight, thisHeight = el.outerHeight(), alreadyVisible = ( el.is( ".ui-header-fixed" ) && fromTop <= thisTop + thisHeight ) || ( el.is( ".ui-footer-fixed" ) && thisTop <= fromTop + screenHeight ); // Add state class el.addClass( "ui-fixed-overlay" ).removeClass( "ui-fixed-inline" ); if ( !alreadyVisible && !immediately ) { el.animationComplete(function() { el.removeClass( "in" ); }).addClass( "in" ); } setTop(el); }); }, hide: function( immediately ) { currentstate = "inline"; var $ap = $.mobile.activePage ? $.mobile.activePage : $( ".ui-page-active" ); return $ap.children( toolbarSelector ).each(function() { var el = $(this), thisCSStop = el.css( "top" ), classes; thisCSStop = thisCSStop == "auto" ? 0 : parseFloat(thisCSStop); // Add state class el.addClass( "ui-fixed-inline" ).removeClass( "ui-fixed-overlay" ); if ( thisCSStop < 0 || ( el.is( ".ui-header-fixed" ) && thisCSStop !== 0 ) ) { if ( immediately ) { el.css( "top", 0); } else { if ( el.css( "top" ) !== "auto" && parseFloat( el.css( "top" ) ) !== 0 ) { classes = "out reverse"; el.animationComplete(function() { el.removeClass( classes ).css( "top", 0 ); }).addClass( classes ); } } } }); }, startShowTimer: function() { $.mobile.fixedToolbars.clearShowTimer(); var args = [].slice.call( arguments ); delayTimer = setTimeout(function() { delayTimer = undefined; $.mobile.fixedToolbars.show.apply( null, args ); }, showDelay); }, clearShowTimer: function() { if ( delayTimer ) { clearTimeout( delayTimer ); } delayTimer = undefined; }, toggle: function( from ) { if ( from ) { currentstate = from; } return ( currentstate === "overlay" ) ? $.mobile.fixedToolbars.hide() : $.mobile.fixedToolbars.show(); }, setTouchToggleEnabled: function( enabled ) { touchToggleEnabled = enabled; } }; })(); // TODO - Deprecated namepace on $. Remove in a later release $.fixedToolbars = $.mobile.fixedToolbars; //auto self-init widgets $( document ).bind( "pagecreate create", function( event ) { if ( $( ":jqmData(position='fixed')", event.target ).length ) { $( event.target ).each(function() { if ( !$.support.scrollTop ) { return this; } var $this = $( this ); if ( $this.jqmData( "fullscreen" ) ) { $this.addClass( "ui-page-fullscreen" ); } // Should be slidedown $this.find( slideDownSelector ).addClass( slideDownClass ); // Should be slideup $this.find( slideUpSelector ).addClass( slideUpClass ); }) } }); })( jQuery ); /* * jQuery Mobile Framework : resolution and CSS media query related helpers and behavior * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { var $window = $( window ), $html = $( "html" ), //media-query-like width breakpoints, which are translated to classes on the html element resolutionBreakpoints = [ 320, 480, 768, 1024 ]; /* private function for adding/removing breakpoint classes to HTML element for faux media-query support It does not require media query support, instead using JS to detect screen width > cross-browser support This function is called on orientationchange, resize, and mobileinit, and is bound via the 'htmlclass' event namespace */ function detectResolutionBreakpoints() { var currWidth = $window.width(), minPrefix = "min-width-", maxPrefix = "max-width-", minBreakpoints = [], maxBreakpoints = [], unit = "px", breakpointClasses; $html.removeClass( minPrefix + resolutionBreakpoints.join(unit + " " + minPrefix) + unit + " " + maxPrefix + resolutionBreakpoints.join( unit + " " + maxPrefix) + unit ); $.each( resolutionBreakpoints, function( i, breakPoint ) { if( currWidth >= breakPoint ) { minBreakpoints.push( minPrefix + breakPoint + unit ); } if( currWidth <= breakPoint ) { maxBreakpoints.push( maxPrefix + breakPoint + unit ); } }); if ( minBreakpoints.length ) { breakpointClasses = minBreakpoints.join(" "); } if ( maxBreakpoints.length ) { breakpointClasses += " " + maxBreakpoints.join(" "); } $html.addClass( breakpointClasses ); }; /* $.mobile.addResolutionBreakpoints method: pass either a number or an array of numbers and they'll be added to the min/max breakpoint classes Examples: $.mobile.addResolutionBreakpoints( 500 ); $.mobile.addResolutionBreakpoints( [500, 1200] ); */ $.mobile.addResolutionBreakpoints = function( newbps ) { if( $.type( newbps ) === "array" ){ resolutionBreakpoints = resolutionBreakpoints.concat( newbps ); } else { resolutionBreakpoints.push( newbps ); } resolutionBreakpoints.sort(function( a, b ) { return a - b; }); detectResolutionBreakpoints(); }; /* on mobileinit, add classes to HTML element and set handlers to update those on orientationchange and resize */ $( document ).bind( "mobileinit.htmlclass", function() { // bind to orientationchange and resize // to add classes to HTML element for min/max breakpoints and orientation var ev = $.support.orientation; $window.bind( "orientationchange.htmlclass throttledResize.htmlclass", function( event ) { // add orientation class to HTML element on flip/resize. if ( event.orientation ) { $html.removeClass( "portrait landscape" ).addClass( event.orientation ); } // add classes to HTML element for min/max breakpoints detectResolutionBreakpoints(); }); }); /* Manually trigger an orientationchange event when the dom ready event fires. This will ensure that any viewport meta tag that may have been injected has taken effect already, allowing us to properly calculate the width of the document. */ $(function() { //trigger event manually $window.trigger( "orientationchange.htmlclass" ); }); })(jQuery);/*! * jQuery Mobile v@VERSION * http://jquerymobile.com/ * * Copyright 2010, jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, window, undefined ) { var $html = $( "html" ), $head = $( "head" ), $window = $( window ); //trigger mobileinit event - useful hook for configuring $.mobile settings before they're used $( window.document ).trigger( "mobileinit" ); //support conditions //if device support condition(s) aren't met, leave things as they are -> a basic, usable experience, //otherwise, proceed with the enhancements if ( !$.mobile.gradeA() ) { return; } // override ajaxEnabled on platforms that have known conflicts with hash history updates // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini) if( $.mobile.ajaxBlacklist ){ $.mobile.ajaxEnabled = false; } //add mobile, initial load "rendering" classes to docEl $html.addClass( "ui-mobile ui-mobile-rendering" ); //loading div which appears during Ajax requests //will not appear if $.mobile.loadingMessage is false var $loader = $( "<div class='ui-loader ui-body-a ui-corner-all'><span class='ui-icon ui-icon-loading spin'></span><h1></h1></div>" ); $.extend($.mobile, { // turn on/off page loading message. showPageLoadingMsg: function() { if( $.mobile.loadingMessage ){ var activeBtn = $( "." + $.mobile.activeBtnClass ).first(); $loader .find( "h1" ) .text( $.mobile.loadingMessage ) .end() .appendTo( $.mobile.pageContainer ) //position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top .css( { top: $.support.scrollTop && $(window).scrollTop() + $(window).height() / 2 || activeBtn.length && activeBtn.offset().top || 100 } ); } $html.addClass( "ui-loading" ); }, hidePageLoadingMsg: function() { $html.removeClass( "ui-loading" ); }, // XXX: deprecate for 1.0 pageLoading: function ( done ) { if ( done ) { $.mobile.hidePageLoadingMsg(); } else { $.mobile.showPageLoadingMsg(); } }, // find and enhance the pages in the dom and transition to the first page. initializePage: function(){ //find present pages var $pages = $( ":jqmData(role='page')" ); //if no pages are found, create one with body's inner html if( !$pages.length ){ $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 ); } //add dialogs, set data-url attrs $pages.add( ":jqmData(role='dialog')" ).each(function(){ var $this = $(this); // unless the data url is already set set it to the id if( !$this.jqmData('url') ){ $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) ); } }); //define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback) $.mobile.firstPage = $pages.first(); //define page container $.mobile.pageContainer = $pages.first().parent().addClass( "ui-mobile-viewport" ); //cue page loading message $.mobile.showPageLoadingMsg(); // if hashchange listening is disabled or there's no hash deeplink, change to the first page in the DOM if( !$.mobile.hashListeningEnabled || !$.mobile.path.stripHash( location.hash ) ){ $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true } ); } // otherwise, trigger a hashchange to load a deeplink else { $window.trigger( "hashchange", [ true ] ); } } }); //initialize events now, after mobileinit has occurred $.mobile._registerInternalEvents(); //check which scrollTop value should be used by scrolling to 1 immediately at domready //then check what the scroll top is. Android will report 0... others 1 //note that this initial scroll won't hide the address bar. It's just for the check. $(function(){ window.scrollTo( 0, 1 ); //if defaultHomeScroll hasn't been set yet, see if scrollTop is 1 //it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar) //so if it's 1, use 0 from now on $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $(window).scrollTop() === 1 ) ? 0 : 1; //dom-ready inits if( $.mobile.autoInitializePage ){ $( $.mobile.initializePage ); } //window load event //hide iOS browser chrome on load $window.load( $.mobile.silentScroll ); }); })( jQuery, this );
JavaScript
//quick view source in new window links $.fn.addSourceLink = function(style){ return $(this).each(function(){ var link = $('<a href="#" data-'+ $.mobile.ns +'inline="true">View Source</a>'), src = src = $('<div></div>').append( $(this).clone() ).html(), page = $( "<div data-"+ $.mobile.ns +"role='dialog' data-"+ $.mobile.ns +"theme='a'>" + "<div data-"+ $.mobile.ns +"role='header' data-"+ $.mobile.ns +"theme='b'>" + "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"icon='delete' data-"+ $.mobile.ns +"iconpos='notext'>Close</a>"+ "<div class='ui-title'>jQuery Mobile Source Excerpt</div>"+ "</div>"+ "<div data-"+ $.mobile.ns +"role='content'></div>"+ "</div>" ) .appendTo( "body" ) .page(); $('<a href="#">View Source</a>') .buttonMarkup({ icon: 'arrow-u', iconpos: 'notext' }) .click(function(){ var codeblock = $('<pre><code></code></pre>'); src = src.replace(/&/gmi, '&amp;').replace(/"/gmi, '&quot;').replace(/>/gmi, '&gt;').replace(/</gmi, '&lt;').replace('data-'+ $.mobile.ns +'source="true"',''); codeblock.find('code').append(src); var activePage = $(this).parents('.ui-page-active'); page.find('.ui-content').append(codeblock); $.changePage(page, 'slideup',false); page.find('.ui-btn-left').click(function(){ $.changePage(activepage, 'slideup',true); return false; }); }) .insertAfter(this); }); }; //set up view source links $('div').live('pagebeforecreate',function(){ $(this).find('[data-'+ $.mobile.ns +'source="true"]').addSourceLink(); });
JavaScript
//set up the theme switcher on the homepage $('div').live('pagecreate',function(event){ if( !$(this).is('.ui-dialog')){ var appendEl = $(this).find('.ui-footer:last'); if( !appendEl.length ){ appendEl = $(this).find('.ui-content'); } if( appendEl.is("[data-position]") ){ return; } $('<a href="#themeswitcher" data-'+ $.mobile.ns +'rel="dialog" data-'+ $.mobile.ns +'transition="pop">Switch theme</a>') .buttonMarkup({ 'icon':'gear', 'inline': true, 'shadow': false, 'theme': 'd' }) .appendTo( appendEl ) .wrap('<div class="jqm-themeswitcher">') .bind( "vclick", function(){ $.themeswitcher(); }); } }); //collapse page navs after use $(function(){ $('body').delegate('.content-secondary .ui-collapsible-content', 'click', function(){ $(this).trigger("collapse") }); }); function setDefaultTransition(){ var winwidth = $( window ).width(), trans ="slide"; if( winwidth >= 1000 ){ trans = "none"; } else if( winwidth >= 650 ){ trans = "fade"; } $.mobile.defaultPageTransition = trans; } $(function(){ setDefaultTransition(); $( window ).bind( "throttledresize", setDefaultTransition ); });
JavaScript
/* * mobile button unit tests */ (function($){ $.mobile.page.prototype.options.keepNative = "button.should-be-native"; test( "button elements in the keepNative set shouldn't be enhanced", function() { same( $("button.should-be-native").siblings("div.ui-slider").length, 0 ); }); test( "button elements should be enhanced", function() { ok( $("#enhanced").hasClass( "ui-btn-hidden" ) ); }); test( "button markup text value should be changed on refresh", function() { var textValueButton = $("#text"), valueButton = $("#value"); // the value shouldn't change unless it's been altered textValueButton.button( 'refresh' ); same( textValueButton.siblings().text(), "foo" ); // use the text where it's provided same( textValueButton.siblings().text(), "foo" ); textValueButton.text( "bar" ).button( 'refresh' ); same( textValueButton.siblings().text(), "bar" ); // use the val if it's provided where the text isn't same( valueButton.siblings().text(), "foo" ); valueButton.val( "bar" ).button( 'refresh' ); same( valueButton.siblings().text(), "bar" ); // prefer the text to the value textValueButton.text( "bar" ).val( "baz" ).button( 'refresh' ); same( textValueButton.siblings().text(), "bar" ); }); // Issue 2877 test( "verify the button placeholder is added many times", function() { var $form = $( "#hidden-element-addition-form" ), count = 3; expect( count * 2 ); for( var x = 0; x < count; x++ ) { $( "#hidden-element-addition" ).trigger( "vclick" ); same( $form.find( "input[type='hidden']" ).length, 1, "hidden form input should be added" ); $form.trigger( "submit" ); same( $form.find( "[type='hidden']" ).length, 0, "hidden form input is removed" ); } }); })( jQuery );
JavaScript
/* * mobile page unit tests */ (function($){ var libName = 'jquery.mobile.page.js'; module(libName); test( "nested header anchors aren't altered", function(){ ok(!$('.ui-header > div > a').hasClass('ui-btn')); }); test( "nested footer anchors aren't altered", function(){ ok(!$('.ui-footer > div > a').hasClass('ui-btn')); }); test( "nested bar anchors aren't styled", function(){ ok(!$('.ui-bar > div > a').hasClass('ui-btn')); }); test( "unnested footer anchors are styled", function(){ ok($('.ui-footer > a').hasClass('ui-btn')); }); test( "unnested footer anchors are styled", function(){ ok($('.ui-footer > a').hasClass('ui-btn')); }); test( "unnested bar anchors are styled", function(){ ok($('.ui-bar > a').hasClass('ui-btn')); }); test( "no auto-generated back button exists on first page", function(){ ok( !$(".ui-header > :jqmData(rel='back')").length ); }); })(jQuery);
JavaScript
/* * mobile textinput unit tests */ (function($){ module( "jquery.mobile.forms.textinput.js" ); test( "inputs without type specified are enhanced", function(){ ok( $( "#typeless-input" ).hasClass( "ui-input-text" ) ); }); $.mobile.page.prototype.options.keepNative = "textarea.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "textarea in the keepNative set shouldn't be enhanced", function() { ok( !$("textarea.should-be-native").is("ui-input-text") ); }); asyncTest( "textarea should autogrow on document ready", function() { var test = $( "#init-autogrow" ); setTimeout(function() { ok( $( "#reference-autogrow" )[0].clientHeight < test[0].clientHeight, "the height is greater than the reference text area with no content" ); ok( test[0].clientHeight > 100, "autogrow text area's height is greater than any style padding"); start(); }, 400); }); asyncTest( "textarea should autogrow when text is added via the keyboard", function() { var test = $( "#keyup-autogrow" ), originalHeight = test[0].clientHeight; test.keyup(function() { setTimeout(function() { ok( test[0].clientHeight > originalHeight, "the height is greater than original with no content" ); ok( test[0].clientHeight > 100, "autogrow text area's height is greater any style/padding"); start(); }, 400); }); test.val("foo\n\n\n\n\n\n\n\n\n\n\n\n\n\n").trigger("keyup"); }); asyncTest( "text area should auto grow when the parent page is loaded via ajax", function() { $.testHelper.pageSequence([ function() { $("#external").click(); }, function() { setTimeout(function() { ok($.mobile.activePage.find( "textarea" )[0].clientHeight > 100, "text area's height has grown"); window.history.back(); }, 1000); }, function() { start(); } ]); }); })(jQuery);
JavaScript
(function($) { asyncTest( "nested pages hash key is always in the hash on default page with no id (replaceState) ", function(){ $.testHelper.pageSequence([ function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ ok( location.hash.search($.mobile.subPageUrlKey) >= 0 ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile listview unit tests */ // TODO split out into seperate test files (function($){ var home = $.mobile.path.parseUrl( location.href ).pathname; $.mobile.defaultTransition = "none"; module( "Basic Linked list", { setup: function(){ $.testHelper.openPage( "#basic-linked-test" ); } }); asyncTest( "The page should enhanced correctly", function(){ setTimeout(function() { ok($('#basic-linked-test .ui-li').length, ".ui-li classes added to li elements"); start(); }, 800); }); asyncTest( "Slides to the listview page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#basic-linked-test"); }, function(){ $('#basic-linked-test li a').first().click(); }, function(){ ok($('#basic-link-results').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Slides back to main page when back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#basic-link-results"); }, function(){ window.history.back(); }, function(){ ok($('#basic-linked-test').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Presence of ui-li-has- classes", function(){ $.testHelper.pageSequence( [ function() { $.testHelper.openPage( "#ui-li-has-test" ); }, function() { var page = $( ".ui-page-active" ), items = page.find( "li" ); ok( items.eq( 0 ).hasClass( "ui-li-has-count"), "First LI should have ui-li-has-count class" ); ok( items.eq( 0 ).hasClass( "ui-li-has-arrow"), "First LI should have ui-li-has-arrow class" ); ok( !items.eq( 1 ).hasClass( "ui-li-has-count"), "Second LI should NOT have ui-li-has-count class" ); ok( items.eq( 1 ).hasClass( "ui-li-has-arrow"), "Second LI should have ui-li-has-arrow class" ); ok( !items.eq( 2 ).hasClass( "ui-li-has-count"), "Third LI should NOT have ui-li-has-count class" ); ok( !items.eq( 2 ).hasClass( "ui-li-has-arrow"), "Third LI should NOT have ui-li-has-arrow class" ); ok( items.eq( 3 ).hasClass( "ui-li-has-count"), "Fourth LI should have ui-li-has-count class" ); ok( !items.eq( 3 ).hasClass( "ui-li-has-arrow"), "Fourth LI should NOT have ui-li-has-arrow class" ); ok( !items.eq( 4 ).hasClass( "ui-li-has-count"), "Fifth LI should NOT have ui-li-has-count class" ); ok( !items.eq( 4 ).hasClass( "ui-li-has-arrow"), "Fifth LI should NOT have ui-li-has-arrow class" ); start(); } ]); }); module('Nested List Test'); asyncTest( "Changes page to nested list test and enhances", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test"); }, function(){ ok($('#nested-list-test').hasClass('ui-page-active'), "makes nested list test page active"); ok($(':jqmData(url="nested-list-test&ui-page=0-0")').length == 1, "Adds first UL to the page"); ok($(':jqmData(url="nested-list-test&ui-page=0-1")').length == 1, "Adds second nested UL to the page"); start(); } ]); }); asyncTest( "change to nested page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test"); }, function(){ $('.ui-page-active li:eq(1) a:eq(0)').click(); }, function(){ var $new_page = $(':jqmData(url="nested-list-test&ui-page=0-0")'); ok($new_page.hasClass('ui-page-active'), 'Makes the nested page the active page.'); ok($('.ui-listview', $new_page).find(":contains('Rhumba of rattlesnakes')").length == 1, "The current page should have the proper text in the list."); ok($('.ui-listview', $new_page).find(":contains('Shoal of Bass')").length == 1, "The current page should have the proper text in the list."); start(); } ]); }); asyncTest( "should go back to top level when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#nested-list-test&ui-page=0-0"); }, function(){ window.history.back(); }, function(){ ok($('#nested-list-test').hasClass('ui-page-active'), 'Transitions back to the parent nested page'); start(); } ]); }); test( "nested list title should use first text node, regardless of line breaks", function(){ ok($('#nested-list-test .linebreaknode').text() === "More animals", 'Text should be "More animals"'); }); asyncTest( "Multiple nested lists on a page with same labels", function() { $.testHelper.pageSequence([ function(){ // https://github.com/jquery/jquery-mobile/issues/1617 $.testHelper.openPage("#nested-lists-test"); }, function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ equal($('.ui-page-active .ui-content .ui-listview li').text(), "Item A-3-0Item A-3-1Item A-3-2", 'Text should be "Item A-3-0Item A-3-1Item A-3-2"'); start(); } ]); }); module('Ordered Lists'); asyncTest( "changes to the numbered list page and enhances it", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#numbered-list-test"); }, function(){ var $new_page = $('#numbered-list-test'); ok($new_page.hasClass('ui-page-active'), "Makes the new page active when the hash is changed."); ok($('.ui-link-inherit', $new_page).first().text() == "Number 1", "The text of the first LI should be Number 1"); start(); } ]); }); asyncTest( "changes to number 1 page when the li a is clicked", function() { $.testHelper.pageSequence([ function(){ $('#numbered-list-test li a').first().click(); }, function(){ ok($('#numbered-list-results').hasClass('ui-page-active'), "The new numbered page was transitioned correctly."); start(); } ]); }); asyncTest( "takes us back to the numbered list when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage('#numbered-list-test'); }, function(){ $.testHelper.openPage('#numbered-list-results'); }, function(){ window.history.back(); }, function(){ ok($('#numbered-list-test').hasClass('ui-page-active')); start(); } ]); }); module('Read only list'); asyncTest( "changes to the read only page when hash is changed", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#read-only-list-test"); }, function(){ var $new_page = $('#read-only-list-test'); ok($new_page.hasClass('ui-page-active'), "makes the read only page the active page"); ok($('li', $new_page).first().text() === "Read", "The first LI has the proper text."); start(); } ]); }); module('Split view list'); asyncTest( "changes the page to the split view list and enhances it correctly.", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ var $new_page = $('#split-list-test'); ok($('.ui-li-link-alt', $new_page).length == 3); ok($('.ui-link-inherit', $new_page).length == 3); start(); } ]); }); asyncTest( "change the page to the split view page 1 when the first link is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-li a:eq(0)').click(); }, function(){ ok($('#split-list-link1').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Slide back to the parent list view when the back button is clicked", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-listview a:eq(0)').click(); }, function(){ history.back(); }, function(){ ok($('#split-list-test').hasClass('ui-page-active')); start(); } ]); }); asyncTest( "Clicking on the icon (the second link) should take the user to other a href of this LI", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#split-list-test"); }, function(){ $('.ui-page-active .ui-li-link-alt:eq(0)').click(); }, function(){ ok($('#split-list-link2').hasClass('ui-page-active')); start(); } ]); }); module( "List Dividers" ); asyncTest( "Makes the list divider page the active page and enhances it correctly.", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#list-divider-test"); }, function(){ var $new_page = $('#list-divider-test'); ok($new_page.find('.ui-li-divider').length == 2); ok($new_page.hasClass('ui-page-active')); start(); } ]); }); module( "Search Filter"); var searchFilterId = "#search-filter-test"; asyncTest( "Filter downs results when the user enters information", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('at'); $searchPage.find('input').trigger('change'); same($searchPage.find('li.ui-screen-hidden').length, 2); start(); } ]); }); asyncTest( "Redisplay results when user removes values", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('a'); $searchPage.find('input').trigger('change'); same($searchPage.find("li[style^='display: none;']").length, 0); start(); } ]); }); asyncTest( "Filter works fine with \\W- or regexp-special-characters", function() { var $searchPage = $(searchFilterId); $.testHelper.pageSequence([ function() { $.testHelper.openPage(searchFilterId); }, function() { $searchPage.find('input').val('*'); $searchPage.find('input').trigger('change'); same($searchPage.find('li.ui-screen-hidden').length, 4); start(); } ]); }); test( "Refresh applies thumb styling", function(){ var ul = $('.ui-page-active ul'); ul.append("<li id='fiz'><img/></li>"); ok(!ul.find("#fiz img").hasClass("ui-li-thumb")); ul.listview('refresh'); ok(ul.find("#fiz img").hasClass("ui-li-thumb")); }); asyncTest( "Filter downs results and dividers when the user enters information", function() { var $searchPage = $("#search-filter-with-dividers-test"); $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, // wait for the page to become active/enhanced function(){ $searchPage.find('input').val('at'); $searchPage.find('input').trigger('change'); setTimeout(function() { //there should be four hidden list entries same($searchPage.find('li.ui-screen-hidden').length, 4); //there should be two list entries that are list dividers and hidden same($searchPage.find('li.ui-screen-hidden:jqmData(role=list-divider)').length, 2); //there should be two list entries that are not list dividers and hidden same($searchPage.find('li.ui-screen-hidden:not(:jqmData(role=list-divider))').length, 2); start(); }, 1000); } ]); }); asyncTest( "Redisplay results when user removes values", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, function() { $('.ui-page-active input').val('a'); $('.ui-page-active input').trigger('change'); setTimeout(function() { same($('.ui-page-active input').val(), 'a'); same($('.ui-page-active li[style^="display: none;"]').length, 0); start(); }, 1000); } ]); }); asyncTest( "Dividers are hidden when preceding hidden rows and shown when preceding shown rows", function () { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-with-dividers-test"); }, function() { var $page = $('.ui-page-active'); $page.find('input').val('at'); $page.find('input').trigger('change'); setTimeout(function() { same($page.find('li:jqmData(role=list-divider):hidden').length, 2); same($page.find('li:jqmData(role=list-divider):hidden + li:not(:jqmData(role=list-divider)):hidden').length, 2); same($page.find('li:jqmData(role=list-divider):not(:hidden) + li:not(:jqmData(role=list-divider)):not([:hidden)').length, 2); start(); }, 1000); } ]); }); asyncTest( "Inset List View should refresh corner classes after filtering", 4 * 2, function () { var checkClasses = function() { var $page = $( ".ui-page-active" ), $li = $page.find( "li:visible" ); ok($li.first().hasClass( "ui-corner-top" ), $li.length+" li elements: First visible element should have class ui-corner-top"); ok($li.last().hasClass( "ui-corner-bottom" ), $li.length+" li elements: Last visible element should have class ui-corner-bottom"); }; $.testHelper.pageSequence([ function() { $.testHelper.openPage("#search-filter-inset-test"); }, function() { var $page = $('.ui-page-active'); $.testHelper.sequence([ function() { checkClasses(); $page.find('input').val('man'); $page.find('input').trigger('change'); }, function() { checkClasses(); $page.find('input').val('at'); $page.find('input').trigger('change'); }, function() { checkClasses(); $page.find('input').val('catwoman'); $page.find('input').trigger('change'); }, function() { checkClasses(); start(); } ], 50); } ]); }); module( "Programmatically generated list items", { setup: function(){ var item, data = [ { id: 1, label: "Item 1" }, { id: 2, label: "Item 2" }, { id: 3, label: "Item 3" }, { id: 4, label: "Item 4" } ]; $( "#programmatically-generated-list-items" ).html(""); for ( var i = 0, len = data.length; i < len; i++ ) { item = $( '<li id="myItem' + data[i].id + '">' ); label = $( "<strong>" + data[i].label + "</strong>").appendTo( item ); $( "#programmatically-generated-list-items" ).append( item ); } } }); asyncTest( "Corner styling on programmatically created list items", function() { // https://github.com/jquery/jquery-mobile/issues/1470 $.testHelper.pageSequence([ function() { $.testHelper.openPage( "#programmatically-generated-list" ); }, function() { ok(!$( "#programmatically-generated-list-items li:first-child" ).hasClass( "ui-corner-bottom" ), "First list item should not have class ui-corner-bottom" ); start(); } ]); }); module("Programmatic list items manipulation"); asyncTest("Removing list items", 4, function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#removing-items-from-list-test"); }, function() { var ul = $('#removing-items-from-list-test ul'); ul.find("li").first().remove(); equal(ul.find("li").length, 3, "There should be only 3 list items left"); ul.listview('refresh'); ok(ul.find("li").first().hasClass("ui-corner-top"), "First list item should have class ui-corner-top"); ul.find("li").last().remove(); equal(ul.find("li").length, 2, "There should be only 2 list items left"); ul.listview('refresh'); ok(ul.find("li").last().hasClass("ui-corner-bottom"), "Last list item should have class ui-corner-bottom"); start(); } ]); }); module("Rounded corners"); asyncTest("Top and bottom corners rounded in inset list", 14, function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#corner-rounded-test"); }, function() { var ul = $('#corner-rounded-test ul'); for( var t = 0; t<3; t++){ ul.append("<li>Item " + t + "</li>"); ul.listview('refresh'); equals(ul.find(".ui-corner-top").length, 1, "There should be only one element with class ui-corner-top"); equals(ul.find("li:visible").first()[0], ul.find(".ui-corner-top")[0], "First list item should have class ui-corner-top in list with " + ul.find("li").length + " item(s)"); equals(ul.find(".ui-corner-bottom").length, 1, "There should be only one element with class ui-corner-bottom"); equals(ul.find("li:visible").last()[0], ul.find(".ui-corner-bottom")[0], "Last list item should have class ui-corner-bottom in list with " + ul.find("li").length + " item(s)"); } ul.find( "li" ).first().hide(); ul.listview( "refresh" ); equals(ul.find("li:visible").first()[0], ul.find(".ui-corner-top")[0], "First visible list item should have class ui-corner-top"); ul.find( "li" ).last().hide(); ul.listview( "refresh" ); equals(ul.find("li:visible").last()[0], ul.find(".ui-corner-bottom")[0], "Last visible list item should have class ui-corner-bottom"); start(); } ]); }); test( "Listview will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-listview").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-listview").length, "enhancements applied" ); }); module( "Cached Linked List" ); var findNestedPages = function(selector){ return $( selector + " #topmost" ).listview( 'childPages' ); }; asyncTest( "nested pages are removed from the dom by default", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/uncached-nested.html" ); }, function(){ ok( findNestedPages( "#uncached-nested-list" ).length > 0, "verify that there are nested pages" ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ same( findNestedPages( "#uncached-nested-list" ).length, 0 ); start(); } ]); }); asyncTest( "nested pages preserved when parent page is cached", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/cached-nested.html" ); }, function(){ ok( findNestedPages( "#cached-nested-list" ).length > 0, "verify that there are nested pages" ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ ok( findNestedPages( "#cached-nested-list" ).length > 0, "nested pages remain" ); start(); } ]); }); asyncTest( "parent page is not removed when visiting a sub page", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ $.testHelper.openPage( "#cache-tests/cached-nested.html" ); }, function(){ same( $("#cached-nested-list").length, 1 ); $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#cache-tests/clear.html" ); }, function(){ same( $("#cached-nested-list").length, 1 ); start(); } ]); }); asyncTest( "filterCallback can be altered after widget creation", function(){ var listPage = $( "#search-filter-test" ); expect( listPage.find("li").length ); $.testHelper.pageSequence( [ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function() { $.testHelper.openPage( "#search-filter-test" ); }, function() { // set the listview instance callback listPage.find( "ul" ).listview( "option", "filterCallback", function() { ok(true, "custom callback invoked"); }); // trigger a change in the search filter listPage.find( "input" ).val( "foo" ).trigger( "change" ); //NOTE beware a poossible issue with timing here start(); } ]); }); asyncTest( "nested pages hash key is always in the hash (replaceState)", function(){ $.testHelper.pageSequence([ function(){ //reset for relative url refs $.testHelper.openPage( "#" + home ); }, function(){ // https://github.com/jquery/jquery-mobile/issues/1617 $.testHelper.openPage("#nested-lists-test"); }, function(){ // Click on the link of the third li element $('.ui-page-active li:eq(2) a:eq(0)').click(); }, function(){ ok( location.hash.search($.mobile.subPageUrlKey) >= 0 ); start(); } ]); }); asyncTest( "embedded listview page with nested pages is not removed from the dom", function() { $.testHelper.pageSequence([ function() { // open the nested list page same( $("div#nested-list-test").length, 1 ); $( "a#nested-list-test-anchor" ).click(); }, function() { // go back to the origin page window.history.back(); }, function() { // make sure the page is still in place same( $("div#nested-list-test").length, 1 ); start(); } ]); }); asyncTest( "list inherits theme from parent", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage("#list-theme-inherit"); }, function() { var theme = $.mobile.activePage.jqmData('theme'); ok( $.mobile.activePage.find("ul > li").hasClass("ui-body-b"), "theme matches the parent"); window.history.back(); }, start ]); }); })(jQuery);
JavaScript
/* * mobile event unit tests */ (function($){ var libName = "jquery.mobile.event.js", absFn = Math.abs, originalEventFn = $.Event.prototype.originalEvent, preventDefaultFn = $.Event.prototype.preventDefault, events = ("touchstart touchmove touchend orientationchange tap taphold " + "swipe swipeleft swiperight scrollstart scrollstop").split( " " ); module(libName, { setup: function(){ // ensure bindings are removed $.each(events + "vmouseup vmousedown".split(" "), function(i, name){ $("#qunit-fixture").unbind(); }); //NOTE unmock Math.abs = absFn; $.Event.prototype.originalEvent = originalEventFn; $.Event.prototype.preventDefault = preventDefaultFn; // make sure the event objects respond to touches to simulate // the collections existence in non touch enabled test browsers $.Event.prototype.touches = [{pageX: 1, pageY: 1 }]; $($.mobile.pageContainer).unbind( "throttledresize" ); } }); $.testHelper.excludeFileProtocol(function(){ test( "new events defined on the jquery object", function(){ $.each(events, function( i, name ) { delete $.fn[name]; same($.fn[name], undefined); }); $.testHelper.reloadLib(libName); $.each(events, function( i, name ) { ok($.fn[name] !== undefined, name + " is not undefined"); }); }); }); asyncTest( "defined event functions bind a closure when passed", function(){ expect( 1 ); $('#qunit-fixture').bind(events[0], function(){ ok(true, "event fired"); start(); }); $('#qunit-fixture').trigger(events[0]); }); asyncTest( "defined event functions trigger the event with no arguments", function(){ expect( 1 ); $('#qunit-fixture').bind('touchstart', function(){ ok(true, "event fired"); start(); }); $('#qunit-fixture').touchstart(); }); test( "defining event functions sets the attrFn to true", function(){ $.each(events, function(i, name){ ok($.attrFn[name], "attribute function is true"); }); }); test( "scrollstart enabled defaults to true", function(){ $.event.special.scrollstart.enabled = false; $.testHelper.reloadLib(libName); ok($.event.special.scrollstart.enabled, "scrollstart enabled"); }); asyncTest( "scrollstart setup binds a function that returns when its disabled", function(){ expect( 1 ); $.event.special.scrollstart.enabled = false; $( "#qunit-fixture" ).bind("scrollstart", function(){ ok(false, "scrollstart fired"); }); $( "#qunit-fixture" ).bind("touchmove", function(){ ok(true, "touchmove fired"); start(); }); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "scrollstart setup binds a function that triggers scroll start when enabled", function(){ $.event.special.scrollstart.enabled = true; $( "#qunit-fixture" ).bind("scrollstart", function(){ ok(true, "scrollstart fired"); start(); }); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "scrollstart setup binds a function that triggers scroll stop after 50 ms", function(){ var triggered = false; $.event.special.scrollstart.enabled = true; $( "#qunit-fixture" ).bind("scrollstop", function(){ triggered = true; }); ok(!triggered, "not triggered"); $( "#qunit-fixture" ).trigger("touchmove"); setTimeout(function(){ ok(triggered, "triggered"); start(); }, 50); }); var forceTouchSupport = function(){ $.support.touch = true; $.testHelper.reloadLib(libName); //mock originalEvent information $.Event.prototype.originalEvent = { touches: [{ 'pageX' : 0 }, { 'pageY' : 0 }] }; }; asyncTest( "long press fires tap hold after 750 ms", function(){ var taphold = false; forceTouchSupport(); $( "#qunit-fixture" ).bind("taphold", function(){ taphold = true; }); $( "#qunit-fixture" ).trigger("vmousedown"); setTimeout(function(){ ok(taphold); start(); }, 751); }); //NOTE used to simulate movement when checked //TODO find a better way ... var mockAbs = function(value){ Math.abs = function(){ return value; }; }; asyncTest( "move prevents taphold", function(){ expect( 1 ); var taphold = false; forceTouchSupport(); mockAbs(100); //NOTE record taphold event $( "#qunit-fixture" ).bind("taphold", function(){ ok(false, "taphold fired"); taphold = true; }); //NOTE start the touch events $( "#qunit-fixture" ).trigger("vmousedown"); //NOTE fire touchmove to push back taphold setTimeout(function(){ $( "#qunit-fixture" ).trigger("vmousecancel"); }, 100); //NOTE verify that the taphold hasn't been fired // with the normal timing setTimeout(function(){ ok(!taphold, "taphold not fired"); start(); }, 751); }); asyncTest( "tap event fired without movement", function(){ expect( 1 ); var tap = false, checkTap = function(){ ok(true, "tap fired"); }; forceTouchSupport(); //NOTE record the tap event $( "#qunit-fixture" ).bind("tap", checkTap); $( "#qunit-fixture" ).trigger("vmousedown"); $( "#qunit-fixture" ).trigger("vmouseup"); $( "#qunit-fixture" ).trigger("vclick"); setTimeout(function(){ start(); }, 400); }); asyncTest( "tap event not fired when there is movement", function(){ expect( 1 ); var tap = false; forceTouchSupport(); //NOTE record tap event $( "#qunit-fixture" ).bind("tap", function(){ ok(false, "tap fired"); tap = true; }); //NOTE make sure movement is recorded mockAbs(100); //NOTE start and move right away $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchmove"); //NOTE end touch sequence after 20 ms setTimeout(function(){ $( "#qunit-fixture" ).trigger("touchend"); }, 20); setTimeout(function(){ ok(!tap, "not tapped"); start(); }, 40); }); asyncTest( "tap event propagates up DOM tree", function(){ var tap = 0, $qf = $( "#qunit-fixture" ), $doc = $( document ), docTapCB = function(){ same(++tap, 2, "document tap callback called once after #qunit-fixture callback"); }; $qf.bind( "tap", function() { same(++tap, 1, "#qunit-fixture tap callback called once"); }); $doc.bind( "tap", docTapCB ); $qf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered twice, once for // #qunit-fixture, and a second time for document. same( tap, 2, "final tap callback count is 2" ); $doc.unbind( "tap", docTapCB ); start(); }); asyncTest( "stopPropagation() prevents tap from propagating up DOM tree", function(){ var tap = 0, $qf = $( "#qunit-fixture" ), $doc = $( document ), docTapCB = function(){ ok(false, "tap should NOT be triggered on document"); }; $qf.bind( "tap", function(e) { same(++tap, 1, "tap callback 1 triggered once on #qunit-fixture"); e.stopPropagation(); }) .bind( "tap", function(e) { same(++tap, 2, "tap callback 2 triggered once on #qunit-fixture"); }); $doc.bind( "tap", docTapCB); $qf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered twice. same( tap, 2, "final tap count is 2" ); $doc.unbind( "tap", docTapCB ); start(); }); asyncTest( "stopImmediatePropagation() prevents tap propagation and execution of 2nd handler", function(){ var tap = 0, $cf = $( "#qunit-fixture" ); $doc = $( document ), docTapCB = function(){ ok(false, "tap should NOT be triggered on document"); }; // Bind 2 tap callbacks on qunit-fixture. Only the first // one should ever be called. $cf.bind( "tap", function(e) { same(++tap, 1, "tap callback 1 triggered once on #qunit-fixture"); e.stopImmediatePropagation(); }) .bind( "tap", function(e) { ok(false, "tap callback 2 should NOT be triggered on #qunit-fixture"); }); $doc.bind( "tap", docTapCB); $cf.trigger( "vmousedown" ) .trigger( "vmouseup" ) .trigger( "vclick" ); // tap binding should be triggered once. same( tap, 1, "final tap count is 1" ); $doc.unbind( "tap", docTapCB ); start(); }); var swipeTimedTest = function(opts){ var swipe = false; forceTouchSupport(); $( "#qunit-fixture" ).bind('swipe', function(){ swipe = true; }); //NOTE bypass the trigger source check $.Event.prototype.originalEvent = { touches: false }; $( "#qunit-fixture" ).trigger("touchstart"); //NOTE make sure the coordinates are calculated within range // to be registered as a swipe mockAbs(opts.coordChange); setTimeout(function(){ $( "#qunit-fixture" ).trigger("touchmove"); $( "#qunit-fixture" ).trigger("touchend"); }, opts.timeout + 100); setTimeout(function(){ same(swipe, opts.expected, "swipe expected"); start(); }, opts.timeout + 200); stop(); }; test( "swipe fired when coordinate change in less than a second", function(){ swipeTimedTest({ timeout: 10, coordChange: 35, expected: true }); }); test( "swipe not fired when coordinate change takes more than a second", function(){ swipeTimedTest({ timeout: 1000, coordChange: 35, expected: false }); }); test( "swipe not fired when coordinate change <= 30", function(){ swipeTimedTest({ timeout: 1000, coordChange: 30, expected: false }); }); test( "swipe not fired when coordinate change >= 75", function(){ swipeTimedTest({ timeout: 1000, coordChange: 75, expected: false }); }); asyncTest( "scrolling prevented when coordinate change > 10", function(){ expect( 1 ); forceTouchSupport(); // ensure the swipe custome event is setup $( "#qunit-fixture" ).bind('swipe', function(){}); //NOTE bypass the trigger source check $.Event.prototype.originalEvent = { touches: false }; $.Event.prototype.preventDefault = function(){ ok(true, "prevent default called"); start(); }; mockAbs(11); $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchmove"); }); asyncTest( "move handler returns when touchstart has been fired since touchstop", function(){ expect( 1 ); // bypass triggered event check $.Event.prototype.originalEvent = { touches: false }; forceTouchSupport(); // ensure the swipe custome event is setup $( "#qunit-fixture" ).bind('swipe', function(){}); $( "#qunit-fixture" ).trigger("touchstart"); $( "#qunit-fixture" ).trigger("touchend"); $( "#qunit-fixture" ).bind("touchmove", function(){ ok(true, "touchmove bound functions are fired"); start(); }); Math.abs = function(){ ok(false, "shouldn't compare coordinates"); }; $( "#qunit-fixture" ).trigger("touchmove"); }); var nativeSupportTest = function(opts){ $.support.orientation = opts.orientationSupport; same($.event.special.orientationchange[opts.method](), opts.returnValue); }; test( "orientation change setup should do nothing when natively supported", function(){ nativeSupportTest({ method: 'setup', orientationSupport: true, returnValue: false }); }); test( "orientation change setup should bind resize when not supported natively", function(){ nativeSupportTest({ method: 'setup', orientationSupport: false, returnValue: undefined //NOTE result of bind function call }); }); test( "orientation change teardown should do nothing when natively supported", function(){ nativeSupportTest({ method: 'teardown', orientationSupport: true, returnValue: false }); }); test( "orientation change teardown should unbind resize when not supported natively", function(){ nativeSupportTest({ method: 'teardown', orientationSupport: false, returnValue: undefined //NOTE result of unbind function call }); }); /* The following 4 tests are async so that the throttled event triggers don't interfere with subsequent tests */ asyncTest( "throttledresize event proxies resize events", function(){ $( window ).one( "throttledresize", function(){ ok( true, "throttledresize called"); start(); }); $( window ).trigger( "resize" ); }); asyncTest( "throttledresize event prevents resize events from firing more frequently than 250ms", function(){ var called = 0; $(window).bind( "throttledresize", function(){ called++; }); // NOTE 250 ms * 3 = 750ms which is plenty of time // for the events to trigger before the next test, but // not so much time that the second resize will be triggered // before the call to same() is made $.testHelper.sequence([ function(){ $(window).trigger( "resize" ).trigger( "resize" ); }, // verify that only one throttled resize was called after 250ms function(){ same( called, 1 ); }, function(){ start(); } ], 250); }); asyncTest( "throttledresize event promises that a held call will execute only once after throttled timeout", function(){ var called = 0; expect( 2 ); $.testHelper.eventSequence( "throttledresize", [ // ignore the first call $.noop, function(){ ok( true, "second throttled resize should run" ); }, function(timedOut){ ok( timedOut, "third throttled resize should not run"); start(); } ]); $.mobile.pageContainer .trigger( "resize" ) .trigger( "resize" ) .trigger( "resize" ); }); asyncTest( "mousedown mouseup and click events should add a which when its not defined", function() { var whichDefined = function( event ){ same(event.which, 1); }; $( document ).bind( "vclick", whichDefined); $( document ).trigger( "click" ); $( document ).bind( "vmousedown", whichDefined); $( document ).trigger( "mousedown" ); $( document ).bind( "vmouseup", function( event ){ same(event.which, 1); start(); }); $( document ).trigger( "mouseup" ); }); })(jQuery);
JavaScript
/* * mobile dialog unit tests */ (function($){ module('jquery.mobile.fieldContain.js'); test( "Field container contains appropriate css styles", function(){ ok($('#test-fieldcontain').hasClass('ui-field-contain ui-body ui-br'), 'A fieldcontain element must contain styles "ui-field-contain ui-body ui-br"'); }); test( "Field container will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-field-contain").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-field-contain").length, "enhancements applied" ); }); })(jQuery);
JavaScript
/* * mobile buttonMarkup tests */ (function($){ module("jquery.mobile.buttonMarkup.js"); test( "control group buttons should be enhanced inside a footer", function(){ var group, linkCount; group = $("#control-group-footer"); linkCount = group.find( "a" ).length; same( group.find("a.ui-btn").length, linkCount, "all 4 links should be buttons"); same( group.find("a > span.ui-corner-left").length, 1, "only 1 left cornered button"); same( group.find("a > span.ui-corner-right").length, 1, "only 1 right cornered button"); same( group.find("a > span:not(.ui-corner-left):not(.ui-corner-right)").length, linkCount - 2, "only 2 buttons are cornered"); }); test( "control group buttons should respect theme-related data attributes", function(){ var group = $("#control-group-content"); ok(!group.find('[data-shadow=false]').hasClass("ui-shadow"), "buttons with data-shadow=false should not have the ui-shadow class"); ok(!group.find('[data-corners=false]').hasClass("ui-btn-corner-all"), "buttons with data-corners=false should not have the ui-btn-corner-all class"); ok(!group.find('[data-iconshadow=false] .ui-icon').hasClass("ui-icon-shadow"), "buttons with data-iconshadow=false should not have the ui-icon-shadow class on their icons"); }); // Test for issue #3046 and #3054: test( "mousedown on SVG elements should not throw an exception", function(){ var svg = $("#embedded-svg"), success = true, rect; ok(svg.length > 0, "found embedded svg document" ); if ( svg.length > 0 ) { rect = $( "rect", svg ); ok(rect.length > 0, "found rect" ); try { rect.trigger("mousedown"); } catch ( ex ) { success = false; } ok( success, "mousedown executed without exception"); } }); })(jQuery);
JavaScript
/* * mobile listview unit tests */ // TODO split out into seperate test files (function( $ ){ module( "Collapsible section", {}); asyncTest( "The page should enhanced correctly", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-test" ); }, function() { var $page = $( "#basic-collapsible-test" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible" ), ".ui-collapsible class added to collapsible elements" ); ok($page.find( ".ui-content >:eq(0) >:header" ).hasClass( "ui-collapsible-heading" ), ".ui-collapsible-heading class added to collapsible heading" ); ok($page.find( ".ui-content >:eq(0) > div" ).hasClass( "ui-collapsible-content" ), ".ui-collapsible-content class added to collapsible content" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible-collapsed" ), ".ui-collapsible-collapsed added to collapsed elements" ); ok(!$page.find( ".ui-content >:eq(1)" ).hasClass( "ui-collapsible-collapsed" ), ".ui-collapsible-collapsed not added to expanded elements" ); ok($page.find( ".ui-collapsible.ui-collapsible-collapsed" ).find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top ui-corner-bottom" ), "Collapsible header button should have class ui-corner-all" ); start(); } ]); }); asyncTest( "Expand/Collapse", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-test" ); }, function() { ok($( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); $( "#basic-collapsible-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok(!$( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be expanded after click"); $( "#basic-collapsible-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok($( "#basic-collapsible-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); start(); } ]); }); module( "Collapsible set", {}); asyncTest( "The page should enhanced correctly", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { var $page = $( "#basic-collapsible-set-test" ); ok($page.find( ".ui-content >:eq(0)" ).hasClass( "ui-collapsible-set" ), ".ui-collapsible-set class added to collapsible set" ); ok($page.find( ".ui-content >:eq(0) > div" ).hasClass( "ui-collapsible" ), ".ui-collapsible class added to collapsible elements" ); $page.find( ".ui-collapsible-set" ).each(function() { var $this = $( this ); ok($this.find( ".ui-collapsible" ).first().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top" ), "First collapsible header button should have class ui-corner-top" ); ok($this.find( ".ui-collapsible" ).last().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-bottom" ), "Last collapsible header button should have class ui-corner-bottom" ); }); start(); } ]); }); asyncTest( "Collapsible set with only one collapsible", function() { $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-set-with-lonely-collapsible-test" ); }, function() { var $page = $( "#collapsible-set-with-lonely-collapsible-test" ); $page.find( ".ui-collapsible-set" ).each(function() { var $this = $( this ); ok($this.find( ".ui-collapsible" ).first().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-top" ), "First collapsible header button should have class ui-corner-top" ); ok($this.find( ".ui-collapsible" ).last().find( ".ui-collapsible-heading-toggle > .ui-btn-inner" ).hasClass( "ui-corner-bottom" ), "Last collapsible header button should have class ui-corner-bottom" ); }); start(); } ]); }); asyncTest( "Section expanded by default", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { equals($( "#basic-collapsible-set-test .ui-content >:eq(0) .ui-collapsible-collapsed" ).length, 2, "There should be 2 section collapsed" ); ok(!$( "#basic-collapsible-set-test .ui-content >:eq(0) >:eq(1)" ).hasClass( "ui-collapsible-collapsed" ), "Section B should be expanded" ); start(); } ]); }); asyncTest( "Expand/Collapse", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#basic-collapsible-set-test" ); }, function() { ok($( "#basic-collapsible-set-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be collapsed"); $( "#basic-collapsible-set-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok(!$( "#basic-collapsible-set-test .ui-collapsible" ).eq(0).hasClass( "ui-collapsible-collapsed" ), "First collapsible should be expanded after click"); $( "#basic-collapsible-set-test .ui-collapsible-heading-toggle" ).eq(0).click(); ok($( "#basic-collapsible-set-test .ui-collapsible" ).hasClass( "ui-collapsible-collapsed" ), "All collapsible should be collapsed"); start(); } ]); }); module( "Theming", {}); asyncTest( "Collapsible", 6, function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-with-theming" ); }, function() { var collapsibles = $.mobile.activePage.find( ".ui-collapsible" ); ok( collapsibles.eq(0).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-a" ), "Heading of first collapsible should have class ui-btn-up-a"); ok( !collapsibles.eq(0).find( ".ui-collapsible-content" ).hasClass( "ui-btn-up-a" ), "Content of first collapsible should NOT have class ui-btn-up-a"); ok( collapsibles.eq(1).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-b" ), "Heading of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(1).find( ".ui-collapsible-content" ).hasClass( "ui-body-b" ), "Content of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(2).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-c" ), "Heading of third collapsible should have class ui-btn-up-c"); ok( collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-body-c" ), "Content of third collapsible should have class ui-btn-up-c"); start(); } ]); }); asyncTest( "Collapsible Set", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage( "#collapsible-set-with-theming" ); }, function() { var collapsibles = $.mobile.activePage.find( ".ui-collapsible" ); ok( collapsibles.eq(0).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-a" ), "Heading of first collapsible should have class ui-btn-up-a"); ok( !collapsibles.eq(0).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of first collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(0).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of first collapsible should NOT have class ui-btn-up-d"); ok( collapsibles.eq(1).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-b" ), "Heading of second collapsible should have class ui-btn-up-b"); ok( !collapsibles.eq(1).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-c,.ui-body-d" ), "Content of second collapsible should NOT have class ui-btn-up-[a,c,d]"); ok( collapsibles.eq(1).find( ".ui-collapsible-content" ).hasClass( "ui-body-b" ), "Content of second collapsible should have class ui-btn-up-b"); ok( collapsibles.eq(2).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-d" ), "Heading of third collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(2).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of third collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of third collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(2).find( ".ui-collapsible-content" ).hasClass( "ui-collapsible-content-collapsed" ), "Content of third collapsible should NOT have class ui-collapsible-content-collapsed"); ok( collapsibles.eq(3).find( ".ui-collapsible-heading-toggle" ).hasClass( "ui-btn-up-d" ), "Heading of fourth collapsible should have class ui-btn-up-d"); ok( !collapsibles.eq(3).find( ".ui-collapsible-content" ).is( ".ui-body-a,.ui-body-b,.ui-body-c" ), "Content of fourth collapsible should NOT have class ui-btn-up-[a,b,c]"); ok( collapsibles.eq(3).find( ".ui-collapsible-content" ).hasClass( "ui-body-d" ), "Content of fourth collapsible should have class ui-btn-up-d"); start(); } ]); }); })( jQuery );
JavaScript
// load testswarm agent (function() { var url = window.location.search; url = decodeURIComponent( url.slice( url.indexOf("swarmURL=") + 9 ) ); if ( !url || url.indexOf("http") !== 0 ) { return; } document.write("<scr" + "ipt src='http://swarm.jquery.org/js/inject.js?" + (new Date).getTime() + "'></scr" + "ipt>"); })();
JavaScript
/* * mobile media unit tests */ (function($){ var cssFn = $.fn.css, widthFn = $.fn.width; // make sure original definitions are reset module('jquery.mobile.media.js', { setup: function(){ $(document).trigger('mobileinit.htmlclass'); }, teardown: function(){ $.fn.css = cssFn; $.fn.width = widthFn; } }); test( "media query check returns true when the position is absolute", function(){ $.fn.css = function(){ return "absolute"; }; same($.mobile.media("screen 1"), true); }); test( "media query check returns false when the position is not absolute", function(){ $.fn.css = function(){ return "not absolute"; }; same($.mobile.media("screen 2"), false); }); test( "media query check is cached", function(){ $.fn.css = function(){ return "absolute"; }; same($.mobile.media("screen 3"), true); $.fn.css = function(){ return "not absolute"; }; same($.mobile.media("screen 3"), true); }); })(jQuery);
JavaScript
/* * mobile page unit tests */ (function($){ var libName = 'jquery.mobile.page.sections.js', themedefault = $.mobile.page.prototype.options.theme, keepNative = $.mobile.page.prototype.options.keepNative; module(libName, { setup: function() { $.mobile.page.prototype.options.keepNative = keepNative; } }); var eventStack = [], etargets = [], cEvents=[], cTargets=[]; $( document ).bind( "pagebeforecreate pagecreate", function( e ){ eventStack.push( e.type ); etargets.push( e.target ); }); $("#c").live( "pagebeforecreate", function( e ){ cEvents.push( e.type ); cTargets.push( e.target ); return false; }); test( "pagecreate event fires when page is created", function(){ ok( eventStack[0] === "pagecreate" || eventStack[1] === "pagecreate" ); }); test( "pagebeforecreate event fires when page is created", function(){ ok( eventStack[0] === "pagebeforecreate" || eventStack[1] === "pagebeforecreate" ); }); test( "pagebeforecreate fires before pagecreate", function(){ ok( eventStack[0] === "pagebeforecreate" ); }); test( "target of pagebeforecreate event was div #a", function(){ ok( $( etargets[0] ).is("#a") ); }); test( "target of pagecreate event was div #a" , function(){ ok( $( etargets[0] ).is("#a") ); }); test( "page element has ui-page class" , function(){ ok( $( "#a" ).hasClass( "ui-page" ) ); }); test( "page element has default body theme when not overidden" , function(){ ok( $( "#a" ).hasClass( "ui-body-" + themedefault ) ); }); test( "B page has non-default theme matching its data-theme attr" , function(){ $( "#b" ).page(); var btheme = $( "#b" ).jqmData( "theme" ); ok( $( "#b" ).hasClass( "ui-body-" + btheme ) ); }); test( "Binding to pagebeforecreate and returning false prevents pagecreate event from firing" , function(){ $("#c").page(); ok( cEvents[0] === "pagebeforecreate" ); ok( !cTargets[1] ); }); test( "Binding to pagebeforecreate and returning false prevents classes from being applied to page" , function(){ ok( !$( "#b" ).hasClass( "ui-body-" + themedefault ) ); ok( !$( "#b" ).hasClass( "ui-page" ) ); }); test( "keepNativeSelector returns the default where keepNative is not different", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = pageProto.options.keepNativeDefault; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); }); test( "keepNativeSelector returns the default where keepNative is empty, undefined, whitespace", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = ""; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); pageProto.options.keepNative = undefined; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); pageProto.options.keepNative = " "; same(pageProto.keepNativeSelector(), pageProto.options.keepNativeDefault); }); test( "keepNativeSelector returns a selector joined with the default", function() { var pageProto = $.mobile.page.prototype; pageProto.options.keepNative = "foo, bar"; same(pageProto.keepNativeSelector(), "foo, bar, " + pageProto.options.keepNativeDefault); }); })(jQuery);
JavaScript
$(function() { var Runner = function( ) { var self = this; $.extend( self, { frame: window.frames[ "testFrame" ], testTimeout: 3 * 60 * 1000, $frameElem: $( "#testFrame" ), assertionResultPrefix: "assertion result for test:", onTimeout: QUnit.start, onFrameLoad: function() { // establish a timeout for a given suite in case of async tests hanging self.testTimer = setTimeout( self.onTimeout, self.testTimeout ); // it might be a redirect with query params for push state // tests skip this call and expect another if( !self.frame.QUnit ) { self.$frameElem.one( "load", self.onFrameLoad ); return; } // when the QUnit object reports done in the iframe // run the onFrameDone method self.frame.QUnit.done = self.onFrameDone; self.frame.QUnit.testDone = self.onTestDone; }, onTestDone: function( result ) { QUnit.ok( !(result.failed > 0), result.name ); self.recordAssertions( result.total - result.failed, result.name ); }, onFrameDone: function( failed, passed, total, runtime ){ // make sure we don't time out the tests clearTimeout( self.testTimer ); // TODO decipher actual cause of multiple test results firing twice // clear the done call to prevent early completion of other test cases self.frame.QUnit.done = $.noop; self.frame.QUnit.testDone = $.noop; // hide the extra assertions made to propogate the count // to the suite level test self.hideAssertionResults(); // continue on to the next suite QUnit.start(); }, recordAssertions: function( count, parentTest ) { for( var i = 0; i < count; i++ ) { ok( true, self.assertionResultPrefix + parentTest ); } }, hideAssertionResults: function() { $( "li:not([id]):contains('" + self.assertionResultPrefix + "')" ).hide(); }, exec: function( data ) { var template = self.$frameElem.attr( "data-src" ); $.each( data.testPages, function(i, dir) { QUnit.asyncTest( dir, function() { self.dir = dir; self.$frameElem.one( "load", self.onFrameLoad ); self.$frameElem.attr( "src", template.replace("{{testdir}}", dir) ); }); }); // having defined all suite level tests let QUnit run QUnit.start(); } }); }; // prevent qunit from starting the test suite until all tests are defined QUnit.begin = function( ) { this.config.autostart = false; }; // get the test directories $.get( "ls.php", (new Runner()).exec ); });
JavaScript
/* * mobile init tests */ (function($){ test( "page element is generated when not present in initial markup", function(){ ok( $( ".ui-page" ).length, 1 ); }); })(jQuery);
JavaScript
/* * mobile init tests */ (function($){ var mobilePage = undefined, libName = 'jquery.mobile.init.js', coreLib = 'jquery.mobile.core.js', extendFn = $.extend, setGradeA = function(value) { $.mobile.gradeA = function(){ return value; }; }, reloadCoreNSandInit = function(){ $.testHelper.reloadLib(coreLib); $.testHelper.reloadLib("jquery.setNamespace.js"); $.testHelper.reloadLib(libName); }; module(libName, { setup: function(){ // NOTE reset for gradeA tests $('html').removeClass('ui-mobile'); // TODO add post reload callback $('.ui-loader').remove(); }, teardown: function(){ $.extend = extendFn; // NOTE reset for showPageLoadingMsg/hidePageLoadingMsg tests $('.ui-loader').remove(); // clear the classes added by reloading the init $("html").attr('class', ''); } }); // NOTE important to use $.fn.one here to make sure library reloads don't fire // the event before the test check below $(document).one("mobileinit", function(){ mobilePage = $.mobile.page; }); // NOTE for the following two tests see index html for the binding test( "mobile.page is available when mobile init is fired", function(){ ok( mobilePage !== undefined, "$.mobile.page is defined" ); }); $.testHelper.excludeFileProtocol(function(){ asyncTest( "loading the init library triggers mobilinit on the document", function(){ var initFired = false; expect( 1 ); $(window.document).one('mobileinit', function(event){ initFired = true; }); $.testHelper.reloadLib(libName); setTimeout(function(){ ok(initFired, "init fired"); start(); }, 1000); }); test( "enhancments are skipped when the browser is not grade A", function(){ setGradeA(false); $.testHelper.reloadLib(libName); //NOTE easiest way to check for enhancements, not the most obvious ok(!$("html").hasClass("ui-mobile"), "html elem doesn't have class ui-mobile"); }); test( "enhancments are added when the browser is grade A", function(){ setGradeA(true); $.testHelper.reloadLib(libName); ok($("html").hasClass("ui-mobile"), "html elem has class mobile"); }); asyncTest( "useFastClick is configurable via mobileinit", function(){ $(document).one( "mobileinit", function(){ $.mobile.useFastClick = false; start(); }); $.testHelper.reloadLib(libName); same( $.mobile.useFastClick, false , "fast click is set to false after init" ); $.mobile.useFastClick = true; }); var findFirstPage = function() { return $(":jqmData(role='page')").first(); }; test( "active page and start page should be set to the fist page in the selected set", function(){ expect( 2 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); same($.mobile.firstPage[0], firstPage[0]); same($.mobile.activePage[0], firstPage[0]); }); test( "mobile viewport class is defined on the first page's parent", function(){ expect( 1 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); ok(firstPage.parent().hasClass("ui-mobile-viewport"), "first page has viewport"); }); test( "mobile page container is the first page's parent", function(){ expect( 1 ); $.testHelper.reloadLib(libName); var firstPage = findFirstPage(); same($.mobile.pageContainer[0], firstPage.parent()[0]); }); asyncTest( "hashchange triggered on document ready with single argument: true", function(){ $.testHelper.sequence([ function(){ location.hash = "#foo"; }, // delay the bind until the first hashchange function(){ $(window).one("hashchange", function(ev, arg){ same(arg, true); start(); }); }, function(){ $.testHelper.reloadLib(libName); } ], 1000); }); test( "pages without a data-url attribute have it set to their id", function(){ same($("#foo").jqmData('url'), "foo"); }); test( "pages with a data-url attribute are left with the original value", function(){ same($("#bar").jqmData('url'), "bak"); }); asyncTest( "showPageLoadingMsg doesn't add the dialog to the page when loading message is false", function(){ expect( 1 ); $.mobile.loadingMessage = false; $.mobile.showPageLoadingMsg(); setTimeout(function(){ ok(!$(".ui-loader").length, "no ui-loader element"); start(); }, 500); }); asyncTest( "hidePageLoadingMsg doesn't add the dialog to the page when loading message is false", function(){ expect( 1 ); $.mobile.loadingMessage = true; $.mobile.hidePageLoadingMsg(); setTimeout(function(){ same($(".ui-loading").length, 0, "page should not be in the loading state"); start(); }, 500); }); asyncTest( "showPageLoadingMsg adds the dialog to the page when loadingMessage is true", function(){ expect( 1 ); $.mobile.loadingMessage = true; $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loading").length, 1, "page should be in the loading state"); start(); }, 500); }); asyncTest( "page loading should contain default loading message", function(){ expect( 1 ); reloadCoreNSandInit(); $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "loading"); start(); }, 500); }); asyncTest( "page loading should contain custom loading message", function(){ $.mobile.loadingMessage = "foo"; $.testHelper.reloadLib(libName); $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "foo"); start(); }, 500); }); asyncTest( "page loading should contain custom loading message when set during runtime", function(){ $.mobile.loadingMessage = "bar"; $.mobile.showPageLoadingMsg(); setTimeout(function(){ same($(".ui-loader h1").text(), "bar"); start(); }, 500); }); // NOTE: the next two tests work on timeouts that assume a page will be created within 2 seconds // it'd be great to get these using a more reliable callback or event asyncTest( "page does auto-initialize at domready when autoinitialize option is true (default) ", function(){ $( "<div />", { "data-nstest-role": "page", "id": "autoinit-on" } ).prependTo( "body" ) $(document).one("mobileinit", function(){ $.mobile.autoInitializePage = true; }); location.hash = ""; reloadCoreNSandInit(); setTimeout(function(){ same( $( "#autoinit-on.ui-page" ).length, 1 ); start(); }, 2000); }); asyncTest( "page does not initialize at domready when autoinitialize option is false ", function(){ $(document).one("mobileinit", function(){ $.mobile.autoInitializePage = false; }); $( "<div />", { "data-nstest-role": "page", "id": "autoinit-off" } ).prependTo( "body" ) location.hash = ""; reloadCoreNSandInit(); setTimeout(function(){ same( $( "#autoinit-off.ui-page" ).length, 0 ); $(document).bind("mobileinit", function(){ $.mobile.autoInitializePage = true; }); reloadCoreNSandInit(); start(); }, 2000); }); }); })(jQuery);
JavaScript
/* * mobile dialog unit tests */ (function($) { module( "jquery.mobile.dialog.js", { setup: function() { $.mobile.page.prototype.options.contentTheme = "d"; } }); asyncTest( "dialog hash is added when the dialog is opened and removed when closed", function() { expect( 2 ); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#foo-dialog-link" ).click(); }, function() { var fooDialog = $( "#foo-dialog" ); // make sure the dialog came up ok( /&ui-state=dialog/.test(location.hash), "ui-state=dialog =~ location.hash", "dialog open" ); // close the dialog $( ".ui-dialog" ).dialog( "close" ); }, function() { ok( !/&ui-state=dialog/.test(location.hash), "ui-state=dialog !~ location.hash" ); start(); } ]); }); asyncTest( "dialog element with no theming", function() { expect(4); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-a" ).click(); }, function() { var dialog = $( "#dialog-a" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-c" ), "Expected explicit theme ui-body-c" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-" + $.mobile.page.prototype.options.contentTheme ), "Expect content to inherit from $.mobile.page.prototype.options.contentTheme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); asyncTest( "dialog element with data-theme", function() { // Reset fallback theme for content $.mobile.page.prototype.options.contentTheme = null; expect(5); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-b" ).click(); }, function() { var dialog = $( "#dialog-b" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-e" ), "Expected explicit theme ui-body-e" ); ok( !dialog.hasClass( "ui-overlay-b" ), "Expected no theme ui-overlay-b" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-e" ), "Expect content to inherit from data-theme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); asyncTest( "dialog element with data-theme & data-overlay-theme", function() { expect(5); $.testHelper.pageSequence([ function() { $.mobile.changePage( $( "#mypage" ) ); }, function() { //bring up the dialog $( "#link-c" ).click(); }, function() { var dialog = $( "#dialog-c" ); // Assert dialog theme inheritance (issue 1375): ok( dialog.hasClass( "ui-body-e" ), "Expected explicit theme ui-body-e" ); ok( dialog.hasClass( "ui-overlay-b" ), "Expected explicit theme ui-overlay-b" ); ok( dialog.find( ":jqmData(role=header)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected header to inherit from $.mobile.page.prototype.options.headerTheme" ); ok( dialog.find( ":jqmData(role=content)" ).hasClass( "ui-body-" + $.mobile.page.prototype.options.contentTheme ), "Expect content to inherit from $.mobile.page.prototype.options.contentTheme" ); ok( dialog.find( ":jqmData(role=footer)" ).hasClass( "ui-bar-" + $.mobile.page.prototype.options.footerTheme ), "Expected footer to inherit from $.mobile.page.prototype.options.footerTheme" ); start(); } ]); }); })( jQuery );
JavaScript
//set namespace for unit test markp $( document ).bind( "mobileinit", function(){ $.mobile.ns = "nstest-"; });
JavaScript
/* * mobile core unit tests */ (function($){ var libName = "jquery.mobile.core.js", setGradeA = function(value, version) { $.support.mediaquery = value; $.mobile.browser.ie = version; }, extendFn = $.extend; module(libName, { setup: function(){ // NOTE reset for gradeA tests $('html').removeClass('ui-mobile'); // NOTE reset for pageLoading tests $('.ui-loader').remove(); }, teardown: function(){ $.extend = extendFn; } }); $.testHelper.excludeFileProtocol(function(){ test( "grade A browser either supports media queries or is IE 7+", function(){ setGradeA(false, 6); $.testHelper.reloadLib(libName); ok(!$.mobile.gradeA()); setGradeA(true, 8); $.testHelper.reloadLib(libName); ok($.mobile.gradeA()); }); }); function clearNSNormalizeDictionary() { var dict = $.mobile.nsNormalizeDict; for ( var prop in dict ) { delete dict[ prop ]; } } test( "$.mobile.nsNormalize works properly with namespace defined (test default)", function(){ // Start with a fresh namespace property cache, just in case // the previous test mucked with namespaces. clearNSNormalizeDictionary(); equal($.mobile.nsNormalize("foo"), "nstestFoo", "appends ns and initcaps"); equal($.mobile.nsNormalize("fooBar"), "nstestFooBar", "leaves capped strings intact"); equal($.mobile.nsNormalize("foo-bar"), "nstestFooBar", "changes dashed strings"); equal($.mobile.nsNormalize("foo-bar-bak"), "nstestFooBarBak", "changes multiple dashed strings"); // Reset the namespace property cache for the next test. clearNSNormalizeDictionary(); }); test( "$.mobile.nsNormalize works properly with an empty namespace", function(){ var realNs = $.mobile.ns; $.mobile.ns = ""; // Start with a fresh namespace property cache, just in case // the previous test mucked with namespaces. clearNSNormalizeDictionary(); equal($.mobile.nsNormalize("foo"), "foo", "leaves uncapped and undashed"); equal($.mobile.nsNormalize("fooBar"), "fooBar", "leaves capped strings intact"); equal($.mobile.nsNormalize("foo-bar"), "fooBar", "changes dashed strings"); equal($.mobile.nsNormalize("foo-bar-bak"), "fooBarBak", "changes multiple dashed strings"); $.mobile.ns = realNs; // Reset the namespace property cache for the next test. clearNSNormalizeDictionary(); }); //data tests test( "$.fn.jqmData and $.fn.jqmRemoveData methods are working properly", function(){ var data; same( $("body").jqmData("foo", true), $("body"), "setting data returns the element" ); same( $("body").jqmData("foo"), true, "getting data returns the right value" ); same( $("body").data($.mobile.nsNormalize("foo")), true, "data was set using namespace" ); same( $("body").jqmData("foo", undefined), true, "getting data still returns the value if there's an undefined second arg" ); data = $.extend( {}, $("body").data() ); delete data[ $.expando ]; //discard the expando for that test same( data , { "nstestFoo": true }, "passing .data() no arguments returns a hash with all set properties" ); same( $("body").jqmData(), undefined, "passing no arguments returns undefined" ); same( $("body").jqmData(undefined), undefined, "passing a single undefined argument returns undefined" ); same( $("body").jqmData(undefined, undefined), undefined, "passing 2 undefined arguments returns undefined" ); same( $("body").jqmRemoveData("foo"), $("body"), "jqmRemoveData returns the element" ); same( $("body").jqmData("foo"), undefined, "jqmRemoveData properly removes namespaced data" ); }); test( "$.jqmData and $.jqmRemoveData methods are working properly", function(){ same( $.jqmData(document.body, "foo", true), true, "setting data returns the value" ); same( $.jqmData(document.body, "foo"), true, "getting data returns the right value" ); same( $.data(document.body, $.mobile.nsNormalize("foo")), true, "data was set using namespace" ); same( $.jqmData(document.body, "foo", undefined), true, "getting data still returns the value if there's an undefined second arg" ); same( $.jqmData(document.body), undefined, "passing no arguments returns undefined" ); same( $.jqmData(document.body, undefined), undefined, "passing a single undefined argument returns undefined" ); same( $.jqmData(document.body, undefined, undefined), undefined, "passing 2 undefined arguments returns undefined" ); same( $.jqmRemoveData(document.body, "foo"), undefined, "jqmRemoveData returns the undefined value" ); same( $("body").jqmData("foo"), undefined, "jqmRemoveData properly removes namespaced data" ); }); test( "addDependents works properly", function() { same( $("#parent").jqmData('dependents'), undefined ); $( "#parent" ).addDependents( $("#dependent") ); same( $("#parent").jqmData('dependents').length, 1 ); }); test( "removeWithDependents removes the parent element and ", function(){ $( "#parent" ).addDependents( $("#dependent") ); same($( "#parent, #dependent" ).length, 2); $( "#parent" ).removeWithDependents(); same($( "#parent, #dependent" ).length, 0); }); test( "$.fn.getEncodedText should return the encoded value where $.fn.text doesn't", function() { same( $("#encoded").text(), "foo>"); same( $("#encoded").getEncodedText(), "foo&gt;"); same( $("#unencoded").getEncodedText(), "foo"); }); })(jQuery);
JavaScript
/* * mobile core unit tests */ (function($){ var libName = "jquery.mobile.core.js", scrollTimeout = 20, // TODO expose timing as an attribute scrollStartEnabledTimeout = 150; module(libName, { setup: function(){ $("<div id='scroll-testing' style='height: 1000px'></div>").appendTo("body"); }, teardown: function(){ $("#scroll-testing").remove(); } }); var scrollUp = function( pos ){ $(window).scrollTop(1000); ok($(window).scrollTop() > 0, $(window).scrollTop()); $.mobile.silentScroll(pos); }; asyncTest( "silent scroll scrolls the page to the top by default", function(){ scrollUp(); setTimeout(function(){ same($(window).scrollTop(), 0); start(); }, scrollTimeout); }); asyncTest( "silent scroll scrolls the page to the passed y position", function(){ var pos = 10; scrollUp(pos); setTimeout(function(){ same($(window).scrollTop(), pos); start(); }, scrollTimeout); }); test( "silent scroll is async", function(){ scrollUp(); ok($(window).scrollTop() != 0, "scrolltop position should not be zero"); start(); }); asyncTest( "scrolling marks scrollstart as disabled for 150 ms", function(){ $.event.special.scrollstart.enabled = true; scrollUp(); ok(!$.event.special.scrollstart.enabled); setTimeout(function(){ ok($.event.special.scrollstart.enabled); start(); }, scrollStartEnabledTimeout); }); //TODO test that silentScroll is called on window load })(jQuery);
JavaScript
/* * mobile support unit tests */ $.testHelper.excludeFileProtocol(function(){ var prependToFn = $.fn.prependTo, libName = "jquery.mobile.support.js"; module(libName, { teardown: function(){ //NOTE undo any mocking $.fn.prependTo = prependToFn; } }); // NOTE following two tests have debatable value as they only // prevent property name changes and improper attribute checks test( "detects functionality from basic affirmative properties and attributes", function(){ // TODO expose properties for less brittle tests $.extend(window, { WebKitTransitionEvent: true, orientation: true, onorientationchange: true }); document.ontouchend = true; window.history.pushState = function(){}; window.history.replaceState = function(){}; $.mobile.media = function(){ return true; }; $.testHelper.reloadLib(libName); ok($.support.orientation); ok($.support.touch); ok($.support.cssTransitions); ok($.support.pushState); ok($.support.mediaquery); }); test( "detects functionality from basic negative properties and attributes (where possible)", function(){ delete window["orientation"]; delete document["ontouchend"]; $.testHelper.reloadLib(libName); ok(!$.support.orientation); ok(!$.support.touch); }); // NOTE mocks prependTo to simulate base href updates or lack thereof var mockBaseCheck = function( url ){ var prependToFn = $.fn.prependTo; $.fn.prependTo = function( selector ){ var result = prependToFn.call(this, selector); if(this[0].href && this[0].href.indexOf("testurl") != -1) result = [{href: url}]; return result; }; }; test( "detects dynamic base tag when new base element added and base href updates", function(){ mockBaseCheck(location.protocol + '//' + location.host + location.pathname + "ui-dir/"); $.testHelper.reloadLib(libName); ok($.support.dynamicBaseTag); }); test( "detects no dynamic base tag when new base element added and base href unchanged", function(){ mockBaseCheck('testurl'); $.testHelper.reloadLib(libName); ok(!$.support.dynamicBaseTag); }); test( "jQM's IE browser check properly detects IE versions", function(){ $.testHelper.reloadLib(libName); //here we're just comparing our version to what the conditional compilation finds var ie = !!$.browser.msie, //get a boolean version = parseInt( $.browser.version, 10), jqmdetectedver = $.mobile.browser.ie; if( ie ){ same(version, jqmdetectedver, "It's IE and the version is correct"); } else{ same(ie, jqmdetectedver, "It's not IE"); } }); //TODO propExists testing, refactor propExists into mockable method //TODO scrollTop testing, refactor scrollTop logic into mockable method });
JavaScript
/* * mobile navigation unit tests */ (function($){ var siteDirectory = location.pathname.replace(/[^/]+$/, ""); module('jquery.mobile.navigation.js', { setup: function(){ if ( location.hash ) { stop(); $(document).one("pagechange", function() { start(); } ); location.hash = ""; } } }); test( "path.get method is working properly", function(){ window.location.hash = "foo"; same($.mobile.path.get(), "foo", "get method returns location.hash minus hash character"); same($.mobile.path.get( "#foo/bar/baz.html" ), "foo/bar/", "get method with hash arg returns path with no filename or hash prefix"); same($.mobile.path.get( "#foo/bar/baz.html/" ), "foo/bar/baz.html/", "last segment of hash is retained if followed by a trailing slash"); }); test( "path.isPath method is working properly", function(){ ok(!$.mobile.path.isPath('bar'), "anything without a slash is not a path"); ok($.mobile.path.isPath('bar/'), "anything with a slash is a path"); ok($.mobile.path.isPath('/bar'), "anything with a slash is a path"); ok($.mobile.path.isPath('a/r'), "anything with a slash is a path"); ok($.mobile.path.isPath('/'), "anything with a slash is a path"); }); test( "path.getFilePath method is working properly", function(){ same($.mobile.path.getFilePath("foo.html" + "&" + $.mobile.subPageUrlKey ), "foo.html", "returns path without sub page key"); }); test( "path.set method is working properly", function(){ $.mobile.urlHistory.ignoreNextHashChange = false; $.mobile.path.set("foo"); same("foo", window.location.hash.replace(/^#/,""), "sets location.hash properly"); }); test( "path.makeUrlAbsolute is working properly", function(){ var mua = $.mobile.path.makeUrlAbsolute, p1 = "http://jqm.com/", p2 = "http://jqm.com/?foo=1&bar=2", p3 = "http://jqm.com/#spaz", p4 = "http://jqm.com/?foo=1&bar=2#spaz", p5 = "http://jqm.com/test.php", p6 = "http://jqm.com/test.php?foo=1&bar=2", p7 = "http://jqm.com/test.php#spaz", p8 = "http://jqm.com/test.php?foo=1&bar=2#spaz", p9 = "http://jqm.com/dir1/dir2/", p10 = "http://jqm.com/dir1/dir2/?foo=1&bar=2", p11 = "http://jqm.com/dir1/dir2/#spaz", p12 = "http://jqm.com/dir1/dir2/?foo=1&bar=2#spaz", p13 = "http://jqm.com/dir1/dir2/test.php", p14 = "http://jqm.com/dir1/dir2/test.php?foo=1&bar=2", p15 = "http://jqm.com/dir1/dir2/test.php#spaz", p16 = "http://jqm.com/dir1/dir2/test.php?foo=1&bar=2#spaz"; // Test URL conversion against an absolute URL to the site root. // directory tests same( mua( "http://jqm.com/", p1 ), "http://jqm.com/", "absolute root - absolute root" ); same( mua( "//jqm.com/", p1 ), "http://jqm.com/", "protocol relative root - absolute root" ); same( mua( "/", p1 ), "http://jqm.com/", "site relative root - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "absolute root with query - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "protocol relative root with query - absolute root" ); same( mua( "/?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "site relative root with query - absolute root" ); same( mua( "?foo=1&bar=2", p1 ), "http://jqm.com/?foo=1&bar=2", "query relative - absolute root" ); same( mua( "http://jqm.com/#spaz", p1 ), "http://jqm.com/#spaz", "absolute root with fragment - absolute root" ); same( mua( "//jqm.com/#spaz", p1 ), "http://jqm.com/#spaz", "protocol relative root with fragment - absolute root" ); same( mua( "/#spaz", p1 ), "http://jqm.com/#spaz", "site relative root with fragment - absolute root" ); same( mua( "#spaz", p1 ), "http://jqm.com/#spaz", "fragment relative - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "absolute root with query and fragment - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "protocol relative root with query and fragment - absolute root" ); same( mua( "/?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "site relative root with query and fragment - absolute root" ); same( mua( "?foo=1&bar=2#spaz", p1 ), "http://jqm.com/?foo=1&bar=2#spaz", "query relative and fragment - absolute root" ); // file tests same( mua( "http://jqm.com/test.php", p1 ), "http://jqm.com/test.php", "absolute file at root - absolute root" ); same( mua( "//jqm.com/test.php", p1 ), "http://jqm.com/test.php", "protocol relative file at root - absolute root" ); same( mua( "/test.php", p1 ), "http://jqm.com/test.php", "site relative file at root - absolute root" ); same( mua( "test.php", p1 ), "http://jqm.com/test.php", "document relative file at root - absolute root" ); same( mua( "http://jqm.com/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "absolute file at root with query - absolute root" ); same( mua( "//jqm.com/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "protocol relative file at root with query - absolute root" ); same( mua( "/test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "site relative file at root with query - absolute root" ); same( mua( "test.php?foo=1&bar=2", p1 ), "http://jqm.com/test.php?foo=1&bar=2", "document relative file at root with query - absolute root" ); same( mua( "http://jqm.com/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "absolute file at root with fragment - absolute root" ); same( mua( "//jqm.com/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "protocol relative file at root with fragment - absolute root" ); same( mua( "/test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "site relative file at root with fragment - absolute root" ); same( mua( "test.php#spaz", p1 ), "http://jqm.com/test.php#spaz", "file at root with fragment - absolute root" ); same( mua( "http://jqm.com/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "absolute file at root with query and fragment - absolute root" ); same( mua( "//jqm.com/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "protocol relative file at root with query and fragment - absolute root" ); same( mua( "/test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "site relative file at root with query and fragment - absolute root" ); same( mua( "test.php?foo=1&bar=2#spaz", p1 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "query relative file at root fragment - absolute root" ); // Test URL conversion against an absolute URL to a file at the site root. same( mua( "http://jqm.com/", p5 ), "http://jqm.com/", "absolute root - absolute root" ); same( mua( "//jqm.com/", p5 ), "http://jqm.com/", "protocol relative root - absolute root" ); same( mua( "/", p5 ), "http://jqm.com/", "site relative root - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "absolute root with query - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "protocol relative root with query - absolute root" ); same( mua( "/?foo=1&bar=2", p5 ), "http://jqm.com/?foo=1&bar=2", "site relative root with query - absolute root" ); same( mua( "?foo=1&bar=2", p5 ), "http://jqm.com/test.php?foo=1&bar=2", "query relative - absolute root" ); same( mua( "http://jqm.com/#spaz", p5 ), "http://jqm.com/#spaz", "absolute root with fragment - absolute root" ); same( mua( "//jqm.com/#spaz", p5 ), "http://jqm.com/#spaz", "protocol relative root with fragment - absolute root" ); same( mua( "/#spaz", p5 ), "http://jqm.com/#spaz", "site relative root with fragment - absolute root" ); same( mua( "#spaz", p5 ), "http://jqm.com/test.php#spaz", "fragment relative - absolute root" ); same( mua( "http://jqm.com/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "absolute root with query and fragment - absolute root" ); same( mua( "//jqm.com/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "protocol relative root with query and fragment - absolute root" ); same( mua( "/?foo=1&bar=2#spaz", p5 ), "http://jqm.com/?foo=1&bar=2#spaz", "site relative root with query and fragment - absolute root" ); same( mua( "?foo=1&bar=2#spaz", p5 ), "http://jqm.com/test.php?foo=1&bar=2#spaz", "query relative and fragment - absolute root" ); }); // https://github.com/jquery/jquery-mobile/issues/2362 test( "ipv6 host support", function(){ // http://www.ietf.org/rfc/rfc2732.txt ipv6 examples for tests // most definitely not comprehensive var ipv6_1 = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html", ipv6_2 = "http://[1080:0:0:0:8:800:200C:417A]/index.html", ipv6_3 = "http://[3ffe:2a00:100:7031::1]", ipv6_4 = "http://[1080::8:800:200C:417A]/foo", ipv6_5 = "http://[::192.9.5.5]/ipng", ipv6_6 = "http://[::FFFF:129.144.52.38]:80/index.html", ipv6_7 = "http://[2010:836B:4179::836B:4179]", fromIssue = "http://[3fff:cafe:babe::]:443/foo"; same( $.mobile.path.parseUrl(ipv6_1).host, "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80"); same( $.mobile.path.parseUrl(ipv6_1).hostname, "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]"); same( $.mobile.path.parseUrl(ipv6_2).host, "[1080:0:0:0:8:800:200C:417A]"); same( $.mobile.path.parseUrl(ipv6_3).host, "[3ffe:2a00:100:7031::1]"); same( $.mobile.path.parseUrl(ipv6_4).host, "[1080::8:800:200C:417A]"); same( $.mobile.path.parseUrl(ipv6_5).host, "[::192.9.5.5]"); same( $.mobile.path.parseUrl(ipv6_6).host, "[::FFFF:129.144.52.38]:80"); same( $.mobile.path.parseUrl(ipv6_6).hostname, "[::FFFF:129.144.52.38]"); same( $.mobile.path.parseUrl(ipv6_7).host, "[2010:836B:4179::836B:4179]"); same( $.mobile.path.parseUrl(fromIssue).host, "[3fff:cafe:babe::]:443"); same( $.mobile.path.parseUrl(fromIssue).hostname, "[3fff:cafe:babe::]"); }); test( "path.clean is working properly", function(){ var localroot = location.protocol + "//" + location.host + location.pathname, remoteroot = "http://google.com/", fakepath = "#foo/bar/baz.html", pathWithParam = localroot + "bar?baz=" + localroot, localpath = localroot + fakepath, remotepath = remoteroot + fakepath; same( $.mobile.path.clean( localpath ), location.pathname + fakepath, "removes location protocol, host, and portfrom same-domain path"); same( $.mobile.path.clean( remotepath ), remotepath, "does nothing to an external domain path"); same( $.mobile.path.clean( pathWithParam ), location.pathname + "bar?baz=" + localroot, "doesn't remove params with localroot value"); }); test( "path.stripHash is working properly", function(){ same( $.mobile.path.stripHash( "#bar" ), "bar", "returns a hash without the # prefix"); }); test( "path.hasProtocol is working properly", function(){ same( $.mobile.path.hasProtocol( "tel:5559999" ), true, "value in tel protocol format has protocol" ); same( $.mobile.path.hasProtocol( location.href ), true, "location href has protocol" ); same( $.mobile.path.hasProtocol( "foo/bar/baz.html" ), false, "simple directory path has no protocol" ); same( $.mobile.path.hasProtocol( "file://foo/bar/baz.html" ), true, "simple directory path with file:// has protocol" ); }); test( "path.isRelativeUrl is working properly", function(){ same( $.mobile.path.isRelativeUrl("http://company.com/"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("http://company.com/test.php"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/test.php"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/test.php"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("test.php"), true, "document relative url is relative" ); same( $.mobile.path.isRelativeUrl("http://company.com/dir1/dir2/test.php?foo=1&bar=2#frag"), false, "absolute url is not relative" ); same( $.mobile.path.isRelativeUrl("//company.com/dir1/dir2/test.php?foo=1&bar=2#frag"), true, "protocol relative url is relative" ); same( $.mobile.path.isRelativeUrl("/dir1/dir2/test.php?foo=1&bar=2#frag"), true, "site relative url is relative" ); same( $.mobile.path.isRelativeUrl("dir1/dir2/test.php?foo=1&bar=2#frag"), true, "document relative path url is relative" ); same( $.mobile.path.isRelativeUrl("test.php?foo=1&bar=2#frag"), true, "document relative file url is relative" ); same( $.mobile.path.isRelativeUrl("?foo=1&bar=2#frag"), true, "query relative url is relative" ); same( $.mobile.path.isRelativeUrl("#frag"), true, "fragments are relative" ); }); test( "path.isExternal is working properly", function(){ same( $.mobile.path.isExternal( location.href ), false, "same domain is not external" ); same( $.mobile.path.isExternal( "http://example.com" ), true, "example.com is external" ); same($.mobile.path.isExternal("mailto:"), true, "mailto protocol"); same($.mobile.path.isExternal("http://foo.com"), true, "http protocol"); same($.mobile.path.isExternal("http://www.foo.com"), true, "http protocol with www"); same($.mobile.path.isExternal("tel:16178675309"), true, "tel protocol"); same($.mobile.path.isExternal("foo.html"), false, "filename"); same($.mobile.path.isExternal("foo/foo/foo.html"), false, "file path"); same($.mobile.path.isExternal("../../index.html"), false, "relative parent path"); same($.mobile.path.isExternal("/foo"), false, "root-relative path"); same($.mobile.path.isExternal("foo"), false, "simple string"); same($.mobile.path.isExternal("#foo"), false, "local id reference"); }); test( "path.cleanHash", function(){ same( $.mobile.path.cleanHash( "#anything/atall?akjfdjjf" ), "anything/atall", "removes query param"); same( $.mobile.path.cleanHash( "#nothing/atall" ), "nothing/atall", "removes query param"); }); })(jQuery);
JavaScript
/* * mobile navigation path unit tests */ (function($){ var url = $.mobile.path.parseUrl( location.href ), home = location.href.replace( url.domain, "" ); var testPageLoad = function(testPageAnchorSelector, expectedTextValue){ expect( 2 ); $.testHelper.pageSequence([ function(){ // reset before each test, all tests expect original page // for relative urls $.testHelper.openPage( "#" + home); }, // open our test page function(){ $.testHelper.openPage("#pathing-tests"); }, // navigate to the linked page function(){ var page = $.mobile.activePage; // check that the reset page isn't still open equal("", page.find(".reset-value").text()); //click he test page link to execute the path page.find("a" + testPageAnchorSelector).click(); }, // verify that the page has changed and the expected text value is present function(){ same($.mobile.activePage.find(".test-value").text(), expectedTextValue); start(); } ]); }; // all of these alterations assume location.pathname will be a directory // this is required to prevent the tests breaking in a subdirectory // TODO could potentially be fragile since the tests could be running while // the urls are being updated $(function(){ $("a.site-rel").each(function(i, elem){ var $elem = $(elem); $elem.attr("href", location.pathname + $(elem).attr("href")); }); $('a.protocol-rel').each(function(i, elem){ var $elem = $(elem); $elem.attr("href", "//" + location.host + location.pathname + $(elem).attr("href")); }); $('a.absolute').each(function(i, elem){ var $elem = $(elem); $elem.attr("href", location.protocol + "//" + location.host + location.pathname + $(elem).attr("href")); }); }); //Doc relative tests module("document relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#doc-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#doc-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#doc-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#doc-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#doc-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#doc-rel-test-six", "doc rel test six"); }); // Site relative tests // NOTE does not test root path or non nested references module("site relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#site-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#site-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#site-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#site-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#site-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#site-rel-test-six", "doc rel test six"); }); // Protocol relative tests // NOTE does not test root path or non nested references module("protocol relative paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#protocol-rel-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#protocol-rel-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#protocol-rel-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#protocol-rel-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#protocol-rel-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#protocol-rel-test-six", "doc rel test six"); }); // absolute tests // NOTE does not test root path or non nested references module("abolute paths"); asyncTest( "file reference no nesting", function(){ testPageLoad("#absolute-test-one", "doc rel test one"); }); asyncTest( "file reference with nesting", function(){ testPageLoad("#absolute-test-two", "doc rel test two"); }); asyncTest( "file reference with double nesting", function(){ testPageLoad("#absolute-test-three", "doc rel test three"); }); asyncTest( "dir refrence with nesting", function(){ testPageLoad("#absolute-test-four", "doc rel test four"); }); asyncTest( "file refrence with parent dir", function(){ testPageLoad("#absolute-test-five", "doc rel test five"); }); asyncTest( "dir refrence with parent dir", function(){ testPageLoad("#absolute-test-six", "doc rel test six"); }); })(jQuery);
JavaScript
(function($) { asyncTest( "dialog ui-state should be part of the hash", function(){ $.testHelper.sequence([ function() { // open the test page $.mobile.activePage.find( "a" ).click(); }, function() { // verify that the hash contains the dialogHashKey ok( location.hash.search($.mobile.dialogHashKey) >= 0 ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile navigation base tag unit tests */ (function($){ var baseDir = $.mobile.path.parseUrl($("base").attr("href")).directory, contentDir = $.mobile.path.makePathAbsolute("../content/", baseDir); module('jquery.mobile.navigation.js - base tag', { setup: function(){ if ( location.hash ) { stop(); $(document).one("pagechange", function() { start(); } ); location.hash = ""; } } }); asyncTest( "can navigate between internal and external pages", function(){ $.testHelper.pageSequence([ function(){ // Navigate from default internal page to another internal page. $.testHelper.openPage( "#internal-page-2" ); }, function(){ // Verify that we are on the 2nd internal page. $.testHelper.assertUrlLocation({ push: location.pathname + "#internal-page-2", hash: "internal-page-2", report: "navigate to internal page" }); // Navigate to a page that is in the base directory. Note that the application // document and this new page are *NOT* in the same directory. $("#internal-page-2 .bp1").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-1.html", report: "navigate from internal page to page in base directory" }); // Navigate to another page in the same directory as the current page. $("#base-page-1 .bp2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-2.html", report: "navigate from base directory page to another base directory page" }); // Navigate to another page in a directory that is the sibling of the base. $("#base-page-2 .cp1").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "navigate from base directory page to a page in a different directory hierarchy" }); // Navigate to another page in a directory that is the sibling of the base. $("#content-page-1 .cp2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-2.html", report: "navigate to another page within the same non-base directory hierarchy" }); // Navigate to an internal page. $("#content-page-2 .ip1").click(); }, function(){ // Verify that we are on the expected page. // the hash based nav result (hash:) is dictate by the fact that #internal-page-1 // is the original root page element $.testHelper.assertUrlLocation({ hashOrPush: location.pathname + location.search, report: "navigate from a page in a non-base directory to an internal page" }); // Try calling changePage() directly with a relative path. $.mobile.changePage("base-page-1.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: baseDir + "base-page-1.html", report: "call changePage() with a filename (no path)" }); // Try calling changePage() directly with a relative path. $.mobile.changePage("../content/content-page-1.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "call changePage() with a relative path containing up-level references" }); // Try calling changePage() with an id $.mobile.changePage("content-page-2.html"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-2.html", report: "call changePage() with a relative path should resolve relative to current page" }); // test that an internal page works $("a.ip2").click(); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hash: "internal-page-2", push: location.pathname + "#internal-page-2", report: "call changePage() with a page id" }); // Try calling changePage() with an id $.mobile.changePage("internal-page-1"); }, function(){ // Verify that we are on the expected page. $.testHelper.assertUrlLocation({ hash: "internal-page-2", push: location.pathname + "#internal-page-2", report: "calling changePage() with a page id that is not prefixed with '#' should not change page" }); // Previous load should have failed and left us on internal-page-2. start(); } ]); }); asyncTest( "internal form with no action submits to document URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage( "#internal-no-action-form-page" ); }, function(){ $( "#internal-no-action-form-page form" ).eq( 0 ).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: location.pathname + "?foo=1&bar=2", report: "hash should match document url and not base url" }); start(); } ]); }); asyncTest( "external page form with no action submits to external page URL", function(){ $.testHelper.pageSequence([ function(){ // Go to an external page that has a form. $("#internal-page-1 .cp1").click(); }, function(){ // Make sure we actually navigated to the external page. $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html", report: "should be on content-page-1.html" }); // Now submit the form in the external page. $("#content-page-1 form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: contentDir + "content-page-1.html?foo=1&bar=2", report: "hash should match page url and not document url" }); start(); }]); }); })(jQuery);
JavaScript
/* * mobile navigation unit tests */ (function($){ // TODO move siteDirectory over to the nav path helper var changePageFn = $.mobile.changePage, originalTitle = document.title, originalLinkBinding = $.mobile.linkBindingEnabled, siteDirectory = location.pathname.replace( /[^/]+$/, "" ), home = $.mobile.path.parseUrl(location.pathname).directory, navigateTestRoot = function(){ $.testHelper.openPage( "#" + location.pathname + location.search ); }; module('jquery.mobile.navigation.js', { setup: function(){ $.mobile.changePage = changePageFn; document.title = originalTitle; var pageReset = function( hash ) { hash = hash || ""; stop(); $(document).one( "pagechange", function() { start(); }); location.hash = "#" + hash; }; // force the page reset for hash based tests if ( location.hash && !$.support.pushState ) { pageReset(); } // force the page reset for all pushstate tests if ( $.support.pushState ) { pageReset( home ); } $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; $.Event.prototype.which = undefined; $.mobile.linkBindingEnabled = originalLinkBinding; } }); asyncTest( "window.history.back() from external to internal page", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ ok( $.mobile.activePage[0] === $( "#active-state-page1" )[ 0 ], "successful navigation to internal page." ); //location.hash = siteDirectory + "external.html"; $.mobile.changePage("external.html"); }, function(){ ok( $.mobile.activePage[0] !== $( "#active-state-page1" )[ 0 ], "successful navigation to external page." ); window.history.back(); }, function(){ ok( $.mobile.activePage[0] === $( "#active-state-page1" )[ 0 ], "successful navigation back to internal page." ); start(); } ]); }); asyncTest( "external page is removed from the DOM after pagehide", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external-test is *NOT* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 0 ); start(); } ]); }); asyncTest( "preventDefault on pageremove event can prevent external page from being removed from the DOM", function(){ var preventRemoval = true, removeCallback = function( e ) { if ( preventRemoval ) { e.preventDefault(); } }; $( document ).bind( "pageremove", removeCallback ); $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external-test *IS* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 1 ); // Switch back to the page again! $.mobile.changePage( "external.html" ); }, // page is still present and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); // Now turn off our removal prevention. preventRemoval = false; window.history.back(); }, // external-test is *NOT* cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 0 ); $( document ).unbind( "pageremove", removeCallback ); start(); } ]); }); asyncTest( "external page is cached in the DOM after pagehide", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.changePage( "cached-external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test-cached" ).length, 1 ); window.history.back(); }, // external test page is cached in the dom after transitioning away function(){ same( $( "#external-test-cached" ).length, 1 ); start(); } ]); }); asyncTest( "external page is cached in the DOM after pagehide when option is set globally", function(){ $.testHelper.pageSequence([ navigateTestRoot, function(){ $.mobile.page.prototype.options.domCache = true; $.mobile.changePage( "external.html" ); }, // page is pulled and displayed in the dom function(){ same( $( "#external-test" ).length, 1 ); window.history.back(); }, // external test page is cached in the dom after transitioning away function(){ same( $( "#external-test" ).length, 1 ); $.mobile.page.prototype.options.domCache = false; $( "#external-test" ).remove(); start(); }]); }); asyncTest( "page last scroll distance is remembered while navigating to and from pages", function(){ $.testHelper.pageSequence([ function(){ $( "body" ).height( $( window ).height() + 500 ); $.mobile.changePage( "external.html" ); }, function(){ // wait for the initial scroll to 0 setTimeout( function() { window.scrollTo( 0, 300 ); same( $(window).scrollTop(), 300, "scrollTop is 300 after setting it" ); }, 300); // wait for the scrollstop to fire and for the scroll to be // recorded 100 ms afterward (see changes made to handle hash // scrolling in some browsers) setTimeout( navigateTestRoot, 500 ); }, function(){ history.back(); }, function(){ // Give the silentScroll function some time to kick in. setTimeout(function() { same( $(window).scrollTop(), 300, "scrollTop is 300 after returning to the page" ); $( "body" ).height( "" ); start(); }, 300 ); } ]); }); asyncTest( "forms with data attribute ajax set to false will not call changePage", function(){ var called = false; var newChangePage = function(){ called = true; }; $.testHelper.sequence([ // avoid initial page load triggering changePage early function(){ $.mobile.changePage = newChangePage; $('#non-ajax-form').one('submit', function(event){ ok(true, 'submit callbacks are fired'); event.preventDefault(); }).submit(); }, function(){ ok(!called, "change page should not be called"); start(); }], 1000); }); asyncTest( "forms with data attribute ajax not set or set to anything but false will call changePage", function(){ var called = 0, newChangePage = function(){ called++; }; $.testHelper.sequence([ // avoid initial page load triggering changePage early function(){ $.mobile.changePage = newChangePage; $('#ajax-form, #rand-ajax-form').submit(); }, function(){ ok(called >= 2, "change page should be called at least twice"); start(); }], 300); }); asyncTest( "anchors with no href attribute will do nothing when clicked", function(){ var fired = false; $(window).bind("hashchange.temp", function(){ fired = true; }); $( "<a>test</a>" ).appendTo( $.mobile.firstPage ).click(); setTimeout(function(){ same(fired, false, "hash shouldn't change after click"); $(window).unbind("hashchange.temp"); start(); }, 500); }); test( "urlHistory is working properly", function(){ //urlHistory same( $.type( $.mobile.urlHistory.stack ), "array", "urlHistory.stack is an array" ); //preload the stack $.mobile.urlHistory.stack[0] = { url: "foo", transition: "bar" }; $.mobile.urlHistory.stack[1] = { url: "baz", transition: "shizam" }; $.mobile.urlHistory.stack[2] = { url: "shizoo", transition: "shizaah" }; //active index same( $.mobile.urlHistory.activeIndex , 0, "urlHistory.activeIndex is 0" ); //getActive same( $.type( $.mobile.urlHistory.getActive() ) , "object", "active item is an object" ); same( $.mobile.urlHistory.getActive().url , "foo", "active item has url foo" ); same( $.mobile.urlHistory.getActive().transition , "bar", "active item has transition bar" ); //get prev / next same( $.mobile.urlHistory.getPrev(), undefined, "urlHistory.getPrev() is undefined when active index is 0" ); $.mobile.urlHistory.activeIndex = 1; same( $.mobile.urlHistory.getPrev().url, "foo", "urlHistory.getPrev() has url foo when active index is 1" ); $.mobile.urlHistory.activeIndex = 0; same( $.mobile.urlHistory.getNext().url, "baz", "urlHistory.getNext() has url baz when active index is 0" ); //add new $.mobile.urlHistory.activeIndex = 2; $.mobile.urlHistory.addNew("test"); same( $.mobile.urlHistory.stack.length, 4, "urlHistory.addNew() adds an item after the active index" ); same( $.mobile.urlHistory.activeIndex, 3, "urlHistory.addNew() moves the activeIndex to the newly added item" ); //clearForward $.mobile.urlHistory.activeIndex = 0; $.mobile.urlHistory.clearForward(); same( $.mobile.urlHistory.stack.length, 1, "urlHistory.clearForward() clears the url stack after the active index" ); }); //url listening function testListening( prop ){ var stillListening = false; $(document).bind("pagebeforehide", function(){ stillListening = true; }); location.hash = "foozball"; setTimeout(function(){ ok( prop == stillListening, prop + " = false disables default hashchange event handler"); location.hash = ""; prop = true; start(); }, 1000); } asyncTest( "ability to disable our hash change event listening internally", function(){ testListening( ! $.mobile.urlHistory.ignoreNextHashChange ); }); asyncTest( "ability to disable our hash change event listening globally", function(){ testListening( $.mobile.hashListeningEnabled ); }); var testDataUrlHash = function( linkSelector, matches ) { $.testHelper.pageSequence([ function(){ window.location.hash = ""; }, function(){ $(linkSelector).click(); }, function(){ $.testHelper.assertUrlLocation( $.extend(matches, { report: "url or hash should match" }) ); start(); } ]); stop(); }; test( "when loading a page where data-url is not defined on a sub element hash defaults to the url", function(){ testDataUrlHash( "#non-data-url a", {hashOrPush: siteDirectory + "data-url-tests/non-data-url.html"} ); }); test( "data url works for nested paths", function(){ var url = "foo/bar.html"; testDataUrlHash( "#nested-data-url a", {hash: url, push: home + url} ); }); test( "data url works for single quoted paths and roles", function(){ var url = "foo/bar/single.html"; testDataUrlHash( "#single-quotes-data-url a", {hash: url, push: home + url} ); }); test( "data url works when role and url are reversed on the page element", function(){ var url = "foo/bar/reverse.html"; testDataUrlHash( "#reverse-attr-data-url a", {hash: url, push: home + url} ); }); asyncTest( "last entry choosen amongst multiple identical url history stack entries on hash change", function(){ // make sure the stack is clear after initial page load an any other delayed page loads // TODO better browser state management $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#dup-history-first"); }, function(){ $("#dup-history-first a").click(); }, function(){ $("#dup-history-second a:first").click(); }, function(){ $("#dup-history-first a").click(); }, function(){ $("#dup-history-second a:last").click(); }, function(){ $("#dup-history-dialog a:contains('Close')").click(); }, function(){ // fourth page (third index) in the stack to account for first page being hash manipulation, // the third page is dup-history-second which has two entries in history // the test is to make sure the index isn't 1 in this case, or the first entry for dup-history-second same($.mobile.urlHistory.activeIndex, 3, "should be the fourth page in the stack"); start(); }]); }); asyncTest( "going back from a page entered from a dialog skips the dialog and goes to the previous page", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#skip-dialog-first"); }, // transition to the dialog function(){ $("#skip-dialog-first a").click(); }, // transition to the second page function(){ $("#skip-dialog a").click(); }, // transition past the dialog via data-rel=back link on the second page function(){ $("#skip-dialog-second a").click(); }, // make sure we're at the first page and not the dialog function(){ $.testHelper.assertUrlLocation({ hash: "skip-dialog-first", push: home + "#skip-dialog-first", report: "should be the first page in the sequence" }); start(); }]); }); asyncTest( "going forward from a page entered from a dialog skips the dialog and goes to the next page", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#skip-dialog-first"); }, // transition to the dialog function(){ $("#skip-dialog-first a").click(); }, // transition to the second page function(){ $("#skip-dialog a").click(); }, // transition to back past the dialog function(){ window.history.back(); }, // transition to the second page past the dialog through history function(){ window.history.forward(); }, // make sure we're on the second page and not the dialog function(){ $.testHelper.assertUrlLocation({ hash: "skip-dialog-second", push: home + "#skip-dialog-second", report: "should be the second page after the dialog" }); start(); }]); }); asyncTest( "going back from a dialog triggered from a dialog should result in the first dialog ", function(){ $.testHelper.pageSequence([ // setup function(){ $.testHelper.openPage("#nested-dialog-page"); }, // transition to the dialog function(){ $("#nested-dialog-page a").click(); }, // transition to the second dialog function(){ $("#nested-dialog-first a").click(); }, // transition to back to the first dialog function(){ window.history.back(); }, // make sure we're on first dialog function(){ same($(".ui-page-active")[0], $("#nested-dialog-first")[0], "should be the first dialog"); start(); }]); }); asyncTest( "loading a relative file path after an embeded page works", function(){ $.testHelper.pageSequence([ // transition second page function(){ $.testHelper.openPage("#relative-after-embeded-page-first"); }, // transition second page function(){ $("#relative-after-embeded-page-first a").click(); }, // transition to the relative ajax loaded page function(){ $("#relative-after-embeded-page-second a").click(); }, // make sure the page was loaded properly via ajax function(){ // data attribute intentionally left without namespace same($(".ui-page-active").data("other"), "for testing", "should be relative ajax loaded page"); start(); }]); }); asyncTest( "Page title updates properly when clicking back to previous page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#relative-after-embeded-page-first"); }, function(){ window.history.back(); }, function(){ same(document.title, "jQuery Mobile Navigation Test Suite"); start(); } ]); }); asyncTest( "Page title updates properly when clicking a link back to first page", function(){ var title = document.title; $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest1").click(); }, function(){ same(document.title, "Title Tag"); $.mobile.activePage.find("#title-check-link").click(); }, function(){ same(document.title, title); start(); } ]); }); asyncTest( "Page title updates properly from title tag when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest1").click(); }, function(){ same(document.title, "Title Tag"); start(); } ]); }); asyncTest( "Page title updates properly from data-title attr when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest2").click(); }, function(){ same(document.title, "Title Attr"); start(); } ]); }); asyncTest( "Page title updates properly from heading text in header when loading an external page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#ajax-title-page"); }, function(){ $("#titletest3").click(); }, function(){ same(document.title, "Title Heading"); start(); } ]); }); asyncTest( "Page links to the current active page result in the same active page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#self-link"); }, function(){ $("a[href='#self-link']").click(); }, function(){ same($.mobile.activePage[0], $("#self-link")[0], "self-link page is still the active page" ); start(); } ]); }); asyncTest( "links on subdirectory pages with query params append the params and load the page", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#data-url-tests/non-data-url.html"); }, function(){ $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url has query params" }); ok($(".ui-page-active").jqmData("url").indexOf("?foo=bar") > -1, "the query params are in the data url"); start(); } ]); }); asyncTest( "identical query param link doesn't add additional set of query params", function(){ $.testHelper.pageSequence([ function(){ $.testHelper.openPage("#data-url-tests/non-data-url.html"); }, function(){ $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url has query params" }); $("#query-param-anchor").click(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "data-url-tests/non-data-url.html?foo=bar", report: "the hash or url still has query params" }); start(); } ]); }); // Special handling inside navigation because query params must be applied to the hash // or absolute reference and dialogs apply extra information int the hash that must be removed asyncTest( "query param link from a dialog to itself should be a not add another dialog", function(){ var firstDialogLoc; $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#dialog-param-link"); }, // navigate to the subdirectory page with the query link function(){ $("#dialog-param-link a").click(); }, // navigate to the query param self reference link function(){ $("#dialog-param-link-page a").click(); }, // attempt to navigate to the same link function(){ // store the current hash for comparison (with one dialog hash key) firstDialogLoc = location.hash || location.href; $("#dialog-param-link-page a").click(); }, function(){ same(location.hash || location.href, firstDialogLoc, "additional dialog hash key not added"); start(); } ]); }); asyncTest( "query data passed as string to changePage is appended to URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.mobile.changePage( "form-tests/changepage-data.html", { data: "foo=1&bar=2" } ); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/changepage-data.html?foo=1&bar=2", report: "the hash or url still has query params" }); start(); } ]); }); asyncTest( "query data passed as object to changePage is appended to URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.mobile.changePage( "form-tests/changepage-data.html", { data: { foo: 3, bar: 4 } } ); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/changepage-data.html?foo=3&bar=4", report: "the hash or url still has query params" }); start(); } ]); }); asyncTest( "refresh of a dialog url should not duplicate page", function(){ $.testHelper.pageSequence([ // open our test page function(){ same($(".foo-class").length, 1, "should only have one instance of foo-class in the document"); location.hash = "#foo&ui-state=dialog"; }, function(){ $.testHelper.assertUrlLocation({ hash: "foo&ui-state=dialog", push: home + "#foo&ui-state=dialog", report: "hash should match what was loaded" }); same( $(".foo-class").length, 1, "should only have one instance of foo-class in the document" ); start(); } ]); }); asyncTest( "internal form with no action submits to document URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#internal-no-action-form-page"); }, function(){ $("#internal-no-action-form-page form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "?foo=1&bar=2", report: "hash should match what was loaded" }); start(); } ]); }); asyncTest( "external page containing form with no action submits to page URL", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#internal-no-action-form-page"); }, function(){ $("#internal-no-action-form-page a").eq(0).click(); }, function(){ $("#external-form-no-action-page form").eq(0).submit(); }, function(){ $.testHelper.assertUrlLocation({ hashOrPush: home + "form-tests/form-no-action.html?foo=1&bar=2", report: "hash should match page url and not document url" }); start(); } ]); }); asyncTest( "handling of active button state when navigating", 1, function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ $("#active-state-page2 a").eq(0).click(); }, function(){ ok(!$("#active-state-page1 a").hasClass( $.mobile.activeBtnClass ), "No button should not have class " + $.mobile.activeBtnClass ); start(); } ]); }); // issue 2444 https://github.com/jquery/jquery-mobile/issues/2444 // results from preventing spurious hash changes asyncTest( "dialog should return to its parent page when open and closed multiple times", function() { $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#default-trans-dialog"); }, function(){ $.mobile.activePage.find( "a" ).click(); }, function(){ window.history.back(); }, function(){ same( $.mobile.activePage[0], $( "#default-trans-dialog" )[0] ); $.mobile.activePage.find( "a" ).click(); }, function(){ window.history.back(); }, function(){ same( $.mobile.activePage[0], $( "#default-trans-dialog" )[0] ); start(); } ]); }); asyncTest( "clicks with middle mouse button are ignored", function() { $.testHelper.pageSequence([ function() { $.testHelper.openPage( "#odd-clicks-page" ); }, function() { $( "#right-or-middle-click" ).click(); }, // make sure the page is opening first without the mocked button click value // only necessary to prevent issues with test specific fixtures function() { same($.mobile.activePage[0], $("#odd-clicks-page-dest")[0]); $.testHelper.openPage( "#odd-clicks-page" ); // mock the which value to simulate a middle click $.Event.prototype.which = 2; }, function() { $( "#right-or-middle-click" ).click(); }, function( timeout ) { ok( timeout, "page event handler timed out due to ignored click" ); ok($.mobile.activePage[0] !== $("#odd-clicks-page-dest")[0], "pages are not the same"); start(); } ]); }); asyncTest( "disabling link binding disables navigation via links and highlighting", function() { $.mobile.linkBindingEnabled = false; $.testHelper.pageSequence([ function() { $.testHelper.openPage("#bar"); }, function() { $.mobile.activePage.find( "a" ).click(); }, function( timeout ) { ok( !$.mobile.activePage.find( "a" ).hasClass( $.mobile.activeBtnClass ), "vlick handler doesn't add the activebtn class" ); ok( timeout, "no page change was fired" ); start(); } ]); }); asyncTest( "handling of button active state when navigating by clicking back button", 1, function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#active-state-page1"); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ $("#active-state-page2 a").eq(1).click(); }, function(){ $("#active-state-page1 a").eq(0).click(); }, function(){ ok(!$("#active-state-page2 a").hasClass( $.mobile.activeBtnClass ), "No button should not have class " + $.mobile.activeBtnClass ); start(); } ]); }); asyncTest( "can navigate to dynamically injected page with dynamically injected link", function(){ $.testHelper.pageSequence([ // open our test page function(){ $.testHelper.openPage("#inject-links-page"); }, function(){ var $ilpage = $( "#inject-links-page" ), $link = $( "<a href='#injected-test-page'>injected-test-page link</a>" ); // Make sure we actually navigated to the expected page. ok( $.mobile.activePage[ 0 ] == $ilpage[ 0 ], "navigated successfully to #inject-links-page" ); // Now dynamically insert a page. $ilpage.parent().append( "<div data-role='page' id='injected-test-page'>testing...</div>" ); // Now inject a link to this page dynamically and attempt to navigate // to the page we just inserted. $link.appendTo( $ilpage ).click(); }, function(){ // Make sure we actually navigated to the expected page. ok( $.mobile.activePage[ 0 ] == $( "#injected-test-page" )[ 0 ], "navigated successfully to #injected-test-page" ); start(); } ]); }); asyncTest( "application url with dialogHashKey loads application's first page", function(){ $.testHelper.pageSequence([ // open our test page function(){ // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "navigated successfully to #foo" ); // Now navigate to an hash that contains just a dialogHashKey. $.mobile.changePage("#" + $.mobile.dialogHashKey); }, function(){ // Make sure we actually navigated to the first page. ok( $.mobile.activePage[ 0 ] === $.mobile.firstPage[ 0 ], "navigated successfully to first-page" ); // Now make sure opening the page didn't result in page duplication. ok( $.mobile.firstPage.hasClass( "first-page" ), "first page has expected class" ); same( $( ".first-page" ).length, 1, "first page was not duplicated" ); start(); } ]); }); asyncTest( "navigate to non-existent internal page throws pagechangefailed", function(){ var pagechangefailed = false, pageChangeFailedCB = function( e ) { pagechangefailed = true; } $( document ).bind( "pagechangefailed", pageChangeFailedCB ); $.testHelper.pageSequence([ // open our test page function(){ // Make sure there's only one copy of the first-page in the DOM to begin with. ok( $.mobile.firstPage.hasClass( "first-page" ), "first page has expected class" ); same( $( ".first-page" ).length, 1, "first page was not duplicated" ); // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ var $foo = $( "#foo" ); ok( $.mobile.activePage[ 0 ] === $foo[ 0 ], "navigated successfully to #foo" ); same( pagechangefailed, false, "no page change failures" ); // Now navigate to a non-existent page. $foo.find( "#bad-internal-page-link" ).click(); }, function(){ // Make sure a pagechangefailed event was triggered. same( pagechangefailed, true, "pagechangefailed dispatched" ); // Make sure we didn't navigate away from #foo. ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "did not navigate away from #foo" ); // Now make sure opening the page didn't result in page duplication. same( $( ".first-page" ).length, 1, "first page was not duplicated" ); $( document ).unbind( "pagechangefailed", pageChangeFailedCB ); start(); } ]); }); asyncTest( "prefetched links with data rel dialog result in a dialog", function() { $.testHelper.pageSequence([ // open our test page function(){ // Navigate to any page except the first page of the application. $.testHelper.openPage("#prefetched-dialog-page"); }, function() { $("#prefetched-dialog-link").click(); }, function() { ok( $.mobile.activePage.is(".ui-dialog"), "prefetched page is rendered as a dialog" ); start(); } ]); }); asyncTest( "first page gets reloaded if pruned from the DOM", function(){ var hideCallbackTriggered = false; function hideCallback( e, data ) { var page = e.target; ok( ( page === $.mobile.firstPage[ 0 ] ), "hide called with prevPage set to firstPage"); if ( page === $.mobile.firstPage[ 0 ] ) { $( page ).remove(); } hideCallbackTriggered = true; } $(document).bind('pagehide', hideCallback); $.testHelper.pageSequence([ function(){ // Make sure the first page is actually in the DOM. ok( $.mobile.firstPage.parent().length !== 0, "first page is currently in the DOM" ); // Make sure the first page is the active page. ok( $.mobile.activePage[ 0 ] === $.mobile.firstPage[ 0 ], "first page is the active page" ); // Now make sure the first page has an id that we can use to reload it. ok( $.mobile.firstPage[ 0 ].id, "first page has an id" ); // Make sure there is only one first page in the DOM. same( $( ".first-page" ).length, 1, "only one instance of the first page in the DOM" ); // Navigate to any page except the first page of the application. $.testHelper.openPage("#foo"); }, function(){ // Make sure the active page is #foo. ok( $.mobile.activePage[ 0 ] === $( "#foo" )[ 0 ], "navigated successfully to #foo" ); // Make sure our hide callback was triggered. ok( hideCallbackTriggered, "hide callback was triggered" ); // Make sure the first page was actually pruned from the document. ok( $.mobile.firstPage.parent().length === 0, "first page was pruned from the DOM" ); same( $( ".first-page" ).length, 0, "no instance of the first page in the DOM" ); // Remove our hideCallback. $(document).unbind('pagehide', hideCallback); // Navigate back to the first page! $.testHelper.openPage( "#" + $.mobile.firstPage[0].id ); }, function(){ var firstPage = $( ".first-page" ); // We should only have one first page in the document at any time! same( firstPage.length, 1, "single instance of first page recreated in the DOM" ); // Make sure the first page in the DOM is actually a different DOM element than the original // one we started with. ok( $.mobile.firstPage[ 0 ] !== firstPage[ 0 ], "first page is a new DOM element"); // Make sure we actually navigated to the new first page. ok( $.mobile.activePage[ 0 ] === firstPage[ 0 ], "navigated successfully to new first-page"); // Reset the $.mobile.firstPage for subsequent tests. // XXX: Should we just get rid of the new one and restore the old? $.mobile.firstPage = $.mobile.activePage; start(); } ]); }); })(jQuery);
JavaScript
/* * mobile navigation unit tests */ (function($){ var perspective = "viewport-flip", transitioning = "ui-mobile-viewport-transitioning", animationCompleteFn = $.fn.animationComplete, //TODO centralize class names? transitionTypes = "in out fade slide flip reverse pop", isTransitioning = function(page){ return $.grep(transitionTypes.split(" "), function(className, i){ return page.hasClass(className); }).length > 0; }, isTransitioningIn = function(page){ return page.hasClass("in") && isTransitioning(page); }, //animationComplete callback queue callbackQueue = [], finishPageTransition = function(){ callbackQueue.pop()(); }, clearPageTransitionStack = function(){ stop(); var checkTransitionStack = function(){ if(callbackQueue.length>0) { setTimeout(function(){ finishPageTransition(); checkTransitionStack(); },0); } else { start(); } }; checkTransitionStack(); }, //wipe all urls clearUrlHistory = function(){ $.mobile.urlHistory.stack = []; $.mobile.urlHistory.activeIndex = 0; }; module('jquery.mobile.navigation.js', { setup: function(){ //stub to prevent class removal $.fn.animationComplete = function(callback){ callbackQueue.unshift(callback); }; clearPageTransitionStack(); clearUrlHistory(); }, teardown: function(){ // unmock animation complete $.fn.animationComplete = animationCompleteFn; } }); test( "changePage applys perspective class to mobile viewport for flip", function(){ $("#foo > a").click(); ok($("body").hasClass(perspective), "has perspective class"); }); test( "changePage does not apply perspective class to mobile viewport for transitions other than flip", function(){ $("#bar > a").click(); ok(!$("body").hasClass(perspective), "doesn't have perspective class"); }); test( "changePage applys transition class to mobile viewport for default transition", function(){ $("#baz > a").click(); ok($("body").hasClass(transitioning), "has transitioning class"); }); test( "explicit transition preferred for page navigation reversal (ie back)", function(){ $("#fade-trans > a").click(); stop(); setTimeout(function(){ finishPageTransition(); $("#flip-trans > a").click(); setTimeout(function(){ finishPageTransition(); $("#fade-trans > a").click(); setTimeout(function(){ ok($("#flip-trans").hasClass("fade"), "has fade class"); start(); },0); },0); },0); }); test( "default transition is slide", function(){ $("#default-trans > a").click(); stop(); setTimeout(function(){ ok($("#no-trans").hasClass("slide"), "has slide class"); start(); },0); }); test( "changePage queues requests", function(){ var firstPage = $("#foo"), secondPage = $("#bar"); $.mobile.changePage(firstPage); $.mobile.changePage(secondPage); stop(); setTimeout(function(){ ok(isTransitioningIn(firstPage), "first page begins transition"); ok(!isTransitioningIn(secondPage), "second page doesn't transition yet"); finishPageTransition(); setTimeout(function(){ ok(!isTransitioningIn(firstPage), "first page transition should be complete"); ok(isTransitioningIn(secondPage), "second page should begin transitioning"); start(); },0); },0); }); test( "default transition is pop for a dialog", function(){ expect( 1 ); stop(); setTimeout(function(){ $("#default-trans-dialog > a").click(); ok($("#no-trans-dialog").hasClass("pop"), "expected the pop class to be present but instead was " + $("#no-trans-dialog").attr('class')); start(); }, 900); }); test( "animationComplete return value", function(){ $.fn.animationComplete = animationCompleteFn; equals($("#foo").animationComplete(function(){})[0], $("#foo")[0]); }); })(jQuery);
JavaScript
/* * mobile widget unit tests */ (function($){ module('jquery.mobile.widget.js'); test( "getting data from creation options", function(){ var expected = "bizzle"; $.mobile.widget.prototype.options = { "fooBar" : true }; $.mobile.widget.prototype.element = $("<div data-foo-bar=" + expected + ">"); same($.mobile.widget.prototype._getCreateOptions()["fooBar"], expected); }); test( "getting no data when the options are empty", function(){ var expected = {}; $.mobile.widget.prototype.options = {}; $.mobile.widget.prototype.element = $("<div data-foo-bar=" + expected + ">"); same($.mobile.widget.prototype._getCreateOptions(), expected); }); test( "getting no data when the element has none", function(){ var expected = {}; $.mobile.widget.prototype.options = { "fooBar" : true }; $.mobile.widget.prototype.element = $("<div>"); same($.mobile.widget.prototype._getCreateOptions(), expected); }); test( "elements embedded in sub page elements are excluded on create when they match the keep native selector", function() { // uses default keep native of data-role=none $("#enhance-prevented") .append('<label for="unenhanced">Text Input:</label><input type="text" name="name" id="unenhanced" value="" data-role="none" />') .trigger("create"); ok( !$("#unenhanced").hasClass( "ui-input-text" ), "doesn't have the ui input text class (unenhanced)"); }); test( "elements embedded in sub page elements are included on create when they don't match the keep native selector", function() { // uses default keep native of data-role=none $("#enhance-allowed") .append('<label for="enhanced">Text Input:</label><input type="text" name="name" id="enhanced" value=""/>') .trigger("create"); ok( $("#enhanced").hasClass( "ui-input-text" ), "has the ui input text class (unenhanced)"); }); })(jQuery);
JavaScript
/* * mobile widget unit tests */ (function($){ var widgetInitialized = false; module( 'jquery.mobile.widget.js' ); $( "#foo" ).live( 'pageinit', function(){ // ordering sensitive here, the value has to be set after the call // so that if the widget factory says that its not yet initialized, // which is an exception, the value won't be set $( "#foo-slider" ).slider( 'refresh' ); widgetInitialized = true; }); test( "page is enhanced before init is fired", function() { ok( widgetInitialized ); }); })( jQuery );
JavaScript
/* * mobile checkboxradio unit tests */ (function($){ module( 'jquery.mobile.forms.checkboxradio.js' ); test( "widget can be disabled and enabled", function(){ var input = $( "#checkbox-1" ), button = input.parent().find( ".ui-btn" ); input.checkboxradio( "disable" ); input.checkboxradio( "enable" ); ok( !input.attr( "disabled" ), "start input as enabled" ); ok( !input.parent().hasClass( "ui-disabled" ), "no disabled styles" ); ok( !input.attr( "checked" ), "not checked before click" ); button.trigger( "click" ); ok( input.attr( "checked" ), "checked after click" ); ok( button.hasClass( "ui-checkbox-on" ), "active styles after click" ); button.trigger( "click" ); input.checkboxradio( "disable" ); ok( input.attr( "disabled" ), "input disabled" ); ok( input.parent().hasClass( "ui-disabled" ), "disabled styles" ); ok( !input.attr( "checked" ), "not checked before click" ); button.trigger( "click" ); ok( !input.attr( "checked" ), "not checked after click" ); ok( !button.hasClass( "ui-checkbox-on" ), "no active styles after click" ); }); test( "clicking a checkbox within a controlgroup does not affect checkboxes with the same name in the same controlgroup", function(){ var input1 = $("#checkbox-31"); var button1 = input1.parent().find(".ui-btn"); var input2 = $("#checkbox-32"); var button2 = input2.parent().find(".ui-btn"); ok(!input1.attr("checked"), "input1 not checked before click"); ok(!input2.attr("checked"), "input2 not checked before click"); button1.trigger("click"); ok(input1.attr("checked"), "input1 checked after click on input1"); ok(!input2.attr("checked"), "input2 not checked after click on input1"); button2.trigger("click"); ok(input1.attr("checked"), "input1 not changed after click on input2"); ok(input2.attr("checked"), "input2 checked after click on input2"); }); asyncTest( "change events fired on checkbox for both check and uncheck", function(){ var $checkbox = $( "#checkbox-2" ), $checkboxLabel = $checkbox.parent().find( ".ui-btn" ); $checkbox.unbind( "change" ); expect( 1 ); $checkbox.one('change', function(){ ok( true, "change fired on click to check the box" ); }); $checkboxLabel.trigger( "click" ); //test above will be triggered twice, and the start here once $checkbox.one('change', function(){ start(); }); $checkboxLabel.trigger( "click" ); }); asyncTest( "radio button labels should update the active button class to last clicked and clear checked", function(){ var $radioBtns = $( '#radio-active-btn-test input' ), singleActiveAndChecked = function(){ same( $( "#radio-active-btn-test .ui-radio-on" ).length, 1, "there should be only one active button" ); same( $( "#radio-active-btn-test :checked" ).length, 1, "there should be only one checked" ); }; $.testHelper.sequence([ function(){ $radioBtns.last().siblings( 'label' ).click(); }, function(){ ok( $radioBtns.last().prop( 'checked' ) ); ok( $radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ), "last input label is an active button" ); ok( !$radioBtns.first().prop( 'checked' ) ); ok( !$radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ), "first input label is not active" ); singleActiveAndChecked(); $radioBtns.first().siblings( 'label' ).click(); }, function(){ ok( $radioBtns.first().prop( 'checked' )); ok( $radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ), "first input label is an active button" ); ok( !$radioBtns.last().prop( 'checked' )); ok( !$radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ), "last input label is not active" ); singleActiveAndChecked(); start(); } ], 500); }); test( "checkboxradio controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-checkbox").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-checkbox").length, "enhancements applied" ); }); $.mobile.page.prototype.options.keepNative = "input.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "checkboxradio elements in the keepNative set shouldn't be enhanced", function() { ok( !$("input.should-be-native").parent().is("div.ui-checkbox") ); }); asyncTest( "clicking the label triggers a click on the element", function() { var clicked = false; expect( 1 ); $( "#checkbox-click-triggered" ).one('click', function() { clicked = true; }); $.testHelper.sequence([ function() { $( "[for='checkbox-click-triggered']" ).click(); }, function() { ok(clicked, "click was fired on input"); start(); } ], 2000); }); })(jQuery);
JavaScript
/* * mobile slider unit tests */ (function($){ $.mobile.page.prototype.options.keepNative = "input.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "slider elements in the keepNative set shouldn't be enhanced", function() { same( $("input.should-be-native").siblings("div.ui-slider").length, 0 ); }); })( jQuery );
JavaScript
/* * mobile slider unit tests */ (function($){ var onChangeCnt = 0; window.onChangeCounter = function() { onChangeCnt++; } module('jquery.mobile.slider.js'); var keypressTest = function(opts){ var slider = $(opts.selector), val = window.parseFloat(slider.val()), handle = slider.siblings('.ui-slider').find('.ui-slider-handle'); expect( opts.keyCodes.length ); $.each(opts.keyCodes, function(i, elem){ // stub the keycode value and trigger the keypress $.Event.prototype.keyCode = $.mobile.keyCode[elem]; handle.trigger('keydown'); val += opts.increment; same(val, window.parseFloat(slider.val(), 10), "new value is " + opts.increment + " different"); }); }; test( "slider should move right with up, right, and page up keypress", function(){ keypressTest({ selector: '#range-slider-up', keyCodes: ['UP', 'RIGHT', 'PAGE_UP'], increment: 1 }); }); test( "slider should move left with down, left, and page down keypress", function(){ keypressTest({ selector: '#range-slider-down', keyCodes: ['DOWN', 'LEFT', 'PAGE_DOWN'], increment: -1 }); }); test( "slider should move to range minimum on end keypress", function(){ var selector = "#range-slider-end", initialVal = window.parseFloat($(selector).val(), 10), max = window.parseFloat($(selector).attr('max'), 10); keypressTest({ selector: selector, keyCodes: ['END'], increment: max - initialVal }); }); test( "slider should move to range minimum on end keypress", function(){ var selector = "#range-slider-home", initialVal = window.parseFloat($(selector).val(), 10); keypressTest({ selector: selector, keyCodes: ['HOME'], increment: 0 - initialVal }); }); test( "slider should move positive by steps on keypress", function(){ keypressTest({ selector: "#stepped", keyCodes: ['RIGHT'], increment: 10 }); }); test( "slider should move negative by steps on keypress", function(){ keypressTest({ selector: "#stepped", keyCodes: ['LEFT'], increment: -10 }); }); test( "slider should validate input value on blur", function(){ var slider = $("#range-slider-up"); slider.focus(); slider.val(200); same(slider.val(), "200"); slider.blur(); same(slider.val(), slider.attr('max')); }); test( "slider should not validate input on keyup", function(){ var slider = $("#range-slider-up"); slider.focus(); slider.val(200); same(slider.val(), "200"); slider.keyup(); same(slider.val(), "200"); }); test( "input type should degrade to number when slider is created", function(){ same($("#range-slider-up").attr( "type" ), "number"); }); // generic switch test function var sliderSwitchTest = function(opts){ var slider = $("#slider-switch"), handle = slider.siblings('.ui-slider').find('a'), switchValues = { 'off' : 0, 'on' : 1 }; // One for the select and one for the aria-valuenow expect( opts.keyCodes.length * 2 ); $.each(opts.keyCodes, function(i, elem){ // reset the values slider[0].selectedIndex = switchValues[opts.start]; handle.attr({'aria-valuenow' : opts.start }); // stub the keycode and trigger the event $.Event.prototype.keyCode = $.mobile.keyCode[elem]; handle.trigger('keydown'); same(handle.attr('aria-valuenow'), opts.finish, "handle value is " + opts.finish); same(slider[0].selectedIndex, switchValues[opts.finish], "select input has correct index"); }); }; test( "switch should select on with up, right, page up and end", function(){ sliderSwitchTest({ start: 'off', finish: 'on', keyCodes: ['UP', 'RIGHT', 'PAGE_UP', 'END'] }); }); test( "switch should select off with down, left, page down and home", function(){ sliderSwitchTest({ start: 'on', finish: 'off', keyCodes: ['DOWN', 'LEFT', 'PAGE_DOWN', 'HOME'] }); }); test( "onchange should not be called on create", function(){ equals(onChangeCnt, 0, "onChange should not have been called"); }); test( "onchange should be called onchange", function(){ onChangeCnt = 0; $( "#onchange" ).slider( "refresh", 50 ); equals(onChangeCnt, 1, "onChange should have been called once"); }); test( "slider controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-slider").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-slider").length, "enhancements applied" ); }); var createEvent = function( name, target, x, y ) { var event = $.Event( name ); event.target = target; event.pageX = x; event.pageY = y; return event; }; test( "toggle switch should fire one change event when clicked", function(){ var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, changeCount = 0, changeFunc = function( e ) { ok( control[0].selectedIndex !== currentValue, "change event should only be triggered if the value changes"); ++changeCount; }, event = null, offset = handle.offset(), currentValue = control[0].selectedIndex; control.bind( "change", changeFunc ); // The toggle switch actually updates on mousedown and mouseup events, so we go through // the motions of generating all the events that happen during a click to make sure that // during all of those events, the value only changes once. slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "click", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); control.unbind( "change", changeFunc ); ok( control[0].selectedIndex !== currentValue, "value did change"); same( changeCount, 1, "change event should be fired once during a click" ); }); var assertLeftCSS = function( obj, opts ) { var integerLeft, compare, css, threshold; css = obj.css('left'); threshold = opts.pxThreshold || 0; if( css.indexOf( "px" ) > -1 ) { // parse the actual pixel value returned by the left css value // and the pixels passed in for comparison integerLeft = Math.round( parseFloat( css.replace("px", "") ) ), compare = parseInt( opts.pixels.replace( "px", "" ), 10 ); // check that the pixel value provided is within a given threshold; default is 0px ok( compare >= integerLeft - threshold && compare <= integerLeft + threshold, opts.message ); } else { equal( css, opts.percent, opts.message ); } }; asyncTest( "toggle switch handle should snap in the old position if dragged less than half of the slider width, in the new position if dragged more than half of the slider width", function() { var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, width = handle.width(), offset = null; $.testHelper.sequence([ function() { // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging less than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + width - 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left + width - 20, offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left + width - 20, offset.top + 10 ) ); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle ends on the right side' }); // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging more than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); }, function() { assertLeftCSS(handle, { percent: '0%', pixels: '0px', message: 'handle ends on the left side' }); start(); } ], 500); }); asyncTest( "toggle switch handle should not move if user is dragging and value is changed", function() { var control = $( "#slider-switch" ), widget = control.data( "slider" ), slider = widget.slider, handle = widget.handle, width = handle.width(), offset = null; $.testHelper.sequence([ function() { // initialize the switch control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css('width'), message: 'handle starts on the right side' }); // simulate dragging more than a half offset = handle.offset(); slider.trigger( createEvent( "mousedown", handle[ 0 ], offset.left + 10, offset.top + 10 ) ); slider.trigger( createEvent( "mousemove", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); }, function() { var min, max; if( handle.css('left').indexOf("%") > -1 ){ min = "0%"; max = "100%"; } else { min = "0px"; max = handle.parent().css( 'width' ); } notEqual(handle.css('left'), min, 'handle is not on the left side'); notEqual(handle.css('left'), max, 'handle is not on the right side'); // reset slider state so it is ready for other tests slider.trigger( createEvent( "mouseup", handle[ 0 ], offset.left - ( width / 2 ), offset.top + 10 ) ); start(); } ], 500); }); asyncTest( "toggle switch should refresh when disabled", function() { var control = $( "#slider-switch" ), handle = control.data( "slider" ).handle; $.testHelper.sequence([ function() { // set the initial value control.val('off').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '0%', pixels: '0px', message: 'handle starts on the left side' }); // disable and change value control.slider('disable'); control.val('on').slider('refresh'); }, function() { assertLeftCSS(handle, { percent: '100%', pixels: handle.parent().css( 'width' ), message: 'handle ends on the right side' }); // reset slider state so it is ready for other tests control.slider('enable'); start(); } ], 500); }); })(jQuery);
JavaScript
/* * degradeInputs unit tests */ (function($){ module('jquery.mobile.slider.js'); test('keepNative elements should not be degraded', function() { same($('input#not-to-be-degraded').attr("type"), "range"); }); test('should degrade input type to a different type, as specified in page options', function(){ var degradeInputs = $.mobile.page.prototype.options.degradeInputs; expect( degradeInputs.length ); $.each(degradeInputs, function( oldType, newType ) { if (newType === false) { newType = oldType; } $('#test-container').html('<input type="' + oldType + '" />').trigger("create"); same($('#test-container input').attr("type"), newType); }); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var resetHash; resetHash = function(timeout){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); }; // https://github.com/jquery/jquery-mobile/issues/2181 asyncTest( "dialog sized select should alter the value of its parent select", function(){ var selectButton, value; $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached.html" ); }, function(){ selectButton = $( "#cached-page-select" ).siblings( 'a' ); selectButton.click(); }, function(){ ok( $.mobile.activePage.hasClass('ui-dialog'), "the dialog came up" ); var option = $.mobile.activePage.find( "li a" ).not(":contains('" + selectButton.text() + "')").last(); value = option.text(); option.click(); }, function(){ same( value, selectButton.text(), "the selected value is propogated back to the button text" ); start(); } ]); }); // https://github.com/jquery/jquery-mobile/issues/2181 asyncTest( "dialog sized select should prevent the removal of its parent page from the dom", function(){ var selectButton, parentPageId; expect( 2 ); $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached.html" ); }, function(){ selectButton = $.mobile.activePage.find( "#cached-page-select" ).siblings( 'a' ); parentPageId = $.mobile.activePage.attr( 'id' ); same( $("#" + parentPageId).length, 1, "establish the parent page exists" ); selectButton.click(); }, function(){ same( $( "#" + parentPageId).length, 1, "make sure parent page is still there after opening the dialog" ); $.mobile.activePage.find( "li a" ).last().click(); }, start ]); }); asyncTest( "dialog sized select shouldn't rebind its parent page remove handler when closing, if the parent page domCache option is true", function(){ expect( 3 ); $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "cached-dom-cache-true.html" ); }, function(){ $.mobile.activePage.find( "#domcache-page-select" ).siblings( 'a' ).click(); }, function(){ ok( $.mobile.activePage.hasClass('ui-dialog'), "the dialog came up" ); $.mobile.activePage.find( "li a" ).last().click(); }, function(){ ok( $.mobile.activePage.is( "#dialog-select-parent-domcache-test" ), "the dialog closed" ); $.mobile.changePage( $( "#default" ) ); }, function(){ same( $("#dialog-select-parent-domcache-test").length, 1, "make sure the select parent page is still cached in the dom after changing page" ); start(); } ]); }); asyncTest( "menupage is removed when the parent page is removed", function(){ var dialogCount = $(":jqmData(role='dialog')").length; $.testHelper.pageSequence([ resetHash, function(){ $.mobile.changePage( "uncached-dom-cached-false.html" ); }, function(){ same( $(":jqmData(role='dialog')").length, dialogCount + 1 ); window.history.back(); }, function() { same( $(":jqmData(role='dialog')").length, dialogCount ); start(); } ]); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ module("jquery.mobile.forms.select native"); test( "native menu selections alter the button text", function(){ var select = $( "#native-select-choice-few" ), setAndCheck; setAndCheck = function(key){ var text; select.val( key ).selectmenu( 'refresh' ); text = select.find( "option[value='" + key + "']" ).text(); same( select.parent().find(".ui-btn-text").text(), text ); }; setAndCheck( 'rush' ); setAndCheck( 'standard' ); }); asyncTest( "selecting a value removes the related buttons down state", function(){ var select = $( "#native-select-choice-few" ); $.testHelper.sequence([ function() { // click the native menu parent button select.parent().trigger( 'vmousedown' ); }, function() { ok( select.parent().hasClass("ui-btn-down-c"), "button down class added" ); }, function() { // trigger a change on the select select.trigger( "change" ); }, function() { ok( !select.parent().hasClass("ui-btn-down-c"), "button down class removed" ); start(); } ], 300); }); // issue https://github.com/jquery/jquery-mobile/issues/2410 test( "adding options and refreshing a native select defaults the text", function() { var select = $( "#native-refresh" ), button = select.siblings( '.ui-btn-inner' ), text = "foo"; same(button.text(), "default"); select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu('refresh'); same(button.text(), text); }); // issue 2424 test( "native selects should provide open and close as a no-op", function() { // exception will prevent test success if undef $( "#native-refresh" ).selectmenu( 'open' ); $( "#native-refresh" ).selectmenu( 'close' ); ok( true ); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var libName = "jquery.mobile.forms.select.js", originalDefaultDialogTrans = $.mobile.defaultDialogTransition, originalDefTransitionHandler = $.mobile.defaultTransitionHandler, originalGetEncodedText = $.fn.getEncodedText, resetHash, closeDialog; resetHash = function(timeout){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); }; closeDialog = function(timeout){ $.mobile.activePage.find("li a").first().click(); }; module(libName, { teardown: function(){ $.mobile.defaultDialogTransition = originalDefaultDialogTrans; $.mobile.defaultTransitionHandler = originalDefTransitionHandler; $.fn.getEncodedText = originalGetEncodedText; window.encodedValueIsDefined = undefined; } }); asyncTest( "firing a click at least 400 ms later on the select screen overlay does close it", function(){ $.testHelper.sequence([ function(){ // bring up the smaller choice menu ok($("#select-choice-few-container a").length > 0, "there is in fact a button in the page"); $("#select-choice-few-container a").trigger("click"); }, function(){ //select the first menu item $("#select-choice-few-menu a:first").click(); }, function(){ same($("#select-choice-few-menu").parent(".ui-selectmenu-hidden").length, 1); start(); } ], 1000); }); asyncTest( "a large select menu should use the default dialog transition", function(){ var select; $.testHelper.pageSequence([ resetHash, function(timeout){ select = $("#select-choice-many-container-1 a"); //set to something else $.mobile.defaultTransitionHandler = $.testHelper.decorate({ fn: $.mobile.defaultTransitionHandler, before: function(name){ same(name, $.mobile.defaultDialogTransition); } }); // bring up the dialog select.trigger("click"); }, closeDialog, start ]); }); asyncTest( "custom select menu always renders screen from the left", function(){ var select; expect( 1 ); $.testHelper.sequence([ resetHash, function(){ select = $("ul#select-offscreen-menu"); $("#select-offscreen-container a").trigger("click"); }, function(){ ok(select.offset().left >= 30, "offset from the left is greater than or equal to 30px" ); start(); } ], 1000); }); asyncTest( "selecting an item from a dialog sized custom select menu leaves no dialog hash key", function(){ var dialogHashKey = "ui-state=dialog"; $.testHelper.pageSequence([ resetHash, function(timeout){ $("#select-choice-many-container-hash-check a").click(); }, function(){ ok(location.hash.indexOf(dialogHashKey) > -1); closeDialog(); }, function(){ same(location.hash.indexOf(dialogHashKey), -1); start(); } ]); }); asyncTest( "dialog sized select menu opened many times remains a dialog", function(){ var dialogHashKey = "ui-state=dialog", openDialogSequence = [ resetHash, function(){ $("#select-choice-many-container-many-clicks a").click(); }, function(){ ok(location.hash.indexOf(dialogHashKey) > -1, "hash should have the dialog hash key"); closeDialog(); } ], sequence = openDialogSequence.concat(openDialogSequence).concat([start]); $.testHelper.sequence(sequence, 1000); }); test( "make sure the label for the select gets the ui-select class", function(){ ok( $( "#native-select-choice-few-container label" ).hasClass( "ui-select" ), "created label has ui-select class" ); }); module("Non native menus", { setup: function() { $.mobile.selectmenu.prototype.options.nativeMenu = false; }, teardown: function() { $.mobile.selectmenu.prototype.options.nativeMenu = true; } }); asyncTest( "a large select option should not overflow", function(){ // https://github.com/jquery/jquery-mobile/issues/1338 var menu, select; $.testHelper.sequence([ resetHash, function(){ select = $("#select-long-option-label"); // bring up the dialog select.trigger("click"); }, function() { menu = $(".ui-selectmenu-list"); equal(menu.width(), menu.find("li:nth-child(2) .ui-btn-text").width(), "ui-btn-text element should not overflow"); start(); } ], 500); }); asyncTest( "using custom refocuses the button after close", function() { var select, button, triggered = false; expect( 1 ); $.testHelper.sequence([ resetHash, function() { select = $("#select-choice-focus-test"); button = select.find( "a" ); button.trigger( "click" ); }, function() { // NOTE this is called twice per triggered click button.focus(function() { triggered = true; }); $(".ui-selectmenu-screen:not(.ui-screen-hidden)").trigger("click"); }, function(){ ok(triggered, "focus is triggered"); start(); } ], 5000); }); asyncTest( "selected items are highlighted", function(){ $.testHelper.sequence([ resetHash, function(){ // bring up the smaller choice menu ok($("#select-choice-few-container a").length > 0, "there is in fact a button in the page"); $("#select-choice-few-container a").trigger("click"); }, function(){ var firstMenuChoice = $("#select-choice-few-menu li:first"); ok( firstMenuChoice.hasClass( $.mobile.activeBtnClass ), "default menu choice has the active button class" ); $("#select-choice-few-menu a:last").click(); }, function(){ // bring up the menu again $("#select-choice-few-container a").trigger("click"); }, function(){ var lastMenuChoice = $("#select-choice-few-menu li:last"); ok( lastMenuChoice.hasClass( $.mobile.activeBtnClass ), "previously slected item has the active button class" ); // close the dialog lastMenuChoice.find( "a" ).click(); }, start ], 1000); }); test( "enabling and disabling", function(){ var select = $( "select" ).first(), button; button = select.siblings( "a" ).first(); select.selectmenu( 'disable' ); same( select.attr('disabled'), "disabled", "select is disabled" ); ok( button.hasClass("ui-disabled"), "disabled class added" ); same( button.attr('aria-disabled'), "true", "select is disabled" ); same( select.selectmenu( 'option', 'disabled' ), true, "disbaled option set" ); select.selectmenu( 'enable' ); same( select.attr('disabled'), undefined, "select is disabled" ); ok( !button.hasClass("ui-disabled"), "disabled class added" ); same( button.attr('aria-disabled'), "false", "select is disabled" ); same( select.selectmenu( 'option', 'disabled' ), false, "disbaled option set" ); }); test( "adding options and refreshing a custom select defaults the text", function() { var select = $( "#custom-refresh" ), button = select.siblings( "a" ).find( ".ui-btn-inner" ), text = "foo"; same(button.text(), "default"); select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu( 'refresh' ); same(button.text(), text); }); asyncTest( "adding options and refreshing a custom select changes the options list", function(){ var select = $( "#custom-refresh-opts-list" ), button = select.siblings( "a" ).find( ".ui-btn-inner" ), text = "foo"; $.testHelper.sequence([ // bring up the dialog function() { button.click(); }, function() { same( $( ".ui-selectmenu.in ul" ).text(), "default" ); $( ".ui-selectmenu-screen" ).click(); }, function() { select.find( "option" ).remove(); //remove the loading message select.append('<option value="1">' + text + '</option>'); select.selectmenu( 'refresh' ); }, function() { button.click(); }, function() { same( $( ".ui-selectmenu.in ul" ).text(), text ); $( ".ui-selectmenu-screen" ).click(); }, start ], 500); }); test( "theme defined on select is used", function(){ var select = $("select#non-parent-themed"); ok( select.siblings( "a" ).hasClass("ui-btn-up-" + select.jqmData('theme'))); }); test( "select without theme defined inherits theme from parent", function() { var select = $("select#parent-themed"); ok( select .siblings( "a" ) .hasClass("ui-btn-up-" + select.parents(":jqmData(role='page')").jqmData('theme'))); }); // issue #2547 test( "custom select list item links have encoded option text values", function() { $( "#encoded-option" ).data( 'selectmenu' )._buildList(); same(window.encodedValueIsDefined, undefined); }); // issue #2547 test( "custom select list item links have unencoded option text values when using vanilla $.fn.text", function() { // undo our changes, undone in teardown $.fn.getEncodedText = $.fn.text; $( "#encoded-option" ).data( 'selectmenu' )._buildList(); same(window.encodedValueIsDefined, true); }); $.mobile.page.prototype.options.keepNative = "select.should-be-native"; // not testing the positive case here since's it's obviously tested elsewhere test( "select elements in the keepNative set shouldn't be enhanced", function() { ok( !$("#keep-native").parent().is("div.ui-btn") ); }); asyncTest( "dialog size select title should match the label", function() { var $select = $( "#select-choice-many-1" ), $label = $select.parent().siblings( "label" ), $button = $select.siblings( "a" ); $.testHelper.pageSequence([ function() { $button.click(); }, function() { same($.mobile.activePage.find( ".ui-title" ).text(), $label.text()); window.history.back(); }, start ]); }); asyncTest( "dialog size select title should match the label when changed after the dialog markup is added to the DOM", function() { var $select = $( "#select-choice-many-1" ), $label = $select.parent().siblings( "label" ), $button = $select.siblings( "a" ); $label.text( "foo" ); $.testHelper.pageSequence([ function() { $label.text( "foo" ); $button.click(); }, function() { same($.mobile.activePage.find( ".ui-title" ).text(), $label.text()); window.history.back(); }, start ]); }); })(jQuery);
JavaScript
/* * mobile select unit tests */ (function($){ var libName = "jquery.mobile.forms.select.js"; $(document).bind('mobileinit', function(){ $.mobile.selectmenu.prototype.options.nativeMenu = false; }); module(libName,{ setup: function(){ $.testHelper.openPage( location.hash.indexOf("#default") >= 0 ? "#" : "#default" ); } }); test( "selects marked with data-native-menu=true should use a div as their button", function(){ same($("#select-choice-native-container div.ui-btn").length, 1); }); test( "selects marked with data-native-menu=true should not have a custom menu", function(){ same($("#select-choice-native-container ul").length, 0); }); test( "selects marked with data-native-menu=true should sit inside the button", function(){ same($("#select-choice-native-container div.ui-btn select").length, 1); }); test( "select controls will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-select").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-select").length, "enhancements applied" ); }); })(jQuery);
JavaScript
/* * mobile checkboxradio unit tests */ (function($){ module( 'vertical controlgroup, no refresh' , { setup: function() { this.vcontrolgroup = $( "#vertical-controlgroup" ); } }); test( "vertical controlgroup classes", function() { var buttons = this.vcontrolgroup.find( ".ui-btn" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( !buttons.hasClass( "ui-btn-corner-all" ), "no button should have class 'ui-btn-corner-all'"); ok( buttons.first().hasClass( "ui-corner-top" ), "first button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last button should have class 'ui-corner-bottom'" ); }); module( 'vertical controlgroup, refresh', { setup: function() { this.vcontrolgroup = $( "#vertical-controlgroup" ); this.vcontrolgroup.find( ".ui-btn" ).show(); this.vcontrolgroup.controlgroup(); } }); test( "vertical controlgroup after first button was hidden", function() { //https://github.com/jquery/jquery-mobile/issues/1929 //We hide the first button and refresh this.vcontrolgroup.find( ".ui-btn" ).first().hide(); this.vcontrolgroup.controlgroup(); var buttons = this.vcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-top" ), "first visible button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last visible button should have class 'ui-corner-bottom'" ); }); test( "vertical controlgroup after last button was hidden", function() { //https://github.com/jquery/jquery-mobile/issues/1929 //We hide the last button and refresh this.vcontrolgroup.find( ".ui-btn" ).last().hide(); this.vcontrolgroup.controlgroup(); var buttons = this.vcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-top" ), "first visible button should have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-top" ), "middle buttons should not have class 'ui-corner-top'" ); ok( !middlebuttons.hasClass( "ui-corner-bottom" ), "middle buttons should not have class 'ui-corner-bottom'" ); ok( buttons.last().hasClass( "ui-corner-bottom"), "last visible button should have class 'ui-corner-bottom'" ); }); module( 'horizontal controlgroup, no refresh', { setup: function() { this.hcontrolgroup = $( "#horizontal-controlgroup" ); } }); test( "horizontal controlgroup classes", function() { var buttons = this.hcontrolgroup.find( ".ui-btn" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( !buttons.hasClass( "ui-btn-corner-all" ), "no button should have class 'ui-btn-corner-all'"); ok( buttons.first().hasClass( "ui-corner-left" ), "first button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last button should have class 'ui-corner-right'" ); }); module( 'horizontal controlgroup, refresh', { setup: function() { this.hcontrolgroup = $( "#horizontal-controlgroup" ); this.hcontrolgroup.find( ".ui-btn" ).show(); this.hcontrolgroup.controlgroup(); } }); test( "horizontal controlgroup after first button was hidden", function() { //We hide the first button and refresh this.hcontrolgroup.find( ".ui-btn" ).first().hide(); this.hcontrolgroup.controlgroup(); var buttons = this.hcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-left" ), "first visible button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last visible button should have class 'ui-corner-right'" ); }); test( "horizontal controlgroup after last button was hidden", function() { //We hide the last button and refresh this.hcontrolgroup.find( ".ui-btn" ).last().hide(); this.hcontrolgroup.controlgroup(); var buttons = this.hcontrolgroup.find( ".ui-btn" ).filter( ":visible" ), middlebuttons = buttons.filter(function(index) { return index > 0 && index < (length-1)}), length = buttons.length; ok( buttons.first().hasClass( "ui-corner-left" ), "first visible button should have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-left" ), "middle buttons should not have class 'ui-corner-left'" ); ok( !middlebuttons.hasClass( "ui-corner-right" ), "middle buttons should not have class 'ui-corner-right'" ); ok( buttons.last().hasClass( "ui-corner-right"), "last visible button should have class 'ui-corner-right'" ); }); test( "controlgroups will create when inside a container that receives a 'create' event", function(){ ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-controlgroup").length, "did not have enhancements applied" ); ok( $("#enhancetest").trigger("create").find(".ui-controlgroup").length, "enhancements applied" ); }); })(jQuery);
JavaScript
(function(Perf) { var $listPage = $( "#list-page" ), firstCounter = 0; Perf.setCurrentRev(); Perf.pageLoadStart = Date.now(); $listPage.live( "pagebeforecreate", function() { if( firstCounter == 0 ) { Perf.pageCreateStart = Date.now(); firstCounter++; } }); $listPage.live( "pageinit", function( event ) { // if a child page init is fired ignore it, we only // want the top level page init event if( event.target !== $("#list-page")[0] ){ return; } Perf.pageLoadEnd = Date.now(); // report the time taken for a full app boot Perf.report({ datapoint: "fullboot", value: Perf.pageLoadEnd - Perf.pageLoadStart }); // record the time taken to load and enhance the page // start polling for a new revision Perf.report({ datapoint: "pageload", value: Perf.pageCreateStart - Perf.pageLoadStart, after: function() { Perf.poll(); } }); }); })(window.Perf);
JavaScript
window.Perf = (function($, Perf) { $.extend(Perf, { reportUrl: 'stats/', revUrl: 'stats/rev.php', // should be defined before report or poll are run currentRev: undefined, report: function( data, after ) { $.extend(data, { pathname: location.pathname, agent: this.agent(), agentFull: window.navigator.userAgent, agentVersion: this.agentVersion() }); $.post( this.reportUrl, data, after ); }, poll: function() { var self = this; setInterval(function() { $.get( self.revUrl, function( data ) { // if there's a new revision refresh or currentRev isn't being set if( self.currentRev && self.currentRev !== data ){ location.href = location.href; } }); }, 60000); }, setCurrentRev: function() { var self = this; $.get( self.revUrl, function( data ) { self.currentRev = data; }); }, agent: function() { var agent = window.navigator.userAgent; for( name in this.agents ) { if( agent.indexOf( this.agents[name] ) > -1 ) { return this.agents[name]; } } return agent; }, agentVersion: function() { var agent = window.navigator.userAgent; agent.search(this.vRegexs[this.agent()] || ""); return RegExp.$1 ? RegExp.$1 : "0.0"; }, agents: { ANDROID: "Android", WP: "Windows Phone OS", IPHONE: "iPhone OS", IPAD: "iPad; U; CPU OS", BLACKBERRY: "BlackBerry" }, vRegexs: {} }); Perf.vRegexs[Perf.agents.ANDROID] = /([0-9].[0-9])(.[0-9])?/; Perf.vRegexs[Perf.agents.WP] = /Windows Phone OS ([0-9].[0-9]);/; Perf.vRegexs[Perf.agents.IPHONE] = /iPhone OS ([0-9]_[0-9])/; Perf.vRegexs[Perf.agents.IPAD] = /iPad; U; CPU OS ([0-9]_[0-9])/; Perf.vRegexs[Perf.agents.BLACKBERRY] = /BlackBerry ([0-9]{4})/; return Perf; })(jQuery, window.Perf || {});
JavaScript
(function($) { // TODO this is entire thing sucks $(function() { var searchMap = (function() { var searchSplit, searchMap = {}; if ( !location.search ){ return searchMap; } searchSplit = location.search.replace(/^\?/, "").split( /&|;/ ); for( var i = 0; i < searchSplit.length; i++ ) { var kv = searchSplit[i].split(/=/); searchMap[ kv[0] ] = kv[1]; } return searchMap; })(); $.get("../", searchMap, function(data) { $.each(data, function( i, avg ) { var tablename = avg.point + " " + avg.agent + " " + avg.agent_version + " " + avg.pathname, $table = $( "table > caption:contains(" + tablename + ")").parent(); if( !$table.length ) { $table = $( "<table></table>", { "data-pathname": avg.pathname, "data-point": avg.point, "data-agent": avg.agent, "data-agent-version": avg.agent_version }); $table.append( "<caption>" + tablename + "</caption>"); $table.append( "<thead><tr></tr></thead>" ); $table.append( "<tbody><tr></tr></tbody>" ); } // TODO assume time ordering in the data set var $heading = $table.find("thead > tr > th:contains(" + avg.day + ")"); if( !$heading.length ) { $heading = $("<th></th>", { text: avg.day, scope: "column" }); $table.find("thead > tr").append($heading); } var $rowHeading = $table.find("tbody > tr > th:contains(" + avg.point + ")" ), $row = $table.find( "tbody > tr" ); if( !$rowHeading.length ) { $rowHeading = $("<th></th>", { text: avg.point, scope: "row" }); $row.append( $rowHeading ); } $row.append( "<td>" + avg.avg_value + "</td>" ); $("#tables").append($table); }); $("#tables table").visualize({ type: "bar", width: 400, height: 400 }).appendTo("#graphs"); }); }); })(jQuery);
JavaScript
/* * mobile support unit tests */ (function( $ ) { $.testHelper = { excludeFileProtocol: function(callback){ var message = "Tests require script reload and cannot be run via file: protocol"; if (location.protocol == "file:") { test(message, function(){ ok(false, message); }); } else { callback(); } }, // TODO prevent test suite loads when the browser doesn't support push state // and push-state false is defined. setPushStateFor: function( libs ) { if( $.support.pushState && location.search.indexOf( "push-state" ) >= 0 ) { $.support.pushState = false; } $.each(libs, function(i, l) { $( "<script>", { src: l }).appendTo("head"); }); }, reloads: {}, reloadLib: function(libName){ if(this.reloads[libName] === undefined) { this.reloads[libName] = { lib: $("script[src$='" + libName + "']"), count: 0 }; } var lib = this.reloads[libName].lib.clone(), src = lib.attr('src'); //NOTE append "cache breaker" to force reload lib.attr('src', src + "?" + this.reloads[libName].count++); $("body").append(lib); }, rerunQunit: function(){ var self = this; QUnit.init(); $("script:not([src*='.\/'])").each(function(i, elem){ var src = elem.src.split("/"); self.reloadLib(src[src.length - 1]); }); QUnit.start(); }, alterExtend: function(extraExtension){ var extendFn = $.extend; $.extend = function(object, extension){ // NOTE extend the object as normal var result = extendFn.apply(this, arguments); // NOTE add custom extensions result = extendFn(result, extraExtension); return result; }; }, hideActivePageWhenComplete: function() { if( $('#qunit-testresult').length > 0 ) { $('.ui-page-active').css('display', 'none'); } else { setTimeout($.testHelper.hideActivePageWhenComplete, 500); } }, openPage: function(hash){ location.href = location.href.split('#')[0] + hash; }, sequence: function(fns, interval){ $.each(fns, function(i, fn){ setTimeout(fn, i * interval); }); }, pageSequence: function(fns){ this.eventSequence("pagechange", fns); }, eventSequence: function(event, fns, timedOut){ var fn = fns.shift(), self = this; if( fn === undefined ) return; // if a pagechange or defined event is never triggered // continue in the sequence to alert possible failures var warnTimer = setTimeout(function(){ self.eventSequence(event, fns, true); }, 2000); // bind the recursive call to the event $.mobile.pageContainer.one(event, function(){ clearTimeout(warnTimer); // Let the current stack unwind before we fire off the next item in the sequence. // TODO setTimeout(self.pageSequence, 0, [fns, event]); setTimeout(function(){ self.eventSequence(event, fns); }, 0); }); // invoke the function which should, in some fashion, // trigger the defined event fn(timedOut); }, decorate: function(opts){ var thisVal = opts.self || window; return function(){ var returnVal; opts.before && opts.before.apply(thisVal, arguments); returnVal = opts.fn.apply(thisVal, arguments); opts.after && opts.after.apply(thisVal, arguments); return returnVal; }; }, assertUrlLocation: function( args ) { var parts = $.mobile.path.parseUrl( location.href ), pathnameOnward = location.href.replace( parts.domain, "" ); if( $.support.pushState ) { same( pathnameOnward, args.hashOrPush || args.push, args.report ); } else { same( parts.hash, "#" + (args.hashOrPush || args.hash), args.report ); } } }; })(jQuery);
JavaScript
//quick & dirty theme switcher, written to potentially work as a bookmarklet (function($){ $.themeswitcher = function(){ if( $('[data-'+ $.mobile.ns +'-url=themeswitcher]').length ){ return; } var themesDir = 'http://jquerymobile.com/test/css/themes/', themes = ['default','valencia'], currentPage = $.mobile.activePage, menuPage = $( '<div data-'+ $.mobile.ns +'url="themeswitcher" data-'+ $.mobile.ns +'role=\'dialog\' data-'+ $.mobile.ns +'theme=\'a\'>' + '<div data-'+ $.mobile.ns +'role=\'header\' data-'+ $.mobile.ns +'theme=\'b\'>' + '<div class=\'ui-title\'>Switch Theme:</div>'+ '</div>'+ '<div data-'+ $.mobile.ns +'role=\'content\' data-'+ $.mobile.ns +'theme=\'c\'><ul data-'+ $.mobile.ns +'role=\'listview\' data-'+ $.mobile.ns +'inset=\'true\'></ul></div>'+ '</div>' ) .appendTo( $.mobile.pageContainer ), menu = menuPage.find('ul'); //menu items $.each(themes, function( i ){ $('<li><a href="#" data-'+ $.mobile.ns +'rel="back">' + themes[ i ].charAt(0).toUpperCase() + themes[ i ].substr(1) + '</a></li>') .bind("vclick", function(){ addTheme( themes[i] ); menuPage.dialog( "close" ); return false; }) .appendTo(menu); }); //remover, adder function addTheme(theme){ $('head').append( '<link rel=\'stylesheet\' href=\''+ themesDir + theme +'/\' />' ); } //create page, listview menuPage.page(); }; })(jQuery);
JavaScript
//thx @elroyjetson for the code example // When map page opens get location and display map $('.page-map').live("pagecreate", function() { //boston :) var lat = 42.35843, lng = -71.059773; //try to get GPS coords if( navigator.geolocation ) { //redirect function for successful location function gpsSuccess(pos){ if( pos.coords ){ lat = pos.coords.latitude; lng = pos.coords.longitude; } else{ lat = pos.latitude; lng = pos.longitude; } } function gpsFail(){ //Geo-location is supported, but we failed to get your coordinates. Workaround here perhaps? } navigator.geolocation.getCurrentPosition(gpsSuccess, gpsFail, {enableHighAccuracy:true, maximumAge: 300000}); } /* if not supported, you might attempt to use google loader for lat,long $.getScript('http://www.google.com/jsapi?key=YOURAPIKEY',function(){ lat = google.loader.ClientLocation.latitude; lng = google.loader.ClientLocation.longitude; }); */ var latlng = new google.maps.LatLng(lat, lng); var myOptions = { zoom: 10, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions); });
JavaScript
/* * jQuery Mobile Framework : scrollview plugin * Copyright (c) 2010 Adobe Systems Incorporated - Kin Blas (jblas@adobe.com) * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. * Note: Code is in draft form and is subject to change */ (function($,window,document,undefined){ jQuery.widget( "mobile.scrollview", jQuery.mobile.widget, { options: { fps: 60, // Frames per second in msecs. direction: null, // "x", "y", or null for both. scrollDuration: 2000, // Duration of the scrolling animation in msecs. overshootDuration: 250, // Duration of the overshoot animation in msecs. snapbackDuration: 500, // Duration of the snapback animation in msecs. moveThreshold: 10, // User must move this many pixels in any direction to trigger a scroll. moveIntervalThreshold: 150, // Time between mousemoves must not exceed this threshold. scrollMethod: "translate", // "translate", "position", "scroll" startEventName: "scrollstart", updateEventName: "scrollupdate", stopEventName: "scrollstop", eventType: $.support.touch ? "touch" : "mouse", showScrollBars: true, pagingEnabled: false, delayedClickSelector: "a,input,textarea,select,button,.ui-btn", delayedClickEnabled: false }, _makePositioned: function($ele) { if ($ele.css("position") == "static") $ele.css("position", "relative"); }, _create: function() { this._$clip = $(this.element).addClass("ui-scrollview-clip"); var $child = this._$clip.children(); if ($child.length > 1) { $child = this._$clip.wrapInner("<div></div>").children(); } this._$view = $child.addClass("ui-scrollview-view"); this._$clip.css("overflow", this.options.scrollMethod === "scroll" ? "scroll" : "hidden"); this._makePositioned(this._$clip); this._$view.css("overflow", "hidden"); // Turn off our faux scrollbars if we are using native scrolling // to position the view. this.options.showScrollBars = this.options.scrollMethod === "scroll" ? false : this.options.showScrollBars; // We really don't need this if we are using a translate transformation // for scrolling. We set it just in case the user wants to switch methods // on the fly. this._makePositioned(this._$view); this._$view.css({ left: 0, top: 0 }); this._sx = 0; this._sy = 0; var direction = this.options.direction; this._hTracker = (direction !== "y") ? new MomentumTracker(this.options) : null; this._vTracker = (direction !== "x") ? new MomentumTracker(this.options) : null; this._timerInterval = 1000/this.options.fps; this._timerID = 0; var self = this; this._timerCB = function(){ self._handleMomentumScroll(); }; this._addBehaviors(); }, _startMScroll: function(speedX, speedY) { this._stopMScroll(); this._showScrollBars(); var keepGoing = false; var duration = this.options.scrollDuration; this._$clip.trigger(this.options.startEventName); var ht = this._hTracker; if (ht) { var c = this._$clip.width(); var v = this._$view.width(); ht.start(this._sx, speedX, duration, (v > c) ? -(v - c) : 0, 0); keepGoing = !ht.done(); } var vt = this._vTracker; if (vt) { var c = this._$clip.height(); var v = this._$view.height(); vt.start(this._sy, speedY, duration, (v > c) ? -(v - c) : 0, 0); keepGoing = keepGoing || !vt.done(); } if (keepGoing) this._timerID = setTimeout(this._timerCB, this._timerInterval); else this._stopMScroll(); }, _stopMScroll: function() { if (this._timerID) { this._$clip.trigger(this.options.stopEventName); clearTimeout(this._timerID); } this._timerID = 0; if (this._vTracker) this._vTracker.reset(); if (this._hTracker) this._hTracker.reset(); this._hideScrollBars(); }, _handleMomentumScroll: function() { var keepGoing = false; var v = this._$view; var x = 0, y = 0; var vt = this._vTracker; if (vt) { vt.update(); y = vt.getPosition(); keepGoing = !vt.done(); } var ht = this._hTracker; if (ht) { ht.update(); x = ht.getPosition(); keepGoing = keepGoing || !ht.done(); } this._setScrollPosition(x, y); this._$clip.trigger(this.options.updateEventName, [ { x: x, y: y } ]); if (keepGoing) this._timerID = setTimeout(this._timerCB, this._timerInterval); else this._stopMScroll(); }, _setScrollPosition: function(x, y) { this._sx = x; this._sy = y; var $v = this._$view; var sm = this.options.scrollMethod; switch (sm) { case "translate": setElementTransform($v, x + "px", y + "px"); break; case "position": $v.css({left: x + "px", top: y + "px"}); break; case "scroll": var c = this._$clip[0]; c.scrollLeft = -x; c.scrollTop = -y; break; } var $vsb = this._$vScrollBar; var $hsb = this._$hScrollBar; if ($vsb) { var $sbt = $vsb.find(".ui-scrollbar-thumb"); if (sm === "translate") setElementTransform($sbt, "0px", -y/$v.height() * $sbt.parent().height() + "px"); else $sbt.css("top", -y/$v.height()*100 + "%"); } if ($hsb) { var $sbt = $hsb.find(".ui-scrollbar-thumb"); if (sm === "translate") setElementTransform($sbt, -x/$v.width() * $sbt.parent().width() + "px", "0px"); else $sbt.css("left", -x/$v.width()*100 + "%"); } }, scrollTo: function(x, y, duration) { this._stopMScroll(); if (!duration) return this._setScrollPosition(x, y); x = -x; y = -y; var self = this; var start = getCurrentTime(); var efunc = $.easing["easeOutQuad"]; var sx = this._sx; var sy = this._sy; var dx = x - sx; var dy = y - sy; var tfunc = function(){ var elapsed = getCurrentTime() - start; if (elapsed >= duration) { self._timerID = 0; self._setScrollPosition(x, y); } else { var ec = efunc(elapsed/duration, elapsed, 0, 1, duration); self._setScrollPosition(sx + (dx * ec), sy + (dy * ec)); self._timerID = setTimeout(tfunc, self._timerInterval); } }; this._timerID = setTimeout(tfunc, this._timerInterval); }, getScrollPosition: function() { return { x: -this._sx, y: -this._sy }; }, _getScrollHierarchy: function() { var svh = []; this._$clip.parents(".ui-scrollview-clip").each(function(){ var d = $(this).jqmData("scrollview"); if (d) svh.unshift(d); }); return svh; }, _getAncestorByDirection: function(dir) { var svh = this._getScrollHierarchy(); var n = svh.length; while (0 < n--) { var sv = svh[n]; var svdir = sv.options.direction; if (!svdir || svdir == dir) return sv; } return null; }, _handleDragStart: function(e, ex, ey) { // Stop any scrolling of elements in our parent hierarcy. $.each(this._getScrollHierarchy(),function(i,sv){ sv._stopMScroll(); }); this._stopMScroll(); var c = this._$clip; var v = this._$view; if (this.options.delayedClickEnabled) { this._$clickEle = $(e.target).closest(this.options.delayedClickSelector); } this._lastX = ex; this._lastY = ey; this._doSnapBackX = false; this._doSnapBackY = false; this._speedX = 0; this._speedY = 0; this._directionLock = ""; this._didDrag = false; if (this._hTracker) { var cw = parseInt(c.css("width"), 10); var vw = parseInt(v.css("width"), 10); this._maxX = cw - vw; if (this._maxX > 0) this._maxX = 0; if (this._$hScrollBar) this._$hScrollBar.find(".ui-scrollbar-thumb").css("width", (cw >= vw ? "100%" : Math.floor(cw/vw*100)+ "%")); } if (this._vTracker) { var ch = parseInt(c.css("height"), 10); var vh = parseInt(v.css("height"), 10); this._maxY = ch - vh; if (this._maxY > 0) this._maxY = 0; if (this._$vScrollBar) this._$vScrollBar.find(".ui-scrollbar-thumb").css("height", (ch >= vh ? "100%" : Math.floor(ch/vh*100)+ "%")); } var svdir = this.options.direction; this._pageDelta = 0; this._pageSize = 0; this._pagePos = 0; if (this.options.pagingEnabled && (svdir === "x" || svdir === "y")) { this._pageSize = svdir === "x" ? cw : ch; this._pagePos = svdir === "x" ? this._sx : this._sy; this._pagePos -= this._pagePos % this._pageSize; } this._lastMove = 0; this._enableTracking(); // If we're using mouse events, we need to prevent the default // behavior to suppress accidental selection of text, etc. We // can't do this on touch devices because it will disable the // generation of "click" events. // // XXX: We should test if this has an effect on links! - kin if (this.options.eventType == "mouse" || this.options.delayedClickEnabled) e.preventDefault(); e.stopPropagation(); }, _propagateDragMove: function(sv, e, ex, ey, dir) { this._hideScrollBars(); this._disableTracking(); sv._handleDragStart(e,ex,ey); sv._directionLock = dir; sv._didDrag = this._didDrag; }, _handleDragMove: function(e, ex, ey) { this._lastMove = getCurrentTime(); var v = this._$view; var dx = ex - this._lastX; var dy = ey - this._lastY; var svdir = this.options.direction; if (!this._directionLock) { var x = Math.abs(dx); var y = Math.abs(dy); var mt = this.options.moveThreshold; if (x < mt && y < mt) { return false; } var dir = null; var r = 0; if (x < y && (x/y) < 0.5) { dir = "y"; } else if (x > y && (y/x) < 0.5) { dir = "x"; } if (svdir && dir && svdir != dir) { // This scrollview can't handle the direction the user // is attempting to scroll. Find an ancestor scrollview // that can handle the request. var sv = this._getAncestorByDirection(dir); if (sv) { this._propagateDragMove(sv, e, ex, ey, dir); return false; } } this._directionLock = svdir ? svdir : (dir ? dir : "none"); } var newX = this._sx; var newY = this._sy; if (this._directionLock !== "y" && this._hTracker) { var x = this._sx; this._speedX = dx; newX = x + dx; // Simulate resistance. this._doSnapBackX = false; if (newX > 0 || newX < this._maxX) { if (this._directionLock === "x") { var sv = this._getAncestorByDirection("x"); if (sv) { this._setScrollPosition(newX > 0 ? 0 : this._maxX, newY); this._propagateDragMove(sv, e, ex, ey, dir); return false; } } newX = x + (dx/2); this._doSnapBackX = true; } } if (this._directionLock !== "x" && this._vTracker) { var y = this._sy; this._speedY = dy; newY = y + dy; // Simulate resistance. this._doSnapBackY = false; if (newY > 0 || newY < this._maxY) { if (this._directionLock === "y") { var sv = this._getAncestorByDirection("y"); if (sv) { this._setScrollPosition(newX, newY > 0 ? 0 : this._maxY); this._propagateDragMove(sv, e, ex, ey, dir); return false; } } newY = y + (dy/2); this._doSnapBackY = true; } } if (this.options.pagingEnabled && (svdir === "x" || svdir === "y")) { if (this._doSnapBackX || this._doSnapBackY) this._pageDelta = 0; else { var opos = this._pagePos; var cpos = svdir === "x" ? newX : newY; var delta = svdir === "x" ? dx : dy; this._pageDelta = (opos > cpos && delta < 0) ? this._pageSize : ((opos < cpos && delta > 0) ? -this._pageSize : 0); } } this._didDrag = true; this._lastX = ex; this._lastY = ey; this._setScrollPosition(newX, newY); this._showScrollBars(); // Call preventDefault() to prevent touch devices from // scrolling the main window. // e.preventDefault(); return false; }, _handleDragStop: function(e) { var l = this._lastMove; var t = getCurrentTime(); var doScroll = l && (t - l) <= this.options.moveIntervalThreshold; var sx = (this._hTracker && this._speedX && doScroll) ? this._speedX : (this._doSnapBackX ? 1 : 0); var sy = (this._vTracker && this._speedY && doScroll) ? this._speedY : (this._doSnapBackY ? 1 : 0); var svdir = this.options.direction; if (this.options.pagingEnabled && (svdir === "x" || svdir === "y") && !this._doSnapBackX && !this._doSnapBackY) { var x = this._sx; var y = this._sy; if (svdir === "x") x = -this._pagePos + this._pageDelta; else y = -this._pagePos + this._pageDelta; this.scrollTo(x, y, this.options.snapbackDuration); } else if (sx || sy) this._startMScroll(sx, sy); else this._hideScrollBars(); this._disableTracking(); if (!this._didDrag && this.options.delayedClickEnabled && this._$clickEle.length) { this._$clickEle .trigger("mousedown") //.trigger("focus") .trigger("mouseup") .trigger("click"); } // If a view scrolled, then we need to absorb // the event so that links etc, underneath our // cursor/finger don't fire. return this._didDrag ? false : undefined; }, _enableTracking: function() { $(document).bind(this._dragMoveEvt, this._dragMoveCB); $(document).bind(this._dragStopEvt, this._dragStopCB); }, _disableTracking: function() { $(document).unbind(this._dragMoveEvt, this._dragMoveCB); $(document).unbind(this._dragStopEvt, this._dragStopCB); }, _showScrollBars: function() { var vclass = "ui-scrollbar-visible"; if (this._$vScrollBar) this._$vScrollBar.addClass(vclass); if (this._$hScrollBar) this._$hScrollBar.addClass(vclass); }, _hideScrollBars: function() { var vclass = "ui-scrollbar-visible"; if (this._$vScrollBar) this._$vScrollBar.removeClass(vclass); if (this._$hScrollBar) this._$hScrollBar.removeClass(vclass); }, _addBehaviors: function() { var self = this; if (this.options.eventType === "mouse") { this._dragStartEvt = "mousedown"; this._dragStartCB = function(e){ return self._handleDragStart(e, e.clientX, e.clientY); }; this._dragMoveEvt = "mousemove"; this._dragMoveCB = function(e){ return self._handleDragMove(e, e.clientX, e.clientY); }; this._dragStopEvt = "mouseup"; this._dragStopCB = function(e){ return self._handleDragStop(e); }; } else // "touch" { this._dragStartEvt = "touchstart"; this._dragStartCB = function(e) { var t = e.originalEvent.targetTouches[0]; return self._handleDragStart(e, t.pageX, t.pageY); }; this._dragMoveEvt = "touchmove"; this._dragMoveCB = function(e) { var t = e.originalEvent.targetTouches[0]; return self._handleDragMove(e, t.pageX, t.pageY); }; this._dragStopEvt = "touchend"; this._dragStopCB = function(e){ return self._handleDragStop(e); }; } this._$view.bind(this._dragStartEvt, this._dragStartCB); if (this.options.showScrollBars) { var $c = this._$clip; var prefix = "<div class=\"ui-scrollbar ui-scrollbar-"; var suffix = "\"><div class=\"ui-scrollbar-track\"><div class=\"ui-scrollbar-thumb\"></div></div></div>"; if (this._vTracker) { $c.append(prefix + "y" + suffix); this._$vScrollBar = $c.children(".ui-scrollbar-y"); } if (this._hTracker) { $c.append(prefix + "x" + suffix); this._$hScrollBar = $c.children(".ui-scrollbar-x"); } } } }); function setElementTransform($ele, x, y) { var v = "translate3d(" + x + "," + y + ", 0px)"; $ele.css({ "-moz-transform": v, "-webkit-transform": v, "transform": v }); } function MomentumTracker(options) { this.options = $.extend({}, options); this.easing = "easeOutQuad"; this.reset(); } var tstates = { scrolling: 0, overshot: 1, snapback: 2, done: 3 }; function getCurrentTime() { return (new Date()).getTime(); } $.extend(MomentumTracker.prototype, { start: function(pos, speed, duration, minPos, maxPos) { this.state = (speed != 0) ? ((pos < minPos || pos > maxPos) ? tstates.snapback : tstates.scrolling) : tstates.done; this.pos = pos; this.speed = speed; this.duration = (this.state == tstates.snapback) ? this.options.snapbackDuration : duration; this.minPos = minPos; this.maxPos = maxPos; this.fromPos = (this.state == tstates.snapback) ? this.pos : 0; this.toPos = (this.state == tstates.snapback) ? ((this.pos < this.minPos) ? this.minPos : this.maxPos) : 0; this.startTime = getCurrentTime(); }, reset: function() { this.state = tstates.done; this.pos = 0; this.speed = 0; this.minPos = 0; this.maxPos = 0; this.duration = 0; }, update: function() { var state = this.state; if (state == tstates.done) return this.pos; var duration = this.duration; var elapsed = getCurrentTime() - this.startTime; elapsed = elapsed > duration ? duration : elapsed; if (state == tstates.scrolling || state == tstates.overshot) { var dx = this.speed * (1 - $.easing[this.easing](elapsed/duration, elapsed, 0, 1, duration)); var x = this.pos + dx; var didOverShoot = (state == tstates.scrolling) && (x < this.minPos || x > this.maxPos); if (didOverShoot) x = (x < this.minPos) ? this.minPos : this.maxPos; this.pos = x; if (state == tstates.overshot) { if (elapsed >= duration) { this.state = tstates.snapback; this.fromPos = this.pos; this.toPos = (x < this.minPos) ? this.minPos : this.maxPos; this.duration = this.options.snapbackDuration; this.startTime = getCurrentTime(); elapsed = 0; } } else if (state == tstates.scrolling) { if (didOverShoot) { this.state = tstates.overshot; this.speed = dx / 2; this.duration = this.options.overshootDuration; this.startTime = getCurrentTime(); } else if (elapsed >= duration) this.state = tstates.done; } } else if (state == tstates.snapback) { if (elapsed >= duration) { this.pos = this.toPos; this.state = tstates.done; } else this.pos = this.fromPos + ((this.toPos - this.fromPos) * $.easing[this.easing](elapsed/duration, elapsed, 0, 1, duration)); } return this.pos; }, done: function() { return this.state == tstates.done; }, getPosition: function(){ return this.pos; } }); jQuery.widget( "mobile.scrolllistview", jQuery.mobile.scrollview, { options: { direction: "y" }, _create: function() { $.mobile.scrollview.prototype._create.call(this); // Cache the dividers so we don't have to search for them everytime the // view is scrolled. // // XXX: Note that we need to update this cache if we ever support lists // that can dynamically update their content. this._$dividers = this._$view.find(":jqmData(role='list-divider')"); this._lastDivider = null; }, _setScrollPosition: function(x, y) { // Let the view scroll like it normally does. $.mobile.scrollview.prototype._setScrollPosition.call(this, x, y); y = -y; // Find the dividers for the list. var $divs = this._$dividers; var cnt = $divs.length; var d = null; var dy = 0; var nd = null; for (var i = 0; i < cnt; i++) { nd = $divs.get(i); var t = nd.offsetTop; if (y >= t) { d = nd; dy = t; } else if (d) break; } // If we found a divider to move position it at the top of the // clip view. if (d) { var h = d.offsetHeight; var mxy = (d != nd) ? nd.offsetTop : (this._$view.get(0).offsetHeight); if (y + h >= mxy) y = (mxy - h) - dy; else y = y - dy; // XXX: Need to convert this over to using $().css() and supporting the non-transform case. var ld = this._lastDivider; if (ld && d != ld) { setElementTransform($(ld), 0, 0); } setElementTransform($(d), 0, y + "px"); this._lastDivider = d; } } }); })(jQuery,window,document); // End Component
JavaScript
function ResizePageContentHeight(page) { var $page = $(page), $content = $page.children( ".ui-content" ), hh = $page.children( ".ui-header" ).outerHeight() || 0, fh = $page.children( ".ui-footer" ).outerHeight() || 0, pt = parseFloat($content.css( "padding-top" )), pb = parseFloat($content.css( "padding-bottom" )), wh = window.innerHeight; $content.height(wh - (hh + fh) - (pt + pb)); } $( ":jqmData(role='page')" ).live( "pageshow", function(event) { var $page = $( this ); // For the demos that use this script, we want the content area of each // page to be scrollable in the 'y' direction. $page.find( ".ui-content" ).attr( "data-" + $.mobile.ns + "scroll", "y" ); // This code that looks for [data-scroll] will eventually be folded // into the jqm page processing code when scrollview support is "official" // instead of "experimental". $page.find( ":jqmData(scroll):not(.ui-scrollview-clip)" ).each(function () { var $this = $( this ); // XXX: Remove this check for ui-scrolllistview once we've // integrated list divider support into the main scrollview class. if ( $this.hasClass( "ui-scrolllistview" ) ) { $this.scrolllistview(); } else { var st = $this.jqmData( "scroll" ) + "", paging = st && st.search(/^[xy]p$/) != -1, dir = st && st.search(/^[xy]/) != -1 ? st.charAt(0) : null, opts = { direction: dir || undefined, paging: paging || undefined, scrollMethod: $this.jqmData("scroll-method") || undefined }; $this.scrollview( opts ); } }); // For the demos, we want to make sure the page being shown has a content // area that is sized to fit completely within the viewport. This should // also handle the case where pages are loaded dynamically. ResizePageContentHeight( event.target ); }); $( window ).bind( "orientationchange", function( event ) { ResizePageContentHeight( $( ".ui-page" ) ); });
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
/* * Copy of http://github.com/nje/jquery-tmpl/raw/master/jquery.tmpl.js at f827fb68417bc14ab9f6ae889421d5fea4cb2859 * jQuery Templating Plugin * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. */ (function( jQuery, undefined ){ var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = []; function newTmplItem( options, parentItem, fn, data ) { // Returns a template item data structure for a new rendered instance of a template (a 'template item'). // The content field is a hierarchical array of strings and nested items (to be // removed and replaced by nodes field of dom elements, once inserted in DOM). var newItem = { data: data || (parentItem ? parentItem.data : {}), _wrap: parentItem ? parentItem._wrap : null, tmpl: null, parent: parentItem || null, nodes: [], calls: tiCalls, nest: tiNest, wrap: tiWrap, html: tiHtml, update: tiUpdate }; if ( options ) { jQuery.extend( newItem, options, { nodes: [], parent: parentItem } ); } if ( fn ) { // Build the hierarchical content to be used during insertion into DOM newItem.tmpl = fn; newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem ); newItem.key = ++itemKey; // Keep track of new template item, until it is stored as jQuery Data on DOM element (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem; } return newItem; } // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core). jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems, parent = this.length === 1 && this[0].parentNode; appendToTmplItems = newTmplItems || {}; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); ret = this; } else { for ( i = 0, l = insert.length; i < l; i++ ) { cloneIndex = i; elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } cloneIndex = 0; ret = this.pushStack( ret, name, insert.selector ); } tmplItems = appendToTmplItems; appendToTmplItems = null; jQuery.tmpl.complete( tmplItems ); return ret; }; }); jQuery.fn.extend({ // Use first wrapped element as template markup. // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( data, options, parentItem ) { return jQuery.tmpl( this[0], data, options, parentItem ); }, // Find which rendered template item the first wrapped DOM element belongs to tmplItem: function() { return jQuery.tmplItem( this[0] ); }, // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template. template: function( name ) { return jQuery.template( name, this[0] ); }, domManip: function( args, table, callback, options ) { // This appears to be a bug in the appendTo, etc. implementation // it should be doing .call() instead of .apply(). See #6227 if ( args[0] && args[0].nodeType ) { var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem; while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {} if ( argsLength > 1 ) { dmArgs[0] = [jQuery.makeArray( args )]; } if ( tmplItem && cloneIndex ) { dmArgs[2] = function( fragClone ) { // Handler called by oldManip when rendered template has been inserted into DOM. jQuery.tmpl.afterManip( this, fragClone, callback ); }; } oldManip.apply( this, dmArgs ); } else { oldManip.apply( this, arguments ); } cloneIndex = 0; if ( !appendToTmplItems ) { jQuery.tmpl.complete( newTmplItems ); } return this; } }); jQuery.extend({ // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( tmpl, data, options, parentItem ) { var ret, topLevel = !parentItem; if ( topLevel ) { // This is a top-level tmpl call (not from a nested template using {{tmpl}}) parentItem = topTmplItem; tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level } else if ( !tmpl ) { // The template item is already associated with DOM - this is a refresh. // Re-evaluate rendered template for the parentItem tmpl = parentItem.tmpl; newTmplItems[parentItem.key] = parentItem; parentItem.nodes = []; if ( parentItem.wrapped ) { updateWrapped( parentItem, parentItem.wrapped ); } // Rebuild, without creating a new template item return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); } if ( !tmpl ) { return []; // Could throw... } if ( typeof data === "function" ) { data = data.call( parentItem || {} ); } if ( options && options.wrapped ) { updateWrapped( options, options.wrapped ); } ret = jQuery.isArray( data ) ? jQuery.map( data, function( dataItem ) { return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; }) : [ newTmplItem( options, parentItem, tmpl, data ) ]; return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; }, // Return rendered template item for an element. tmplItem: function( elem ) { var tmplItem; if ( elem instanceof jQuery ) { elem = elem[0]; } while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} return tmplItem || topTmplItem; }, // Set: // Use $.template( name, tmpl ) to cache a named template, // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc. // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration. // Get: // Use $.template( name ) to access a cached template. // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString ) // will return the compiled template, without adding a name reference. // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent // to $.template( null, templateString ) template: function( name, tmpl ) { if (tmpl) { // Compile template and associate with name if ( typeof tmpl === "string" ) { // This is an HTML string being passed directly in. tmpl = buildTmplFn( tmpl ) } else if ( tmpl instanceof jQuery ) { tmpl = tmpl[0] || {}; } if ( tmpl.nodeType ) { // If this is a template block, use cached copy, or generate tmpl function and cache. tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML )); } return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl; } // Return named compiled template return name ? (typeof name !== "string" ? jQuery.template( null, name ): (jQuery.template[name] || // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; }, encode: function( text ) { // Do HTML encoding replacing < > & and ' and " by corresponding entities. return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;"); } }); jQuery.extend( jQuery.tmpl, { tag: { "tmpl": { _default: { $2: "null" }, open: "if($notnull_1){_=_.concat($item.nest($1,$2));}" // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions) // This means that {{tmpl foo}} treats foo as a template (which IS a function). // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}. }, "wrap": { _default: { $2: "null" }, open: "$item.calls(_,$1,$2);_=[];", close: "call=$item.calls();_=call._.concat($item.wrap(call,_));" }, "each": { _default: { $2: "$index, $value" }, open: "if($notnull_1){$.each($1a,function($2){with(this){", close: "}});}" }, "if": { open: "if(($notnull_1) && $1a){", close: "}" }, "else": { _default: { $1: "true" }, open: "}else if(($notnull_1) && $1a){" }, "html": { // Unecoded expression evaluation. open: "if($notnull_1){_.push($1a);}" }, "=": { // Encoded expression evaluation. Abbreviated form is ${}. _default: { $1: "$data" }, open: "if($notnull_1){_.push($.encode($1a));}" }, "!": { // Comment tag. Skipped by parser open: "" } }, // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events complete: function( items ) { newTmplItems = {}; }, // Call this from code which overrides domManip, or equivalent // Manage cloning/storing template items etc. afterManip: function afterManip( elem, fragClone, callback ) { // Provides cloned fragment ready for fixup prior to and after insertion into DOM var content = fragClone.nodeType === 11 ? jQuery.makeArray(fragClone.childNodes) : fragClone.nodeType === 1 ? [fragClone] : []; // Return fragment to original caller (e.g. append) for DOM insertion callback.call( elem, fragClone ); // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data. storeTmplItems( content ); cloneIndex++; } }); //========================== Private helper functions, used by code above ========================== function build( tmplItem, nested, content ) { // Convert hierarchical content into flat string array // and finally return array of fragments ready for DOM insertion var frag, ret = content ? jQuery.map( content, function( item ) { return (typeof item === "string") ? // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM. (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) : // This is a child template item. Build nested template. build( item, tmplItem, item._ctnt ); }) : // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. tmplItem; if ( nested ) { return ret; } // top-level template ret = ret.join(""); // Support templates which have initial or final text nodes, or consist only of text // Also support HTML entities within the HTML markup. ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) { frag = jQuery( middle ).get(); storeTmplItems( frag ); if ( before ) { frag = unencode( before ).concat(frag); } if ( after ) { frag = frag.concat(unencode( after )); } }); return frag ? frag : unencode( ret ); } function unencode( text ) { // Use createElement, since createTextNode will not render HTML entities correctly var el = document.createElement( "div" ); el.innerHTML = text; return jQuery.makeArray(el.childNodes); } // Generate a reusable function that will serve to render a template against data function buildTmplFn( markup ) { return new Function("jQuery","$item", "var $=jQuery,call,_=[],$data=$item.data;" + // Introduce the data as local variables using with(){} "with($data){_.push('" + // Convert the template into pure JavaScript jQuery.trim(markup) .replace( /([\\'])/g, "\\$1" ) .replace( /[\r\t\n]/g, " " ) .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" ) .replace( /\{\{(\/?)(\w+|.)(?:\(((?:.(?!\}\}))*?)?\))?(?:\s+(.*?)?)?(\((.*?)\))?\s*\}\}/g, function( all, slash, type, fnargs, target, parens, args ) { var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect; if ( !tag ) { throw "Template command not found: " + type; } def = tag._default || []; if ( parens && !/\w$/.test(target)) { target += parens; parens = ""; } if ( target ) { target = unescape( target ); args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : ""); // Support for target being things like a.toLowerCase(); // In that case don't call with template item as 'this' pointer. Just evaluate... expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target; exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))"; } else { exprAutoFnDetect = expr = def.$1 || "null"; } fnargs = unescape( fnargs ); return "');" + tag[ slash ? "close" : "open" ] .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" ) .split( "$1a" ).join( exprAutoFnDetect ) .split( "$1" ).join( expr ) .split( "$2" ).join( fnargs ? fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) { params = params ? ("," + params + ")") : (parens ? ")" : ""); return params ? ("(" + name + ").call($item" + params) : all; }) : (def.$2||"") ) + "_.push('"; }) + "');}return _;" ); } function updateWrapped( options, wrapped ) { // Build the wrapped content. options._wrap = build( options, true, // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string. jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()] ).join(""); } function unescape( args ) { return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null; } function outerHtml( elem ) { var div = document.createElement("div"); div.appendChild( elem.cloneNode(true) ); return div.innerHTML; } // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance. function storeTmplItems( content ) { var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m; for ( i = 0, l = content.length; i < l; i++ ) { if ( (elem = content[i]).nodeType !== 1 ) { continue; } elems = elem.getElementsByTagName("*"); for ( m = elems.length - 1; m >= 0; m-- ) { processItemKey( elems[m] ); } processItemKey( elem ); } function processItemKey( el ) { var pntKey, pntNode = el, pntItem, tmplItem, key; // Ensure that each rendered template inserted into the DOM has its own template item, if ( (key = el.getAttribute( tmplItmAtt ))) { while ((pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { } if ( pntKey !== key ) { // The next ancestor with a _tmplitem expando is on a different key than this one. // So this is a top-level element within this template item pntNode = pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0); if ( !(tmplItem = newTmplItems[key]) ) { // The item is for wrapped content, and was copied from the temporary parent wrappedItem. tmplItem = wrappedItems[key]; tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true ); tmplItem.key = ++itemKey; newTmplItems[itemKey] = tmplItem; } if ( cloneIndex ) { cloneTmplItem( key ); } } el.removeAttribute( tmplItmAtt ); } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) { // This was a rendered element, cloned during append or appendTo etc. // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem. cloneTmplItem( tmplItem.key ); newTmplItems[tmplItem.key] = tmplItem; pntNode = jQuery.data( el.parentNode, "tmplItem" ); pntNode = pntNode ? pntNode.key : 0; } if ( tmplItem ) { pntItem = tmplItem; // Find the template item of the parent element. // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string) while ( pntItem && pntItem.key != pntNode ) { // Add this element as a top-level node for this rendered template item, as well as for any // ancestor items between this item and the item of its parent element pntItem.nodes.push( el ); pntItem = pntItem.parent; } // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering... delete tmplItem._ctnt; delete tmplItem._wrap; // Store template item as jQuery data on the element jQuery.data( el, "tmplItem", tmplItem ); } function cloneTmplItem( key ) { key = key + keySuffix; tmplItem = newClonedItems[key] = (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true )); } } } //---- Helper functions for template item ---- function tiCalls( content, tmpl, data, options ) { if ( !content ) { return stack.pop(); } stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options }); } function tiNest( tmpl, data, options ) { // nested template, using {{tmpl}} tag return jQuery.tmpl( jQuery.template( tmpl ), data, options, this ); } function tiWrap( call, wrapped ) { // nested template, using {{wrap}} tag var options = call.options || {}; options.wrapped = wrapped; // Apply the template, which may incorporate wrapped content, return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item ); } function tiHtml( filter, textOnly ) { var wrapped = this._wrap; return jQuery.map( jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ), function(e) { return textOnly ? e.innerText || e.textContent : e.outerHTML || outerHtml(e); }); } function tiUpdate() { var coll = this.nodes; jQuery.tmpl( null, null, null, this).insertBefore( coll[0] ); jQuery( coll ).remove(); } })( jQuery );
JavaScript
$(function() { var symbols = { "USD": "$", "EUR": "&euro;", "GBP": "&pound;", "Miles": "m", "Kilometer": "km", "inch": "\"", "centimeter": "cm" }; function list() { var ul = $( "#conversions" ).empty(), ulEdit = $( "#edit-conversions" ).empty(); $.each( all, function( index, conversion ) { // if last update was less then a minute ago, don't update if ( conversion.type === "currency" && !conversion.rate || conversion.updated && conversion.updated + 60000 < +new Date) { var self = conversion; var url = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + conversion.from + conversion.to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&diagnostics=true&callback=?"; $.getJSON( url, function( result ) { self.rate = parseFloat( result.query.results.row.rate ); $( "#term" ).keyup(); self.updated = +new Date; conversions.store(); }); } $( "#conversion-field" ).tmpl( conversion, { symbols: symbols }).appendTo( ul ); $( "#conversion-edit-field" ).tmpl( conversion, { symbols: symbols }).appendTo( ulEdit ); }); ul.add(ulEdit).listview("refresh"); $( "#term" ).keyup(); } var all = conversions.all(); $( "#term" ).keyup(function() { var value = this.value; $.each( all, function( index, conversion ) { $( "#" + conversion.from + conversion.to ).text( conversion.rate ? Math.ceil( value * conversion.rate * 100 ) / 100 : "Rate not available, yet." ); }); }).focus(); list(); $( "form" ).submit(function() { $( "#term" ).blur(); return false; }); $( "#add" ).click(function() { all.push({ type: "currency", from: $( "#currency-options-from" ).val(), to: $( "#currency-options-to" ).val() }); conversions.store(); list(); }); $( "#clear" ).click(function() { conversions.clear(); list(); return false; }); $( "#restore" ).click(function() { conversions.restore(); list(); return false; }); $( "#edit-conversions" ).click(function( event ) { var target = $( event.target ).closest( ".deletebutton" ); if ( target.length ) { conversions.remove( target.prev( "label" ).attr( "for" ) ); list(); } return false; }); });
JavaScript
(function() { var defaults = [ { type: "currency", from: "USD", to: "EUR" }, { type: "currency", from: "GBP", to: "EUR" } // TODO add back in as defaults once its possible to add other conversions, not just currencies /*, { type: "distance", from: "Miles", to: "Kilometer", rate: 1.609344 }, { type: "distance", from: "inch", to: "centimeter", rate: 2.54 }*/ ]; // TODO fallback to whatever else when localStorage isn't available function get() { return JSON.parse( localStorage.getItem( "conversions" ) ); } function set( value ) { localStorage.setItem( "conversions", JSON.stringify( value ) ); } var conversions = get( "conversions" ); if ( !conversions ) { conversions = defaults.slice(); set( conversions ); } window.conversions = { store: function() { set( conversions ); }, all: function() { return conversions; }, clear: function() { conversions.length = 0; this.store(); }, restore: function() { conversions.length = 0; $.extend( conversions, defaults ); this.store(); }, remove: function( tofrom ) { $.each( conversions, function( index, conversion ) { if ( ( conversion.from + conversion.to ) === tofrom ) { conversions.splice( index, 1 ); return false; } }); this.store(); } }; })();
JavaScript
{ "data":{ "current_condition":[ { "cloudcover":"50", "humidity":"71", "observation_time":"03:28 PM", "precipMM":"0.5", "pressure":"998", "temp_C":"8", "temp_F":"46", "visibility":"10", "weatherCode":"116", "weatherDesc":[ { "value":"Partly Cloudy" } ], "weatherIconUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } ], "winddir16Point":"E", "winddirDegree":"100", "windspeedKmph":"13", "windspeedMiles":"8" } ], "request":[ { "query":"London, United Kingdom", "type":"City" } ], "weather":[ { "date":"2013-03-19", "precipMM":"0.8", "tempMaxC":"9", "tempMaxF":"48", "tempMinC":"0", "tempMinF":"33", "weatherCode":"116", "weatherDesc":[ { "value":"Partly Cloudy" } ], "weatherIconUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } ], "winddir16Point":"ESE", "winddirDegree":"118", "winddirection":"ESE", "windspeedKmph":"14", "windspeedMiles":"9" }, { "date":"2013-03-20", "precipMM":"0.7", "tempMaxC":"6", "tempMaxF":"43", "tempMinC":"-1", "tempMinF":"30", "weatherCode":"353", "weatherDesc":[ { "value":"Light rain shower" } ], "weatherIconUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png" } ], "winddir16Point":"NNE", "winddirDegree":"34", "winddirection":"NNE", "windspeedKmph":"15", "windspeedMiles":"10" } ] } }
JavaScript
http:// www.worldweatheronline.com/feed/search.ashx?key=216f120440170120131803&format=json&query=Rus { "search_api":{ "result":[ { "areaName":[ { "value":"Onitewa" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Onitewa-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Komupau" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Komupau-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Viavusa" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Viavusa-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Oterama" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Oterama-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Konibau" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Konibau-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Univa" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Univa-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Ione" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Ione-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Waihusa" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Waihusa-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Untava" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Untava-weather\/Makira\/SB.aspx" } ] }, { "areaName":[ { "value":"Oneteva" } ], "country":[ { "value":"Solomon Islands" } ], "latitude":"-9.867", "longitude":"160.817", "population":"0", "region":[ { "value":"Makira" } ], "weatherUrl":[ { "value":"http:\/\/www.worldweatheronline.com\/Oneteva-weather\/Makira\/SB.aspx" } ] } ] } }
JavaScript
if(typeof Object.create!=="function"){ Object.create=function(o){ function F(){ }; F.prototype=o; return new F(); }; } var ua={toString:function(){ return navigator.userAgent; },test:function(s){ return this.toString().toLowerCase().indexOf(s.toLowerCase())>-1; }}; ua.version=(ua.toString().toLowerCase().match(/[\s\S]+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1]; ua.webkit=ua.test("webkit"); ua.gecko=ua.test("gecko")&&!ua.webkit; ua.opera=ua.test("opera"); ua.ie=ua.test("msie")&&!ua.opera; ua.ie6=ua.ie&&document.compatMode&&typeof document.documentElement.style.maxHeight==="undefined"; ua.ie7=ua.ie&&document.documentElement&&typeof document.documentElement.style.maxHeight!=="undefined"&&typeof XDomainRequest==="undefined"; ua.ie8=ua.ie&&typeof XDomainRequest!=="undefined"; var domReady=function(){ var _1=[]; var _2=function(){ if(!arguments.callee.done){ arguments.callee.done=true; for(var i=0;i<_1.length;i++){ _1[i](); } } }; if(document.addEventListener){ document.addEventListener("DOMContentLoaded",_2,false); } if(ua.ie){ (function(){ try{ document.documentElement.doScroll("left"); } catch(e){ setTimeout(arguments.callee,50); return; } _2(); })(); document.onreadystatechange=function(){ if(document.readyState==="complete"){ document.onreadystatechange=null; _2(); } }; } if(ua.webkit&&document.readyState){ (function(){ if(document.readyState!=="loading"){ _2(); }else{ setTimeout(arguments.callee,10); } })(); } window.onload=_2; return function(fn){ if(typeof fn==="function"){ _1[_1.length]=fn; } return fn; }; }(); var cssHelper=function(){ var _3={BLOCKS:/[^\s{][^{]*\{(?:[^{}]*\{[^{}]*\}[^{}]*|[^{}]*)*\}/g,BLOCKS_INSIDE:/[^\s{][^{]*\{[^{}]*\}/g,DECLARATIONS:/[a-zA-Z\-]+[^;]*:[^;]+;/g,RELATIVE_URLS:/url\(['"]?([^\/\)'"][^:\)'"]+)['"]?\)/g,REDUNDANT_COMPONENTS:/(?:\/\*([^*\\\\]|\*(?!\/))+\*\/|@import[^;]+;)/g,REDUNDANT_WHITESPACE:/\s*(,|:|;|\{|\})\s*/g,MORE_WHITESPACE:/\s{2,}/g,FINAL_SEMICOLONS:/;\}/g,NOT_WHITESPACE:/\S+/g}; var _4,_5=false; var _6=[]; var _7=function(fn){ if(typeof fn==="function"){ _6[_6.length]=fn; } }; var _8=function(){ for(var i=0;i<_6.length;i++){ _6[i](_4); } }; var _9={}; var _a=function(n,v){ if(_9[n]){ var _b=_9[n].listeners; if(_b){ for(var i=0;i<_b.length;i++){ _b[i](v); } } } }; var _c=function(_d,_e,_f){ if(ua.ie&&!window.XMLHttpRequest){ window.XMLHttpRequest=function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }; } if(!XMLHttpRequest){ return ""; } var r=new XMLHttpRequest(); try{ r.open("get",_d,true); r.setRequestHeader("X_REQUESTED_WITH","XMLHttpRequest"); } catch(e){ _f(); return; } var _10=false; setTimeout(function(){ _10=true; },5000); document.documentElement.style.cursor="progress"; r.onreadystatechange=function(){ if(r.readyState===4&&!_10){ if(!r.status&&location.protocol==="file:"||(r.status>=200&&r.status<300)||r.status===304||navigator.userAgent.indexOf("Safari")>-1&&typeof r.status==="undefined"){ _e(r.responseText); }else{ _f(); } document.documentElement.style.cursor=""; r=null; } }; r.send(""); }; var _11=function(_12){ _12=_12.replace(_3.REDUNDANT_COMPONENTS,""); _12=_12.replace(_3.REDUNDANT_WHITESPACE,"$1"); _12=_12.replace(_3.MORE_WHITESPACE," "); _12=_12.replace(_3.FINAL_SEMICOLONS,"}"); return _12; }; var _13={mediaQueryList:function(s){ var o={}; var idx=s.indexOf("{"); var lt=s.substring(0,idx); s=s.substring(idx+1,s.length-1); var mqs=[],rs=[]; var qts=lt.toLowerCase().substring(7).split(","); for(var i=0;i<qts.length;i++){ mqs[mqs.length]=_13.mediaQuery(qts[i],o); } var rts=s.match(_3.BLOCKS_INSIDE); if(rts!==null){ for(i=0;i<rts.length;i++){ rs[rs.length]=_13.rule(rts[i],o); } } o.getMediaQueries=function(){ return mqs; }; o.getRules=function(){ return rs; }; o.getListText=function(){ return lt; }; o.getCssText=function(){ return s; }; return o; },mediaQuery:function(s,mql){ s=s||""; var not=false,_14; var exp=[]; var _15=true; var _16=s.match(_3.NOT_WHITESPACE); for(var i=0;i<_16.length;i++){ var _17=_16[i]; if(!_14&&(_17==="not"||_17==="only")){ if(_17==="not"){ not=true; } }else{ if(!_14){ _14=_17; }else{ if(_17.charAt(0)==="("){ var _18=_17.substring(1,_17.length-1).split(":"); exp[exp.length]={mediaFeature:_18[0],value:_18[1]||null}; } } } } return {getList:function(){ return mql||null; },getValid:function(){ return _15; },getNot:function(){ return not; },getMediaType:function(){ return _14; },getExpressions:function(){ return exp; }}; },rule:function(s,mql){ var o={}; var idx=s.indexOf("{"); var st=s.substring(0,idx); var ss=st.split(","); var ds=[]; var dts=s.substring(idx+1,s.length-1).split(";"); for(var i=0;i<dts.length;i++){ ds[ds.length]=_13.declaration(dts[i],o); } o.getMediaQueryList=function(){ return mql||null; }; o.getSelectors=function(){ return ss; }; o.getSelectorText=function(){ return st; }; o.getDeclarations=function(){ return ds; }; o.getPropertyValue=function(n){ for(var i=0;i<ds.length;i++){ if(ds[i].getProperty()===n){ return ds[i].getValue(); } } return null; }; return o; },declaration:function(s,r){ var idx=s.indexOf(":"); var p=s.substring(0,idx); var v=s.substring(idx+1); return {getRule:function(){ return r||null; },getProperty:function(){ return p; },getValue:function(){ return v; }}; }}; var _19=function(el){ if(typeof el.cssHelperText!=="string"){ return; } var o={mediaQueryLists:[],rules:[],selectors:{},declarations:[],properties:{}}; var _1a=o.mediaQueryLists; var ors=o.rules; var _1b=el.cssHelperText.match(_3.BLOCKS); if(_1b!==null){ for(var i=0;i<_1b.length;i++){ if(_1b[i].substring(0,7)==="@media "){ _1a[_1a.length]=_13.mediaQueryList(_1b[i]); ors=o.rules=ors.concat(_1a[_1a.length-1].getRules()); }else{ ors[ors.length]=_13.rule(_1b[i]); } } } var oss=o.selectors; var _1c=function(r){ var ss=r.getSelectors(); for(var i=0;i<ss.length;i++){ var n=ss[i]; if(!oss[n]){ oss[n]=[]; } oss[n][oss[n].length]=r; } }; for(i=0;i<ors.length;i++){ _1c(ors[i]); } var ods=o.declarations; for(i=0;i<ors.length;i++){ ods=o.declarations=ods.concat(ors[i].getDeclarations()); } var ops=o.properties; for(i=0;i<ods.length;i++){ var n=ods[i].getProperty(); if(!ops[n]){ ops[n]=[]; } ops[n][ops[n].length]=ods[i]; } el.cssHelperParsed=o; _4[_4.length]=el; return o; }; var _1d=function(el,s){ el.cssHelperText=_11(s||el.innerHTML); return _19(el); }; var _1e=function(){ _5=true; _4=[]; var _1f=[]; var _20=function(){ for(var i=0;i<_1f.length;i++){ _19(_1f[i]); } var _21=document.getElementsByTagName("style"); for(i=0;i<_21.length;i++){ _1d(_21[i]); } _5=false; _8(); }; var _22=document.getElementsByTagName("link"); for(var i=0;i<_22.length;i++){ var _23=_22[i]; if(_23.getAttribute("rel").indexOf("style")>-1&&_23.href&&_23.href.length!==0&&!_23.disabled){ _1f[_1f.length]=_23; } } if(_1f.length>0){ var c=0; var _24=function(){ c++; if(c===_1f.length){ _20(); } }; var _25=function(_26){ var _27=_26.href; _c(_27,function(_28){ _28=_11(_28).replace(_3.RELATIVE_URLS,"url("+_27.substring(0,_27.lastIndexOf("/"))+"/$1)"); _26.cssHelperText=_28; _24(); },_24); }; for(i=0;i<_1f.length;i++){ _25(_1f[i]); } }else{ _20(); } }; var _29={mediaQueryLists:"array",rules:"array",selectors:"object",declarations:"array",properties:"object"}; var _2a={mediaQueryLists:null,rules:null,selectors:null,declarations:null,properties:null}; var _2b=function(_2c,v){ if(_2a[_2c]!==null){ if(_29[_2c]==="array"){ return (_2a[_2c]=_2a[_2c].concat(v)); }else{ var c=_2a[_2c]; for(var n in v){ if(v.hasOwnProperty(n)){ if(!c[n]){ c[n]=v[n]; }else{ c[n]=c[n].concat(v[n]); } } } return c; } } }; var _2d=function(_2e){ _2a[_2e]=(_29[_2e]==="array")?[]:{}; for(var i=0;i<_4.length;i++){ _2b(_2e,_4[i].cssHelperParsed[_2e]); } return _2a[_2e]; }; domReady(function(){ var els=document.body.getElementsByTagName("*"); for(var i=0;i<els.length;i++){ els[i].checkedByCssHelper=true; } if(document.implementation.hasFeature("MutationEvents","2.0")||window.MutationEvent){ document.body.addEventListener("DOMNodeInserted",function(e){ var el=e.target; if(el.nodeType===1){ _a("DOMElementInserted",el); el.checkedByCssHelper=true; } },false); }else{ setInterval(function(){ var els=document.body.getElementsByTagName("*"); for(var i=0;i<els.length;i++){ if(!els[i].checkedByCssHelper){ _a("DOMElementInserted",els[i]); els[i].checkedByCssHelper=true; } } },1000); } }); var _2f=function(d){ if(typeof window.innerWidth!="undefined"){ return window["inner"+d]; }else{ if(typeof document.documentElement!="undefined"&&typeof document.documentElement.clientWidth!="undefined"&&document.documentElement.clientWidth!=0){ return document.documentElement["client"+d]; } } }; return {addStyle:function(s,_30){ var el=document.createElement("style"); el.setAttribute("type","text/css"); document.getElementsByTagName("head")[0].appendChild(el); if(el.styleSheet){ el.styleSheet.cssText=s; }else{ el.appendChild(document.createTextNode(s)); } el.addedWithCssHelper=true; if(typeof _30==="undefined"||_30===true){ cssHelper.parsed(function(_31){ var o=_1d(el,s); for(var n in o){ if(o.hasOwnProperty(n)){ _2b(n,o[n]); } } _a("newStyleParsed",el); }); }else{ el.parsingDisallowed=true; } return el; },removeStyle:function(el){ return el.parentNode.removeChild(el); },parsed:function(fn){ if(_5){ _7(fn); }else{ if(typeof _4!=="undefined"){ if(typeof fn==="function"){ fn(_4); } }else{ _7(fn); _1e(); } } },mediaQueryLists:function(fn){ cssHelper.parsed(function(_32){ fn(_2a.mediaQueryLists||_2d("mediaQueryLists")); }); },rules:function(fn){ cssHelper.parsed(function(_33){ fn(_2a.rules||_2d("rules")); }); },selectors:function(fn){ cssHelper.parsed(function(_34){ fn(_2a.selectors||_2d("selectors")); }); },declarations:function(fn){ cssHelper.parsed(function(_35){ fn(_2a.declarations||_2d("declarations")); }); },properties:function(fn){ cssHelper.parsed(function(_36){ fn(_2a.properties||_2d("properties")); }); },broadcast:_a,addListener:function(n,fn){ if(typeof fn==="function"){ if(!_9[n]){ _9[n]={listeners:[]}; } _9[n].listeners[_9[n].listeners.length]=fn; } },removeListener:function(n,fn){ if(typeof fn==="function"&&_9[n]){ var ls=_9[n].listeners; for(var i=0;i<ls.length;i++){ if(ls[i]===fn){ ls.splice(i,1); i-=1; } } } },getViewportWidth:function(){ return _2f("Width"); },getViewportHeight:function(){ return _2f("Height"); }}; }(); domReady(function enableCssMediaQueries(){ var _37; var _38={LENGTH_UNIT:/[0-9]+(em|ex|px|in|cm|mm|pt|pc)$/,RESOLUTION_UNIT:/[0-9]+(dpi|dpcm)$/,ASPECT_RATIO:/^[0-9]+\/[0-9]+$/,ABSOLUTE_VALUE:/^[0-9]*(\.[0-9]+)*$/}; var _39=[]; var _3a=function(){ var id="css3-mediaqueries-test"; var el=document.createElement("div"); el.id=id; var _3b=cssHelper.addStyle("@media all and (width) { #"+id+" { width: 1px !important; } }",false); document.body.appendChild(el); var ret=el.offsetWidth===1; _3b.parentNode.removeChild(_3b); el.parentNode.removeChild(el); _3a=function(){ return ret; }; return ret; }; var _3c=function(){ _37=document.createElement("div"); _37.style.cssText="position:absolute;top:-9999em;left:-9999em;"+"margin:0;border:none;padding:0;width:1em;font-size:1em;"; document.body.appendChild(_37); if(_37.offsetWidth!==16){ _37.style.fontSize=16/_37.offsetWidth+"em"; } _37.style.width=""; }; var _3d=function(_3e){ _37.style.width=_3e; var _3f=_37.offsetWidth; _37.style.width=""; return _3f; }; var _40=function(_41,_42){ var l=_41.length; var min=(_41.substring(0,4)==="min-"); var max=(!min&&_41.substring(0,4)==="max-"); if(_42!==null){ var _43; var _44; if(_38.LENGTH_UNIT.exec(_42)){ _43="length"; _44=_3d(_42); }else{ if(_38.RESOLUTION_UNIT.exec(_42)){ _43="resolution"; _44=parseInt(_42,10); var _45=_42.substring((_44+"").length); }else{ if(_38.ASPECT_RATIO.exec(_42)){ _43="aspect-ratio"; _44=_42.split("/"); }else{ if(_38.ABSOLUTE_VALUE){ _43="absolute"; _44=_42; }else{ _43="unknown"; } } } } } var _46,_47; if("device-width"===_41.substring(l-12,l)){ _46=screen.width; if(_42!==null){ if(_43==="length"){ return ((min&&_46>=_44)||(max&&_46<_44)||(!min&&!max&&_46===_44)); }else{ return false; } }else{ return _46>0; } }else{ if("device-height"===_41.substring(l-13,l)){ _47=screen.height; if(_42!==null){ if(_43==="length"){ return ((min&&_47>=_44)||(max&&_47<_44)||(!min&&!max&&_47===_44)); }else{ return false; } }else{ return _47>0; } }else{ if("width"===_41.substring(l-5,l)){ _46=document.documentElement.clientWidth||document.body.clientWidth; if(_42!==null){ if(_43==="length"){ return ((min&&_46>=_44)||(max&&_46<_44)||(!min&&!max&&_46===_44)); }else{ return false; } }else{ return _46>0; } }else{ if("height"===_41.substring(l-6,l)){ _47=document.documentElement.clientHeight||document.body.clientHeight; if(_42!==null){ if(_43==="length"){ return ((min&&_47>=_44)||(max&&_47<_44)||(!min&&!max&&_47===_44)); }else{ return false; } }else{ return _47>0; } }else{ if("device-aspect-ratio"===_41.substring(l-19,l)){ return _43==="aspect-ratio"&&screen.width*_44[1]===screen.height*_44[0]; }else{ if("color-index"===_41.substring(l-11,l)){ var _48=Math.pow(2,screen.colorDepth); if(_42!==null){ if(_43==="absolute"){ return ((min&&_48>=_44)||(max&&_48<_44)||(!min&&!max&&_48===_44)); }else{ return false; } }else{ return _48>0; } }else{ if("color"===_41.substring(l-5,l)){ var _49=screen.colorDepth; if(_42!==null){ if(_43==="absolute"){ return ((min&&_49>=_44)||(max&&_49<_44)||(!min&&!max&&_49===_44)); }else{ return false; } }else{ return _49>0; } }else{ if("resolution"===_41.substring(l-10,l)){ var res; if(_45==="dpcm"){ res=_3d("1cm"); }else{ res=_3d("1in"); } if(_42!==null){ if(_43==="resolution"){ return ((min&&res>=_44)||(max&&res<_44)||(!min&&!max&&res===_44)); }else{ return false; } }else{ return res>0; } }else{ return false; } } } } } } } } }; var _4a=function(mq){ var _4b=mq.getValid(); var _4c=mq.getExpressions(); var l=_4c.length; if(l>0){ for(var i=0;i<l&&_4b;i++){ _4b=_40(_4c[i].mediaFeature,_4c[i].value); } var not=mq.getNot(); return (_4b&&!not||not&&!_4b); } }; var _4d=function(mql){ var mqs=mql.getMediaQueries(); var t={}; for(var i=0;i<mqs.length;i++){ if(_4a(mqs[i])){ t[mqs[i].getMediaType()]=true; } } var s=[],c=0; for(var n in t){ if(t.hasOwnProperty(n)){ if(c>0){ s[c++]=","; } s[c++]=n; } } if(s.length>0){ _39[_39.length]=cssHelper.addStyle("@media "+s.join("")+"{"+mql.getCssText()+"}",false); } }; var _4e=function(_4f){ for(var i=0;i<_4f.length;i++){ _4d(_4f[i]); } if(ua.ie){ document.documentElement.style.display="block"; setTimeout(function(){ document.documentElement.style.display=""; },0); setTimeout(function(){ cssHelper.broadcast("cssMediaQueriesTested"); },100); }else{ cssHelper.broadcast("cssMediaQueriesTested"); } }; var _50=function(){ for(var i=0;i<_39.length;i++){ cssHelper.removeStyle(_39[i]); } _39=[]; cssHelper.mediaQueryLists(_4e); }; var _51=0; var _52=function(){ var _53=cssHelper.getViewportWidth(); var _54=cssHelper.getViewportHeight(); if(ua.ie){ var el=document.createElement("div"); el.style.position="absolute"; el.style.top="-9999em"; el.style.overflow="scroll"; document.body.appendChild(el); _51=el.offsetWidth-el.clientWidth; document.body.removeChild(el); } var _55; var _56=function(){ var vpw=cssHelper.getViewportWidth(); var vph=cssHelper.getViewportHeight(); if(Math.abs(vpw-_53)>_51||Math.abs(vph-_54)>_51){ _53=vpw; _54=vph; clearTimeout(_55); _55=setTimeout(function(){ if(!_3a()){ _50(); }else{ cssHelper.broadcast("cssMediaQueriesTested"); } },500); } }; window.onresize=function(){ var x=window.onresize||function(){ }; return function(){ x(); _56(); }; }(); }; var _57=document.documentElement; _57.style.marginLeft="-32767px"; setTimeout(function(){ _57.style.marginTop=""; },20000); return function(){ if(!_3a()){ cssHelper.addListener("newStyleParsed",function(el){ _4e(el.cssHelperParsed.mediaQueryLists); }); cssHelper.addListener("cssMediaQueriesTested",function(){ if(ua.ie){ _57.style.width="1px"; } setTimeout(function(){ _57.style.width=""; _57.style.marginLeft=""; },0); cssHelper.removeListener("cssMediaQueriesTested",arguments.callee); }); _3c(); _50(); }else{ _57.style.marginLeft=""; } _52(); }; }()); try{ document.execCommand("BackgroundImageCache",false,true); } catch(e){ }
JavaScript