How to use selectfile method in Cypress

Best JavaScript code snippet using cypress

select-file.js

Source:select-file.js Github

copy

Full Screen

...384                obj.appendIcos(json.data);385                obj.total = parseInt(json.total);386                obj.totalpage = Math.ceil(obj.total / obj.perpage);387            } else {388                obj = new _selectfile(json.sid, json.data, json.param);389                if (_selectfile.selectall.container !== '_selectfile-' + json.sid) {390                    _selectfile.selectall = {391                        position: {},392                        container: '',393                        icos: []394                    };395                }396                obj.showIcos();397            }398            obj.url = url;399            //修改初始化时的排列方式指示400            jQuery('.icons-thumbnail').attr('iconview', obj.view).find('.dzz').removeClass('dzz-view-module').removeClass('dzz-view-list').addClass(obj.view === 2 ? 'dzz-view-list' : 'dzz-view-module');401            jQuery('.icons-thumbnail').attr('iconview', obj.view).find('.dzz').attr('data-original-title', obj.view === 2 ? __lang.deltail_lsit : __lang.medium_icons);402            jQuery('.icons-thumbnail').attr('folderid', obj.id);...

Full Screen

Full Screen

test-shuffl-card-selectfile.js

Source:test-shuffl-card-selectfile.js Github

copy

Full Screen

1/**2 * @fileoverview3 *  Test suite for 00-skeleton4 *  5 * @author Graham Klyne6 * @version $Id: test-shuffl-card-selectfile.js 840 2010-06-18 09:50:42Z gk-google@ninebynine.org $7 * 8 * Coypyright (C) 2010, University of Oxford9 *10 * Licensed under the MIT License.  You may obtain a copy of the license at:11 *12 *     http://www.opensource.org/licenses/mit-license.php13 *14 * Unless required by applicable law or agreed to in writing, software15 * distributed under the License is distributed on an "AS IS" BASIS,16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.17 * See the License for the specific language governing permissions and18 * limitations under the License.19 */20/**21 * Test suite for free text card functions22 */23/**24 * Data25 */26var testcardselectfile_carddata = 27    { 'shuffl:id':        'card_N'28    , 'shuffl:type':      'shuffl-selectfile-ZZZZZZ'29    , 'shuffl:version':   '0.1'30    , 'shuffl:base-uri':  '#'31    , 'shuffl:uses-prefixes':32      [ { 'shuffl:prefix':  'shuffl', 'shuffl:uri': 'http://purl.org/NET/Shuffl/vocab#' }33      , { 'shuffl:prefix':  'rdf',    'shuffl:uri': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' }34      , { 'shuffl:prefix':  'rdfs',   'shuffl:uri': 'http://www.w3.org/2000/01/rdf-schema#' }35      , { 'shuffl:prefix':  'owl',    'shuffl:uri': 'http://www.w3.org/2002/07/owl#' }36      , { 'shuffl:prefix':  'xsd',    'shuffl:uri': 'http://www.w3.org/2001/XMLSchema#' }37      ]38    , 'shuffl:data':39      { 'shuffl:title':   "Card N title"40      , 'shuffl:fileuri': "./file"41      }42    };43var baseuri = jQuery.uri("..").toString();44/**45 * Function to register tests46 */47TestCardSelectfile = function() {48    module("TestCardSelectfile");49    // Figure base URI based on page URI50    var pageuri = jQuery.uri().toString();51    var baseuri = null;52    var webdav_root = null;53    var baseuri_list =54        [ "http://localhost/webdav/shuffl/static/test/"55        , "http://zoo-samos.zoo.ox.ac.uk/webdav/shuffl/static/test/"56        ];57    var webdav_root_list =58        [ "/webdav/shuffl/static/test/"59        , "/webdav/shuffl/static/test/"60        ];61    for (i in baseuri_list)62    {63        var b = baseuri_list[i];64        if (shuffl.starts(b, pageuri))65        {66            baseuri = b;67            webdav_root = webdav_root_list[i];68        }69    }70    var basepath = shuffl.uriPath(baseuri);71    // Check we have a suitable base URI72    test("NOTE: this test must be run from the web server used to store shuffl workspace data", function ()73    {74        logtest("TestCardSelectfile source check");75        if (!baseuri)76        {77            ok(baseuri, "TestCardSelectfile must be served from WebDAV location");78            throw "TestSaveWorkspace must be served from WebDAV location";79        }80    });81    test("TestCardSelectfile(init)", function ()82    {83        logtest("TestCardSelectfile(init)");84        shuffl.resetStorageHandlers();85        shuffl.addStorageHandler( 86            { uri:      "file:///"87            , name:     "LocalFile"88            , factory:  shuffl.LocalFileStorage89            });90        shuffl.addStorageHandler( 91            { uri:      "http://localhost/test/"92            , name:     "LocalFile"93            , factory:  shuffl.LocalFileStorage94            });95        shuffl.addStorageHandler(96            { uri:      "http://zoo-samos.zoo.ox.ac.uk/webdav/shuffl/static/test/"97            , name:     "WebDAVsamos"98            , factory:  shuffl.WebDAVStorage99            });100        shuffl.addStorageHandler(101            { uri:      "http://localhost/webdav/shuffl/static/test/"102            , name:     "WebDAVlocalhost"103            , factory:  shuffl.WebDAVStorage104            });105        log.debug("Storage handlers: "+jQuery.toJSON(shuffl.listStorageHandlers()));106        ok(true, "TestCardSelectfile storage handlers initialized");107    });108    test("shuffl.addCardFactories",109        function () {110            logtest("TestCardSelectfile: shuffl.addCardFactories");111            // Card factories are created when shuffl-card-selectfile module is loaded112            equals(shuffl.CardFactoryMap['shuffl-selectfile'].cardcss, "stock-default", "shuffl-selectfile");113        });114    115    test("shuffl.getCardFactories",116        function () {117            logtest("TestCardSelectfile: shuffl.getCardFactories");118            var c0 = shuffl.getCardFactory("default-type");119            equals(typeof c0, "function", "default factory");120            var c1 = shuffl.getCardFactory("shuffl-selectfile");121            equals(typeof c1, "function", "retrieved selectfile factory");122        });123    test("shuffl.card.selectfile.newCard",124        function () {125            logtest("TestCardSelectfile: shuffl.card.selectfile.newCard");126            var css = 'stock-default';127            var c   = shuffl.card.selectfile.newCard("shuffl-selectfile", css, "card-1",128                { 'shuffl:title':    "card-title"129                , 'shuffl:fileuri':  baseuri+"testdir/test-csv.csv"130                });131            equals(c.attr('id'), "card-1", "card id attribute");132            //ok(c.hasClass('shuffl-card'),   "shuffl card class");133            ok(c.hasClass('shuffl-card-setsize'), "shuffl-card-setsize class");134            ok(c.hasClass('stock-default'),       "stock-default class");135            ok(c.hasClass('shuffl-selectfile'),   "shuffl-selectfile class");136            equals(c.attr('class'), 'shuffl-card-setsize shuffl-selectfile stock-default ui-resizable', "CSS class");137            ok(c.hasClass('stock-default'), "default colour class");138            equals(c.find("ctitle").text(), "card-title", "card title field");139            // Created with dummy values140            equals(c.find("ccoll").text(), "(collection path)", "collection path field");141            equals(c.find("clist > cdir").text(), "(dir)/", "collection content listing field (dir)");142            equals(c.find("clist > cname").text(), "(filename)", "collection content listing field (name)");143            equals(c.find("cfile").text(), "(filename)", "file name field");144            equals(c.find("cclose > button").text(),  "Close",  "Close button text");            145            equals(c.find("ccancel > button").text(), "Cancel", "Cancel button text");            146            ok(c.find("ccancel > button").is(":hidden"), "Cancel button hidden");            147            // Later, after card has been placed, values are updated to reflect supplied data148            setTimeout( function()149                {150                    equals(c.find("ccoll").text(), basepath+"testdir/", "collection path field");151                    // TODO: Work out what to do about .svn/ directory152                    equals(c.find("clist").text(), "../.svn/directory/test-csv.csv", "collection content listing field");153                    equals(c.find("cfile").text(), "test-csv.csv", "file name field");154                    start();155                },156                500);157            stop(2500);                158    });159    160    test("shuffl.createStockpiles",161        function () {162            logtest("TestCardSelectfile: shuffl.createStockpiles");163            equals(jQuery('#stockbar').children().length, 1, "old stockbar content");164            var s1 = shuffl.createStockpile(165                "stock_1", "stock-default", "File", "shuffl-selectfile");166            equals(jQuery('#stockbar').children().length, 3, "new stockbar content");167            //1168            equals(s1.attr('id'), "stock_1", "stock 1 id");169            ok(s1.hasClass("stock-default"), "stock 1 class");170            equals(s1.text(), "File", "stock 1 label");171            equals(typeof s1.data('makeCard'), "function", "stock 1 function");172            equals(s1.data('CardType'), "shuffl-selectfile", "stock 1 type");173    });174    test("shuffl.createCardFromStock",175        function () {176            logtest("TestCardSelectfile: shuffl.createCardFromStock");177            var s = shuffl.createStockpile(178                      "stock_id", "stock-default", "File", "shuffl-selectfile");179            var c = shuffl.createCardFromStock(jQuery("#stock_id"));180            ////log.debug("- card "+shuffl.objectString(c));181            var card_id = shuffl.lastId("card_");182            equals(c.attr('id'), card_id,       "card id attribute");183            ok(c.hasClass('shuffl-card'),   "shuffl card class");184            ok(c.hasClass('shuffl-card-setsize'), "shuffl-card-setsize class");185            ok(c.hasClass('stock-default'),       "stock-default class");186            ok(c.hasClass('shuffl-selectfile'),   "shuffl-selectfile class");187            equals(c.attr('class'), 'shuffl-card-setsize shuffl-selectfile stock-default ui-resizable shuffl-card', "CSS class");188            equals(c.find("ctitle").text(),     card_id, "card title field");189            equals(c.find("ccoll").text(), "(collection path)", "collection path field");190            equals(c.find("clist > cdir").text(), "(dir)/", "collection content listing field (dir)");191            equals(c.find("clist > cname").text(), "(filename)", "collection content listing field (name)");192            equals(c.find("cfile").text(), "(filename)", "file name field");            193            // Check saved card data194            var d = testcardselectfile_carddata;195            equals(c.data('shuffl:id'),    card_id, "layout card id");196            equals(c.data('shuffl:type' ), "shuffl-selectfile", "saved card type");197            equals(c.data('shuffl:title'),    card_id, "shuffl:title");198            equals(c.data('shuffl:fileuri'),  baseuri, "shuffl:fileuri");199            equals(c.data('shuffl:collpath'), "", "shuffl:collpath");200            equals(c.data('shuffl:filename'), "", "shuffl:filename");201            equals(c.data('shuffl:external')['shuffl:id'],          card_id, "card data id");202            equals(c.data('shuffl:external')['shuffl:type'],        "shuffl-selectfile", "card data class");203            equals(c.data('shuffl:external')['shuffl:version'],     d['shuffl:version'], "card data version");204            equals(c.data('shuffl:external')['shuffl:base-uri'],    d['shuffl:base-uri'], "card data base-uri");205            same(c.data('shuffl:external')['shuffl:uses-prefixes'], d['shuffl:uses-prefixes'], "card data uses-prefixes");206            equals(c.data('shuffl:external')['shuffl:data'],        undefined, "card data");207            setTimeout( function()208                {209                    equals(c.find("ccoll").text(), basepath, "collection path field");210                    equals(c.find("cfile").text(), "(Double-click to edit)", "file name field");211                    equals(c.data('shuffl:collpath'), basepath, "shuffl:collpath");212                    equals(c.data('shuffl:filename'), "", "shuffl:filename");213                    start();214                },215                500);216            stop(2500);217        });218    test("shuffl.createCardFromData",219        function () {220            logtest("TestCardSelectfile: shuffl.createCardFromData");221            var d = testcardselectfile_carddata;222            var c = shuffl.createCardFromData("cardfromdata_id", "shuffl-selectfile", d);223            // Check card details224            equals(c.attr('id'), "cardfromdata_id", "card id attribute");225            ok(c.hasClass('shuffl-card-setsize'), "shuffl card class");226            ok(c.hasClass('stock-default'),     "CSS class");227            equals(c.find("ctitle").text(),     "Card N title", "card title field");228            equals(c.find("ccoll").text(), "(collection path)", "collection path field");229            equals(c.find("clist > cdir").text(), "(dir)/", "collection content listing field (dir)");230            equals(c.find("clist > cname").text(), "(filename)", "collection content listing field (name)");231            equals(c.find("cfile").text(), "(filename)", "file name field");            232            // Check saved card data233            var d = testcardselectfile_carddata;234            equals(c.data('shuffl:id'),       "cardfromdata_id", "layout card id");235            equals(c.data('shuffl:type' ),    "shuffl-selectfile", "saved card type");236            equals(c.data('shuffl:title'),    "Card N title", "shuffl:title");237            equals(c.data('shuffl:fileuri'),  baseuri+"file", "shuffl:fileuri");238            equals(c.data('shuffl:collpath'), "", "shuffl:collpath");239            equals(c.data('shuffl:filename'), "", "shuffl:filename");240            same(c.data('shuffl:external'),   d,  "card data");241            setTimeout( function()242                {243                    equals(c.find("ccoll").text(), basepath, "collection path field");244                    equals(c.find("cfile").text(), "file", "file name field");245                    equals(c.data('shuffl:collpath'), basepath, "shuffl:collpath");246                    equals(c.data('shuffl:filename'), "file", "shuffl:filename");247                    start();248                },249                500);250            stop(2500);             251        });252    test("shuffl.createDataFromCard",253        function () {254            logtest("TestCardSelectfile: shuffl.createDataFromCard");255            // Create card (copy of code already tested)256            var d = testcardselectfile_carddata;257            var c = shuffl.createCardFromData("cardfromdata_id", "shuffl-selectfile", d);258            // (Re)create data and test259            var e = shuffl.createDataFromCard(c);260            setTimeout( function()261                {262                    equals(e['shuffl:id'],          "cardfromdata_id",         'shuffl:id');263                    equals(e['shuffl:type'],        "shuffl-selectfile",       'shuffl:type' );264                    equals(e['shuffl:version'],     d['shuffl:version'],       'shuffl:version');265                    equals(e['shuffl:base-uri'],    d['shuffl:base-uri'],      'shuffl:base-uri');266                    same(e['shuffl:uses-prefixes'], d['shuffl:uses-prefixes'], 'shuffl:uses-prefixes');267                    equals(e['shuffl:data']['shuffl:title'], "Card N title",   'shuffl:data-title');268                    equals(e['shuffl:data']['shuffl:fileuri'], baseuri+"file", 'shuffl:fileuri');269                    for ( k in e['shuffl:data'] )270                    {271                        ok( d['shuffl:data'][k] != undefined, "Unexpected serialized data "+k);272                    }273                    start();274                },275                500);276            stop(2500);             277        });278    var checkFileList = function (card, tag, baseuri, files, types)279        {280            var filelist = card.data('shuffl:filelist');281            equals(filelist.length, files.length, "shuffl:filelist.length ("+tag+")");282            for ( var i = 0 ; (i < files.length) && (i < filelist.length) ; i++ )283            {284                var fileuri = jQuery.uri(files[i], baseuri).toString();285                equals(filelist[i].uri,    fileuri,  "shuffl:filelist["+i+"].uri");286                equals(filelist[i].relref, files[i], "shuffl:filelist["+i+"].relref");287                equals(filelist[i].type,   types[i], "shuffl:filelist["+i+"].type");288            }289        };290    test("shuffl.card.selectfile model 'shuffl:collpath' setting",291        function () {292		    var nextcallback;293            logtest("TestCardSelectfile: shuffl.card.selectfile model 'shuffl:collpath' setting");294            expect(72);295            // Create card (copy of code already tested)296            var d = testcardselectfile_carddata;297            var c = shuffl.createCardFromData("cardfromdata_id", "shuffl-selectfile", d);298            var m = new shuffl.AsyncComputation();299            m.eval(function(val,callback) {300                // Continue testing after card is fully initialized301                setTimeout(callback, 500);302            });303            m.eval(function(val,callback) {304                // Check updatable values305                equals(c.find("ctitle").text(), "Card N title", "card title field");306                equals(c.data('shuffl:collpath'), basepath, "shuffl:collpath");307                equals(c.data('shuffl:filename'), "file",   "shuffl:filename");308                // Simulate user input: set model to update title309                c.model("shuffl:title", "Card N updated");310                equals(c.find("ctitle").text(), "Card N updated", "updated title field");311                // Update collection path with new directory312                nextcallback = callback;313                c.modelBind("shuffl:filelist", nextcallback);314                c.model("shuffl:collpath", "testdir/");315            });316            m.eval(function(val,callback) {317                c.modelUnbind("shuffl:filelist", nextcallback);318                var files = ["../", ".svn/", "directory/", "test-csv.csv"];319                var types = ["collection", "collection", "collection", "item"];320                equals(c.data('shuffl:collpath'), basepath+"testdir/", "shuffl:collpath");321                checkFileList(c, "path:testdir", baseuri+"testdir/", files, types);322                equals(c.data('shuffl:filename'), "file", "shuffl:filename");323                // Update collection path with new filename324                c.model("shuffl:collpath", "newfile");325                // No refresh of file list this time..326                callback(val);327            })328            m.eval(function(val,callback) {329                c.modelUnbind("shuffl:filelist", nextcallback);330                var files = ["../", ".svn/", "directory/", "test-csv.csv"];331                var types = ["collection", "collection", "collection", "item"];332                equals(c.data('shuffl:collpath'), basepath+"testdir/", "shuffl:collpath");333                checkFileList(c, "path:testdir", baseuri+"testdir/", files, types);334                equals(c.data('shuffl:filename'), "newfile", "shuffl:filename");335                // Update collection path with new directory and filename336                nextcallback = callback;337                c.modelBind("shuffl:filelist", nextcallback);338                c.model("shuffl:collpath", "directory/file3.c");339            }); 340            m.eval(function(val,callback) {341                c.modelUnbind("shuffl:filelist", nextcallback);342                var files = ["../", ".svn/", "file1.a", "file1.b", "file2.a"];343                var types = ["collection", "collection", "item", "item", "item"];344                equals(c.data('shuffl:collpath'), basepath+"testdir/directory/", "shuffl:collpath");345                checkFileList(c, "path:testdir", baseuri+"testdir/directory/", files, types);346                equals(c.data('shuffl:filename'), "file3.c", "shuffl:filename");347                equals(c.find("ccoll").text(), basepath+"testdir/directory/", "<ccoll>");348                // Update collection path with new directory and filename349                nextcallback = callback;350                c.modelBind("shuffl:filelist", nextcallback);351                c.model("shuffl:collpath", basepath+"testdir/directory/../");352            }); 353            m.eval(function(val,callback) {354                c.modelUnbind("shuffl:filelist", nextcallback);355                var files = ["../", ".svn/", "directory/", "test-csv.csv"];356                var types = ["collection", "collection", "collection", "item"];357                equals(c.data('shuffl:collpath'), basepath+"testdir/", "shuffl:collpath");358                checkFileList(c, "path:testdir", baseuri+"testdir/", files, types);359                equals(c.data('shuffl:filename'), "file3.c", "shuffl:filename");360                equals(c.find("ccoll").text(), basepath+"testdir/", "<ccoll>");361                // Update collection path with non-existent directory362                nextcallback = callback;363                c.modelBind("shuffl:filelist", nextcallback);364                c.model("shuffl:collpath", "../testdir/nosuchdirectory/");365            }); 366            m.eval(function(val,callback) {367                c.modelUnbind("shuffl:filelist", nextcallback);368                var files = [];369                var types = [];370                equals(c.data('shuffl:collpath'), basepath+"testdir/nosuchdirectory/", "shuffl:collpath");371                checkFileList(c, "path:testdir", baseuri+"testdir/nosuchdirectory/", files, types);372                equals(c.data('shuffl:filename'), "file3.c", "shuffl:filename");373                callback(val);374            }); 375            m.exec({}, start);376            stop(2500);377    });378    test("shuffl.card.selectfile model 'shuffl:filename' setting",379        function () {380            var nextcallback;381            logtest("TestCardSelectfile: shuffl.card.selectfile model 'shuffl:filename' setting");382            expect(55);383            // Create card (copy of code already tested)384            var d = testcardselectfile_carddata;385            var c = shuffl.createCardFromData("cardfromdata_id", "shuffl-selectfile", d);386            var m = new shuffl.AsyncComputation();387            m.eval(function(val,callback) {388                // Continue testing after card is fully initialized389                setTimeout(callback, 500);390            });391            m.eval(function(val,callback) {392                // Check updatable values393                equals(c.find("ctitle").text(), "Card N title", "card title field");394                equals(c.data('shuffl:collpath'), basepath, "shuffl:collpath");395                equals(c.data('shuffl:filename'), "file",   "shuffl:filename");396                // Simulate user input: set model to update title397                c.model("shuffl:title", "Card N updated");398                equals(c.find("ctitle").text(), "Card N updated", "updated title field");399                // Update collection path with new directory400                nextcallback = callback;401                c.modelBind("shuffl:filelist", nextcallback);402                c.model("shuffl:filename", "testdir/");403            });404            m.eval(function(val,callback) {405                c.modelUnbind("shuffl:filelist", nextcallback);406                var files = ["../", ".svn/", "directory/", "test-csv.csv"];407                var types = ["collection", "collection", "collection", "item"];408                equals(c.data('shuffl:collpath'), basepath+"testdir/", "shuffl:collpath");409                checkFileList(c, "path:testdir", baseuri+"testdir/", files, types);410                equals(c.data('shuffl:filename'), "", "shuffl:filename");411                // Update collection path with new filename412                c.model("shuffl:filename", "newfile");413                // No refresh of file list this time..414                callback(val);415            })416            m.eval(function(val,callback) {417                c.modelUnbind("shuffl:filelist", nextcallback);418                var files = ["../", ".svn/", "directory/", "test-csv.csv"];419                var types = ["collection", "collection", "collection", "item"];420                equals(c.data('shuffl:collpath'), basepath+"testdir/", "shuffl:collpath");421                checkFileList(c, "path:testdir", baseuri+"testdir/", files, types);422                equals(c.data('shuffl:filename'), "newfile", "shuffl:filename");423                // Update collection path with new directory and filename424                nextcallback = callback;425                c.modelBind("shuffl:filelist", nextcallback);426                c.model("shuffl:filename", "directory/file3.c");427            }); 428            m.eval(function(val,callback) {429                c.modelUnbind("shuffl:filelist", nextcallback);430                var files = ["../", ".svn/", "file1.a", "file1.b", "file2.a"];431                var types = ["collection", "collection", "item", "item", "item"];432                equals(c.data('shuffl:collpath'), basepath+"testdir/directory/", "shuffl:collpath");433                checkFileList(c, "path:testdir", baseuri+"testdir/directory/", files, types);434                equals(c.data('shuffl:filename'), "file3.c", "shuffl:filename");435                // Update collection path with non-existent directory436                nextcallback = callback;437                c.modelBind("shuffl:filelist", nextcallback);438                c.model("shuffl:filename", "../nosuchdirectory/file");439            }); 440            m.eval(function(val,callback) {441                c.modelUnbind("shuffl:filelist", nextcallback);442                var files = [];443                var types = [];444                equals(c.data('shuffl:collpath'), basepath+"testdir/nosuchdirectory/", "shuffl:collpath");445                checkFileList(c, "path:testdir", baseuri+"testdir/nosuchdirectory/", files, types);446                equals(c.data('shuffl:filename'), "file", "shuffl:filename");447                callback(val);448            }); 449            m.exec({}, start);450            stop(2500);451    });452    test("shuffl.card.selectfile model 'shuffl:filelist' selection",453        function () {454        var nextcallback;455            logtest("TestCardSelectfile: shuffl.card.selectfile model 'shuffl:filelist' selection");456            expect(52);457            // Create card (copy of code already tested)458            var d = testcardselectfile_carddata;459            var c = shuffl.createCardFromData("cardfromdata_id", "shuffl-selectfile", d);460            var m = new shuffl.AsyncComputation();461            m.eval(function(val,callback) {462                // Continue testing after card is fully initialized463                setTimeout(callback, 500);464            });465            m.eval(function(val,callback) {466                // Check updatable values467                equals(c.find("ctitle").text(), "Card N title", "card title field");468                equals(c.data('shuffl:collpath'), basepath, "shuffl:collpath");469                equals(c.data('shuffl:filename'), "file",   "shuffl:filename");470                // Simulate user input: set model to update title471                c.model("shuffl:title", "Card N updated");472                equals(c.find("ctitle").text(), "Card N updated", "updated title field");473                // Update collection path with new directory474                nextcallback = callback;475                c.modelBind("shuffl:filelist", nextcallback);476                c.model("shuffl:filename", "testdir/");477            });478            m.eval(function(val,callback) {479                c.modelUnbind("shuffl:filelist", nextcallback);480                var files = ["../", ".svn/", "directory/", "test-csv.csv"];481                var types = ["collection", "collection", "collection", "item"];482                equals(c.data('shuffl:collpath'), basepath+"testdir/", "shuffl:collpath");483                checkFileList(c, "path:testdir", baseuri+"testdir/", files, types);484                equals(c.data('shuffl:filename'), "", "shuffl:filename");485                // simulate click on file486                c.model("shuffl:filelistelem", 3);487                callback(val);488            });489            m.eval(function(val,callback) {490                c.modelUnbind("shuffl:filelist", nextcallback);491                var files = ["../", ".svn/", "directory/", "test-csv.csv"];492                var types = ["collection", "collection", "collection", "item"];493                equals(c.data('shuffl:collpath'), basepath+"testdir/", "shuffl:collpath");494                checkFileList(c, "path:testdir", baseuri+"testdir/", files, types);495                equals(c.data('shuffl:filename'), "test-csv.csv", "shuffl:filename");496                // simulate click on dir497                nextcallback = callback;498                c.modelBind("shuffl:filelist", nextcallback);499                c.model("shuffl:filelistelem", 2);500            });501            m.eval(function(val,callback) {502                c.modelUnbind("shuffl:filelist", nextcallback);503                var files = ["../", ".svn/", "file1.a", "file1.b", "file2.a"];504                var types = ["collection", "collection", "item", "item", "item"];505                equals(c.data('shuffl:collpath'), basepath+"testdir/directory/", "shuffl:collpath");506                checkFileList(c, "path:testdir", baseuri+"testdir/directory/", files, types);507                // Preserve filename when selecting directory:508                equals(c.data('shuffl:filename'), "test-csv.csv", "shuffl:filename");509                callback(val);510            });511            m.exec({}, start);512            stop(2500);513    });514    test("shuffl.card.selectfile model non-webdav path setting",515        function () {516            var nextcallback;517            logtest("TestCardSelectfile: shuffl.card.selectfile non-webdav path setting");518            expect(27);519            // Create card (copy of code already tested)520            var d = testcardselectfile_carddata;521            var c = shuffl.createCardFromData("cardfromdata_id", "shuffl-selectfile", d);522            var m = new shuffl.AsyncComputation();523            var savelist = null;524            m.eval(function(val,callback) {525                // Continue testing after card is fully initialized526                setTimeout(callback, 500);527            });528            m.eval(function(val,callback) {529                // Check updatable values530                equals(c.find("ctitle").text(),     "Card N title", "card title field");531                equals(c.data('shuffl:collpath'), basepath, "shuffl:collpath");532                equals(c.data('shuffl:filename'), "file",   "shuffl:filename");533                // Update collection path with new directory534                nextcallback = callback;535                c.modelBind("shuffl:filelist", nextcallback);536                c.model("shuffl:collpath", webdav_root+"data/");537            });538            m.eval(function(val,callback) {539                c.modelUnbind("shuffl:filelist", nextcallback);540                equals(c.data('shuffl:collpath'), webdav_root+"data/", "shuffl:collpath");541                equals(c.data('shuffl:filename'), "file", "shuffl:filename");542                savelist = c.data('shuffl:filelist');543                // Update collection path with out-of-webdav path544                c.model("shuffl:collpath", webdav_root+"data/../../");545                nextcallback = callback;546                setTimeout(callback, 500);547            })548            m.eval(function(val,callback) {549                c.modelUnbind("shuffl:filelist", nextcallback);550                equals(c.data('shuffl:collpath'), webdav_root+"data/", "shuffl:collpath (.../data/../..)");551                equals(c.data('shuffl:filename'), "file", "shuffl:filename");552                same(c.data('shuffl:filelist'), savelist, "shuffl:filelist unchanged");553                // Update collection path with new directory554                c.model("shuffl:collpath", "../../");555                nextcallback = callback;556                setTimeout(callback, 500);557            })558            m.eval(function(val,callback) {559                c.modelUnbind("shuffl:filelist", nextcallback);560                equals(c.data('shuffl:collpath'), webdav_root+"data/", "shuffl:collpath (http://localhost/test/)");561                equals(c.data('shuffl:filename'), "file", "shuffl:filename");562                same(c.data('shuffl:filelist'), savelist, "shuffl:filelist unchanged");563                // Try valid session but without canList capability564                try565                {566                    c.model("shuffl:collpath", "http://localhost/test/");567                    ok(true, "No exception setting shuffl:collpath = http://localhost/test/");568                }569                catch (e)570                {571                    log.error("Exception setting shuffl:collpath = http://localhost/test/: "+e);572                    ok(false, "Exception setting shuffl:collpath = http://localhost/test/: "+e);573                }574                nextcallback = callback;575                setTimeout(callback, 500);576            });577            m.eval(function(val,callback) {578                c.modelUnbind("shuffl:filelist", nextcallback);579                equals(c.data('shuffl:collpath'), webdav_root+"data/", "shuffl:collpath (http://localhost/test/)");580                equals(c.data('shuffl:filename'), "file", "shuffl:filename");581                same(c.data('shuffl:filelist'), savelist, "shuffl:filelist unchanged");582                // Update collection path with new directory without listable parent583                try584                {585                    c.model("shuffl:collpath", webdav_root);586                    ok(true, "No exception setting shuffl:collpath = "+webdav_root);587                }588                catch (e)589                {590                    log.error("Exception setting shuffl:collpath = "+webdav_root+": "+e);591                    ok(false, "Exception setting shuffl:collpath = "+webdav_root+": "+e);592                }593                nextcallback = callback;594                setTimeout(callback, 500);595            });596            m.eval(function(val,callback) {597                c.modelUnbind("shuffl:filelist", nextcallback);598                equals(c.data('shuffl:collpath'), webdav_root, "shuffl:collpath (webdav_root)");599                equals(c.data('shuffl:filename'), "file", "shuffl:filename");600                // Check listing does not include "../" entry601                try602                {603                    var files = [".svn/", "data/", "images/"];604                    var types = ["collection", "collection", "collection"];605                    var filelist = c.data('shuffl:filelist').slice(0, 3);606                    for ( var i = 0 ; i < 3 ; i++ )607                    {608                        equals(filelist[i].uri,    baseuri+files[i], "shuffl:filelist["+i+"].uri");609                        equals(filelist[i].relref, files[i],         "shuffl:filelist["+i+"].relref");610                        equals(filelist[i].type,   types[i],         "shuffl:filelist["+i+"].type");611                    }612                }613                catch(e)614                {615                    ok(false, "Exception: "+e);616                };617                callback(val);618            }); 619            m.exec({}, start);620            stop(5000);621    });622    test("shuffl.card.selectfile.closeClicked",623        function () {624            logtest("TestCardSelectfile: shuffl.card.selectfile.closeClicked");625            expect(8);626            // Create card (copy of code already tested)627            var d = testcardselectfile_carddata;628            var c = shuffl.createCardFromData("cardfromdata_id", "shuffl-selectfile", d);629            var m = new shuffl.AsyncComputation();630            m.eval(function(val,callback) {631                // Continue testing after card is fully initialized632                setTimeout(callback, 500);633            });634            m.eval(function(val,callback) {635                // Check updatable values636                equals(c.find("ctitle").text(),     "Card N title", "card title field");637                equals(c.data('shuffl:collpath'), basepath, "shuffl:collpath");638                equals(c.data('shuffl:filename'), "file",   "shuffl:filename");639                // Update collection path with new directory640                nextcallback = callback;641                c.modelBind("shuffl:filelist", nextcallback);642                c.model("shuffl:collpath", webdav_root+"data/closevalue");643            });644            m.eval(function(val,callback) {645                c.modelUnbind("shuffl:filelist", nextcallback);646                equals(c.data('shuffl:collpath'), webdav_root+"data/", "shuffl:collpath (data)");647                equals(c.data('shuffl:filename'), "closevalue", "shuffl:filename");648                // Simulate click on close button649                nextcallback = function (event, val) { callback(val); };650                c.modelBind("shuffl:closeUri", nextcallback);651                c.model("shuffl:close", "-");652            });653            m.eval(function(val,callback) {654                c.modelUnbind("shuffl:closeUri", nextcallback);655                equals(val.name,              "shuffl:closeUri",         "shuffl:closeUri (name)");656                equals(val.oldval,            undefined,                 "shuffl:closeUri (oldval)");657                equals(val.newval.toString(), baseuri+"data/closevalue", "shuffl:closeUri (newval)");658                callback(val);659            });660            m.exec({}, start);661            stop(2500);             662        });663    test("shuffl.card.selectfile callbacks",664        function () {665            logtest("TestCardSelectfile: shuffl.card.selectfile callbacks");666            expect(45);667            // Create card (copy of code already tested)668            var d = testcardselectfile_carddata;669            var c = shuffl.createCardFromData("cardfromdata_id", "shuffl-selectfile", d);670            var m = new shuffl.AsyncComputation();671            // Set up listener on filename changes672            var furi = null;673            var fcount = 0;674            c.modelBind("shuffl:fileuri",675                function (event, val)676                {677                    log.debug("Selectfile shuffl:fileuri changed "+val.newval);678                    furi = val;679                    fcount++;680                });681            // Set up listener for final URI on closing682            var curi = null;683            c.modelBind("shuffl:closeUri",684                function (event, val)685                {686                    log.debug("Selectfile shuffl:closeUri changed "+val.newval);687                    curi = val;688                });689            // Continue testing after card is fully initialized690            m.eval(function(val,callback) {691                setTimeout(callback, 500);692            });693            m.eval(function(val,callback) {694                equals(c.find("ctitle").text(),              "Card N title", "card title field");695                equals(c.data('shuffl:collpath'),            basepath,       "shuffl:collpath");696                equals(c.data('shuffl:filename'),            "file",         "shuffl:filename");697                equals(c.data('shuffl:fileuri').toString(),  baseuri+"file", "shuffl:fileuri");698                equals(c.data('shuffl:closeUri'),            undefined,      "shuffl:closeUri");699                callback(val);700            });701            // Set directory702            m.eval(function(val,callback) {703                nextcallback = callback;704                c.modelBind("shuffl:filelist", nextcallback);705                c.model("shuffl:collpath", basepath+"testdir/");706            });707            m.eval(function(val,callback) {708                c.modelUnbind("shuffl:filelist", nextcallback);709                equals(c.data('shuffl:collpath'),           basepath+"testdir/",     "shuffl:collpath (1)");710                equals(c.data('shuffl:filename'),           "file",                  "shuffl:filename (1)");711                equals(c.data('shuffl:fileuri').toString(), baseuri+"testdir/file",  "shuffl:fileuri  (1)");712                equals(c.data('shuffl:closeUri'),           undefined,               "shuffl:closeUri (1)");713                equals(fcount,                 3,                      "fcount      (1)");714                equals(furi.name,              'shuffl:fileuri',       "furi.name   (1)");715                equals(furi.oldval.toString(), baseuri+"file",         "furi.oldval (1)");716                equals(furi.newval.toString(), baseuri+"testdir/file", "furi.newval (1)");717                equals(curi,                   null,                   "curi        (1)");718                callback(val);719            });720            // Set filename721            m.eval(function(val,callback) {722                c.model("shuffl:filename", "newfile");723                callback(val);    // No refresh of file list this time..724            });725            m.eval(function(val,callback) {726                equals(c.data('shuffl:collpath'), basepath+"testdir/", "shuffl:collpath (2)");727                equals(c.data('shuffl:filename'), "newfile",           "shuffl:filename (2)");728                equals(fcount,                 4,                         "fcount      (2)");729                equals(furi.name,              'shuffl:fileuri',          "furi.name   (2)");730                equals(furi.oldval.toString(), baseuri+"testdir/file",    "furi.oldval (2)");731                equals(furi.newval.toString(), baseuri+"testdir/newfile", "furi.newval (2)");732                equals(curi,                   null,                      "curi        (2)");733                callback(val);734            });735            // Simulate click on directory (2=directory/)736            m.eval(function(val,callback) {737                nextcallback = callback;738                c.modelBind("shuffl:filelist", nextcallback);739                c.model("shuffl:filelistelem", 2);740            });741            m.eval(function(val,callback) {742                c.modelUnbind("shuffl:filelist", nextcallback);743                equals(c.data('shuffl:collpath'), basepath+"testdir/directory/", "shuffl:collpath (3)");744                equals(c.data('shuffl:filename'), "newfile",                     "shuffl:filename (3)");745                equals(fcount,                 6,                                   "fcount      (3)");746                equals(furi.name,              'shuffl:fileuri',                    "furi.name   (3)");747                equals(furi.newval.toString(), baseuri+"testdir/directory/newfile", "furi.newval (3)");748                equals(curi,                   null,                                "curi        (3)");749                callback(val);750            });751            // Simulate click on filename (3=file1.a)752            m.eval(function(val,callback) {753                c.model("shuffl:filelistelem", 4);754                callback(val);    // No refresh of file list this time..755            });756            m.eval(function(val,callback) {757                equals(c.data('shuffl:collpath'), basepath+"testdir/directory/", "shuffl:collpath (4)");758                equals(c.data('shuffl:filename'), "file2.a",                     "shuffl:filename (4)");759                equals(fcount,                 7,                                    "fcount      (4)");760                equals(furi.name,              'shuffl:fileuri',                     "furi.name   (4)");761                equals(furi.oldval.toString(), baseuri+"testdir/directory/newfile",  "furi.oldval (4)");762                equals(furi.newval.toString(), baseuri+"testdir/directory/file2.a",  "furi.newval (4)");763                equals(curi,                   null,                                 "curi        (4)");764                callback(val);765            });766            // Simulate click on close button767            m.eval(function(val,callback) {768                nextcallback = function (event, val) { callback(val); };769                c.modelBind("shuffl:closeUri", nextcallback);770                c.model("shuffl:close", "-");771            });772            m.eval(function(val,callback) {773                c.modelUnbind("shuffl:closeUri", nextcallback);774                equals(c.data('shuffl:collpath'), basepath+"testdir/directory/",       "shuffl:collpath (close)");775                equals(c.data('shuffl:filename'), "file2.a",                           "shuffl:filename (close)");776                equals(c.data('shuffl:fileuri'),  baseuri+"testdir/directory/file2.a", "shuffl:fileuri  (close)");777                equals(c.data('shuffl:closeUri'), baseuri+"testdir/directory/file2.a", "shuffl:closeUri (close)");778                equals(fcount,                 7,                                   "fcount      (close)");779                equals(furi.name,              'shuffl:fileuri',                    "furi.name   (close)");780                equals(furi.oldval.toString(), baseuri+"testdir/directory/newfile", "furi.oldval (close)");781                equals(furi.newval.toString(), baseuri+"testdir/directory/file2.a", "furi.newval (close)");782                equals(curi.name,              'shuffl:closeUri',                   "curi.name   (close)");783                equals(curi.oldval,            undefined,                           "curi.oldval (close)");784                equals(curi.newval.toString(), baseuri+"testdir/directory/file2.a", "curi.newval (close)");785                callback(val);786            });787            m.exec({}, start);788            stop(2000);             789        });790    // Test independent creation and placement of card,791    // alternative label for close button, 792    // and display and activation of cancel button793    test("shuffl.createAndPlaceCard",794        function () {795            logtest("TestCardSelectfile: shuffl.createAndPlaceCard");796            expect(51);797            var c = shuffl.createAndPlaceCard("test_id", "shuffl-selectfile", 798                { 'shuffl:title':   "Test title"799                , 'shuffl:fileuri': baseuri+"testdir/testcsv"800                , 'shuffl:close':   "Test-close"801                , 'shuffl:cancel':  "Test-cancel"802                },803                jQuery("#layout"), 1000, {left:40, top:30}804                );805            // Set up listener on filename changes806            var furi = null;807            var fcount = 0;808            c.modelBind("shuffl:fileuri",809                function (event, val)810                {811                    log.debug("Selectfile shuffl:fileuri changed "+val.newval);812                    furi = val;813                    fcount++;814                });815            // Set up listener for final URI on closing816            var curi = null;817            c.modelBind("shuffl:closeUri",818                function (event, val)819                {820                    log.debug("Selectfile shuffl:closeUri changed "+val.newval);821                    curi = val;822                });823            // Check card details824            ok(c.hasClass('shuffl-card-setsize'), "shuffl card class");825            ok(c.hasClass('stock-default'),       "CSS class");826            equals(c.attr('id'),                      "test_id",           "card id attribute");827            equals(c.find("ctitle").text(),           "Test title",        "card title field");828            equals(c.find("ccoll").text(),            "(collection path)", "collection path field");829            equals(c.find("clist > cdir").text(),     "(dir)/",            "collection content listing field (dir)");830            equals(c.find("clist > cname").text(),    "(filename)",        "collection content listing field (name)");831            equals(c.find("cfile").text(),            "(filename)",        "file name field");            832            equals(c.find("cclose > button").text(),  "Test-close",        "Close button text");            833            equals(c.find("ccancel > button").text(), "Test-cancel",       "Cancel button text");            834            ok(c.find("ccancel > button").is(":visible"), "Cancel button visible");            835            var p = c.position();836            equals(Math.floor(p.left+0.5), 40, "card position-left");837            equals(Math.floor(p.top+0.5),  30, "card position-top");838            range(Math.floor(c.width()),  260, 270, "card width");839            range(Math.floor(c.height()), 130, 132, "card height");840            equals(c.css("zIndex"), "1000", "card zIndex");841            // Continue testing after card is fully initialized842            var m = new shuffl.AsyncComputation();843            m.eval(function(val,callback) {844                setTimeout(callback, 500);845            });846            m.eval(function(val,callback) {847                equals(c.find("ctitle").text(), "Test title",            "card title field");848                equals(c.find("ccoll").text(),  basepath+"testdir/",     "collection path field");849                equals(c.find("clist").text(),  "../.svn/directory/test-csv.csv", "collection content listing field");850                equals(c.find("cfile").text(),  "testcsv",               "file name field");851                equals(c.find("cclose > button").text(),  "Test-close",  "Close button text");            852                equals(c.find("ccancel > button").text(), "Test-cancel", "Cancel button text");            853                ok(c.find("ccancel > button").is(":visible"), "Cancel button visible");            854                callback(val);855            });856            m.eval(function(val,callback) {857                equals(c.data('shuffl:collpath'),            basepath+"testdir/",       "shuffl:collpath");858                equals(c.data('shuffl:filename'),            "testcsv",                 "shuffl:filename");859                equals(c.data('shuffl:fileuri').toString(),  baseuri+"testdir/testcsv", "shuffl:fileuri");860                equals(c.data('shuffl:closeUri'),            undefined,                 "shuffl:closeUri");861                callback(val);862            });863            // Simulate click on directory (2=directory/)864            m.eval(function(val,callback) {865                nextcallback = callback;866                c.modelBind("shuffl:filelist", nextcallback);867                c.model("shuffl:filelistelem", 2);868            });869            m.eval(function(val,callback) {870                c.modelUnbind("shuffl:filelist", nextcallback);871                equals(c.data('shuffl:collpath'), basepath+"testdir/directory/", "shuffl:collpath (3)");872                equals(c.data('shuffl:filename'), "testcsv",                     "shuffl:filename (3)");873                equals(fcount,                 4,                                   "fcount      (3)");874                equals(furi.name,              'shuffl:fileuri',                    "furi.name   (3)");875                equals(furi.newval.toString(), baseuri+"testdir/directory/testcsv", "furi.newval (3)");876                equals(curi,                   null,                                "curi        (3)");877                callback(val);878            });879            // Simulate click on filename (3=file1.a)880            m.eval(function(val,callback) {881                c.model("shuffl:filelistelem", 4);882                callback(val);    // No refresh of file list this time..883            });884            m.eval(function(val,callback) {885                equals(c.data('shuffl:collpath'), basepath+"testdir/directory/", "shuffl:collpath (4)");886                equals(c.data('shuffl:filename'), "file2.a",                     "shuffl:filename (4)");887                equals(fcount,                 5,                                    "fcount      (4)");888                equals(furi.name,              'shuffl:fileuri',                     "furi.name   (4)");889                equals(furi.oldval.toString(), baseuri+"testdir/directory/testcsv",  "furi.oldval (4)");890                equals(furi.newval.toString(), baseuri+"testdir/directory/file2.a",  "furi.newval (4)");891                equals(curi,                   null,                                 "curi        (4)");892                callback(val);893            });894            // Simulate click on cancel button895            m.eval(function(val,callback) {896                nextcallback = function (event, val) { callback(val); };897                c.modelBind("shuffl:closeUri", nextcallback);898                c.model("shuffl:cancel", "-");899            });900            m.eval(function(val,callback) {901                c.modelUnbind("shuffl:closeUri", nextcallback);902                equals(val.name,   "shuffl:closeUri", "shuffl:closeUri (name)");903                equals(val.oldval, undefined,         "shuffl:closeUri (oldval)");904                equals(val.newval, null,              "shuffl:closeUri (newval)");905                setTimeout(callback, 100);906            });907            m.eval(function(val,callback) {908                ok(c.is(":hidden"),  "card hidden  (close)");909                equals(fcount,                 5,                                   "fcount      (close)");910                equals(furi.name,              'shuffl:fileuri',                    "furi.name   (close)");911                equals(furi.oldval.toString(), baseuri+"testdir/directory/testcsv", "furi.oldval (close)");912                equals(furi.newval.toString(), baseuri+"testdir/directory/file2.a", "furi.newval (close)");913                equals(curi.name,              'shuffl:closeUri',                   "curi.name   (close)");914                equals(curi.oldval,            undefined,                           "curi.oldval (close)");915                equals(curi.newval,            null,                                "curi.newval (close)");916                callback(val);917            });918            m.exec({}, start);919            stop(2000);             920        });921};...

Full Screen

Full Screen

selectFile_spec.js

Source:selectFile_spec.js Github

copy

Full Screen

1const { _, $ } = Cypress2// Reading and decoding files from an input element would, in the real world,3// be handled by the application under test, and they would assert on their4// application state. We want to assert on how selectFile behaves directly5// though, and getting the files associated with an <input> as strings is6// handy.7function getFileContents (subject) {8  const decoder = new TextDecoder('utf8')9  const fileContents = _.map(subject[0].files, (f) => {10    return f11    .arrayBuffer()12    .then((c) => decoder.decode(c))13  })14  return Promise.all(fileContents)15}16describe('src/cy/commands/actions/selectFile', () => {17  beforeEach(() => {18    cy.visit('/fixtures/files-form.html')19    cy.wrap(Cypress.Buffer.from('foo')).as('foo')20  })21  context('#selectFile', () => {22    it('selects a single file', () => {23      cy.get('#basic')24      .selectFile({ contents: '@foo', fileName: 'foo.txt' })25      cy.get('#basic')26      .then((input) => {27        expect(input[0].files.length).to.eq(1)28        expect(input[0].files[0].name).to.eq('foo.txt')29        expect(input[0].files[0].type).to.eq('text/plain')30        expect(input[0].files[0].lastModified).to.be.closeTo(Date.now(), 1000)31      })32      cy.get('#basic')33      .then(getFileContents)34      .then((contents) => {35        expect(contents[0]).to.eql('foo')36      })37    })38    it('selects multiple files', () => {39      cy.get('#multiple')40      .selectFile([41        {42          contents: '@foo',43          fileName: 'foo.txt',44        }, {45          contents: Cypress.Buffer.from('{"a":"bar"}'),46          fileName: 'bar.json',47        },48        Cypress.Buffer.from('baz'),49        // 'baz' in ascii50        Uint8Array.from([98, 97, 122]),51      ])52      cy.get('#multiple')53      .should('include.value', 'foo.txt')54      .then((input) => {55        expect(input[0].files[0].name).to.eq('foo.txt')56        expect(input[0].files[1].name).to.eq('bar.json')57        expect(input[0].files[2].name).to.eq('')58        expect(input[0].files[3].name).to.eq('')59      })60      cy.get('#multiple')61      .then(getFileContents)62      .then((contents) => {63        expect(contents[0]).to.eq('foo')64        expect(contents[1]).to.eq('{"a":"bar"}')65        expect(contents[2]).to.eq('baz')66        expect(contents[3]).to.eq('baz')67      })68    })69    it('allows custom lastModified', () => {70      cy.get('#basic').selectFile({71        contents: '@foo',72        lastModified: 1234,73      })74      cy.get('#basic').then((input) => {75        expect(input[0].files[0].lastModified).to.eq(1234)76      })77    })78    it('selects files with an input from a label', () => {79      cy.get('#basic-label').selectFile({ contents: '@foo' })80      cy.get('#basic')81      .then(getFileContents)82      .then((contents) => {83        expect(contents[0]).to.eql('foo')84      })85    })86    it('selects files with an input from a containing label', () => {87      cy.get('#containing-label').selectFile({ contents: '@foo' })88      cy.get('#contained')89      .then(getFileContents)90      .then((contents) => {91        expect(contents[0]).to.eql('foo')92      })93    })94    it('invokes change and input events on the input', (done) => {95      const $input = cy.$$('#basic')96      $input.on('input', (e) => {97        const obj = _.pick(e.originalEvent, 'bubbles', 'cancelable', 'composed', 'target', 'type')98        expect(obj).to.deep.eq({99          bubbles: true,100          cancelable: false,101          composed: true,102          target: $input.get(0),103          type: 'input',104        })105        $input.on('change', (e) => {106          const obj = _.pick(e.originalEvent, 'bubbles', 'cancelable', 'composed', 'target', 'type')107          expect(obj).to.deep.eq({108            bubbles: true,109            cancelable: false,110            composed: false,111            target: $input.get(0),112            type: 'change',113          })114          done()115        })116      })117      cy.get('#basic').selectFile({ contents: '@foo' })118    })119    it('bubbles events', (done) => {120      cy.window().then((win) => {121        $(win).on('input', () => {122          done()123        })124      })125      cy.get('#basic').selectFile({ contents: '@foo' })126    })127    it('invokes events on the input without changing subject when passed a label', (done) => {128      cy.$$('#basic-label').on('input', () => {129        throw new Error('shouldn\'t happen')130      })131      cy.$$('#basic').on('input', () => {132        done()133      })134      cy.get('#basic-label').selectFile({ contents: '@foo' })135      .should('have.id', 'basic-label')136    })137    it('can empty previously filled input', () => {138      cy.get('#basic').selectFile({ contents: '@foo' })139      cy.get('#basic').selectFile([])140      .then((input) => {141        expect(input[0].files.length).to.eq(0)142      })143    })144    it('works with shadow DOMs', () => {145      cy.get('#shadow')146      .shadow()147      .find('input')148      .as('shadowInput')149      .selectFile('@foo')150      cy.get('@shadowInput')151      .then(getFileContents)152      .then((contents) => {153        expect(contents[0]).to.eql('foo')154      })155    })156    it('uses the AUT\'s File constructor', () => {157      cy.window().then(($autWindow) => {158        cy.get('#basic').selectFile('@foo', { action: 'select' }).then((input) => {159          expect(input[0].files[0]).to.be.instanceOf($autWindow.File)160        })161        cy.get('#basic').selectFile('@foo', { action: 'drag-drop' }).then((input) => {162          expect(input[0].files[0]).to.be.instanceOf($autWindow.File)163        })164      })165    })166    describe('shorthands', () => {167      const validJsonString = `{168  "foo": 1,169  "bar": {170    "baz": "cypress"171  }172}173`174      it('works with aliased strings', () => {175        cy.wrap('foobar').as('alias')176        cy.get('#basic').selectFile('@alias')177        .then(getFileContents)178        .then((contents) => {179          expect(contents[0]).to.eql('foobar')180        })181      })182      it('works with aliased objects', () => {183        cy.wrap({ foo: 'bar' }).as('alias')184        cy.get('#basic').selectFile('@alias')185        .then(getFileContents)186        .then((contents) => {187          expect(contents[0]).to.eql('{"foo":"bar"}')188        })189      })190      it('works with aliased fixtures', () => {191        cy.fixture('valid.json').as('myFixture')192        cy.get('#basic').selectFile('@myFixture')193        .then((input) => {194          expect(input[0].files[0].name).to.eq('valid.json')195          expect(input[0].files[0].type).to.eq('application/json')196        })197        .then(getFileContents)198        .then((contents) => {199          // Because json files are loaded as objects, they get reencoded before200          // being used, stripping spaces and newlines201          expect(contents[0]).to.eql('{"foo":1,"bar":{"baz":"cypress"}}')202        })203      })204      // Because this is such an important recipe for users, it gets a separate test205      // even though readFile already has unit tests around reading files as buffers.206      it('works with files read with null encoding', () => {207        cy.readFile('cypress/fixtures/valid.json', { encoding: null }).as('myFile')208        cy.get('#basic').selectFile('@myFile')209        .then((input) => {210          expect(input[0].files[0].name).to.eq('valid.json')211          expect(input[0].files[0].type).to.eq('application/json')212        })213        .then(getFileContents)214        .then((contents) => {215          expect(contents[0]).to.eql(validJsonString)216        })217      })218      it('works with passed in paths', () => {219        cy.get('#multiple').selectFile(['cypress/fixtures/valid.json', 'cypress/fixtures/app.js'])220        .then(getFileContents)221        .then((contents) => {222          expect(contents[0]).to.eql(validJsonString)223          expect(contents[1]).to.eql('{ \'bar\' }\n')224        })225        cy.get('#multiple')226        .should('include.value', 'valid.json')227        .then((input) => {228          expect(input[0].files[0].name).to.eq('valid.json')229          expect(input[0].files[1].name).to.eq('app.js')230          expect(input[0].files[0].type).to.eq('application/json')231          expect(input[0].files[1].type).to.eq('application/javascript')232        })233      })234      it('allows users to override the inferred filenames and mimetypes', () => {235        cy.fixture('valid.json').as('myFixture')236        cy.get('#multiple').selectFile([{237          contents: 'cypress/fixtures/valid.json',238          fileName: '1.png',239        },240        {241          contents: '@myFixture',242          fileName: '2.png',243          mimeType: 'text/plain',244        }])245        .then((input) => {246          expect(input[0].files[0].name).to.eq('1.png')247          expect(input[0].files[1].name).to.eq('2.png')248          // The mimetype should be inferred from the user-supplied filename,249          // rather than the actual path250          expect(input[0].files[0].type).to.eq('image/png')251          // And ever if they supply a filename, explicit mimetype252          // should always take precedent.253          expect(input[0].files[1].type).to.eq('text/plain')254        })255      })256    })257    describe('mime types', () => {258      it('uses empty string for unknown extensions', () => {259        cy.get('#basic')260        .selectFile({ contents: '@foo', fileName: 'foo.barbaz' })261        .then((input) => {262          expect(input[0].files[0].type).to.eq('')263        })264      })265      it('works with several common extensions', () => {266        [267          ['png', 'image/png'],268          ['jpg', 'image/jpeg'],269          ['zip', 'application/zip'],270          ['yaml', 'text/yaml'],271          ['json', 'application/json'],272        ].forEach(([extension, mimeType]) => {273          cy.get('#basic')274          .selectFile({ contents: '@foo', fileName: `foo.${extension}` })275          .then((input) => {276            expect(input[0].files[0].type).to.eq(mimeType)277          })278        })279      })280      it('allows users to specify a mimetype', () => {281        cy.get('#basic')282        .selectFile({ contents: '@foo', fileName: 'foo.zip', mimeType: 'image/png' })283        .then((input) => {284          expect(input[0].files[0].type).to.eq('image/png')285        })286      })287    })288    describe('errors', {289      defaultCommandTimeout: 50,290    }, () => {291      it('is a child command', (done) => {292        cy.on('fail', (err) => {293          expect(err.message).to.include('A child command must be chained after a parent because it operates on a previous subject.')294          done()295        })296        cy.selectFile({ contents: '@foo' })297      })298      it('throws when non dom subject', (done) => {299        cy.on('fail', (err) => {300          expect(err.message).to.include('`cy.selectFile()` failed because it requires a DOM element.')301          done()302        })303        cy.noop({}).selectFile({ contents: '@foo' })304      })305      it('throws when non-input subject', function (done) {306        cy.on('fail', (err) => {307          expect(err.message).to.include('`cy.selectFile()` can only be called on an `<input type="file">` or a `<label for="fileInput">` pointing to or containing one. Your subject is: `<body>...</body>`')308          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')309          done()310        })311        cy.get('body').selectFile({ contents: '@foo' })312      })313      it('throws when non-file input', function (done) {314        cy.on('fail', (err) => {315          expect(err.message).to.include('`cy.selectFile()` can only be called on an `<input type="file">` or a `<label for="fileInput">` pointing to or containing one. Your subject is: `<input type="text" id="text-input">`')316          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')317          done()318        })319        cy.get('#text-input').selectFile({ contents: '@foo' })320      })321      it('throws when label for non-file input', function (done) {322        cy.on('fail', (err) => {323          expect(err.message).to.include('`cy.selectFile()` can only be called on an `<input type="file">` or a `<label for="fileInput">` pointing to or containing one. Your subject is: `<label for="text-input" id="text-label">Text label</label>`')324          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')325          done()326        })327        cy.get('#text-label').selectFile({ contents: '@foo' })328      })329      it('throws when label without an attached input', function (done) {330        // Even though this label contains a file input, testing on real browsers confirms that clicking it331        // does *not* activate the contained input.332        cy.on('fail', (err) => {333          expect(err.message).to.include('`cy.selectFile()` can only be called on an `<input type="file">` or a `<label for="fileInput">` pointing to or containing one. Your subject is: `<label for="nonexistent" id="nonexistent-label">...</label>`')334          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')335          done()336        })337        cy.get('#nonexistent-label').selectFile({ contents: '@foo' })338      })339      it('throws when subject is collection of elements', function (done) {340        cy.on('fail', (err) => {341          expect(err.message).to.include('`cy.selectFile()` can only be called on a single element. Your subject contained')342          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')343          done()344        })345        cy.get('input[type="file"]').selectFile({ contents: '@foo' })346      })347      it('throws when no arguments given', function (done) {348        cy.on('fail', (err) => {349          expect(err.message).to.include('`cy.selectFile()` must be passed a Buffer or an object with a non-null `contents` property as its 1st argument. You passed: `undefined`.')350          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')351          done()352        })353        cy.get('#basic').selectFile()354      })355      it('throws when file is null', function (done) {356        cy.on('fail', (err) => {357          expect(err.message).to.include('`cy.selectFile()` must be passed a Buffer or an object with a non-null `contents` property as its 1st argument. You passed: `null`.')358          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')359          done()360        })361        cy.get('#basic').selectFile(null)362      })363      it('throws when single file.contents is null', function (done) {364        cy.on('fail', (err) => {365          expect(err.message).to.include('`cy.selectFile()` must be passed a Buffer or an object with a non-null `contents` property as its 1st argument. You passed: `{"contents":null}`.')366          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')367          done()368        })369        cy.get('#basic').selectFile({ contents: null })370      })371      it('throws when file is an unknown alias', function (done) {372        cy.on('fail', (err) => {373          expect(err.message).to.include('`cy.selectFile()` could not find a registered alias for: `@unknown`.')374          done()375        })376        cy.get('#basic').selectFile('@unknown')377      })378      it('throws when file is an alias for a DOM node', function (done) {379        cy.on('fail', (err) => {380          expect(err.message).to.include('`cy.selectFile()` can only attach strings, Buffers or objects, while your alias `@body` resolved to: `<body>...</body>`.')381          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')382          done()383        })384        cy.get('body').as('body')385        cy.get('#basic').selectFile('@body')386      })387      it('throws when file is an alias for null', function (done) {388        cy.on('fail', (err) => {389          expect(err.message).to.include('`cy.selectFile()` can only attach strings, Buffers or objects, while your alias `@null` resolved to: `null`.')390          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')391          done()392        })393        cy.wrap(null).as('null')394        cy.get('#basic').selectFile('@null')395      })396      it('throws with aliased intercepts', function (done) {397        cy.on('fail', (err) => {398          expect(err.message).to.include('`cy.selectFile()` can only attach strings, Buffers or objects, while your alias `@postUser` resolved to: `null`.')399          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')400          done()401        })402        cy.intercept('POST', '/users', {}).as('postUser')403        cy.get('#basic').selectFile('@postUser')404      })405      it('throws when any path does not exist', function (done) {406        cy.on('fail', (err) => {407          expect(err.message).to.include('`cy.selectFile("this/file/doesNotExist.json")` failed because the file does not exist at the following path:')408          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')409          done()410        })411        cy.get('#basic').selectFile(['cypress/fixtures/valid.json', 'this/file/doesNotExist.json'])412      })413      it('throws when any file\'s contents is undefined', function (done) {414        cy.on('fail', (err) => {415          expect(err.message).to.include('`cy.selectFile()` must be passed an array of Buffers or objects with non-null `contents`. At files[1] you passed: `{}`.')416          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')417          done()418        })419        cy.get('#basic').selectFile([{ contents: '@foo' }, {}])420      })421      it('throws on invalid action', function (done) {422        cy.on('fail', (err) => {423          expect(err.message).to.include('`cy.selectFile()` `action` can only be `select` or `drag-drop`. You passed: `foobar`.')424          expect(err.docsUrl).to.eq('https://on.cypress.io/selectfile')425          done()426        })427        cy.get('#basic').selectFile({ contents: '@foo' }, { action: 'foobar' })428      })429    })430    /*431     * The tests around actionability are somewhat limited, since the functionality is thoroughly tested in the432     * `cy.trigger()` unit tests. We include a few tests directly on `cy.selectFile()` in order to ensure we're433     * using $actionability.verify() properly, but don't extensively exercise the logic within it here.434     *435     * See trigger_spec.js for the full actionability test suite.436     */437    describe('actionability', {438      defaultCommandTimeout: 50,439    }, () => {440      it('selects files with a hidden input from a visible label', () => {441        cy.get('#hidden-label').selectFile({ contents: '@foo' })442        cy.get('#hidden')443        .then(getFileContents)444        .then((contents) => {445          expect(contents[0]).to.eql('foo')446        })447      })448      it('does not work on hidden inputs by default', (done) => {449        cy.on('fail', (err) => {450          expect(err.message).to.include('`cy.selectFile()` failed because this element is not visible')451          done()452        })453        cy.get('#hidden').selectFile({ contents: '@foo' })454      })455      it('can force on hidden inputs', () => {456        cy.get('#hidden').selectFile({ contents: '@foo' }, { force: true })457      })458      it('does not work on covered inputs by default', (done) => {459        cy.on('fail', (err) => {460          expect(err.message).to.include(`\`<input id="covered" type="file">\`461is being covered by another element:462\`<div id="covering"></div>\``)463          done()464        })465        cy.get('#covered').selectFile({ contents: '@foo' })466      })467      it('can force on covered inputs', () => {468        cy.get('#covered').selectFile({ contents: '@foo' }, { force: true })469      })470      it('does not work on disabled inputs by default', (done) => {471        cy.on('fail', (err) => {472          expect(err.message).to.include('`cy.selectFile()` failed because this element is `disabled`')473          done()474        })475        cy.get('#disabled-label').selectFile({ contents: '@foo' })476      })477      it('can force on disabled inputs', () => {478        cy.get('#disabled-label').selectFile({ contents: '@foo' }, { force: true })479      })480      it('does not work on hidden labels by default', (done) => {481        cy.on('fail', (err) => {482          expect(err.message).to.include('`cy.selectFile()` failed because this element is not visible')483          done()484        })485        cy.get('#hidden-basic-label').selectFile({ contents: '@foo' })486      })487      it('can force on hidden labels', () => {488        cy.get('#hidden-basic-label').selectFile({ contents: '@foo' }, { force: true })489      })490      it('can scroll to input', () => {491        const scrolled = []492        cy.on('scrolled', ($el, type) => {493          scrolled.push(type)494        })495        cy.get('#scroll').selectFile({ contents: '@foo' })496        .then(() => {497          expect(scrolled).not.to.be.empty498        })499      })500      it('can scroll to label', () => {501        const scrolled = []502        cy.on('scrolled', ($el, type) => {503          scrolled.push(type)504        })505        cy.get('#scroll-label').selectFile({ contents: '@foo' })506        .then(() => {507          expect(scrolled).not.to.be.empty508        })509      })510      it('does not scroll when forced', () => {511        const scrolled = []512        cy.on('scrolled', ($el, type) => {513          scrolled.push(type)514        })515        cy.get('#scroll-label').selectFile({ contents: '@foo' }, { force: true })516        .then(() => {517          expect(scrolled).to.be.empty518        })519      })520      it('waits until input stops animating', {521        defaultCommandTimeout: 1000,522      }, () => {523        let retries = 0524        cy.on('command:retry', (obj) => {525          retries += 1526        })527        cy.stub(cy, 'ensureElementIsNotAnimating')528        .throws(new Error('animating!'))529        .onThirdCall().returns()530        cy.get('#basic').selectFile({ contents: '@foo' }).then(() => {531          expect(retries).to.eq(3)532          expect(cy.ensureElementIsNotAnimating).to.be.calledThrice533        })534      })535      it('can specify scrollBehavior in options', () => {536        cy.get('#scroll').then((el) => {537          cy.spy(el[0], 'scrollIntoView')538        })539        cy.get('#scroll').selectFile({ contents: '@foo' }, { scrollBehavior: 'bottom' })540        cy.get('#scroll').then((el) => {541          expect(el[0].scrollIntoView).to.be.calledWith({ block: 'end' })542        })543      })544    })545    describe('drag-drop', () => {546      it('attaches a file to an input when targeted', () => {547        cy.get('#basic').selectFile({ contents: '@foo' }, { action: 'drag-drop' })548        cy.get('#basic')549        .then(getFileContents)550        .then((contents) => {551          expect(contents[0]).to.eql('foo')552        })553      })554      it('invokes change and input events on an input when dropped over', (done) => {555        const $input = cy.$$('#basic')556        $input.on('input', (e) => {557          const obj = _.pick(e.originalEvent, 'bubbles', 'cancelable', 'composed', 'target', 'type')558          expect(obj).to.deep.eq({559            bubbles: true,560            cancelable: false,561            composed: true,562            target: $input.get(0),563            type: 'input',564          })565          $input.on('change', (e) => {566            const obj = _.pick(e.originalEvent, 'bubbles', 'cancelable', 'composed', 'target', 'type')567            expect(obj).to.deep.eq({568              bubbles: true,569              cancelable: false,570              composed: false,571              target: $input.get(0),572              type: 'change',573            })574            done()575          })576        })577        cy.get('#basic').selectFile({ contents: '@foo' }, { action: 'drag-drop' })578      })579      it('does not follow labels to their inputs', () => {580        cy.get('#basic-label').selectFile({ contents: '@foo' }, { action: 'drag-drop' })581        cy.get('#basic').then((input) => {582          expect(input[0].files.length).to.eql(0)583        })584      })585      it('does not select multiple files with a single-file input', () => {586        cy.get('#basic').selectFile(['@foo', '@foo'], { action: 'drag-drop' })587        cy.get('#basic').then((input) => {588          expect(input[0].files.length).to.eql(0)589        })590      })591      it('drops files onto any element and triggers events', (done) => {592        const $body = cy.$$('body')593        let events = []594        $body.on('input', (e) => {595          throw new Error('should not trigger input')596        })597        $body.on('change', (e) => {598          throw new Error('should not trigger change')599        })600        $body.on('drag', (e) => events.push(e))601        $body.on('dragenter', (e) => events.push(e))602        $body.on('dragover', (e) => events.push(e))603        $body.on('drop', (e) => {604          events.push(e)605          expect(_.map(events, 'originalEvent.type')).to.deep.eql(['drag', 'dragenter', 'dragover', 'drop'])606          expect(_.every(events, ['originalEvent.bubbles', true])).to.be.true607          expect(_.every(events, ['originalEvent.cancelable', true])).to.be.true608          expect(_.every(events, ['originalEvent.composed', true])).to.be.true609          expect(_.every(events, ['originalEvent.target', $body[0]])).to.be.true610          done()611        })612        cy.get('body').selectFile('@foo', { action: 'drag-drop' })613      })614      it('includes an entry in `dataTransfer.types`', (done) => {615        cy.$$('#multiple').on('drop', (e) => {616          expect(e.originalEvent.dataTransfer.types).to.contain('Files')617          done()618        })619        cy.get('#multiple').selectFile({ contents: '@foo' }, { action: 'drag-drop' })620      })621    })622  })...

Full Screen

Full Screen

letvUpload.js

Source:letvUpload.js Github

copy

Full Screen

1/**2 * Created by 郝少禅3 * Email:sxchying@126.com4 * QQ:4907462375 */6window.html5Upload = (function () {7    var signUploadFlag = false;8    function html5Upload() {9    }10    //添加文件的Option对象11    var addFileOption = {};12    //点击上传的Option对象13    var uploadOption = {};14    var defaults = {15        addFile: function (data) {1617        },18        addFileError: function (data) {1920        }21    };2223    //拓展函数24    (function () {25        //使用jq拓展文件添加函数26        (function ($) {27            var defaults = {28                addFile: function (data) {2930                },31                addFileError: function (data) {3233                }34            };35            $.fn.addFile = function (options) {36                addFileOption = $.extend(defaults, options || {});37                return this.each(function () {38                    $(this).click(uploadFileOperation.addFile);39                });40            };41        })(jQuery);42        //使用jq拓展上传函数43        (function ($) {44            var defaults = {45                uploadInitUrl: "",46                uploadFinish: function (data) {4748                },49                uploadProgress: function (data) {5051                },52                uploadError: function (data) {5354                },55                uploadAbort: function (data) {5657                }58            };59            $.fn.uploadletv = function (options) {60                uploadOption = $.extend(defaults, options || {});61                return this.each(function () {62                    $(this).change(function (data) {63                        //验证选择的文件格式64                        videoUpload.init(data);65                    });66                });67            };68        })(jQuery);69    })();70    //cookie操作71    var uploadCookie = (function () {72        function uploadCookie() {73        }74        uploadCookie.setCookie = function (key, value, expiresDays) {75            var date = new Date();76            date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000);77            document.cookie = key + "=" + value + "; expires=" + date.toGMTString();78        };79        uploadCookie.getCookie = function (key) {80            var strCookie = document.cookie;81            var arrCookie = strCookie.split("; ");82            for (var i = 0; i < arrCookie.length; i++) {83                var arr = arrCookie[i].split("=");84                if (arr[0] == key) {85                    return arr[1];86                }87                if (i == arrCookie.length - 1) {88                    return false;89                }90            }91        };92        uploadCookie.removeCookie = function (key) {93            uploadCookie.setCookie(key, "", -1);94        };95        return uploadCookie;96    })();97    //ajax98    var uploadAjax = (function () {99        function uploadAjax() {100        }101        uploadAjax.post = function (url, success, error) {102            $.ajax({103                url: url,104                type: 'post',105                dataType: "json",106                success: function (data) {107                    success(data);108                },109                error: function (data) {110                    if (error) {111                        error(data);112                    }113                }114            });115        };116        return uploadAjax;117    })();118    //上传回调函数119    var xhrEventCallback = (function () {120        function xhrEventCallback() {121        }122        var getFileType = function (file) {123            return file.name.split(".").pop();124        };125        var getFileKey = function (file) {126            return [getFileType(file), file.size,  (file.lastModifiedDate==null)?0:file.lastModifiedDate.getTime()].join('_');127        };128        xhrEventCallback.loadstart = function (e) {129            var currStack = videoUpload.cellStack;130            currStack.inittime = (new Date()).getTime(); //标记开始 即时的 时间131            var transferedsize = videoUpload.cellStack ? videoUpload.cellStack.transferedsize : 0;132            currStack.transferedsize = transferedsize;133        };134        xhrEventCallback.load = function (e) {135            var res = eval("(" + e.target.responseText + ")");136            if (!!res.transferedsize) {137                //记录断点续传token138                var tokenUrl = videoUpload.uploadUrl.split('token').pop();139                var videoToken = tokenUrl.substr(1, tokenUrl.length - 1).split('&')[0];140                //uploadCookie.setCookie(html5Upload.exportObject.selectFile.fileKey, videoToken, 2);141                var transferedsize = parseInt(res.transferedsize);142                videoUpload.cellStack.transferedsize = transferedsize;143                transferedsize < html5Upload.exportObject.selectFile.file.size && videoUpload.streamUpload(transferedsize);144            }145            else {146                if (!res.totalsize && res.status != '200') {147                    uploadOption.uploadError({ code: res.status, msg: res.msg });148                    //uploadCookie.removeCookie(html5Upload.exportObject.selectFile.fileKey);149                    videoUpload.xhrAbort();150                }151            }152            videoUpload.cellStack.starttime = (new Date()).getTime();153            if (res.transferedsize && res.transferedsize == res.totalsize) {154                //文件上传完成155                uploadOption.uploadFinish({ code: 0, video_unique:html5Upload.exportObject.selectFile.video_unique,msg: "上传完成",filesize:html5Upload.exportObject.selectFile.file.size,video_id:html5Upload.exportObject.selectFile.video_id },getFileKey(html5Upload.exportObject.selectFile.file));156                //uploadCookie.removeCookie(html5Upload.exportObject.selectFile.fileKey);157                videoUpload.xhrAbort();158159                html5Upload.exportObject.selectFile.fileList.splice(0,1);160                if(html5Upload.exportObject.selectFile.fileList.length>0){161                    html5Upload.exportObject.selectFile.file = html5Upload.exportObject.selectFile.fileList[0].file;162                    html5Upload.exportObject.selectFile.fileKey = html5Upload.exportObject.selectFile.fileList[0].fileKey;163                    videoUpload.tryUpload();164                }165            }166        };167        xhrEventCallback.progress = function (e) {168            var cellstack = videoUpload.cellStack, filetransfered = parseInt(cellstack.transferedsize);169            var pc = parseInt((filetransfered + e.loaded) / html5Upload.exportObject.selectFile.file.size * 100), delttime = ((new Date()).getTime() - (cellstack.starttime || cellstack.inittime)) / 1000, rate = e.loaded / delttime;170            rate = rate / 1024;171            var s = html5Upload.exportObject.selectFile.file.size/1024;172            var fileSize = s > 1024 ? (((s / 1024 * 10) >> 0) / 10).toFixed(1) + "M" : (((s * 10) >> 0) / 10).toFixed(1) + "KB";173            rate = rate > 1024 ? (((rate / 1024 * 10) >> 0) / 10).toFixed(1) + "M/s" : (((rate * 10) >> 0) / 10).toFixed(1) + "K/s";174            //在上传过程中如果用户在电脑上删除了视频,会触发视频丢失错误175            if (isNaN(pc)) {176                uploadOption.uploadError({ code: 203, msg: "视频丢失" });177                videoUpload.xhrAbort();178            }179            else {180                if (pc == 100) {181                    pc = 99;182                }183184                uploadOption.uploadProgress({ progress: pc + "%", speed: rate, size:fileSize },getFileKey(html5Upload.exportObject.selectFile.file));185            }186        };187        xhrEventCallback.error = function (e) {188            uploadOption.uploadError({ code: 404, msg: "网络异常" });189            videoUpload.xhrAbort();190        };191        xhrEventCallback.abort = function (e) {192            console.log(e);193            uploadOption.uploadAbort({ code: 202, msg: "中断上传" });194195        };196        return xhrEventCallback;197    })();198    //上传199    var videoUpload = (function () {200        function videoUpload() {201        }202        videoUpload.init = function(data){203            //验证文件的是否满足204            //允许上传的文件类型205            var fileTypes = "wmv|avi|dat|asf|rm|rmvb|ram|mpg|mpeg|mp4|mov|m4v|mkv|flv|vob|qt|divx|cpk|fli|flc|mod|dvix|dv|ts";206            //获取文件的类型207            var getFileType = function (file) {208                return file.name.split(".").pop();209            };210            //获取文件的key211            var getFileKey = function (file) {212                return [getFileType(file), file.size, (file.lastModifiedDate==null)?0:file.lastModifiedDate.getTime()].join('_');213            };214215            for(var i=0;i<data.target.files.length;i++){216                var file = data.target.files[i];217                var fType = getFileType(file);218                if (file.size < 0) {219                    uploadOption.uploadError({ code: 100, msg: file.name+"文件大小为0" });220                    return;221                } else if (!eval("/" + fileTypes + "$/i").test(fType)) {222                    uploadOption.uploadError({ code: 101, msg: file.name+"不支持此视频格式" });223                    return;224                } else if($("#"+getFileKey(data.target.files[i])).is("tr")){225                    uploadOption.uploadError({ code: 102, msg: file.name+"此视频已经存在" });226                    return ;227228                }else{229                    //addFileOption.addFile({ code: 0, msg: "成功", data: { fileName: file.name, fileSize: file.size, fileType: fType } });230                    html5Upload.exportObject.selectFile.fileList = html5Upload.exportObject.selectFile.fileList || [];231                    html5Upload.exportObject.selectFile.fileList.push({"file":file,fileKey:getFileKey(file)});232                    //html5Upload.exportObject.selectFile.file = file;233                    //html5Upload.exportObject.selectFile.fileKey = getFileType(file);234                }235236            }237            uploadOption.uploadBefore(data);238239            //html5Upload.exportObject.selectFile.file = data.target.files[0];240            //html5Upload.exportObject.selectFile.fileKey = getFileKey(data.target.files[0]);241            if(!signUploadFlag){242                html5Upload.exportObject.selectFile.file = html5Upload.exportObject.selectFile.fileList[0].file;243                html5Upload.exportObject.selectFile.fileKey = html5Upload.exportObject.selectFile.fileList[0].fileKey;244                videoUpload.tryUpload();245246            }247        }248        var cellSize = 10485760;249        var xhr = null;250        var tryNum = 0;251        var sliceFile = function (file, start) {252            var blob;253            start = start || 0;254            var range = start + cellSize;255            if (start != -1) {256                if (file.slice) {257                    blob = file.slice(start, range);258                }259                else if (file.webkitSlice) {260                    blob = file.webkitSlice(start, range);261                }262                else if (file.mozSlice) {263                    blob = file.mozSlice(start, range);264                }265                else {266                    blob = file;267                }268            }269            else {270                return null;271            }272            return blob;273        };274        videoUpload.cellStack = {};275        videoUpload.uploadUrl = "";276        videoUpload.streamUpload = function (loadedsize) {277            videoUpload.cellStack.transferedsize = loadedsize;278            xhr = new XMLHttpRequest();279            html5Upload.exportObject.selectFile.xhrAbort = videoUpload.xhrAbort;280            html5Upload.exportObject.selectFile.nextUpload = videoUpload.nextUpload;281            xhr.upload.addEventListener("progress", function (e) { xhrEventCallback.progress(e); }, false);282            xhr.addEventListener("loadstart", function (e) { xhrEventCallback.loadstart(e); }, false);283            xhr.addEventListener("load", function (e) { xhrEventCallback.load(e); }, false);284            xhr.addEventListener("error", function (e) { xhrEventCallback.error(e); }, false);285            xhr.addEventListener("abort", function (e) { xhrEventCallback.abort(e); }, false);286            var cellFile = sliceFile(html5Upload.exportObject.selectFile.file, loadedsize);287            var content = loadedsize == -1 ? "bytes *" : "bytes " + (loadedsize + 1) + "-" + (loadedsize + cellFile.size) + "/" + html5Upload.exportObject.selectFile.file.size;288            xhr.open("POST", videoUpload.uploadUrl, true);289            xhr.setRequestHeader("X_FILENAME", encodeURI(html5Upload.exportObject.selectFile.file.name));290            xhr.setRequestHeader("Content-Range", content);291            xhr.send(cellFile);292        };293        videoUpload.xhrAbort = function () {294            xhr && xhr.abort();295            signUploadFlag = false;296        };297        videoUpload.nextUpload = function () {298            html5Upload.exportObject.selectFile.fileList.splice(0,1);299            if(html5Upload.exportObject.selectFile.fileList.length>0){300                html5Upload.exportObject.selectFile.file = html5Upload.exportObject.selectFile.fileList[0].file;301                html5Upload.exportObject.selectFile.fileKey = html5Upload.exportObject.selectFile.fileList[0].fileKey;302                videoUpload.tryUpload();303            }304        };305        videoUpload.tryUpload = function () {306            signUploadFlag = true;307            var video_name = encodeURIComponent(html5Upload.exportObject.selectFile.file.name);308            var uploadtype = 1;309            var file_size = html5Upload.exportObject.selectFile.file.size;310            var initUrl = uploadOption.uploadInitUrl + "?video_name=" + video_name + "&uploadtype=" + uploadtype + "&file_size=" + file_size;311            if (uploadCookie.getCookie(html5Upload.exportObject.selectFile.fileKey)) {312                initUrl = uploadOption.uploadInitUrl + "?token=" + uploadCookie.getCookie(html5Upload.exportObject.selectFile.fileKey) + "&uploadtype=" + uploadtype;313            }314            try {315                uploadAjax.post(initUrl, function (data) {316                    data = (new Function("return "+data))();317                    if (data.code == 0) {318                        html5Upload.exportObject.selectFile.video_id = data.data.video_id;319                        //html5Upload.exportObject.selectFile.video_id = data.data.video_id+"@@"+data.data.video_unique;320                        html5Upload.exportObject.selectFile.video_unique = data.data.video_unique;321                        tryNum = 0;322                        videoUpload.uploadUrl = data.data.upload_url.split('&')[0];323                        var nextBlob = data.data.upload_size || 0;324                        videoUpload.streamUpload(nextBlob);325                    } else {326                        switch (data.code) {327                            case 112:328                                if (tryNum < 2) {329                                    setTimeout(function () {330                                        videoUpload.tryUpload();331                                    }, 20000);332                                    ++tryNum;333                                } else {334                                    if (tryNum < 3) {335                                        uploadCookie.removeCookie(html5Upload.exportObject.selectFile.fileKey);336                                        ++tryNum;337                                        videoUpload.tryUpload();338                                    } else {339                                        uploadOption.uploadAbort({ code: data.code, msg: data.message });340                                        tryNum = 0;341                                    }342                                }343                                break;344                            default:345                                uploadOption.uploadAbort({ code: data.code, msg: data.message });346                        }347                    }348                }, function (data) {349                    if (tryNum < 3) {350                        setTimeout(function () {351                            videoUpload.tryUpload();352                        }, 1000);353                        ++tryNum;354                    } else {355                        uploadOption.uploadAbort({ code: 206, msg: data.statusText });356                        tryNum = 0;357                    }358                });359            } catch (e) {360                if (tryNum < 3) {361                    setTimeout(function () {362                        videoUpload.tryUpload();363                    }, 1000);364                    ++tryNum;365                } else {366                    uploadOption.uploadAbort({ code: 207, msg: e.message });367                    tryNum = 0;368                }369            }370        };371        return videoUpload;372    })();373    //文件操作374    var uploadFileOperation = (function () {375        function uploadFileOperation() {376        }377        //允许上传的文件类型378        var fileTypes = "wmv|avi|dat|asf|rm|rmvb|ram|mpg|mpeg|mp4|mov|m4v|mkv|flv|vob|qt|divx|cpk|fli|flc|mod|dvix|dv|ts";379        //获取文件的类型380        var getFileType = function (file) {381            return file.name.split(".").pop();382        };383        //获取文件的key384        var getFileKey = function (file) {385            return [uploadFileOperation.getFileType(file), (file.lastModifiedDate==null)?0:file.lastModifiedDate.getTime()].join('_');386        };387        //选中文件的时候388        var inputFileChange = function (e) {389            var file = e.target.files[0];390            var fType = getFileType(file);391            if (file.size < 0) {392                addFileOption.addFileError({ code: 100, msg: "文件大小为0" });393            } else if (!eval("/" + fileTypes + "$/i").test(fType)) {394                addFileOption.addFileError({ code: 101, msg: "不支持此视频格式" });395            } else {396                addFileOption.addFile({ code: 0, msg: "成功", data: { fileName: file.name, fileSize: file.size, fileType: fType } });397                html5Upload.exportObject.selectFile.file = file;398                html5Upload.exportObject.selectFile.fileKey = getFileType(file);399            }400        };401        //添加文件402        uploadFileOperation.addFile = function (e) {403            var inpfile = document.getElementById("fileUploadId_Hsc");404            if (inpfile) {405                inpfile.click && e.target != inpfile && inpfile.click();406            } else {407                inpfile = document.createElement("input");408                $(inpfile).append(inpfile);409                inpfile.setAttribute("id", "fileUploadId_Hsc");410                inpfile.setAttribute("type", "file");411                inpfile.style.display = "none";412                inpfile.addEventListener('change', inputFileChange, !1);413                inpfile.click && e.target != inpfile && inpfile.click();414            }415        };416        return uploadFileOperation;417    })();418    //可供用户访问的属性419    html5Upload.exportObject = (function () {420        function exportObject() {421        }422        //选中的文件对象423        exportObject.selectFile = {};424        return exportObject;425    })();426    return html5Upload;
...

Full Screen

Full Screen

_select.js

Source:_select.js Github

copy

Full Screen

1/*2 * @copyright   Leyun internet Technology(Shanghai)Co.,Ltd3 * @license     http://www.dzzoffice.com/licenses/license.txt4 * @package     DzzOffice5 * @link        http://www.dzzoffice.com6 * @author      zyx(zyx@dzz.cc)7 */8function _select(container)9{10	this.id=this.name=container;11	this.string="_select.icos."+this.id;12	this.board=document.getElementById(container);13	_select.icos[this.id]=this;14};15_select.delay=500;16_select.width=120;17_select.height=120;18_select.icos={};19_select.onmousemove=null;20_select.onmouseup=null;21_select.tach=null;22_select.onselectstart=1;23_select.init=function(container){24	var obj= new _select(container);25	jQuery(obj.board).on('mousedown',function(e){26		27		e=e?e:window.event;28		var tag = e.srcElement ? e.srcElement :e.target;29		30		if(/input|textarea/i.test(tag.tagName)){31			return true;32		}	33		34		if(e.button==2) return true;35		dfire('mousedown');//dfire('touchstart');36		obj.Mousedown(e?e:window.event);37		return true;38	});39        jQuery(obj.board).on('mouseup',function(e){40            e=e?e:window.event;41            var tag = e.srcElement ? e.srcElement :e.target;42            if(/input|textarea/i.test(tag.tagName)){43                return true;44            }45            dfire('mouseup');46            //dfire('touchend');47            obj.Mouseup(e?e:window.event);48            return true;49        });50	return obj;51};52_select.prototype.DetachEvent=function(e)53{54	if(!_select.tach) return;55	//document.body.style.cursor="url('dzz/images/cur/aero_arrow.cur'),auto";56	document.onmousemove=_select.onmousemove;57	document.onmouseup=_select.onmouseup;58	document.onselectstart=_select.onselectstart;59	try{60		if(this.board.releaseCapture) this.board.releaseCapture();61	}catch(e){};62	_select.tach=0;63	_select.finishblank=0;64	65};66_select.prototype.AttachEvent=function(e)67{ 68	if(_select.tach) return69	_select.onmousemove=document.onmousemove;70	_select.onmouseup=document.onmouseup;71	_select.onselectstart=document.onselectstart;72	try{73		document.onselectstart=function(){return false;}74		if(e.preventDefault) e.preventDefault();75		else{76			if(this.board.setCapture) this.board.setCapture();77		}78	}catch(e){};79	_select.tach=1;80};81_select.prototype.Duplicate=function()82{83	this.copy=document.createElement('div');84	85	document.body.appendChild(this.copy);86	this.copy.style.cssText="position:absolute;left:0px;top:0px;width:0px;height:0px;filter:Alpha(opacity=50);opacity:0.5;z-index:10002;overflow:hidden;background:#000;border:1px solid #000;";87	//jQuery(this.copy).find('#text'+this.id).html(' ');88};89_select.prototype.Mousedown=function(e)90{91//	console.log(_explorer.type);92	this.mousedowndoing=false;93	if(e.type=='touchstart'){94		var XX=e.touches[0].clientX;95		var YY=e.touches[0].clientY;96	}else{97		var XX=e.clientX;98		var YY=e.clientY;99	}100	101	_select.oldxx=XX;102	_select.oldyy=YY;103	this.tl=XX;104	this.tt=YY;105	this.oldx=XX;106	this.oldy=YY;107	//alert('down');108	var self=this;109	if(!_select.tach) this.AttachEvent(e);110	111	if(e.type=='touchstart'){112		jQuery(this.board).on('touchmove',function(e){self.Move(e);return false});113	}else{114		document.onmousemove=function(e){self.Move(e?e:window.event);return false};115	}116	117	//this.mousedownTimer=setTimeout(function(){self.PreMove(XX,YY);},200);118};119_select.prototype.Mouseup=function(e)120{121	if(_select.tach) this.DetachEvent(e);122	if(!this.mousedowndoing) {123	}else this.Moved(e);124};125_select.prototype.PreMove=function(e)126{127	jQuery('#_blank').empty().show();128	if (this.move=="no") return;129	this.Duplicate();130	131	var self=this;132	this.mousedowndoing=true;133	var p=jQuery(this.board).offset();134	135	136	this.copy.style.left=this.tl+'px';137	this.copy.style.top=this.tt+'px';138	139	//清空数据140	if(_hotkey.ctrl>0 && _selectfile.selectall.container==this.id){141		142	}else{143		if(_selectfile.selectall.container) jQuery('#'+_selectfile.selectall.container).find('.Icoblock').removeClass('Icoselected');144		_selectfile.selectall.container=this.id;145		_selectfile.selectall.icos=[];146		_selectfile.selectall.position={};147	}148		//计算此容器内的所有ico的绝对位置,并且存入_selectfile.selectall.position中;149		jQuery(this.board).find('.Icoblock').each(function(){150			var el=jQuery(this);151			var p=el.offset();152			var icoid=el.attr('rid');153			if(icoid){154				_selectfile.selectall.position[icoid]={icoid:icoid,left:p.left,top:p.top,width:el.width(),height:el.height()};155			}156		});157	if(e.type=='touchmove'){158		jQuery(this.board).on('touchend',function(e){self.Moved(e);return true});159	}else{160		document.onmouseup=function(e){self.Moved(e?e:window.event);return false;};161	}162};163_select.prototype.Move=function(e)164{165	if(e.type==='touchmove'){166		var XX=e.touches[0].clientX;167		var YY=e.touches[0].clientY;168	}else{169		var XX=e.clientX;170		var YY=e.clientY;171	}172	if(!this.mousedowndoing && (Math.abs(this.oldx-XX)>5 || Math.abs(this.oldy-YY)>5)){173		this.PreMove(e);174	}175	if(!this.mousedowndoing) return;176	var flag=0;177	if(XX-this.oldx>0){178		this.copy.style.width=(XX-this.oldx)+"px";179	}else{180		this.copy.style.width=Math.abs(XX-this.oldx)+"px";181		this.copy.style.left=this.tl+(XX-this.oldx)+"px";182	}183	if(YY-this.oldy>0){184		this.copy.style.height=(YY-this.oldy)+"px";185	}else{186		this.copy.style.height=Math.abs(YY-this.oldy)+"px";187		this.copy.style.top=this.tt+(YY-this.oldy)+"px";188	}189	if(!BROWSER.ie){190		//if(Math.abs(_select.oldxx-XX)>20 || Math.abs(_select.oldyy-YY)>20){191			if(XX>this.oldx && YY > this.oldy){192				if(Math.abs(XX-_select.oldxx)>20 || Math.abs(YY-_select.oldyy)>20){193					 _select.oldxx=XX;194					 _select.oldyy=YY;195					 this.setSelected(true);196				}197			}else{198				if(Math.abs(XX-_select.oldxx)>20 || Math.abs(YY-_select.oldyy)>20){199					 _select.oldxx=XX;200					 _select.oldyy=YY;201					 this.setSelected();202				}203			}204	}205};206_select.prototype.Moved=function(e)207{208	var self=this;209	jQuery('#_blank').hide();210	if(_select.tach)	this.DetachEvent(e);211	if(e.type=='touchend'){212		var XX=e.changedTouches[0].clientX;213		var YY=e.changedTouches[0].clientY;214	}else{215		var XX=e.clientX;216		var YY=e.clientY;217	}218	if(BROWSER.ie){219		if(XX>this.oldx && YY > this.oldy){220			this.setSelected(true);221		}else{222			this.setSelected();223		}224	}225	jQuery(this.copy).remove();226	227};228_select.prototype.setSelected=function(flag){229	_select.sum++;230	var p=jQuery(this.copy).offset();231	var icos=[];232	var copydata={left:p.left,top:p.top,width:jQuery(this.copy).width(),height:jQuery(this.copy).height()};233	for(var icoid in _selectfile.selectall.position){234		var data=_selectfile.selectall.position[icoid];235		if(_select.checkInArea(copydata,data,flag)){236			_select.SelectedStyle(this.id,icoid,true,true);237		}else if(_hotkey.ctrl<1){238			_select.SelectedStyle(this.id,icoid,false,true);239		}240	}241};242_select.checkInArea=function(copydata,data,flag){243	var rect={minx:0,miny:0,maxx:0,maxy:0}244	rect.minx=Math.max(data.left,copydata.left);245	rect.miny =Math.max(data.top,copydata.top) ;246	rect.maxx =Math.min(data.left+data.width,copydata.left+copydata.width) ;247	rect.maxy =Math.min(data.top+data.height,copydata.top+copydata.height) ;248	if(!flag){249		if(rect.minx>rect.maxx || rect.miny>rect.maxy){250			return false;251		}else{252			return true253		}254	}else{255		if(rect.minx>rect.maxx || rect.miny>rect.maxy){256			return false;257		}else{258			return true;259			var area=(rect.maxx-rect.minx)*(rect.maxy-rect.miny);260			var dataarea=data.width*data.height;261			if(dataarea==area) return true;262			else return false;263		}264	}265};266_select.SelectedStyle=function(container,rid,flag,multi){267	var icos=_selectfile.selectall.icos||[];268	var fidarr=container.split('-');269	var fid=parseInt(fidarr[2]);270	var filemanageid=container.replace('filemanage-','');//'f-'+fidarr[2];271	if(flag){272	}273	var el=jQuery('#'+container).find('.Icoblock[rid='+rid+']');274	if(flag){275		if(_selectfile.selectall.container=='') _selectfile.selectall.container=container;276		if(multi  && _selectfile.selectall.container==container){277			if(jQuery.inArray(rid,_selectfile.selectall.icos)<0){278			 	_selectfile.selectall.icos.push(rid);279			}280		}else{281			jQuery('#'+_selectfile.selectall.container).find('.Icoblock').removeClass('Icoselected');282			_selectfile.selectall.container=container;283			_selectfile.selectall.icos=[rid];284			_selectfile.selectall.position={};285		}286		el.addClass('Icoselected');287		288	}else{289		var arr=[];290		if(_selectfile.selectall.container==container){291			for(var i in icos){292				if(icos[i]!=rid) arr.push(icos[i]);293			}294		}295		_selectfile.selectall.icos=arr;296		el.removeClass('Icoselected');	297	}298	if(_selectfile.cons[filemanageid]) _selectfile.cons[filemanageid].selectInfo();299	if(_explorer.type){300		_selectfile.changefileName(rid);301	}302};303_select.Cut=function(icoid){304	//处理原对象 去除样式305	if(_config.cut.iscut>0 && _config.cut.icos.length>0){306		for(var i in _config.cut.icos){307			jQuery('.Icoblock[icoid='+_config.cut.icos[i]+']').removeClass('iscut');308		}309	}310	//添加新对象到剪切板,并且设置剪切样式311	_config.cut.iscut=1;312	if(jQuery.inArray(icoid,_config.selectall.icos)>-1){313		_config.cut.icos=_config.selectall.icos;314	}else{315		_config.cut.icos=[icoid];316	}317	for(var i in _config.cut.icos){318		jQuery('.Icoblock[rid='+_config.cut.icos[i]+']').addClass('iscut');319	}320}321_select.Copy=function(icoid){322	//处理原对象 去除样式323	if(_config.cut.iscut>0 && _config.cut.icos.length>0){324		for(var i in _config.cut.icos){325			jQuery('.Icoblock[icoid='+_config.cut.icos[i]+']').removeClass('iscut');326		}327	}328	//添加新对象到剪切板,并且设置剪切样式329	_config.cut.iscut=0;330	if(jQuery.inArray(icoid,_config.selectall.icos)>-1){331		_config.cut.icos=_config.selectall.icos;332	}else{333		_config.cut.icos=[icoid];334	}335	336}337_select.Paste=function(pfid,XX,YY){338	if(_config.cut.icos.length<1) return ;//剪贴板无数据,返回;339	//判断默认应用不能更换容器340	/*for(var i=0;i<_config.cut.icos.length;i++){341		if(_config.cut.iscut>0 && !_config.Permission('delete',_config.sourcedata.icos[_config.cut.icos[i]])){342			_config.cut.icos.splice(i,1);343			jQuery('.Icoblock[icoid='+_config.cut.icos[i]+']').removeClass('iscut');344			//showPrompt(null,'',_lang.default_app_not_move,1000);345		}346	}*/347	348	//判断容器是否接受此类图标;349	/*if(!_config.Permission_Container(_config.sourcedata.icos[_config.cut.icos[0]].type,pfid)){350			showPrompt(null,'',_lang.paste.paste_in_here_forbidden,1000);351			return ;352	}*/353	//获得目标路径的tbz354	var tbz=_config.sourcedata.folder[pfid].bz||'';355	if(tbz){356		var path=encodeURIComponent(_config.sourcedata.folder[pfid].path);357	}else{358		var path=pfid;359	}360	361	//组织data362	if(_config.sourcedata.icos[_config.cut.icos[0]].bz && _config.sourcedata.icos[_config.cut.icos[0]].bz!=''){363		var paths=[];364		for(var i=0;i<_config.cut.icos.length;i++){365			paths.push((_config.sourcedata.icos[_config.cut.icos[i]].dpath));366		}367		368		var data={"obz":_config.sourcedata.icos[_config.cut.icos[0]].bz,"tbz":tbz,"sourcetype":"icoid","icoid":paths.join(','),"ticoid":0,"container":'icosContainer_folder_'+path,iscut:_config.cut.iscut>0?1:2};369	}else{370		var paths=[];371		for(var i=0;i<_config.cut.icos.length;i++){372			paths.push((_config.sourcedata.icos[_config.cut.icos[i]].dpath));373		}374		var data={"obz":'',"tbz":tbz,"sourcetype":"icoid","icoid":paths.join(','),"ticoid":0,"container":'icosContainer_folder_'+path,iscut:_config.cut.iscut>0?1:2};375	}376	var container=_config.getContainerByFid(pfid);377	378	var progress='<div class="progress progress-striped active" style="margin:0"><div class="bar" style="width:100%;"></div></div>'379	//alert(_config.saveurl+'&do=move&gid='+_config.gid+'&'+jQuery.param(data));380	showmessage('<p>'+__lang.file_drag_processing+'</p>'+progress,'success',0,1,'right-bottom');381	jQuery.getJSON(_config.saveurl+'&do=move&'+jQuery.param(data),function(json){382		if(json.msg=='success'){383			 _config.cut.icos=[];384				_config.cut.successicos=[];385				_config.cut.osuccessicos=[];386				387				for(var ico in json.successicos){388					_config.cut.successicos.push(json.successicos[ico]);389					_config.cut.osuccessicos.push(ico);390					391				}392				if(json.iscopy>0){393					showmessage(__lang.file_copy_success,'success',3000,1,'right-bottom')394					395				}else{396					showmessage(__lang.crop_files_success,'success',3000,1,'right-bottom')397				   _select.remove(_config.cut.osuccessicos);398				  399				}	400				for(var i in json.icoarr){401					_config.sourcedata.icos[json.icoarr[i].icoid]=json.icoarr[i];402				}403				for(var i in json.folderarr){404					_config.sourcedata.folder[json.folderarr[i].fid]=json.folderarr[i];405				}406				_ico.appendIcoids(_config.cut.successicos);407				if(json.error){408					showmessage(__lang.operate_files_error,'error',3000,1,'right-bottom');409				}410				411		}else{412			showmessage(__lang.operate_files_error,'error',3000,1,'right-bottom');413		}414	});415};416_select.remove=function(icos){//移除原来的icoid417	for(var i=0;i<icos.length;i++){418		_ico.removeIcoid(icos[i]);419	}...

Full Screen

Full Screen

IDE-Rotuer.js

Source:IDE-Rotuer.js Github

copy

Full Screen

1import React from 'react';2import FileNavigation from '../modules/File-Navigation';3import Tabs from '../modules/Tabs';4// import Editor from '../modules/Editor';5import Alert from '../modules/Alert';6import Http from '../modules/Http';7import './IDE-Router.scss';8import dummyProjectData from '../dummy-data/project.json';9import AceEditor from 'react-ace';10import "ace-builds/src-noconflict/mode-java";11import "ace-builds/src-noconflict/mode-c_cpp";12import "ace-builds/src-noconflict/theme-monokai";13const SHORT_CUT_ITEM = {14    CLOSE: "close-file-or-editor",15    SAVE: "save-file-and-item",16    CREATE: "create-file-or-item"17}18const shortcuts = [19    { ctrlKey: true, altKey: false, shiftKey: false, key: 'e', eventName: SHORT_CUT_ITEM.CLOSE},20    { ctrlKey: true, altKey: false, shiftKey: false,key: 's', eventName: SHORT_CUT_ITEM.SAVE},21    { ctrlKey: true, altKey: false, shiftKey: false,key: 'm', eventName: SHORT_CUT_ITEM.CREATE}22]23function CreateNewFileBody({project, onChangeName}) {24    const [name, setName] = React.useState("");25    function Directory({files}) {26        const directory = files.map((file, tabSize)=> {27            if(!file.isDirectory) { return; }28            return (29                <>30                    <p style={{"paddingLeft": tabSize*15}}>{file.name}</p>31                    <Directory files={file.files}></Directory>32                </>33            )34        });35        return directory;36    }37    return (38        <>39            <div className="save-modal">40                <div className="directory-structure">41                    <p style={{"paddingLeft": 5}}>/</p>42                    <Directory files={project.files} tabSize={0}/>43                </div>44                <div className="input-form">45                    <label htmlFor="save-modal-name">이름</label>46                    <input id="save-modal-name" type="text" value={name} 47                        onChange={(e)=>{onChangeName(e.target.value); setName(e.target.value)}}/>48                </div>49            </div>50        </>51    )52}53class IDERouter extends React.Component{54    state = { 55        project: { files: [] },56        openFiles: [],57        selectFile: null,58    }59    constructor(props) {60        super(props);61        this.shortcutHandler = this.shortcutHandler.bind(this);62    }63    shortcutHandler(event) {64        const item = shortcuts.find(e => ( e.key === event.key && e.altKey === event.altKey && e.ctrlKey === event.ctrlKey && e.shiftKey === event.shiftKey ));65        if(!item) return;66        event.preventDefault();67        switch(item.eventName) {68            case SHORT_CUT_ITEM.CLOSE:69                this.onCloseFile(this.state.selectFile);70                break;71            case SHORT_CUT_ITEM.SAVE:72                if(this.state.selectFile) this.onSaveFile(this.state.selectFile);73                break;74            case SHORT_CUT_ITEM.CREATE:75                this.onCreateNewFile();76                break;77            default: break;78        }79    }80    componentDidMount() {81        window.addEventListener("keydown", this.shortcutHandler);82        Http.get({path: `/projects/${this.props.match.params.id}`}).then(({ data })=>{83            this.setState({ project: data });84        }).catch(()=>{});85    }86    87    componentWillUnmount() {88        window.removeEventListener("keydown", this.shortcutHandler);89    }90    onChangeText(text) {91        const { openFiles, selectFile } = this.state;92        if(!selectFile) { 93            this.onCreateNewFile(text);94            return; 95        }96        const idx = openFiles.indexOf(selectFile);97        openFiles[idx].data = text;98        openFiles[idx].modify = true;99        this.setState({openFiles});100    }101    createFileIdx = 1;102    onCreateNewFile(text="") {103        const file = {104            name: `undefined-${this.createFileIdx++}`,105            modify: true,106            ext: "",107            data : text108        }109        this.onClickFile(file);110    }111    onClickFile(file) {112        const { openFiles } = this.state;113        const idx = openFiles.indexOf(file);114        if(idx !== -1) { // 파일이 존재 안했을 경우115            this.setState({selectFile: file})116        } else {117            openFiles.push(file);118            this.setState({openFiles, selectFile: file});119        }120    }121    onCloseFile(file) {122        const { openFiles, selectFile } = this.state;123        const idx = openFiles.indexOf(file);124        if(idx === -1) return;125        126        const setNextFile = () => {127            openFiles.splice(idx, 1);128            this.setState({openFiles});129    130            if(selectFile === file) {131                let selectFile;132                if(openFiles.length === 0) { selectFile = null; }133                else if(idx === 0) { selectFile = openFiles[0]; }134                else { selectFile = openFiles[idx - 1] };135    136                this.setState({selectFile});137            }138        }139    140        if(file.modify) {141            Alert({142                title: "저장되지 않았습니다.", 143                text: "저장하시겠습니까?", 144                btns: [145                    {text: "예", onClick: ()=>{146                        this.onSaveFile(file, setNextFile);147                    }},148                    {text: "아니오", onClick: ()=>{149                        setNextFile();150                    }},151                    {text: "취소", onClick: ()=>{}},152                ]153            });154        } else {155            setNextFile();156        }157    }158    onSaveNewFile(file) {159        const { selectFile, project } = this.state;160        selectFile.name = file.name;161        selectFile.modify = false;162        const newFile = {163            fullpath: file.name,164            name: file.name,165            data: file.data,166        };167        168        project.files.push(newFile);169        this.setState({project, selectFile});170    }171    onSaveFile(file, cb=()=>{}) {172        const {project} = this.state;173        function _find(prev, curr) {174            if(curr.fullpath === file.fullpath) return curr;175            if(curr.files) {176                const fileInChildren = curr.files.reduce(_find, undefined);177                if(fileInChildren) return fileInChildren;178            }179            return prev;180        }181        const fileOnProject = project.files.reduce(_find, undefined);182        183        if(fileOnProject) {184            fileOnProject.data = file.data;185            file.modify = false;186            this.setState({project, selectFile: file}, cb);187        } else {188            Alert({189                title: "새 파일 생성",190                text: (<CreateNewFileBody project={this.state.project} onChangeName={(name)=>{file.name = name}}></CreateNewFileBody>),191                btns: [192                    {text: "예", onClick: ()=>{193                        this.onSaveNewFile(file)194                    }},195                    {text: "아니오", onClick: ()=>{}}196                ]197            })198        }199    }200    render() {        201        return (202            <div className="IDE" tabIndex="-1">203              <header>204                <p>dgu-web-ide</p>205              </header>206              <article>207                <FileNavigation className="navigation" 208                    openFiles={this.state.openFiles} files={this.state.project.files}209                    onClick={this.onClickFile.bind(this)} onClose={this.onCloseFile.bind(this)}></FileNavigation>210                <section>211                    <div className="workspace-wrapper">212                        <Tabs className="tab" files={this.state.openFiles} selectFile={this.state.selectFile}213                            onClick={this.onClickFile.bind(this)} onClose={this.onCloseFile.bind(this)}></Tabs>214                        <AceEditor215                            width="100%"216                            height="100%"217                            fontSize={18}218                            mode={this.state.selectFile ? getMode(this.state.selectFile.ext) : ""}219                            theme="monokai"220                            onChange={this.onChangeText.bind(this)}221                            name="UNIQUE_ID_OF_DIV"222                            value={this.state.selectFile ? this.state.selectFile.data : ""}></AceEditor>223                    </div>224                    <div className="console">225                        <textarea className="console" readOnly={true} rows={12} defaultValue={"원을 달라로 바꿉니다. 원을 입력하세요 >> 10000\n변환결과 : 9.90099달러"}></textarea>226                    </div> 227                </section>228              </article>229              <footer>230                  <p></p>231                  <p>Developed by PLASS LAB</p>232              </footer>233            </div>234        );235    }236}237function getMode(ext) {238    switch(ext) {239        case "c": case "cpp":240            return "c_cpp";241        default:242            return ext;243    }244}...

Full Screen

Full Screen

filedialog.js

Source:filedialog.js Github

copy

Full Screen

1'use strict';2(function () {3  4  var Promise = require('./js/promise'),5      path    = require('path');6  angular.module('fileDialog', [])7    .provider('fileDialog', [function () {8        var selectFile = document.createElement('input'),9            selectFiles = document.createElement('input'),10            selectDir = document.createElement('input'),11            saveFile = document.createElement('input');12        selectFile.type = 'file';13        selectFiles.type = 'file';14        selectDir.type = 'file';15        saveFile.type = 'file';16        selectFiles.setAttribute('multiple', '');17        selectDir.setAttribute('nwdirectory', '');18        saveFile.setAttribute('nwsaveas', '');19        selectFiles.style.display = 'none';20        selectFile.style.display = 'none';21        selectDir.style.display = 'none';22        saveFile.style.display = 'none';23        var f = document.createDocumentFragment();24        f.appendChild(selectFiles);25        f.appendChild(selectFile);26        f.appendChild(selectDir);27        f.appendChild(saveFile);28        document.body.appendChild(f);29        var _methods = {};30        // select file31        var lastSelectedPath;32        function selectFileHandler() {33          var files = selectFile.files;34          selectFile.deferred.resolve(files[0]);35          lastSelectedPath = path.dirname(files[0].path);36          selectFile.files = [];37          selectFile.value = '';38        }39        _methods.selectFile = function (defaultPath) {40          selectFile.deferred = new Promise;41          if (defaultPath || lastSelectedPath) {42            selectFile.setAttribute('nwworkingdir', defaultPath || lastSelectedPath);43          }44          selectFile.addEventListener('change', selectFileHandler, false);45          selectFile.click();46          $(window).one('focus', function (evt) {47            if (selectFile.deferred.state === 'pending') {48              selectFile.deferred.reject();49            }50            selectFile.removeEventListener('change', selectFileHandler, false);51          });52          return selectFile.deferred.protect;53        };54        function selectDirHandler() {55          var files = selectDir.files;56          selectDir.deferred.resolve(files[0]);57          lastSelectedPath = path.dirname(files[0].path);58          selectDir.files = [];59          selectDir.value = '';60        }61        _methods.selectDir = function (defaultPath) {62          selectDir.deferred = new Promise;63          if (defaultPath || lastSelectedPath) {64            selectDir.setAttribute('nwworkingdir', defaultPath || lastSelectedPath);65          }66          selectDir.addEventListener('change', selectDirHandler, false);67          selectDir.click();68          $(window).one('focus', function (evt) {69            if (selectDir.deferred.state === 'pending') {70              selectDir.deferred.reject();71            }72            selectDir.removeEventListener('change', selectDirHandler, false);73          });74          return selectDir.deferred.protect;75        };76        function saveFileHandler() {77          var files = saveFile.files;78          saveFile.deferred.resolve(files[0]);79          lastSelectedPath = path.dirname(files[0].path);80          saveFile.files = [];81          saveFile.value = '';82        }83        _methods.saveFile = function (defaultName, defaultPath) {84          saveFile.deferred = new Promise;85          if (defaultName) {86            console.log(saveFile);87            saveFile.setAttribute('nwsaveas', defaultName);88          }89          if (defaultPath || lastSelectedPath) {90            saveFile.setAttribute('nwworkingdir', defaultPath || lastSelectedPath);91          }92          saveFile.addEventListener('change', saveFileHandler, false);93          saveFile.click();94          $(window).one('focus', function (evt) {95            if (saveFile.deferred.state === 'pending') {96              saveFile.deferred.reject('canceled');97            }98            saveFile.removeEventListener('change', selectDirHandler, false);99          });100          return saveFile.deferred.protect;101        };102        this.$get = function () {103          return _methods;104        };105      }]);...

Full Screen

Full Screen

selectFile.test.js

Source:selectFile.test.js Github

copy

Full Screen

1jest.unmock('./selectFile.js')2jest.unmock('../constants')3import * as types from '../constants'4import selectFile from './selectFile.js'5import configureMockStore from 'redux-mock-store'6import thunk from 'redux-thunk'7const mockStore = configureMockStore([thunk])8const store = mockStore({ app: { lei: '123' } })9window.localStorage = {10  setItem: jest.fn()11}12describe('selectFile', () => {13  it('creates a thunk to signal file selection', () => {14    expect(typeof selectFile()).toEqual('function')15  })16  it('suppresses edits if the file is too large', () => {17    const dispatch = jest.fn()18    const getState = jest.fn(() => {19      return {20        app: {21          lei: '123'22        }23      }24    })25    selectFile({ size: 5e7 })(dispatch, getState)26    expect(dispatch.mock.calls.length).toBe(2)27  })28  it('creates an action to signal file selection when dispatched', () => {29    const file = { size: 42, name: 'test.txt' }30    store.dispatch(selectFile(file))31    expect(store.getActions()).toEqual([32      { type: types.SELECT_FILE, file, lei: '123' }33    ])34  })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', () => {2    it('Does not do much!', () => {3        cy.contains('type').click()4        cy.url().should('include', '/commands/actions')5        cy.get('.action-email')6            .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2    it('selects the file', function() {3        cy.contains('File Upload').click()4        cy.get('input[type="file"]').selectFile('example.json')5    })6})7Cypress.Commands.add('selectFile', { prevSubject: 'element' }, (subject, fileName) => {8    cy.fixture(fileName, 'base64').then(content => {9        cy.get(subject).upload({ fileContent: content, fileName, mimeType: 'application/json' }, { subjectType: 'input' })10    })11})12import './commands'

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('clicks the link "type"', function() {3    cy.contains('type').click()4  })5})6describe('My First Test', function() {7  it('clicks the link "type"', function() {8    cy.contains('type').click()9  })10})11describe('My First Test', function() {12  it('clicks the link "type"', function() {13    cy.contains('type').click()14  })15})16describe('My First Test', function() {17  it('clicks the link "type"', function() {18    cy.contains('type').click()19  })20})21describe('My First Test', function() {22  it('clicks the link "type"', function() {23    cy.contains('type').click()24  })25})26describe('My First Test', function() {27  it('clicks the link "type"', function() {28    cy.contains('type').click()29  })30})31describe('My First Test', function() {32  it('clicks the link "type"', function() {33    cy.contains('type').click()34  })35})36describe('My First Test', function() {37  it('clicks the link "type"', function() {38    cy.contains('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('File Upload', () => {2  it('Upload a file', () => {3    cy.get('#file-upload').attachFile('file.json')4    cy.get('#file-submit').click()5  })6})7describe('File Upload', () => {8  it('Upload a file', () => {9    cy.get('#file-upload').attachFile('file.json')10    cy.get('#file-submit').click()11  })12})13describe('File Upload', () => {14  it('Upload a file', () => {15    cy.get('#file-upload').attachFile('file.json')16    cy.get('#file-submit').click()17  })18})19describe('File Upload', () => {20  it('Upload a file', () => {21    cy.get('#file-upload').attachFile('file.json')22    cy.get('#file-submit').click()23  })24})25describe('File Upload', () => {26  it('Upload a file', () => {27    cy.get('#file-upload').attachFile('file.json')28    cy.get('#file-submit').click()29  })30})31describe('File Upload', () => {32  it('Upload a file', () => {33    cy.get('#file-upload').attachFile('file.json')34    cy.get('#file-submit').click()35  })36})37describe('File Upload', () => {38  it('Upload a file', () => {39    cy.get('#file-upload').attachFile('file.json')40    cy.get('#file-submit').click()41  })42})43describe('File Upload', () => {44  it('Upload a file', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Upload File', () => {2    it('Upload', () => {3        cy.get('#iframeResult').iframe().find('[type="file"]').selectFile('C:\\Users\\sara\\Desktop\\test.txt')4        cy.get('#iframeResult').iframe().find('[type="submit"]').click()5    })6})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('File Upload', () => {2  it('Upload a file', () => {3    cy.get('input[type="file"]').selectFile('file.json')4  })5})6{7}8{

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add("selectfile", (selector, fileUrl, type = "") => {2  cy.get(selector).then(subject => {3      .fixture(fileUrl, "base64")4      .then(Cypress.Blob.base64StringToBlob)5      .then(blob => {6        const el = subject[0];7        const testFile = new File([blob], fileUrl, { type });8        const dataTransfer = new DataTransfer();9        dataTransfer.items.add(testFile);10        el.files = dataTransfer.files;11        return subject;12      });13  });14});

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful