cp.scripts.js 240 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971
  1. /*!
  2. * Bootstrap-select v1.13.9 (https://developer.snapappointments.com/bootstrap-select)
  3. *
  4. * Copyright 2012-2019 SnapAppointments, LLC
  5. * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
  6. */
  7. (function (root, factory) {
  8. if (root === undefined && window !== undefined) root = window;
  9. if (typeof define === 'function' && define.amd) {
  10. // AMD. Register as an anonymous module unless amdModuleId is set
  11. define(["jquery"], function (a0) {
  12. return (factory(a0));
  13. });
  14. } else if (typeof module === 'object' && module.exports) {
  15. // Node. Does not work with strict CommonJS, but
  16. // only CommonJS-like environments that support module.exports,
  17. // like Node.
  18. module.exports = factory(require("jquery"));
  19. } else {
  20. factory(root["jQuery"]);
  21. }
  22. }(this, function (jQuery) {
  23. (function ($) {
  24. 'use strict';
  25. var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn'];
  26. var uriAttrs = [
  27. 'background',
  28. 'cite',
  29. 'href',
  30. 'itemtype',
  31. 'longdesc',
  32. 'poster',
  33. 'src',
  34. 'xlink:href'
  35. ];
  36. var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i;
  37. var DefaultWhitelist = {
  38. // Global attributes allowed on any supplied element below.
  39. '*': ['class', 'dir', 'id', 'lang', 'role', 'tabindex', 'style', ARIA_ATTRIBUTE_PATTERN],
  40. a: ['target', 'href', 'title', 'rel'],
  41. area: [],
  42. b: [],
  43. br: [],
  44. col: [],
  45. code: [],
  46. div: [],
  47. em: [],
  48. hr: [],
  49. h1: [],
  50. h2: [],
  51. h3: [],
  52. h4: [],
  53. h5: [],
  54. h6: [],
  55. i: [],
  56. img: ['src', 'alt', 'title', 'width', 'height'],
  57. li: [],
  58. ol: [],
  59. p: [],
  60. pre: [],
  61. s: [],
  62. small: [],
  63. span: [],
  64. sub: [],
  65. sup: [],
  66. strong: [],
  67. u: [],
  68. ul: []
  69. }
  70. /**
  71. * A pattern that recognizes a commonly useful subset of URLs that are safe.
  72. *
  73. * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
  74. */
  75. var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi;
  76. /**
  77. * A pattern that matches safe data URLs. Only matches image, video and audio types.
  78. *
  79. * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
  80. */
  81. var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i;
  82. function allowedAttribute (attr, allowedAttributeList) {
  83. var attrName = attr.nodeName.toLowerCase()
  84. if ($.inArray(attrName, allowedAttributeList) !== -1) {
  85. if ($.inArray(attrName, uriAttrs) !== -1) {
  86. return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))
  87. }
  88. return true
  89. }
  90. var regExp = $(allowedAttributeList).filter(function (index, value) {
  91. return value instanceof RegExp
  92. })
  93. // Check if a regular expression validates the attribute.
  94. for (var i = 0, l = regExp.length; i < l; i++) {
  95. if (attrName.match(regExp[i])) {
  96. return true
  97. }
  98. }
  99. return false
  100. }
  101. function sanitizeHtml (unsafeElements, whiteList, sanitizeFn) {
  102. if (sanitizeFn && typeof sanitizeFn === 'function') {
  103. return sanitizeFn(unsafeElements);
  104. }
  105. var whitelistKeys = Object.keys(whiteList);
  106. for (var i = 0, len = unsafeElements.length; i < len; i++) {
  107. var elements = unsafeElements[i].querySelectorAll('*');
  108. for (var j = 0, len2 = elements.length; j < len2; j++) {
  109. var el = elements[j];
  110. var elName = el.nodeName.toLowerCase();
  111. if (whitelistKeys.indexOf(elName) === -1) {
  112. el.parentNode.removeChild(el);
  113. continue;
  114. }
  115. var attributeList = [].slice.call(el.attributes);
  116. var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []);
  117. for (var k = 0, len3 = attributeList.length; k < len3; k++) {
  118. var attr = attributeList[k];
  119. if (!allowedAttribute(attr, whitelistedAttributes)) {
  120. el.removeAttribute(attr.nodeName);
  121. }
  122. }
  123. }
  124. }
  125. }
  126. // Polyfill for browsers with no classList support
  127. // Remove in v2
  128. if (!('classList' in document.createElement('_'))) {
  129. (function (view) {
  130. if (!('Element' in view)) return;
  131. var classListProp = 'classList',
  132. protoProp = 'prototype',
  133. elemCtrProto = view.Element[protoProp],
  134. objCtr = Object,
  135. classListGetter = function () {
  136. var $elem = $(this);
  137. return {
  138. add: function (classes) {
  139. classes = Array.prototype.slice.call(arguments).join(' ');
  140. return $elem.addClass(classes);
  141. },
  142. remove: function (classes) {
  143. classes = Array.prototype.slice.call(arguments).join(' ');
  144. return $elem.removeClass(classes);
  145. },
  146. toggle: function (classes, force) {
  147. return $elem.toggleClass(classes, force);
  148. },
  149. contains: function (classes) {
  150. return $elem.hasClass(classes);
  151. }
  152. }
  153. };
  154. if (objCtr.defineProperty) {
  155. var classListPropDesc = {
  156. get: classListGetter,
  157. enumerable: true,
  158. configurable: true
  159. };
  160. try {
  161. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  162. } catch (ex) { // IE 8 doesn't support enumerable:true
  163. // adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36
  164. // modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected
  165. if (ex.number === undefined || ex.number === -0x7FF5EC54) {
  166. classListPropDesc.enumerable = false;
  167. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  168. }
  169. }
  170. } else if (objCtr[protoProp].__defineGetter__) {
  171. elemCtrProto.__defineGetter__(classListProp, classListGetter);
  172. }
  173. }(window));
  174. }
  175. var testElement = document.createElement('_');
  176. testElement.classList.add('c1', 'c2');
  177. if (!testElement.classList.contains('c2')) {
  178. var _add = DOMTokenList.prototype.add,
  179. _remove = DOMTokenList.prototype.remove;
  180. DOMTokenList.prototype.add = function () {
  181. Array.prototype.forEach.call(arguments, _add.bind(this));
  182. }
  183. DOMTokenList.prototype.remove = function () {
  184. Array.prototype.forEach.call(arguments, _remove.bind(this));
  185. }
  186. }
  187. testElement.classList.toggle('c3', false);
  188. // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
  189. // support the second argument.
  190. if (testElement.classList.contains('c3')) {
  191. var _toggle = DOMTokenList.prototype.toggle;
  192. DOMTokenList.prototype.toggle = function (token, force) {
  193. if (1 in arguments && !this.contains(token) === !force) {
  194. return force;
  195. } else {
  196. return _toggle.call(this, token);
  197. }
  198. };
  199. }
  200. testElement = null;
  201. // shallow array comparison
  202. function isEqual (array1, array2) {
  203. return array1.length === array2.length && array1.every(function (element, index) {
  204. return element === array2[index];
  205. });
  206. };
  207. // <editor-fold desc="Shims">
  208. if (!String.prototype.startsWith) {
  209. (function () {
  210. 'use strict';
  211. var defineProperty = (function () {
  212. try {
  213. var object = {};
  214. var $defineProperty = Object.defineProperty;
  215. var result = $defineProperty(object, object, object) && $defineProperty;
  216. } catch (error) {
  217. }
  218. return result;
  219. }());
  220. var toString = {}.toString;
  221. var startsWith = function (search) {
  222. if (this == null) {
  223. throw new TypeError();
  224. }
  225. var string = String(this);
  226. if (search && toString.call(search) == '[object RegExp]') {
  227. throw new TypeError();
  228. }
  229. var stringLength = string.length;
  230. var searchString = String(search);
  231. var searchLength = searchString.length;
  232. var position = arguments.length > 1 ? arguments[1] : undefined;
  233. var pos = position ? Number(position) : 0;
  234. if (pos != pos) {
  235. pos = 0;
  236. }
  237. var start = Math.min(Math.max(pos, 0), stringLength);
  238. if (searchLength + start > stringLength) {
  239. return false;
  240. }
  241. var index = -1;
  242. while (++index < searchLength) {
  243. if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
  244. return false;
  245. }
  246. }
  247. return true;
  248. };
  249. if (defineProperty) {
  250. defineProperty(String.prototype, 'startsWith', {
  251. 'value': startsWith,
  252. 'configurable': true,
  253. 'writable': true
  254. });
  255. } else {
  256. String.prototype.startsWith = startsWith;
  257. }
  258. }());
  259. }
  260. if (!Object.keys) {
  261. Object.keys = function (
  262. o, // object
  263. k, // key
  264. r // result array
  265. ) {
  266. // initialize object and result
  267. r = [];
  268. // iterate over object keys
  269. for (k in o) {
  270. // fill result array with non-prototypical keys
  271. r.hasOwnProperty.call(o, k) && r.push(k);
  272. }
  273. // return result
  274. return r;
  275. };
  276. }
  277. if (HTMLSelectElement && !HTMLSelectElement.prototype.hasOwnProperty('selectedOptions')) {
  278. Object.defineProperty(HTMLSelectElement.prototype, 'selectedOptions', {
  279. get: function () {
  280. return this.querySelectorAll(':checked');
  281. }
  282. });
  283. }
  284. // much faster than $.val()
  285. function getSelectValues (select) {
  286. var result = [];
  287. var options = select.selectedOptions;
  288. var opt;
  289. if (select.multiple) {
  290. for (var i = 0, len = options.length; i < len; i++) {
  291. opt = options[i];
  292. result.push(opt.value || opt.text);
  293. }
  294. } else {
  295. result = select.value;
  296. }
  297. return result;
  298. }
  299. // set data-selected on select element if the value has been programmatically selected
  300. // prior to initialization of bootstrap-select
  301. // * consider removing or replacing an alternative method *
  302. var valHooks = {
  303. useDefault: false,
  304. _set: $.valHooks.select.set
  305. };
  306. $.valHooks.select.set = function (elem, value) {
  307. if (value && !valHooks.useDefault) $(elem).data('selected', true);
  308. return valHooks._set.apply(this, arguments);
  309. };
  310. var changedArguments = null;
  311. var EventIsSupported = (function () {
  312. try {
  313. new Event('change');
  314. return true;
  315. } catch (e) {
  316. return false;
  317. }
  318. })();
  319. $.fn.triggerNative = function (eventName) {
  320. var el = this[0],
  321. event;
  322. if (el.dispatchEvent) { // for modern browsers & IE9+
  323. if (EventIsSupported) {
  324. // For modern browsers
  325. event = new Event(eventName, {
  326. bubbles: true
  327. });
  328. } else {
  329. // For IE since it doesn't support Event constructor
  330. event = document.createEvent('Event');
  331. event.initEvent(eventName, true, false);
  332. }
  333. el.dispatchEvent(event);
  334. } else if (el.fireEvent) { // for IE8
  335. event = document.createEventObject();
  336. event.eventType = eventName;
  337. el.fireEvent('on' + eventName, event);
  338. } else {
  339. // fall back to jQuery.trigger
  340. this.trigger(eventName);
  341. }
  342. };
  343. // </editor-fold>
  344. function stringSearch (li, searchString, method, normalize) {
  345. var stringTypes = [
  346. 'display',
  347. 'subtext',
  348. 'tokens'
  349. ],
  350. searchSuccess = false;
  351. for (var i = 0; i < stringTypes.length; i++) {
  352. var stringType = stringTypes[i],
  353. string = li[stringType];
  354. if (string) {
  355. string = string.toString();
  356. // Strip HTML tags. This isn't perfect, but it's much faster than any other method
  357. if (stringType === 'display') {
  358. string = string.replace(/<[^>]+>/g, '');
  359. }
  360. if (normalize) string = normalizeToBase(string);
  361. string = string.toUpperCase();
  362. if (method === 'contains') {
  363. searchSuccess = string.indexOf(searchString) >= 0;
  364. } else {
  365. searchSuccess = string.startsWith(searchString);
  366. }
  367. if (searchSuccess) break;
  368. }
  369. }
  370. return searchSuccess;
  371. }
  372. function toInteger (value) {
  373. return parseInt(value, 10) || 0;
  374. }
  375. // Borrowed from Lodash (_.deburr)
  376. /** Used to map Latin Unicode letters to basic Latin letters. */
  377. var deburredLetters = {
  378. // Latin-1 Supplement block.
  379. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  380. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  381. '\xc7': 'C', '\xe7': 'c',
  382. '\xd0': 'D', '\xf0': 'd',
  383. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  384. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  385. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  386. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  387. '\xd1': 'N', '\xf1': 'n',
  388. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  389. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  390. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  391. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  392. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  393. '\xc6': 'Ae', '\xe6': 'ae',
  394. '\xde': 'Th', '\xfe': 'th',
  395. '\xdf': 'ss',
  396. // Latin Extended-A block.
  397. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  398. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  399. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  400. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  401. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  402. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  403. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  404. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  405. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  406. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  407. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  408. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  409. '\u0134': 'J', '\u0135': 'j',
  410. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  411. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  412. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  413. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  414. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  415. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  416. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  417. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  418. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  419. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  420. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  421. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  422. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  423. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  424. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  425. '\u0174': 'W', '\u0175': 'w',
  426. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  427. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  428. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  429. '\u0132': 'IJ', '\u0133': 'ij',
  430. '\u0152': 'Oe', '\u0153': 'oe',
  431. '\u0149': "'n", '\u017f': 's'
  432. };
  433. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  434. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  435. /** Used to compose unicode character classes. */
  436. var rsComboMarksRange = '\\u0300-\\u036f',
  437. reComboHalfMarksRange = '\\ufe20-\\ufe2f',
  438. rsComboSymbolsRange = '\\u20d0-\\u20ff',
  439. rsComboMarksExtendedRange = '\\u1ab0-\\u1aff',
  440. rsComboMarksSupplementRange = '\\u1dc0-\\u1dff',
  441. rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange + rsComboMarksExtendedRange + rsComboMarksSupplementRange;
  442. /** Used to compose unicode capture groups. */
  443. var rsCombo = '[' + rsComboRange + ']';
  444. /**
  445. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  446. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  447. */
  448. var reComboMark = RegExp(rsCombo, 'g');
  449. function deburrLetter (key) {
  450. return deburredLetters[key];
  451. };
  452. function normalizeToBase (string) {
  453. string = string.toString();
  454. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  455. }
  456. // List of HTML entities for escaping.
  457. var escapeMap = {
  458. '&': '&amp;',
  459. '<': '&lt;',
  460. '>': '&gt;',
  461. '"': '&quot;',
  462. "'": '&#x27;',
  463. };
  464. escapeMap[String.fromCharCode(96)] = '&#x60;';
  465. // Functions for escaping and unescaping strings to/from HTML interpolation.
  466. var createEscaper = function (map) {
  467. var escaper = function (match) {
  468. return map[match];
  469. };
  470. // Regexes for identifying a key that needs to be escaped.
  471. var source = '(?:' + Object.keys(map).join('|') + ')';
  472. var testRegexp = RegExp(source);
  473. var replaceRegexp = RegExp(source, 'g');
  474. return function (string) {
  475. string = string == null ? '' : '' + string;
  476. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  477. };
  478. };
  479. var htmlEscape = createEscaper(escapeMap);
  480. /**
  481. * ------------------------------------------------------------------------
  482. * Constants
  483. * ------------------------------------------------------------------------
  484. */
  485. var keyCodeMap = {
  486. 32: ' ',
  487. 48: '0',
  488. 49: '1',
  489. 50: '2',
  490. 51: '3',
  491. 52: '4',
  492. 53: '5',
  493. 54: '6',
  494. 55: '7',
  495. 56: '8',
  496. 57: '9',
  497. 59: ';',
  498. 65: 'A',
  499. 66: 'B',
  500. 67: 'C',
  501. 68: 'D',
  502. 69: 'E',
  503. 70: 'F',
  504. 71: 'G',
  505. 72: 'H',
  506. 73: 'I',
  507. 74: 'J',
  508. 75: 'K',
  509. 76: 'L',
  510. 77: 'M',
  511. 78: 'N',
  512. 79: 'O',
  513. 80: 'P',
  514. 81: 'Q',
  515. 82: 'R',
  516. 83: 'S',
  517. 84: 'T',
  518. 85: 'U',
  519. 86: 'V',
  520. 87: 'W',
  521. 88: 'X',
  522. 89: 'Y',
  523. 90: 'Z',
  524. 96: '0',
  525. 97: '1',
  526. 98: '2',
  527. 99: '3',
  528. 100: '4',
  529. 101: '5',
  530. 102: '6',
  531. 103: '7',
  532. 104: '8',
  533. 105: '9'
  534. };
  535. var keyCodes = {
  536. ESCAPE: 27, // KeyboardEvent.which value for Escape (Esc) key
  537. ENTER: 13, // KeyboardEvent.which value for Enter key
  538. SPACE: 32, // KeyboardEvent.which value for space key
  539. TAB: 9, // KeyboardEvent.which value for tab key
  540. ARROW_UP: 38, // KeyboardEvent.which value for up arrow key
  541. ARROW_DOWN: 40 // KeyboardEvent.which value for down arrow key
  542. }
  543. var version = {
  544. success: false,
  545. major: '3'
  546. };
  547. try {
  548. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  549. version.major = version.full[0];
  550. version.success = true;
  551. } catch (err) {
  552. // do nothing
  553. }
  554. var selectId = 0;
  555. var EVENT_KEY = '.bs.select';
  556. var classNames = {
  557. DISABLED: 'disabled',
  558. DIVIDER: 'divider',
  559. SHOW: 'open',
  560. DROPUP: 'dropup',
  561. MENU: 'dropdown-menu',
  562. MENURIGHT: 'dropdown-menu-right',
  563. MENULEFT: 'dropdown-menu-left',
  564. // to-do: replace with more advanced template/customization options
  565. BUTTONCLASS: 'btn-default',
  566. POPOVERHEADER: 'popover-title',
  567. ICONBASE: 'glyphicon',
  568. TICKICON: 'glyphicon-ok'
  569. }
  570. var Selector = {
  571. MENU: '.' + classNames.MENU
  572. }
  573. var elementTemplates = {
  574. span: document.createElement('span'),
  575. i: document.createElement('i'),
  576. subtext: document.createElement('small'),
  577. a: document.createElement('a'),
  578. li: document.createElement('li'),
  579. whitespace: document.createTextNode('\u00A0'),
  580. fragment: document.createDocumentFragment()
  581. }
  582. elementTemplates.a.setAttribute('role', 'option');
  583. elementTemplates.subtext.className = 'text-muted';
  584. elementTemplates.text = elementTemplates.span.cloneNode(false);
  585. elementTemplates.text.className = 'text';
  586. elementTemplates.checkMark = elementTemplates.span.cloneNode(false);
  587. var REGEXP_ARROW = new RegExp(keyCodes.ARROW_UP + '|' + keyCodes.ARROW_DOWN);
  588. var REGEXP_TAB_OR_ESCAPE = new RegExp('^' + keyCodes.TAB + '$|' + keyCodes.ESCAPE);
  589. var generateOption = {
  590. li: function (content, classes, optgroup) {
  591. var li = elementTemplates.li.cloneNode(false);
  592. if (content) {
  593. if (content.nodeType === 1 || content.nodeType === 11) {
  594. li.appendChild(content);
  595. } else {
  596. li.innerHTML = content;
  597. }
  598. }
  599. if (typeof classes !== 'undefined' && classes !== '') li.className = classes;
  600. if (typeof optgroup !== 'undefined' && optgroup !== null) li.classList.add('optgroup-' + optgroup);
  601. return li;
  602. },
  603. a: function (text, classes, inline) {
  604. var a = elementTemplates.a.cloneNode(true);
  605. if (text) {
  606. if (text.nodeType === 11) {
  607. a.appendChild(text);
  608. } else {
  609. a.insertAdjacentHTML('beforeend', text);
  610. }
  611. }
  612. if (typeof classes !== 'undefined' && classes !== '') a.className = classes;
  613. if (version.major === '4') a.classList.add('dropdown-item');
  614. if (inline) a.setAttribute('style', inline);
  615. return a;
  616. },
  617. text: function (options, useFragment) {
  618. var textElement = elementTemplates.text.cloneNode(false),
  619. subtextElement,
  620. iconElement;
  621. if (options.content) {
  622. textElement.innerHTML = options.content;
  623. } else {
  624. textElement.textContent = options.text;
  625. if (options.icon) {
  626. var whitespace = elementTemplates.whitespace.cloneNode(false);
  627. // need to use <i> for icons in the button to prevent a breaking change
  628. // note: switch to span in next major release
  629. iconElement = (useFragment === true ? elementTemplates.i : elementTemplates.span).cloneNode(false);
  630. iconElement.className = options.iconBase + ' ' + options.icon;
  631. elementTemplates.fragment.appendChild(iconElement);
  632. elementTemplates.fragment.appendChild(whitespace);
  633. }
  634. if (options.subtext) {
  635. subtextElement = elementTemplates.subtext.cloneNode(false);
  636. subtextElement.textContent = options.subtext;
  637. textElement.appendChild(subtextElement);
  638. }
  639. }
  640. if (useFragment === true) {
  641. while (textElement.childNodes.length > 0) {
  642. elementTemplates.fragment.appendChild(textElement.childNodes[0]);
  643. }
  644. } else {
  645. elementTemplates.fragment.appendChild(textElement);
  646. }
  647. return elementTemplates.fragment;
  648. },
  649. label: function (options) {
  650. var textElement = elementTemplates.text.cloneNode(false),
  651. subtextElement,
  652. iconElement;
  653. textElement.innerHTML = options.label;
  654. if (options.icon) {
  655. var whitespace = elementTemplates.whitespace.cloneNode(false);
  656. iconElement = elementTemplates.span.cloneNode(false);
  657. iconElement.className = options.iconBase + ' ' + options.icon;
  658. elementTemplates.fragment.appendChild(iconElement);
  659. elementTemplates.fragment.appendChild(whitespace);
  660. }
  661. if (options.subtext) {
  662. subtextElement = elementTemplates.subtext.cloneNode(false);
  663. subtextElement.textContent = options.subtext;
  664. textElement.appendChild(subtextElement);
  665. }
  666. elementTemplates.fragment.appendChild(textElement);
  667. return elementTemplates.fragment;
  668. }
  669. }
  670. var Selectpicker = function (element, options) {
  671. var that = this;
  672. // bootstrap-select has been initialized - revert valHooks.select.set back to its original function
  673. if (!valHooks.useDefault) {
  674. $.valHooks.select.set = valHooks._set;
  675. valHooks.useDefault = true;
  676. }
  677. this.$element = $(element);
  678. this.$newElement = null;
  679. this.$button = null;
  680. this.$menu = null;
  681. this.options = options;
  682. this.selectpicker = {
  683. main: {},
  684. current: {}, // current changes if a search is in progress
  685. search: {},
  686. view: {},
  687. keydown: {
  688. keyHistory: '',
  689. resetKeyHistory: {
  690. start: function () {
  691. return setTimeout(function () {
  692. that.selectpicker.keydown.keyHistory = '';
  693. }, 800);
  694. }
  695. }
  696. }
  697. };
  698. // If we have no title yet, try to pull it from the html title attribute (jQuery doesnt' pick it up as it's not a
  699. // data-attribute)
  700. if (this.options.title === null) {
  701. this.options.title = this.$element.attr('title');
  702. }
  703. // Format window padding
  704. var winPad = this.options.windowPadding;
  705. if (typeof winPad === 'number') {
  706. this.options.windowPadding = [winPad, winPad, winPad, winPad];
  707. }
  708. // Expose public methods
  709. this.val = Selectpicker.prototype.val;
  710. this.render = Selectpicker.prototype.render;
  711. this.refresh = Selectpicker.prototype.refresh;
  712. this.setStyle = Selectpicker.prototype.setStyle;
  713. this.selectAll = Selectpicker.prototype.selectAll;
  714. this.deselectAll = Selectpicker.prototype.deselectAll;
  715. this.destroy = Selectpicker.prototype.destroy;
  716. this.remove = Selectpicker.prototype.remove;
  717. this.show = Selectpicker.prototype.show;
  718. this.hide = Selectpicker.prototype.hide;
  719. this.init();
  720. };
  721. Selectpicker.VERSION = '1.13.9';
  722. // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
  723. Selectpicker.DEFAULTS = {
  724. noneSelectedText: 'Nothing selected',
  725. noneResultsText: 'No results matched {0}',
  726. countSelectedText: function (numSelected, numTotal) {
  727. return (numSelected == 1) ? '{0} item selected' : '{0} items selected';
  728. },
  729. maxOptionsText: function (numAll, numGroup) {
  730. return [
  731. (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
  732. (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
  733. ];
  734. },
  735. selectAllText: 'Select All',
  736. deselectAllText: 'Deselect All',
  737. doneButton: false,
  738. doneButtonText: 'Close',
  739. multipleSeparator: ', ',
  740. styleBase: 'btn',
  741. style: classNames.BUTTONCLASS,
  742. size: 'auto',
  743. title: null,
  744. selectedTextFormat: 'values',
  745. width: false,
  746. container: false,
  747. hideDisabled: false,
  748. showSubtext: false,
  749. showIcon: true,
  750. showContent: true,
  751. dropupAuto: true,
  752. header: false,
  753. liveSearch: false,
  754. liveSearchPlaceholder: null,
  755. liveSearchNormalize: false,
  756. liveSearchStyle: 'contains',
  757. actionsBox: false,
  758. iconBase: classNames.ICONBASE,
  759. tickIcon: classNames.TICKICON,
  760. showTick: false,
  761. template: {
  762. caret: '<span class="caret"></span>'
  763. },
  764. maxOptions: false,
  765. mobile: false,
  766. selectOnTab: false,
  767. dropdownAlignRight: false,
  768. windowPadding: 0,
  769. virtualScroll: 600,
  770. display: false,
  771. sanitize: true,
  772. sanitizeFn: null,
  773. whiteList: DefaultWhitelist
  774. };
  775. Selectpicker.prototype = {
  776. constructor: Selectpicker,
  777. init: function () {
  778. var that = this,
  779. id = this.$element.attr('id');
  780. this.selectId = selectId++;
  781. this.$element[0].classList.add('bs-select-hidden');
  782. this.multiple = this.$element.prop('multiple');
  783. this.autofocus = this.$element.prop('autofocus');
  784. this.options.showTick = this.$element[0].classList.contains('show-tick');
  785. this.$newElement = this.createDropdown();
  786. this.$element
  787. .after(this.$newElement)
  788. .prependTo(this.$newElement);
  789. this.$button = this.$newElement.children('button');
  790. this.$menu = this.$newElement.children(Selector.MENU);
  791. this.$menuInner = this.$menu.children('.inner');
  792. this.$searchbox = this.$menu.find('input');
  793. this.$element[0].classList.remove('bs-select-hidden');
  794. if (this.options.dropdownAlignRight === true) this.$menu[0].classList.add(classNames.MENURIGHT);
  795. if (typeof id !== 'undefined') {
  796. this.$button.attr('data-id', id);
  797. }
  798. this.checkDisabled();
  799. this.clickListener();
  800. if (this.options.liveSearch) this.liveSearchListener();
  801. this.setStyle();
  802. this.render();
  803. this.setWidth();
  804. if (this.options.container) {
  805. this.selectPosition();
  806. } else {
  807. this.$element.on('hide' + EVENT_KEY, function () {
  808. if (that.isVirtual()) {
  809. // empty menu on close
  810. var menuInner = that.$menuInner[0],
  811. emptyMenu = menuInner.firstChild.cloneNode(false);
  812. // replace the existing UL with an empty one - this is faster than $.empty() or innerHTML = ''
  813. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  814. menuInner.scrollTop = 0;
  815. }
  816. });
  817. }
  818. this.$menu.data('this', this);
  819. this.$newElement.data('this', this);
  820. if (this.options.mobile) this.mobile();
  821. this.$newElement.on({
  822. 'hide.bs.dropdown': function (e) {
  823. that.$menuInner.attr('aria-expanded', false);
  824. that.$element.trigger('hide' + EVENT_KEY, e);
  825. },
  826. 'hidden.bs.dropdown': function (e) {
  827. that.$element.trigger('hidden' + EVENT_KEY, e);
  828. },
  829. 'show.bs.dropdown': function (e) {
  830. that.$menuInner.attr('aria-expanded', true);
  831. that.$element.trigger('show' + EVENT_KEY, e);
  832. },
  833. 'shown.bs.dropdown': function (e) {
  834. that.$element.trigger('shown' + EVENT_KEY, e);
  835. }
  836. });
  837. if (that.$element[0].hasAttribute('required')) {
  838. this.$element.on('invalid' + EVENT_KEY, function () {
  839. that.$button[0].classList.add('bs-invalid');
  840. that.$element
  841. .on('shown' + EVENT_KEY + '.invalid', function () {
  842. that.$element
  843. .val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened
  844. .off('shown' + EVENT_KEY + '.invalid');
  845. })
  846. .on('rendered' + EVENT_KEY, function () {
  847. // if select is no longer invalid, remove the bs-invalid class
  848. if (this.validity.valid) that.$button[0].classList.remove('bs-invalid');
  849. that.$element.off('rendered' + EVENT_KEY);
  850. });
  851. that.$button.on('blur' + EVENT_KEY, function () {
  852. that.$element.trigger('focus').trigger('blur');
  853. that.$button.off('blur' + EVENT_KEY);
  854. });
  855. });
  856. }
  857. setTimeout(function () {
  858. that.createLi();
  859. that.$element.trigger('loaded' + EVENT_KEY);
  860. });
  861. },
  862. createDropdown: function () {
  863. // Options
  864. // If we are multiple or showTick option is set, then add the show-tick class
  865. var showTick = (this.multiple || this.options.showTick) ? ' show-tick' : '',
  866. inputGroup = '',
  867. autofocus = this.autofocus ? ' autofocus' : '';
  868. if (version.major < 4 && this.$element.parent().hasClass('input-group')) {
  869. inputGroup = ' input-group-btn';
  870. }
  871. // Elements
  872. var drop,
  873. header = '',
  874. searchbox = '',
  875. actionsbox = '',
  876. donebutton = '';
  877. if (this.options.header) {
  878. header =
  879. '<div class="' + classNames.POPOVERHEADER + '">' +
  880. '<button type="button" class="close" aria-hidden="true">&times;</button>' +
  881. this.options.header +
  882. '</div>';
  883. }
  884. if (this.options.liveSearch) {
  885. searchbox =
  886. '<div class="bs-searchbox">' +
  887. '<input type="text" class="form-control" autocomplete="off"' +
  888. (
  889. this.options.liveSearchPlaceholder === null ? ''
  890. :
  891. ' placeholder="' + htmlEscape(this.options.liveSearchPlaceholder) + '"'
  892. ) +
  893. ' role="textbox" aria-label="Search">' +
  894. '</div>';
  895. }
  896. if (this.multiple && this.options.actionsBox) {
  897. actionsbox =
  898. '<div class="bs-actionsbox">' +
  899. '<div class="btn-group btn-group-sm btn-block">' +
  900. '<button type="button" class="actions-btn bs-select-all btn ' + classNames.BUTTONCLASS + '">' +
  901. this.options.selectAllText +
  902. '</button>' +
  903. '<button type="button" class="actions-btn bs-deselect-all btn ' + classNames.BUTTONCLASS + '">' +
  904. this.options.deselectAllText +
  905. '</button>' +
  906. '</div>' +
  907. '</div>';
  908. }
  909. if (this.multiple && this.options.doneButton) {
  910. donebutton =
  911. '<div class="bs-donebutton">' +
  912. '<div class="btn-group btn-block">' +
  913. '<button type="button" class="btn btn-sm ' + classNames.BUTTONCLASS + '">' +
  914. this.options.doneButtonText +
  915. '</button>' +
  916. '</div>' +
  917. '</div>';
  918. }
  919. drop =
  920. '<div class="dropdown bootstrap-select' + showTick + inputGroup + '">' +
  921. '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" ' + (this.options.display === 'static' ? 'data-display="static"' : '') + 'data-toggle="dropdown"' + autofocus + ' role="button">' +
  922. '<div class="filter-option">' +
  923. '<div class="filter-option-inner">' +
  924. '<div class="filter-option-inner-inner"></div>' +
  925. '</div> ' +
  926. '</div>' +
  927. (
  928. version.major === '4' ? ''
  929. :
  930. '<span class="bs-caret">' +
  931. this.options.template.caret +
  932. '</span>'
  933. ) +
  934. '</button>' +
  935. '<div class="' + classNames.MENU + ' ' + (version.major === '4' ? '' : classNames.SHOW) + '" role="combobox">' +
  936. header +
  937. searchbox +
  938. actionsbox +
  939. '<div class="inner ' + classNames.SHOW + '" role="listbox" aria-expanded="false" tabindex="-1">' +
  940. '<ul class="' + classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '') + '">' +
  941. '</ul>' +
  942. '</div>' +
  943. donebutton +
  944. '</div>' +
  945. '</div>';
  946. return $(drop);
  947. },
  948. setPositionData: function () {
  949. this.selectpicker.view.canHighlight = [];
  950. for (var i = 0; i < this.selectpicker.current.data.length; i++) {
  951. var li = this.selectpicker.current.data[i],
  952. canHighlight = true;
  953. if (li.type === 'divider') {
  954. canHighlight = false;
  955. li.height = this.sizeInfo.dividerHeight;
  956. } else if (li.type === 'optgroup-label') {
  957. canHighlight = false;
  958. li.height = this.sizeInfo.dropdownHeaderHeight;
  959. } else {
  960. li.height = this.sizeInfo.liHeight;
  961. }
  962. if (li.disabled) canHighlight = false;
  963. this.selectpicker.view.canHighlight.push(canHighlight);
  964. li.position = (i === 0 ? 0 : this.selectpicker.current.data[i - 1].position) + li.height;
  965. }
  966. },
  967. isVirtual: function () {
  968. return (this.options.virtualScroll !== false) && (this.selectpicker.main.elements.length >= this.options.virtualScroll) || this.options.virtualScroll === true;
  969. },
  970. createView: function (isSearching, scrollTop) {
  971. scrollTop = scrollTop || 0;
  972. var that = this;
  973. this.selectpicker.current = isSearching ? this.selectpicker.search : this.selectpicker.main;
  974. var active = [];
  975. var selected;
  976. var prevActive;
  977. this.setPositionData();
  978. scroll(scrollTop, true);
  979. this.$menuInner.off('scroll.createView').on('scroll.createView', function (e, updateValue) {
  980. if (!that.noScroll) scroll(this.scrollTop, updateValue);
  981. that.noScroll = false;
  982. });
  983. function scroll (scrollTop, init) {
  984. var size = that.selectpicker.current.elements.length,
  985. chunks = [],
  986. chunkSize,
  987. chunkCount,
  988. firstChunk,
  989. lastChunk,
  990. currentChunk,
  991. prevPositions,
  992. positionIsDifferent,
  993. previousElements,
  994. menuIsDifferent = true,
  995. isVirtual = that.isVirtual();
  996. that.selectpicker.view.scrollTop = scrollTop;
  997. if (isVirtual === true) {
  998. // if an option that is encountered that is wider than the current menu width, update the menu width accordingly
  999. if (that.sizeInfo.hasScrollBar && that.$menu[0].offsetWidth > that.sizeInfo.totalMenuWidth) {
  1000. that.sizeInfo.menuWidth = that.$menu[0].offsetWidth;
  1001. that.sizeInfo.totalMenuWidth = that.sizeInfo.menuWidth + that.sizeInfo.scrollBarWidth;
  1002. that.$menu.css('min-width', that.sizeInfo.menuWidth);
  1003. }
  1004. }
  1005. chunkSize = Math.ceil(that.sizeInfo.menuInnerHeight / that.sizeInfo.liHeight * 1.5); // number of options in a chunk
  1006. chunkCount = Math.round(size / chunkSize) || 1; // number of chunks
  1007. for (var i = 0; i < chunkCount; i++) {
  1008. var endOfChunk = (i + 1) * chunkSize;
  1009. if (i === chunkCount - 1) {
  1010. endOfChunk = size;
  1011. }
  1012. chunks[i] = [
  1013. (i) * chunkSize + (!i ? 0 : 1),
  1014. endOfChunk
  1015. ];
  1016. if (!size) break;
  1017. if (currentChunk === undefined && scrollTop <= that.selectpicker.current.data[endOfChunk - 1].position - that.sizeInfo.menuInnerHeight) {
  1018. currentChunk = i;
  1019. }
  1020. }
  1021. if (currentChunk === undefined) currentChunk = 0;
  1022. prevPositions = [that.selectpicker.view.position0, that.selectpicker.view.position1];
  1023. // always display previous, current, and next chunks
  1024. firstChunk = Math.max(0, currentChunk - 1);
  1025. lastChunk = Math.min(chunkCount - 1, currentChunk + 1);
  1026. that.selectpicker.view.position0 = isVirtual === false ? 0 : (Math.max(0, chunks[firstChunk][0]) || 0);
  1027. that.selectpicker.view.position1 = isVirtual === false ? size : (Math.min(size, chunks[lastChunk][1]) || 0);
  1028. positionIsDifferent = prevPositions[0] !== that.selectpicker.view.position0 || prevPositions[1] !== that.selectpicker.view.position1;
  1029. if (that.activeIndex !== undefined) {
  1030. prevActive = that.selectpicker.main.elements[that.prevActiveIndex];
  1031. active = that.selectpicker.main.elements[that.activeIndex];
  1032. selected = that.selectpicker.main.elements[that.selectedIndex];
  1033. if (init) {
  1034. if (that.activeIndex !== that.selectedIndex && active && active.length) {
  1035. active.classList.remove('active');
  1036. if (active.firstChild) active.firstChild.classList.remove('active');
  1037. }
  1038. that.activeIndex = undefined;
  1039. }
  1040. if (that.activeIndex && that.activeIndex !== that.selectedIndex && selected && selected.length) {
  1041. selected.classList.remove('active');
  1042. if (selected.firstChild) selected.firstChild.classList.remove('active');
  1043. }
  1044. }
  1045. if (that.prevActiveIndex !== undefined && that.prevActiveIndex !== that.activeIndex && that.prevActiveIndex !== that.selectedIndex && prevActive && prevActive.length) {
  1046. prevActive.classList.remove('active');
  1047. if (prevActive.firstChild) prevActive.firstChild.classList.remove('active');
  1048. }
  1049. if (init || positionIsDifferent) {
  1050. previousElements = that.selectpicker.view.visibleElements ? that.selectpicker.view.visibleElements.slice() : [];
  1051. if (isVirtual === false) {
  1052. that.selectpicker.view.visibleElements = that.selectpicker.current.elements;
  1053. } else {
  1054. that.selectpicker.view.visibleElements = that.selectpicker.current.elements.slice(that.selectpicker.view.position0, that.selectpicker.view.position1);
  1055. }
  1056. that.setOptionStatus();
  1057. // if searching, check to make sure the list has actually been updated before updating DOM
  1058. // this prevents unnecessary repaints
  1059. if (isSearching || (isVirtual === false && init)) menuIsDifferent = !isEqual(previousElements, that.selectpicker.view.visibleElements);
  1060. // if virtual scroll is disabled and not searching,
  1061. // menu should never need to be updated more than once
  1062. if ((init || isVirtual === true) && menuIsDifferent) {
  1063. var menuInner = that.$menuInner[0],
  1064. menuFragment = document.createDocumentFragment(),
  1065. emptyMenu = menuInner.firstChild.cloneNode(false),
  1066. marginTop,
  1067. marginBottom,
  1068. elements = that.selectpicker.view.visibleElements,
  1069. toSanitize = [];
  1070. // replace the existing UL with an empty one - this is faster than $.empty()
  1071. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  1072. for (var i = 0, visibleElementsLen = elements.length; i < visibleElementsLen; i++) {
  1073. var element = elements[i],
  1074. elText,
  1075. elementData;
  1076. if (that.options.sanitize) {
  1077. elText = element.lastChild;
  1078. if (elText) {
  1079. elementData = that.selectpicker.current.data[i + that.selectpicker.view.position0];
  1080. if (elementData && elementData.content && !elementData.sanitized) {
  1081. toSanitize.push(elText);
  1082. elementData.sanitized = true;
  1083. }
  1084. }
  1085. }
  1086. menuFragment.appendChild(element);
  1087. }
  1088. if (that.options.sanitize && toSanitize.length) {
  1089. sanitizeHtml(toSanitize, that.options.whiteList, that.options.sanitizeFn);
  1090. }
  1091. if (isVirtual === true) {
  1092. marginTop = (that.selectpicker.view.position0 === 0 ? 0 : that.selectpicker.current.data[that.selectpicker.view.position0 - 1].position);
  1093. marginBottom = (that.selectpicker.view.position1 > size - 1 ? 0 : that.selectpicker.current.data[size - 1].position - that.selectpicker.current.data[that.selectpicker.view.position1 - 1].position);
  1094. menuInner.firstChild.style.marginTop = marginTop + 'px';
  1095. menuInner.firstChild.style.marginBottom = marginBottom + 'px';
  1096. }
  1097. menuInner.firstChild.appendChild(menuFragment);
  1098. }
  1099. }
  1100. that.prevActiveIndex = that.activeIndex;
  1101. if (!that.options.liveSearch) {
  1102. that.$menuInner.trigger('focus');
  1103. } else if (isSearching && init) {
  1104. var index = 0,
  1105. newActive;
  1106. if (!that.selectpicker.view.canHighlight[index]) {
  1107. index = 1 + that.selectpicker.view.canHighlight.slice(1).indexOf(true);
  1108. }
  1109. newActive = that.selectpicker.view.visibleElements[index];
  1110. if (that.selectpicker.view.currentActive) {
  1111. that.selectpicker.view.currentActive.classList.remove('active');
  1112. if (that.selectpicker.view.currentActive.firstChild) that.selectpicker.view.currentActive.firstChild.classList.remove('active');
  1113. }
  1114. if (newActive) {
  1115. newActive.classList.add('active');
  1116. if (newActive.firstChild) newActive.firstChild.classList.add('active');
  1117. }
  1118. that.activeIndex = (that.selectpicker.current.data[index] || {}).index;
  1119. }
  1120. }
  1121. $(window)
  1122. .off('resize' + EVENT_KEY + '.' + this.selectId + '.createView')
  1123. .on('resize' + EVENT_KEY + '.' + this.selectId + '.createView', function () {
  1124. var isActive = that.$newElement.hasClass(classNames.SHOW);
  1125. if (isActive) scroll(that.$menuInner[0].scrollTop);
  1126. });
  1127. },
  1128. setPlaceholder: function () {
  1129. var updateIndex = false;
  1130. if (this.options.title && !this.multiple) {
  1131. if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option');
  1132. // this option doesn't create a new <li> element, but does add a new option at the start,
  1133. // so startIndex should increase to prevent having to check every option for the bs-title-option class
  1134. updateIndex = true;
  1135. var element = this.$element[0],
  1136. isSelected = false,
  1137. titleNotAppended = !this.selectpicker.view.titleOption.parentNode;
  1138. if (titleNotAppended) {
  1139. // Use native JS to prepend option (faster)
  1140. this.selectpicker.view.titleOption.className = 'bs-title-option';
  1141. this.selectpicker.view.titleOption.value = '';
  1142. // Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option.
  1143. // the selected item may have been changed by user or programmatically before the bootstrap select plugin runs,
  1144. // if so, the select will have the data-selected attribute
  1145. var $opt = $(element.options[element.selectedIndex]);
  1146. isSelected = $opt.attr('selected') === undefined && this.$element.data('selected') === undefined;
  1147. }
  1148. if (titleNotAppended || this.selectpicker.view.titleOption.index !== 0) {
  1149. element.insertBefore(this.selectpicker.view.titleOption, element.firstChild);
  1150. }
  1151. // Set selected *after* appending to select,
  1152. // otherwise the option doesn't get selected in IE
  1153. // set using selectedIndex, as setting the selected attr to true here doesn't work in IE11
  1154. if (isSelected) element.selectedIndex = 0;
  1155. }
  1156. return updateIndex;
  1157. },
  1158. createLi: function () {
  1159. var that = this,
  1160. iconBase = this.options.iconBase,
  1161. optionSelector = ':not([hidden]):not([data-hidden="true"])',
  1162. mainElements = [],
  1163. mainData = [],
  1164. widestOptionLength = 0,
  1165. optID = 0,
  1166. startIndex = this.setPlaceholder() ? 1 : 0; // append the titleOption if necessary and skip the first option in the loop
  1167. if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
  1168. if ((that.options.showTick || that.multiple) && !elementTemplates.checkMark.parentNode) {
  1169. elementTemplates.checkMark.className = iconBase + ' ' + that.options.tickIcon + ' check-mark';
  1170. elementTemplates.a.appendChild(elementTemplates.checkMark);
  1171. }
  1172. var selectOptions = this.$element[0].querySelectorAll('select > *' + optionSelector);
  1173. function addDivider (config) {
  1174. var previousData = mainData[mainData.length - 1];
  1175. // ensure optgroup doesn't create back-to-back dividers
  1176. if (
  1177. previousData &&
  1178. previousData.type === 'divider' &&
  1179. (previousData.optID || config.optID)
  1180. ) {
  1181. return;
  1182. }
  1183. config = config || {};
  1184. config.type = 'divider';
  1185. mainElements.push(
  1186. generateOption.li(
  1187. false,
  1188. classNames.DIVIDER,
  1189. (config.optID ? config.optID + 'div' : undefined)
  1190. )
  1191. );
  1192. mainData.push(config);
  1193. }
  1194. function addOption (option, config) {
  1195. config = config || {};
  1196. config.divider = option.getAttribute('data-divider') === 'true';
  1197. if (config.divider) {
  1198. addDivider({
  1199. optID: config.optID
  1200. });
  1201. } else {
  1202. var liIndex = mainData.length,
  1203. cssText = option.style.cssText,
  1204. inlineStyle = cssText ? htmlEscape(cssText) : '',
  1205. optionClass = (option.className || '') + (config.optgroupClass || '');
  1206. if (config.optID) optionClass = 'opt ' + optionClass;
  1207. config.text = option.textContent;
  1208. config.content = option.getAttribute('data-content');
  1209. config.tokens = option.getAttribute('data-tokens');
  1210. config.subtext = option.getAttribute('data-subtext');
  1211. config.icon = option.getAttribute('data-icon');
  1212. config.iconBase = iconBase;
  1213. var textElement = generateOption.text(config);
  1214. mainElements.push(
  1215. generateOption.li(
  1216. generateOption.a(
  1217. textElement,
  1218. optionClass,
  1219. inlineStyle
  1220. ),
  1221. '',
  1222. config.optID
  1223. )
  1224. );
  1225. option.liIndex = liIndex;
  1226. config.display = config.content || config.text;
  1227. config.type = 'option';
  1228. config.index = liIndex;
  1229. config.option = option;
  1230. config.disabled = config.disabled || option.disabled;
  1231. mainData.push(config);
  1232. var combinedLength = 0;
  1233. // count the number of characters in the option - not perfect, but should work in most cases
  1234. if (config.display) combinedLength += config.display.length;
  1235. if (config.subtext) combinedLength += config.subtext.length;
  1236. // if there is an icon, ensure this option's width is checked
  1237. if (config.icon) combinedLength += 1;
  1238. if (combinedLength > widestOptionLength) {
  1239. widestOptionLength = combinedLength;
  1240. // guess which option is the widest
  1241. // use this when calculating menu width
  1242. // not perfect, but it's fast, and the width will be updating accordingly when scrolling
  1243. that.selectpicker.view.widestOption = mainElements[mainElements.length - 1];
  1244. }
  1245. }
  1246. }
  1247. function addOptgroup (index, selectOptions) {
  1248. var optgroup = selectOptions[index],
  1249. previous = selectOptions[index - 1],
  1250. next = selectOptions[index + 1],
  1251. options = optgroup.querySelectorAll('option' + optionSelector);
  1252. if (!options.length) return;
  1253. var config = {
  1254. label: htmlEscape(optgroup.label),
  1255. subtext: optgroup.getAttribute('data-subtext'),
  1256. icon: optgroup.getAttribute('data-icon'),
  1257. iconBase: iconBase
  1258. },
  1259. optgroupClass = ' ' + (optgroup.className || ''),
  1260. headerIndex,
  1261. lastIndex;
  1262. optID++;
  1263. if (previous) {
  1264. addDivider({ optID: optID });
  1265. }
  1266. var labelElement = generateOption.label(config);
  1267. mainElements.push(
  1268. generateOption.li(labelElement, 'dropdown-header' + optgroupClass, optID)
  1269. );
  1270. mainData.push({
  1271. display: config.label,
  1272. subtext: config.subtext,
  1273. type: 'optgroup-label',
  1274. optID: optID
  1275. });
  1276. for (var j = 0, len = options.length; j < len; j++) {
  1277. var option = options[j];
  1278. if (j === 0) {
  1279. headerIndex = mainData.length - 1;
  1280. lastIndex = headerIndex + len;
  1281. }
  1282. addOption(option, {
  1283. headerIndex: headerIndex,
  1284. lastIndex: lastIndex,
  1285. optID: optID,
  1286. optgroupClass: optgroupClass,
  1287. disabled: optgroup.disabled
  1288. });
  1289. }
  1290. if (next) {
  1291. addDivider({ optID: optID });
  1292. }
  1293. }
  1294. for (var len = selectOptions.length; startIndex < len; startIndex++) {
  1295. var item = selectOptions[startIndex];
  1296. if (item.tagName !== 'OPTGROUP') {
  1297. addOption(item, {});
  1298. } else {
  1299. addOptgroup(startIndex, selectOptions);
  1300. }
  1301. }
  1302. this.selectpicker.main.elements = mainElements;
  1303. this.selectpicker.main.data = mainData;
  1304. this.selectpicker.current = this.selectpicker.main;
  1305. },
  1306. findLis: function () {
  1307. return this.$menuInner.find('.inner > li');
  1308. },
  1309. render: function () {
  1310. // ensure titleOption is appended and selected (if necessary) before getting selectedOptions
  1311. this.setPlaceholder();
  1312. var that = this,
  1313. selectedOptions = this.$element[0].selectedOptions,
  1314. selectedCount = selectedOptions.length,
  1315. button = this.$button[0],
  1316. buttonInner = button.querySelector('.filter-option-inner-inner'),
  1317. multipleSeparator = document.createTextNode(this.options.multipleSeparator),
  1318. titleFragment = elementTemplates.fragment.cloneNode(false),
  1319. showCount,
  1320. countMax,
  1321. hasContent = false;
  1322. this.togglePlaceholder();
  1323. this.tabIndex();
  1324. if (this.options.selectedTextFormat === 'static') {
  1325. titleFragment = generateOption.text({ text: this.options.title }, true);
  1326. } else {
  1327. showCount = this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1 && selectedCount > 1;
  1328. // determine if the number of selected options will be shown (showCount === true)
  1329. if (showCount) {
  1330. countMax = this.options.selectedTextFormat.split('>');
  1331. showCount = (countMax.length > 1 && selectedCount > countMax[1]) || (countMax.length === 1 && selectedCount >= 2);
  1332. }
  1333. // only loop through all selected options if the count won't be shown
  1334. if (showCount === false) {
  1335. for (var selectedIndex = 0; selectedIndex < selectedCount; selectedIndex++) {
  1336. if (selectedIndex < 50) {
  1337. var option = selectedOptions[selectedIndex],
  1338. titleOptions = {},
  1339. thisData = {
  1340. content: option.getAttribute('data-content'),
  1341. subtext: option.getAttribute('data-subtext'),
  1342. icon: option.getAttribute('data-icon')
  1343. };
  1344. if (this.multiple && selectedIndex > 0) {
  1345. titleFragment.appendChild(multipleSeparator.cloneNode(false));
  1346. }
  1347. if (option.title) {
  1348. titleOptions.text = option.title;
  1349. } else if (thisData.content && that.options.showContent) {
  1350. titleOptions.content = thisData.content.toString();
  1351. hasContent = true;
  1352. } else {
  1353. if (that.options.showIcon) {
  1354. titleOptions.icon = thisData.icon;
  1355. titleOptions.iconBase = this.options.iconBase;
  1356. }
  1357. if (that.options.showSubtext && !that.multiple && thisData.subtext) titleOptions.subtext = ' ' + thisData.subtext;
  1358. titleOptions.text = option.textContent.trim();
  1359. }
  1360. titleFragment.appendChild(generateOption.text(titleOptions, true));
  1361. } else {
  1362. break;
  1363. }
  1364. }
  1365. // add ellipsis
  1366. if (selectedCount > 49) {
  1367. titleFragment.appendChild(document.createTextNode('...'));
  1368. }
  1369. } else {
  1370. var optionSelector = ':not([hidden]):not([data-hidden="true"]):not([data-divider="true"])';
  1371. if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
  1372. // If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected, etc.
  1373. var totalCount = this.$element[0].querySelectorAll('select > option' + optionSelector + ', optgroup' + optionSelector + ' option' + optionSelector).length,
  1374. tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedCount, totalCount) : this.options.countSelectedText;
  1375. titleFragment = generateOption.text({
  1376. text: tr8nText.replace('{0}', selectedCount.toString()).replace('{1}', totalCount.toString())
  1377. }, true);
  1378. }
  1379. }
  1380. if (this.options.title == undefined) {
  1381. // use .attr to ensure undefined is returned if title attribute is not set
  1382. this.options.title = this.$element.attr('title');
  1383. }
  1384. // If the select doesn't have a title, then use the default, or if nothing is set at all, use noneSelectedText
  1385. if (!titleFragment.childNodes.length) {
  1386. titleFragment = generateOption.text({
  1387. text: typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText
  1388. }, true);
  1389. }
  1390. // strip all HTML tags and trim the result, then unescape any escaped tags
  1391. button.title = titleFragment.textContent.replace(/<[^>]*>?/g, '').trim();
  1392. if (this.options.sanitize && hasContent) {
  1393. sanitizeHtml([titleFragment], that.options.whiteList, that.options.sanitizeFn);
  1394. }
  1395. buttonInner.innerHTML = '';
  1396. buttonInner.appendChild(titleFragment);
  1397. if (version.major < 4 && this.$newElement[0].classList.contains('bs3-has-addon')) {
  1398. var filterExpand = button.querySelector('.filter-expand'),
  1399. clone = buttonInner.cloneNode(true);
  1400. clone.className = 'filter-expand';
  1401. if (filterExpand) {
  1402. button.replaceChild(clone, filterExpand);
  1403. } else {
  1404. button.appendChild(clone);
  1405. }
  1406. }
  1407. this.$element.trigger('rendered' + EVENT_KEY);
  1408. },
  1409. /**
  1410. * @param [style]
  1411. * @param [status]
  1412. */
  1413. setStyle: function (newStyle, status) {
  1414. var button = this.$button[0],
  1415. newElement = this.$newElement[0],
  1416. style = this.options.style.trim(),
  1417. buttonClass;
  1418. if (this.$element.attr('class')) {
  1419. this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, ''));
  1420. }
  1421. if (version.major < 4) {
  1422. newElement.classList.add('bs3');
  1423. if (newElement.parentNode.classList.contains('input-group') &&
  1424. (newElement.previousElementSibling || newElement.nextElementSibling) &&
  1425. (newElement.previousElementSibling || newElement.nextElementSibling).classList.contains('input-group-addon')
  1426. ) {
  1427. newElement.classList.add('bs3-has-addon');
  1428. }
  1429. }
  1430. if (newStyle) {
  1431. buttonClass = newStyle.trim();
  1432. } else {
  1433. buttonClass = style;
  1434. }
  1435. if (status == 'add') {
  1436. if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' '));
  1437. } else if (status == 'remove') {
  1438. if (buttonClass) button.classList.remove.apply(button.classList, buttonClass.split(' '));
  1439. } else {
  1440. if (style) button.classList.remove.apply(button.classList, style.split(' '));
  1441. if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' '));
  1442. }
  1443. },
  1444. liHeight: function (refresh) {
  1445. if (!refresh && (this.options.size === false || this.sizeInfo)) return;
  1446. if (!this.sizeInfo) this.sizeInfo = {};
  1447. var newElement = document.createElement('div'),
  1448. menu = document.createElement('div'),
  1449. menuInner = document.createElement('div'),
  1450. menuInnerInner = document.createElement('ul'),
  1451. divider = document.createElement('li'),
  1452. dropdownHeader = document.createElement('li'),
  1453. li = document.createElement('li'),
  1454. a = document.createElement('a'),
  1455. text = document.createElement('span'),
  1456. header = this.options.header && this.$menu.find('.' + classNames.POPOVERHEADER).length > 0 ? this.$menu.find('.' + classNames.POPOVERHEADER)[0].cloneNode(true) : null,
  1457. search = this.options.liveSearch ? document.createElement('div') : null,
  1458. actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
  1459. doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null,
  1460. firstOption = this.$element.find('option')[0];
  1461. this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth;
  1462. text.className = 'text';
  1463. a.className = 'dropdown-item ' + (firstOption ? firstOption.className : '');
  1464. newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW;
  1465. newElement.style.width = this.sizeInfo.selectWidth + 'px';
  1466. if (this.options.width === 'auto') menu.style.minWidth = 0;
  1467. menu.className = classNames.MENU + ' ' + classNames.SHOW;
  1468. menuInner.className = 'inner ' + classNames.SHOW;
  1469. menuInnerInner.className = classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '');
  1470. divider.className = classNames.DIVIDER;
  1471. dropdownHeader.className = 'dropdown-header';
  1472. text.appendChild(document.createTextNode('\u200b'));
  1473. a.appendChild(text);
  1474. li.appendChild(a);
  1475. dropdownHeader.appendChild(text.cloneNode(true));
  1476. if (this.selectpicker.view.widestOption) {
  1477. menuInnerInner.appendChild(this.selectpicker.view.widestOption.cloneNode(true));
  1478. }
  1479. menuInnerInner.appendChild(li);
  1480. menuInnerInner.appendChild(divider);
  1481. menuInnerInner.appendChild(dropdownHeader);
  1482. if (header) menu.appendChild(header);
  1483. if (search) {
  1484. var input = document.createElement('input');
  1485. search.className = 'bs-searchbox';
  1486. input.className = 'form-control';
  1487. search.appendChild(input);
  1488. menu.appendChild(search);
  1489. }
  1490. if (actions) menu.appendChild(actions);
  1491. menuInner.appendChild(menuInnerInner);
  1492. menu.appendChild(menuInner);
  1493. if (doneButton) menu.appendChild(doneButton);
  1494. newElement.appendChild(menu);
  1495. document.body.appendChild(newElement);
  1496. var liHeight = li.offsetHeight,
  1497. dropdownHeaderHeight = dropdownHeader ? dropdownHeader.offsetHeight : 0,
  1498. headerHeight = header ? header.offsetHeight : 0,
  1499. searchHeight = search ? search.offsetHeight : 0,
  1500. actionsHeight = actions ? actions.offsetHeight : 0,
  1501. doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
  1502. dividerHeight = $(divider).outerHeight(true),
  1503. // fall back to jQuery if getComputedStyle is not supported
  1504. menuStyle = window.getComputedStyle ? window.getComputedStyle(menu) : false,
  1505. menuWidth = menu.offsetWidth,
  1506. $menu = menuStyle ? null : $(menu),
  1507. menuPadding = {
  1508. vert: toInteger(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
  1509. toInteger(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
  1510. toInteger(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
  1511. toInteger(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
  1512. horiz: toInteger(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
  1513. toInteger(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
  1514. toInteger(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
  1515. toInteger(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
  1516. },
  1517. menuExtras = {
  1518. vert: menuPadding.vert +
  1519. toInteger(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
  1520. toInteger(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
  1521. horiz: menuPadding.horiz +
  1522. toInteger(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
  1523. toInteger(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
  1524. },
  1525. scrollBarWidth;
  1526. menuInner.style.overflowY = 'scroll';
  1527. scrollBarWidth = menu.offsetWidth - menuWidth;
  1528. document.body.removeChild(newElement);
  1529. this.sizeInfo.liHeight = liHeight;
  1530. this.sizeInfo.dropdownHeaderHeight = dropdownHeaderHeight;
  1531. this.sizeInfo.headerHeight = headerHeight;
  1532. this.sizeInfo.searchHeight = searchHeight;
  1533. this.sizeInfo.actionsHeight = actionsHeight;
  1534. this.sizeInfo.doneButtonHeight = doneButtonHeight;
  1535. this.sizeInfo.dividerHeight = dividerHeight;
  1536. this.sizeInfo.menuPadding = menuPadding;
  1537. this.sizeInfo.menuExtras = menuExtras;
  1538. this.sizeInfo.menuWidth = menuWidth;
  1539. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth;
  1540. this.sizeInfo.scrollBarWidth = scrollBarWidth;
  1541. this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight;
  1542. this.setPositionData();
  1543. },
  1544. getSelectPosition: function () {
  1545. var that = this,
  1546. $window = $(window),
  1547. pos = that.$newElement.offset(),
  1548. $container = $(that.options.container),
  1549. containerPos;
  1550. if (that.options.container && $container.length && !$container.is('body')) {
  1551. containerPos = $container.offset();
  1552. containerPos.top += parseInt($container.css('borderTopWidth'));
  1553. containerPos.left += parseInt($container.css('borderLeftWidth'));
  1554. } else {
  1555. containerPos = { top: 0, left: 0 };
  1556. }
  1557. var winPad = that.options.windowPadding;
  1558. this.sizeInfo.selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
  1559. this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo.selectHeight - containerPos.top - winPad[2];
  1560. this.sizeInfo.selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
  1561. this.sizeInfo.selectOffsetRight = $window.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo.selectWidth - containerPos.left - winPad[1];
  1562. this.sizeInfo.selectOffsetTop -= winPad[0];
  1563. this.sizeInfo.selectOffsetLeft -= winPad[3];
  1564. },
  1565. setMenuSize: function (isAuto) {
  1566. this.getSelectPosition();
  1567. var selectWidth = this.sizeInfo.selectWidth,
  1568. liHeight = this.sizeInfo.liHeight,
  1569. headerHeight = this.sizeInfo.headerHeight,
  1570. searchHeight = this.sizeInfo.searchHeight,
  1571. actionsHeight = this.sizeInfo.actionsHeight,
  1572. doneButtonHeight = this.sizeInfo.doneButtonHeight,
  1573. divHeight = this.sizeInfo.dividerHeight,
  1574. menuPadding = this.sizeInfo.menuPadding,
  1575. menuInnerHeight,
  1576. menuHeight,
  1577. divLength = 0,
  1578. minHeight,
  1579. _minHeight,
  1580. maxHeight,
  1581. menuInnerMinHeight,
  1582. estimate;
  1583. if (this.options.dropupAuto) {
  1584. // Get the estimated height of the menu without scrollbars.
  1585. // This is useful for smaller menus, where there might be plenty of room
  1586. // below the button without setting dropup, but we can't know
  1587. // the exact height of the menu until createView is called later
  1588. estimate = liHeight * this.selectpicker.current.elements.length + menuPadding.vert;
  1589. this.$newElement.toggleClass(classNames.DROPUP, this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && estimate + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot);
  1590. }
  1591. if (this.options.size === 'auto') {
  1592. _minHeight = this.selectpicker.current.elements.length > 3 ? this.sizeInfo.liHeight * 3 + this.sizeInfo.menuExtras.vert - 2 : 0;
  1593. menuHeight = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert;
  1594. minHeight = _minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1595. menuInnerMinHeight = Math.max(_minHeight - menuPadding.vert, 0);
  1596. if (this.$newElement.hasClass(classNames.DROPUP)) {
  1597. menuHeight = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert;
  1598. }
  1599. maxHeight = menuHeight;
  1600. menuInnerHeight = menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert;
  1601. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1602. for (var i = 0; i < this.options.size; i++) {
  1603. if (this.selectpicker.current.data[i].type === 'divider') divLength++;
  1604. }
  1605. menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
  1606. menuInnerHeight = menuHeight - menuPadding.vert;
  1607. maxHeight = menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1608. minHeight = menuInnerMinHeight = '';
  1609. }
  1610. if (this.options.dropdownAlignRight === 'auto') {
  1611. this.$menu.toggleClass(classNames.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < (this.sizeInfo.totalMenuWidth - selectWidth));
  1612. }
  1613. this.$menu.css({
  1614. 'max-height': maxHeight + 'px',
  1615. 'overflow': 'hidden',
  1616. 'min-height': minHeight + 'px'
  1617. });
  1618. this.$menuInner.css({
  1619. 'max-height': menuInnerHeight + 'px',
  1620. 'overflow-y': 'auto',
  1621. 'min-height': menuInnerMinHeight + 'px'
  1622. });
  1623. // ensure menuInnerHeight is always a positive number to prevent issues calculating chunkSize in createView
  1624. this.sizeInfo.menuInnerHeight = Math.max(menuInnerHeight, 1);
  1625. if (this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight) {
  1626. this.sizeInfo.hasScrollBar = true;
  1627. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth;
  1628. this.$menu.css('min-width', this.sizeInfo.totalMenuWidth);
  1629. }
  1630. if (this.dropdown && this.dropdown._popper) this.dropdown._popper.update();
  1631. },
  1632. setSize: function (refresh) {
  1633. this.liHeight(refresh);
  1634. if (this.options.header) this.$menu.css('padding-top', 0);
  1635. if (this.options.size === false) return;
  1636. var that = this,
  1637. $window = $(window),
  1638. selectedIndex,
  1639. offset = 0;
  1640. this.setMenuSize();
  1641. if (this.options.liveSearch) {
  1642. this.$searchbox
  1643. .off('input.setMenuSize propertychange.setMenuSize')
  1644. .on('input.setMenuSize propertychange.setMenuSize', function () {
  1645. return that.setMenuSize();
  1646. });
  1647. }
  1648. if (this.options.size === 'auto') {
  1649. $window
  1650. .off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize')
  1651. .on('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize', function () {
  1652. return that.setMenuSize();
  1653. });
  1654. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1655. $window.off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize');
  1656. }
  1657. if (refresh) {
  1658. offset = this.$menuInner[0].scrollTop;
  1659. } else if (!that.multiple) {
  1660. var element = that.$element[0];
  1661. selectedIndex = (element.options[element.selectedIndex] || {}).liIndex;
  1662. if (typeof selectedIndex === 'number' && that.options.size !== false) {
  1663. offset = that.sizeInfo.liHeight * selectedIndex;
  1664. offset = offset - (that.sizeInfo.menuInnerHeight / 2) + (that.sizeInfo.liHeight / 2);
  1665. }
  1666. }
  1667. that.createView(false, offset);
  1668. },
  1669. setWidth: function () {
  1670. var that = this;
  1671. if (this.options.width === 'auto') {
  1672. requestAnimationFrame(function () {
  1673. that.$menu.css('min-width', '0');
  1674. that.$element.on('loaded' + EVENT_KEY, function () {
  1675. that.liHeight();
  1676. that.setMenuSize();
  1677. // Get correct width if element is hidden
  1678. var $selectClone = that.$newElement.clone().appendTo('body'),
  1679. btnWidth = $selectClone.css('width', 'auto').children('button').outerWidth();
  1680. $selectClone.remove();
  1681. // Set width to whatever's larger, button title or longest option
  1682. that.sizeInfo.selectWidth = Math.max(that.sizeInfo.totalMenuWidth, btnWidth);
  1683. that.$newElement.css('width', that.sizeInfo.selectWidth + 'px');
  1684. });
  1685. });
  1686. } else if (this.options.width === 'fit') {
  1687. // Remove inline min-width so width can be changed from 'auto'
  1688. this.$menu.css('min-width', '');
  1689. this.$newElement.css('width', '').addClass('fit-width');
  1690. } else if (this.options.width) {
  1691. // Remove inline min-width so width can be changed from 'auto'
  1692. this.$menu.css('min-width', '');
  1693. this.$newElement.css('width', this.options.width);
  1694. } else {
  1695. // Remove inline min-width/width so width can be changed
  1696. this.$menu.css('min-width', '');
  1697. this.$newElement.css('width', '');
  1698. }
  1699. // Remove fit-width class if width is changed programmatically
  1700. if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
  1701. this.$newElement[0].classList.remove('fit-width');
  1702. }
  1703. },
  1704. selectPosition: function () {
  1705. this.$bsContainer = $('<div class="bs-container" />');
  1706. var that = this,
  1707. $container = $(this.options.container),
  1708. pos,
  1709. containerPos,
  1710. actualHeight,
  1711. getPlacement = function ($element) {
  1712. var containerPosition = {},
  1713. // fall back to dropdown's default display setting if display is not manually set
  1714. display = that.options.display || (
  1715. // Bootstrap 3 doesn't have $.fn.dropdown.Constructor.Default
  1716. $.fn.dropdown.Constructor.Default ? $.fn.dropdown.Constructor.Default.display
  1717. : false
  1718. );
  1719. that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass(classNames.DROPUP, $element.hasClass(classNames.DROPUP));
  1720. pos = $element.offset();
  1721. if (!$container.is('body')) {
  1722. containerPos = $container.offset();
  1723. containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
  1724. containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
  1725. } else {
  1726. containerPos = { top: 0, left: 0 };
  1727. }
  1728. actualHeight = $element.hasClass(classNames.DROPUP) ? 0 : $element[0].offsetHeight;
  1729. // Bootstrap 4+ uses Popper for menu positioning
  1730. if (version.major < 4 || display === 'static') {
  1731. containerPosition.top = pos.top - containerPos.top + actualHeight;
  1732. containerPosition.left = pos.left - containerPos.left;
  1733. }
  1734. containerPosition.width = $element[0].offsetWidth;
  1735. that.$bsContainer.css(containerPosition);
  1736. };
  1737. this.$button.on('click.bs.dropdown.data-api', function () {
  1738. if (that.isDisabled()) {
  1739. return;
  1740. }
  1741. getPlacement(that.$newElement);
  1742. that.$bsContainer
  1743. .appendTo(that.options.container)
  1744. .toggleClass(classNames.SHOW, !that.$button.hasClass(classNames.SHOW))
  1745. .append(that.$menu);
  1746. });
  1747. $(window)
  1748. .off('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId)
  1749. .on('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId, function () {
  1750. var isActive = that.$newElement.hasClass(classNames.SHOW);
  1751. if (isActive) getPlacement(that.$newElement);
  1752. });
  1753. this.$element.on('hide' + EVENT_KEY, function () {
  1754. that.$menu.data('height', that.$menu.height());
  1755. that.$bsContainer.detach();
  1756. });
  1757. },
  1758. setOptionStatus: function () {
  1759. var that = this;
  1760. that.noScroll = false;
  1761. if (that.selectpicker.view.visibleElements && that.selectpicker.view.visibleElements.length) {
  1762. for (var i = 0; i < that.selectpicker.view.visibleElements.length; i++) {
  1763. var liData = that.selectpicker.current.data[i + that.selectpicker.view.position0],
  1764. option = liData.option;
  1765. if (option) {
  1766. that.setDisabled(
  1767. liData.index,
  1768. liData.disabled
  1769. );
  1770. that.setSelected(
  1771. liData.index,
  1772. option.selected
  1773. );
  1774. }
  1775. }
  1776. }
  1777. },
  1778. /**
  1779. * @param {number} index - the index of the option that is being changed
  1780. * @param {boolean} selected - true if the option is being selected, false if being deselected
  1781. */
  1782. setSelected: function (index, selected) {
  1783. var li = this.selectpicker.main.elements[index],
  1784. liData = this.selectpicker.main.data[index],
  1785. activeIndexIsSet = this.activeIndex !== undefined,
  1786. thisIsActive = this.activeIndex === index,
  1787. prevActive,
  1788. a,
  1789. // if current option is already active
  1790. // OR
  1791. // if the current option is being selected, it's NOT multiple, and
  1792. // activeIndex is undefined:
  1793. // - when the menu is first being opened, OR
  1794. // - after a search has been performed, OR
  1795. // - when retainActive is false when selecting a new option (i.e. index of the newly selected option is not the same as the current activeIndex)
  1796. keepActive = thisIsActive || (selected && !this.multiple && !activeIndexIsSet);
  1797. liData.selected = selected;
  1798. a = li.firstChild;
  1799. if (selected) {
  1800. this.selectedIndex = index;
  1801. }
  1802. li.classList.toggle('selected', selected);
  1803. li.classList.toggle('active', keepActive);
  1804. if (keepActive) {
  1805. this.selectpicker.view.currentActive = li;
  1806. this.activeIndex = index;
  1807. }
  1808. if (a) {
  1809. a.classList.toggle('selected', selected);
  1810. a.classList.toggle('active', keepActive);
  1811. a.setAttribute('aria-selected', selected);
  1812. }
  1813. if (!keepActive) {
  1814. if (!activeIndexIsSet && selected && this.prevActiveIndex !== undefined) {
  1815. prevActive = this.selectpicker.main.elements[this.prevActiveIndex];
  1816. prevActive.classList.remove('active');
  1817. if (prevActive.firstChild) {
  1818. prevActive.firstChild.classList.remove('active');
  1819. }
  1820. }
  1821. }
  1822. },
  1823. /**
  1824. * @param {number} index - the index of the option that is being disabled
  1825. * @param {boolean} disabled - true if the option is being disabled, false if being enabled
  1826. */
  1827. setDisabled: function (index, disabled) {
  1828. var li = this.selectpicker.main.elements[index],
  1829. a;
  1830. this.selectpicker.main.data[index].disabled = disabled;
  1831. a = li.firstChild;
  1832. li.classList.toggle(classNames.DISABLED, disabled);
  1833. if (a) {
  1834. if (version.major === '4') a.classList.toggle(classNames.DISABLED, disabled);
  1835. a.setAttribute('aria-disabled', disabled);
  1836. if (disabled) {
  1837. a.setAttribute('tabindex', -1);
  1838. } else {
  1839. a.setAttribute('tabindex', 0);
  1840. }
  1841. }
  1842. },
  1843. isDisabled: function () {
  1844. return this.$element[0].disabled;
  1845. },
  1846. checkDisabled: function () {
  1847. var that = this;
  1848. if (this.isDisabled()) {
  1849. this.$newElement[0].classList.add(classNames.DISABLED);
  1850. this.$button.addClass(classNames.DISABLED).attr('tabindex', -1).attr('aria-disabled', true);
  1851. } else {
  1852. if (this.$button[0].classList.contains(classNames.DISABLED)) {
  1853. this.$newElement[0].classList.remove(classNames.DISABLED);
  1854. this.$button.removeClass(classNames.DISABLED).attr('aria-disabled', false);
  1855. }
  1856. if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
  1857. this.$button.removeAttr('tabindex');
  1858. }
  1859. }
  1860. this.$button.on('click', function () {
  1861. return !that.isDisabled();
  1862. });
  1863. },
  1864. togglePlaceholder: function () {
  1865. // much faster than calling $.val()
  1866. var element = this.$element[0],
  1867. selectedIndex = element.selectedIndex,
  1868. nothingSelected = selectedIndex === -1;
  1869. if (!nothingSelected && !element.options[selectedIndex].value) nothingSelected = true;
  1870. this.$button.toggleClass('bs-placeholder', nothingSelected);
  1871. },
  1872. tabIndex: function () {
  1873. if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
  1874. (this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
  1875. this.$element.data('tabindex', this.$element.attr('tabindex'));
  1876. this.$button.attr('tabindex', this.$element.data('tabindex'));
  1877. }
  1878. this.$element.attr('tabindex', -98);
  1879. },
  1880. clickListener: function () {
  1881. var that = this,
  1882. $document = $(document);
  1883. $document.data('spaceSelect', false);
  1884. this.$button.on('keyup', function (e) {
  1885. if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
  1886. e.preventDefault();
  1887. $document.data('spaceSelect', false);
  1888. }
  1889. });
  1890. this.$newElement.on('show.bs.dropdown', function () {
  1891. if (version.major > 3 && !that.dropdown) {
  1892. that.dropdown = that.$button.data('bs.dropdown');
  1893. that.dropdown._menu = that.$menu[0];
  1894. }
  1895. });
  1896. this.$button.on('click.bs.dropdown.data-api', function () {
  1897. if (!that.$newElement.hasClass(classNames.SHOW)) {
  1898. that.setSize();
  1899. }
  1900. });
  1901. function setFocus () {
  1902. if (that.options.liveSearch) {
  1903. that.$searchbox.trigger('focus');
  1904. } else {
  1905. that.$menuInner.trigger('focus');
  1906. }
  1907. }
  1908. function checkPopperExists () {
  1909. if (that.dropdown && that.dropdown._popper && that.dropdown._popper.state.isCreated) {
  1910. setFocus();
  1911. } else {
  1912. requestAnimationFrame(checkPopperExists);
  1913. }
  1914. }
  1915. this.$element.on('shown' + EVENT_KEY, function () {
  1916. if (that.$menuInner[0].scrollTop !== that.selectpicker.view.scrollTop) {
  1917. that.$menuInner[0].scrollTop = that.selectpicker.view.scrollTop;
  1918. }
  1919. if (version.major > 3) {
  1920. requestAnimationFrame(checkPopperExists);
  1921. } else {
  1922. setFocus();
  1923. }
  1924. });
  1925. this.$menuInner.on('click', 'li a', function (e, retainActive) {
  1926. var $this = $(this),
  1927. position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
  1928. clickedData = that.selectpicker.current.data[$this.parent().index() + position0],
  1929. clickedIndex = clickedData.index,
  1930. prevValue = getSelectValues(that.$element[0]),
  1931. prevIndex = that.$element.prop('selectedIndex'),
  1932. triggerChange = true;
  1933. // Don't close on multi choice menu
  1934. if (that.multiple && that.options.maxOptions !== 1) {
  1935. e.stopPropagation();
  1936. }
  1937. e.preventDefault();
  1938. // Don't run if the select is disabled
  1939. if (!that.isDisabled() && !$this.parent().hasClass(classNames.DISABLED)) {
  1940. var $options = that.$element.find('option'),
  1941. option = clickedData.option,
  1942. $option = $(option),
  1943. state = option.selected,
  1944. $optgroup = $option.parent('optgroup'),
  1945. $optgroupOptions = $optgroup.find('option'),
  1946. maxOptions = that.options.maxOptions,
  1947. maxOptionsGrp = $optgroup.data('maxOptions') || false;
  1948. if (clickedIndex === that.activeIndex) retainActive = true;
  1949. if (!retainActive) {
  1950. that.prevActiveIndex = that.activeIndex;
  1951. that.activeIndex = undefined;
  1952. }
  1953. if (!that.multiple) { // Deselect all others if not multi select box
  1954. $options.prop('selected', false);
  1955. option.selected = true;
  1956. that.setSelected(clickedIndex, true);
  1957. } else { // Toggle the one we have chosen if we are multi select.
  1958. option.selected = !state;
  1959. that.setSelected(clickedIndex, !state);
  1960. $this.trigger('blur');
  1961. if (maxOptions !== false || maxOptionsGrp !== false) {
  1962. var maxReached = maxOptions < $options.filter(':selected').length,
  1963. maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
  1964. if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
  1965. if (maxOptions && maxOptions == 1) {
  1966. $options.prop('selected', false);
  1967. $option.prop('selected', true);
  1968. for (var i = 0; i < $options.length; i++) {
  1969. that.setSelected(i, false);
  1970. }
  1971. that.setSelected(clickedIndex, true);
  1972. } else if (maxOptionsGrp && maxOptionsGrp == 1) {
  1973. $optgroup.find('option:selected').prop('selected', false);
  1974. $option.prop('selected', true);
  1975. for (var i = 0; i < $optgroupOptions.length; i++) {
  1976. var option = $optgroupOptions[i];
  1977. that.setSelected($options.index(option), false);
  1978. }
  1979. that.setSelected(clickedIndex, true);
  1980. } else {
  1981. var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
  1982. maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
  1983. maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
  1984. maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
  1985. $notify = $('<div class="notify"></div>');
  1986. // If {var} is set in array, replace it
  1987. /** @deprecated */
  1988. if (maxOptionsArr[2]) {
  1989. maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
  1990. maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
  1991. }
  1992. $option.prop('selected', false);
  1993. that.$menu.append($notify);
  1994. if (maxOptions && maxReached) {
  1995. $notify.append($('<div>' + maxTxt + '</div>'));
  1996. triggerChange = false;
  1997. that.$element.trigger('maxReached' + EVENT_KEY);
  1998. }
  1999. if (maxOptionsGrp && maxReachedGrp) {
  2000. $notify.append($('<div>' + maxTxtGrp + '</div>'));
  2001. triggerChange = false;
  2002. that.$element.trigger('maxReachedGrp' + EVENT_KEY);
  2003. }
  2004. setTimeout(function () {
  2005. that.setSelected(clickedIndex, false);
  2006. }, 10);
  2007. $notify.delay(750).fadeOut(300, function () {
  2008. $(this).remove();
  2009. });
  2010. }
  2011. }
  2012. }
  2013. }
  2014. if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) {
  2015. that.$button.trigger('focus');
  2016. } else if (that.options.liveSearch) {
  2017. that.$searchbox.trigger('focus');
  2018. }
  2019. // Trigger select 'change'
  2020. if (triggerChange) {
  2021. if ((prevValue != getSelectValues(that.$element[0]) && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
  2022. // $option.prop('selected') is current option state (selected/unselected). prevValue is the value of the select prior to being changed.
  2023. changedArguments = [option.index, $option.prop('selected'), prevValue];
  2024. that.$element
  2025. .triggerNative('change');
  2026. }
  2027. }
  2028. }
  2029. });
  2030. this.$menu.on('click', 'li.' + classNames.DISABLED + ' a, .' + classNames.POPOVERHEADER + ', .' + classNames.POPOVERHEADER + ' :not(.close)', function (e) {
  2031. if (e.currentTarget == this) {
  2032. e.preventDefault();
  2033. e.stopPropagation();
  2034. if (that.options.liveSearch && !$(e.target).hasClass('close')) {
  2035. that.$searchbox.trigger('focus');
  2036. } else {
  2037. that.$button.trigger('focus');
  2038. }
  2039. }
  2040. });
  2041. this.$menuInner.on('click', '.divider, .dropdown-header', function (e) {
  2042. e.preventDefault();
  2043. e.stopPropagation();
  2044. if (that.options.liveSearch) {
  2045. that.$searchbox.trigger('focus');
  2046. } else {
  2047. that.$button.trigger('focus');
  2048. }
  2049. });
  2050. this.$menu.on('click', '.' + classNames.POPOVERHEADER + ' .close', function () {
  2051. that.$button.trigger('click');
  2052. });
  2053. this.$searchbox.on('click', function (e) {
  2054. e.stopPropagation();
  2055. });
  2056. this.$menu.on('click', '.actions-btn', function (e) {
  2057. if (that.options.liveSearch) {
  2058. that.$searchbox.trigger('focus');
  2059. } else {
  2060. that.$button.trigger('focus');
  2061. }
  2062. e.preventDefault();
  2063. e.stopPropagation();
  2064. if ($(this).hasClass('bs-select-all')) {
  2065. that.selectAll();
  2066. } else {
  2067. that.deselectAll();
  2068. }
  2069. });
  2070. this.$element
  2071. .on('change' + EVENT_KEY, function () {
  2072. that.render();
  2073. that.$element.trigger('changed' + EVENT_KEY, changedArguments);
  2074. changedArguments = null;
  2075. })
  2076. .on('focus' + EVENT_KEY, function () {
  2077. if (!that.options.mobile) that.$button.trigger('focus');
  2078. });
  2079. },
  2080. liveSearchListener: function () {
  2081. var that = this,
  2082. noResults = document.createElement('li');
  2083. this.$button.on('click.bs.dropdown.data-api', function () {
  2084. if (!!that.$searchbox.val()) {
  2085. that.$searchbox.val('');
  2086. }
  2087. });
  2088. this.$searchbox.on('click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api', function (e) {
  2089. e.stopPropagation();
  2090. });
  2091. this.$searchbox.on('input propertychange', function () {
  2092. var searchValue = that.$searchbox.val();
  2093. that.selectpicker.search.elements = [];
  2094. that.selectpicker.search.data = [];
  2095. if (searchValue) {
  2096. var i,
  2097. searchMatch = [],
  2098. q = searchValue.toUpperCase(),
  2099. cache = {},
  2100. cacheArr = [],
  2101. searchStyle = that._searchStyle(),
  2102. normalizeSearch = that.options.liveSearchNormalize;
  2103. if (normalizeSearch) q = normalizeToBase(q);
  2104. that._$lisSelected = that.$menuInner.find('.selected');
  2105. for (var i = 0; i < that.selectpicker.main.data.length; i++) {
  2106. var li = that.selectpicker.main.data[i];
  2107. if (!cache[i]) {
  2108. cache[i] = stringSearch(li, q, searchStyle, normalizeSearch);
  2109. }
  2110. if (cache[i] && li.headerIndex !== undefined && cacheArr.indexOf(li.headerIndex) === -1) {
  2111. if (li.headerIndex > 0) {
  2112. cache[li.headerIndex - 1] = true;
  2113. cacheArr.push(li.headerIndex - 1);
  2114. }
  2115. cache[li.headerIndex] = true;
  2116. cacheArr.push(li.headerIndex);
  2117. cache[li.lastIndex + 1] = true;
  2118. }
  2119. if (cache[i] && li.type !== 'optgroup-label') cacheArr.push(i);
  2120. }
  2121. for (var i = 0, cacheLen = cacheArr.length; i < cacheLen; i++) {
  2122. var index = cacheArr[i],
  2123. prevIndex = cacheArr[i - 1],
  2124. li = that.selectpicker.main.data[index],
  2125. liPrev = that.selectpicker.main.data[prevIndex];
  2126. if (li.type !== 'divider' || (li.type === 'divider' && liPrev && liPrev.type !== 'divider' && cacheLen - 1 !== i)) {
  2127. that.selectpicker.search.data.push(li);
  2128. searchMatch.push(that.selectpicker.main.elements[index]);
  2129. }
  2130. }
  2131. that.activeIndex = undefined;
  2132. that.noScroll = true;
  2133. that.$menuInner.scrollTop(0);
  2134. that.selectpicker.search.elements = searchMatch;
  2135. that.createView(true);
  2136. if (!searchMatch.length) {
  2137. noResults.className = 'no-results';
  2138. noResults.innerHTML = that.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"');
  2139. that.$menuInner[0].firstChild.appendChild(noResults);
  2140. }
  2141. } else {
  2142. that.$menuInner.scrollTop(0);
  2143. that.createView(false);
  2144. }
  2145. });
  2146. },
  2147. _searchStyle: function () {
  2148. return this.options.liveSearchStyle || 'contains';
  2149. },
  2150. val: function (value) {
  2151. if (typeof value !== 'undefined') {
  2152. var prevValue = getSelectValues(this.$element[0]);
  2153. changedArguments = [null, null, prevValue];
  2154. this.$element
  2155. .val(value)
  2156. .trigger('changed' + EVENT_KEY, changedArguments);
  2157. this.render();
  2158. changedArguments = null;
  2159. return this.$element;
  2160. } else {
  2161. return this.$element.val();
  2162. }
  2163. },
  2164. changeAll: function (status) {
  2165. if (!this.multiple) return;
  2166. if (typeof status === 'undefined') status = true;
  2167. var element = this.$element[0],
  2168. previousSelected = 0,
  2169. currentSelected = 0,
  2170. prevValue = getSelectValues(element);
  2171. element.classList.add('bs-select-hidden');
  2172. for (var i = 0, len = this.selectpicker.current.elements.length; i < len; i++) {
  2173. var liData = this.selectpicker.current.data[i],
  2174. option = liData.option;
  2175. if (option && !liData.disabled && liData.type !== 'divider') {
  2176. if (liData.selected) previousSelected++;
  2177. option.selected = status;
  2178. if (status) currentSelected++;
  2179. }
  2180. }
  2181. element.classList.remove('bs-select-hidden');
  2182. if (previousSelected === currentSelected) return;
  2183. this.setOptionStatus();
  2184. this.togglePlaceholder();
  2185. changedArguments = [null, null, prevValue];
  2186. this.$element
  2187. .triggerNative('change');
  2188. },
  2189. selectAll: function () {
  2190. return this.changeAll(true);
  2191. },
  2192. deselectAll: function () {
  2193. return this.changeAll(false);
  2194. },
  2195. toggle: function (e) {
  2196. e = e || window.event;
  2197. if (e) e.stopPropagation();
  2198. this.$button.trigger('click.bs.dropdown.data-api');
  2199. },
  2200. keydown: function (e) {
  2201. var $this = $(this),
  2202. isToggle = $this.hasClass('dropdown-toggle'),
  2203. $parent = isToggle ? $this.closest('.dropdown') : $this.closest(Selector.MENU),
  2204. that = $parent.data('this'),
  2205. $items = that.findLis(),
  2206. index,
  2207. isActive,
  2208. liActive,
  2209. activeLi,
  2210. offset,
  2211. updateScroll = false,
  2212. downOnTab = e.which === keyCodes.TAB && !isToggle && !that.options.selectOnTab,
  2213. isArrowKey = REGEXP_ARROW.test(e.which) || downOnTab,
  2214. scrollTop = that.$menuInner[0].scrollTop,
  2215. isVirtual = that.isVirtual(),
  2216. position0 = isVirtual === true ? that.selectpicker.view.position0 : 0;
  2217. isActive = that.$newElement.hasClass(classNames.SHOW);
  2218. if (
  2219. !isActive &&
  2220. (
  2221. isArrowKey ||
  2222. (e.which >= 48 && e.which <= 57) ||
  2223. (e.which >= 96 && e.which <= 105) ||
  2224. (e.which >= 65 && e.which <= 90)
  2225. )
  2226. ) {
  2227. that.$button.trigger('click.bs.dropdown.data-api');
  2228. if (that.options.liveSearch) {
  2229. that.$searchbox.trigger('focus');
  2230. return;
  2231. }
  2232. }
  2233. if (e.which === keyCodes.ESCAPE && isActive) {
  2234. e.preventDefault();
  2235. that.$button.trigger('click.bs.dropdown.data-api').trigger('focus');
  2236. }
  2237. if (isArrowKey) { // if up or down
  2238. if (!$items.length) return;
  2239. // $items.index/.filter is too slow with a large list and no virtual scroll
  2240. index = isVirtual === true ? $items.index($items.filter('.active')) : that.activeIndex;
  2241. if (index === undefined) index = -1;
  2242. if (index !== -1) {
  2243. liActive = that.selectpicker.current.elements[index + position0];
  2244. liActive.classList.remove('active');
  2245. if (liActive.firstChild) liActive.firstChild.classList.remove('active');
  2246. }
  2247. if (e.which === keyCodes.ARROW_UP) { // up
  2248. if (index !== -1) index--;
  2249. if (index + position0 < 0) index += $items.length;
  2250. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2251. index = that.selectpicker.view.canHighlight.slice(0, index + position0).lastIndexOf(true) - position0;
  2252. if (index === -1) index = $items.length - 1;
  2253. }
  2254. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2255. index++;
  2256. if (index + position0 >= that.selectpicker.view.canHighlight.length) index = 0;
  2257. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2258. index = index + 1 + that.selectpicker.view.canHighlight.slice(index + position0 + 1).indexOf(true);
  2259. }
  2260. }
  2261. e.preventDefault();
  2262. var liActiveIndex = position0 + index;
  2263. if (e.which === keyCodes.ARROW_UP) { // up
  2264. // scroll to bottom and highlight last option
  2265. if (position0 === 0 && index === $items.length - 1) {
  2266. that.$menuInner[0].scrollTop = that.$menuInner[0].scrollHeight;
  2267. liActiveIndex = that.selectpicker.current.elements.length - 1;
  2268. } else {
  2269. activeLi = that.selectpicker.current.data[liActiveIndex];
  2270. offset = activeLi.position - activeLi.height;
  2271. updateScroll = offset < scrollTop;
  2272. }
  2273. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2274. // scroll to top and highlight first option
  2275. if (index === 0) {
  2276. that.$menuInner[0].scrollTop = 0;
  2277. liActiveIndex = 0;
  2278. } else {
  2279. activeLi = that.selectpicker.current.data[liActiveIndex];
  2280. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2281. updateScroll = offset > scrollTop;
  2282. }
  2283. }
  2284. liActive = that.selectpicker.current.elements[liActiveIndex];
  2285. if (liActive) {
  2286. liActive.classList.add('active');
  2287. if (liActive.firstChild) liActive.firstChild.classList.add('active');
  2288. }
  2289. that.activeIndex = that.selectpicker.current.data[liActiveIndex].index;
  2290. that.selectpicker.view.currentActive = liActive;
  2291. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2292. if (that.options.liveSearch) {
  2293. that.$searchbox.trigger('focus');
  2294. } else {
  2295. $this.trigger('focus');
  2296. }
  2297. } else if (
  2298. (!$this.is('input') && !REGEXP_TAB_OR_ESCAPE.test(e.which)) ||
  2299. (e.which === keyCodes.SPACE && that.selectpicker.keydown.keyHistory)
  2300. ) {
  2301. var searchMatch,
  2302. matches = [],
  2303. keyHistory;
  2304. e.preventDefault();
  2305. that.selectpicker.keydown.keyHistory += keyCodeMap[e.which];
  2306. if (that.selectpicker.keydown.resetKeyHistory.cancel) clearTimeout(that.selectpicker.keydown.resetKeyHistory.cancel);
  2307. that.selectpicker.keydown.resetKeyHistory.cancel = that.selectpicker.keydown.resetKeyHistory.start();
  2308. keyHistory = that.selectpicker.keydown.keyHistory;
  2309. // if all letters are the same, set keyHistory to just the first character when searching
  2310. if (/^(.)\1+$/.test(keyHistory)) {
  2311. keyHistory = keyHistory.charAt(0);
  2312. }
  2313. // find matches
  2314. for (var i = 0; i < that.selectpicker.current.data.length; i++) {
  2315. var li = that.selectpicker.current.data[i],
  2316. hasMatch;
  2317. hasMatch = stringSearch(li, keyHistory, 'startsWith', true);
  2318. if (hasMatch && that.selectpicker.view.canHighlight[i]) {
  2319. matches.push(li.index);
  2320. }
  2321. }
  2322. if (matches.length) {
  2323. var matchIndex = 0;
  2324. $items.removeClass('active').find('a').removeClass('active');
  2325. // either only one key has been pressed or they are all the same key
  2326. if (keyHistory.length === 1) {
  2327. matchIndex = matches.indexOf(that.activeIndex);
  2328. if (matchIndex === -1 || matchIndex === matches.length - 1) {
  2329. matchIndex = 0;
  2330. } else {
  2331. matchIndex++;
  2332. }
  2333. }
  2334. searchMatch = matches[matchIndex];
  2335. activeLi = that.selectpicker.main.data[searchMatch];
  2336. if (scrollTop - activeLi.position > 0) {
  2337. offset = activeLi.position - activeLi.height;
  2338. updateScroll = true;
  2339. } else {
  2340. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2341. // if the option is already visible at the current scroll position, just keep it the same
  2342. updateScroll = activeLi.position > scrollTop + that.sizeInfo.menuInnerHeight;
  2343. }
  2344. liActive = that.selectpicker.main.elements[searchMatch];
  2345. liActive.classList.add('active');
  2346. if (liActive.firstChild) liActive.firstChild.classList.add('active');
  2347. that.activeIndex = matches[matchIndex];
  2348. liActive.firstChild.focus();
  2349. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2350. $this.trigger('focus');
  2351. }
  2352. }
  2353. // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
  2354. if (
  2355. isActive &&
  2356. (
  2357. (e.which === keyCodes.SPACE && !that.selectpicker.keydown.keyHistory) ||
  2358. e.which === keyCodes.ENTER ||
  2359. (e.which === keyCodes.TAB && that.options.selectOnTab)
  2360. )
  2361. ) {
  2362. if (e.which !== keyCodes.SPACE) e.preventDefault();
  2363. if (!that.options.liveSearch || e.which !== keyCodes.SPACE) {
  2364. that.$menuInner.find('.active a').trigger('click', true); // retain active class
  2365. $this.trigger('focus');
  2366. if (!that.options.liveSearch) {
  2367. // Prevent screen from scrolling if the user hits the spacebar
  2368. e.preventDefault();
  2369. // Fixes spacebar selection of dropdown items in FF & IE
  2370. $(document).data('spaceSelect', true);
  2371. }
  2372. }
  2373. }
  2374. },
  2375. mobile: function () {
  2376. this.$element[0].classList.add('mobile-device');
  2377. },
  2378. refresh: function () {
  2379. // update options if data attributes have been changed
  2380. var config = $.extend({}, this.options, this.$element.data());
  2381. this.options = config;
  2382. this.checkDisabled();
  2383. this.setStyle();
  2384. this.render();
  2385. this.createLi();
  2386. this.setWidth();
  2387. this.setSize(true);
  2388. this.$element.trigger('refreshed' + EVENT_KEY);
  2389. },
  2390. hide: function () {
  2391. this.$newElement.hide();
  2392. },
  2393. show: function () {
  2394. this.$newElement.show();
  2395. },
  2396. remove: function () {
  2397. this.$newElement.remove();
  2398. this.$element.remove();
  2399. },
  2400. destroy: function () {
  2401. this.$newElement.before(this.$element).remove();
  2402. if (this.$bsContainer) {
  2403. this.$bsContainer.remove();
  2404. } else {
  2405. this.$menu.remove();
  2406. }
  2407. this.$element
  2408. .off(EVENT_KEY)
  2409. .removeData('selectpicker')
  2410. .removeClass('bs-select-hidden selectpicker');
  2411. $(window).off(EVENT_KEY + '.' + this.selectId);
  2412. }
  2413. };
  2414. // SELECTPICKER PLUGIN DEFINITION
  2415. // ==============================
  2416. function Plugin (option) {
  2417. // get the args of the outer function..
  2418. var args = arguments;
  2419. // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
  2420. // to get lost/corrupted in android 2.3 and IE9 #715 #775
  2421. var _option = option;
  2422. [].shift.apply(args);
  2423. // if the version was not set successfully
  2424. if (!version.success) {
  2425. // try to retreive it again
  2426. try {
  2427. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  2428. } catch (err) {
  2429. // fall back to use BootstrapVersion if set
  2430. if (Selectpicker.BootstrapVersion) {
  2431. version.full = Selectpicker.BootstrapVersion.split(' ')[0].split('.');
  2432. } else {
  2433. version.full = [version.major, '0', '0'];
  2434. console.warn(
  2435. 'There was an issue retrieving Bootstrap\'s version. ' +
  2436. 'Ensure Bootstrap is being loaded before bootstrap-select and there is no namespace collision. ' +
  2437. 'If loading Bootstrap asynchronously, the version may need to be manually specified via $.fn.selectpicker.Constructor.BootstrapVersion.',
  2438. err
  2439. );
  2440. }
  2441. }
  2442. version.major = version.full[0];
  2443. version.success = true;
  2444. }
  2445. if (version.major === '4') {
  2446. // some defaults need to be changed if using Bootstrap 4
  2447. // check to see if they have already been manually changed before forcing them to update
  2448. var toUpdate = [];
  2449. if (Selectpicker.DEFAULTS.style === classNames.BUTTONCLASS) toUpdate.push({ name: 'style', className: 'BUTTONCLASS' });
  2450. if (Selectpicker.DEFAULTS.iconBase === classNames.ICONBASE) toUpdate.push({ name: 'iconBase', className: 'ICONBASE' });
  2451. if (Selectpicker.DEFAULTS.tickIcon === classNames.TICKICON) toUpdate.push({ name: 'tickIcon', className: 'TICKICON' });
  2452. classNames.DIVIDER = 'dropdown-divider';
  2453. classNames.SHOW = 'show';
  2454. classNames.BUTTONCLASS = 'btn-light';
  2455. classNames.POPOVERHEADER = 'popover-header';
  2456. classNames.ICONBASE = '';
  2457. classNames.TICKICON = 'bs-ok-default';
  2458. for (var i = 0; i < toUpdate.length; i++) {
  2459. var option = toUpdate[i];
  2460. Selectpicker.DEFAULTS[option.name] = classNames[option.className];
  2461. }
  2462. }
  2463. var value;
  2464. var chain = this.each(function () {
  2465. var $this = $(this);
  2466. if ($this.is('select')) {
  2467. var data = $this.data('selectpicker'),
  2468. options = typeof _option == 'object' && _option;
  2469. if (!data) {
  2470. var dataAttributes = $this.data();
  2471. for (var dataAttr in dataAttributes) {
  2472. if (dataAttributes.hasOwnProperty(dataAttr) && $.inArray(dataAttr, DISALLOWED_ATTRIBUTES) !== -1) {
  2473. delete dataAttributes[dataAttr];
  2474. }
  2475. }
  2476. var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, dataAttributes, options);
  2477. config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), dataAttributes.template, options.template);
  2478. $this.data('selectpicker', (data = new Selectpicker(this, config)));
  2479. } else if (options) {
  2480. for (var i in options) {
  2481. if (options.hasOwnProperty(i)) {
  2482. data.options[i] = options[i];
  2483. }
  2484. }
  2485. }
  2486. if (typeof _option == 'string') {
  2487. if (data[_option] instanceof Function) {
  2488. value = data[_option].apply(data, args);
  2489. } else {
  2490. value = data.options[_option];
  2491. }
  2492. }
  2493. }
  2494. });
  2495. if (typeof value !== 'undefined') {
  2496. // noinspection JSUnusedAssignment
  2497. return value;
  2498. } else {
  2499. return chain;
  2500. }
  2501. }
  2502. var old = $.fn.selectpicker;
  2503. $.fn.selectpicker = Plugin;
  2504. $.fn.selectpicker.Constructor = Selectpicker;
  2505. // SELECTPICKER NO CONFLICT
  2506. // ========================
  2507. $.fn.selectpicker.noConflict = function () {
  2508. $.fn.selectpicker = old;
  2509. return this;
  2510. };
  2511. $(document)
  2512. .off('keydown.bs.dropdown.data-api')
  2513. .on('keydown' + EVENT_KEY, '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', Selectpicker.prototype.keydown)
  2514. .on('focusin.modal', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', function (e) {
  2515. e.stopPropagation();
  2516. });
  2517. // SELECTPICKER DATA-API
  2518. // =====================
  2519. $(window).on('load' + EVENT_KEY + '.data-api', function () {
  2520. $('.selectpicker').each(function () {
  2521. var $selectpicker = $(this);
  2522. Plugin.call($selectpicker, $selectpicker.data());
  2523. })
  2524. });
  2525. })(jQuery);
  2526. }));
  2527. /******************************************************************************/
  2528. // https://github.com/jackmoore/autosize
  2529. (function (global, factory) {
  2530. if (typeof define === "function" && define.amd) {
  2531. define(['module', 'exports'], factory);
  2532. } else if (typeof exports !== "undefined") {
  2533. factory(module, exports);
  2534. } else {
  2535. var mod = {
  2536. exports: {}
  2537. };
  2538. factory(mod, mod.exports);
  2539. global.autosize = mod.exports;
  2540. }
  2541. })(this, function (module, exports) {
  2542. 'use strict';
  2543. var map = typeof Map === "function" ? new Map() : function () {
  2544. var keys = [];
  2545. var values = [];
  2546. return {
  2547. has: function has(key) {
  2548. return keys.indexOf(key) > -1;
  2549. },
  2550. get: function get(key) {
  2551. return values[keys.indexOf(key)];
  2552. },
  2553. set: function set(key, value) {
  2554. if (keys.indexOf(key) === -1) {
  2555. keys.push(key);
  2556. values.push(value);
  2557. }
  2558. },
  2559. delete: function _delete(key) {
  2560. var index = keys.indexOf(key);
  2561. if (index > -1) {
  2562. keys.splice(index, 1);
  2563. values.splice(index, 1);
  2564. }
  2565. }
  2566. };
  2567. }();
  2568. var createEvent = function createEvent(name) {
  2569. return new Event(name, { bubbles: true });
  2570. };
  2571. try {
  2572. new Event('test');
  2573. } catch (e) {
  2574. // IE does not support 'new Event()'
  2575. createEvent = function createEvent(name) {
  2576. var evt = document.createEvent('Event');
  2577. evt.initEvent(name, true, false);
  2578. return evt;
  2579. };
  2580. }
  2581. function assign(ta) {
  2582. if (!ta || !ta.nodeName || ta.nodeName !== 'TEXTAREA' || map.has(ta)) return;
  2583. var heightOffset = null;
  2584. var clientWidth = null;
  2585. var cachedHeight = null;
  2586. function init() {
  2587. var style = window.getComputedStyle(ta, null);
  2588. if (style.resize === 'vertical') {
  2589. ta.style.resize = 'none';
  2590. } else if (style.resize === 'both') {
  2591. ta.style.resize = 'horizontal';
  2592. }
  2593. if (style.boxSizing === 'content-box') {
  2594. heightOffset = -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom));
  2595. } else {
  2596. heightOffset = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
  2597. }
  2598. // Fix when a textarea is not on document body and heightOffset is Not a Number
  2599. if (isNaN(heightOffset)) {
  2600. heightOffset = 0;
  2601. }
  2602. update();
  2603. }
  2604. function changeOverflow(value) {
  2605. {
  2606. // Chrome/Safari-specific fix:
  2607. // When the textarea y-overflow is hidden, Chrome/Safari do not reflow the text to account for the space
  2608. // made available by removing the scrollbar. The following forces the necessary text reflow.
  2609. var width = ta.style.width;
  2610. ta.style.width = '0px';
  2611. // Force reflow:
  2612. /* jshint ignore:start */
  2613. ta.offsetWidth;
  2614. /* jshint ignore:end */
  2615. ta.style.width = width;
  2616. }
  2617. ta.style.overflowY = value;
  2618. }
  2619. function getParentOverflows(el) {
  2620. var arr = [];
  2621. while (el && el.parentNode && el.parentNode instanceof Element) {
  2622. if (el.parentNode.scrollTop) {
  2623. arr.push({
  2624. node: el.parentNode,
  2625. scrollTop: el.parentNode.scrollTop
  2626. });
  2627. }
  2628. el = el.parentNode;
  2629. }
  2630. return arr;
  2631. }
  2632. function resize() {
  2633. if (ta.scrollHeight === 0) {
  2634. // If the scrollHeight is 0, then the element probably has display:none or is detached from the DOM.
  2635. return;
  2636. }
  2637. var overflows = getParentOverflows(ta);
  2638. var docTop = document.documentElement && document.documentElement.scrollTop; // Needed for Mobile IE (ticket #240)
  2639. ta.style.height = '';
  2640. ta.style.height = ta.scrollHeight + heightOffset + 'px';
  2641. // used to check if an update is actually necessary on window.resize
  2642. clientWidth = ta.clientWidth;
  2643. // prevents scroll-position jumping
  2644. overflows.forEach(function (el) {
  2645. el.node.scrollTop = el.scrollTop;
  2646. });
  2647. if (docTop) {
  2648. document.documentElement.scrollTop = docTop;
  2649. }
  2650. }
  2651. function update() {
  2652. resize();
  2653. var styleHeight = Math.round(parseFloat(ta.style.height));
  2654. var computed = window.getComputedStyle(ta, null);
  2655. // Using offsetHeight as a replacement for computed.height in IE, because IE does not account use of border-box
  2656. var actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(computed.height)) : ta.offsetHeight;
  2657. // The actual height not matching the style height (set via the resize method) indicates that
  2658. // the max-height has been exceeded, in which case the overflow should be allowed.
  2659. if (actualHeight < styleHeight) {
  2660. if (computed.overflowY === 'hidden') {
  2661. changeOverflow('scroll');
  2662. resize();
  2663. actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
  2664. }
  2665. } else {
  2666. // Normally keep overflow set to hidden, to avoid flash of scrollbar as the textarea expands.
  2667. if (computed.overflowY !== 'hidden') {
  2668. changeOverflow('hidden');
  2669. resize();
  2670. actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
  2671. }
  2672. }
  2673. if (cachedHeight !== actualHeight) {
  2674. cachedHeight = actualHeight;
  2675. var evt = createEvent('autosize:resized');
  2676. try {
  2677. ta.dispatchEvent(evt);
  2678. } catch (err) {
  2679. // Firefox will throw an error on dispatchEvent for a detached element
  2680. // https://bugzilla.mozilla.org/show_bug.cgi?id=889376
  2681. }
  2682. }
  2683. }
  2684. var pageResize = function pageResize() {
  2685. if (ta.clientWidth !== clientWidth) {
  2686. update();
  2687. }
  2688. };
  2689. var destroy = function (style) {
  2690. window.removeEventListener('resize', pageResize, false);
  2691. ta.removeEventListener('input', update, false);
  2692. ta.removeEventListener('keyup', update, false);
  2693. ta.removeEventListener('autosize:destroy', destroy, false);
  2694. ta.removeEventListener('autosize:update', update, false);
  2695. Object.keys(style).forEach(function (key) {
  2696. ta.style[key] = style[key];
  2697. });
  2698. map.delete(ta);
  2699. }.bind(ta, {
  2700. height: ta.style.height,
  2701. resize: ta.style.resize,
  2702. overflowY: ta.style.overflowY,
  2703. overflowX: ta.style.overflowX,
  2704. wordWrap: ta.style.wordWrap
  2705. });
  2706. ta.addEventListener('autosize:destroy', destroy, false);
  2707. // IE9 does not fire onpropertychange or oninput for deletions,
  2708. // so binding to onkeyup to catch most of those events.
  2709. // There is no way that I know of to detect something like 'cut' in IE9.
  2710. if ('onpropertychange' in ta && 'oninput' in ta) {
  2711. ta.addEventListener('keyup', update, false);
  2712. }
  2713. window.addEventListener('resize', pageResize, false);
  2714. ta.addEventListener('input', update, false);
  2715. ta.addEventListener('autosize:update', update, false);
  2716. ta.style.overflowX = 'hidden';
  2717. ta.style.wordWrap = 'break-word';
  2718. map.set(ta, {
  2719. destroy: destroy,
  2720. update: update
  2721. });
  2722. init();
  2723. }
  2724. function destroy(ta) {
  2725. var methods = map.get(ta);
  2726. if (methods) {
  2727. methods.destroy();
  2728. }
  2729. }
  2730. function update(ta) {
  2731. var methods = map.get(ta);
  2732. if (methods) {
  2733. methods.update();
  2734. }
  2735. }
  2736. var autosize = null;
  2737. // Do nothing in Node.js environment and IE8 (or lower)
  2738. if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') {
  2739. autosize = function autosize(el) {
  2740. return el;
  2741. };
  2742. autosize.destroy = function (el) {
  2743. return el;
  2744. };
  2745. autosize.update = function (el) {
  2746. return el;
  2747. };
  2748. } else {
  2749. autosize = function autosize(el, options) {
  2750. if (el) {
  2751. Array.prototype.forEach.call(el.length ? el : [el], function (x) {
  2752. return assign(x, options);
  2753. });
  2754. }
  2755. return el;
  2756. };
  2757. autosize.destroy = function (el) {
  2758. if (el) {
  2759. Array.prototype.forEach.call(el.length ? el : [el], destroy);
  2760. }
  2761. return el;
  2762. };
  2763. autosize.update = function (el) {
  2764. if (el) {
  2765. Array.prototype.forEach.call(el.length ? el : [el], update);
  2766. }
  2767. return el;
  2768. };
  2769. }
  2770. exports.default = autosize;
  2771. module.exports = exports['default'];
  2772. });
  2773. /******************************************************************************/
  2774. /**!
  2775. * Sortable 1.10.0-rc3
  2776. * @author RubaXa <trash@rubaxa.org>
  2777. * @author owenm <owen23355@gmail.com>
  2778. * @license MIT
  2779. */
  2780. (function (global, factory) {
  2781. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  2782. typeof define === 'function' && define.amd ? define(factory) :
  2783. (global = global || self, global.Sortable = factory());
  2784. }(this, function () { 'use strict';
  2785. function _typeof(obj) {
  2786. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  2787. _typeof = function (obj) {
  2788. return typeof obj;
  2789. };
  2790. } else {
  2791. _typeof = function (obj) {
  2792. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  2793. };
  2794. }
  2795. return _typeof(obj);
  2796. }
  2797. function _defineProperty(obj, key, value) {
  2798. if (key in obj) {
  2799. Object.defineProperty(obj, key, {
  2800. value: value,
  2801. enumerable: true,
  2802. configurable: true,
  2803. writable: true
  2804. });
  2805. } else {
  2806. obj[key] = value;
  2807. }
  2808. return obj;
  2809. }
  2810. function _extends() {
  2811. _extends = Object.assign || function (target) {
  2812. for (var i = 1; i < arguments.length; i++) {
  2813. var source = arguments[i];
  2814. for (var key in source) {
  2815. if (Object.prototype.hasOwnProperty.call(source, key)) {
  2816. target[key] = source[key];
  2817. }
  2818. }
  2819. }
  2820. return target;
  2821. };
  2822. return _extends.apply(this, arguments);
  2823. }
  2824. function _objectSpread(target) {
  2825. for (var i = 1; i < arguments.length; i++) {
  2826. var source = arguments[i] != null ? arguments[i] : {};
  2827. var ownKeys = Object.keys(source);
  2828. if (typeof Object.getOwnPropertySymbols === 'function') {
  2829. ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
  2830. return Object.getOwnPropertyDescriptor(source, sym).enumerable;
  2831. }));
  2832. }
  2833. ownKeys.forEach(function (key) {
  2834. _defineProperty(target, key, source[key]);
  2835. });
  2836. }
  2837. return target;
  2838. }
  2839. function _objectWithoutPropertiesLoose(source, excluded) {
  2840. if (source == null) return {};
  2841. var target = {};
  2842. var sourceKeys = Object.keys(source);
  2843. var key, i;
  2844. for (i = 0; i < sourceKeys.length; i++) {
  2845. key = sourceKeys[i];
  2846. if (excluded.indexOf(key) >= 0) continue;
  2847. target[key] = source[key];
  2848. }
  2849. return target;
  2850. }
  2851. function _objectWithoutProperties(source, excluded) {
  2852. if (source == null) return {};
  2853. var target = _objectWithoutPropertiesLoose(source, excluded);
  2854. var key, i;
  2855. if (Object.getOwnPropertySymbols) {
  2856. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  2857. for (i = 0; i < sourceSymbolKeys.length; i++) {
  2858. key = sourceSymbolKeys[i];
  2859. if (excluded.indexOf(key) >= 0) continue;
  2860. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  2861. target[key] = source[key];
  2862. }
  2863. }
  2864. return target;
  2865. }
  2866. function _toConsumableArray(arr) {
  2867. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
  2868. }
  2869. function _arrayWithoutHoles(arr) {
  2870. if (Array.isArray(arr)) {
  2871. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  2872. return arr2;
  2873. }
  2874. }
  2875. function _iterableToArray(iter) {
  2876. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  2877. }
  2878. function _nonIterableSpread() {
  2879. throw new TypeError("Invalid attempt to spread non-iterable instance");
  2880. }
  2881. var version = "1.10.0-rc3";
  2882. function userAgent(pattern) {
  2883. return !!
  2884. /*@__PURE__*/
  2885. navigator.userAgent.match(pattern);
  2886. }
  2887. var IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i);
  2888. var Edge = userAgent(/Edge/i);
  2889. var FireFox = userAgent(/firefox/i);
  2890. var Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);
  2891. var IOS = userAgent(/iP(ad|od|hone)/i);
  2892. var ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);
  2893. var captureMode = {
  2894. capture: false,
  2895. passive: false
  2896. };
  2897. function on(el, event, fn) {
  2898. el.addEventListener(event, fn, !IE11OrLess && captureMode);
  2899. }
  2900. function off(el, event, fn) {
  2901. el.removeEventListener(event, fn, !IE11OrLess && captureMode);
  2902. }
  2903. function matches(
  2904. /**HTMLElement*/
  2905. el,
  2906. /**String*/
  2907. selector) {
  2908. if (!selector) return;
  2909. selector[0] === '>' && (selector = selector.substring(1));
  2910. if (el) {
  2911. try {
  2912. if (el.matches) {
  2913. return el.matches(selector);
  2914. } else if (el.msMatchesSelector) {
  2915. return el.msMatchesSelector(selector);
  2916. } else if (el.webkitMatchesSelector) {
  2917. return el.webkitMatchesSelector(selector);
  2918. }
  2919. } catch (_) {
  2920. return false;
  2921. }
  2922. }
  2923. return false;
  2924. }
  2925. function getParentOrHost(el) {
  2926. return el.host && el !== document && el.host.nodeType ? el.host : el.parentNode;
  2927. }
  2928. function closest(
  2929. /**HTMLElement*/
  2930. el,
  2931. /**String*/
  2932. selector,
  2933. /**HTMLElement*/
  2934. ctx, includeCTX) {
  2935. if (el) {
  2936. ctx = ctx || document;
  2937. do {
  2938. if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) {
  2939. return el;
  2940. }
  2941. if (el === ctx) break;
  2942. /* jshint boss:true */
  2943. } while (el = getParentOrHost(el));
  2944. }
  2945. return null;
  2946. }
  2947. var R_SPACE = /\s+/g;
  2948. function toggleClass(el, name, state) {
  2949. if (el && name) {
  2950. if (el.classList) {
  2951. el.classList[state ? 'add' : 'remove'](name);
  2952. } else {
  2953. var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
  2954. el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
  2955. }
  2956. }
  2957. }
  2958. function css(el, prop, val) {
  2959. var style = el && el.style;
  2960. if (style) {
  2961. if (val === void 0) {
  2962. if (document.defaultView && document.defaultView.getComputedStyle) {
  2963. val = document.defaultView.getComputedStyle(el, '');
  2964. } else if (el.currentStyle) {
  2965. val = el.currentStyle;
  2966. }
  2967. return prop === void 0 ? val : val[prop];
  2968. } else {
  2969. if (!(prop in style) && prop.indexOf('webkit') === -1) {
  2970. prop = '-webkit-' + prop;
  2971. }
  2972. style[prop] = val + (typeof val === 'string' ? '' : 'px');
  2973. }
  2974. }
  2975. }
  2976. function matrix(el, selfOnly) {
  2977. var appliedTransforms = '';
  2978. do {
  2979. var transform = css(el, 'transform');
  2980. if (transform && transform !== 'none') {
  2981. appliedTransforms = transform + ' ' + appliedTransforms;
  2982. }
  2983. /* jshint boss:true */
  2984. } while (!selfOnly && (el = el.parentNode));
  2985. var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix;
  2986. /*jshint -W056 */
  2987. return matrixFn && new matrixFn(appliedTransforms);
  2988. }
  2989. function find(ctx, tagName, iterator) {
  2990. if (ctx) {
  2991. var list = ctx.getElementsByTagName(tagName),
  2992. i = 0,
  2993. n = list.length;
  2994. if (iterator) {
  2995. for (; i < n; i++) {
  2996. iterator(list[i], i);
  2997. }
  2998. }
  2999. return list;
  3000. }
  3001. return [];
  3002. }
  3003. function getWindowScrollingElement() {
  3004. if (IE11OrLess) {
  3005. return document.documentElement;
  3006. } else {
  3007. return document.scrollingElement;
  3008. }
  3009. }
  3010. /**
  3011. * Returns the "bounding client rect" of given element
  3012. * @param {HTMLElement} el The element whose boundingClientRect is wanted
  3013. * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container
  3014. * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr
  3015. * @param {[Boolean]} undoScale Whether the container's scale() should be undone
  3016. * @param {[HTMLElement]} container The parent the element will be placed in
  3017. * @return {Object} The boundingClientRect of el, with specified adjustments
  3018. */
  3019. function getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) {
  3020. if (!el.getBoundingClientRect && el !== window) return;
  3021. var elRect, top, left, bottom, right, height, width;
  3022. if (el !== window && el !== getWindowScrollingElement()) {
  3023. elRect = el.getBoundingClientRect();
  3024. top = elRect.top;
  3025. left = elRect.left;
  3026. bottom = elRect.bottom;
  3027. right = elRect.right;
  3028. height = elRect.height;
  3029. width = elRect.width;
  3030. } else {
  3031. top = 0;
  3032. left = 0;
  3033. bottom = window.innerHeight;
  3034. right = window.innerWidth;
  3035. height = window.innerHeight;
  3036. width = window.innerWidth;
  3037. }
  3038. if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) {
  3039. // Adjust for translate()
  3040. container = container || el.parentNode; // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)
  3041. // Not needed on <= IE11
  3042. if (!IE11OrLess) {
  3043. do {
  3044. if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) {
  3045. var containerRect = container.getBoundingClientRect(); // Set relative to edges of padding box of container
  3046. top -= containerRect.top + parseInt(css(container, 'border-top-width'));
  3047. left -= containerRect.left + parseInt(css(container, 'border-left-width'));
  3048. bottom = top + elRect.height;
  3049. right = left + elRect.width;
  3050. break;
  3051. }
  3052. /* jshint boss:true */
  3053. } while (container = container.parentNode);
  3054. }
  3055. }
  3056. if (undoScale && el !== window) {
  3057. // Adjust for scale()
  3058. var elMatrix = matrix(container || el),
  3059. scaleX = elMatrix && elMatrix.a,
  3060. scaleY = elMatrix && elMatrix.d;
  3061. if (elMatrix) {
  3062. top /= scaleY;
  3063. left /= scaleX;
  3064. width /= scaleX;
  3065. height /= scaleY;
  3066. bottom = top + height;
  3067. right = left + width;
  3068. }
  3069. }
  3070. return {
  3071. top: top,
  3072. left: left,
  3073. bottom: bottom,
  3074. right: right,
  3075. width: width,
  3076. height: height
  3077. };
  3078. }
  3079. /**
  3080. * Checks if a side of an element is scrolled past a side of its parents
  3081. * @param {HTMLElement} el The element who's side being scrolled out of view is in question
  3082. * @param {[DOMRect]} rect Optional rect of el to use
  3083. * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom')
  3084. * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom')
  3085. * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element
  3086. */
  3087. function isScrolledPast(el, rect, elSide, parentSide) {
  3088. var parent = getParentAutoScrollElement(el, true),
  3089. elSideVal = (rect ? rect : getRect(el))[elSide];
  3090. /* jshint boss:true */
  3091. while (parent) {
  3092. var parentSideVal = getRect(parent)[parentSide],
  3093. visible = void 0;
  3094. if (parentSide === 'top' || parentSide === 'left') {
  3095. visible = elSideVal >= parentSideVal;
  3096. } else {
  3097. visible = elSideVal <= parentSideVal;
  3098. }
  3099. if (!visible) return parent;
  3100. if (parent === getWindowScrollingElement()) break;
  3101. parent = getParentAutoScrollElement(parent, false);
  3102. }
  3103. return false;
  3104. }
  3105. /**
  3106. * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)
  3107. * and non-draggable elements
  3108. * @param {HTMLElement} el The parent element
  3109. * @param {Number} childNum The index of the child
  3110. * @param {Object} options Parent Sortable's options
  3111. * @return {HTMLElement} The child at index childNum, or null if not found
  3112. */
  3113. function getChild(el, childNum, options) {
  3114. var currentChild = 0,
  3115. i = 0,
  3116. children = el.children;
  3117. while (i < children.length) {
  3118. if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && children[i] !== Sortable.dragged && closest(children[i], options.draggable, el, false)) {
  3119. if (currentChild === childNum) {
  3120. return children[i];
  3121. }
  3122. currentChild++;
  3123. }
  3124. i++;
  3125. }
  3126. return null;
  3127. }
  3128. /**
  3129. * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)
  3130. * @param {HTMLElement} el Parent element
  3131. * @param {selector} selector Any other elements that should be ignored
  3132. * @return {HTMLElement} The last child, ignoring ghostEl
  3133. */
  3134. function lastChild(el, selector) {
  3135. var last = el.lastElementChild;
  3136. while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) {
  3137. last = last.previousElementSibling;
  3138. }
  3139. return last || null;
  3140. }
  3141. /**
  3142. * Returns the index of an element within its parent for a selected set of
  3143. * elements
  3144. * @param {HTMLElement} el
  3145. * @param {selector} selector
  3146. * @return {number}
  3147. */
  3148. function index(el, selector) {
  3149. var index = 0;
  3150. if (!el || !el.parentNode) {
  3151. return -1;
  3152. }
  3153. /* jshint boss:true */
  3154. while (el = el.previousElementSibling) {
  3155. if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) {
  3156. index++;
  3157. }
  3158. }
  3159. return index;
  3160. }
  3161. /**
  3162. * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.
  3163. * The value is returned in real pixels.
  3164. * @param {HTMLElement} el
  3165. * @return {Array} Offsets in the format of [left, top]
  3166. */
  3167. function getRelativeScrollOffset(el) {
  3168. var offsetLeft = 0,
  3169. offsetTop = 0,
  3170. winScroller = getWindowScrollingElement();
  3171. if (el) {
  3172. do {
  3173. var elMatrix = matrix(el),
  3174. scaleX = elMatrix.a,
  3175. scaleY = elMatrix.d;
  3176. offsetLeft += el.scrollLeft * scaleX;
  3177. offsetTop += el.scrollTop * scaleY;
  3178. } while (el !== winScroller && (el = el.parentNode));
  3179. }
  3180. return [offsetLeft, offsetTop];
  3181. }
  3182. /**
  3183. * Returns the index of the object within the given array
  3184. * @param {Array} arr Array that may or may not hold the object
  3185. * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find
  3186. * @return {Number} The index of the object in the array, or -1
  3187. */
  3188. function indexOfObject(arr, obj) {
  3189. for (var i in arr) {
  3190. if (!arr.hasOwnProperty(i)) continue;
  3191. for (var key in obj) {
  3192. if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i);
  3193. }
  3194. }
  3195. return -1;
  3196. }
  3197. function getParentAutoScrollElement(el, includeSelf) {
  3198. // skip to window
  3199. if (!el || !el.getBoundingClientRect) return getWindowScrollingElement();
  3200. var elem = el;
  3201. var gotSelf = false;
  3202. do {
  3203. // we don't need to get elem css if it isn't even overflowing in the first place (performance)
  3204. if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {
  3205. var elemCSS = css(elem);
  3206. if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) {
  3207. if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement();
  3208. if (gotSelf || includeSelf) return elem;
  3209. gotSelf = true;
  3210. }
  3211. }
  3212. /* jshint boss:true */
  3213. } while (elem = elem.parentNode);
  3214. return getWindowScrollingElement();
  3215. }
  3216. function extend(dst, src) {
  3217. if (dst && src) {
  3218. for (var key in src) {
  3219. if (src.hasOwnProperty(key)) {
  3220. dst[key] = src[key];
  3221. }
  3222. }
  3223. }
  3224. return dst;
  3225. }
  3226. function isRectEqual(rect1, rect2) {
  3227. return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width);
  3228. }
  3229. var _throttleTimeout;
  3230. function throttle(callback, ms) {
  3231. return function () {
  3232. if (!_throttleTimeout) {
  3233. var args = arguments,
  3234. _this = this;
  3235. if (args.length === 1) {
  3236. callback.call(_this, args[0]);
  3237. } else {
  3238. callback.apply(_this, args);
  3239. }
  3240. _throttleTimeout = setTimeout(function () {
  3241. _throttleTimeout = void 0;
  3242. }, ms);
  3243. }
  3244. };
  3245. }
  3246. function cancelThrottle() {
  3247. clearTimeout(_throttleTimeout);
  3248. _throttleTimeout = void 0;
  3249. }
  3250. function scrollBy(el, x, y) {
  3251. el.scrollLeft += x;
  3252. el.scrollTop += y;
  3253. }
  3254. function clone(el) {
  3255. var Polymer = window.Polymer;
  3256. var $ = window.jQuery || window.Zepto;
  3257. if (Polymer && Polymer.dom) {
  3258. return Polymer.dom(el).cloneNode(true);
  3259. } else if ($) {
  3260. return $(el).clone(true)[0];
  3261. } else {
  3262. return el.cloneNode(true);
  3263. }
  3264. }
  3265. function setRect(el, rect) {
  3266. css(el, 'position', 'absolute');
  3267. css(el, 'top', rect.top);
  3268. css(el, 'left', rect.left);
  3269. css(el, 'width', rect.width);
  3270. css(el, 'height', rect.height);
  3271. }
  3272. function unsetRect(el) {
  3273. css(el, 'position', '');
  3274. css(el, 'top', '');
  3275. css(el, 'left', '');
  3276. css(el, 'width', '');
  3277. css(el, 'height', '');
  3278. }
  3279. var expando = 'Sortable' + new Date().getTime();
  3280. function AnimationStateManager() {
  3281. var animationStates = [],
  3282. animationCallbackId;
  3283. return {
  3284. captureAnimationState: function captureAnimationState() {
  3285. animationStates = [];
  3286. if (!this.options.animation) return;
  3287. var children = [].slice.call(this.el.children);
  3288. children.forEach(function (child) {
  3289. if (css(child, 'display') === 'none' || child === Sortable.ghost) return;
  3290. animationStates.push({
  3291. target: child,
  3292. rect: getRect(child)
  3293. });
  3294. var fromRect = getRect(child); // If animating: compensate for current animation
  3295. if (child.thisAnimationDuration) {
  3296. var childMatrix = matrix(child, true);
  3297. if (childMatrix) {
  3298. fromRect.top -= childMatrix.f;
  3299. fromRect.left -= childMatrix.e;
  3300. }
  3301. }
  3302. child.fromRect = fromRect;
  3303. });
  3304. },
  3305. addAnimationState: function addAnimationState(state) {
  3306. animationStates.push(state);
  3307. },
  3308. removeAnimationState: function removeAnimationState(target) {
  3309. animationStates.splice(indexOfObject(animationStates, {
  3310. target: target
  3311. }), 1);
  3312. },
  3313. animateAll: function animateAll(callback) {
  3314. var _this = this;
  3315. if (!this.options.animation) {
  3316. clearTimeout(animationCallbackId);
  3317. if (typeof callback === 'function') callback();
  3318. return;
  3319. }
  3320. var animating = false,
  3321. animationTime = 0;
  3322. animationStates.forEach(function (state) {
  3323. var time = 0,
  3324. target = state.target,
  3325. fromRect = target.fromRect,
  3326. toRect = getRect(target),
  3327. prevFromRect = target.prevFromRect,
  3328. prevToRect = target.prevToRect,
  3329. animatingRect = state.rect,
  3330. targetMatrix = matrix(target, true);
  3331. if (targetMatrix) {
  3332. // Compensate for current animation
  3333. toRect.top -= targetMatrix.f;
  3334. toRect.left -= targetMatrix.e;
  3335. }
  3336. target.toRect = toRect; // If element is scrolled out of view: Do not animate
  3337. if ((isScrolledPast(target, toRect, 'bottom', 'top') || isScrolledPast(target, toRect, 'top', 'bottom') || isScrolledPast(target, toRect, 'right', 'left') || isScrolledPast(target, toRect, 'left', 'right')) && (isScrolledPast(target, animatingRect, 'bottom', 'top') || isScrolledPast(target, animatingRect, 'top', 'bottom') || isScrolledPast(target, animatingRect, 'right', 'left') || isScrolledPast(target, animatingRect, 'left', 'right')) && (isScrolledPast(target, fromRect, 'bottom', 'top') || isScrolledPast(target, fromRect, 'top', 'bottom') || isScrolledPast(target, fromRect, 'right', 'left') || isScrolledPast(target, fromRect, 'left', 'right'))) return;
  3338. if (target.thisAnimationDuration) {
  3339. // Could also check if animatingRect is between fromRect and toRect
  3340. if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) && // Make sure animatingRect is on line between toRect & fromRect
  3341. (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) {
  3342. // If returning to same place as started from animation and on same axis
  3343. time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options);
  3344. }
  3345. } // if fromRect != toRect: animate
  3346. if (!isRectEqual(toRect, fromRect)) {
  3347. target.prevFromRect = fromRect;
  3348. target.prevToRect = toRect;
  3349. if (!time) {
  3350. time = _this.options.animation;
  3351. }
  3352. _this.animate(target, animatingRect, time);
  3353. }
  3354. if (time) {
  3355. animating = true;
  3356. animationTime = Math.max(animationTime, time);
  3357. clearTimeout(target.animationResetTimer);
  3358. target.animationResetTimer = setTimeout(function () {
  3359. target.animationTime = 0;
  3360. target.prevFromRect = null;
  3361. target.fromRect = null;
  3362. target.prevToRect = null;
  3363. target.thisAnimationDuration = null;
  3364. }, time);
  3365. target.thisAnimationDuration = time;
  3366. }
  3367. });
  3368. clearTimeout(animationCallbackId);
  3369. if (!animating) {
  3370. if (typeof callback === 'function') callback();
  3371. } else {
  3372. animationCallbackId = setTimeout(function () {
  3373. if (typeof callback === 'function') callback();
  3374. }, animationTime);
  3375. }
  3376. animationStates = [];
  3377. },
  3378. animate: function animate(target, prev, duration) {
  3379. if (duration) {
  3380. css(target, 'transition', '');
  3381. css(target, 'transform', '');
  3382. var currentRect = getRect(target),
  3383. elMatrix = matrix(this.el),
  3384. scaleX = elMatrix && elMatrix.a,
  3385. scaleY = elMatrix && elMatrix.d,
  3386. translateX = (prev.left - currentRect.left) / (scaleX || 1),
  3387. translateY = (prev.top - currentRect.top) / (scaleY || 1);
  3388. target.animatingX = !!translateX;
  3389. target.animatingY = !!translateY;
  3390. css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)');
  3391. repaint(target); // repaint
  3392. css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));
  3393. css(target, 'transform', 'translate3d(0,0,0)');
  3394. typeof target.animated === 'number' && clearTimeout(target.animated);
  3395. target.animated = setTimeout(function () {
  3396. css(target, 'transition', '');
  3397. css(target, 'transform', '');
  3398. target.animated = false;
  3399. target.animatingX = false;
  3400. target.animatingY = false;
  3401. }, duration);
  3402. }
  3403. }
  3404. };
  3405. }
  3406. function repaint(target) {
  3407. return target.offsetWidth;
  3408. }
  3409. function calculateRealTime(animatingRect, fromRect, toRect, options) {
  3410. return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation;
  3411. }
  3412. var plugins = [];
  3413. var defaults = {
  3414. initializeByDefault: true
  3415. };
  3416. var PluginManager = {
  3417. mount: function mount(plugin) {
  3418. // Set default static properties
  3419. for (var option in defaults) {
  3420. if (defaults.hasOwnProperty(option) && !(option in plugin)) {
  3421. plugin[option] = defaults[option];
  3422. }
  3423. }
  3424. plugins.push(plugin);
  3425. },
  3426. pluginEvent: function pluginEvent(eventName, sortable, evt) {
  3427. var _this = this;
  3428. this.eventCanceled = false;
  3429. var eventNameGlobal = eventName + 'Global';
  3430. plugins.forEach(function (plugin) {
  3431. if (!sortable[plugin.pluginName]) return; // Fire global events if it exists in this sortable
  3432. if (sortable[plugin.pluginName][eventNameGlobal]) {
  3433. _this.eventCanceled = !!sortable[plugin.pluginName][eventNameGlobal](_objectSpread({
  3434. sortable: sortable
  3435. }, evt));
  3436. } // Only fire plugin event if plugin is enabled in this sortable,
  3437. // and plugin has event defined
  3438. if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) {
  3439. _this.eventCanceled = _this.eventCanceled || !!sortable[plugin.pluginName][eventName](_objectSpread({
  3440. sortable: sortable
  3441. }, evt));
  3442. }
  3443. });
  3444. },
  3445. initializePlugins: function initializePlugins(sortable, el, defaults) {
  3446. plugins.forEach(function (plugin) {
  3447. var pluginName = plugin.pluginName;
  3448. if (!sortable.options[pluginName] && !plugin.initializeByDefault) return;
  3449. var initialized = new plugin(sortable, el);
  3450. initialized.sortable = sortable;
  3451. sortable[pluginName] = initialized; // Add default options from plugin
  3452. _extends(defaults, initialized.options);
  3453. });
  3454. for (var option in sortable.options) {
  3455. if (!sortable.options.hasOwnProperty(option)) continue;
  3456. var modified = this.modifyOption(sortable, option, sortable.options[option]);
  3457. if (typeof modified !== 'undefined') {
  3458. sortable.options[option] = modified;
  3459. }
  3460. }
  3461. },
  3462. getEventOptions: function getEventOptions(name, sortable) {
  3463. var eventOptions = {};
  3464. plugins.forEach(function (plugin) {
  3465. if (typeof plugin.eventOptions !== 'function') return;
  3466. _extends(eventOptions, plugin.eventOptions.call(sortable, name));
  3467. });
  3468. return eventOptions;
  3469. },
  3470. modifyOption: function modifyOption(sortable, name, value) {
  3471. var modifiedValue;
  3472. plugins.forEach(function (plugin) {
  3473. // Plugin must exist on the Sortable
  3474. if (!sortable[plugin.pluginName]) return; // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin
  3475. if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') {
  3476. modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value);
  3477. }
  3478. });
  3479. return modifiedValue;
  3480. }
  3481. };
  3482. function dispatchEvent(_ref) {
  3483. var sortable = _ref.sortable,
  3484. rootEl = _ref.rootEl,
  3485. name = _ref.name,
  3486. targetEl = _ref.targetEl,
  3487. cloneEl = _ref.cloneEl,
  3488. toEl = _ref.toEl,
  3489. fromEl = _ref.fromEl,
  3490. oldIndex = _ref.oldIndex,
  3491. newIndex = _ref.newIndex,
  3492. oldDraggableIndex = _ref.oldDraggableIndex,
  3493. newDraggableIndex = _ref.newDraggableIndex,
  3494. originalEvent = _ref.originalEvent,
  3495. putSortable = _ref.putSortable,
  3496. eventOptions = _ref.eventOptions;
  3497. sortable = sortable || rootEl[expando];
  3498. var evt,
  3499. options = sortable.options,
  3500. onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); // Support for new CustomEvent feature
  3501. if (window.CustomEvent && !IE11OrLess && !Edge) {
  3502. evt = new CustomEvent(name, {
  3503. bubbles: true,
  3504. cancelable: true
  3505. });
  3506. } else {
  3507. evt = document.createEvent('Event');
  3508. evt.initEvent(name, true, true);
  3509. }
  3510. evt.to = toEl || rootEl;
  3511. evt.from = fromEl || rootEl;
  3512. evt.item = targetEl || rootEl;
  3513. evt.clone = cloneEl;
  3514. evt.oldIndex = oldIndex;
  3515. evt.newIndex = newIndex;
  3516. evt.oldDraggableIndex = oldDraggableIndex;
  3517. evt.newDraggableIndex = newDraggableIndex;
  3518. evt.originalEvent = originalEvent;
  3519. evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;
  3520. var allEventOptions = _objectSpread({}, eventOptions, PluginManager.getEventOptions(name, sortable));
  3521. for (var option in allEventOptions) {
  3522. evt[option] = allEventOptions[option];
  3523. }
  3524. if (rootEl) {
  3525. rootEl.dispatchEvent(evt);
  3526. }
  3527. if (options[onName]) {
  3528. options[onName].call(sortable, evt);
  3529. }
  3530. }
  3531. var pluginEvent = function pluginEvent(eventName, sortable) {
  3532. var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  3533. originalEvent = _ref.evt,
  3534. data = _objectWithoutProperties(_ref, ["evt"]);
  3535. PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread({
  3536. dragEl: dragEl,
  3537. parentEl: parentEl,
  3538. ghostEl: ghostEl,
  3539. rootEl: rootEl,
  3540. nextEl: nextEl,
  3541. lastDownEl: lastDownEl,
  3542. cloneEl: cloneEl,
  3543. cloneHidden: cloneHidden,
  3544. dragStarted: moved,
  3545. putSortable: putSortable,
  3546. activeSortable: Sortable.active,
  3547. originalEvent: originalEvent,
  3548. oldIndex: oldIndex,
  3549. oldDraggableIndex: oldDraggableIndex,
  3550. newIndex: newIndex,
  3551. newDraggableIndex: newDraggableIndex,
  3552. hideGhostForTarget: _hideGhostForTarget,
  3553. unhideGhostForTarget: _unhideGhostForTarget,
  3554. cloneNowHidden: function cloneNowHidden() {
  3555. cloneHidden = true;
  3556. },
  3557. cloneNowShown: function cloneNowShown() {
  3558. cloneHidden = false;
  3559. },
  3560. dispatchSortableEvent: function dispatchSortableEvent(name) {
  3561. _dispatchEvent({
  3562. sortable: sortable,
  3563. name: name,
  3564. originalEvent: originalEvent
  3565. });
  3566. }
  3567. }, data));
  3568. };
  3569. function _dispatchEvent(info) {
  3570. dispatchEvent(_objectSpread({
  3571. putSortable: putSortable,
  3572. cloneEl: cloneEl,
  3573. targetEl: dragEl,
  3574. rootEl: rootEl,
  3575. oldIndex: oldIndex,
  3576. oldDraggableIndex: oldDraggableIndex,
  3577. newIndex: newIndex,
  3578. newDraggableIndex: newDraggableIndex
  3579. }, info));
  3580. }
  3581. if (typeof window === "undefined" || !window.document) {
  3582. throw new Error("Sortable.js requires a window with a document");
  3583. }
  3584. var dragEl,
  3585. parentEl,
  3586. ghostEl,
  3587. rootEl,
  3588. nextEl,
  3589. lastDownEl,
  3590. cloneEl,
  3591. cloneHidden,
  3592. oldIndex,
  3593. newIndex,
  3594. oldDraggableIndex,
  3595. newDraggableIndex,
  3596. activeGroup,
  3597. putSortable,
  3598. awaitingDragStarted = false,
  3599. ignoreNextClick = false,
  3600. sortables = [],
  3601. tapEvt,
  3602. touchEvt,
  3603. moved,
  3604. lastTarget,
  3605. lastDirection,
  3606. pastFirstInvertThresh = false,
  3607. isCircumstantialInvert = false,
  3608. targetMoveDistance,
  3609. // For positioning ghost absolutely
  3610. ghostRelativeParent,
  3611. ghostRelativeParentInitialScroll = [],
  3612. // (left, top)
  3613. _silent = false,
  3614. savedInputChecked = [];
  3615. /** @const */
  3616. var PositionGhostAbsolutely = IOS,
  3617. CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',
  3618. // This will not pass for IE9, because IE9 DnD only works on anchors
  3619. supportDraggable = !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'),
  3620. supportCssPointerEvents = function () {
  3621. // false when <= IE11
  3622. if (IE11OrLess) {
  3623. return false;
  3624. }
  3625. var el = document.createElement('x');
  3626. el.style.cssText = 'pointer-events:auto';
  3627. return el.style.pointerEvents === 'auto';
  3628. }(),
  3629. _detectDirection = function _detectDirection(el, options) {
  3630. var elCSS = css(el),
  3631. elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth),
  3632. child1 = getChild(el, 0, options),
  3633. child2 = getChild(el, 1, options),
  3634. firstChildCSS = child1 && css(child1),
  3635. secondChildCSS = child2 && css(child2),
  3636. firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width,
  3637. secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width;
  3638. if (elCSS.display === 'flex') {
  3639. return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal';
  3640. }
  3641. if (elCSS.display === 'grid') {
  3642. return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';
  3643. }
  3644. if (child1 && firstChildCSS["float"] !== 'none') {
  3645. var touchingSideChild2 = firstChildCSS["float"] === 'left' ? 'left' : 'right';
  3646. return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal';
  3647. }
  3648. return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal';
  3649. },
  3650. _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) {
  3651. var dragElS1Opp = vertical ? dragRect.left : dragRect.top,
  3652. dragElS2Opp = vertical ? dragRect.right : dragRect.bottom,
  3653. dragElOppLength = vertical ? dragRect.width : dragRect.height,
  3654. targetS1Opp = vertical ? targetRect.left : targetRect.top,
  3655. targetS2Opp = vertical ? targetRect.right : targetRect.bottom,
  3656. targetOppLength = vertical ? targetRect.width : targetRect.height;
  3657. return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2;
  3658. },
  3659. /**
  3660. * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.
  3661. * @param {Number} x X position
  3662. * @param {Number} y Y position
  3663. * @return {HTMLElement} Element of the first found nearest Sortable
  3664. */
  3665. _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) {
  3666. var ret;
  3667. sortables.some(function (sortable) {
  3668. if (lastChild(sortable)) return;
  3669. var rect = getRect(sortable),
  3670. threshold = sortable[expando].options.emptyInsertThreshold,
  3671. insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold,
  3672. insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold;
  3673. if (threshold && insideHorizontally && insideVertically) {
  3674. return ret = sortable;
  3675. }
  3676. });
  3677. return ret;
  3678. },
  3679. _prepareGroup = function _prepareGroup(options) {
  3680. function toFn(value, pull) {
  3681. return function (to, from, dragEl, evt) {
  3682. var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name;
  3683. if (value == null && (pull || sameGroup)) {
  3684. // Default pull value
  3685. // Default pull and put value if same group
  3686. return true;
  3687. } else if (value == null || value === false) {
  3688. return false;
  3689. } else if (pull && value === 'clone') {
  3690. return value;
  3691. } else if (typeof value === 'function') {
  3692. return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);
  3693. } else {
  3694. var otherGroup = (pull ? to : from).options.group.name;
  3695. return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1;
  3696. }
  3697. };
  3698. }
  3699. var group = {};
  3700. var originalGroup = options.group;
  3701. if (!originalGroup || _typeof(originalGroup) != 'object') {
  3702. originalGroup = {
  3703. name: originalGroup
  3704. };
  3705. }
  3706. group.name = originalGroup.name;
  3707. group.checkPull = toFn(originalGroup.pull, true);
  3708. group.checkPut = toFn(originalGroup.put);
  3709. group.revertClone = originalGroup.revertClone;
  3710. options.group = group;
  3711. },
  3712. _hideGhostForTarget = function _hideGhostForTarget() {
  3713. if (!supportCssPointerEvents && ghostEl) {
  3714. css(ghostEl, 'display', 'none');
  3715. }
  3716. },
  3717. _unhideGhostForTarget = function _unhideGhostForTarget() {
  3718. if (!supportCssPointerEvents && ghostEl) {
  3719. css(ghostEl, 'display', '');
  3720. }
  3721. }; // #1184 fix - Prevent click event on fallback if dragged but item not changed position
  3722. document.addEventListener('click', function (evt) {
  3723. if (ignoreNextClick) {
  3724. evt.preventDefault();
  3725. evt.stopPropagation && evt.stopPropagation();
  3726. evt.stopImmediatePropagation && evt.stopImmediatePropagation();
  3727. ignoreNextClick = false;
  3728. return false;
  3729. }
  3730. }, true);
  3731. var nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) {
  3732. if (dragEl) {
  3733. evt = evt.touches ? evt.touches[0] : evt;
  3734. var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);
  3735. if (nearest) {
  3736. // Create imitation event
  3737. var event = {};
  3738. for (var i in evt) {
  3739. if (evt.hasOwnProperty(i)) {
  3740. event[i] = evt[i];
  3741. }
  3742. }
  3743. event.target = event.rootEl = nearest;
  3744. event.preventDefault = void 0;
  3745. event.stopPropagation = void 0;
  3746. nearest[expando]._onDragOver(event);
  3747. }
  3748. }
  3749. };
  3750. var _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) {
  3751. if (dragEl) {
  3752. dragEl.parentNode[expando]._isOutsideThisEl(evt.target);
  3753. }
  3754. };
  3755. /**
  3756. * @class Sortable
  3757. * @param {HTMLElement} el
  3758. * @param {Object} [options]
  3759. */
  3760. function Sortable(el, options) {
  3761. if (!(el && el.nodeType && el.nodeType === 1)) {
  3762. throw "Sortable: el must be an HTMLElement, not ".concat({}.toString.call(el));
  3763. }
  3764. this.el = el; // root element
  3765. this.options = options = _extends({}, options); // Export instance
  3766. el[expando] = this;
  3767. var defaults = {
  3768. group: null,
  3769. sort: true,
  3770. disabled: false,
  3771. store: null,
  3772. handle: null,
  3773. draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*',
  3774. swapThreshold: 1,
  3775. // percentage; 0 <= x <= 1
  3776. invertSwap: false,
  3777. // invert always
  3778. invertedSwapThreshold: null,
  3779. // will be set to same as swapThreshold if default
  3780. removeCloneOnHide: true,
  3781. direction: function direction() {
  3782. return _detectDirection(el, this.options);
  3783. },
  3784. ghostClass: 'sortable-ghost',
  3785. chosenClass: 'sortable-chosen',
  3786. dragClass: 'sortable-drag',
  3787. ignore: 'a, img',
  3788. filter: null,
  3789. preventOnFilter: true,
  3790. animation: 0,
  3791. easing: null,
  3792. setData: function setData(dataTransfer, dragEl) {
  3793. dataTransfer.setData('Text', dragEl.textContent);
  3794. },
  3795. dropBubble: false,
  3796. dragoverBubble: false,
  3797. dataIdAttr: 'data-id',
  3798. delay: 0,
  3799. delayOnTouchOnly: false,
  3800. touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1,
  3801. forceFallback: false,
  3802. fallbackClass: 'sortable-fallback',
  3803. fallbackOnBody: false,
  3804. fallbackTolerance: 0,
  3805. fallbackOffset: {
  3806. x: 0,
  3807. y: 0
  3808. },
  3809. supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window,
  3810. emptyInsertThreshold: 5
  3811. };
  3812. PluginManager.initializePlugins(this, el, defaults); // Set default options
  3813. for (var name in defaults) {
  3814. !(name in options) && (options[name] = defaults[name]);
  3815. }
  3816. _prepareGroup(options); // Bind all private methods
  3817. for (var fn in this) {
  3818. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  3819. this[fn] = this[fn].bind(this);
  3820. }
  3821. } // Setup drag mode
  3822. this.nativeDraggable = options.forceFallback ? false : supportDraggable;
  3823. if (this.nativeDraggable) {
  3824. // Touch start threshold cannot be greater than the native dragstart threshold
  3825. this.options.touchStartThreshold = 1;
  3826. } // Bind events
  3827. if (options.supportPointer) {
  3828. on(el, 'pointerdown', this._onTapStart);
  3829. } else {
  3830. on(el, 'mousedown', this._onTapStart);
  3831. on(el, 'touchstart', this._onTapStart);
  3832. }
  3833. if (this.nativeDraggable) {
  3834. on(el, 'dragover', this);
  3835. on(el, 'dragenter', this);
  3836. }
  3837. sortables.push(this.el); // Restore sorting
  3838. options.store && options.store.get && this.sort(options.store.get(this) || []); // Add animation state manager
  3839. _extends(this, AnimationStateManager());
  3840. }
  3841. Sortable.prototype =
  3842. /** @lends Sortable.prototype */
  3843. {
  3844. constructor: Sortable,
  3845. _isOutsideThisEl: function _isOutsideThisEl(target) {
  3846. if (!this.el.contains(target) && target !== this.el) {
  3847. lastTarget = null;
  3848. }
  3849. },
  3850. _getDirection: function _getDirection(evt, target) {
  3851. return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;
  3852. },
  3853. _onTapStart: function _onTapStart(
  3854. /** Event|TouchEvent */
  3855. evt) {
  3856. if (!evt.cancelable) return;
  3857. var _this = this,
  3858. el = this.el,
  3859. options = this.options,
  3860. preventOnFilter = options.preventOnFilter,
  3861. type = evt.type,
  3862. touch = evt.touches && evt.touches[0],
  3863. target = (touch || evt).target,
  3864. originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target,
  3865. filter = options.filter;
  3866. _saveInputCheckedState(el); // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
  3867. if (dragEl) {
  3868. return;
  3869. }
  3870. if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
  3871. return; // only left button and enabled
  3872. } // cancel dnd if original target is content editable
  3873. if (originalTarget.isContentEditable) {
  3874. return;
  3875. }
  3876. target = closest(target, options.draggable, el, false);
  3877. if (target && target.animated) {
  3878. return;
  3879. }
  3880. if (lastDownEl === target) {
  3881. // Ignoring duplicate down
  3882. return;
  3883. } // Get the index of the dragged element within its parent
  3884. oldIndex = index(target);
  3885. oldDraggableIndex = index(target, options.draggable); // Check filter
  3886. if (typeof filter === 'function') {
  3887. if (filter.call(this, evt, target, this)) {
  3888. _dispatchEvent({
  3889. sortable: _this,
  3890. rootEl: originalTarget,
  3891. name: 'filter',
  3892. targetEl: target,
  3893. toEl: el,
  3894. fromEl: el
  3895. });
  3896. pluginEvent('filter', _this, {
  3897. evt: evt
  3898. });
  3899. preventOnFilter && evt.cancelable && evt.preventDefault();
  3900. return; // cancel dnd
  3901. }
  3902. } else if (filter) {
  3903. filter = filter.split(',').some(function (criteria) {
  3904. criteria = closest(originalTarget, criteria.trim(), el, false);
  3905. if (criteria) {
  3906. _dispatchEvent({
  3907. sortable: _this,
  3908. rootEl: criteria,
  3909. name: 'filter',
  3910. targetEl: target,
  3911. fromEl: el,
  3912. toEl: el
  3913. });
  3914. pluginEvent('filter', _this, {
  3915. evt: evt
  3916. });
  3917. return true;
  3918. }
  3919. });
  3920. if (filter) {
  3921. preventOnFilter && evt.cancelable && evt.preventDefault();
  3922. return; // cancel dnd
  3923. }
  3924. }
  3925. if (options.handle && !closest(originalTarget, options.handle, el, false)) {
  3926. return;
  3927. } // Prepare
  3928. this._prepareDragStart(evt, touch, target);
  3929. },
  3930. _prepareDragStart: function _prepareDragStart(
  3931. /** Event */
  3932. evt,
  3933. /** Touch */
  3934. touch,
  3935. /** HTMLElement */
  3936. target) {
  3937. var _this = this,
  3938. el = _this.el,
  3939. options = _this.options,
  3940. ownerDocument = el.ownerDocument,
  3941. dragStartFn;
  3942. if (target && !dragEl && target.parentNode === el) {
  3943. rootEl = el;
  3944. dragEl = target;
  3945. parentEl = dragEl.parentNode;
  3946. nextEl = dragEl.nextSibling;
  3947. lastDownEl = target;
  3948. activeGroup = options.group;
  3949. Sortable.dragged = dragEl;
  3950. tapEvt = {
  3951. target: dragEl,
  3952. clientX: (touch || evt).clientX,
  3953. clientY: (touch || evt).clientY
  3954. };
  3955. this._lastX = (touch || evt).clientX;
  3956. this._lastY = (touch || evt).clientY;
  3957. dragEl.style['will-change'] = 'all';
  3958. dragStartFn = function dragStartFn() {
  3959. pluginEvent('delayEnded', _this, {
  3960. evt: evt
  3961. });
  3962. if (Sortable.eventCanceled) {
  3963. _this._onDrop();
  3964. return;
  3965. } // Delayed drag has been triggered
  3966. // we can re-enable the events: touchmove/mousemove
  3967. _this._disableDelayedDragEvents();
  3968. if (!FireFox && _this.nativeDraggable) {
  3969. dragEl.draggable = true;
  3970. } // Bind the events: dragstart/dragend
  3971. _this._triggerDragStart(evt, touch); // Drag start event
  3972. _dispatchEvent({
  3973. sortable: _this,
  3974. name: 'choose',
  3975. originalEvent: evt
  3976. }); // Chosen item
  3977. toggleClass(dragEl, options.chosenClass, true);
  3978. }; // Disable "draggable"
  3979. options.ignore.split(',').forEach(function (criteria) {
  3980. find(dragEl, criteria.trim(), _disableDraggable);
  3981. });
  3982. on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent);
  3983. on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent);
  3984. on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent);
  3985. on(ownerDocument, 'mouseup', _this._onDrop);
  3986. on(ownerDocument, 'touchend', _this._onDrop);
  3987. on(ownerDocument, 'touchcancel', _this._onDrop); // Make dragEl draggable (must be before delay for FireFox)
  3988. if (FireFox && this.nativeDraggable) {
  3989. this.options.touchStartThreshold = 4;
  3990. dragEl.draggable = true;
  3991. }
  3992. pluginEvent('delayStart', this, {
  3993. evt: evt
  3994. }); // Delay is impossible for native DnD in Edge or IE
  3995. if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) {
  3996. if (Sortable.eventCanceled) {
  3997. this._onDrop();
  3998. return;
  3999. } // If the user moves the pointer or let go the click or touch
  4000. // before the delay has been reached:
  4001. // disable the delayed drag
  4002. on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
  4003. on(ownerDocument, 'touchend', _this._disableDelayedDrag);
  4004. on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
  4005. on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);
  4006. on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);
  4007. options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);
  4008. _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
  4009. } else {
  4010. dragStartFn();
  4011. }
  4012. }
  4013. },
  4014. _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler(
  4015. /** TouchEvent|PointerEvent **/
  4016. e) {
  4017. var touch = e.touches ? e.touches[0] : e;
  4018. if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) {
  4019. this._disableDelayedDrag();
  4020. }
  4021. },
  4022. _disableDelayedDrag: function _disableDelayedDrag() {
  4023. dragEl && _disableDraggable(dragEl);
  4024. clearTimeout(this._dragStartTimer);
  4025. this._disableDelayedDragEvents();
  4026. },
  4027. _disableDelayedDragEvents: function _disableDelayedDragEvents() {
  4028. var ownerDocument = this.el.ownerDocument;
  4029. off(ownerDocument, 'mouseup', this._disableDelayedDrag);
  4030. off(ownerDocument, 'touchend', this._disableDelayedDrag);
  4031. off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
  4032. off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);
  4033. off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);
  4034. off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);
  4035. },
  4036. _triggerDragStart: function _triggerDragStart(
  4037. /** Event */
  4038. evt,
  4039. /** Touch */
  4040. touch) {
  4041. touch = touch || evt.pointerType == 'touch' && evt;
  4042. if (!this.nativeDraggable || touch) {
  4043. if (this.options.supportPointer) {
  4044. on(document, 'pointermove', this._onTouchMove);
  4045. } else if (touch) {
  4046. on(document, 'touchmove', this._onTouchMove);
  4047. } else {
  4048. on(document, 'mousemove', this._onTouchMove);
  4049. }
  4050. } else {
  4051. on(dragEl, 'dragend', this);
  4052. on(rootEl, 'dragstart', this._onDragStart);
  4053. }
  4054. try {
  4055. if (document.selection) {
  4056. // Timeout neccessary for IE9
  4057. _nextTick(function () {
  4058. document.selection.empty();
  4059. });
  4060. } else {
  4061. window.getSelection().removeAllRanges();
  4062. }
  4063. } catch (err) {}
  4064. },
  4065. _dragStarted: function _dragStarted(fallback, evt) {
  4066. awaitingDragStarted = false;
  4067. if (rootEl && dragEl) {
  4068. pluginEvent('dragStarted', this, {
  4069. evt: evt
  4070. });
  4071. if (this.nativeDraggable) {
  4072. on(document, 'dragover', _checkOutsideTargetEl);
  4073. }
  4074. var options = this.options; // Apply effect
  4075. !fallback && toggleClass(dragEl, options.dragClass, false);
  4076. toggleClass(dragEl, options.ghostClass, true);
  4077. Sortable.active = this;
  4078. fallback && this._appendGhost(); // Drag start event
  4079. _dispatchEvent({
  4080. sortable: this,
  4081. name: 'start',
  4082. originalEvent: evt
  4083. });
  4084. } else {
  4085. this._nulling();
  4086. }
  4087. },
  4088. _emulateDragOver: function _emulateDragOver() {
  4089. if (touchEvt) {
  4090. this._lastX = touchEvt.clientX;
  4091. this._lastY = touchEvt.clientY;
  4092. _hideGhostForTarget();
  4093. var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
  4094. var parent = target;
  4095. while (target && target.shadowRoot) {
  4096. target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
  4097. if (target === parent) break;
  4098. parent = target;
  4099. }
  4100. dragEl.parentNode[expando]._isOutsideThisEl(target);
  4101. if (parent) {
  4102. do {
  4103. if (parent[expando]) {
  4104. var inserted = void 0;
  4105. inserted = parent[expando]._onDragOver({
  4106. clientX: touchEvt.clientX,
  4107. clientY: touchEvt.clientY,
  4108. target: target,
  4109. rootEl: parent
  4110. });
  4111. if (inserted && !this.options.dragoverBubble) {
  4112. break;
  4113. }
  4114. }
  4115. target = parent; // store last element
  4116. }
  4117. /* jshint boss:true */
  4118. while (parent = parent.parentNode);
  4119. }
  4120. _unhideGhostForTarget();
  4121. }
  4122. },
  4123. _onTouchMove: function _onTouchMove(
  4124. /**TouchEvent*/
  4125. evt) {
  4126. if (tapEvt) {
  4127. var options = this.options,
  4128. fallbackTolerance = options.fallbackTolerance,
  4129. fallbackOffset = options.fallbackOffset,
  4130. touch = evt.touches ? evt.touches[0] : evt,
  4131. ghostMatrix = ghostEl && matrix(ghostEl),
  4132. scaleX = ghostEl && ghostMatrix && ghostMatrix.a,
  4133. scaleY = ghostEl && ghostMatrix && ghostMatrix.d,
  4134. relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent),
  4135. dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1),
  4136. dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1),
  4137. translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)'; // only set the status to dragging, when we are actually dragging
  4138. if (!Sortable.active && !awaitingDragStarted) {
  4139. if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) {
  4140. return;
  4141. }
  4142. this._onDragStart(evt, true);
  4143. }
  4144. touchEvt = touch;
  4145. css(ghostEl, 'webkitTransform', translate3d);
  4146. css(ghostEl, 'mozTransform', translate3d);
  4147. css(ghostEl, 'msTransform', translate3d);
  4148. css(ghostEl, 'transform', translate3d);
  4149. evt.cancelable && evt.preventDefault();
  4150. }
  4151. },
  4152. _appendGhost: function _appendGhost() {
  4153. // Bug if using scale(): https://stackoverflow.com/questions/2637058
  4154. // Not being adjusted for
  4155. if (!ghostEl) {
  4156. var container = this.options.fallbackOnBody ? document.body : rootEl,
  4157. rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container),
  4158. options = this.options; // Position absolutely
  4159. if (PositionGhostAbsolutely) {
  4160. // Get relatively positioned parent
  4161. ghostRelativeParent = container;
  4162. while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) {
  4163. ghostRelativeParent = ghostRelativeParent.parentNode;
  4164. }
  4165. if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {
  4166. if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement();
  4167. rect.top += ghostRelativeParent.scrollTop;
  4168. rect.left += ghostRelativeParent.scrollLeft;
  4169. } else {
  4170. ghostRelativeParent = getWindowScrollingElement();
  4171. }
  4172. ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent);
  4173. }
  4174. ghostEl = dragEl.cloneNode(true);
  4175. toggleClass(ghostEl, options.ghostClass, false);
  4176. toggleClass(ghostEl, options.fallbackClass, true);
  4177. toggleClass(ghostEl, options.dragClass, true);
  4178. css(ghostEl, 'transition', '');
  4179. css(ghostEl, 'transform', '');
  4180. css(ghostEl, 'box-sizing', 'border-box');
  4181. css(ghostEl, 'margin', 0);
  4182. css(ghostEl, 'top', rect.top);
  4183. css(ghostEl, 'left', rect.left);
  4184. css(ghostEl, 'width', rect.width);
  4185. css(ghostEl, 'height', rect.height);
  4186. css(ghostEl, 'opacity', '0.8');
  4187. css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed');
  4188. css(ghostEl, 'zIndex', '100000');
  4189. css(ghostEl, 'pointerEvents', 'none');
  4190. Sortable.ghost = ghostEl;
  4191. container.appendChild(ghostEl);
  4192. }
  4193. },
  4194. _onDragStart: function _onDragStart(
  4195. /**Event*/
  4196. evt,
  4197. /**boolean*/
  4198. fallback) {
  4199. var _this = this;
  4200. var dataTransfer = evt.dataTransfer;
  4201. var options = _this.options;
  4202. pluginEvent('dragStart', this, {
  4203. evt: evt
  4204. });
  4205. if (Sortable.eventCanceled) {
  4206. this._onDrop();
  4207. return;
  4208. }
  4209. pluginEvent('setupClone', this);
  4210. if (!Sortable.eventCanceled) {
  4211. cloneEl = clone(dragEl);
  4212. cloneEl.draggable = false;
  4213. cloneEl.style['will-change'] = '';
  4214. this._hideClone();
  4215. toggleClass(cloneEl, this.options.chosenClass, false);
  4216. Sortable.clone = cloneEl;
  4217. } // #1143: IFrame support workaround
  4218. _this.cloneId = _nextTick(function () {
  4219. pluginEvent('clone', _this);
  4220. if (Sortable.eventCanceled) return;
  4221. if (!_this.options.removeCloneOnHide) {
  4222. rootEl.insertBefore(cloneEl, dragEl);
  4223. }
  4224. _this._hideClone();
  4225. _dispatchEvent({
  4226. sortable: _this,
  4227. name: 'clone'
  4228. });
  4229. });
  4230. !fallback && toggleClass(dragEl, options.dragClass, true); // Set proper drop events
  4231. if (fallback) {
  4232. ignoreNextClick = true;
  4233. _this._loopId = setInterval(_this._emulateDragOver, 50);
  4234. } else {
  4235. // Undo what was set in _prepareDragStart before drag started
  4236. off(document, 'mouseup', _this._onDrop);
  4237. off(document, 'touchend', _this._onDrop);
  4238. off(document, 'touchcancel', _this._onDrop);
  4239. if (dataTransfer) {
  4240. dataTransfer.effectAllowed = 'move';
  4241. options.setData && options.setData.call(_this, dataTransfer, dragEl);
  4242. }
  4243. on(document, 'drop', _this); // #1276 fix:
  4244. css(dragEl, 'transform', 'translateZ(0)');
  4245. }
  4246. awaitingDragStarted = true;
  4247. _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));
  4248. on(document, 'selectstart', _this);
  4249. moved = true;
  4250. if (Safari) {
  4251. css(document.body, 'user-select', 'none');
  4252. }
  4253. },
  4254. // Returns true - if no further action is needed (either inserted or another condition)
  4255. _onDragOver: function _onDragOver(
  4256. /**Event*/
  4257. evt) {
  4258. var el = this.el,
  4259. target = evt.target,
  4260. dragRect,
  4261. targetRect,
  4262. revert,
  4263. options = this.options,
  4264. group = options.group,
  4265. activeSortable = Sortable.active,
  4266. isOwner = activeGroup === group,
  4267. canSort = options.sort,
  4268. fromSortable = putSortable || activeSortable,
  4269. vertical,
  4270. _this = this,
  4271. completedFired = false;
  4272. if (_silent) return;
  4273. function dragOverEvent(name, extra) {
  4274. pluginEvent(name, _this, _objectSpread({
  4275. evt: evt,
  4276. isOwner: isOwner,
  4277. axis: vertical ? 'vertical' : 'horizontal',
  4278. revert: revert,
  4279. dragRect: dragRect,
  4280. targetRect: targetRect,
  4281. canSort: canSort,
  4282. fromSortable: fromSortable,
  4283. target: target,
  4284. completed: completed,
  4285. onMove: function onMove(target, after) {
  4286. return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after);
  4287. },
  4288. changed: changed
  4289. }, extra));
  4290. } // Capture animation state
  4291. function capture() {
  4292. dragOverEvent('dragOverAnimationCapture');
  4293. _this.captureAnimationState();
  4294. if (_this !== fromSortable) {
  4295. fromSortable.captureAnimationState();
  4296. }
  4297. } // Return invocation when dragEl is inserted (or completed)
  4298. function completed(insertion) {
  4299. dragOverEvent('dragOverCompleted', {
  4300. insertion: insertion
  4301. });
  4302. if (insertion) {
  4303. // Clones must be hidden before folding animation to capture dragRectAbsolute properly
  4304. if (isOwner) {
  4305. activeSortable._hideClone();
  4306. } else {
  4307. activeSortable._showClone(_this);
  4308. }
  4309. if (_this !== fromSortable) {
  4310. // Set ghost class to new sortable's ghost class
  4311. toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);
  4312. toggleClass(dragEl, options.ghostClass, true);
  4313. }
  4314. if (putSortable !== _this && _this !== Sortable.active) {
  4315. putSortable = _this;
  4316. } else if (_this === Sortable.active && putSortable) {
  4317. putSortable = null;
  4318. } // Animation
  4319. if (fromSortable === _this) {
  4320. _this._ignoreWhileAnimating = target;
  4321. }
  4322. _this.animateAll(function () {
  4323. dragOverEvent('dragOverAnimationComplete');
  4324. _this._ignoreWhileAnimating = null;
  4325. });
  4326. if (_this !== fromSortable) {
  4327. fromSortable.animateAll();
  4328. fromSortable._ignoreWhileAnimating = null;
  4329. }
  4330. } // Null lastTarget if it is not inside a previously swapped element
  4331. if (target === dragEl && !dragEl.animated || target === el && !target.animated) {
  4332. lastTarget = null;
  4333. } // no bubbling and not fallback
  4334. if (!options.dragoverBubble && !evt.rootEl && target !== document) {
  4335. dragEl.parentNode[expando]._isOutsideThisEl(evt.target); // Do not detect for empty insert if already inserted
  4336. !insertion && nearestEmptyInsertDetectEvent(evt);
  4337. }
  4338. !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();
  4339. return completedFired = true;
  4340. } // Call when dragEl has been inserted
  4341. function changed() {
  4342. newIndex = index(dragEl);
  4343. newDraggableIndex = index(dragEl, options.draggable);
  4344. _dispatchEvent({
  4345. sortable: _this,
  4346. name: 'change',
  4347. toEl: el,
  4348. newIndex: newIndex,
  4349. newDraggableIndex: newDraggableIndex,
  4350. originalEvent: evt
  4351. });
  4352. }
  4353. if (evt.preventDefault !== void 0) {
  4354. evt.cancelable && evt.preventDefault();
  4355. }
  4356. target = closest(target, options.draggable, el, true);
  4357. dragOverEvent('dragOver');
  4358. if (Sortable.eventCanceled) return completedFired;
  4359. if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) {
  4360. return completed(false);
  4361. }
  4362. ignoreNextClick = false;
  4363. if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list
  4364. : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) {
  4365. vertical = this._getDirection(evt, target) === 'vertical';
  4366. dragRect = getRect(dragEl);
  4367. dragOverEvent('dragOverValid');
  4368. if (Sortable.eventCanceled) return completedFired;
  4369. if (revert) {
  4370. parentEl = rootEl; // actualization
  4371. capture();
  4372. this._hideClone();
  4373. dragOverEvent('revert');
  4374. if (!Sortable.eventCanceled) {
  4375. if (nextEl) {
  4376. rootEl.insertBefore(dragEl, nextEl);
  4377. } else {
  4378. rootEl.appendChild(dragEl);
  4379. }
  4380. }
  4381. return completed(true);
  4382. }
  4383. var elLastChild = lastChild(el, options.draggable);
  4384. if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) {
  4385. // If already at end of list: Do not insert
  4386. if (elLastChild === dragEl) {
  4387. return completed(false);
  4388. } // assign target only if condition is true
  4389. if (elLastChild && el === evt.target) {
  4390. target = elLastChild;
  4391. }
  4392. if (target) {
  4393. targetRect = getRect(target);
  4394. }
  4395. if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {
  4396. capture();
  4397. el.appendChild(dragEl);
  4398. parentEl = el; // actualization
  4399. changed();
  4400. return completed(true);
  4401. }
  4402. } else if (target.parentNode === el) {
  4403. targetRect = getRect(target);
  4404. var direction = 0,
  4405. targetBeforeFirstSwap,
  4406. differentLevel = dragEl.parentNode !== el,
  4407. differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical),
  4408. side1 = vertical ? 'top' : 'left',
  4409. scrolledPastTop = isScrolledPast(target, null, 'top', 'top') || isScrolledPast(dragEl, null, 'top', 'top'),
  4410. scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;
  4411. if (lastTarget !== target) {
  4412. targetBeforeFirstSwap = targetRect[side1];
  4413. pastFirstInvertThresh = false;
  4414. isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;
  4415. }
  4416. direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);
  4417. var sibling;
  4418. if (direction !== 0) {
  4419. // Check if target is beside dragEl in respective direction (ignoring hidden elements)
  4420. var dragIndex = index(dragEl);
  4421. do {
  4422. dragIndex -= direction;
  4423. sibling = parentEl.children[dragIndex];
  4424. } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl));
  4425. } // If dragEl is already beside target: Do not insert
  4426. if (direction === 0 || sibling === target) {
  4427. return completed(false);
  4428. }
  4429. lastTarget = target;
  4430. lastDirection = direction;
  4431. var nextSibling = target.nextElementSibling,
  4432. after = false;
  4433. after = direction === 1;
  4434. var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);
  4435. if (moveVector !== false) {
  4436. if (moveVector === 1 || moveVector === -1) {
  4437. after = moveVector === 1;
  4438. }
  4439. _silent = true;
  4440. setTimeout(_unsilent, 30);
  4441. capture();
  4442. if (after && !nextSibling) {
  4443. el.appendChild(dragEl);
  4444. } else {
  4445. target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
  4446. } // Undo chrome's scroll adjustment (has no effect on other browsers)
  4447. if (scrolledPastTop) {
  4448. scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);
  4449. }
  4450. parentEl = dragEl.parentNode; // actualization
  4451. // must be done before animation
  4452. if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {
  4453. targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]);
  4454. }
  4455. changed();
  4456. return completed(true);
  4457. }
  4458. }
  4459. if (el.contains(dragEl)) {
  4460. return completed(false);
  4461. }
  4462. }
  4463. return false;
  4464. },
  4465. _ignoreWhileAnimating: null,
  4466. _offMoveEvents: function _offMoveEvents() {
  4467. off(document, 'mousemove', this._onTouchMove);
  4468. off(document, 'touchmove', this._onTouchMove);
  4469. off(document, 'pointermove', this._onTouchMove);
  4470. off(document, 'dragover', nearestEmptyInsertDetectEvent);
  4471. off(document, 'mousemove', nearestEmptyInsertDetectEvent);
  4472. off(document, 'touchmove', nearestEmptyInsertDetectEvent);
  4473. },
  4474. _offUpEvents: function _offUpEvents() {
  4475. var ownerDocument = this.el.ownerDocument;
  4476. off(ownerDocument, 'mouseup', this._onDrop);
  4477. off(ownerDocument, 'touchend', this._onDrop);
  4478. off(ownerDocument, 'pointerup', this._onDrop);
  4479. off(ownerDocument, 'touchcancel', this._onDrop);
  4480. off(document, 'selectstart', this);
  4481. },
  4482. _onDrop: function _onDrop(
  4483. /**Event*/
  4484. evt) {
  4485. var el = this.el,
  4486. options = this.options; // Get the index of the dragged element within its parent
  4487. newIndex = index(dragEl);
  4488. newDraggableIndex = index(dragEl, options.draggable);
  4489. pluginEvent('drop', this, {
  4490. evt: evt
  4491. }); // Get again after plugin event
  4492. newIndex = index(dragEl);
  4493. newDraggableIndex = index(dragEl, options.draggable);
  4494. if (Sortable.eventCanceled) {
  4495. this._nulling();
  4496. return;
  4497. }
  4498. awaitingDragStarted = false;
  4499. isCircumstantialInvert = false;
  4500. pastFirstInvertThresh = false;
  4501. clearInterval(this._loopId);
  4502. clearTimeout(this._dragStartTimer);
  4503. _cancelNextTick(this.cloneId);
  4504. _cancelNextTick(this._dragStartId); // Unbind events
  4505. if (this.nativeDraggable) {
  4506. off(document, 'drop', this);
  4507. off(el, 'dragstart', this._onDragStart);
  4508. }
  4509. this._offMoveEvents();
  4510. this._offUpEvents();
  4511. if (Safari) {
  4512. css(document.body, 'user-select', '');
  4513. }
  4514. if (evt) {
  4515. if (moved) {
  4516. evt.cancelable && evt.preventDefault();
  4517. !options.dropBubble && evt.stopPropagation();
  4518. }
  4519. ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);
  4520. if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
  4521. // Remove clone(s)
  4522. cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
  4523. }
  4524. if (dragEl) {
  4525. if (this.nativeDraggable) {
  4526. off(dragEl, 'dragend', this);
  4527. }
  4528. _disableDraggable(dragEl);
  4529. dragEl.style['will-change'] = ''; // Remove classes
  4530. // ghostClass is added in dragStarted
  4531. if (moved && !awaitingDragStarted) {
  4532. toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);
  4533. }
  4534. toggleClass(dragEl, this.options.chosenClass, false); // Drag stop event
  4535. _dispatchEvent({
  4536. sortable: this,
  4537. name: 'unchoose',
  4538. toEl: parentEl,
  4539. newIndex: null,
  4540. newDraggableIndex: null,
  4541. originalEvent: evt
  4542. });
  4543. if (rootEl !== parentEl) {
  4544. if (newIndex >= 0) {
  4545. // Add event
  4546. _dispatchEvent({
  4547. rootEl: parentEl,
  4548. name: 'add',
  4549. toEl: parentEl,
  4550. fromEl: rootEl,
  4551. originalEvent: evt
  4552. }); // Remove event
  4553. _dispatchEvent({
  4554. sortable: this,
  4555. name: 'remove',
  4556. toEl: parentEl,
  4557. originalEvent: evt
  4558. }); // drag from one list and drop into another
  4559. _dispatchEvent({
  4560. rootEl: parentEl,
  4561. name: 'sort',
  4562. toEl: parentEl,
  4563. fromEl: rootEl,
  4564. originalEvent: evt
  4565. });
  4566. _dispatchEvent({
  4567. sortable: this,
  4568. name: 'sort',
  4569. toEl: parentEl,
  4570. originalEvent: evt
  4571. });
  4572. }
  4573. putSortable && putSortable.save();
  4574. } else {
  4575. if (newIndex !== oldIndex) {
  4576. if (newIndex >= 0) {
  4577. // drag & drop within the same list
  4578. _dispatchEvent({
  4579. sortable: this,
  4580. name: 'update',
  4581. toEl: parentEl,
  4582. originalEvent: evt
  4583. });
  4584. _dispatchEvent({
  4585. sortable: this,
  4586. name: 'sort',
  4587. toEl: parentEl,
  4588. originalEvent: evt
  4589. });
  4590. }
  4591. }
  4592. }
  4593. if (Sortable.active) {
  4594. /* jshint eqnull:true */
  4595. if (newIndex == null || newIndex === -1) {
  4596. newIndex = oldIndex;
  4597. newDraggableIndex = oldDraggableIndex;
  4598. }
  4599. _dispatchEvent({
  4600. sortable: this,
  4601. name: 'end',
  4602. toEl: parentEl,
  4603. originalEvent: evt
  4604. }); // Save sorting
  4605. this.save();
  4606. }
  4607. }
  4608. }
  4609. this._nulling();
  4610. },
  4611. _nulling: function _nulling() {
  4612. pluginEvent('nulling', this);
  4613. rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null;
  4614. savedInputChecked.forEach(function (el) {
  4615. el.checked = true;
  4616. });
  4617. savedInputChecked.length = 0;
  4618. },
  4619. handleEvent: function handleEvent(
  4620. /**Event*/
  4621. evt) {
  4622. switch (evt.type) {
  4623. case 'drop':
  4624. case 'dragend':
  4625. this._onDrop(evt);
  4626. break;
  4627. case 'dragenter':
  4628. case 'dragover':
  4629. if (dragEl) {
  4630. this._onDragOver(evt);
  4631. _globalDragOver(evt);
  4632. }
  4633. break;
  4634. case 'selectstart':
  4635. evt.preventDefault();
  4636. break;
  4637. }
  4638. },
  4639. /**
  4640. * Serializes the item into an array of string.
  4641. * @returns {String[]}
  4642. */
  4643. toArray: function toArray() {
  4644. var order = [],
  4645. el,
  4646. children = this.el.children,
  4647. i = 0,
  4648. n = children.length,
  4649. options = this.options;
  4650. for (; i < n; i++) {
  4651. el = children[i];
  4652. if (closest(el, options.draggable, this.el, false)) {
  4653. order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
  4654. }
  4655. }
  4656. return order;
  4657. },
  4658. /**
  4659. * Sorts the elements according to the array.
  4660. * @param {String[]} order order of the items
  4661. */
  4662. sort: function sort(order) {
  4663. var items = {},
  4664. rootEl = this.el;
  4665. this.toArray().forEach(function (id, i) {
  4666. var el = rootEl.children[i];
  4667. if (closest(el, this.options.draggable, rootEl, false)) {
  4668. items[id] = el;
  4669. }
  4670. }, this);
  4671. order.forEach(function (id) {
  4672. if (items[id]) {
  4673. rootEl.removeChild(items[id]);
  4674. rootEl.appendChild(items[id]);
  4675. }
  4676. });
  4677. },
  4678. /**
  4679. * Save the current sorting
  4680. */
  4681. save: function save() {
  4682. var store = this.options.store;
  4683. store && store.set && store.set(this);
  4684. },
  4685. /**
  4686. * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
  4687. * @param {HTMLElement} el
  4688. * @param {String} [selector] default: options.draggable
  4689. * @returns {HTMLElement|null}
  4690. */
  4691. closest: function closest$1(el, selector) {
  4692. return closest(el, selector || this.options.draggable, this.el, false);
  4693. },
  4694. /**
  4695. * Set/get option
  4696. * @param {string} name
  4697. * @param {*} [value]
  4698. * @returns {*}
  4699. */
  4700. option: function option(name, value) {
  4701. var options = this.options;
  4702. if (value === void 0) {
  4703. return options[name];
  4704. } else {
  4705. var modifiedValue = PluginManager.modifyOption(this, name, value);
  4706. if (typeof modifiedValue !== 'undefined') {
  4707. options[name] = modifiedValue;
  4708. } else {
  4709. options[name] = value;
  4710. }
  4711. if (name === 'group') {
  4712. _prepareGroup(options);
  4713. }
  4714. }
  4715. },
  4716. /**
  4717. * Destroy
  4718. */
  4719. destroy: function destroy() {
  4720. pluginEvent('destroy', this);
  4721. var el = this.el;
  4722. el[expando] = null;
  4723. off(el, 'mousedown', this._onTapStart);
  4724. off(el, 'touchstart', this._onTapStart);
  4725. off(el, 'pointerdown', this._onTapStart);
  4726. if (this.nativeDraggable) {
  4727. off(el, 'dragover', this);
  4728. off(el, 'dragenter', this);
  4729. } // Remove draggable attributes
  4730. Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
  4731. el.removeAttribute('draggable');
  4732. });
  4733. this._onDrop();
  4734. sortables.splice(sortables.indexOf(this.el), 1);
  4735. this.el = el = null;
  4736. },
  4737. _hideClone: function _hideClone() {
  4738. if (!cloneHidden) {
  4739. pluginEvent('hideClone', this);
  4740. if (Sortable.eventCanceled) return;
  4741. css(cloneEl, 'display', 'none');
  4742. if (this.options.removeCloneOnHide && cloneEl.parentNode) {
  4743. cloneEl.parentNode.removeChild(cloneEl);
  4744. }
  4745. cloneHidden = true;
  4746. }
  4747. },
  4748. _showClone: function _showClone(putSortable) {
  4749. if (putSortable.lastPutMode !== 'clone') {
  4750. this._hideClone();
  4751. return;
  4752. }
  4753. if (cloneHidden) {
  4754. pluginEvent('showClone', this);
  4755. if (Sortable.eventCanceled) return; // show clone at dragEl or original position
  4756. if (rootEl.contains(dragEl) && !this.options.group.revertClone) {
  4757. rootEl.insertBefore(cloneEl, dragEl);
  4758. } else if (nextEl) {
  4759. rootEl.insertBefore(cloneEl, nextEl);
  4760. } else {
  4761. rootEl.appendChild(cloneEl);
  4762. }
  4763. if (this.options.group.revertClone) {
  4764. this._animate(dragEl, cloneEl);
  4765. }
  4766. css(cloneEl, 'display', '');
  4767. cloneHidden = false;
  4768. }
  4769. }
  4770. };
  4771. function _globalDragOver(
  4772. /**Event*/
  4773. evt) {
  4774. if (evt.dataTransfer) {
  4775. evt.dataTransfer.dropEffect = 'move';
  4776. }
  4777. evt.cancelable && evt.preventDefault();
  4778. }
  4779. function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) {
  4780. var evt,
  4781. sortable = fromEl[expando],
  4782. onMoveFn = sortable.options.onMove,
  4783. retVal; // Support for new CustomEvent feature
  4784. if (window.CustomEvent && !IE11OrLess && !Edge) {
  4785. evt = new CustomEvent('move', {
  4786. bubbles: true,
  4787. cancelable: true
  4788. });
  4789. } else {
  4790. evt = document.createEvent('Event');
  4791. evt.initEvent('move', true, true);
  4792. }
  4793. evt.to = toEl;
  4794. evt.from = fromEl;
  4795. evt.dragged = dragEl;
  4796. evt.draggedRect = dragRect;
  4797. evt.related = targetEl || toEl;
  4798. evt.relatedRect = targetRect || getRect(toEl);
  4799. evt.willInsertAfter = willInsertAfter;
  4800. evt.originalEvent = originalEvent;
  4801. fromEl.dispatchEvent(evt);
  4802. if (onMoveFn) {
  4803. retVal = onMoveFn.call(sortable, evt, originalEvent);
  4804. }
  4805. return retVal;
  4806. }
  4807. function _disableDraggable(el) {
  4808. el.draggable = false;
  4809. }
  4810. function _unsilent() {
  4811. _silent = false;
  4812. }
  4813. function _ghostIsLast(evt, vertical, sortable) {
  4814. var rect = getRect(lastChild(sortable.el, sortable.options.draggable));
  4815. var spacer = 10;
  4816. return vertical ? evt.clientX > rect.right + spacer || evt.clientX <= rect.right && evt.clientY > rect.bottom && evt.clientX >= rect.left : evt.clientX > rect.right && evt.clientY > rect.top || evt.clientX <= rect.right && evt.clientY > rect.bottom + spacer;
  4817. }
  4818. function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {
  4819. var mouseOnAxis = vertical ? evt.clientY : evt.clientX,
  4820. targetLength = vertical ? targetRect.height : targetRect.width,
  4821. targetS1 = vertical ? targetRect.top : targetRect.left,
  4822. targetS2 = vertical ? targetRect.bottom : targetRect.right,
  4823. invert = false;
  4824. if (!invertSwap) {
  4825. // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold
  4826. if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) {
  4827. // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2
  4828. // check if past first invert threshold on side opposite of lastDirection
  4829. if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) {
  4830. // past first invert threshold, do not restrict inverted threshold to dragEl shadow
  4831. pastFirstInvertThresh = true;
  4832. }
  4833. if (!pastFirstInvertThresh) {
  4834. // dragEl shadow (target move distance shadow)
  4835. if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow
  4836. : mouseOnAxis > targetS2 - targetMoveDistance) {
  4837. return -lastDirection;
  4838. }
  4839. } else {
  4840. invert = true;
  4841. }
  4842. } else {
  4843. // Regular
  4844. if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) {
  4845. return _getInsertDirection(target);
  4846. }
  4847. }
  4848. }
  4849. invert = invert || invertSwap;
  4850. if (invert) {
  4851. // Invert of regular
  4852. if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) {
  4853. return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1;
  4854. }
  4855. }
  4856. return 0;
  4857. }
  4858. /**
  4859. * Gets the direction dragEl must be swapped relative to target in order to make it
  4860. * seem that dragEl has been "inserted" into that element's position
  4861. * @param {HTMLElement} target The target whose position dragEl is being inserted at
  4862. * @return {Number} Direction dragEl must be swapped
  4863. */
  4864. function _getInsertDirection(target) {
  4865. if (index(dragEl) < index(target)) {
  4866. return 1;
  4867. } else {
  4868. return -1;
  4869. }
  4870. }
  4871. /**
  4872. * Generate id
  4873. * @param {HTMLElement} el
  4874. * @returns {String}
  4875. * @private
  4876. */
  4877. function _generateId(el) {
  4878. var str = el.tagName + el.className + el.src + el.href + el.textContent,
  4879. i = str.length,
  4880. sum = 0;
  4881. while (i--) {
  4882. sum += str.charCodeAt(i);
  4883. }
  4884. return sum.toString(36);
  4885. }
  4886. function _saveInputCheckedState(root) {
  4887. savedInputChecked.length = 0;
  4888. var inputs = root.getElementsByTagName('input');
  4889. var idx = inputs.length;
  4890. while (idx--) {
  4891. var _el = inputs[idx];
  4892. _el.checked && savedInputChecked.push(_el);
  4893. }
  4894. }
  4895. function _nextTick(fn) {
  4896. return setTimeout(fn, 0);
  4897. }
  4898. function _cancelNextTick(id) {
  4899. return clearTimeout(id);
  4900. } // Fixed #973:
  4901. on(document, 'touchmove', function (evt) {
  4902. if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {
  4903. evt.preventDefault();
  4904. }
  4905. }); // Export utils
  4906. Sortable.utils = {
  4907. on: on,
  4908. off: off,
  4909. css: css,
  4910. find: find,
  4911. is: function is(el, selector) {
  4912. return !!closest(el, selector, el, false);
  4913. },
  4914. extend: extend,
  4915. throttle: throttle,
  4916. closest: closest,
  4917. toggleClass: toggleClass,
  4918. clone: clone,
  4919. index: index,
  4920. nextTick: _nextTick,
  4921. cancelNextTick: _cancelNextTick,
  4922. detectDirection: _detectDirection,
  4923. getChild: getChild
  4924. };
  4925. /**
  4926. * Mount a plugin to Sortable
  4927. * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted
  4928. */
  4929. Sortable.mount = function () {
  4930. for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {
  4931. plugins[_key] = arguments[_key];
  4932. }
  4933. if (plugins[0].constructor === Array) plugins = plugins[0];
  4934. plugins.forEach(function (plugin) {
  4935. if (!plugin.prototype || !plugin.prototype.constructor) {
  4936. throw "Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(el));
  4937. }
  4938. if (plugin.utils) Sortable.utils = _objectSpread({}, Sortable.utils, plugin.utils);
  4939. PluginManager.mount(plugin);
  4940. });
  4941. };
  4942. /**
  4943. * Create sortable instance
  4944. * @param {HTMLElement} el
  4945. * @param {Object} [options]
  4946. */
  4947. Sortable.create = function (el, options) {
  4948. return new Sortable(el, options);
  4949. }; // Export
  4950. Sortable.version = version;
  4951. var autoScrolls = [],
  4952. scrollEl,
  4953. scrollRootEl,
  4954. scrolling = false,
  4955. lastAutoScrollX,
  4956. lastAutoScrollY,
  4957. touchEvt$1,
  4958. pointerElemChangedInterval;
  4959. function AutoScrollPlugin() {
  4960. function AutoScroll() {
  4961. this.options = {
  4962. scroll: true,
  4963. scrollSensitivity: 30,
  4964. scrollSpeed: 10,
  4965. bubbleScroll: true
  4966. }; // Bind all private methods
  4967. for (var fn in this) {
  4968. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  4969. this[fn] = this[fn].bind(this);
  4970. }
  4971. }
  4972. }
  4973. AutoScroll.prototype = {
  4974. dragStarted: function dragStarted(_ref) {
  4975. var originalEvent = _ref.originalEvent;
  4976. if (this.sortable.nativeDraggable) {
  4977. on(document, 'dragover', this._handleAutoScroll);
  4978. } else {
  4979. if (this.sortable.options.supportPointer) {
  4980. on(document, 'pointermove', this._handleFallbackAutoScroll);
  4981. } else if (originalEvent.touches) {
  4982. on(document, 'touchmove', this._handleFallbackAutoScroll);
  4983. } else {
  4984. on(document, 'mousemove', this._handleFallbackAutoScroll);
  4985. }
  4986. }
  4987. },
  4988. dragOverCompleted: function dragOverCompleted(_ref2) {
  4989. var originalEvent = _ref2.originalEvent;
  4990. // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached)
  4991. if (!this.sortable.options.dragOverBubble && !originalEvent.rootEl) {
  4992. this._handleAutoScroll(originalEvent);
  4993. }
  4994. },
  4995. drop: function drop() {
  4996. if (this.sortable.nativeDraggable) {
  4997. off(document, 'dragover', this._handleAutoScroll);
  4998. } else {
  4999. off(document, 'pointermove', this._handleFallbackAutoScroll);
  5000. off(document, 'touchmove', this._handleFallbackAutoScroll);
  5001. off(document, 'mousemove', this._handleFallbackAutoScroll);
  5002. }
  5003. clearPointerElemChangedInterval();
  5004. clearAutoScrolls();
  5005. cancelThrottle();
  5006. },
  5007. nulling: function nulling() {
  5008. touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null;
  5009. autoScrolls.length = 0;
  5010. },
  5011. _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) {
  5012. this._handleAutoScroll(evt, true);
  5013. },
  5014. _handleAutoScroll: function _handleAutoScroll(evt, fallback) {
  5015. var _this = this;
  5016. var x = evt.clientX,
  5017. y = evt.clientY,
  5018. elem = document.elementFromPoint(x, y);
  5019. touchEvt$1 = evt; // IE does not seem to have native autoscroll,
  5020. // Edge's autoscroll seems too conditional,
  5021. // MACOS Safari does not have autoscroll,
  5022. // Firefox and Chrome are good
  5023. if (fallback || Edge || IE11OrLess || Safari) {
  5024. autoScroll(evt, this.options, elem, fallback); // Listener for pointer element change
  5025. var ogElemScroller = getParentAutoScrollElement(elem, true);
  5026. if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) {
  5027. pointerElemChangedInterval && clearPointerElemChangedInterval(); // Detect for pointer elem change, emulating native DnD behaviour
  5028. pointerElemChangedInterval = setInterval(function () {
  5029. var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true);
  5030. if (newElem !== ogElemScroller) {
  5031. ogElemScroller = newElem;
  5032. clearAutoScrolls();
  5033. }
  5034. autoScroll(evt, _this.options, newElem, fallback);
  5035. }, 10);
  5036. lastAutoScrollX = x;
  5037. lastAutoScrollY = y;
  5038. }
  5039. } else {
  5040. // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll
  5041. if (!this.sortable.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) {
  5042. clearAutoScrolls();
  5043. return;
  5044. }
  5045. autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false);
  5046. }
  5047. }
  5048. };
  5049. return _extends(AutoScroll, {
  5050. pluginName: 'scroll',
  5051. initializeByDefault: true
  5052. });
  5053. }
  5054. function clearAutoScrolls() {
  5055. autoScrolls.forEach(function (autoScroll) {
  5056. clearInterval(autoScroll.pid);
  5057. });
  5058. autoScrolls = [];
  5059. }
  5060. function clearPointerElemChangedInterval() {
  5061. clearInterval(pointerElemChangedInterval);
  5062. }
  5063. var autoScroll = throttle(function (evt, options, rootEl, isFallback) {
  5064. // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
  5065. if (!options.scroll) return;
  5066. var sens = options.scrollSensitivity,
  5067. speed = options.scrollSpeed,
  5068. winScroller = getWindowScrollingElement();
  5069. var scrollThisInstance = false,
  5070. scrollCustomFn; // New scroll root, set scrollEl
  5071. if (scrollRootEl !== rootEl) {
  5072. scrollRootEl = rootEl;
  5073. clearAutoScrolls();
  5074. scrollEl = options.scroll;
  5075. scrollCustomFn = options.scrollFn;
  5076. if (scrollEl === true) {
  5077. scrollEl = getParentAutoScrollElement(rootEl, true);
  5078. }
  5079. }
  5080. var layersOut = 0;
  5081. var currentParent = scrollEl;
  5082. do {
  5083. var el = currentParent,
  5084. rect = getRect(el),
  5085. top = rect.top,
  5086. bottom = rect.bottom,
  5087. left = rect.left,
  5088. right = rect.right,
  5089. width = rect.width,
  5090. height = rect.height,
  5091. canScrollX = void 0,
  5092. canScrollY = void 0,
  5093. scrollWidth = el.scrollWidth,
  5094. scrollHeight = el.scrollHeight,
  5095. elCSS = css(el),
  5096. scrollPosX = el.scrollLeft,
  5097. scrollPosY = el.scrollTop;
  5098. if (el === winScroller) {
  5099. canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible');
  5100. canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible');
  5101. } else {
  5102. canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll');
  5103. canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll');
  5104. }
  5105. var vx = canScrollX && (Math.abs(right - evt.clientX) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - evt.clientX) <= sens && !!scrollPosX);
  5106. var vy = canScrollY && (Math.abs(bottom - evt.clientY) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - evt.clientY) <= sens && !!scrollPosY);
  5107. if (!autoScrolls[layersOut]) {
  5108. for (var i = 0; i <= layersOut; i++) {
  5109. if (!autoScrolls[i]) {
  5110. autoScrolls[i] = {};
  5111. }
  5112. }
  5113. }
  5114. if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {
  5115. autoScrolls[layersOut].el = el;
  5116. autoScrolls[layersOut].vx = vx;
  5117. autoScrolls[layersOut].vy = vy;
  5118. clearInterval(autoScrolls[layersOut].pid);
  5119. if (vx != 0 || vy != 0) {
  5120. scrollThisInstance = true;
  5121. /* jshint loopfunc:true */
  5122. autoScrolls[layersOut].pid = setInterval(function () {
  5123. // emulate drag over during autoscroll (fallback), emulating native DnD behaviour
  5124. if (isFallback && this.layer === 0) {
  5125. Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely
  5126. }
  5127. var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;
  5128. var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;
  5129. if (typeof scrollCustomFn === 'function') {
  5130. if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') {
  5131. return;
  5132. }
  5133. }
  5134. scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);
  5135. }.bind({
  5136. layer: layersOut
  5137. }), 24);
  5138. }
  5139. }
  5140. layersOut++;
  5141. } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false)));
  5142. scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not
  5143. }, 30);
  5144. var drop = function drop(_ref) {
  5145. var originalEvent = _ref.originalEvent,
  5146. putSortable = _ref.putSortable,
  5147. dragEl = _ref.dragEl,
  5148. activeSortable = _ref.activeSortable,
  5149. dispatchSortableEvent = _ref.dispatchSortableEvent,
  5150. hideGhostForTarget = _ref.hideGhostForTarget,
  5151. unhideGhostForTarget = _ref.unhideGhostForTarget;
  5152. var toSortable = putSortable || activeSortable;
  5153. hideGhostForTarget();
  5154. var target = document.elementFromPoint(originalEvent.clientX, originalEvent.clientY);
  5155. unhideGhostForTarget();
  5156. if (toSortable && !toSortable.el.contains(target)) {
  5157. dispatchSortableEvent('spill');
  5158. this.onSpill(dragEl);
  5159. }
  5160. };
  5161. function Revert() {}
  5162. Revert.prototype = {
  5163. startIndex: null,
  5164. dragStart: function dragStart(_ref2) {
  5165. var oldDraggableIndex = _ref2.oldDraggableIndex;
  5166. this.startIndex = oldDraggableIndex;
  5167. },
  5168. onSpill: function onSpill(dragEl) {
  5169. this.sortable.captureAnimationState();
  5170. var nextSibling = getChild(this.sortable.el, this.startIndex, this.sortable.options);
  5171. if (nextSibling) {
  5172. this.sortable.el.insertBefore(dragEl, nextSibling);
  5173. } else {
  5174. this.sortable.el.appendChild(dragEl);
  5175. }
  5176. this.sortable.animateAll();
  5177. },
  5178. drop: drop
  5179. };
  5180. _extends(Revert, {
  5181. pluginName: 'revertOnSpill'
  5182. });
  5183. function Remove() {}
  5184. Remove.prototype = {
  5185. onSpill: function onSpill(dragEl) {
  5186. this.sortable.captureAnimationState();
  5187. dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
  5188. this.sortable.animateAll();
  5189. },
  5190. drop: drop
  5191. };
  5192. _extends(Remove, {
  5193. pluginName: 'removeOnSpill'
  5194. });
  5195. var lastSwapEl;
  5196. function SwapPlugin() {
  5197. function Swap() {
  5198. this.options = {
  5199. swapClass: 'sortable-swap-highlight'
  5200. };
  5201. }
  5202. Swap.prototype = {
  5203. dragStart: function dragStart(_ref) {
  5204. var dragEl = _ref.dragEl;
  5205. lastSwapEl = dragEl;
  5206. },
  5207. dragOverValid: function dragOverValid(_ref2) {
  5208. var completed = _ref2.completed,
  5209. target = _ref2.target,
  5210. onMove = _ref2.onMove,
  5211. activeSortable = _ref2.activeSortable,
  5212. changed = _ref2.changed;
  5213. if (!activeSortable.options.swap) return;
  5214. var el = this.sortable.el,
  5215. options = this.sortable.options;
  5216. if (target && target !== el) {
  5217. var prevSwapEl = lastSwapEl;
  5218. if (onMove(target) !== false) {
  5219. toggleClass(target, options.swapClass, true);
  5220. lastSwapEl = target;
  5221. } else {
  5222. lastSwapEl = null;
  5223. }
  5224. if (prevSwapEl && prevSwapEl !== lastSwapEl) {
  5225. toggleClass(prevSwapEl, options.swapClass, false);
  5226. }
  5227. }
  5228. changed();
  5229. return completed(true);
  5230. },
  5231. drop: function drop(_ref3) {
  5232. var activeSortable = _ref3.activeSortable,
  5233. putSortable = _ref3.putSortable,
  5234. dragEl = _ref3.dragEl;
  5235. var toSortable = putSortable || this.sortable;
  5236. var options = this.sortable.options;
  5237. lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false);
  5238. if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) {
  5239. if (dragEl !== lastSwapEl) {
  5240. toSortable.captureAnimationState();
  5241. if (toSortable !== activeSortable) activeSortable.captureAnimationState();
  5242. swapNodes(dragEl, lastSwapEl);
  5243. toSortable.animateAll();
  5244. if (toSortable !== activeSortable) activeSortable.animateAll();
  5245. }
  5246. }
  5247. },
  5248. nulling: function nulling() {
  5249. lastSwapEl = null;
  5250. }
  5251. };
  5252. return _extends(Swap, {
  5253. pluginName: 'swap',
  5254. eventOptions: function eventOptions() {
  5255. return {
  5256. swapItem: lastSwapEl
  5257. };
  5258. }
  5259. });
  5260. }
  5261. function swapNodes(n1, n2) {
  5262. var p1 = n1.parentNode,
  5263. p2 = n2.parentNode,
  5264. i1,
  5265. i2;
  5266. if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return;
  5267. i1 = index(n1);
  5268. i2 = index(n2);
  5269. if (p1.isEqualNode(p2) && i1 < i2) {
  5270. i2++;
  5271. }
  5272. p1.insertBefore(n2, p1.children[i1]);
  5273. p2.insertBefore(n1, p2.children[i2]);
  5274. }
  5275. var multiDragElements = [],
  5276. multiDragClones = [],
  5277. lastMultiDragSelect,
  5278. // for selection with modifier key down (SHIFT)
  5279. multiDragSortable,
  5280. initialFolding = false,
  5281. // Initial multi-drag fold when drag started
  5282. folding = false,
  5283. // Folding any other time
  5284. dragStarted = false,
  5285. dragEl$1,
  5286. clonesFromRect,
  5287. clonesHidden;
  5288. function MultiDragPlugin() {
  5289. function MultiDrag(sortable) {
  5290. // Bind all private methods
  5291. for (var fn in this) {
  5292. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  5293. this[fn] = this[fn].bind(this);
  5294. }
  5295. }
  5296. if (sortable.options.supportPointer) {
  5297. on(document, 'pointerup', this._deselectMultiDrag);
  5298. } else {
  5299. on(document, 'mouseup', this._deselectMultiDrag);
  5300. on(document, 'touchend', this._deselectMultiDrag);
  5301. }
  5302. on(document, 'keydown', this._checkKeyDown);
  5303. on(document, 'keyup', this._checkKeyUp);
  5304. this.options = {
  5305. selectedClass: 'sortable-selected',
  5306. multiDragKey: null,
  5307. setData: function setData(dataTransfer, dragEl) {
  5308. var data = '';
  5309. if (multiDragElements.length && multiDragSortable === sortable) {
  5310. multiDragElements.forEach(function (multiDragElement, i) {
  5311. data += (!i ? '' : ', ') + multiDragElement.textContent;
  5312. });
  5313. } else {
  5314. data = dragEl.textContent;
  5315. }
  5316. dataTransfer.setData('Text', data);
  5317. }
  5318. };
  5319. }
  5320. MultiDrag.prototype = {
  5321. multiDragKeyDown: false,
  5322. isMultiDrag: false,
  5323. delayStartGlobal: function delayStartGlobal(_ref) {
  5324. var dragged = _ref.dragEl;
  5325. dragEl$1 = dragged;
  5326. },
  5327. delayEnded: function delayEnded() {
  5328. this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1);
  5329. },
  5330. setupClone: function setupClone(_ref2) {
  5331. var sortable = _ref2.sortable;
  5332. if (!this.isMultiDrag) return;
  5333. for (var _i = 0; _i < multiDragElements.length; _i++) {
  5334. multiDragClones.push(clone(multiDragElements[_i]));
  5335. multiDragClones[_i].sortableIndex = multiDragElements[_i].sortableIndex;
  5336. multiDragClones[_i].draggable = false;
  5337. multiDragClones[_i].style['will-change'] = '';
  5338. toggleClass(multiDragClones[_i], sortable.options.selectedClass, false);
  5339. multiDragElements[_i] === dragEl$1 && toggleClass(multiDragClones[_i], sortable.options.chosenClass, false);
  5340. }
  5341. sortable._hideClone();
  5342. return true;
  5343. },
  5344. clone: function clone(_ref3) {
  5345. var sortable = _ref3.sortable,
  5346. rootEl = _ref3.rootEl,
  5347. dispatchSortableEvent = _ref3.dispatchSortableEvent;
  5348. if (!this.isMultiDrag) return;
  5349. if (!sortable.options.removeCloneOnHide) {
  5350. if (multiDragElements.length && multiDragSortable === sortable) {
  5351. insertMultiDragClones(true, rootEl);
  5352. dispatchSortableEvent('clone');
  5353. return true;
  5354. }
  5355. }
  5356. },
  5357. showClone: function showClone(_ref4) {
  5358. var cloneNowShown = _ref4.cloneNowShown,
  5359. rootEl = _ref4.rootEl;
  5360. if (!this.isMultiDrag) return;
  5361. insertMultiDragClones(false, rootEl);
  5362. multiDragClones.forEach(function (clone) {
  5363. css(clone, 'display', '');
  5364. });
  5365. cloneNowShown();
  5366. clonesHidden = false;
  5367. return true;
  5368. },
  5369. hideClone: function hideClone(_ref5) {
  5370. var sortable = _ref5.sortable,
  5371. cloneNowHidden = _ref5.cloneNowHidden;
  5372. if (!this.isMultiDrag) return;
  5373. multiDragClones.forEach(function (clone) {
  5374. css(clone, 'display', 'none');
  5375. if (sortable.options.removeCloneOnHide && clone.parentNode) {
  5376. clone.parentNode.removeChild(clone);
  5377. }
  5378. });
  5379. cloneNowHidden();
  5380. clonesHidden = true;
  5381. return true;
  5382. },
  5383. dragStartGlobal: function dragStartGlobal(_ref6) {
  5384. var sortable = _ref6.sortable;
  5385. if (!this.isMultiDrag && multiDragSortable) {
  5386. multiDragSortable.multiDrag._deselectMultiDrag();
  5387. }
  5388. multiDragElements.forEach(function (multiDragElement) {
  5389. multiDragElement.sortableIndex = index(multiDragElement);
  5390. }); // Sort multi-drag elements
  5391. multiDragElements = multiDragElements.sort(function (a, b) {
  5392. return a.sortableIndex - b.sortableIndex;
  5393. });
  5394. dragStarted = true;
  5395. },
  5396. dragStarted: function dragStarted(_ref7) {
  5397. var sortable = _ref7.sortable;
  5398. if (!this.isMultiDrag) return;
  5399. if (sortable.options.sort) {
  5400. // Capture rects,
  5401. // hide multi drag elements (by positioning them absolute),
  5402. // set multi drag elements rects to dragRect,
  5403. // show multi drag elements,
  5404. // animate to rects,
  5405. // unset rects & remove from DOM
  5406. sortable.captureAnimationState();
  5407. if (sortable.options.animation) {
  5408. multiDragElements.forEach(function (multiDragElement) {
  5409. if (multiDragElement === dragEl$1) return;
  5410. css(multiDragElement, 'position', 'absolute');
  5411. });
  5412. var dragRect = getRect(dragEl$1, false, true, true);
  5413. multiDragElements.forEach(function (multiDragElement) {
  5414. if (multiDragElement === dragEl$1) return;
  5415. setRect(multiDragElement, dragRect);
  5416. });
  5417. folding = true;
  5418. initialFolding = true;
  5419. }
  5420. }
  5421. sortable.animateAll(function () {
  5422. folding = false;
  5423. initialFolding = false;
  5424. if (sortable.options.animation) {
  5425. multiDragElements.forEach(function (multiDragElement) {
  5426. unsetRect(multiDragElement);
  5427. });
  5428. } // Remove all auxiliary multidrag items from el, if sorting enabled
  5429. if (sortable.options.sort) {
  5430. removeMultiDragElements();
  5431. }
  5432. });
  5433. },
  5434. dragOver: function dragOver(_ref8) {
  5435. var target = _ref8.target,
  5436. completed = _ref8.completed;
  5437. if (folding && ~multiDragElements.indexOf(target)) {
  5438. return completed(false);
  5439. }
  5440. },
  5441. revert: function revert(_ref9) {
  5442. var fromSortable = _ref9.fromSortable,
  5443. rootEl = _ref9.rootEl,
  5444. sortable = _ref9.sortable,
  5445. dragRect = _ref9.dragRect;
  5446. if (multiDragElements.length > 1) {
  5447. // Setup unfold animation
  5448. multiDragElements.forEach(function (multiDragElement) {
  5449. sortable.addAnimationState({
  5450. target: multiDragElement,
  5451. rect: folding ? getRect(multiDragElement) : dragRect
  5452. });
  5453. unsetRect(multiDragElement);
  5454. multiDragElement.fromRect = dragRect;
  5455. fromSortable.removeAnimationState(multiDragElement);
  5456. });
  5457. folding = false;
  5458. insertMultiDragElements(!sortable.options.removeCloneOnHide, rootEl);
  5459. }
  5460. },
  5461. dragOverCompleted: function dragOverCompleted(_ref10) {
  5462. var sortable = _ref10.sortable,
  5463. isOwner = _ref10.isOwner,
  5464. insertion = _ref10.insertion,
  5465. activeSortable = _ref10.activeSortable,
  5466. parentEl = _ref10.parentEl,
  5467. putSortable = _ref10.putSortable;
  5468. var options = sortable.options;
  5469. if (insertion) {
  5470. // Clones must be hidden before folding animation to capture dragRectAbsolute properly
  5471. if (isOwner) {
  5472. activeSortable._hideClone();
  5473. }
  5474. initialFolding = false; // If leaving sort:false root, or already folding - Fold to new location
  5475. if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) {
  5476. // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible
  5477. var dragRectAbsolute = getRect(dragEl$1, false, true, true);
  5478. multiDragElements.forEach(function (multiDragElement) {
  5479. if (multiDragElement === dragEl$1) return;
  5480. setRect(multiDragElement, dragRectAbsolute); // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted
  5481. // while folding, and so that we can capture them again because old sortable will no longer be fromSortable
  5482. parentEl.appendChild(multiDragElement);
  5483. });
  5484. folding = true;
  5485. } // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out
  5486. if (!isOwner) {
  5487. // Only remove if not folding (folding will remove them anyways)
  5488. if (!folding) {
  5489. removeMultiDragElements();
  5490. }
  5491. if (multiDragElements.length > 1) {
  5492. var clonesHiddenBefore = clonesHidden;
  5493. activeSortable._showClone(sortable); // Unfold animation for clones if showing from hidden
  5494. if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) {
  5495. multiDragClones.forEach(function (clone) {
  5496. activeSortable.addAnimationState({
  5497. target: clone,
  5498. rect: clonesFromRect
  5499. });
  5500. clone.fromRect = clonesFromRect;
  5501. clone.thisAnimationDuration = null;
  5502. });
  5503. }
  5504. } else {
  5505. activeSortable._showClone(sortable);
  5506. }
  5507. }
  5508. }
  5509. },
  5510. dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) {
  5511. var dragRect = _ref11.dragRect,
  5512. isOwner = _ref11.isOwner,
  5513. activeSortable = _ref11.activeSortable;
  5514. multiDragElements.forEach(function (multiDragElement) {
  5515. multiDragElement.thisAnimationDuration = null;
  5516. });
  5517. if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) {
  5518. clonesFromRect = _extends({}, dragRect);
  5519. var dragMatrix = matrix(dragEl$1, true);
  5520. clonesFromRect.top -= dragMatrix.f;
  5521. clonesFromRect.left -= dragMatrix.e;
  5522. }
  5523. },
  5524. dragOverAnimationComplete: function dragOverAnimationComplete() {
  5525. if (folding) {
  5526. folding = false;
  5527. removeMultiDragElements();
  5528. }
  5529. },
  5530. drop: function drop(_ref12) {
  5531. var evt = _ref12.originalEvent,
  5532. rootEl = _ref12.rootEl,
  5533. parentEl = _ref12.parentEl,
  5534. sortable = _ref12.sortable,
  5535. dispatchSortableEvent = _ref12.dispatchSortableEvent,
  5536. oldIndex = _ref12.oldIndex,
  5537. putSortable = _ref12.putSortable;
  5538. var toSortable = putSortable || this.sortable;
  5539. if (!evt) return;
  5540. var options = sortable.options,
  5541. children = parentEl.children; // Multi-drag selection
  5542. if (!dragStarted) {
  5543. if (options.multiDragKey && !this.multiDragKeyDown) {
  5544. this._deselectMultiDrag();
  5545. }
  5546. toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1));
  5547. if (!~multiDragElements.indexOf(dragEl$1)) {
  5548. multiDragElements.push(dragEl$1);
  5549. dispatchEvent({
  5550. sortable: sortable,
  5551. rootEl: rootEl,
  5552. name: 'select',
  5553. targetEl: dragEl$1,
  5554. originalEvt: evt
  5555. }); // Modifier activated, select from last to dragEl
  5556. if ((!options.multiDragKey || this.multiDragKeyDown) && evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) {
  5557. var lastIndex = index(lastMultiDragSelect),
  5558. currentIndex = index(dragEl$1);
  5559. if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) {
  5560. // Must include lastMultiDragSelect (select it), in case modified selection from no selection
  5561. // (but previous selection existed)
  5562. var n, _i2;
  5563. if (currentIndex > lastIndex) {
  5564. _i2 = lastIndex;
  5565. n = currentIndex;
  5566. } else {
  5567. _i2 = currentIndex;
  5568. n = lastIndex + 1;
  5569. }
  5570. for (; _i2 < n; _i2++) {
  5571. if (~multiDragElements.indexOf(children[_i2])) continue;
  5572. toggleClass(children[_i2], options.selectedClass, true);
  5573. multiDragElements.push(children[_i2]);
  5574. dispatchEvent({
  5575. sortable: sortable,
  5576. rootEl: rootEl,
  5577. name: 'select',
  5578. targetEl: children[_i2],
  5579. originalEvt: evt
  5580. });
  5581. }
  5582. }
  5583. } else {
  5584. lastMultiDragSelect = dragEl$1;
  5585. }
  5586. multiDragSortable = toSortable;
  5587. } else {
  5588. multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1);
  5589. lastMultiDragSelect = null;
  5590. dispatchEvent({
  5591. sortable: sortable,
  5592. rootEl: rootEl,
  5593. name: 'deselect',
  5594. targetEl: dragEl$1,
  5595. originalEvt: evt
  5596. });
  5597. }
  5598. } // Multi-drag drop
  5599. if (dragStarted && this.isMultiDrag) {
  5600. // Do not "unfold" after around dragEl if reverted
  5601. if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) {
  5602. var dragRect = getRect(dragEl$1),
  5603. multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')');
  5604. if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null;
  5605. toSortable.captureAnimationState();
  5606. if (!initialFolding) {
  5607. if (options.animation) {
  5608. dragEl$1.fromRect = dragRect;
  5609. multiDragElements.forEach(function (multiDragElement) {
  5610. multiDragElement.thisAnimationDuration = null;
  5611. if (multiDragElement !== dragEl$1) {
  5612. var rect = folding ? getRect(multiDragElement) : dragRect;
  5613. multiDragElement.fromRect = rect; // Prepare unfold animation
  5614. toSortable.addAnimationState({
  5615. target: multiDragElement,
  5616. rect: rect
  5617. });
  5618. }
  5619. });
  5620. } // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert
  5621. // properly they must all be removed
  5622. removeMultiDragElements();
  5623. multiDragElements.forEach(function (multiDragElement) {
  5624. if (children[multiDragIndex]) {
  5625. parentEl.insertBefore(multiDragElement, children[multiDragIndex]);
  5626. } else {
  5627. parentEl.appendChild(multiDragElement);
  5628. }
  5629. multiDragIndex++;
  5630. }); // If initial folding is done, the elements may have changed position because they are now
  5631. // unfolding around dragEl, even though dragEl may not have his index changed, so update event
  5632. // must be fired here as Sortable will not.
  5633. if (oldIndex === index(dragEl$1)) {
  5634. var update = false;
  5635. multiDragElements.forEach(function (multiDragElement) {
  5636. if (multiDragElement.sortableIndex !== index(multiDragElement)) {
  5637. update = true;
  5638. return;
  5639. }
  5640. });
  5641. if (update) {
  5642. dispatchSortableEvent('update');
  5643. }
  5644. }
  5645. } // Must be done after capturing individual rects (scroll bar)
  5646. multiDragElements.forEach(function (multiDragElement) {
  5647. unsetRect(multiDragElement);
  5648. });
  5649. toSortable.animateAll();
  5650. }
  5651. multiDragSortable = toSortable;
  5652. } // Remove clones if necessary
  5653. if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
  5654. multiDragClones.forEach(function (clone) {
  5655. clone.parentNode && clone.parentNode.removeChild(clone);
  5656. });
  5657. }
  5658. },
  5659. nullingGlobal: function nullingGlobal() {
  5660. this.isMultiDrag = dragStarted = false;
  5661. multiDragClones.length = 0;
  5662. },
  5663. destroy: function destroy() {
  5664. this._deselectMultiDrag();
  5665. off(document, 'pointerup', this._deselectMultiDrag);
  5666. off(document, 'mouseup', this._deselectMultiDrag);
  5667. off(document, 'touchend', this._deselectMultiDrag);
  5668. off(document, 'keydown', this._checkKeyDown);
  5669. off(document, 'keyup', this._checkKeyUp);
  5670. },
  5671. _deselectMultiDrag: function _deselectMultiDrag(evt) {
  5672. if (dragStarted) return; // Only deselect if selection is in this sortable
  5673. if (multiDragSortable !== this.sortable) return; // Only deselect if target is not item in this sortable
  5674. if (evt && closest(evt.target, this.sortable.options.draggable, this.sortable.el, false)) return; // Only deselect if left click
  5675. if (evt && evt.button !== 0) return;
  5676. while (multiDragElements.length) {
  5677. var el = multiDragElements[0];
  5678. toggleClass(el, this.sortable.options.selectedClass, false);
  5679. multiDragElements.shift();
  5680. dispatchEvent({
  5681. sortable: this.sortable,
  5682. rootEl: this.sortable.el,
  5683. name: 'deselect',
  5684. targetEl: el,
  5685. originalEvt: evt
  5686. });
  5687. }
  5688. },
  5689. _checkKeyDown: function _checkKeyDown(evt) {
  5690. if (evt.key === this.sortable.options.multiDragKey) {
  5691. this.multiDragKeyDown = true;
  5692. }
  5693. },
  5694. _checkKeyUp: function _checkKeyUp(evt) {
  5695. if (evt.key === this.sortable.options.multiDragKey) {
  5696. this.multiDragKeyDown = false;
  5697. }
  5698. }
  5699. };
  5700. return _extends(MultiDrag, {
  5701. // Static methods & properties
  5702. pluginName: 'multiDrag',
  5703. utils: {
  5704. /**
  5705. * Selects the provided multi-drag item
  5706. * @param {HTMLElement} el The element to be selected
  5707. */
  5708. select: function select(el) {
  5709. var sortable = el.parentNode[expando];
  5710. if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return;
  5711. if (multiDragSortable && multiDragSortable !== sortable) {
  5712. multiDragSortable.multiDrag._deselectMultiDrag();
  5713. multiDragSortable = sortable;
  5714. }
  5715. toggleClass(el, sortable.options.selectedClass, true);
  5716. multiDragElements.push(el);
  5717. },
  5718. /**
  5719. * Deselects the provided multi-drag item
  5720. * @param {HTMLElement} el The element to be deselected
  5721. */
  5722. deselect: function deselect(el) {
  5723. var sortable = el.parentNode[expando],
  5724. index = multiDragElements.indexOf(el);
  5725. if (!sortable || !sortable.options.multiDrag || !~index) return;
  5726. toggleClass(el, sortable.options.selectedClass, false);
  5727. multiDragElements.splice(index, 1);
  5728. }
  5729. },
  5730. eventOptions: function eventOptions() {
  5731. var _this = this;
  5732. var oldIndicies = [],
  5733. newIndicies = [];
  5734. multiDragElements.forEach(function (multiDragElement) {
  5735. oldIndicies.push({
  5736. multiDragElement: multiDragElement,
  5737. index: multiDragElement.sortableIndex
  5738. }); // multiDragElements will already be sorted if folding
  5739. var newIndex;
  5740. if (folding && multiDragElement !== dragEl$1) {
  5741. newIndex = -1;
  5742. } else if (folding) {
  5743. newIndex = index(multiDragElement, ':not(.' + _this.options.selectedClass + ')');
  5744. } else {
  5745. newIndex = index(multiDragElement);
  5746. }
  5747. newIndicies.push({
  5748. multiDragElement: multiDragElement,
  5749. index: newIndex
  5750. });
  5751. });
  5752. return {
  5753. items: _toConsumableArray(multiDragElements),
  5754. clones: [].concat(multiDragClones),
  5755. oldIndicies: oldIndicies,
  5756. newIndicies: newIndicies
  5757. };
  5758. },
  5759. optionListeners: {
  5760. multiDragKey: function multiDragKey(key) {
  5761. key = key.toLowerCase();
  5762. if (key === 'ctrl') {
  5763. key = 'Control';
  5764. } else if (key.length > 1) {
  5765. key = key.charAt(0).toUpperCase() + key.substr(1);
  5766. }
  5767. return key;
  5768. }
  5769. }
  5770. });
  5771. }
  5772. function insertMultiDragElements(clonesInserted, rootEl) {
  5773. multiDragElements.forEach(function (multiDragElement) {
  5774. var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)];
  5775. if (target) {
  5776. rootEl.insertBefore(multiDragElement, target);
  5777. } else {
  5778. rootEl.appendChild(multiDragElement);
  5779. }
  5780. });
  5781. }
  5782. /**
  5783. * Insert multi-drag clones
  5784. * @param {[Boolean]} elementsInserted Whether the multi-drag elements are inserted
  5785. * @param {HTMLElement} rootEl
  5786. */
  5787. function insertMultiDragClones(elementsInserted, rootEl) {
  5788. multiDragClones.forEach(function (clone) {
  5789. var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)];
  5790. if (target) {
  5791. rootEl.insertBefore(clone, target);
  5792. } else {
  5793. rootEl.appendChild(clone);
  5794. }
  5795. });
  5796. }
  5797. function removeMultiDragElements() {
  5798. multiDragElements.forEach(function (multiDragElement) {
  5799. if (multiDragElement === dragEl$1) return;
  5800. multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement);
  5801. });
  5802. }
  5803. Sortable.mount(new AutoScrollPlugin());
  5804. Sortable.mount(Remove, Revert);
  5805. Sortable.mount(new SwapPlugin());
  5806. Sortable.mount(new MultiDragPlugin());
  5807. return Sortable;
  5808. }));
  5809. /******************************************************************************/
  5810. (function(window, $) {
  5811. var fave = function(window, $) {
  5812. // Private
  5813. var FormDataWasChanged = false;
  5814. function IsDebugMode() {
  5815. return window.fave_debug && window.fave_debug === true;
  5816. };
  5817. function GetModalAlertTmpl(title, message, error) {
  5818. return '<div class="alert alert-' + (!error?'success':'danger') + ' alert-dismissible fade show" role="alert"><strong>' + title + '</strong> ' + message + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
  5819. };
  5820. function ShowSystemMsg(title, message, error) {
  5821. var modal_alert_place = $('.modal.show .sys-messages');
  5822. if(!modal_alert_place.length) {
  5823. modal_alert_place = $('form.alert-here .sys-messages');
  5824. }
  5825. if(modal_alert_place.length) {
  5826. modal_alert_place.html(GetModalAlertTmpl(title, message, error));
  5827. } else {
  5828. ShowSystemMsgModal(title, message, error);
  5829. }
  5830. };
  5831. function ShowSystemMsgModal(title, message, error) {
  5832. $('#sys-modal-system-message-placeholder').html('');
  5833. var html = '<div class="modal fade" id="sys-modal-system-message" tabindex="-1" role="dialog" aria-labelledby="sysModalSystemMessageLabel" aria-hidden="true"> \
  5834. <div class="modal-dialog modal-dialog-centered" role="document"> \
  5835. <div class="modal-content"> \
  5836. <div class="modal-header"> \
  5837. <h5 class="modal-title" id="sysModalSystemMessageLabel">' + title + '</h5> \
  5838. <button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
  5839. <span aria-hidden="true">&times;</span> \
  5840. </button> \
  5841. </div> \
  5842. <div class="modal-body text-left">' + message + '</div> \
  5843. <div class="modal-footer"> \
  5844. <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> \
  5845. </div> \
  5846. </div> \
  5847. </div> \
  5848. </div>';
  5849. $('#sys-modal-system-message-placeholder').html(html);
  5850. $('#sys-modal-system-message').modal({
  5851. backdrop: 'static',
  5852. keyboard: true,
  5853. show: false,
  5854. });
  5855. $('#sys-modal-system-message').on('hidden.bs.modal', function(e) {
  5856. $('#sys-modal-system-message-placeholder').html('');
  5857. });
  5858. $('#sys-modal-system-message').modal('show');
  5859. };
  5860. function AjaxEval(data) {
  5861. try {
  5862. eval(data);
  5863. } catch(e) {
  5864. if(e instanceof SyntaxError) {
  5865. console.log(data);
  5866. console.log('Error: JavaScript code eval error', e.message);
  5867. }
  5868. }
  5869. };
  5870. function AjaxDone(data) {
  5871. AjaxEval(data);
  5872. };
  5873. function AjaxFail(data, status, error) {
  5874. if(status.toLowerCase() === "error" && error.toLowerCase() === "not found") {
  5875. AjaxEval(data);
  5876. } else {
  5877. console.log('Error: data sending error, page will be reloaded', data, status, error);
  5878. setTimeout(function() {
  5879. window.location.reload(false);
  5880. }, 1000);
  5881. }
  5882. };
  5883. function FormToAjax(form) {
  5884. form.submit(function(e) {
  5885. if(form.hasClass('loading')) {
  5886. e.preventDefault();
  5887. return;
  5888. }
  5889. // Block send button
  5890. form.addClass('loading').addClass('alert-here');
  5891. var button = form.find('button[type=submit]');
  5892. button.addClass('progress-bar-striped')
  5893. .addClass('progress-bar-animated');
  5894. // Another button
  5895. if(button.attr('data-target') != '') {
  5896. $('#' + button.attr('data-target')).addClass('progress-bar-striped')
  5897. .addClass('progress-bar-animated');
  5898. }
  5899. // Clear form messages
  5900. form.find('.sys-messages').html('');
  5901. $.ajax({
  5902. type: "POST",
  5903. url: form.attr('action'),
  5904. data: form.serialize()
  5905. }).done(function(data) {
  5906. FormDataWasChanged = false;
  5907. if(IsDebugMode()) console.log('done', data);
  5908. AjaxDone(data);
  5909. }).fail(function(xhr, status, error) {
  5910. if(IsDebugMode()) console.log('fail', xhr, status, error);
  5911. AjaxFail(xhr.responseText, status, error);
  5912. }).always(function() {
  5913. // Add delay for one second
  5914. setTimeout(function() {
  5915. form.removeClass('loading').removeClass('alert-here');
  5916. button.removeClass('progress-bar-striped')
  5917. .removeClass('progress-bar-animated');
  5918. // Another button
  5919. if(button.attr('data-target') != '') {
  5920. $('#' + button.attr('data-target'))
  5921. .removeClass('progress-bar-striped')
  5922. .removeClass('progress-bar-animated');
  5923. }
  5924. }, 100);
  5925. });
  5926. // Prevent submit action
  5927. e.preventDefault();
  5928. });
  5929. // Bind to another button
  5930. var button = form.find('button[type=submit]');
  5931. if(button.attr('data-target') != '') {
  5932. $('#' + button.attr('data-target')).click(function() {
  5933. button.click();
  5934. });
  5935. }
  5936. // Mark body if any data in form was changed
  5937. if(form.hasClass('prev-data-lost')) {
  5938. form.find('input, textarea, select').on('input', function() {
  5939. if(!FormDataWasChanged) {
  5940. if(!$(this).hasClass('ignore-lost-data')) {
  5941. FormDataWasChanged = true;
  5942. }
  5943. }
  5944. });
  5945. }
  5946. };
  5947. function PreventDataLost() {
  5948. if(!FormDataWasChanged) {
  5949. FormDataWasChanged = true;
  5950. }
  5951. };
  5952. function FormDataIsChanged() {
  5953. return FormDataWasChanged;
  5954. }
  5955. function HtmlDecode(value) {
  5956. var doc = new DOMParser().parseFromString(value, "text/html");
  5957. return doc.documentElement.textContent;
  5958. };
  5959. function HtmlFixEditorHtml(value) {
  5960. newValue = value;
  5961. newValue = newValue.replace(/&nbsp;/gi, '');
  5962. return newValue;
  5963. };
  5964. function AllFormsToAjax() {
  5965. $('form').each(function() {
  5966. FormToAjax($(this));
  5967. });
  5968. };
  5969. function BindWindowBeforeUnload() {
  5970. // Prevent page reload if data was changed
  5971. $(window).bind('beforeunload', function(){
  5972. if(FormDataWasChanged) {
  5973. return 'Some data was changed and not saved. Are you sure want to leave page?';
  5974. }
  5975. });
  5976. };
  5977. function MakeTextAreasAutoSized() {
  5978. autosize($('textarea.autosize'));
  5979. };
  5980. function MakeTextAreasWysiwyg() {
  5981. $('textarea.wysiwyg').each(function() {
  5982. var area = $(this)[0];
  5983. var area_id = area.id;
  5984. var area_name = area.name;
  5985. var area_html = area.innerHTML;
  5986. // Wrap editro by additional DIV and remove target textarea
  5987. $(area).wrap('<div id="' + area_id + '_wysiwyg" class="form-control wysiwyg" style="height:auto;padding:0px"></div>').remove();
  5988. var wysiwyg = document.getElementById(area_id + '_wysiwyg');
  5989. wysiwyg.id = area_id;
  5990. // Create and init editor
  5991. var editor = window.pell.init({
  5992. element: wysiwyg,
  5993. onChange: function(html) {
  5994. area.innerHTML = HtmlFixEditorHtml(html);
  5995. $(area).val(HtmlFixEditorHtml(html));
  5996. if(!FormDataWasChanged) {
  5997. FormDataWasChanged = true;
  5998. }
  5999. },
  6000. defaultParagraphSeparator: 'p',
  6001. styleWithCSS: false,
  6002. actions: [
  6003. 'paragraph',
  6004. 'heading1',
  6005. 'heading2',
  6006. 'bold',
  6007. 'italic',
  6008. 'underline',
  6009. 'strikethrough',
  6010. 'ulist',
  6011. 'olist',
  6012. 'link',
  6013. {
  6014. name: 'htmlcode',
  6015. icon: 'HTML',
  6016. title: 'HTML Source',
  6017. result: function(edt, ctn, btn) {
  6018. var jedt = $(edt);
  6019. var jctn = $(ctn);
  6020. var jbtn = $(btn);
  6021. if(!jbtn.hasClass('pell-button-html-pressed')) {
  6022. jbtn.addClass('pell-button-html-pressed');
  6023. jedt.addClass('pell-html-mode');
  6024. jedt.find('.pell-actionbar .pell-button').prop('disabled', true);
  6025. jbtn.prop('disabled', false);
  6026. setTimeout(function() {
  6027. jedt.find('textarea.form-control').focus();
  6028. }, 0);
  6029. } else {
  6030. jbtn.removeClass('pell-button-html-pressed');
  6031. jedt.removeClass('pell-html-mode');
  6032. jedt.find('.pell-actionbar .pell-button').prop('disabled', false);
  6033. var srcValue = jedt.find('textarea.form-control').val();
  6034. ctn.innerHTML = HtmlFixEditorHtml(srcValue);
  6035. $(ctn).val(HtmlFixEditorHtml(srcValue));
  6036. setTimeout(function() {
  6037. jctn.focus();
  6038. }, 0);
  6039. }
  6040. },
  6041. },
  6042. ],
  6043. classes: {
  6044. actionbar: 'pell-actionbar',
  6045. button: 'pell-button',
  6046. content: 'pell-content',
  6047. selected: 'pell-button-selected'
  6048. }
  6049. });
  6050. editor.onfocusin = function() {
  6051. $(wysiwyg).addClass('focused');
  6052. };
  6053. editor.onfocusout = function() {
  6054. $(wysiwyg).find('.pell-actionbar button.pell-button-selected').removeClass('pell-button-selected');
  6055. $(wysiwyg).removeClass('focused');
  6056. };
  6057. // Re-add textarea
  6058. $(wysiwyg).append('<textarea class="form-control" id="' + area_id + '_wysiwyg' + '" name="' + area_name + '" style="display:none"></textarea>');
  6059. area = document.getElementById(area_id + '_wysiwyg');
  6060. // Prevent data lost if HTML was changed
  6061. $(area).on('input', function() {
  6062. if(!FormDataWasChanged) {
  6063. FormDataWasChanged = true;
  6064. }
  6065. });
  6066. // Copy HTML to textarea and editor
  6067. area.innerHTML = HtmlFixEditorHtml(HtmlDecode(area_html));
  6068. $(area).val(HtmlFixEditorHtml(HtmlDecode(area_html)));
  6069. editor.content.innerHTML = HtmlFixEditorHtml(HtmlDecode(area_html));
  6070. });
  6071. };
  6072. function MakeTextAreasTmplEditor() {
  6073. var IgnoreDataLost = true;
  6074. $('textarea.tmpl-editor').each(function() {
  6075. var targetTextArea = $(this)[0];
  6076. var targetFileExt = $(this).data('emode');
  6077. var targetEditorMode = 'text/html';
  6078. if(targetFileExt == 'js') {
  6079. targetEditorMode = 'javascript';
  6080. } else if(targetFileExt == 'css') {
  6081. targetEditorMode = 'css';
  6082. }
  6083. CodeMirror.fromTextArea(targetTextArea, {
  6084. lineNumbers: true,
  6085. lineWrapping: true,
  6086. viewportMargin: Infinity,
  6087. indentWithTabs: true,
  6088. indentUnit: 4,
  6089. tabSize: 4,
  6090. mode: targetEditorMode,
  6091. }).on('change', function(editor){
  6092. targetTextArea.value = editor.getValue();
  6093. if(!IgnoreDataLost) {
  6094. if(!FormDataWasChanged) {
  6095. FormDataWasChanged = true;
  6096. }
  6097. }
  6098. });
  6099. });
  6100. IgnoreDataLost = false;
  6101. };
  6102. function MakeTextAreasNotReactOnTab() {
  6103. $('textarea.use-tab-key').each(function() {
  6104. $(this).keydown(function(e) {
  6105. if(e.keyCode === 9) {
  6106. var start = this.selectionStart;
  6107. var end = this.selectionEnd;
  6108. var $this = $(this);
  6109. var value = $this.val();
  6110. $this.val(value.substring(0, start) + "\t" + value.substring(end));
  6111. this.selectionStart = this.selectionEnd = start + 1;
  6112. e.preventDefault();
  6113. if(!FormDataWasChanged) {
  6114. FormDataWasChanged = true;
  6115. }
  6116. }
  6117. });
  6118. });
  6119. };
  6120. function Initialize() {
  6121. // Check if jQuery was loaded
  6122. if(typeof $ == 'function') {
  6123. AllFormsToAjax();
  6124. BindWindowBeforeUnload();
  6125. MakeTextAreasAutoSized();
  6126. MakeTextAreasWysiwyg();
  6127. MakeTextAreasTmplEditor();
  6128. MakeTextAreasNotReactOnTab();
  6129. } else {
  6130. console.log('Error: jQuery is not loaded!');
  6131. }
  6132. };
  6133. // Initialize
  6134. if(window.addEventListener) {
  6135. // W3C standard
  6136. window.addEventListener('load', Initialize, false);
  6137. } else if(window.attachEvent) {
  6138. // Microsoft
  6139. window.attachEvent('onload', Initialize);
  6140. };
  6141. // Public
  6142. return {
  6143. ShowMsgSuccess: function(title, message) {
  6144. ShowSystemMsg(title, message, false);
  6145. },
  6146. ShowMsgError: function(title, message) {
  6147. ShowSystemMsg(title, message, true);
  6148. },
  6149. FormDataWasChanged: function() {
  6150. PreventDataLost();
  6151. },
  6152. ModalUserProfile: function() {
  6153. var html = '<div class="modal fade" id="sys-modal-user-settings" tabindex="-1" role="dialog" aria-labelledby="sysModalUserSettingsLabel" aria-hidden="true"> \
  6154. <div class="modal-dialog modal-dialog-centered" role="document"> \
  6155. <div class="modal-content"> \
  6156. <form class="form-user-settings" action="/cp/" method="post" autocomplete="off"> \
  6157. <input type="hidden" name="action" value="index-user-update-profile"> \
  6158. <div class="modal-header"> \
  6159. <h5 class="modal-title" id="sysModalUserSettingsLabel">My profile</h5> \
  6160. <button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
  6161. <span aria-hidden="true">&times;</span> \
  6162. </button> \
  6163. </div> \
  6164. <div class="modal-body text-left"> \
  6165. <div class="form-group"> \
  6166. <label for="first_name">First name</label> \
  6167. <input type="text" class="form-control" id="first_name" name="first_name" value="' + window.CurrentUserProfileData.first_name + '" placeholder="User first name" autocomplete="off"> \
  6168. </div> \
  6169. <div class="form-group"> \
  6170. <label for="last_name">Last name</label> \
  6171. <input type="text" class="form-control" id="last_name" name="last_name" value="' + window.CurrentUserProfileData.last_name + '" placeholder="User last name" autocomplete="off"> \
  6172. </div> \
  6173. <div class="form-group"> \
  6174. <label for="email">Email</label> \
  6175. <input type="email" class="form-control" id="email" name="email" value="' + window.CurrentUserProfileData.email + '" placeholder="User email" autocomplete="off" required> \
  6176. </div> \
  6177. <div class="form-group"> \
  6178. <label for="password">New password</label> \
  6179. <input type="password" class="form-control" id="password" aria-describedby="passwordHelp" name="password" value="" placeholder="User new password" autocomplete="off"> \
  6180. <small id="passwordHelp" class="form-text text-muted">Leave this field empty if you don\'t want change your password</small> \
  6181. </div> \
  6182. <div class="sys-messages"></div> \
  6183. </div> \
  6184. <div class="modal-footer"> \
  6185. <button type="submit" class="btn btn-primary">Save</button> \
  6186. <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> \
  6187. </div> \
  6188. </form> \
  6189. </div> \
  6190. </div> \
  6191. </div>';
  6192. $('#sys-modal-user-settings-placeholder').html(html);
  6193. $("#sys-modal-user-settings").modal({
  6194. backdrop: 'static',
  6195. keyboard: false,
  6196. show: false,
  6197. });
  6198. $('#sys-modal-user-settings').on('hidden.bs.modal', function(e) {
  6199. $('#sys-modal-user-settings-placeholder').html('');
  6200. });
  6201. FormToAjax($('#sys-modal-user-settings form'));
  6202. $("#sys-modal-user-settings").modal('show');
  6203. },
  6204. ShopProductsAdd: function() {
  6205. var selText = $('#lbl_attributes option:selected').text();
  6206. var selValue = $('#lbl_attributes').val();
  6207. if(selValue == '0') { return; }
  6208. $('#lbl_attributes')[0].selectedIndex = 0;
  6209. $('#lbl_attributes').selectpicker('refresh');
  6210. if($('#prod_attr_' + selValue).length > 0) { return; }
  6211. $('#list').append('<div class="form-group" id="prod_attr_' + selValue + '"><div><b>' + selText + '</b></div><div class="position-relative"><select class="form-control" name="value.' + selValue + '" autocomplete="off" required disabled><option value="0">Loading values...</option></select><button type="button" class="btn btn-danger btn-dynamic-remove" onclick="fave.ShopProductsRemove(this);" disabled>&times;</button></div></div>');
  6212. PreventDataLost();
  6213. $.ajax({
  6214. type: 'POST',
  6215. url: '/cp/',
  6216. data: {
  6217. action: 'shop-get-attribute-values',
  6218. id: selValue
  6219. }
  6220. }).done(function(data) {
  6221. try {
  6222. eval(data);
  6223. } catch(e) {
  6224. if(e instanceof SyntaxError) {
  6225. console.log(data);
  6226. console.log('Error: JavaScript code eval error', e.message);
  6227. }
  6228. }
  6229. }).fail(function(xhr, status, error) {
  6230. $('#prod_attr_' + selValue).remove();
  6231. try {
  6232. eval(xhr.responseText);
  6233. } catch(e) {
  6234. if(e instanceof SyntaxError) {
  6235. console.log(xhr.responseText);
  6236. console.log('Error: JavaScript code eval error', e.message);
  6237. }
  6238. }
  6239. });
  6240. },
  6241. ShopProductsRemove: function(button) {
  6242. $(button).parent().parent().remove();
  6243. PreventDataLost();
  6244. },
  6245. ShopAttributesAdd: function() {
  6246. $('#list').append('<div class="form-group position-relative"><input class="form-control" type="text" name="value.0" value="" placeholder="" autocomplete="off" required><button type="button" class="btn btn-danger btn-dynamic-remove" onclick="fave.ShopAttributesRemove(this);">&times;</button></div>');
  6247. PreventDataLost();
  6248. setTimeout(function() {
  6249. $('#list input').last().focus();
  6250. }, 100);
  6251. },
  6252. ShopAttributesRemove: function(button) {
  6253. $(button).parent().remove();
  6254. PreventDataLost();
  6255. },
  6256. ShopProductsUploadImage: function(action_name, product_id, input_id) {
  6257. var file_el = $('#' + input_id)[0];
  6258. if(!file_el.files) return;
  6259. if(file_el.files.length <= 0) return;
  6260. $('#img-upload-block input').prop('disabled', true);
  6261. $('#upload-msg').css('display', 'block');
  6262. var fd = new FormData();
  6263. fd.append('action', action_name);
  6264. fd.append('id', product_id);
  6265. fd.append('count', file_el.files.length);
  6266. for(var i = 0; i < file_el.files.length; i++) {
  6267. fd.append('file_' + i, file_el.files[i]);
  6268. }
  6269. $.ajax({
  6270. url: '/cp/',
  6271. method: 'POST',
  6272. type: 'POST',
  6273. data: fd,
  6274. contentType: false,
  6275. processData: false
  6276. }).done(function(data) {
  6277. try {
  6278. eval(data);
  6279. } catch(e) {
  6280. if(e instanceof SyntaxError) {
  6281. console.log(data);
  6282. console.log('Error: JavaScript code eval error', e.message);
  6283. }
  6284. }
  6285. }).fail(function(xhr, status, error) {
  6286. try {
  6287. eval(xhr.responseText);
  6288. } catch(e) {
  6289. if(e instanceof SyntaxError) {
  6290. console.log(xhr.responseText);
  6291. console.log('Error: JavaScript code eval error', e.message);
  6292. }
  6293. }
  6294. }).always(function() {
  6295. file_el.value = '';
  6296. $('#img-upload-block input').prop('disabled', false);
  6297. $('#upload-msg').css('display', 'none');
  6298. });
  6299. },
  6300. ShopProductsDeleteImage: function(button, product_id, filename) {
  6301. if($(button).hasClass('in-progress')) return;
  6302. $(button).addClass('in-progress');
  6303. $.ajax({
  6304. type: "POST",
  6305. url: '/cp/',
  6306. data: {
  6307. action: 'shop-upload-delete',
  6308. id: product_id,
  6309. file: filename,
  6310. }
  6311. }).done(function(data) {
  6312. if(IsDebugMode()) console.log('done', data);
  6313. AjaxDone(data);
  6314. }).fail(function(xhr, status, error) {
  6315. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6316. AjaxFail(xhr.responseText, status, error);
  6317. });
  6318. },
  6319. ShopProductsDuplicateBase: function(button, product_id, attach) {
  6320. if($(button).hasClass('in-progress')) return;
  6321. if(FormDataIsChanged()) {
  6322. fave.ShowMsgError('Warning!', 'Something was changed, save changes before duplicate product', true);
  6323. return;
  6324. }
  6325. $(button).addClass('in-progress');
  6326. $.ajax({
  6327. type: "POST",
  6328. url: '/cp/',
  6329. data: {
  6330. action: 'shop-duplicate',
  6331. id: product_id,
  6332. attach: attach,
  6333. }
  6334. }).done(function(data) {
  6335. try {
  6336. eval(data);
  6337. } catch(e) {
  6338. if(e instanceof SyntaxError) {
  6339. console.log(data);
  6340. console.log('Error: JavaScript code eval error', e.message);
  6341. }
  6342. }
  6343. }).fail(function(xhr, status, error) {
  6344. try {
  6345. eval(xhr.responseText);
  6346. } catch(e) {
  6347. if(e instanceof SyntaxError) {
  6348. console.log(xhr.responseText);
  6349. console.log('Error: JavaScript code eval error', e.message);
  6350. }
  6351. }
  6352. }).always(function() {
  6353. $(button).removeClass('in-progress');
  6354. });
  6355. },
  6356. ShopProductsDuplicate: function(button, product_id) {
  6357. fave.ShopProductsDuplicateBase(button, product_id, 0);
  6358. },
  6359. ShopProductsDuplicateWithAttach: function(button, product_id) {
  6360. fave.ShopProductsDuplicateBase(button, product_id, 1);
  6361. },
  6362. ShopProductsRetryImage: function(img, id) {
  6363. var target = $('#' + id);
  6364. var src = target.attr('src');
  6365. target.attr('src', '/assets/cp/img-load.gif');
  6366. setTimeout(function() {
  6367. target.attr('src', src);
  6368. }, 1000);
  6369. },
  6370. ActionLogout: function(message) {
  6371. if(confirm(message)) {
  6372. $.ajax({
  6373. type: "POST",
  6374. url: '/cp/',
  6375. data: {
  6376. action: 'index-user-logout',
  6377. }
  6378. }).done(function(data) {
  6379. if(IsDebugMode()) console.log('done', data);
  6380. AjaxDone(data);
  6381. }).fail(function(xhr, status, error) {
  6382. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6383. AjaxFail(xhr.responseText, status, error);
  6384. });
  6385. }
  6386. },
  6387. ActionDataTableDelete: function(object, action, id, message) {
  6388. if(confirm(message)) {
  6389. $.ajax({
  6390. type: "POST",
  6391. url: '/cp/',
  6392. data: {
  6393. action: action,
  6394. id: id,
  6395. }
  6396. }).done(function(data) {
  6397. if(IsDebugMode()) console.log('done', data);
  6398. AjaxDone(data);
  6399. }).fail(function(xhr, status, error) {
  6400. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6401. AjaxFail(xhr.responseText, status, error);
  6402. });
  6403. }
  6404. },
  6405. ActionThemeFile: function(action_name, file_name, message) {
  6406. if(confirm(message)) {
  6407. $.ajax({
  6408. type: "POST",
  6409. url: '/cp/',
  6410. data: {
  6411. action: action_name,
  6412. file: file_name,
  6413. }
  6414. }).done(function(data) {
  6415. if(IsDebugMode()) console.log('done', data);
  6416. AjaxDone(data);
  6417. }).fail(function(xhr, status, error) {
  6418. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6419. AjaxFail(xhr.responseText, status, error);
  6420. });
  6421. }
  6422. return false;
  6423. },
  6424. ShopProductsImageReorder: function(action, orderData) {
  6425. $.ajax({
  6426. type: "POST",
  6427. url: '/cp/',
  6428. data: {
  6429. action: action,
  6430. data: JSON.stringify(orderData),
  6431. },
  6432. }).done(function(data) {
  6433. if(IsDebugMode()) console.log('done', data);
  6434. AjaxDone(data);
  6435. }).fail(function(xhr, status, error) {
  6436. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6437. AjaxFail(xhr.responseText, status, error);
  6438. });
  6439. },
  6440. ShopAttachProduct: function(product_id) {
  6441. var html = '<div class="modal fade" id="sys-modal-shop-product-attach" tabindex="-1" role="dialog" aria-labelledby="sysModalShopProductLabel" aria-hidden="true"> \
  6442. <div class="modal-dialog modal-dialog-centered" role="document"> \
  6443. <div class="modal-content"> \
  6444. <div class="modal-header"> \
  6445. <h5 class="modal-title" id="sysModalShopProductLabel">Attach product</h5> \
  6446. <button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
  6447. <span aria-hidden="true">&times;</span> \
  6448. </button> \
  6449. </div> \
  6450. <div class="modal-body text-left"> \
  6451. <div class="form-group"> \
  6452. <input type="text" class="form-control" name="product-name" value="" placeholder="Type product name here..." readonly autocomplete="off"> \
  6453. </div> \
  6454. <div class="form-group" style="margin-bottom:0px;"> \
  6455. <div class="products-list"></div> \
  6456. </div> \
  6457. </div> \
  6458. <div class="modal-footer"> \
  6459. <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> \
  6460. </div> \
  6461. </div> \
  6462. </div> \
  6463. </div>';
  6464. $('#sys-modal-shop-product-attach-placeholder').html(html);
  6465. $("#sys-modal-shop-product-attach").modal({
  6466. backdrop: 'static',
  6467. keyboard: true,
  6468. show: false,
  6469. });
  6470. $('#sys-modal-shop-product-attach').on('hidden.bs.modal', function(e) {
  6471. $('#sys-modal-shop-product-attach-placeholder').html('');
  6472. });
  6473. $("#sys-modal-shop-product-attach").modal('show');
  6474. setTimeout(function() {
  6475. var SearchInput = $('#sys-modal-shop-product-attach input[name="product-name"]');
  6476. SearchInput.keyup(function() {
  6477. if(true || this.value != '') {
  6478. $.ajax({
  6479. type: "POST",
  6480. url: '/cp/',
  6481. data: {
  6482. action: 'shop-attach-product-search',
  6483. words: this.value,
  6484. id: product_id,
  6485. }
  6486. }).done(function(data) {
  6487. if($('#sys-modal-shop-product-attach').length > 0) {
  6488. if(IsDebugMode()) console.log('done', data);
  6489. AjaxDone(data);
  6490. }
  6491. }).fail(function(xhr, status, error) {
  6492. if(false) {
  6493. if($('#sys-modal-shop-product-attach').length > 0) {
  6494. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6495. AjaxFail(xhr.responseText, status, error);
  6496. }
  6497. }
  6498. });
  6499. }
  6500. });
  6501. SearchInput.attr("readonly", false);
  6502. SearchInput.keyup();
  6503. SearchInput.focus();
  6504. }, 500);
  6505. },
  6506. ShopAttachProductTo: function(parent_id, product_id) {
  6507. $.ajax({
  6508. type: "POST",
  6509. url: '/cp/',
  6510. data: {
  6511. action: 'shop-attach-product-to',
  6512. parent_id: parent_id,
  6513. product_id: product_id,
  6514. }
  6515. }).done(function(data) {
  6516. if(IsDebugMode()) console.log('done', data);
  6517. AjaxDone(data);
  6518. }).fail(function(xhr, status, error) {
  6519. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6520. AjaxFail(xhr.responseText, status, error);
  6521. });
  6522. },
  6523. ShopSetOrderStatus: function(object, id, status, message) {
  6524. if(confirm(message)) {
  6525. $.ajax({
  6526. type: "POST",
  6527. url: '/cp/',
  6528. data: {
  6529. action: 'shop-order-set-status',
  6530. id: id,
  6531. status: status,
  6532. }
  6533. }).done(function(data) {
  6534. if(IsDebugMode()) console.log('done', data);
  6535. AjaxDone(data);
  6536. }).fail(function(xhr, status, error) {
  6537. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6538. AjaxFail(xhr.responseText, status, error);
  6539. });
  6540. }
  6541. },
  6542. FilesManagerDialog: function() {
  6543. var html = '<div class="modal fade" id="sys-modal-files-manager" tabindex="-1" role="dialog" aria-labelledby="sysModalFilesManagerLabel" aria-hidden="true"> \
  6544. <div class="modal-dialog modal-dialog-centered" role="document"> \
  6545. <div class="modal-content"> \
  6546. <input type="hidden" name="path" value="/"> \
  6547. <div class="modal-header"> \
  6548. <h5 class="modal-title" id="sysModalFilesManagerLabel">Files manager</h5> \
  6549. <button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
  6550. <span aria-hidden="true">&times;</span> \
  6551. </button> \
  6552. </div> \
  6553. <div class="modal-body text-left"> \
  6554. <div class="dialog-path alert alert-secondary"><span class="text-dotted">/</span></div> \
  6555. <div class="dialog-data"></div> \
  6556. </div> \
  6557. <div class="modal-footer"> \
  6558. <button type="button" class="btn btn-success upload" disabled>Uploading...</button> \
  6559. <input class="form-control" type="file" id="fmfiles" name="fmfiles" onchange="fave.FilesManagerUploadFile();" style="font-size:12px;background-color:#28a745;border-color:#28a745;color:#fff;cursor:pointer;" multiple=""> \
  6560. <button type="button" class="btn btn-primary folder" onclick="fave.FilesManagerNewFolderClick();" disabled>New folder</button> \
  6561. <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> \
  6562. </div> \
  6563. </div> \
  6564. </div> \
  6565. </div>';
  6566. $('#sys-modal-files-manager-placeholder').html(html);
  6567. $("#sys-modal-files-manager").modal({
  6568. backdrop: 'static',
  6569. keyboard: true,
  6570. show: false,
  6571. });
  6572. $('#sys-modal-files-manager').on('hidden.bs.modal', function(e) {
  6573. $('#sys-modal-files-manager-placeholder').html('');
  6574. });
  6575. $("#sys-modal-files-manager").modal('show');
  6576. setTimeout(function() {
  6577. fave.FilesManagerLoadData('/');
  6578. }, 500);
  6579. },
  6580. FilesManagerSetPath: function(path) {
  6581. $('#sys-modal-files-manager input[name=path]').val(path);
  6582. $('#sys-modal-files-manager .dialog-path span').html(path);
  6583. },
  6584. FilesManagerGetPath: function() {
  6585. return $('#sys-modal-files-manager input[name=path]').val();
  6586. },
  6587. FilesManagerRemoveFolder: function(filename, msg) {
  6588. if(!confirm(msg)) {
  6589. return;
  6590. }
  6591. fave.FilesManagerEnableDisableButtons(true);
  6592. $.ajax({
  6593. type: "POST",
  6594. url: '/cp/',
  6595. data: {
  6596. action: 'files-remove-folder',
  6597. file: filename,
  6598. }
  6599. }).done(function(data) {
  6600. if($('#sys-modal-files-manager').length > 0) {
  6601. if(IsDebugMode()) console.log('done', data);
  6602. AjaxDone(data);
  6603. }
  6604. }).fail(function(xhr, status, error) {
  6605. if($('#sys-modal-files-manager').length > 0) {
  6606. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6607. AjaxFail(xhr.responseText, status, error);
  6608. }
  6609. }).always(function() {
  6610. fave.FilesManagerEnableDisableButtons(false);
  6611. });
  6612. },
  6613. FilesManagerRemoveFile: function(filename, msg) {
  6614. if(!confirm(msg)) {
  6615. return;
  6616. }
  6617. fave.FilesManagerEnableDisableButtons(true);
  6618. $.ajax({
  6619. type: "POST",
  6620. url: '/cp/',
  6621. data: {
  6622. action: 'files-remove-file',
  6623. file: filename,
  6624. }
  6625. }).done(function(data) {
  6626. if($('#sys-modal-files-manager').length > 0) {
  6627. if(IsDebugMode()) console.log('done', data);
  6628. AjaxDone(data);
  6629. }
  6630. }).fail(function(xhr, status, error) {
  6631. if($('#sys-modal-files-manager').length > 0) {
  6632. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6633. AjaxFail(xhr.responseText, status, error);
  6634. }
  6635. }).always(function() {
  6636. fave.FilesManagerEnableDisableButtons(false);
  6637. });
  6638. },
  6639. FilesManagerLoadData: function(path) {
  6640. fave.FilesManagerEnableDisableButtons(true);
  6641. $('#sys-modal-files-manager .dialog-data').html('<div class="fm-loading"></div>');
  6642. $.ajax({
  6643. type: "POST",
  6644. url: '/cp/',
  6645. data: {
  6646. action: 'files-list',
  6647. path: path,
  6648. }
  6649. }).done(function(data) {
  6650. if($('#sys-modal-files-manager').length > 0) {
  6651. if(IsDebugMode()) console.log('done', data);
  6652. AjaxDone(data);
  6653. }
  6654. }).fail(function(xhr, status, error) {
  6655. if($('#sys-modal-files-manager').length > 0) {
  6656. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6657. AjaxFail(xhr.responseText, status, error);
  6658. }
  6659. });
  6660. },
  6661. FilesManagerLoadDataUp: function(path) {
  6662. newPath = path.replace(/\/$/i, '');
  6663. newPath = newPath.replace(/[^\/]+$/i, '');
  6664. fave.FilesManagerLoadData(newPath);
  6665. },
  6666. FilesManagerEnableDisableButtons: function(disabled) {
  6667. $('#sys-modal-files-manager #fmfiles').prop('disabled', disabled);
  6668. $('#sys-modal-files-manager button.folder').prop('disabled', disabled);
  6669. },
  6670. FilesManagerUploadFile: function() {
  6671. var file_el = $('#fmfiles')[0];
  6672. if(!file_el.files) return;
  6673. if(file_el.files.length <= 0) return;
  6674. fave.FilesManagerEnableDisableButtons(true);
  6675. $('#sys-modal-files-manager').addClass('uploading');
  6676. var fd = new FormData();
  6677. fd.append('action', 'files-upload');
  6678. fd.append('count', file_el.files.length);
  6679. fd.append('path', fave.FilesManagerGetPath());
  6680. for(var i = 0; i < file_el.files.length; i++) {
  6681. fd.append('file_' + i, file_el.files[i]);
  6682. }
  6683. $.ajax({
  6684. url: '/cp/',
  6685. method: 'POST',
  6686. type: 'POST',
  6687. data: fd,
  6688. contentType: false,
  6689. processData: false
  6690. }).done(function(data) {
  6691. if($('#sys-modal-files-manager').length > 0) {
  6692. if(IsDebugMode()) console.log('done', data);
  6693. AjaxDone(data);
  6694. }
  6695. }).fail(function(xhr, status, error) {
  6696. if($('#sys-modal-files-manager').length > 0) {
  6697. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6698. AjaxFail(xhr.responseText, status, error);
  6699. }
  6700. }).always(function() {
  6701. file_el.value = '';
  6702. $('#sys-modal-files-manager').removeClass('uploading');
  6703. fave.FilesManagerEnableDisableButtons(false);
  6704. });
  6705. },
  6706. FilesManagerNewFolderClick: function() {
  6707. var folderName = prompt('Please enter new folder name', '');
  6708. if(folderName != null) {
  6709. path = fave.FilesManagerGetPath();
  6710. fave.FilesManagerEnableDisableButtons(true);
  6711. $.ajax({
  6712. type: "POST",
  6713. url: '/cp/',
  6714. data: {
  6715. action: 'files-mkdir',
  6716. path: path,
  6717. name: folderName,
  6718. }
  6719. }).done(function(data) {
  6720. if($('#sys-modal-files-manager').length > 0) {
  6721. if(IsDebugMode()) console.log('done', data);
  6722. AjaxDone(data);
  6723. }
  6724. }).fail(function(xhr, status, error) {
  6725. if($('#sys-modal-files-manager').length > 0) {
  6726. if(IsDebugMode()) console.log('fail', xhr, status, error);
  6727. AjaxFail(xhr.responseText, status, error);
  6728. }
  6729. }).always(function() {
  6730. fave.FilesManagerEnableDisableButtons(false);
  6731. });
  6732. }
  6733. },
  6734. };
  6735. }(window, $);
  6736. // Make it public
  6737. window.fave = fave;
  6738. }(window, jQuery));