footable.js 262 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371
  1. /*
  2. * FooTable v3 - FooTable is a jQuery plugin that aims to make HTML tables on smaller devices look awesome.
  3. * @version 3.1.6
  4. * @link http://fooplugins.com
  5. * @copyright Steven Usher & Brad Vincent 2015
  6. * @license Released under the GPLv3 license.
  7. */
  8. (function($, F){
  9. // add in console we use in case it's missing
  10. window.console = window.console || { log:function(){}, error:function(){} };
  11. /**
  12. * The jQuery plugin initializer.
  13. * @function jQuery.fn.footable
  14. * @param {(object|FooTable.Defaults)} [options] - The options to initialize the plugin with.
  15. * @param {function} [ready] - A callback function to execute for each initialized plugin.
  16. * @returns {jQuery}
  17. */
  18. $.fn.footable = function (options, ready) {
  19. options = options || {};
  20. // make sure we only work with tables
  21. return this.filter('table').each(function (i, tbl) {
  22. F.init(tbl, options, ready);
  23. });
  24. };
  25. var debug_defaults = {
  26. events: []
  27. };
  28. F.__debug__ = JSON.parse(localStorage.getItem('footable_debug')) || false;
  29. F.__debug_options__ = JSON.parse(localStorage.getItem('footable_debug_options')) || debug_defaults;
  30. /**
  31. * Gets or sets the internal debug variable which enables some additional logging to the console.
  32. * When enabled this value is stored in the localStorage so it can persist across page reloads.
  33. * @param {boolean} value - Whether or not to enable additional logging.
  34. * @param {object} [options] - Any debug specific options.
  35. * @returns {(boolean|undefined)}
  36. */
  37. F.debug = function(value, options){
  38. if (!F.is.boolean(value)) return F.__debug__;
  39. F.__debug__ = value;
  40. if (F.__debug__){
  41. localStorage.setItem('footable_debug', JSON.stringify(F.__debug__));
  42. F.__debug_options__ = $.extend(true, {}, debug_defaults, options || {});
  43. if (F.is.hash(options)){
  44. localStorage.setItem('footable_debug_options', JSON.stringify(F.__debug_options__));
  45. }
  46. } else {
  47. localStorage.removeItem('footable_debug');
  48. localStorage.removeItem('footable_debug_options');
  49. }
  50. };
  51. /**
  52. * Gets the FooTable instance of the supplied table if one exists.
  53. * @param {(jQuery|jQuery.selector|HTMLTableElement)} table - The jQuery table object, selector or the HTMLTableElement to retrieve FooTable from.
  54. * @returns {(FooTable.Table|undefined)}
  55. */
  56. F.get = function(table){
  57. return $(table).first().data('__FooTable__');
  58. };
  59. /**
  60. * Initializes a new instance of FooTable on the supplied table.
  61. * @param {(jQuery|jQuery.selector|HTMLTableElement)} table - The jQuery table object, selector or the HTMLTableElement to initialize FooTable on.
  62. * @param {object} options - The options to initialize FooTable with.
  63. * @param {function} [ready] - A callback function to execute once the plugin is initialized.
  64. * @returns {FooTable.Table}
  65. */
  66. F.init = function(table, options, ready){
  67. var ft = F.get(table);
  68. if (ft instanceof F.Table) ft.destroy();
  69. return new F.Table(table, options, ready);
  70. };
  71. /**
  72. * Gets the FooTable.Row instance for the supplied element.
  73. * @param {(jQuery|jQuery.selector|HTMLTableElement)} element - A jQuery object, selector or the HTMLElement of an element to retrieve the FooTable.Row for.
  74. * @returns {FooTable.Row}
  75. */
  76. F.getRow = function(element){
  77. // to get the FooTable.Row object simply walk up the DOM, find the TR and grab the __FooTableRow__ data value
  78. var $row = $(element).closest('tr');
  79. // if this is a detail row get the previous row in the table to get the main TR element
  80. if ($row.hasClass('footable-detail-row')){
  81. $row = $row.prev();
  82. }
  83. // grab the row object
  84. return $row.data('__FooTableRow__');
  85. };
  86. // The below are external type definitions mainly used as pointers to jQuery docs for important information
  87. /**
  88. * jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API
  89. * that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
  90. * @name jQuery
  91. * @constructor
  92. * @returns {jQuery}
  93. * @see {@link http://api.jquery.com/}
  94. */
  95. /**
  96. * This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, and state) to prevent users from changing the state of the Deferred.
  97. * @typedef {object} jQuery.Promise
  98. * @see {@link http://api.jquery.com/Types/#Promise}
  99. */
  100. /**
  101. * As of jQuery 1.5, the Deferred object provides a way to register multiple callbacks into self-managed callback queues, invoke callback queues as appropriate,
  102. * and relay the success or failure state of any synchronous or asynchronous function.
  103. * @typedef {object} jQuery.Deferred
  104. * @see {@link http://api.jquery.com/Types/#Deferred}
  105. */
  106. /**
  107. * jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler. Most properties from
  108. * the original event are copied over and normalized to the new event object.
  109. * @typedef {object} jQuery.Event
  110. * @see {@link http://api.jquery.com/category/events/event-object/}
  111. */
  112. /**
  113. * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
  114. * @memberof jQuery
  115. * @function when
  116. * @param {...jQuery.Deferred} deferreds - Any number of deferred objects to wait for.
  117. * @returns {jQuery.Promise}
  118. * @see {@link http://api.jquery.com/jQuery.when/}
  119. */
  120. /**
  121. * The jQuery.fn namespace used to register plugins with jQuery.
  122. * @memberof jQuery
  123. * @namespace fn
  124. * @see {@link http://learn.jquery.com/plugins/basic-plugin-creation/}
  125. */
  126. })(
  127. jQuery,
  128. /**
  129. * The core FooTable namespace containing all the plugin code.
  130. * @namespace
  131. */
  132. FooTable = window.FooTable || {}
  133. );
  134. (function(F){
  135. var returnTrue = function(){ return true; };
  136. /**
  137. * This namespace contains commonly used array utility methods.
  138. * @namespace {object} FooTable.arr
  139. */
  140. F.arr = {};
  141. /**
  142. * Iterates over each item in the supplied array and performs the supplied function passing in the current item as the first argument.
  143. * @memberof FooTable.arr
  144. * @function each
  145. * @param {Array} array - The array to iterate
  146. * @param {function} func - The function to execute for each item. The first argument supplied to this function is the current item and the second is the current index.
  147. */
  148. F.arr.each = function (array, func) {
  149. if (!F.is.array(array) || !F.is.fn(func)) return;
  150. for (var i = 0, len = array.length; i < len; i++) {
  151. if (func(array[i], i) === false) break;
  152. }
  153. };
  154. /**
  155. * Get all items in the supplied array that optionally matches the supplied where function. If no items are found an empty array is returned.
  156. * @memberof FooTable.arr
  157. * @function get
  158. * @param {Array} array - The array to get items from.
  159. * @param {function} where - This function must return a boolean value, true includes the item in the result array.
  160. * @returns {Array}
  161. */
  162. F.arr.get = function (array, where) {
  163. var result = [];
  164. if (!F.is.array(array)) return result;
  165. if (!F.is.fn(where)) return array;
  166. for (var i = 0, len = array.length; i < len; i++) {
  167. if (where(array[i], i)) result.push(array[i]);
  168. }
  169. return result;
  170. };
  171. /**
  172. * Get a boolean value indicating if any item exists in the supplied array that optionally matches the supplied where function.
  173. * @memberof FooTable.arr
  174. * @function any
  175. * @param {Array} array - The array to check.
  176. * @param {function} [where] - [Optional] This function must return a boolean value, true indicates that the current item is a valid match.
  177. * @returns {boolean}
  178. */
  179. F.arr.any = function (array, where) {
  180. if (!F.is.array(array)) return false;
  181. where = F.is.fn(where) ? where : returnTrue;
  182. for (var i = 0, len = array.length; i < len; i++) {
  183. if (where(array[i], i)) return true;
  184. }
  185. return false;
  186. };
  187. /**
  188. * Checks if the supplied value exists in the array.
  189. * @memberof FooTable.arr
  190. * @function contains
  191. * @param {Array} array - The array to check.
  192. * @param {*} value - The value to check for.
  193. * @returns {boolean}
  194. */
  195. F.arr.contains = function(array, value){
  196. if (!F.is.array(array) || F.is.undef(value)) return false;
  197. for (var i = 0, len = array.length; i < len; i++) {
  198. if (array[i] == value) return true;
  199. }
  200. return false;
  201. };
  202. /**
  203. * Get the first item in the supplied array that optionally matches the supplied where function. If no item is found null is returned.
  204. * @memberof FooTable.arr
  205. * @function first
  206. * @param {Array} array - The array to get the item from.
  207. * @param {function} [where] - [Optional] This function must return a boolean value, true indicates that the current item can be returned.
  208. * @returns {(*|null)}
  209. */
  210. F.arr.first = function (array, where) {
  211. if (!F.is.array(array)) return null;
  212. where = F.is.fn(where) ? where : returnTrue;
  213. for (var i = 0, len = array.length; i < len; i++) {
  214. if (where(array[i], i)) return array[i];
  215. }
  216. return null;
  217. };
  218. /**
  219. * Creates a new array from the results of the supplied getter function. If no items are found an empty array is returned, to exclude an item from the results return null.
  220. * @memberof FooTable.arr
  221. * @function map
  222. * @param {Array} array - The array to iterate.
  223. * @param {function} getter - This function must return either a new value or null.
  224. * The first argument is the result being returned at this point in the iteration. The second argument is the current item being iterated.
  225. * @returns {(*|null)}
  226. */
  227. F.arr.map = function (array, getter) {
  228. var result = [], returned = null;
  229. if (!F.is.array(array) || !F.is.fn(getter)) return result;
  230. for (var i = 0, len = array.length; i < len; i++) {
  231. if ((returned = getter(array[i], i)) != null) result.push(returned);
  232. }
  233. return result;
  234. };
  235. /**
  236. * Removes items from the array matching the supplied where function. All removed items are returned in a new array.
  237. * @memberof FooTable.arr
  238. * @function remove
  239. * @param {Array} array - The array to iterate and remove items from.
  240. * @param {function} where - This function must return a boolean value, true includes the item in the result array.
  241. * @returns {*}
  242. */
  243. F.arr.remove = function (array, where) {
  244. var remove = [], removed = [];
  245. if (!F.is.array(array) || !F.is.fn(where)) return removed;
  246. var i = 0, len = array.length;
  247. for (; i < len; i++) {
  248. if (where(array[i], i, removed)){
  249. remove.push(i);
  250. removed.push(array[i]);
  251. }
  252. }
  253. // sort the indexes to be removed from largest to smallest
  254. remove.sort(function(a, b){ return b - a; });
  255. i = 0; len = remove.length;
  256. for(; i < len; i++){
  257. var index = remove[i] - i;
  258. array.splice(index, 1);
  259. }
  260. return removed;
  261. };
  262. /**
  263. * Deletes a single item from the array. The item if removed is returned.
  264. * @memberof FooTable.arr
  265. * @function delete
  266. * @param {Array} array - The array to iterate and delete the item from.
  267. * @param {*} item - The item to find and delete.
  268. * @returns {(*|null)}
  269. */
  270. F.arr.delete = function(array, item){
  271. var remove = -1, removed = null;
  272. if (!F.is.array(array) || F.is.undef(item)) return removed;
  273. var i = 0, len = array.length;
  274. for (; i < len; i++) {
  275. if (array[i] == item){
  276. remove = i;
  277. removed = array[i];
  278. break;
  279. }
  280. }
  281. if (remove != -1) array.splice(remove, 1);
  282. return removed;
  283. };
  284. /**
  285. * Replaces a single item in the array with a new one.
  286. * @memberof FooTable.arr
  287. * @function replace
  288. * @param {Array} array - The array to iterate and replace the item in.
  289. * @param {*} oldItem - The item to be replaced.
  290. * @param {*} newItem - The item to be inserted.
  291. */
  292. F.arr.replace = function(array, oldItem, newItem){
  293. var index = array.indexOf(oldItem);
  294. if (index !== -1) array[index] = newItem;
  295. };
  296. })(FooTable);
  297. (function (F) {
  298. /**
  299. * This namespace contains commonly used 'is' type methods that return boolean values.
  300. * @namespace FooTable.is
  301. */
  302. F.is = {};
  303. /**
  304. * Checks if the type of the value is the same as that supplied.
  305. * @memberof FooTable.is
  306. * @function type
  307. * @param {*} value - The value to check the type of.
  308. * @param {string} type - The type to check for.
  309. * @returns {boolean}
  310. */
  311. F.is.type = function (value, type) {
  312. return typeof value === type;
  313. };
  314. /**
  315. * Checks if the value is defined.
  316. * @memberof FooTable.is
  317. * @function defined
  318. * @param {*} value - The value to check is defined.
  319. * @returns {boolean}
  320. */
  321. F.is.defined = function (value) {
  322. return typeof value !== 'undefined';
  323. };
  324. /**
  325. * Checks if the value is undefined.
  326. * @memberof FooTable.is
  327. * @function undef
  328. * @param {*} value - The value to check is undefined.
  329. * @returns {boolean}
  330. */
  331. F.is.undef = function (value) {
  332. return typeof value === 'undefined';
  333. };
  334. /**
  335. * Checks if the value is an array.
  336. * @memberof FooTable.is
  337. * @function array
  338. * @param {*} value - The value to check.
  339. * @returns {boolean}
  340. */
  341. F.is.array = function (value) {
  342. return '[object Array]' === Object.prototype.toString.call(value);
  343. };
  344. /**
  345. * Checks if the value is a date.
  346. * @memberof FooTable.is
  347. * @function date
  348. * @param {*} value - The value to check.
  349. * @returns {boolean}
  350. */
  351. F.is.date = function (value) {
  352. return '[object Date]' === Object.prototype.toString.call(value) && !isNaN(value.getTime());
  353. };
  354. /**
  355. * Checks if the value is a boolean.
  356. * @memberof FooTable.is
  357. * @function boolean
  358. * @param {*} value - The value to check.
  359. * @returns {boolean}
  360. */
  361. F.is.boolean = function (value) {
  362. return '[object Boolean]' === Object.prototype.toString.call(value);
  363. };
  364. /**
  365. * Checks if the value is a string.
  366. * @memberof FooTable.is
  367. * @function string
  368. * @param {*} value - The value to check.
  369. * @returns {boolean}
  370. */
  371. F.is.string = function (value) {
  372. return '[object String]' === Object.prototype.toString.call(value);
  373. };
  374. /**
  375. * Checks if the value is a number.
  376. * @memberof FooTable.is
  377. * @function number
  378. * @param {*} value - The value to check.
  379. * @returns {boolean}
  380. */
  381. F.is.number = function (value) {
  382. return '[object Number]' === Object.prototype.toString.call(value) && !isNaN(value);
  383. };
  384. /**
  385. * Checks if the value is a function.
  386. * @memberof FooTable.is
  387. * @function fn
  388. * @param {*} value - The value to check.
  389. * @returns {boolean}
  390. */
  391. F.is.fn = function (value) {
  392. return (F.is.defined(window) && value === window.alert) || '[object Function]' === Object.prototype.toString.call(value);
  393. };
  394. /**
  395. * Checks if the value is an error.
  396. * @memberof FooTable.is
  397. * @function error
  398. * @param {*} value - The value to check.
  399. * @returns {boolean}
  400. */
  401. F.is.error = function (value) {
  402. return '[object Error]' === Object.prototype.toString.call(value);
  403. };
  404. /**
  405. * Checks if the value is an object.
  406. * @memberof FooTable.is
  407. * @function object
  408. * @param {*} value - The value to check.
  409. * @returns {boolean}
  410. */
  411. F.is.object = function (value) {
  412. return '[object Object]' === Object.prototype.toString.call(value);
  413. };
  414. /**
  415. * Checks if the value is a hash.
  416. * @memberof FooTable.is
  417. * @function hash
  418. * @param {*} value - The value to check.
  419. * @returns {boolean}
  420. */
  421. F.is.hash = function (value) {
  422. return F.is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval;
  423. };
  424. /**
  425. * Checks if the supplied object is an HTMLElement
  426. * @memberof FooTable.is
  427. * @function element
  428. * @param {object} obj - The object to check.
  429. * @returns {boolean}
  430. */
  431. F.is.element = function (obj) {
  432. return typeof HTMLElement === 'object'
  433. ? obj instanceof HTMLElement
  434. : obj && typeof obj === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string';
  435. };
  436. /**
  437. * This is a simple check to determine if an object is a jQuery promise object. It simply checks the object has a "then" and "promise" function defined.
  438. * The promise object is created as an object literal inside of jQuery.Deferred.
  439. * It has no prototype, nor any other truly unique properties that could be used to distinguish it.
  440. * This method should be a little more accurate than the internal jQuery one that simply checks for a "promise" method.
  441. * @memberof FooTable.is
  442. * @function promise
  443. * @param {object} obj - The object to check.
  444. * @returns {boolean}
  445. */
  446. F.is.promise = function(obj){
  447. return F.is.object(obj) && F.is.fn(obj.then) && F.is.fn(obj.promise);
  448. };
  449. /**
  450. * Checks if the supplied object is an instance of a jQuery object.
  451. * @memberof FooTable.is
  452. * @function jq
  453. * @param {object} obj - The object to check.
  454. * @returns {boolean}
  455. */
  456. F.is.jq = function(obj){
  457. return F.is.defined(window.jQuery) && obj instanceof jQuery && obj.length > 0;
  458. };
  459. /**
  460. * Checks if the supplied object is a moment.js date object.
  461. * @memberof FooTable.is
  462. * @function moment
  463. * @param {object} obj - The object to check.
  464. * @returns {boolean}
  465. */
  466. F.is.moment = function(obj){
  467. return F.is.defined(window.moment) && F.is.object(obj) && F.is.boolean(obj._isAMomentObject)
  468. };
  469. /**
  470. * Checks if the supplied value is an object and if it is empty.
  471. * @memberof FooTable.is
  472. * @function emptyObject
  473. * @param {*} value - The value to check.
  474. * @returns {boolean}
  475. */
  476. F.is.emptyObject = function(value){
  477. if (!F.is.hash(value)) return false;
  478. for(var prop in value) {
  479. if(value.hasOwnProperty(prop))
  480. return false;
  481. }
  482. return true;
  483. };
  484. /**
  485. * Checks if the supplied value is an array and if it is empty.
  486. * @memberof FooTable.is
  487. * @function emptyArray
  488. * @param {*} value - The value to check.
  489. * @returns {boolean}
  490. */
  491. F.is.emptyArray = function(value){
  492. return F.is.array(value) ? value.length === 0 : true;
  493. };
  494. /**
  495. * Checks if the supplied value is a string and if it is empty.
  496. * @memberof FooTable.is
  497. * @function emptyString
  498. * @param {*} value - The value to check.
  499. * @returns {boolean}
  500. */
  501. F.is.emptyString = function(value){
  502. return F.is.string(value) ? value.length === 0 : true;
  503. };
  504. })(FooTable);
  505. (function (F) {
  506. /**
  507. * This namespace contains commonly used string utility methods.
  508. * @namespace FooTable.str
  509. */
  510. F.str = {};
  511. /**
  512. * Checks if the supplied string contains the given substring.
  513. * @memberof FooTable.str
  514. * @function contains
  515. * @param {string} str - The string to check.
  516. * @param {string} contains - The string to check for.
  517. * @param {boolean} [ignoreCase=false] - Whether or not to ignore casing when performing the check.
  518. * @returns {boolean}
  519. */
  520. F.str.contains = function (str, contains, ignoreCase) {
  521. if (F.is.emptyString(str) || F.is.emptyString(contains)) return false;
  522. return contains.length <= str.length
  523. && (ignoreCase ? str.toUpperCase().indexOf(contains.toUpperCase()) : str.indexOf(contains)) !== -1;
  524. };
  525. /**
  526. * Checks if the supplied string contains the exact given substring.
  527. * @memberof FooTable.str
  528. * @function contains
  529. * @param {string} str - The string to check.
  530. * @param {string} contains - The string to check for.
  531. * @param {boolean} [ignoreCase=false] - Whether or not to ignore casing when performing the check.
  532. * @returns {boolean}
  533. */
  534. F.str.containsExact = function (str, contains, ignoreCase) {
  535. if (F.is.emptyString(str) || F.is.emptyString(contains) || contains.length > str.length) return false;
  536. return new RegExp('\\b'+ F.str.escapeRegExp(contains)+'\\b', ignoreCase ? 'i' : '').test(str);
  537. };
  538. /**
  539. * Checks if the supplied string contains the given word.
  540. * @memberof FooTable.str
  541. * @function containsWord
  542. * @param {string} str - The string to check.
  543. * @param {string} word - The word to check for.
  544. * @param {boolean} [ignoreCase=false] - Whether or not to ignore casing when performing the check.
  545. * @returns {boolean}
  546. */
  547. F.str.containsWord = function(str, word, ignoreCase){
  548. if (F.is.emptyString(str) || F.is.emptyString(word) || str.length < word.length)
  549. return false;
  550. var parts = str.split(/\W/);
  551. for (var i = 0, len = parts.length; i < len; i++){
  552. if (ignoreCase ? parts[i].toUpperCase() == word.toUpperCase() : parts[i] == word) return true;
  553. }
  554. return false;
  555. };
  556. /**
  557. * Returns the remainder of a string split on the first index of the given substring.
  558. * @memberof FooTable.str
  559. * @function from
  560. * @param {string} str - The string to split.
  561. * @param {string} from - The substring to split on.
  562. * @returns {string}
  563. */
  564. F.str.from = function (str, from) {
  565. if (F.is.emptyString(str)) return str;
  566. return F.str.contains(str, from) ? str.substring(str.indexOf(from) + 1) : str;
  567. };
  568. /**
  569. * Checks if a string starts with the supplied prefix.
  570. * @memberof FooTable.str
  571. * @function startsWith
  572. * @param {string} str - The string to check.
  573. * @param {string} prefix - The prefix to check for.
  574. * @returns {boolean}
  575. */
  576. F.str.startsWith = function (str, prefix) {
  577. if (F.is.emptyString(str)) return str == prefix;
  578. return str.slice(0, prefix.length) == prefix;
  579. };
  580. /**
  581. * Takes the supplied string and converts it to camel case.
  582. * @memberof FooTable.str
  583. * @function toCamelCase
  584. * @param {string} str - The string to camel case.
  585. * @returns {string}
  586. */
  587. F.str.toCamelCase = function (str) {
  588. if (F.is.emptyString(str)) return str;
  589. if (str.toUpperCase() === str) return str.toLowerCase();
  590. return str.replace(/^([A-Z])|[-\s_](\w)/g, function (match, p1, p2) {
  591. if (F.is.string(p2)) return p2.toUpperCase();
  592. return p1.toLowerCase();
  593. });
  594. };
  595. /**
  596. * Generates a random string 9 characters long using the optional prefix if supplied.
  597. * @memberof FooTable.str
  598. * @function random
  599. * @param {string} [prefix] - The prefix to append to the 9 random characters.
  600. * @returns {string}
  601. */
  602. F.str.random = function(prefix){
  603. prefix = F.is.emptyString(prefix) ? '' : prefix;
  604. return prefix + Math.random().toString(36).substr(2, 9);
  605. };
  606. /**
  607. * Escapes a string for use in a regular expression.
  608. * @memberof FooTable.str
  609. * @function escapeRegExp
  610. * @param {string} str - The string to escape.
  611. * @returns {string}
  612. */
  613. F.str.escapeRegExp = function(str){
  614. if (F.is.emptyString(str)) return str;
  615. return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  616. };
  617. })(FooTable);
  618. (function (F) {
  619. "use strict";
  620. if (!Object.create) {
  621. Object.create = (function () {
  622. var Object = function () {};
  623. return function (prototype) {
  624. if (arguments.length > 1)
  625. throw Error('Second argument not supported');
  626. if (!F.is.object(prototype))
  627. throw TypeError('Argument must be an object');
  628. Object.prototype = prototype;
  629. var result = new Object();
  630. Object.prototype = null;
  631. return result;
  632. };
  633. })();
  634. }
  635. /**
  636. * This base implementation does nothing except provide access to the {@link FooTable.Class#extend} method.
  637. * @constructs FooTable.Class
  638. * @classdesc This class is based off of John Resig's [Simple JavaScript Inheritance]{@link http://ejohn.org/blog/simple-javascript-inheritance} but it has been updated to be ES 5.1
  639. * compatible by implementing an [Object.create polyfill]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill}
  640. * for older browsers.
  641. * @see {@link http://ejohn.org/blog/simple-javascript-inheritance}
  642. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill}
  643. * @returns {FooTable.Class}
  644. */
  645. function Class() {}
  646. var __extendable__ = /xyz/.test(function () {xyz;}) ? /\b_super\b/ : /.*/;
  647. // this._super() within the context of the new function is a pointer to the original function
  648. // except if the hook param is specified then the this._super variable is the result of the original function
  649. Class.__extend__ = function(proto, name, func, original){
  650. // to all who venture here, here be dragons!
  651. proto[name] = F.is.fn(original) && __extendable__.test(func) ?
  652. (function (name, fn) {
  653. return function () {
  654. var tmp, ret;
  655. tmp = this._super;
  656. this._super = original;
  657. ret = fn.apply(this, arguments);
  658. this._super = tmp;
  659. return ret;
  660. };
  661. })(name, func) : func;
  662. };
  663. /**
  664. * Creates a new class that inherits from this class which in turn allows itself to be extended or if a name and function is supplied extends only that specific function on the class.
  665. * @param {(object|string)} arg1 - An object containing any new methods/members to implement or the name of the method to extend.
  666. * @param {function} arg2 - If the first argument is a method name then this is the new function to replace it with.
  667. * @returns {FooTable.Class} A new class that inherits from the base class.
  668. * @example <caption>The below shows an example of how to implement inheritance using this method.</caption>
  669. * var Person = FooTable.Class.extend({
  670. * construct: function(isDancing){
  671. * this.dancing = isDancing;
  672. * },
  673. * dance: function(){
  674. * return this.dancing;
  675. * }
  676. * });
  677. *
  678. * var Ninja = Person.extend({
  679. * construct: function(){
  680. * this._super( false );
  681. * },
  682. * dance: function(){
  683. * // Call the inherited version of dance()
  684. * return this._super();
  685. * },
  686. * swingSword: function(){
  687. * return true;
  688. * }
  689. * });
  690. *
  691. * var p = new Person(true);
  692. * p.dance(); // => true
  693. *
  694. * var n = new Ninja();
  695. * n.dance(); // => false
  696. * n.swingSword(); // => true
  697. *
  698. * // Should all be true
  699. * p instanceof Person && p instanceof FooTable.Class &&
  700. * n instanceof Ninja && n instanceof Person && n instanceof FooTable.Class
  701. */
  702. Class.extend = function (arg1 , arg2) {
  703. var args = Array.prototype.slice.call(arguments);
  704. arg1 = args.shift();
  705. arg2 = args.shift();
  706. function __extend__(proto, name, func, original){
  707. // to all who venture here, here be dragons!
  708. proto[name] = F.is.fn(original) && __extendable__.test(func) ?
  709. (function (name, fn, ofn) {
  710. return function () {
  711. var tmp, ret;
  712. tmp = this._super;
  713. this._super = ofn;
  714. ret = fn.apply(this, arguments);
  715. this._super = tmp;
  716. return ret;
  717. };
  718. })(name, func, original) : func;
  719. }
  720. if (F.is.hash(arg1)){
  721. var proto = Object.create(this.prototype),
  722. _super = this.prototype;
  723. for (var name in arg1) {
  724. if (name === '__ctor__') continue;
  725. __extend__(proto, name, arg1[name], _super[name]);
  726. }
  727. var obj = F.is.fn(proto.__ctor__) ? proto.__ctor__ : function () {
  728. if (!F.is.fn(this.construct))
  729. throw new SyntaxError('FooTable class objects must be constructed with the "new" keyword.');
  730. this.construct.apply(this, arguments);
  731. };
  732. proto.construct = F.is.fn(proto.construct) ? proto.construct : function(){};
  733. obj.prototype = proto;
  734. proto.constructor = obj;
  735. obj.extend = Class.extend;
  736. return obj;
  737. } else if (F.is.string(arg1) && F.is.fn(arg2)) {
  738. __extend__(this.prototype, arg1, arg2, this.prototype[arg1]);
  739. }
  740. };
  741. F.Class = Class;
  742. F.ClassFactory = F.Class.extend(/** @lends FooTable.ClassFactory */{
  743. /**
  744. * This is a simple factory for {@link FooTable.Class} objects allowing them to be registered using a friendly name
  745. * and then new instances can be created using this friendly name.
  746. * @constructs
  747. * @extends FooTable.Class
  748. * @returns {FooTable.ClassFactory}
  749. * @this FooTable.ClassFactory
  750. */
  751. construct: function(){
  752. /**
  753. * An object containing all registered classes.
  754. * @type {{}}
  755. */
  756. this.registered = {};
  757. },
  758. /**
  759. * Checks if the factory contains a class registered using the supplied name.
  760. * @instance
  761. * @param {string} name - The name of the class to check.
  762. * @returns {boolean}
  763. * @this FooTable.ClassFactory
  764. */
  765. contains: function(name){
  766. return F.is.defined(this.registered[name]);
  767. },
  768. /**
  769. * Gets an array of all registered names.
  770. * @instance
  771. * @returns {Array.<string>}
  772. * @this FooTable.ClassFactory
  773. */
  774. names: function(){
  775. var names = [], name;
  776. for (name in this.registered){
  777. if (!this.registered.hasOwnProperty(name)) continue;
  778. names.push(name);
  779. }
  780. return names;
  781. },
  782. /**
  783. * Registers a class object using the supplied friendly name and priority. The priority is only taken into account when loading all registered classes
  784. * using the {@link FooTable.ClassFactory#load} method.
  785. * @instance
  786. * @param {string} name - The friendly name of the class.
  787. * @param {function} klass - The class to register.
  788. * @param {number} priority - This determines the order that the class is created when using the {@link FooTable.ClassFactory#load} method, higher values are loaded first.
  789. * @this FooTable.ClassFactory
  790. */
  791. register: function(name, klass, priority){
  792. if (!F.is.string(name) || !F.is.fn(klass)) return;
  793. var current = this.registered[name];
  794. this.registered[name] = {
  795. name: name,
  796. klass: klass,
  797. priority: F.is.number(priority) ? priority : (F.is.defined(current) ? current.priority : 0)
  798. };
  799. },
  800. /**
  801. * Creates new instances of all registered classes using there priority and the supplied arguments to return them in an array.
  802. * @instance
  803. * @param {object} subs - An object containing classes to substitute on load.
  804. * @param {*} arg1 - The first argument to supply when creating new instances of all registered classes.
  805. * @param {*} [argN...] - Any number of additional arguments to supply when creating new instances of all registered classes.
  806. * @returns {Array.<FooTable.Class>}
  807. * @this FooTable.ClassFactory
  808. */
  809. load: function(subs, arg1, argN){
  810. var self = this, args = Array.prototype.slice.call(arguments), reg = [], loaded = [], name, klass;
  811. subs = args.shift() || {};
  812. for (name in self.registered){
  813. if (!self.registered.hasOwnProperty(name)) continue;
  814. var component = self.registered[name];
  815. if (subs.hasOwnProperty(name)){
  816. klass = subs[name];
  817. if (F.is.string(klass)) klass = F.getFnPointer(subs[name]);
  818. if (F.is.fn(klass)){
  819. component = {name: name, klass: klass, priority: self.registered[name].priority};
  820. }
  821. }
  822. reg.push(component);
  823. }
  824. for (name in subs){
  825. if (!subs.hasOwnProperty(name) || self.registered.hasOwnProperty(name)) continue;
  826. klass = subs[name];
  827. if (F.is.string(klass)) klass = F.getFnPointer(subs[name]);
  828. if (F.is.fn(klass)){
  829. reg.push({name: name, klass: klass, priority: 0});
  830. }
  831. }
  832. reg.sort(function(a, b){ return b.priority - a.priority; });
  833. F.arr.each(reg, function(r){
  834. if (F.is.fn(r.klass)){
  835. loaded.push(self._make(r.klass, args));
  836. }
  837. });
  838. return loaded;
  839. },
  840. /**
  841. * Create a new instance of a single class using the supplied name and arguments.
  842. * @instance
  843. * @param {string} name - The name of the class to create.
  844. * @param {*} arg1 - The first argument to supply to the new instance.
  845. * @param {*} [argN...] - Any number of additional arguments to supply to the new instance.
  846. * @returns {FooTable.Class}
  847. * @this FooTable.ClassFactory
  848. */
  849. make: function(name, arg1, argN){
  850. var self = this, args = Array.prototype.slice.call(arguments), reg;
  851. name = args.shift();
  852. reg = self.registered[name];
  853. if (F.is.fn(reg.klass)){
  854. return self._make(reg.klass, args);
  855. }
  856. return null;
  857. },
  858. /**
  859. * This in effect lets us use the "apply" method on a function using the "new" keyword.
  860. * @instance
  861. * @private
  862. * @param {function} klass
  863. * @param args
  864. * @returns {FooTable.Class}
  865. * @this FooTable.ClassFactory
  866. */
  867. _make: function(klass, args){
  868. function Class() {
  869. return klass.apply(this, args);
  870. }
  871. Class.prototype = klass.prototype;
  872. return new Class();
  873. }
  874. });
  875. })(FooTable);
  876. (function($, F){
  877. /**
  878. * Converts the supplied cssText string into JSON object.
  879. * @param {string} cssText - The cssText to convert to a JSON object.
  880. * @returns {object}
  881. */
  882. F.css2json = function(cssText){
  883. if (F.is.emptyString(cssText)) return {};
  884. var json = {}, props = cssText.split(';'), pair, key, value;
  885. for (var i = 0, i_len = props.length; i < i_len; i++){
  886. if (F.is.emptyString(props[i])) continue;
  887. pair = props[i].split(':');
  888. if (F.is.emptyString(pair[0]) || F.is.emptyString(pair[1])) continue;
  889. key = F.str.toCamelCase($.trim(pair[0]));
  890. value = $.trim(pair[1]);
  891. json[key] = value;
  892. }
  893. return json;
  894. };
  895. /**
  896. * Attempts to retrieve a function pointer using the given name.
  897. * @param {string} functionName - The name of the function to fetch a pointer to.
  898. * @returns {(function|object|null)}
  899. */
  900. F.getFnPointer = function(functionName){
  901. if (F.is.emptyString(functionName)) return null;
  902. var pointer = window,
  903. parts = functionName.split('.');
  904. F.arr.each(parts, function(part){
  905. if (pointer[part]) pointer = pointer[part];
  906. });
  907. return F.is.fn(pointer) ? pointer : null;
  908. };
  909. /**
  910. * Checks the value for function properties such as the {@link FooTable.Column#formatter} option which could also be specified using just the name
  911. * and attempts to return the correct function pointer or null if none was found matching the value.
  912. * @param {FooTable.Class} self - The class to use as the 'this' keyword within the context of the function.
  913. * @param {(function|string)} value - The actual function or the name of the function for the property.
  914. * @param {function} [def] - A default function to return if none is found.
  915. * @returns {(function|null)}
  916. */
  917. F.checkFnValue = function(self, value, def){
  918. def = F.is.fn(def) ? def : null;
  919. function wrap(t, fn, d){
  920. if (!F.is.fn(fn)) return d;
  921. return function(){
  922. return fn.apply(t, arguments);
  923. };
  924. }
  925. return F.is.fn(value) ? wrap(self, value, def) : (F.is.type(value, 'string') ? wrap(self, F.getFnPointer(value), def) : def);
  926. };
  927. })(jQuery, FooTable);
  928. (function($, F){
  929. F.Cell = F.Class.extend(/** @lends FooTable.Cell */{
  930. /**
  931. * The cell class containing all the properties for cells.
  932. * @constructs
  933. * @extends FooTable.Class
  934. * @param {FooTable.Table} table - The root {@link FooTable.Table} this cell belongs to.
  935. * @param {FooTable.Row} row - The parent {@link FooTable.Row} this cell belongs to.
  936. * @param {FooTable.Column} column - The {@link FooTable.Column} this cell falls under.
  937. * @param {(*|HTMLElement|jQuery)} valueOrElement - Either the value or the element for the cell.
  938. * @returns {FooTable.Cell}
  939. * @this FooTable.Cell
  940. */
  941. construct: function (table, row, column, valueOrElement) {
  942. /**
  943. * The root {@link FooTable.Table} for the cell.
  944. * @instance
  945. * @readonly
  946. * @type {FooTable.Table}
  947. */
  948. this.ft = table;
  949. /**
  950. * The parent {@link FooTable.Row} for the cell.
  951. * @instance
  952. * @readonly
  953. * @type {FooTable.Row}
  954. */
  955. this.row = row;
  956. /**
  957. * The {@link FooTable.Column} this cell falls under.
  958. * @instance
  959. * @readonly
  960. * @type {FooTable.Column}
  961. */
  962. this.column = column;
  963. this.created = false;
  964. this.define(valueOrElement);
  965. },
  966. /**
  967. * This is supplied either the value or the cell element/jQuery object if it exists.
  968. * If supplied the element we need set the $el property and parse the value from it.
  969. * @instance
  970. * @protected
  971. * @param {(*|jQuery)} valueOrElement - The value or element to define the cell.
  972. * @this FooTable.Cell
  973. */
  974. define: function(valueOrElement){
  975. /**
  976. * The jQuery table cell object this instance wraps.
  977. * @instance
  978. * @type {jQuery}
  979. */
  980. this.$el = F.is.element(valueOrElement) || F.is.jq(valueOrElement) ? $(valueOrElement) : null;
  981. /**
  982. * The jQuery row object that represents this cell in the details table.
  983. * @type {jQuery}
  984. */
  985. this.$detail = null;
  986. var hasOptions = F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options) && F.is.defined(valueOrElement.value);
  987. /**
  988. * The value of the cell.
  989. * @instance
  990. * @type {*}
  991. */
  992. this.value = this.column.parser.call(this.column, F.is.jq(this.$el) ? this.$el : (hasOptions ? valueOrElement.value : valueOrElement), this.ft.o);
  993. /**
  994. * Contains any options for the cell. These are the options supplied through the plugin constructor as part of the row object itself.
  995. * @type {object}
  996. */
  997. this.o = $.extend(true, {
  998. classes: null,
  999. style: null
  1000. }, hasOptions ? valueOrElement.options : {});
  1001. /**
  1002. * An array of CSS classes for the cell.
  1003. * @instance
  1004. * @protected
  1005. * @type {Array.<string>}
  1006. */
  1007. this.classes = F.is.jq(this.$el) && this.$el.attr('class') ? this.$el.attr('class').match(/\S+/g) : (F.is.array(this.o.classes) ? this.o.classes : (F.is.string(this.o.classes) ? this.o.classes.match(/\S+/g) : []));
  1008. /**
  1009. * The inline styles for the cell.
  1010. * @instance
  1011. * @protected
  1012. * @type {object}
  1013. */
  1014. this.style = F.is.jq(this.$el) && this.$el.attr('style') ? F.css2json(this.$el.attr('style')) : (F.is.hash(this.o.style) ? this.o.style : (F.is.string(this.o.style) ? F.css2json(this.o.style) : {}));
  1015. },
  1016. /**
  1017. * After the cell has been defined this ensures that the $el and #detail properties are jQuery objects by either creating or updating them.
  1018. * @instance
  1019. * @protected
  1020. * @this FooTable.Cell
  1021. */
  1022. $create: function(){
  1023. if (this.created) return;
  1024. (this.$el = F.is.jq(this.$el) ? this.$el : $('<td/>'))
  1025. .data('value', this.value)
  1026. .contents().detach().end()
  1027. .append(this.format(this.value));
  1028. this._setClasses(this.$el);
  1029. this._setStyle(this.$el);
  1030. this.$detail = $('<tr/>').addClass(this.row.classes.join(' '))
  1031. .data('__FooTableCell__', this)
  1032. .append($('<th/>'))
  1033. .append($('<td/>'));
  1034. this.created = true;
  1035. },
  1036. /**
  1037. * Collapses this cell and displays it in the details row.
  1038. * @instance
  1039. * @protected
  1040. */
  1041. collapse: function(){
  1042. if (!this.created) return;
  1043. this.$detail.children('th').html(this.column.title);
  1044. this.$el.clone()
  1045. .attr('id', this.$el.attr('id') ? this.$el.attr('id') + '-detail' : undefined)
  1046. .css('display', 'table-cell')
  1047. .html('')
  1048. .append(this.$el.contents().detach())
  1049. .replaceAll(this.$detail.children('td').first());
  1050. if (!F.is.jq(this.$detail.parent()))
  1051. this.$detail.appendTo(this.row.$details.find('.footable-details > tbody'));
  1052. },
  1053. /**
  1054. * Restores this cell from a detail row back into the normal row.
  1055. * @instance
  1056. * @protected
  1057. */
  1058. restore: function(){
  1059. if (!this.created) return;
  1060. if (F.is.jq(this.$detail.parent())){
  1061. var $cell = this.$detail.children('td').first();
  1062. this.$el
  1063. .attr('class', $cell.attr('class'))
  1064. .attr('style', $cell.attr('style'))
  1065. .css('display', (this.column.hidden || !this.column.visible) ? 'none' : 'table-cell')
  1066. .append($cell.contents().detach());
  1067. }
  1068. this.$detail.detach();
  1069. },
  1070. /**
  1071. * Helper method to call this cell's column parser function supplying the required parameters.
  1072. * @instance
  1073. * @protected
  1074. * @returns {*}
  1075. * @see FooTable.Column#parser
  1076. * @this FooTable.Cell
  1077. */
  1078. parse: function(){
  1079. return this.column.parser.call(this.column, this.$el, this.ft.o);
  1080. },
  1081. /**
  1082. * Helper method to call this cell's column formatter function using the supplied value and any additional required parameters.
  1083. * @instance
  1084. * @protected
  1085. * @param {*} value - The value to format.
  1086. * @returns {(string|HTMLElement|jQuery)}
  1087. * @see FooTable.Column#formatter
  1088. * @this FooTable.Cell
  1089. */
  1090. format: function(value){
  1091. return this.column.formatter.call(this.column, value, this.ft.o, this.row.value);
  1092. },
  1093. /**
  1094. * Allows easy access to getting or setting the cell's value. If the value is set all associated properties are also updated along with the actual element.
  1095. * Using this method also allows us to supply an object containing options and the value for the cell.
  1096. * @instance
  1097. * @param {*} [value] - The value to set for the cell. If not supplied the current value of the cell is returned.
  1098. * @param {boolean} [redraw=true] - Whether or not to redraw the row once the value has been set.
  1099. * @param {boolean} [redrawSelf=true] - Whether or not to redraw the cell itself once the value has been set, if `false` this will override the supplied `redraw` value and prevent the row from redrawing as well.
  1100. * @returns {(*|undefined)}
  1101. * @this FooTable.Cell
  1102. */
  1103. val: function(value, redraw, redrawSelf){
  1104. if (F.is.undef(value)){
  1105. // get
  1106. return this.value;
  1107. }
  1108. // set
  1109. var self = this, hasOptions = F.is.hash(value) && F.is.hash(value.options) && F.is.defined(value.value);
  1110. this.o = $.extend(true, {
  1111. classes: self.classes,
  1112. style: self.style
  1113. }, hasOptions ? value.options : {});
  1114. this.value = hasOptions ? value.value : value;
  1115. this.classes = F.is.array(this.o.classes) ? this.o.classes : (F.is.string(this.o.classes) ? this.o.classes.match(/\S+/g) : []);
  1116. this.style = F.is.hash(this.o.style) ? this.o.style : (F.is.string(this.o.style) ? F.css2json(this.o.style) : {});
  1117. redrawSelf = F.is.boolean(redrawSelf) ? redrawSelf : true;
  1118. if (this.created && redrawSelf){
  1119. this.$el.data('value', this.value).empty();
  1120. var $detail = this.$detail.children('td').first().empty(),
  1121. $target = F.is.jq(this.$detail.parent()) ? $detail : this.$el;
  1122. $target.append(this.format(this.value));
  1123. this._setClasses($target);
  1124. this._setStyle($target);
  1125. if (F.is.boolean(redraw) ? redraw : true) this.row.draw();
  1126. }
  1127. },
  1128. _setClasses: function($el){
  1129. var hasColClasses = !F.is.emptyArray(this.column.classes),
  1130. hasClasses = !F.is.emptyArray(this.classes),
  1131. classes = null;
  1132. $el.removeAttr('class');
  1133. if (!hasColClasses && !hasClasses) return;
  1134. if (hasColClasses && hasClasses){
  1135. classes = this.classes.concat(this.column.classes).join(' ');
  1136. } else if (hasColClasses) {
  1137. classes = this.column.classes.join(' ');
  1138. } else if (hasClasses){
  1139. classes = this.classes.join(' ');
  1140. }
  1141. if (!F.is.emptyString(classes)){
  1142. $el.addClass(classes);
  1143. }
  1144. },
  1145. _setStyle: function($el){
  1146. var hasColStyle = !F.is.emptyObject(this.column.style),
  1147. hasStyle = !F.is.emptyObject(this.style),
  1148. style = null;
  1149. $el.removeAttr('style');
  1150. if (!hasColStyle && !hasStyle) return;
  1151. if (hasColStyle && hasStyle){
  1152. style = $.extend({}, this.column.style, this.style);
  1153. } else if (hasColStyle) {
  1154. style = this.column.style;
  1155. } else if (hasStyle){
  1156. style = this.style;
  1157. }
  1158. if (F.is.hash(style)){
  1159. $el.css(style);
  1160. }
  1161. }
  1162. });
  1163. })(jQuery, FooTable);
  1164. (function($, F){
  1165. F.Column = F.Class.extend(/** @lends FooTable.Column */{
  1166. /**
  1167. * The column class containing all the properties for columns. All members marked as "readonly" should not be used when defining {@link FooTable.Defaults#columns}.
  1168. * @constructs
  1169. * @extends FooTable.Class
  1170. * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this component belongs to.
  1171. * @param {object} definition - An object containing all the properties to set for the column.
  1172. * @param {string} [type] - The type of column, "text" by default.
  1173. * @returns {FooTable.Column}
  1174. * @this FooTable.Column
  1175. */
  1176. construct: function(instance, definition, type){
  1177. /**
  1178. * The root {@link FooTable.Table} for the column.
  1179. * @instance
  1180. * @readonly
  1181. * @type {FooTable.Table}
  1182. */
  1183. this.ft = instance;
  1184. /**
  1185. * The type of data displayed by the column.
  1186. * @instance
  1187. * @readonly
  1188. * @type {string}
  1189. */
  1190. this.type = F.is.emptyString(type) ? 'text' : type;
  1191. /**
  1192. * Whether or not the column was parsed from a standard table row containing data instead of from an actual header row.
  1193. * @instance
  1194. * @readonly
  1195. * @type {boolean}
  1196. */
  1197. this.virtual = F.is.boolean(definition.virtual) ? definition.virtual : false;
  1198. /**
  1199. * The jQuery cell object for the column header.
  1200. * @instance
  1201. * @readonly
  1202. * @type {jQuery}
  1203. */
  1204. this.$el = F.is.jq(definition.$el) ? definition.$el : null;
  1205. /**
  1206. * The index of the column in the table. This is set by the plugin during initialization.
  1207. * @instance
  1208. * @readonly
  1209. * @type {number}
  1210. * @default -1
  1211. */
  1212. this.index = F.is.number(definition.index) ? definition.index : -1;
  1213. /**
  1214. * Whether or not this in an internal only column.
  1215. * @instance
  1216. * @readonly
  1217. * @type {boolean}
  1218. * @description Internal columns or there cells will not be returned when calling methods such as `FooTable.Row#val`.
  1219. */
  1220. this.internal = false;
  1221. this.define(definition);
  1222. this.$create();
  1223. },
  1224. /**
  1225. * This is supplied the column definition in the form of a simple object created by merging options supplied via the plugin constructor with those parsed from the DOM.
  1226. * @instance
  1227. * @protected
  1228. * @param {object} definition - The object containing the column definition.
  1229. * @this FooTable.Column
  1230. */
  1231. define: function(definition){
  1232. /**
  1233. * Whether or not this column is hidden from view and appears in the details row.
  1234. * @type {boolean}
  1235. * @default false
  1236. */
  1237. this.hidden = F.is.boolean(definition.hidden) ? definition.hidden : false;
  1238. /**
  1239. * Whether or not this column is completely hidden from view and will not appear in the details row.
  1240. * @type {boolean}
  1241. * @default true
  1242. */
  1243. this.visible = F.is.boolean(definition.visible) ? definition.visible : true;
  1244. /**
  1245. * The name of the column. This name must correspond to the property name of the JSON row data.
  1246. * @type {string}
  1247. * @default null
  1248. */
  1249. this.name = F.is.string(definition.name) ? definition.name : null;
  1250. if (this.name == null) this.name = 'col'+(definition.index+1);
  1251. /**
  1252. * The title to display in the column header, this can be HTML.
  1253. * @type {string}
  1254. * @default null
  1255. */
  1256. this.title = F.is.string(definition.title) ? definition.title : null;
  1257. if (!this.virtual && this.title == null && F.is.jq(this.$el)) this.title = this.$el.html();
  1258. if (this.title == null) this.title = 'Column '+(definition.index+1);
  1259. /**
  1260. * The styles to apply to all cells in this column.
  1261. * @type {object}
  1262. */
  1263. this.style = F.is.hash(definition.style) ? definition.style : (F.is.string(definition.style) ? F.css2json(definition.style) : {});
  1264. /**
  1265. * The classes to apply to all cells in this column.
  1266. * @type {Array.<string>}
  1267. */
  1268. this.classes = F.is.array(definition.classes) ? definition.classes : (F.is.string(definition.classes) ? definition.classes.match(/\S+/g) : []);
  1269. // override any default functions ensuring when they are executed "this" within the context of the function points to the instance of this object.
  1270. this.parser = F.checkFnValue(this, definition.parser, this.parser);
  1271. this.formatter = F.checkFnValue(this, definition.formatter, this.formatter);
  1272. },
  1273. /**
  1274. * After the column has been defined this ensures that the $el property is a jQuery object by either creating or updating the current value.
  1275. * @instance
  1276. * @protected
  1277. * @this FooTable.Column
  1278. */
  1279. $create: function(){
  1280. (this.$el = !this.virtual && F.is.jq(this.$el) ? this.$el : $('<th/>')).html(this.title).addClass(this.classes.join(' ')).css(this.style);
  1281. },
  1282. /**
  1283. * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and will be provided to the {@link FooTable.Column#format} function
  1284. * to generate the cell contents.
  1285. * @instance
  1286. * @protected
  1287. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  1288. * @returns {string}
  1289. * @this FooTable.Column
  1290. */
  1291. parser: function(valueOrElement){
  1292. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){ // use jQuery to get the value
  1293. var data = $(valueOrElement).data('value');
  1294. return F.is.defined(data) ? data : $(valueOrElement).html();
  1295. }
  1296. if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement+''; // use the native toString of the value
  1297. return null; // otherwise we have no value so return null
  1298. },
  1299. /**
  1300. * This is supplied the value retrieved from the {@link FooTable.Column#parse} function and must return a string, HTMLElement or jQuery object.
  1301. * The return value from this function is what is displayed in the cell in the table.
  1302. * @instance
  1303. * @protected
  1304. * @param {string} value - The value to format.
  1305. * @param {object} options - The current plugin options.
  1306. * @param {object} rowData - An object containing the current row data.
  1307. * @returns {(string|HTMLElement|jQuery)}
  1308. * @this FooTable.Column
  1309. */
  1310. formatter: function(value, options, rowData){
  1311. return value == null ? '' : value;
  1312. },
  1313. /**
  1314. * Creates a cell for this column from the supplied {@link FooTable.Row} object. This allows different column types to return different types of cells.
  1315. * @instance
  1316. * @protected
  1317. * @param {FooTable.Row} row - The row to create the cell from.
  1318. * @returns {FooTable.Cell}
  1319. * @this FooTable.Column
  1320. */
  1321. createCell: function(row){
  1322. var element = F.is.jq(row.$el) ? row.$el.children('td,th').get(this.index) : null,
  1323. data = F.is.hash(row.value) ? row.value[this.name] : null;
  1324. return new F.Cell(this.ft, row, this, element || data);
  1325. }
  1326. });
  1327. F.columns = new F.ClassFactory();
  1328. F.columns.register('text', F.Column);
  1329. })(jQuery, FooTable);
  1330. (function ($, F) {
  1331. F.Component = F.Class.extend(/** @lends FooTable.Component */{
  1332. /**
  1333. * The base class for all FooTable components.
  1334. * @constructs
  1335. * @extends FooTable.Class
  1336. * @param {FooTable.Table} instance - The parent {@link FooTable.Table} object for the component.
  1337. * @param {boolean} enabled - Whether or not the component is enabled.
  1338. * @throws {TypeError} The instance parameter must be an instance of {@link FooTable.Table}.
  1339. * @returns {FooTable.Component}
  1340. */
  1341. construct: function (instance, enabled) {
  1342. if (!(instance instanceof F.Table))
  1343. throw new TypeError('The instance parameter must be an instance of FooTable.Table.');
  1344. /**
  1345. * The parent {@link FooTable.Table} for the component.
  1346. * @type {FooTable.Table}
  1347. */
  1348. this.ft = instance;
  1349. /**
  1350. * Whether or not this component is enabled. Disabled components only have there preinit method called allowing for this value to be overridden.
  1351. * @type {boolean}
  1352. */
  1353. this.enabled = F.is.boolean(enabled) ? enabled : false;
  1354. },
  1355. /**
  1356. * The preinit method is called during the parent {@link FooTable.Table} constructor call.
  1357. * @param {object} data - The jQuery.data() object of the root table.
  1358. * @instance
  1359. * @protected
  1360. * @function
  1361. */
  1362. preinit: function(data){},
  1363. /**
  1364. * The init method is called during the parent {@link FooTable.Table} constructor call.
  1365. * @instance
  1366. * @protected
  1367. * @function
  1368. */
  1369. init: function(){},
  1370. /**
  1371. * This method is called from the {@link FooTable.Table#destroy} method.
  1372. * @instance
  1373. * @protected
  1374. * @function
  1375. */
  1376. destroy: function(){},
  1377. /**
  1378. * This method is called from the {@link FooTable.Table#draw} method.
  1379. * @instance
  1380. * @protected
  1381. * @function
  1382. */
  1383. predraw: function(){},
  1384. /**
  1385. * This method is called from the {@link FooTable.Table#draw} method.
  1386. * @instance
  1387. * @protected
  1388. * @function
  1389. */
  1390. draw: function(){},
  1391. /**
  1392. * This method is called from the {@link FooTable.Table#draw} method.
  1393. * @instance
  1394. * @protected
  1395. * @function
  1396. */
  1397. postdraw: function(){}
  1398. });
  1399. F.components = new F.ClassFactory();
  1400. })(jQuery, FooTable);
  1401. (function ($, F) {
  1402. /**
  1403. * Contains all the available options for the FooTable plugin.
  1404. * @name FooTable.Defaults
  1405. * @function
  1406. * @constructor
  1407. * @returns {FooTable.Defaults}
  1408. */
  1409. F.Defaults = function () {
  1410. /**
  1411. * Whether or not events raised using the {@link FooTable.Table#raise} method are propagated up the DOM. By default this is set to false and all events bubble up the DOM as per usual
  1412. * however the reason for this option is if we have nested tables. If false the parent table would receive all the events raised by it's children and any handlers bound to both the
  1413. * parent and child would be triggered which is not the desired behavior.
  1414. * @type {boolean}
  1415. * @default false
  1416. */
  1417. this.stopPropagation = false;
  1418. /**
  1419. * An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).
  1420. * @type {object.<string, function>}
  1421. * @default NULL
  1422. * @example <caption>This example shows how to pass an object containing the events and handlers.</caption>
  1423. * "on": {
  1424. * "click": function(e){
  1425. * // bind a custom click event to do something whenever the table is clicked
  1426. * },
  1427. * "init.ft.table": function(e, ft){
  1428. * // bind to the FooTable initialize event to do something
  1429. * }
  1430. * }
  1431. */
  1432. this.on = null;
  1433. };
  1434. /**
  1435. * Contains all the default options for the plugin.
  1436. * @type {FooTable.Defaults}
  1437. */
  1438. F.defaults = new F.Defaults();
  1439. })(jQuery, FooTable);
  1440. (function($, F){
  1441. F.Row = F.Class.extend(/** @lends FooTable.Row */{
  1442. /**
  1443. * The row class containing all the properties for a row and its' cells.
  1444. * @constructs
  1445. * @extends FooTable.Class
  1446. * @param {FooTable.Table} table - The parent {@link FooTable.Table} this component belongs to.
  1447. * @param {Array.<FooTable.Column>} columns - The array of {@link FooTable.Column} for this row.
  1448. * @param {(*|HTMLElement|jQuery)} dataOrElement - Either the data for the row (create) or the element (parse) for the row.
  1449. * @returns {FooTable.Row}
  1450. */
  1451. construct: function (table, columns, dataOrElement) {
  1452. /**
  1453. * The {@link FooTable.Table} for the row.
  1454. * @type {FooTable.Table}
  1455. */
  1456. this.ft = table;
  1457. /**
  1458. * The array of {@link FooTable.Column} for this row.
  1459. * @type {Array.<FooTable.Column>}
  1460. */
  1461. this.columns = columns;
  1462. this.created = false;
  1463. this.define(dataOrElement);
  1464. },
  1465. /**
  1466. * This is supplied either the object containing the values for the row or the row element/jQuery object if it exists.
  1467. * If supplied the element we need to set the $el property and parse the cells from it using the column index.
  1468. * If we have an object we parse the cells from it using the column name.
  1469. * @param {(object|jQuery)} dataOrElement - The row object or element to define the row.
  1470. */
  1471. define: function(dataOrElement){
  1472. /**
  1473. * The jQuery table row object this instance wraps.
  1474. * @instance
  1475. * @protected
  1476. * @type {jQuery}
  1477. */
  1478. this.$el = F.is.element(dataOrElement) || F.is.jq(dataOrElement) ? $(dataOrElement) : null;
  1479. /**
  1480. * The jQuery toggle element for the row.
  1481. * @instance
  1482. * @protected
  1483. * @type {jQuery}
  1484. */
  1485. this.$toggle = $('<span/>', {'class': 'footable-toggle fooicon fooicon-plus'});
  1486. var isObj = F.is.hash(dataOrElement),
  1487. hasOptions = isObj && F.is.hash(dataOrElement.options) && F.is.hash(dataOrElement.value);
  1488. /**
  1489. * The value of the row.
  1490. * @instance
  1491. * @protected
  1492. * @type {Object}
  1493. */
  1494. this.value = isObj ? (hasOptions ? dataOrElement.value : dataOrElement) : null;
  1495. /**
  1496. * Contains any options for the row.
  1497. * @type {object}
  1498. */
  1499. this.o = $.extend(true, {
  1500. expanded: false,
  1501. classes: null,
  1502. style: null
  1503. }, hasOptions ? dataOrElement.options : {});
  1504. /**
  1505. * Whether or not this row is expanded and will display it's detail row when there are any hidden columns.
  1506. * @instance
  1507. * @protected
  1508. * @type {boolean}
  1509. */
  1510. this.expanded = F.is.jq(this.$el) ? (this.$el.data('expanded') || this.o.expanded) : this.o.expanded;
  1511. /**
  1512. * An array of CSS classes for the row.
  1513. * @instance
  1514. * @protected
  1515. * @type {Array.<string>}
  1516. */
  1517. this.classes = F.is.jq(this.$el) && this.$el.attr('class') ? this.$el.attr('class').match(/\S+/g) : (F.is.array(this.o.classes) ? this.o.classes : (F.is.string(this.o.classes) ? this.o.classes.match(/\S+/g) : []));
  1518. /**
  1519. * The inline styles for the row.
  1520. * @instance
  1521. * @protected
  1522. * @type {object}
  1523. */
  1524. this.style = F.is.jq(this.$el) && this.$el.attr('style') ? F.css2json(this.$el.attr('style')) : (F.is.hash(this.o.style) ? this.o.style : (F.is.string(this.o.style) ? F.css2json(this.o.style) : {}));
  1525. /**
  1526. * The cells array. This is populated before the call to the {@link FooTable.Row#$create} method.
  1527. * @instance
  1528. * @type {Array.<FooTable.Cell>}
  1529. */
  1530. this.cells = this.createCells();
  1531. // this ensures the value contains the parsed cell values and not the supplied values
  1532. var self = this;
  1533. self.value = {};
  1534. F.arr.each(self.cells, function(cell){
  1535. self.value[cell.column.name] = cell.val();
  1536. });
  1537. },
  1538. /**
  1539. * After the row has been defined this ensures that the $el property is a jQuery object by either creating or updating the current value.
  1540. * @instance
  1541. * @protected
  1542. * @this FooTable.Row
  1543. */
  1544. $create: function(){
  1545. if (this.created) return;
  1546. (this.$el = F.is.jq(this.$el) ? this.$el : $('<tr/>'))
  1547. .data('__FooTableRow__', this);
  1548. this._setClasses(this.$el);
  1549. this._setStyle(this.$el);
  1550. if (this.ft.rows.toggleColumn == 'last') this.$toggle.addClass('last-column');
  1551. this.$details = $('<tr/>', { 'class': 'footable-detail-row' })
  1552. .append($('<td/>', { colspan: this.ft.columns.visibleColspan })
  1553. .append($('<table/>', { 'class': 'footable-details ' + this.ft.classes.join(' ') })
  1554. .append('<tbody/>')));
  1555. var self = this;
  1556. F.arr.each(self.cells, function(cell){
  1557. if (!cell.created) cell.$create();
  1558. self.$el.append(cell.$el);
  1559. });
  1560. self.$el.off('click.ft.row').on('click.ft.row', { self: self }, self._onToggle);
  1561. this.created = true;
  1562. },
  1563. /**
  1564. * This is called during the construct method and uses the current column definitions to create an array of {@link FooTable.Cell} objects for the row.
  1565. * @instance
  1566. * @protected
  1567. * @returns {Array.<FooTable.Cell>}
  1568. * @this FooTable.Row
  1569. */
  1570. createCells: function(){
  1571. var self = this;
  1572. return F.arr.map(self.columns, function(col){
  1573. return col.createCell(self);
  1574. });
  1575. },
  1576. /**
  1577. * Allows easy access to getting or setting the row's data. If the data is set all associated properties are also updated along with the actual element.
  1578. * Using this method also allows us to supply an object containing options and the data for the row at the same time.
  1579. * @instance
  1580. * @param {object} [data] - The data to set for the row. If not supplied the current value of the row is returned.
  1581. * @param {boolean} [redraw=true] - Whether or not to redraw the table once the value has been set.
  1582. * @param {boolean} [redrawSelf=true] - Whether or not to redraw the row itself once the value has been set, if `false` this will override the supplied `redraw` value and prevent the table from redrawing as well.
  1583. * @returns {(*|undefined)}
  1584. */
  1585. val: function(data, redraw, redrawSelf){
  1586. var self = this;
  1587. if (!F.is.hash(data)){
  1588. // get - check the value property and build it from the cells if required.
  1589. if (!F.is.hash(this.value) || F.is.emptyObject(this.value)){
  1590. this.value = {};
  1591. F.arr.each(this.cells, function(cell){
  1592. if (!cell.column.internal){
  1593. self.value[cell.column.name] = cell.val();
  1594. }
  1595. });
  1596. }
  1597. return this.value;
  1598. }
  1599. // set
  1600. this.collapse(false);
  1601. var isObj = F.is.hash(data),
  1602. hasOptions = isObj && F.is.hash(data.options) && F.is.hash(data.value);
  1603. this.o = $.extend(true, {
  1604. expanded: self.expanded,
  1605. classes: self.classes,
  1606. style: self.style
  1607. }, hasOptions ? data.options : {});
  1608. this.expanded = this.o.expanded;
  1609. this.classes = F.is.array(this.o.classes) ? this.o.classes : (F.is.string(this.o.classes) ? this.o.classes.match(/\S+/g) : []);
  1610. this.style = F.is.hash(this.o.style) ? this.o.style : (F.is.string(this.o.style) ? F.css2json(this.o.style) : {});
  1611. if (isObj) {
  1612. if ( hasOptions ) data = data.value;
  1613. if (F.is.hash(this.value)){
  1614. for (var prop in data) {
  1615. if (!data.hasOwnProperty(prop)) continue;
  1616. this.value[prop] = data[prop];
  1617. }
  1618. } else {
  1619. this.value = data;
  1620. }
  1621. } else {
  1622. this.value = null;
  1623. }
  1624. redrawSelf = F.is.boolean(redrawSelf) ? redrawSelf : true;
  1625. F.arr.each(this.cells, function(cell){
  1626. if (!cell.column.internal && F.is.defined(self.value[cell.column.name])){
  1627. cell.val(self.value[cell.column.name], false, redrawSelf);
  1628. }
  1629. });
  1630. if (this.created && redrawSelf){
  1631. this._setClasses(this.$el);
  1632. this._setStyle(this.$el);
  1633. if (F.is.boolean(redraw) ? redraw : true) this.draw();
  1634. }
  1635. },
  1636. _setClasses: function($el){
  1637. var hasClasses = !F.is.emptyArray(this.classes),
  1638. classes = null;
  1639. $el.removeAttr('class');
  1640. if (!hasClasses) return;
  1641. else classes = this.classes.join(' ');
  1642. if (!F.is.emptyString(classes)){
  1643. $el.addClass(classes);
  1644. }
  1645. },
  1646. _setStyle: function($el){
  1647. var hasStyle = !F.is.emptyObject(this.style),
  1648. style = null;
  1649. $el.removeAttr('style');
  1650. if (!hasStyle) return;
  1651. else style = this.style;
  1652. if (F.is.hash(style)){
  1653. $el.css(style);
  1654. }
  1655. },
  1656. /**
  1657. * Sets the current row to an expanded state displaying any hidden columns in a detail row just below it.
  1658. * @instance
  1659. * @fires FooTable.Row#"expand.ft.row"
  1660. */
  1661. expand: function(){
  1662. if (!this.created) return;
  1663. var self = this;
  1664. /**
  1665. * The expand.ft.row event is raised before the the row is expanded.
  1666. * Calling preventDefault on this event will stop the row being expanded.
  1667. * @event FooTable.Row#"expand.ft.row"
  1668. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  1669. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  1670. * @param {FooTable.Row} row - The row about to be expanded.
  1671. */
  1672. self.ft.raise('expand.ft.row',[self]).then(function(){
  1673. self.__hidden__ = F.arr.map(self.cells, function(cell){
  1674. return cell.column.hidden && cell.column.visible ? cell : null;
  1675. });
  1676. if (self.__hidden__.length > 0){
  1677. self.$details.insertAfter(self.$el)
  1678. .children('td').first()
  1679. .attr('colspan', self.ft.columns.visibleColspan);
  1680. F.arr.each(self.__hidden__, function(cell){
  1681. cell.collapse();
  1682. });
  1683. }
  1684. self.$el.attr('data-expanded', true);
  1685. self.$toggle.removeClass('fooicon-plus').addClass('fooicon-minus');
  1686. self.expanded = true;
  1687. self.ft.raise('expanded.ft.row', [self]);
  1688. });
  1689. },
  1690. /**
  1691. * Sets the current row to a collapsed state removing the detail row if it exists.
  1692. * @instance
  1693. * @param {boolean} [setExpanded] - Whether or not to set the {@link FooTable.Row#expanded} property to false.
  1694. * @fires FooTable.Row#"collapse.ft.row"
  1695. */
  1696. collapse: function(setExpanded){
  1697. if (!this.created) return;
  1698. var self = this;
  1699. /**
  1700. * The collapse.ft.row event is raised before the the row is collapsed.
  1701. * Calling preventDefault on this event will stop the row being collapsed.
  1702. * @event FooTable.Row#"collapse.ft.row"
  1703. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  1704. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  1705. * @param {FooTable.Row} row - The row about to be expanded.
  1706. */
  1707. self.ft.raise('collapse.ft.row',[self]).then(function(){
  1708. F.arr.each(self.__hidden__, function(cell){
  1709. cell.restore();
  1710. });
  1711. self.$details.detach();
  1712. self.$el.removeAttr('data-expanded');
  1713. self.$toggle.removeClass('fooicon-minus').addClass('fooicon-plus');
  1714. if (F.is.boolean(setExpanded) ? setExpanded : true) self.expanded = false;
  1715. self.ft.raise('collapsed.ft.row', [self]);
  1716. });
  1717. },
  1718. /**
  1719. * Prior to drawing this moves the details contents back to there original cells and detaches the toggle element from the row.
  1720. * @instance
  1721. * @param {boolean} [detach] - Whether or not to detach the row.
  1722. * @this FooTable.Row
  1723. */
  1724. predraw: function(detach){
  1725. if (this.created){
  1726. if (this.expanded){
  1727. this.collapse(false);
  1728. }
  1729. this.$toggle.detach();
  1730. detach = F.is.boolean(detach) ? detach : true;
  1731. if (detach) this.$el.detach();
  1732. }
  1733. },
  1734. /**
  1735. * Draws the current row and cells.
  1736. * @instance
  1737. * @this FooTable.Row
  1738. */
  1739. draw: function($parent){
  1740. if (!this.created) this.$create();
  1741. if (F.is.jq($parent)) $parent.append(this.$el);
  1742. var self = this;
  1743. F.arr.each(self.cells, function(cell){
  1744. cell.$el.css('display', (cell.column.hidden || !cell.column.visible ? 'none' : 'table-cell'));
  1745. if (self.ft.rows.showToggle && self.ft.columns.hasHidden){
  1746. if ((self.ft.rows.toggleColumn == 'first' && cell.column.index == self.ft.columns.firstVisibleIndex)
  1747. || (self.ft.rows.toggleColumn == 'last' && cell.column.index == self.ft.columns.lastVisibleIndex)) {
  1748. cell.$el.prepend(self.$toggle);
  1749. }
  1750. }
  1751. cell.$el.add(cell.column.$el).removeClass('footable-first-visible footable-last-visible');
  1752. if (cell.column.index == self.ft.columns.firstVisibleIndex){
  1753. cell.$el.add(cell.column.$el).addClass('footable-first-visible');
  1754. }
  1755. if (cell.column.index == self.ft.columns.lastVisibleIndex){
  1756. cell.$el.add(cell.column.$el).addClass('footable-last-visible');
  1757. }
  1758. });
  1759. if (this.expanded){
  1760. this.expand();
  1761. }
  1762. },
  1763. /**
  1764. * Toggles the row between it's expanded and collapsed state if there are hidden columns.
  1765. * @instance
  1766. * @this FooTable.Row
  1767. */
  1768. toggle: function(){
  1769. if (this.created && this.ft.columns.hasHidden){
  1770. if (this.expanded) this.collapse();
  1771. else this.expand();
  1772. }
  1773. },
  1774. /**
  1775. * Handles the toggle click event for rows.
  1776. * @instance
  1777. * @param {jQuery.Event} e - The jQuery.Event object for the click event.
  1778. * @private
  1779. * @this jQuery
  1780. */
  1781. _onToggle: function (e) {
  1782. var self = e.data.self;
  1783. // only execute the toggle if the event.target is one of the approved initiators
  1784. if ($(e.target).is(self.ft.rows.toggleSelector)){
  1785. self.toggle();
  1786. }
  1787. }
  1788. });
  1789. })(jQuery, FooTable);
  1790. (function ($, F) {
  1791. /**
  1792. * An array of all currently loaded instances of the plugin.
  1793. * @protected
  1794. * @readonly
  1795. * @type {Array.<FooTable.Table>}
  1796. */
  1797. F.instances = [];
  1798. F.Table = F.Class.extend(/** @lends FooTable.Table */{
  1799. /**
  1800. * This class is the core of the plugin and drives the logic of all components.
  1801. * @constructs
  1802. * @this FooTable.Table
  1803. * @extends FooTable.Class
  1804. * @param {(HTMLTableElement|jQuery)} element - The element or jQuery table object to bind the plugin to.
  1805. * @param {object} options - The options to initialize the plugin with.
  1806. * @param {function} [ready] - A callback function to execute once the plugin is initialized.
  1807. * @returns {FooTable.Table}
  1808. */
  1809. construct: function (element, options, ready) {
  1810. //BEGIN MEMBERS
  1811. /**
  1812. * The timeout ID for the resize event.
  1813. * @instance
  1814. * @private
  1815. * @type {?number}
  1816. */
  1817. this._resizeTimeout = null;
  1818. /**
  1819. * The ID of the FooTable instance.
  1820. * @instance
  1821. * @type {number}
  1822. */
  1823. this.id = F.instances.push(this);
  1824. /**
  1825. * Whether or not the plugin and all components and add-ons are fully initialized.
  1826. * @instance
  1827. * @type {boolean}
  1828. */
  1829. this.initialized = false;
  1830. /**
  1831. * The jQuery table object the plugin is bound to.
  1832. * @instance
  1833. * @type {jQuery}
  1834. */
  1835. this.$el = (F.is.jq(element) ? element : $(element)).first(); // ensure one table, one instance
  1836. /**
  1837. * A loader jQuery instance
  1838. * @instance
  1839. * @type {jQuery}
  1840. */
  1841. this.$loader = $('<div/>', { 'class': 'footable-loader' }).append($('<span/>', {'class': 'fooicon fooicon-loader'}));
  1842. /**
  1843. * The options for the plugin. This is a merge of user defined options and the default options.
  1844. * @instance
  1845. * @type {object}
  1846. */
  1847. this.o = $.extend(true, {}, F.defaults, options);
  1848. /**
  1849. * The jQuery data object for the table at initialization.
  1850. * @instance
  1851. * @type {object}
  1852. */
  1853. this.data = this.$el.data() || {};
  1854. /**
  1855. * An array of all CSS classes on the table that do not start with "footable".
  1856. * @instance
  1857. * @protected
  1858. * @type {Array.<string>}
  1859. */
  1860. this.classes = [];
  1861. /**
  1862. * All components for this instance of the plugin. These are executed in the order they appear in the array for the initialize phase and in reverse order for the destroy phase of the plugin.
  1863. * @instance
  1864. * @protected
  1865. * @type {object}
  1866. * @prop {Array.<FooTable.Component>} internal - The internal components for the plugin. These are executed either before all other components in the initialize phase or after them in the destroy phase of the plugin.
  1867. * @prop {Array.<FooTable.Component>} core - The core components for the plugin. These are executed either after the internal components in the initialize phase or before them in the destroy phase of the plugin.
  1868. * @prop {Array.<FooTable.Component>} custom - The custom components for the plugin. These are executed either after the core components in the initialize phase or before them in the destroy phase of the plugin.
  1869. */
  1870. this.components = F.components.load((F.is.hash(this.data.components) ? this.data.components : this.o.components), this);
  1871. /**
  1872. * The breakpoints component for this instance of the plugin.
  1873. * @instance
  1874. * @type {FooTable.Breakpoints}
  1875. */
  1876. this.breakpoints = this.use(FooTable.Breakpoints);
  1877. /**
  1878. * The columns component for this instance of the plugin.
  1879. * @instance
  1880. * @type {FooTable.Columns}
  1881. */
  1882. this.columns = this.use(FooTable.Columns);
  1883. /**
  1884. * The rows component for this instance of the plugin.
  1885. * @instance
  1886. * @type {FooTable.Rows}
  1887. */
  1888. this.rows = this.use(FooTable.Rows);
  1889. //END MEMBERS
  1890. this._construct(ready);
  1891. },
  1892. /**
  1893. * Once all properties are set this performs the actual initialization of the plugin calling the {@link FooTable.Table#_preinit} and
  1894. * {@link FooTable.Table#_init} methods as well as raising the {@link FooTable.Table#"ready.ft.table"} event.
  1895. * @this FooTable.Table
  1896. * @instance
  1897. * @param {function} [ready] - A callback function to execute once the plugin is initialized.
  1898. * @private
  1899. * @returns {jQuery.Promise}
  1900. * @fires FooTable.Table#"ready.ft.table"
  1901. */
  1902. _construct: function(ready){
  1903. var self = this;
  1904. return this._preinit().then(function(){
  1905. return self._init().then(function(){
  1906. /**
  1907. * The ready.ft.table event is raised after the plugin has been initialized and the table drawn.
  1908. * Calling preventDefault on this event will stop the ready callback being executed.
  1909. * @event FooTable.Table#"ready.ft.table"
  1910. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  1911. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  1912. */
  1913. return self.raise('ready.ft.table').then(function(){
  1914. if (F.is.fn(ready)) ready.call(self, self);
  1915. });
  1916. });
  1917. }).always(function(arg){
  1918. self.$el.show();
  1919. if (F.is.error(arg)){
  1920. console.error('FooTable: unhandled error thrown during initialization.', arg);
  1921. }
  1922. });
  1923. },
  1924. /**
  1925. * The preinit method is called prior to the plugins actual initialization and provides itself and it's components an opportunity to parse any additional option values.
  1926. * @instance
  1927. * @private
  1928. * @returns {jQuery.Promise}
  1929. * @fires FooTable.Table#"preinit.ft.table"
  1930. */
  1931. _preinit: function(){
  1932. var self = this;
  1933. /**
  1934. * The preinit.ft.table event is raised before any components.
  1935. * Calling preventDefault on this event will disable the entire plugin.
  1936. * @event FooTable.Table#"preinit.ft.table"
  1937. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  1938. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  1939. * @param {object} data - The jQuery data object from the root table element.
  1940. */
  1941. return this.raise('preinit.ft.table', [self.data]).then(function(){
  1942. var classes = (self.$el.attr('class') || '').match(/\S+/g) || [];
  1943. self.o.ajax = F.checkFnValue(self, self.data.ajax, self.o.ajax);
  1944. self.o.stopPropagation = F.is.boolean(self.data.stopPropagation)
  1945. ? self.data.stopPropagation
  1946. : self.o.stopPropagation;
  1947. for (var i = 0, len = classes.length; i < len; i++){
  1948. if (!F.str.startsWith(classes[i], 'footable')) self.classes.push(classes[i]);
  1949. }
  1950. self.$el.hide().after(self.$loader);
  1951. return self.execute(false, false, 'preinit', self.data);
  1952. });
  1953. },
  1954. /**
  1955. * Initializes this instance of the plugin and calls the callback function if one is supplied once complete.
  1956. * @this FooTable.Table
  1957. * @instance
  1958. * @private
  1959. * @return {jQuery.Promise}
  1960. * @fires FooTable.Table#"init.ft.table"
  1961. */
  1962. _init: function(){
  1963. var self = this;
  1964. /**
  1965. * The init.ft.table event is raised before any components are initialized.
  1966. * Calling preventDefault on this event will disable the entire plugin.
  1967. * @event FooTable.Table#"init.ft.table"
  1968. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  1969. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  1970. */
  1971. return self.raise('init.ft.table').then(function(){
  1972. var $thead = self.$el.children('thead'),
  1973. $tbody = self.$el.children('tbody'),
  1974. $tfoot = self.$el.children('tfoot');
  1975. self.$el.addClass('footable footable-' + self.id);
  1976. if (F.is.hash(self.o.on)) self.$el.on(self.o.on);
  1977. if ($tfoot.length == 0) self.$el.append($tfoot = $('<tfoot/>'));
  1978. if ($tbody.length == 0) self.$el.append('<tbody/>');
  1979. if ($thead.length == 0) self.$el.prepend($thead = $('<thead/>'));
  1980. return self.execute(false, true, 'init').then(function(){
  1981. self.$el.data('__FooTable__', self);
  1982. if ($tfoot.children('tr').length == 0) $tfoot.remove();
  1983. if ($thead.children('tr').length == 0) $thead.remove();
  1984. /**
  1985. * The postinit.ft.table event is raised after any components are initialized but before the table is
  1986. * drawn for the first time.
  1987. * Calling preventDefault on this event will disable the initial drawing of the table.
  1988. * @event FooTable.Table#"postinit.ft.table"
  1989. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  1990. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  1991. */
  1992. return self.raise('postinit.ft.table').then(function(){
  1993. return self.draw();
  1994. }).always(function(){
  1995. $(window).off('resize.ft'+self.id, self._onWindowResize)
  1996. .on('resize.ft'+self.id, { self: self }, self._onWindowResize);
  1997. self.initialized = true;
  1998. });
  1999. });
  2000. });
  2001. },
  2002. /**
  2003. * Destroys this plugin removing it from the table.
  2004. * @this FooTable.Table
  2005. * @instance
  2006. * @fires FooTable.Table#"destroy.ft.table"
  2007. */
  2008. destroy: function () {
  2009. var self = this;
  2010. /**
  2011. * The destroy.ft.table event is called before all core components.
  2012. * Calling preventDefault on this event will prevent the entire plugin from being destroyed.
  2013. * @event FooTable.Table#"destroy.ft.table"
  2014. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2015. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2016. */
  2017. return self.raise('destroy.ft.table').then(function(){
  2018. return self.execute(true, true, 'destroy').then(function () {
  2019. self.$el.removeData('__FooTable__').removeClass('footable-' + self.id);
  2020. if (F.is.hash(self.o.on)) self.$el.off(self.o.on);
  2021. $(window).off('resize.ft'+self.id, self._onWindowResize);
  2022. self.initialized = false;
  2023. F.instances[self.id] = null;
  2024. });
  2025. }).fail(function(err){
  2026. if (F.is.error(err)){
  2027. console.error('FooTable: unhandled error thrown while destroying the plugin.', err);
  2028. }
  2029. });
  2030. },
  2031. /**
  2032. * Raises an event on this instance supplying the args array as additional parameters to the handlers.
  2033. * @this FooTable.Table
  2034. * @instance
  2035. * @param {string} eventName - The name of the event to raise, this can include namespaces.
  2036. * @param {Array} [args] - An array containing additional parameters to be passed to any bound handlers.
  2037. * @returns {jQuery.Event}
  2038. */
  2039. raise: function(eventName, args){
  2040. var self = this,
  2041. debug = F.__debug__ && (F.is.emptyArray(F.__debug_options__.events) || F.arr.any(F.__debug_options__.events, function(name){ return F.str.contains(eventName, name); }));
  2042. args = args || [];
  2043. args.unshift(this);
  2044. return $.Deferred(function(d){
  2045. var evt = $.Event(eventName);
  2046. if (self.o.stopPropagation == true){
  2047. self.$el.one(eventName, function (e) {e.stopPropagation();});
  2048. }
  2049. if (debug) console.log('FooTable:'+eventName+': ', args);
  2050. self.$el.trigger(evt, args);
  2051. if (evt.isDefaultPrevented()){
  2052. if (debug) console.log('FooTable: default prevented for the "'+eventName+'" event.');
  2053. d.reject(evt);
  2054. } else d.resolve(evt);
  2055. });
  2056. },
  2057. /**
  2058. * Attempts to retrieve the instance of the supplied component type for this instance.
  2059. * @this FooTable.Table
  2060. * @instance
  2061. * @param {object} type - The content type to retrieve for this instance.
  2062. * @returns {(*|null)}
  2063. */
  2064. use: function(type){
  2065. for (var i = 0, len = this.components.length; i < len; i++){
  2066. if (this.components[i] instanceof type) return this.components[i];
  2067. }
  2068. return null;
  2069. },
  2070. /**
  2071. * Performs the drawing of the table.
  2072. * @this FooTable.Table
  2073. * @instance
  2074. * @protected
  2075. * @returns {jQuery.Promise}
  2076. * @fires FooTable.Table#"predraw.ft.table"
  2077. * @fires FooTable.Table#"draw.ft.table"
  2078. * @fires FooTable.Table#"postdraw.ft.table"
  2079. */
  2080. draw: function () {
  2081. var self = this;
  2082. // Clone the current table and insert it into the original's place
  2083. var $elCopy = self.$el.clone().insertBefore(self.$el);
  2084. // Detach `self.$el` from the DOM, retaining its event handlers
  2085. self.$el.detach();
  2086. // when drawing the order that the components are executed is important so chain the methods but use promises to retain async safety.
  2087. return self.execute(false, true, 'predraw').then(function(){
  2088. /**
  2089. * The predraw.ft.table event is raised after all core components and add-ons have executed there predraw functions but before they execute there draw functions.
  2090. * @event FooTable.Table#"predraw.ft.table"
  2091. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2092. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2093. */
  2094. return self.raise('predraw.ft.table').then(function(){
  2095. return self.execute(false, true, 'draw').then(function(){
  2096. /**
  2097. * The draw.ft.table event is raised after all core components and add-ons have executed there draw functions.
  2098. * @event FooTable.Table#"draw.ft.table"
  2099. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2100. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2101. */
  2102. return self.raise('draw.ft.table').then(function(){
  2103. return self.execute(false, true, 'postdraw').then(function(){
  2104. /**
  2105. * The postdraw.ft.table event is raised after all core components and add-ons have executed there postdraw functions.
  2106. * @event FooTable.Table#"postdraw.ft.table"
  2107. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2108. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2109. */
  2110. return self.raise('postdraw.ft.table');
  2111. });
  2112. });
  2113. });
  2114. });
  2115. }).fail(function(err){
  2116. if (F.is.error(err)){
  2117. console.error('FooTable: unhandled error thrown during a draw operation.', err);
  2118. }
  2119. }).always(function(){
  2120. // Replace the copy that we added above with the modified `self.$el`
  2121. $elCopy.replaceWith(self.$el);
  2122. self.$loader.remove();
  2123. });
  2124. },
  2125. /**
  2126. * Executes the specified method with the optional number of parameters on all components and waits for the promise from each to be resolved before executing the next.
  2127. * @this FooTable.Table
  2128. * @instance
  2129. * @protected
  2130. * @param {boolean} reverse - Whether or not to execute the component methods in the reverse order to what they were registered in.
  2131. * @param {boolean} enabled - Whether or not to execute the method on enabled components only.
  2132. * @param {string} methodName - The name of the method to execute.
  2133. * @param {*} [param1] - The first parameter for the method.
  2134. * @param {...*} [paramN] - Any number of additional parameters for the method.
  2135. * @returns {jQuery.Promise}
  2136. */
  2137. execute: function(reverse, enabled, methodName, param1, paramN){
  2138. var self = this, args = Array.prototype.slice.call(arguments);
  2139. reverse = args.shift();
  2140. enabled = args.shift();
  2141. var components = enabled ? F.arr.get(self.components, function(c){ return c.enabled; }) : self.components.slice(0);
  2142. args.unshift(reverse ? components.reverse() : components);
  2143. return self._execute.apply(self, args);
  2144. },
  2145. /**
  2146. * Executes the specified method with the optional number of parameters on all supplied components waiting for the result of each before executing the next.
  2147. * @this FooTable.Table
  2148. * @instance
  2149. * @private
  2150. * @param {Array.<FooTable.Component>} components - The components to call the method on.
  2151. * @param {string} methodName - The name of the method to execute
  2152. * @param {*} [param1] - The first parameter for the method.
  2153. * @param {...*} [paramN] - Any additional parameters for the method.
  2154. * @returns {jQuery.Promise}
  2155. */
  2156. _execute: function(components, methodName, param1, paramN){
  2157. if (!components || !components.length) return $.when();
  2158. var self = this, args = Array.prototype.slice.call(arguments),
  2159. component;
  2160. components = args.shift();
  2161. methodName = args.shift();
  2162. component = components.shift();
  2163. if (!F.is.fn(component[methodName]))
  2164. return self._execute.apply(self, [components, methodName].concat(args));
  2165. return $.Deferred(function(d){
  2166. try {
  2167. var result = component[methodName].apply(component, args);
  2168. if (F.is.promise(result)){
  2169. return result.then(d.resolve, d.reject);
  2170. } else {
  2171. d.resolve(result);
  2172. }
  2173. } catch (err) {
  2174. d.reject(err);
  2175. }
  2176. }).then(function(){
  2177. return self._execute.apply(self, [components, methodName].concat(args));
  2178. });
  2179. },
  2180. /**
  2181. * Listens to the window resize event and performs a check to see if the breakpoint has changed.
  2182. * @this window
  2183. * @instance
  2184. * @private
  2185. * @fires FooTable.Table#"resize.ft.table"
  2186. */
  2187. _onWindowResize: function (e) {
  2188. var self = e.data.self;
  2189. if (self._resizeTimeout != null) { clearTimeout(self._resizeTimeout); }
  2190. self._resizeTimeout = setTimeout(function () {
  2191. self._resizeTimeout = null;
  2192. /**
  2193. * The resize event is raised a short time after window resize operations cease.
  2194. * @event FooTable.Table#"resize.ft.table"
  2195. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2196. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2197. */
  2198. self.raise('resize.ft.table').then(function(){
  2199. self.breakpoints.check();
  2200. });
  2201. }, 300);
  2202. }
  2203. });
  2204. })(jQuery, FooTable);
  2205. (function($, F){
  2206. F.ArrayColumn = F.Column.extend(/** @lends FooTable.ArrayColumn */{
  2207. /**
  2208. * @summary A column to handle Array values.
  2209. * @constructs
  2210. * @extends FooTable.Column
  2211. * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
  2212. * @param {object} definition - An object containing all the properties to set for the column.
  2213. */
  2214. construct: function(instance, definition) {
  2215. this._super(instance, definition, 'array');
  2216. },
  2217. /**
  2218. * @summary Parses the supplied value or element to retrieve a column value.
  2219. * @description This is supplied either the cell value or jQuery object to parse. This method will return either the Array containing the values or null.
  2220. * @instance
  2221. * @protected
  2222. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  2223. * @returns {(array|null)}
  2224. */
  2225. parser: function(valueOrElement){
  2226. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){ // use jQuery to get the value
  2227. var $el = $(valueOrElement), data = $el.data('value'); // .data() will automatically convert a JSON string to an array
  2228. if (F.is.array(data)) return data;
  2229. data = $el.html();
  2230. try {
  2231. data = JSON.parse(data);
  2232. } catch(err) {
  2233. data = null;
  2234. }
  2235. return F.is.array(data) ? data : null; // if we have an array return it
  2236. }
  2237. if (F.is.array(valueOrElement)) return valueOrElement; // if we have an array return it
  2238. return null; // otherwise we have no value so return null
  2239. },
  2240. /**
  2241. * @summary Formats the column value and creates the HTML seen within a cell.
  2242. * @description This is supplied the value retrieved from the {@link FooTable.ArrayColumn#parser} function and must return a string, HTMLElement or jQuery object.
  2243. * The return value from this function is what is displayed in the cell in the table.
  2244. * @instance
  2245. * @protected
  2246. * @param {?Array} value - The value to format.
  2247. * @param {object} options - The current plugin options.
  2248. * @param {object} rowData - An object containing the current row data.
  2249. * @returns {(string|HTMLElement|jQuery)}
  2250. */
  2251. formatter: function(value, options, rowData){
  2252. return F.is.array(value) ? JSON.stringify(value) : '';
  2253. }
  2254. });
  2255. F.columns.register('array', F.ArrayColumn);
  2256. })(jQuery, FooTable);
  2257. (function($, F){
  2258. if (F.is.undef(window.moment)){
  2259. // The DateColumn requires moment.js to parse and format date values. Goto http://momentjs.com/ to get it.
  2260. return;
  2261. }
  2262. F.DateColumn = F.Column.extend(/** @lends FooTable.DateColumn */{
  2263. /**
  2264. * The date column class is used to handle date values. This column is dependent on [moment.js]{@link http://momentjs.com/} to provide date parsing and formatting functionality.
  2265. * @constructs
  2266. * @extends FooTable.Column
  2267. * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
  2268. * @param {object} definition - An object containing all the properties to set for the column.
  2269. * @returns {FooTable.DateColumn}
  2270. */
  2271. construct: function(instance, definition){
  2272. this._super(instance, definition, 'date');
  2273. /**
  2274. * The format string to use when parsing and formatting dates.
  2275. * @instance
  2276. * @type {string}
  2277. */
  2278. this.formatString = F.is.string(definition.formatString) ? definition.formatString : 'MM-DD-YYYY';
  2279. },
  2280. /**
  2281. * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and will be provided to the {@link FooTable.DateColumn#format} function
  2282. * to generate the cell contents.
  2283. * @instance
  2284. * @protected
  2285. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  2286. * @returns {(moment|null)}
  2287. * @this FooTable.DateColumn
  2288. */
  2289. parser: function(valueOrElement){
  2290. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
  2291. var data = $(valueOrElement).data('value');
  2292. valueOrElement = F.is.defined(data) ? data : $(valueOrElement).text();
  2293. if (F.is.string(valueOrElement)) valueOrElement = isNaN(valueOrElement) ? valueOrElement : +valueOrElement;
  2294. }
  2295. if (F.is.date(valueOrElement)) return moment(valueOrElement);
  2296. if (F.is.object(valueOrElement) && F.is.boolean(valueOrElement._isAMomentObject)) return valueOrElement;
  2297. if (F.is.string(valueOrElement)){
  2298. // if it looks like a number convert it and do nothing else otherwise create a new moment using the string value and formatString
  2299. if (isNaN(valueOrElement)){
  2300. return moment(valueOrElement, this.formatString);
  2301. } else {
  2302. valueOrElement = +valueOrElement;
  2303. }
  2304. }
  2305. if (F.is.number(valueOrElement)){
  2306. return moment(valueOrElement);
  2307. }
  2308. return null;
  2309. },
  2310. /**
  2311. * This is supplied the value retrieved from the {@link FooTable.DateColumn#parser} function and must return a string, HTMLElement or jQuery object.
  2312. * The return value from this function is what is displayed in the cell in the table.
  2313. * @instance
  2314. * @protected
  2315. * @param {*} value - The value to format.
  2316. * @param {object} options - The current plugin options.
  2317. * @param {object} rowData - An object containing the current row data.
  2318. * @returns {(string|HTMLElement|jQuery)}
  2319. * @this FooTable.DateColumn
  2320. */
  2321. formatter: function(value, options, rowData){
  2322. return F.is.object(value) && F.is.boolean(value._isAMomentObject) && value.isValid() ? value.format(this.formatString) : '';
  2323. },
  2324. /**
  2325. * This is supplied either the cell value or jQuery object to parse. A string value must be returned from this method and will be used during filtering operations.
  2326. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  2327. * @returns {string}
  2328. * @this FooTable.DateColumn
  2329. */
  2330. filterValue: function(valueOrElement){
  2331. // if we have an element or a jQuery object use jQuery to get the value
  2332. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)) valueOrElement = $(valueOrElement).data('filterValue') || $(valueOrElement).text();
  2333. // if options are supplied with the value
  2334. if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
  2335. if (F.is.string(valueOrElement.options.filterValue)) valueOrElement = valueOrElement.options.filterValue;
  2336. if (F.is.defined(valueOrElement.value)) valueOrElement = valueOrElement.value;
  2337. }
  2338. // if the value is a moment object just return the formatted value
  2339. if (F.is.object(valueOrElement) && F.is.boolean(valueOrElement._isAMomentObject)) return valueOrElement.format(this.formatString);
  2340. // if its a string
  2341. if (F.is.string(valueOrElement)){
  2342. // if its not a number return it
  2343. if (isNaN(valueOrElement)){
  2344. return valueOrElement;
  2345. } else { // otherwise convert it and carry on
  2346. valueOrElement = +valueOrElement;
  2347. }
  2348. }
  2349. // if the value is a number or date convert to a moment object and return the formatted result.
  2350. if (F.is.number(valueOrElement) || F.is.date(valueOrElement)){
  2351. return moment(valueOrElement).format(this.formatString);
  2352. }
  2353. // try use the native toString of the value if its not undefined or null
  2354. if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement+'';
  2355. return ''; // otherwise we have no value so return an empty string
  2356. }
  2357. });
  2358. F.columns.register('date', F.DateColumn);
  2359. })(jQuery, FooTable);
  2360. (function($, F){
  2361. F.HTMLColumn = F.Column.extend(/** @lends FooTable.HTMLColumn */{
  2362. /**
  2363. * The HTML column class is used to handle any raw HTML columns.
  2364. * @constructs
  2365. * @extends FooTable.Column
  2366. * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
  2367. * @param {object} definition - An object containing all the properties to set for the column.
  2368. * @returns {FooTable.HTMLColumn}
  2369. */
  2370. construct: function(instance, definition){
  2371. this._super(instance, definition, 'html');
  2372. },
  2373. /**
  2374. * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and will be provided to the {@link FooTable.HTMLColumn#format} function
  2375. * to generate the cell contents.
  2376. * @instance
  2377. * @protected
  2378. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  2379. * @returns {(jQuery|null)}
  2380. * @this FooTable.HTMLColumn
  2381. */
  2382. parser: function(valueOrElement){
  2383. if (F.is.string(valueOrElement)) valueOrElement = $($.trim(valueOrElement));
  2384. if (F.is.element(valueOrElement)) valueOrElement = $(valueOrElement);
  2385. if (F.is.jq(valueOrElement)){
  2386. var tagName = valueOrElement.prop('tagName').toLowerCase();
  2387. if (tagName == 'td' || tagName == 'th'){
  2388. var data = valueOrElement.data('value');
  2389. return F.is.defined(data) ? data : valueOrElement.contents();
  2390. }
  2391. return valueOrElement;
  2392. }
  2393. return null;
  2394. }
  2395. });
  2396. F.columns.register('html', F.HTMLColumn);
  2397. })(jQuery, FooTable);
  2398. (function($, F){
  2399. F.NumberColumn = F.Column.extend(/** @lends FooTable.NumberColumn */{
  2400. /**
  2401. * The number column class is used to handle simple number columns.
  2402. * @constructs
  2403. * @extends FooTable.Column
  2404. * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
  2405. * @param {object} definition - An object containing all the properties to set for the column.
  2406. * @returns {FooTable.NumberColumn}
  2407. */
  2408. construct: function(instance, definition){
  2409. this._super(instance, definition, 'number');
  2410. this.decimalSeparator = F.is.string(definition.decimalSeparator) ? definition.decimalSeparator : '.';
  2411. this.thousandSeparator = F.is.string(definition.thousandSeparator) ? definition.thousandSeparator : ',';
  2412. this.decimalSeparatorRegex = new RegExp(F.str.escapeRegExp(this.decimalSeparator), 'g');
  2413. this.thousandSeparatorRegex = new RegExp(F.str.escapeRegExp(this.thousandSeparator), 'g');
  2414. this.cleanRegex = new RegExp('[^\-0-9' + F.str.escapeRegExp(this.decimalSeparator) + ']', 'g');
  2415. },
  2416. /**
  2417. * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and will be provided to the {@link FooTable.Column#formatter} function
  2418. * to generate the cell contents.
  2419. * @instance
  2420. * @protected
  2421. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  2422. * @returns {(number|null)}
  2423. * @this FooTable.NumberColumn
  2424. */
  2425. parser: function(valueOrElement){
  2426. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
  2427. var data = $(valueOrElement).data('value');
  2428. valueOrElement = F.is.defined(data) ? data : $(valueOrElement).text().replace(this.cleanRegex, '');
  2429. }
  2430. if (F.is.string(valueOrElement)){
  2431. valueOrElement = valueOrElement.replace(this.thousandSeparatorRegex, '').replace(this.decimalSeparatorRegex, '.');
  2432. valueOrElement = parseFloat(valueOrElement);
  2433. }
  2434. if (F.is.number(valueOrElement)) return valueOrElement;
  2435. return null;
  2436. },
  2437. /**
  2438. * This is supplied the value retrieved from the {@link FooTable.NumberColumn#parse} function and must return a string, HTMLElement or jQuery object.
  2439. * The return value from this function is what is displayed in the cell in the table.
  2440. * @instance
  2441. * @protected
  2442. * @param {number} value - The value to format.
  2443. * @param {object} options - The current plugin options.
  2444. * @param {object} rowData - An object containing the current row data.
  2445. * @returns {(string|HTMLElement|jQuery)}
  2446. * @this FooTable.NumberColumn
  2447. */
  2448. formatter: function(value, options, rowData){
  2449. if (value == null) return '';
  2450. var s = (value + '').split('.');
  2451. if (s.length == 2 && s[0].length > 3) {
  2452. s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, this.thousandSeparator);
  2453. }
  2454. return s.join(this.decimalSeparator);
  2455. }
  2456. });
  2457. F.columns.register('number', F.NumberColumn);
  2458. })(jQuery, FooTable);
  2459. (function($, F){
  2460. F.ObjectColumn = F.Column.extend(/** @lends FooTable.ObjectColumn */{
  2461. /**
  2462. * @summary A column to handle Object values.
  2463. * @constructs
  2464. * @extends FooTable.Column
  2465. * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
  2466. * @param {object} definition - An object containing all the properties to set for the column.
  2467. */
  2468. construct: function(instance, definition) {
  2469. this._super(instance, definition, 'object');
  2470. },
  2471. /**
  2472. * @summary Parses the supplied value or element to retrieve a column value.
  2473. * @description This is supplied either the cell value or jQuery object to parse. This method will return either the Object containing the values or null.
  2474. * @instance
  2475. * @protected
  2476. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  2477. * @returns {(object|null)}
  2478. */
  2479. parser: function(valueOrElement){
  2480. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){ // use jQuery to get the value
  2481. var $el = $(valueOrElement), data = $el.data('value'); // .data() will automatically convert a JSON string to an object
  2482. if (F.is.object(data)) return data;
  2483. data = $el.html();
  2484. try {
  2485. data = JSON.parse(data);
  2486. } catch(err) {
  2487. data = null;
  2488. }
  2489. return F.is.object(data) ? data : null; // if we have an object return it
  2490. }
  2491. if (F.is.object(valueOrElement)) return valueOrElement; // if we have an object return it
  2492. return null; // otherwise we have no value so return null
  2493. },
  2494. /**
  2495. * @summary Formats the column value and creates the HTML seen within a cell.
  2496. * @description This is supplied the value retrieved from the {@link FooTable.ObjectColumn#parser} function and must return a string, HTMLElement or jQuery object.
  2497. * The return value from this function is what is displayed in the cell in the table.
  2498. * @instance
  2499. * @protected
  2500. * @param {*} value - The value to format.
  2501. * @param {object} options - The current plugin options.
  2502. * @param {object} rowData - An object containing the current row data.
  2503. * @returns {(string|HTMLElement|jQuery)}
  2504. */
  2505. formatter: function(value, options, rowData){
  2506. return F.is.object(value) ? JSON.stringify(value) : '';
  2507. }
  2508. });
  2509. F.columns.register('object', F.ObjectColumn);
  2510. })(jQuery, FooTable);
  2511. (function($, F){
  2512. F.Breakpoint = F.Class.extend(/** @lends FooTable.Breakpoint */{
  2513. /**
  2514. * The breakpoint class containing the name and maximum width for the breakpoint.
  2515. * @constructs
  2516. * @extends FooTable.Class
  2517. * @param {string} name - The name of the breakpoint. Must contain no spaces or special characters.
  2518. * @param {number} width - The width of the breakpoint in pixels.
  2519. * @returns {FooTable.Breakpoint}
  2520. */
  2521. construct: function(name, width){
  2522. /**
  2523. * The name of the breakpoint.
  2524. * @type {string}
  2525. */
  2526. this.name = name;
  2527. /**
  2528. * The maximum width of the breakpoint in pixels.
  2529. * @type {number}
  2530. */
  2531. this.width = width;
  2532. }
  2533. });
  2534. })(jQuery, FooTable);
  2535. (function($, F){
  2536. F.Breakpoints = F.Component.extend(/** @lends FooTable.Breakpoints */{
  2537. /**
  2538. * Contains the logic to calculate and apply breakpoints for the plugin.
  2539. * @constructs
  2540. * @extends FooTable.Component
  2541. * @param {FooTable.Table} table - The parent {@link FooTable.Table} this component belongs to.
  2542. * @returns {FooTable.Breakpoints}
  2543. */
  2544. construct: function(table){
  2545. // call the base class constructor
  2546. this._super(table, true);
  2547. /* PROTECTED */
  2548. /**
  2549. * This provides a shortcut to the {@link FooTable.Table#options} object.
  2550. * @protected
  2551. * @type {FooTable.Table#options}
  2552. */
  2553. this.o = table.o;
  2554. /* PUBLIC */
  2555. /**
  2556. * The current breakpoint.
  2557. * @type {FooTable.Breakpoint}
  2558. */
  2559. this.current = null;
  2560. /**
  2561. * An array of {@link FooTable.Breakpoint} objects created from parsing the options.
  2562. * @type {Array.<FooTable.Breakpoint>}
  2563. */
  2564. this.array = [];
  2565. /**
  2566. * Whether or not breakpoints cascade. When set to true all breakpoints larger than the current will be hidden along with it.
  2567. * @type {boolean}
  2568. */
  2569. this.cascade = this.o.cascade;
  2570. /**
  2571. * Whether or not to calculate breakpoints on the width of the parent element rather than the viewport.
  2572. * @type {boolean}
  2573. */
  2574. this.useParentWidth = this.o.useParentWidth;
  2575. /**
  2576. * This value is updated each time the current breakpoint changes and contains a space delimited string of the names of the current breakpoint and all those smaller than it.
  2577. * @type {string}
  2578. */
  2579. this.hidden = null;
  2580. /* PRIVATE */
  2581. /**
  2582. * This value is set once when the {@link FooTable.Breakpoints#array} is generated and contains a space delimited string of all the breakpoint class names.
  2583. * @type {string}
  2584. * @private
  2585. */
  2586. this._classNames = '';
  2587. // check if a function was supplied to override the default getWidth
  2588. this.getWidth = F.checkFnValue(this, this.o.getWidth, this.getWidth);
  2589. },
  2590. /* PROTECTED */
  2591. /**
  2592. * Checks the supplied data and options for the breakpoints component.
  2593. * @instance
  2594. * @protected
  2595. * @param {object} data - The jQuery data object from the parent table.
  2596. * @fires FooTable.Breakpoints#"preinit.ft.breakpoints"
  2597. */
  2598. preinit: function(data){
  2599. var self = this;
  2600. /**
  2601. * The preinit.ft.breakpoints event is raised before any UI is created and provides the tables jQuery data object for additional options parsing.
  2602. * Calling preventDefault on this event will disable the entire plugin.
  2603. * @event FooTable.Breakpoints#"preinit.ft.breakpoints"
  2604. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2605. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2606. * @param {object} data - The jQuery data object of the table raising the event.
  2607. */
  2608. return this.ft.raise('preinit.ft.breakpoints', [data]).then(function(){
  2609. self.cascade = F.is.boolean(data.cascade) ? data.cascade : self.cascade;
  2610. self.o.breakpoints = F.is.hash(data.breakpoints) ? data.breakpoints : self.o.breakpoints;
  2611. self.getWidth = F.checkFnValue(self, data.getWidth, self.getWidth);
  2612. if (self.o.breakpoints == null) self.o.breakpoints = { "xs": 480, "sm": 768, "md": 992, "lg": 1200 };
  2613. // Create a nice friendly array to work with out of the breakpoints object.
  2614. for (var name in self.o.breakpoints) {
  2615. if (!self.o.breakpoints.hasOwnProperty(name)) continue;
  2616. self.array.push(new F.Breakpoint(name, self.o.breakpoints[name]));
  2617. self._classNames += 'breakpoint-' + name + ' ';
  2618. }
  2619. // Sort the breakpoints so the largest is checked first
  2620. self.array.sort(function (a, b) {
  2621. return b.width - a.width;
  2622. });
  2623. });
  2624. },
  2625. /**
  2626. * Initializes the class parsing the options into a sorted array of {@link FooTable.Breakpoint} objects.
  2627. * @instance
  2628. * @protected
  2629. * @fires FooTable.Breakpoints#"init.ft.breakpoints"
  2630. */
  2631. init: function(){
  2632. var self = this;
  2633. /**
  2634. * The init.ft.breakpoints event is raised before any UI is generated.
  2635. * Calling preventDefault on this event will disable the entire plugin.
  2636. * @event FooTable.Breakpoints#"init.ft.breakpoints"
  2637. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2638. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2639. */
  2640. return this.ft.raise('init.ft.breakpoints').then(function(){
  2641. self.current = self.get();
  2642. });
  2643. },
  2644. /**
  2645. * Whenever the table is drawn this ensures the correct breakpoint class is applied to the table.
  2646. * @instance
  2647. * @protected
  2648. */
  2649. draw: function(){
  2650. this.ft.$el.removeClass(this._classNames).addClass('breakpoint-' + this.current.name);
  2651. },
  2652. /* PUBLIC */
  2653. /**
  2654. * Calculates the current breakpoint from the {@link FooTable.Breakpoints#array} and sets the {@link FooTable.Breakpoints#current} property.
  2655. * @instance
  2656. * @returns {FooTable.Breakpoint}
  2657. */
  2658. calculate: function(){
  2659. var self = this, current = null, hidden = [], breakpoint, prev = null, width = self.getWidth();
  2660. for (var i = 0, len = self.array.length; i < len; i++) {
  2661. breakpoint = self.array[i];
  2662. // if the width is smaller than the smallest breakpoint set the smallest as the current.
  2663. // if the width is larger than the largest breakpoint set the largest as the current.
  2664. // otherwise if the width is somewhere in between check all breakpoints testing if the width
  2665. // is greater than the current but smaller than the previous.
  2666. if ((!current && i == len -1)
  2667. || (width >= breakpoint.width && (prev instanceof F.Breakpoint ? width < prev.width : true))) {
  2668. current = breakpoint;
  2669. }
  2670. if (!current) hidden.push(breakpoint.name);
  2671. prev = breakpoint;
  2672. }
  2673. hidden.push(current.name);
  2674. self.hidden = hidden.join(' ');
  2675. return current;
  2676. },
  2677. /**
  2678. * Supplied a columns breakpoints this returns a boolean value indicating whether or not the column is visible.
  2679. * @param {string} breakpoints - A space separated string of breakpoint names.
  2680. * @returns {boolean}
  2681. */
  2682. visible: function(breakpoints){
  2683. if (F.is.emptyString(breakpoints)) return true;
  2684. if (breakpoints === 'all') return false;
  2685. var parts = breakpoints.split(' '), i = 0, len = parts.length;
  2686. for (; i < len; i++){
  2687. if (this.cascade ? F.str.containsWord(this.hidden, parts[i]) : parts[i] == this.current.name) return false;
  2688. }
  2689. return true;
  2690. },
  2691. /**
  2692. * Performs a check between the current breakpoint and the previous breakpoint and performs a redraw if they differ.
  2693. * @instance
  2694. * @fires FooTable.Breakpoints#"before.ft.breakpoints"
  2695. * @fires FooTable.Breakpoints#"after.ft.breakpoints"
  2696. */
  2697. check: function(){
  2698. var self = this, bp = self.get();
  2699. if (!(bp instanceof F.Breakpoint)
  2700. || bp == self.current)
  2701. return;
  2702. /**
  2703. * The before.ft.breakpoints event is raised if the breakpoint has changed but before the UI is redrawn and is supplied both the current breakpoint
  2704. * and the next "new" one that is about to be applied.
  2705. * Calling preventDefault on this event will prevent the next breakpoint from being applied.
  2706. * @event FooTable.Breakpoints#"before.ft.breakpoints"
  2707. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2708. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2709. * @param {FooTable.Breakpoint} current - The current breakpoint.
  2710. * @param {FooTable.Breakpoint} next - The breakpoint that is about to be applied.
  2711. */
  2712. self.ft.raise('before.ft.breakpoints', [self.current, bp]).then(function(){
  2713. var previous = self.current;
  2714. self.current = bp;
  2715. return self.ft.draw().then(function(){
  2716. /**
  2717. * The after.ft.breakpoints event is raised after the breakpoint has changed and the UI is redrawn and is supplied both the "new" current breakpoint
  2718. * and the previous one that was replaced.
  2719. * @event FooTable.Breakpoints#"after.ft.breakpoints"
  2720. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2721. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2722. * @param {FooTable.Breakpoint} current - The current breakpoint.
  2723. * @param {FooTable.Breakpoint} previous - The breakpoint that was just replaced.
  2724. */
  2725. self.ft.raise('after.ft.breakpoints', [self.current, previous]);
  2726. });
  2727. });
  2728. },
  2729. /**
  2730. * Attempts to return a {@link FooTable.Breakpoint} instance when passed a {@link FooTable.Breakpoint},
  2731. * the {@link FooTable.Breakpoint#name} string or if nothing is supplied the current breakpoint.
  2732. * @instance
  2733. * @param {(FooTable.Breakpoint|string|number)} [breakpoint] - The breakpoint to retrieve.
  2734. * @returns {FooTable.Breakpoint}
  2735. */
  2736. get: function(breakpoint){
  2737. if (F.is.undef(breakpoint)) return this.calculate();
  2738. if (breakpoint instanceof F.Breakpoint) return breakpoint;
  2739. if (F.is.string(breakpoint)) return F.arr.first(this.array, function (bp) { return bp.name == breakpoint; });
  2740. if (F.is.number(breakpoint)) return breakpoint >= 0 && breakpoint < this.array.length ? this.array[breakpoint] : null;
  2741. return null;
  2742. },
  2743. /**
  2744. * Gets the width used to determine breakpoints whether it be from the viewport, parent or a custom function.
  2745. * @instance
  2746. * @returns {number}
  2747. */
  2748. getWidth: function(){
  2749. if (F.is.fn(this.o.getWidth)) return this.o.getWidth(this.ft);
  2750. if (this.useParentWidth == true) return this.getParentWidth();
  2751. return this.getViewportWidth();
  2752. },
  2753. /**
  2754. * Gets the tables direct parents width.
  2755. * @instance
  2756. * @returns {number}
  2757. */
  2758. getParentWidth: function(){
  2759. return this.ft.$el.parent().width();
  2760. },
  2761. /**
  2762. * Gets the current viewport width.
  2763. * @instance
  2764. * @returns {number}
  2765. */
  2766. getViewportWidth: function(){
  2767. return Math.max(document.documentElement.clientWidth, window.innerWidth, 0);
  2768. }
  2769. });
  2770. F.components.register('breakpoints', F.Breakpoints, 1000);
  2771. })(jQuery, FooTable);
  2772. (function(F){
  2773. /**
  2774. * A space delimited string of breakpoint names that specify when the column will be hidden. You can also specify "all" to make a column permanently display in an expandable detail row.
  2775. * @type {string}
  2776. * @default null
  2777. * @example <caption>The below shows how this value would be set</caption>
  2778. * breakpoints: "md"
  2779. */
  2780. F.Column.prototype.breakpoints = null;
  2781. F.Column.prototype.__breakpoints_define__ = function(definition){
  2782. this.breakpoints = F.is.emptyString(definition.breakpoints) ? null : definition.breakpoints;
  2783. };
  2784. F.Column.extend('define', function(definition){
  2785. this._super(definition);
  2786. this.__breakpoints_define__(definition);
  2787. });
  2788. })(FooTable);
  2789. (function(F){
  2790. /**
  2791. * An object containing the breakpoints for the plugin.
  2792. * @type {object.<string, number>}
  2793. * @default { "xs": 480, "sm": 768, "md": 992, "lg": 1200 }
  2794. */
  2795. F.Defaults.prototype.breakpoints = null;
  2796. /**
  2797. * Whether or not breakpoints cascade. When set to true all breakpoints larger than the current will also be hidden along with it.
  2798. * @type {boolean}
  2799. * @default false
  2800. */
  2801. F.Defaults.prototype.cascade = false;
  2802. /**
  2803. * Whether or not to calculate breakpoints on the width of the parent element rather than the viewport.
  2804. * @type {boolean}
  2805. * @default false
  2806. */
  2807. F.Defaults.prototype.useParentWidth = false;
  2808. /**
  2809. * A function used to override the default getWidth function with a custom one.
  2810. * @type {function}
  2811. * @default null
  2812. * @example <caption>The below shows what the default getWidth function would look like.</caption>
  2813. * getWidth: function(instance){
  2814. * if (instance.o.useParentWidth == true) return instance.$el.parent().width();
  2815. * return instance.breakpoints.getViewportWidth();
  2816. * }
  2817. */
  2818. F.Defaults.prototype.getWidth = null;
  2819. })(FooTable);
  2820. (function($, F){
  2821. F.Columns = F.Component.extend(/** @lends FooTable.Columns */{
  2822. /**
  2823. * The columns class contains all the logic for handling columns.
  2824. * @constructs
  2825. * @extends FooTable.Component
  2826. * @param {FooTable.Table} table - The parent {@link FooTable.Table} this component belongs to.
  2827. * @returns {FooTable.Columns}
  2828. */
  2829. construct: function(table){
  2830. // call the base class constructor
  2831. this._super(table, true);
  2832. /* PROTECTED */
  2833. /**
  2834. * This provides a shortcut to the {@link FooTable.Table#options} object.
  2835. * @protected
  2836. * @type {FooTable.Table#options}
  2837. */
  2838. this.o = table.o;
  2839. /* PUBLIC */
  2840. /**
  2841. * An array of {@link FooTable.Column} objects created from parsing the options and/or DOM.
  2842. * @type {Array.<FooTable.Column>}
  2843. */
  2844. this.array = [];
  2845. /**
  2846. * The jQuery header row object.
  2847. * @type {jQuery}
  2848. */
  2849. this.$header = null;
  2850. /**
  2851. * Whether or not to display the header row.
  2852. * @type {boolean}
  2853. */
  2854. this.showHeader = table.o.showHeader;
  2855. this._fromHTML = F.is.emptyArray(table.o.columns) && !F.is.promise(table.o.columns);
  2856. },
  2857. /* PROTECTED */
  2858. /**
  2859. * This parses the columns from either the tables rows or the supplied options.
  2860. * @instance
  2861. * @protected
  2862. * @param {object} data - The tables jQuery data object.
  2863. * @returns {jQuery.Promise}
  2864. * @this FooTable.Columns
  2865. */
  2866. parse: function(data){
  2867. var self = this;
  2868. return $.Deferred(function(d){
  2869. function merge(cols1, cols2){
  2870. var merged = [];
  2871. // check if either of the arrays is empty as it can save us having to merge them by index.
  2872. if (cols1.length == 0 || cols2.length == 0){
  2873. merged = cols1.concat(cols2);
  2874. } else {
  2875. // at this point we have two arrays of column definitions, we now need to merge them based on there index properties
  2876. // first figure out the highest column index provided so we can loop that many times to merge all columns and provide
  2877. // defaults where nothing was specified (fill in the gaps in the array as it were).
  2878. var highest = 0;
  2879. F.arr.each(cols1.concat(cols2), function(c){
  2880. if (c.index > highest) highest = c.index;
  2881. });
  2882. highest++;
  2883. for (var i = 0, cols1_c, cols2_c; i < highest; i++){
  2884. cols1_c = {};
  2885. F.arr.each(cols1, function(c){
  2886. if (c.index == i){
  2887. cols1_c = c;
  2888. return false;
  2889. }
  2890. });
  2891. cols2_c = {};
  2892. F.arr.each(cols2, function(c){
  2893. if (c.index == i){
  2894. cols2_c = c;
  2895. return false;
  2896. }
  2897. });
  2898. merged.push($.extend(true, {}, cols1_c, cols2_c));
  2899. }
  2900. }
  2901. return merged;
  2902. }
  2903. var json = [], html = [];
  2904. // get the column options from the content
  2905. var $header = self.ft.$el.find('tr.footable-header, thead > tr:last:has([data-breakpoints]), tbody > tr:first:has([data-breakpoints]), thead > tr:last, tbody > tr:first').first(), $cell, cdata;
  2906. if ($header.length > 0){
  2907. var virtual = $header.parent().is('tbody') && $header.children().length == $header.children('td').length;
  2908. if (!virtual) self.$header = $header.addClass('footable-header');
  2909. $header.children('td,th').each(function(i, cell){
  2910. $cell = $(cell);
  2911. cdata = $cell.data();
  2912. cdata.index = i;
  2913. cdata.$el = $cell;
  2914. cdata.virtual = virtual;
  2915. html.push(cdata);
  2916. });
  2917. if (virtual) self.showHeader = false;
  2918. }
  2919. // get the supplied column options
  2920. if (F.is.array(self.o.columns) && !F.is.emptyArray(self.o.columns)){
  2921. F.arr.each(self.o.columns, function(c, i){
  2922. c.index = i;
  2923. json.push(c);
  2924. });
  2925. self.parseFinalize(d, merge(json, html));
  2926. } else if (F.is.promise(self.o.columns)){
  2927. self.o.columns.then(function(cols){
  2928. F.arr.each(cols, function(c, i){
  2929. c.index = i;
  2930. json.push(c);
  2931. });
  2932. self.parseFinalize(d, merge(json, html));
  2933. }, function(xhr){
  2934. d.reject(Error('Columns ajax request error: ' + xhr.status + ' (' + xhr.statusText + ')'));
  2935. });
  2936. } else {
  2937. self.parseFinalize(d, merge(json, html));
  2938. }
  2939. });
  2940. },
  2941. /**
  2942. * Used to finalize the parsing of columns it is supplied the parse deferred object which must be resolved with an array of {@link FooTable.Column} objects
  2943. * or rejected with an error.
  2944. * @instance
  2945. * @protected
  2946. * @param {jQuery.Deferred} deferred - The deferred object used for parsing.
  2947. * @param {Array.<object>} cols - An array of all merged column definitions.
  2948. */
  2949. parseFinalize: function(deferred, cols){
  2950. // we now have a merged array of all column definitions supplied to the plugin, time to make the objects.
  2951. var self = this, columns = [], column;
  2952. F.arr.each(cols, function(def){
  2953. // if we have a column registered using the definition type then create an instance of that column otherwise just create a default text column.
  2954. if (column = F.columns.contains(def.type) ? F.columns.make(def.type, self.ft, def) : new F.Column(self.ft, def))
  2955. columns.push(column);
  2956. });
  2957. if (F.is.emptyArray(columns)){
  2958. deferred.reject(Error("No columns supplied."));
  2959. } else {
  2960. // make sure to sort by the column index as the merge process may have mixed them up
  2961. columns.sort(function(a, b){ return a.index - b.index; });
  2962. deferred.resolve(columns);
  2963. }
  2964. },
  2965. /**
  2966. * The columns preinit method is used to parse and check the column options supplied from both static content and through the constructor.
  2967. * @instance
  2968. * @protected
  2969. * @param {object} data - The jQuery data object from the root table element.
  2970. * @this FooTable.Columns
  2971. */
  2972. preinit: function(data){
  2973. var self = this;
  2974. /**
  2975. * The preinit.ft.columns event is raised before any UI is created and provides the tables jQuery data object for additional options parsing.
  2976. * Calling preventDefault on this event will disable the entire plugin.
  2977. * @event FooTable.Columns#"preinit.ft.columns"
  2978. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  2979. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  2980. * @param {object} data - The jQuery data object of the table raising the event.
  2981. */
  2982. return self.ft.raise('preinit.ft.columns', [data]).then(function(){
  2983. return self.parse(data).then(function(columns){
  2984. self.array = columns;
  2985. self.showHeader = F.is.boolean(data.showHeader) ? data.showHeader : self.showHeader;
  2986. });
  2987. });
  2988. },
  2989. /**
  2990. * Initializes the columns creating the table header if required.
  2991. * @instance
  2992. * @protected
  2993. * @fires FooTable.Columns#"init.ft.columns"
  2994. * @this FooTable.Columns
  2995. */
  2996. init: function(){
  2997. var self = this;
  2998. /**
  2999. * The init.ft.columns event is raised after the header row is created/parsed for column data.
  3000. * @event FooTable.Columns#"init.ft.columns"
  3001. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3002. * @param {FooTable.Table} instance - The instance of the plugin raising the event.
  3003. * @param {Array.<FooTable.Column>} columns - The array of {@link FooTable.Column} objects parsed from the options and/or DOM.
  3004. */
  3005. return this.ft.raise('init.ft.columns', [ self.array ]).then(function(){
  3006. self.$create();
  3007. });
  3008. },
  3009. /**
  3010. * Destroys the columns component removing any UI generated from the table.
  3011. * @instance
  3012. * @protected
  3013. * @fires FooTable.Columns#"destroy.ft.columns"
  3014. */
  3015. destroy: function(){
  3016. /**
  3017. * The destroy.ft.columns event is raised before its UI is removed.
  3018. * Calling preventDefault on this event will prevent the component from being destroyed.
  3019. * @event FooTable.Columns#"destroy.ft.columns"
  3020. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3021. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  3022. */
  3023. var self = this;
  3024. this.ft.raise('destroy.ft.columns').then(function(){
  3025. if (!self._fromHTML) self.$header.remove();
  3026. });
  3027. },
  3028. /**
  3029. * The predraw method called from within the {@link FooTable.Table#draw} method.
  3030. * @instance
  3031. * @protected
  3032. * @this FooTable.Columns
  3033. */
  3034. predraw: function(){
  3035. var self = this, first = true;
  3036. self.visibleColspan = 0;
  3037. self.firstVisibleIndex = 0;
  3038. self.lastVisibleIndex = 0;
  3039. self.hasHidden = false;
  3040. F.arr.each(self.array, function(col){
  3041. col.hidden = !self.ft.breakpoints.visible(col.breakpoints);
  3042. if (!col.hidden && col.visible){
  3043. if (first){
  3044. self.firstVisibleIndex = col.index;
  3045. first = false;
  3046. }
  3047. self.lastVisibleIndex = col.index;
  3048. self.visibleColspan++;
  3049. }
  3050. if (col.hidden) self.hasHidden = true;
  3051. });
  3052. self.ft.$el.toggleClass('breakpoint', self.hasHidden);
  3053. },
  3054. /**
  3055. * Performs the actual drawing of the columns, hiding or displaying them depending on there breakpoints.
  3056. * @instance
  3057. * @protected
  3058. * @this FooTable.Columns
  3059. */
  3060. draw: function(){
  3061. F.arr.each(this.array, function(col){
  3062. col.$el.css('display', (col.hidden || !col.visible ? 'none' : 'table-cell'));
  3063. });
  3064. if (!this.showHeader && F.is.jq(this.$header.parent())){
  3065. this.$header.detach();
  3066. }
  3067. },
  3068. /**
  3069. * Creates the header row for the table from the parsed column definitions.
  3070. * @instance
  3071. * @protected
  3072. * @this FooTable.Columns
  3073. */
  3074. $create: function(){
  3075. var self = this;
  3076. self.$header = F.is.jq(self.$header) ? self.$header : $('<tr/>', {'class': 'footable-header'});
  3077. self.$header.children('th,td').detach();
  3078. F.arr.each(self.array, function(col){
  3079. self.$header.append(col.$el);
  3080. });
  3081. if (self.showHeader && !F.is.jq(self.$header.parent())){
  3082. self.ft.$el.children('thead').append(self.$header);
  3083. }
  3084. },
  3085. /**
  3086. * Attempts to return a {@link FooTable.Column} instance when passed the {@link FooTable.Column} instance, the {@link FooTable.Column#name} string or the {@link FooTable.Column#index} number.
  3087. * If supplied a function this will return an array by iterating all columns passing the index and column itself to the supplied callback as arguments.
  3088. * Returning true in the callback will include the column in the result.
  3089. * @instance
  3090. * @param {(FooTable.Column|string|number|function)} column - The column to retrieve.
  3091. * @returns {(Array.<FooTable.Column>|FooTable.Column|null)} The column if one is found otherwise it returns NULL.
  3092. * @example <caption>This example shows retrieving a column by name assuming a column called "id" exists. The <code>columns</code> object is an instance of {@link FooTable.Columns}.</caption>
  3093. * var column = columns.get('id');
  3094. * if (column instanceof FooTable.Column){
  3095. * // found the "id" column
  3096. * } else {
  3097. * // no column with a name of "id" exists
  3098. * }
  3099. * // to get an array of all hidden columns
  3100. * var columns = columns.get(function(col){
  3101. * return col.hidden;
  3102. * });
  3103. */
  3104. get: function(column){
  3105. if (column instanceof F.Column) return column;
  3106. if (F.is.string(column)) return F.arr.first(this.array, function (col) { return col.name == column; });
  3107. if (F.is.number(column)) return F.arr.first(this.array, function (col) { return col.index == column; });
  3108. if (F.is.fn(column)) return F.arr.get(this.array, column);
  3109. return null;
  3110. },
  3111. /**
  3112. * Takes an array of column names, index's or actual {@link FooTable.Column} and ensures that an array of only {@link FooTable.Column} is returned.
  3113. * @instance
  3114. * @param {(Array.<string>|Array.<number>|Array.<FooTable.Column>)} columns - The array of column names, index's or {@link FooTable.Column} to check.
  3115. * @returns {Array.<FooTable.Column>}
  3116. */
  3117. ensure: function(columns){
  3118. var self = this, result = [];
  3119. if (!F.is.array(columns)) return result;
  3120. F.arr.each(columns, function(name){
  3121. result.push(self.get(name));
  3122. });
  3123. return result;
  3124. }
  3125. });
  3126. F.components.register('columns', F.Columns, 900);
  3127. })(jQuery, FooTable);
  3128. (function(F){
  3129. /**
  3130. * An array containing the column options or a jQuery promise that resolves returning the columns. The index of the definitions must match the index of each column as it should appear in the table. For more information on the options available see the {@link FooTable.Column} object.
  3131. * @type {(Array.<object>|jQuery.Promise)}
  3132. * @default []
  3133. * @example <caption>The below shows column definitions for a row defined as <code>{ id: Number, name: String, age: Number }</code>. The ID column has a fixed width, the table is initially sorted on the Name column and the Age column will be hidden on phones.</caption>
  3134. * columns: [
  3135. * { name: 'id', title: 'ID', type: 'number' },
  3136. * { name: 'name', title: 'Name', sorted: true, direction: 'ASC' }
  3137. * { name: 'age', title: 'Age', type: 'number', breakpoints: 'xs' }
  3138. * ]
  3139. */
  3140. F.Defaults.prototype.columns = [];
  3141. /**
  3142. * Specifies whether or not the column headers should be displayed.
  3143. * @type {boolean}
  3144. * @default true
  3145. */
  3146. F.Defaults.prototype.showHeader = true;
  3147. })(FooTable);
  3148. (function ($, F) {
  3149. F.Rows = F.Component.extend(/** @lends FooTable.Rows */{
  3150. /**
  3151. * The rows class contains all the logic for handling rows.
  3152. * @constructs
  3153. * @extends FooTable.Component
  3154. * @param {FooTable.Table} table - The parent {@link FooTable.Table} this component belongs to.
  3155. * @returns {FooTable.Rows}
  3156. */
  3157. construct: function (table) {
  3158. // call the base class constructor
  3159. this._super(table, true);
  3160. /**
  3161. * This provides a shortcut to the {@link FooTable.Table#options} object.
  3162. * @instance
  3163. * @protected
  3164. * @type {FooTable.Table#options}
  3165. */
  3166. this.o = table.o;
  3167. /**
  3168. * The current working array of {@link FooTable.Row} objects.
  3169. * @instance
  3170. * @protected
  3171. * @type {Array.<FooTable.Row>}
  3172. * @default []
  3173. */
  3174. this.array = [];
  3175. /**
  3176. * The base array of rows parsed from either the DOM or the constructor options.
  3177. * The {@link FooTable.Rows#current} member is populated with a shallow clone of this array
  3178. * during the predraw operation before any core or custom components are executed.
  3179. * @instance
  3180. * @protected
  3181. * @type {Array.<FooTable.Row>}
  3182. * @default []
  3183. */
  3184. this.all = [];
  3185. /**
  3186. * Whether or not to display a toggle in each row when it contains hidden columns.
  3187. * @type {boolean}
  3188. * @default true
  3189. */
  3190. this.showToggle = table.o.showToggle;
  3191. /**
  3192. * The CSS selector used to filter row click events. If the event.target property matches the selector the row will be toggled.
  3193. * @type {string}
  3194. * @default "tr,td,.footable-toggle"
  3195. */
  3196. this.toggleSelector = table.o.toggleSelector;
  3197. /**
  3198. * Specifies which column the row toggle is appended to. Supports only two values; "first" and "last"
  3199. * @type {string}
  3200. */
  3201. this.toggleColumn = table.o.toggleColumn;
  3202. /**
  3203. * The text to display when the table has no rows.
  3204. * @type {string}
  3205. */
  3206. this.emptyString = table.o.empty;
  3207. /**
  3208. * Whether or not the first rows details are expanded by default when displayed on a device that hides any columns.
  3209. * @type {boolean}
  3210. */
  3211. this.expandFirst = table.o.expandFirst;
  3212. /**
  3213. * Whether or not all row details are expanded by default when displayed on a device that hides any columns.
  3214. * @type {boolean}
  3215. */
  3216. this.expandAll = table.o.expandAll;
  3217. /**
  3218. * The jQuery object that contains the empty row control.
  3219. * @type {jQuery}
  3220. */
  3221. this.$empty = null;
  3222. this._fromHTML = F.is.emptyArray(table.o.rows) && !F.is.promise(table.o.rows);
  3223. },
  3224. /**
  3225. * This parses the rows from either the tables rows or the supplied options.
  3226. * @instance
  3227. * @protected
  3228. * @returns {jQuery.Promise}
  3229. */
  3230. parse: function(){
  3231. var self = this;
  3232. return $.Deferred(function(d){
  3233. var $rows = self.ft.$el.children('tbody').children('tr');
  3234. if (F.is.array(self.o.rows) && self.o.rows.length > 0){
  3235. self.parseFinalize(d, self.o.rows);
  3236. } else if (F.is.promise(self.o.rows)){
  3237. self.o.rows.then(function(rows){
  3238. self.parseFinalize(d, rows);
  3239. }, function(xhr){
  3240. d.reject(Error('Rows ajax request error: ' + xhr.status + ' (' + xhr.statusText + ')'));
  3241. });
  3242. } else if (F.is.jq($rows)){
  3243. self.parseFinalize(d, $rows);
  3244. $rows.detach();
  3245. } else {
  3246. self.parseFinalize(d, []);
  3247. }
  3248. });
  3249. },
  3250. /**
  3251. * Used to finalize the parsing of rows it is supplied the parse deferred object which must be resolved with an array of {@link FooTable.Row} objects
  3252. * or rejected with an error.
  3253. * @instance
  3254. * @protected
  3255. * @param {jQuery.Deferred} deferred - The deferred object used for parsing.
  3256. * @param {(Array.<object>|jQuery)} rows - An array of row values and options or the jQuery object containing all rows.
  3257. */
  3258. parseFinalize: function(deferred, rows){
  3259. var self = this, result = $.map(rows, function(r){
  3260. return new F.Row(self.ft, self.ft.columns.array, r);
  3261. });
  3262. deferred.resolve(result);
  3263. },
  3264. /**
  3265. * The columns preinit method is used to parse and check the column options supplied from both static content and through the constructor.
  3266. * @instance
  3267. * @protected
  3268. * @param {object} data - The jQuery data object from the root table element.
  3269. * @fires FooTable.Rows#"preinit.ft.rows"
  3270. */
  3271. preinit: function(data){
  3272. var self = this;
  3273. /**
  3274. * The preinit.ft.rows event is raised before any UI is created and provides the tables jQuery data object for additional options parsing.
  3275. * Calling preventDefault on this event will disable the entire plugin.
  3276. * @event FooTable.Rows#"preinit.ft.rows"
  3277. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3278. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  3279. * @param {object} data - The jQuery data object of the table raising the event.
  3280. */
  3281. return self.ft.raise('preinit.ft.rows', [data]).then(function(){
  3282. return self.parse().then(function(rows){
  3283. self.all = rows;
  3284. self.array = self.all.slice(0);
  3285. self.showToggle = F.is.boolean(data.showToggle) ? data.showToggle : self.showToggle;
  3286. self.toggleSelector = F.is.string(data.toggleSelector) ? data.toggleSelector : self.toggleSelector;
  3287. self.toggleColumn = F.is.string(data.toggleColumn) ? data.toggleColumn : self.toggleColumn;
  3288. if (self.toggleColumn != "first" && self.toggleColumn != "last") self.toggleColumn = "first";
  3289. self.emptyString = F.is.string(data.empty) ? data.empty : self.emptyString;
  3290. self.expandFirst = F.is.boolean(data.expandFirst) ? data.expandFirst : self.expandFirst;
  3291. self.expandAll = F.is.boolean(data.expandAll) ? data.expandAll : self.expandAll;
  3292. });
  3293. });
  3294. },
  3295. /**
  3296. * Initializes the rows class using the supplied table and options.
  3297. * @instance
  3298. * @protected
  3299. * @fires FooTable.Rows#"init.ft.rows"
  3300. */
  3301. init: function () {
  3302. var self = this;
  3303. /**
  3304. * The init.ft.rows event is raised after the the rows are parsed from either the DOM or the options.
  3305. * Calling preventDefault on this event will disable the entire plugin.
  3306. * @event FooTable.Rows#"init.ft.rows"
  3307. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3308. * @param {FooTable.Table} instance - The instance of the plugin raising the event.
  3309. * @param {Array.<FooTable.Row>} rows - The array of {@link FooTable.Row} objects parsed from the DOM or the options.
  3310. */
  3311. return self.ft.raise('init.ft.rows', [self.all]).then(function(){
  3312. self.$create();
  3313. });
  3314. },
  3315. /**
  3316. * Destroys the rows component removing any UI generated from the table.
  3317. * @instance
  3318. * @protected
  3319. * @fires FooTable.Rows#"destroy.ft.rows"
  3320. */
  3321. destroy: function(){
  3322. /**
  3323. * The destroy.ft.rows event is raised before its UI is removed.
  3324. * Calling preventDefault on this event will prevent the component from being destroyed.
  3325. * @event FooTable.Rows#"destroy.ft.rows"
  3326. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3327. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  3328. */
  3329. var self = this;
  3330. this.ft.raise('destroy.ft.rows').then(function(){
  3331. F.arr.each(self.array, function(row){
  3332. row.predraw(!self._fromHTML);
  3333. });
  3334. self.all = self.array = [];
  3335. });
  3336. },
  3337. /**
  3338. * Performs the predraw operations that are required including creating the shallow clone of the {@link FooTable.Rows#array} to work with.
  3339. * @instance
  3340. * @protected
  3341. */
  3342. predraw: function(){
  3343. F.arr.each(this.array, function(row){
  3344. row.predraw();
  3345. });
  3346. this.array = this.all.slice(0);
  3347. },
  3348. $create: function(){
  3349. this.$empty = $('<tr/>', { 'class': 'footable-empty' }).append($('<td/>').text(this.emptyString));
  3350. },
  3351. /**
  3352. * Performs the actual drawing of the table rows.
  3353. * @instance
  3354. * @protected
  3355. */
  3356. draw: function(){
  3357. var self = this, $tbody = self.ft.$el.children('tbody'), first = true;
  3358. // if we have rows
  3359. if (self.array.length > 0){
  3360. self.$empty.detach();
  3361. // loop through them appending to the tbody and then drawing
  3362. F.arr.each(self.array, function(row){
  3363. if ((self.expandFirst && first) || self.expandAll){
  3364. row.expanded = true;
  3365. first = false;
  3366. }
  3367. row.draw($tbody);
  3368. });
  3369. } else {
  3370. // otherwise display the $empty row
  3371. self.$empty.children('td').attr('colspan', self.ft.columns.visibleColspan);
  3372. $tbody.append(self.$empty);
  3373. }
  3374. },
  3375. /**
  3376. * Loads a JSON array of row objects into the table
  3377. * @instance
  3378. * @param {Array.<object>} data - An array of row objects to load.
  3379. * @param {boolean} [append=false] - Whether or not to append the new rows to the current rows array or to replace them entirely.
  3380. */
  3381. load: function(data, append){
  3382. var self = this, rows = $.map(data, function(r){
  3383. return new F.Row(self.ft, self.ft.columns.array, r);
  3384. });
  3385. F.arr.each(this.array, function(row){
  3386. row.predraw();
  3387. });
  3388. this.all = (F.is.boolean(append) ? append : false) ? this.all.concat(rows) : rows;
  3389. this.array = this.all.slice(0);
  3390. this.ft.draw();
  3391. },
  3392. /**
  3393. * Expands all visible rows.
  3394. * @instance
  3395. */
  3396. expand: function(){
  3397. F.arr.each(this.array, function(row){
  3398. row.expand();
  3399. });
  3400. },
  3401. /**
  3402. * Collapses all visible rows.
  3403. * @instance
  3404. */
  3405. collapse: function(){
  3406. F.arr.each(this.array, function(row){
  3407. row.collapse();
  3408. });
  3409. }
  3410. });
  3411. F.components.register('rows', F.Rows, 800);
  3412. })(jQuery, FooTable);
  3413. (function(F){
  3414. /**
  3415. * An array of JSON objects containing the row data or a jQuery promise that resolves returning the row data.
  3416. * @type {(Array.<object>|jQuery.Promise)}
  3417. * @default []
  3418. */
  3419. F.Defaults.prototype.rows = [];
  3420. /**
  3421. * A string to display when there are no rows in the table.
  3422. * @type {string}
  3423. * @default "No results"
  3424. */
  3425. F.Defaults.prototype.empty = 'No results';
  3426. /**
  3427. * Whether or not the toggle is appended to each row.
  3428. * @type {boolean}
  3429. * @default true
  3430. */
  3431. F.Defaults.prototype.showToggle = true;
  3432. /**
  3433. * The CSS selector used to filter row click events. If the event.target property matches the selector the row will be toggled.
  3434. * @type {string}
  3435. * @default "tr,td,.footable-toggle"
  3436. */
  3437. F.Defaults.prototype.toggleSelector = 'tr,td,.footable-toggle';
  3438. /**
  3439. * Specifies which column to display the row toggle in. The only supported values are "first" or "last".
  3440. * @type {string}
  3441. * @default "first"
  3442. */
  3443. F.Defaults.prototype.toggleColumn = 'first';
  3444. /**
  3445. * Whether or not the first rows details are expanded by default when displayed on a device that hides any columns.
  3446. * @type {boolean}
  3447. */
  3448. F.Defaults.prototype.expandFirst = false;
  3449. /**
  3450. * Whether or not all row details are expanded by default when displayed on a device that hides any columns.
  3451. * @type {boolean}
  3452. */
  3453. F.Defaults.prototype.expandAll = false;
  3454. })(FooTable);
  3455. (function(F){
  3456. /**
  3457. * Loads a JSON array of row objects into the table
  3458. * @param {Array.<object>} data - An array of row objects to load.
  3459. * @param {boolean} [append=false] - Whether or not to append the new rows to the current rows array or to replace them entirely.
  3460. */
  3461. F.Table.prototype.loadRows = function(data, append){
  3462. this.rows.load(data, append);
  3463. };
  3464. })(FooTable);
  3465. (function(F){
  3466. F.Filter = F.Class.extend(/** @lends FooTable.Filter */{
  3467. /**
  3468. * The filter object contains the query to filter by and the columns to apply it to.
  3469. * @constructs
  3470. * @extends FooTable.Class
  3471. * @param {string} name - The name for the filter.
  3472. * @param {(string|FooTable.Query)} query - The query for the filter.
  3473. * @param {Array.<FooTable.Column>} columns - The columns to apply the query to.
  3474. * @param {string} [space="AND"] - How the query treats space chars.
  3475. * @param {boolean} [connectors=true] - Whether or not to replace phrase connectors (+.-_) with spaces.
  3476. * @param {boolean} [ignoreCase=true] - Whether or not ignore case when matching.
  3477. * @param {boolean} [hidden=true] - Whether or not this is a hidden filter.
  3478. * @returns {FooTable.Filter}
  3479. */
  3480. construct: function(name, query, columns, space, connectors, ignoreCase, hidden){
  3481. /**
  3482. * The name of the filter.
  3483. * @instance
  3484. * @type {string}
  3485. */
  3486. this.name = name;
  3487. /**
  3488. * A string specifying how the filter treats space characters. Can be either "OR" or "AND".
  3489. * @instance
  3490. * @type {string}
  3491. */
  3492. this.space = F.is.string(space) && (space == 'OR' || space == 'AND') ? space : 'AND';
  3493. /**
  3494. * Whether or not to replace phrase connectors (+.-_) with spaces before executing the query.
  3495. * @instance
  3496. * @type {boolean}
  3497. */
  3498. this.connectors = F.is.boolean(connectors) ? connectors : true;
  3499. /**
  3500. * Whether or not ignore case when matching.
  3501. * @instance
  3502. * @type {boolean}
  3503. */
  3504. this.ignoreCase = F.is.boolean(ignoreCase) ? ignoreCase : true;
  3505. /**
  3506. * Whether or not this is a hidden filter.
  3507. * @instance
  3508. * @type {boolean}
  3509. */
  3510. this.hidden = F.is.boolean(hidden) ? hidden : false;
  3511. /**
  3512. * The query for the filter.
  3513. * @instance
  3514. * @type {(string|FooTable.Query)}
  3515. */
  3516. this.query = query instanceof F.Query ? query : new F.Query(query, this.space, this.connectors, this.ignoreCase);
  3517. /**
  3518. * The columns to apply the query to.
  3519. * @instance
  3520. * @type {Array.<FooTable.Column>}
  3521. */
  3522. this.columns = columns;
  3523. },
  3524. /**
  3525. * Checks if the current filter matches the supplied string.
  3526. * If the current query property is a string it will be auto converted to a {@link FooTable.Query} object to perform the match.
  3527. * @instance
  3528. * @param {string} str - The string to check.
  3529. * @returns {boolean}
  3530. */
  3531. match: function(str){
  3532. if (!F.is.string(str)) return false;
  3533. if (F.is.string(this.query)){
  3534. this.query = new F.Query(this.query, this.space, this.connectors, this.ignoreCase);
  3535. }
  3536. return this.query instanceof F.Query ? this.query.match(str) : false;
  3537. },
  3538. /**
  3539. * Checks if the current filter matches the supplied {@link FooTable.Row}.
  3540. * @instance
  3541. * @param {FooTable.Row} row - The row to check.
  3542. * @returns {boolean}
  3543. */
  3544. matchRow: function(row){
  3545. var self = this, text = F.arr.map(row.cells, function(cell){
  3546. return F.arr.contains(self.columns, cell.column) ? cell.filterValue : null;
  3547. }).join(' ');
  3548. return self.match(text);
  3549. }
  3550. });
  3551. })(FooTable);
  3552. (function ($, F) {
  3553. F.Filtering = F.Component.extend(/** @lends FooTable.Filtering */{
  3554. /**
  3555. * The filtering component adds a search input and column selector dropdown to the table allowing users to filter the using space delimited queries.
  3556. * @constructs
  3557. * @extends FooTable.Component
  3558. * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
  3559. * @returns {FooTable.Filtering}
  3560. */
  3561. construct: function (table) {
  3562. // call the constructor of the base class
  3563. this._super(table, table.o.filtering.enabled);
  3564. /* PUBLIC */
  3565. /**
  3566. * The filters to apply to the current {@link FooTable.Rows#array}.
  3567. * @instance
  3568. * @type {Array.<FooTable.Filter>}
  3569. */
  3570. this.filters = table.o.filtering.filters;
  3571. /**
  3572. * The delay in milliseconds before the query is auto applied after a change.
  3573. * @instance
  3574. * @type {number}
  3575. */
  3576. this.delay = table.o.filtering.delay;
  3577. /**
  3578. * The minimum number of characters allowed in the search input before it is auto applied.
  3579. * @instance
  3580. * @type {number}
  3581. */
  3582. this.min = table.o.filtering.min;
  3583. /**
  3584. * Specifies how whitespace in a filter query is handled.
  3585. * @instance
  3586. * @type {string}
  3587. */
  3588. this.space = table.o.filtering.space;
  3589. /**
  3590. * Whether or not to replace phrase connectors (+.-_) with spaces before executing the query.
  3591. * @instance
  3592. * @type {boolean}
  3593. */
  3594. this.connectors = table.o.filtering.connectors;
  3595. /**
  3596. * Whether or not ignore case when matching.
  3597. * @instance
  3598. * @type {boolean}
  3599. */
  3600. this.ignoreCase = table.o.filtering.ignoreCase;
  3601. /**
  3602. * Whether or not search queries are treated as phrases when matching.
  3603. * @instance
  3604. * @type {boolean}
  3605. */
  3606. this.exactMatch = table.o.filtering.exactMatch;
  3607. /**
  3608. * The placeholder text to display within the search $input.
  3609. * @instance
  3610. * @type {string}
  3611. */
  3612. this.placeholder = table.o.filtering.placeholder;
  3613. /**
  3614. * The title to display at the top of the search input column select.
  3615. * @type {string}
  3616. */
  3617. this.dropdownTitle = table.o.filtering.dropdownTitle;
  3618. /**
  3619. * The position of the $search input within the filtering rows cell.
  3620. * @type {string}
  3621. */
  3622. this.position = table.o.filtering.position;
  3623. /**
  3624. * Whether or not to focus the search input after the search/clear button is clicked or after auto applying the search input query.
  3625. * @type {boolean}
  3626. */
  3627. this.focus = table.o.filtering.focus;
  3628. /**
  3629. * A selector specifying where to place the filtering components form, if null the form is displayed within a row in the head of the table.
  3630. * @type {string}
  3631. */
  3632. this.container = table.o.filtering.container;
  3633. /**
  3634. * The jQuery object of the element containing the entire filtering form.
  3635. * @instance
  3636. * @type {jQuery}
  3637. */
  3638. this.$container = null;
  3639. /**
  3640. * The jQuery row object that contains all the filtering specific elements.
  3641. * @instance
  3642. * @type {jQuery}
  3643. */
  3644. this.$row = null;
  3645. /**
  3646. * The jQuery cell object that contains the search input and column selector.
  3647. * @instance
  3648. * @type {jQuery}
  3649. */
  3650. this.$cell = null;
  3651. /**
  3652. * The jQuery form object of the form that contains the search input and column selector.
  3653. * @instance
  3654. * @type {jQuery}
  3655. */
  3656. this.$form = null;
  3657. /**
  3658. * The jQuery object of the column selector dropdown.
  3659. * @instance
  3660. * @type {jQuery}
  3661. */
  3662. this.$dropdown = null;
  3663. /**
  3664. * The jQuery object of the search input.
  3665. * @instance
  3666. * @type {jQuery}
  3667. */
  3668. this.$input = null;
  3669. /**
  3670. * The jQuery object of the search button.
  3671. * @instance
  3672. * @type {jQuery}
  3673. */
  3674. this.$button = null;
  3675. /* PRIVATE */
  3676. /**
  3677. * The timeout ID for the filter changed event.
  3678. * @instance
  3679. * @private
  3680. * @type {?number}
  3681. */
  3682. this._filterTimeout = null;
  3683. /**
  3684. * The regular expression used to check for encapsulating quotations.
  3685. * @instance
  3686. * @private
  3687. * @type {RegExp}
  3688. */
  3689. this._exactRegExp = /^"(.*?)"$/;
  3690. },
  3691. /* PROTECTED */
  3692. /**
  3693. * Checks the supplied data and options for the filtering component.
  3694. * @instance
  3695. * @protected
  3696. * @param {object} data - The jQuery data object from the parent table.
  3697. * @fires FooTable.Filtering#"preinit.ft.filtering"
  3698. */
  3699. preinit: function(data){
  3700. var self = this;
  3701. /**
  3702. * The preinit.ft.filtering event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
  3703. * Calling preventDefault on this event will disable the component.
  3704. * @event FooTable.Filtering#"preinit.ft.filtering"
  3705. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3706. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  3707. * @param {object} data - The jQuery data object of the table raising the event.
  3708. */
  3709. return self.ft.raise('preinit.ft.filtering').then(function(){
  3710. // first check if filtering is enabled via the class being applied
  3711. if (self.ft.$el.hasClass('footable-filtering'))
  3712. self.enabled = true;
  3713. // then check if the data-filtering-enabled attribute has been set
  3714. self.enabled = F.is.boolean(data.filtering)
  3715. ? data.filtering
  3716. : self.enabled;
  3717. // if filtering is not enabled exit early as we don't need to do anything else
  3718. if (!self.enabled) return;
  3719. self.space = F.is.string(data.filterSpace)
  3720. ? data.filterSpace
  3721. : self.space;
  3722. self.min = F.is.number(data.filterMin)
  3723. ? data.filterMin
  3724. : self.min;
  3725. self.connectors = F.is.boolean(data.filterConnectors)
  3726. ? data.filterConnectors
  3727. : self.connectors;
  3728. self.ignoreCase = F.is.boolean(data.filterIgnoreCase)
  3729. ? data.filterIgnoreCase
  3730. : self.ignoreCase;
  3731. self.exactMatch = F.is.boolean(data.filterExactMatch)
  3732. ? data.filterExactMatch
  3733. : self.exactMatch;
  3734. self.focus = F.is.boolean(data.filterFocus)
  3735. ? data.filterFocus
  3736. : self.focus;
  3737. self.delay = F.is.number(data.filterDelay)
  3738. ? data.filterDelay
  3739. : self.delay;
  3740. self.placeholder = F.is.string(data.filterPlaceholder)
  3741. ? data.filterPlaceholder
  3742. : self.placeholder;
  3743. self.dropdownTitle = F.is.string(data.filterDropdownTitle)
  3744. ? data.filterDropdownTitle
  3745. : self.dropdownTitle;
  3746. self.container = F.is.string(data.filterContainer)
  3747. ? data.filterContainer
  3748. : self.container;
  3749. self.filters = F.is.array(data.filterFilters)
  3750. ? self.ensure(data.filterFilters)
  3751. : self.ensure(self.filters);
  3752. if (self.ft.$el.hasClass('footable-filtering-left'))
  3753. self.position = 'left';
  3754. if (self.ft.$el.hasClass('footable-filtering-center'))
  3755. self.position = 'center';
  3756. if (self.ft.$el.hasClass('footable-filtering-right'))
  3757. self.position = 'right';
  3758. self.position = F.is.string(data.filterPosition)
  3759. ? data.filterPosition
  3760. : self.position;
  3761. },function(){
  3762. self.enabled = false;
  3763. });
  3764. },
  3765. /**
  3766. * Initializes the filtering component for the plugin.
  3767. * @instance
  3768. * @protected
  3769. * @fires FooTable.Filtering#"init.ft.filtering"
  3770. */
  3771. init: function () {
  3772. var self = this;
  3773. /**
  3774. * The init.ft.filtering event is raised before its UI is generated.
  3775. * Calling preventDefault on this event will disable the component.
  3776. * @event FooTable.Filtering#"init.ft.filtering"
  3777. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3778. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  3779. */
  3780. return self.ft.raise('init.ft.filtering').then(function(){
  3781. self.$create();
  3782. }, function(){
  3783. self.enabled = false;
  3784. });
  3785. },
  3786. /**
  3787. * Destroys the filtering component removing any UI from the table.
  3788. * @instance
  3789. * @protected
  3790. * @fires FooTable.Filtering#"destroy.ft.filtering"
  3791. */
  3792. destroy: function () {
  3793. var self = this;
  3794. /**
  3795. * The destroy.ft.filtering event is raised before its UI is removed.
  3796. * Calling preventDefault on this event will prevent the component from being destroyed.
  3797. * @event FooTable.Filtering#"destroy.ft.filtering"
  3798. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3799. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  3800. */
  3801. return self.ft.raise('destroy.ft.filtering').then(function(){
  3802. self.ft.$el.removeClass('footable-filtering')
  3803. .find('thead > tr.footable-filtering').remove();
  3804. });
  3805. },
  3806. /**
  3807. * Creates the filtering UI from the current options setting the various jQuery properties of this component.
  3808. * @instance
  3809. * @protected
  3810. * @this FooTable.Filtering
  3811. */
  3812. $create: function () {
  3813. var self = this;
  3814. // generate the cell that actually contains all the UI.
  3815. var $form_grp = $('<div/>', {'class': 'form-group footable-filtering-search'})
  3816. .append($('<label/>', {'class': 'sr-only', text: 'Search'})),
  3817. $input_grp = $('<div/>', {'class': 'input-group'}).appendTo($form_grp),
  3818. $input_grp_btn = $('<div/>', {'class': 'input-group-btn'}),
  3819. $dropdown_toggle = $('<button/>', {type: 'button', 'class': 'btn btn-default dropdown-toggle'})
  3820. .on('click', { self: self }, self._onDropdownToggleClicked)
  3821. .append($('<span/>', {'class': 'caret'})),
  3822. position;
  3823. switch (self.position){
  3824. case 'left': position = 'footable-filtering-left'; break;
  3825. case 'center': position = 'footable-filtering-center'; break;
  3826. default: position = 'footable-filtering-right'; break;
  3827. }
  3828. self.ft.$el.addClass('footable-filtering').addClass(position);
  3829. self.$container = self.container === null ? $() : $(self.container).first();
  3830. if (!self.$container.length){
  3831. // add it to a row and then populate it with the search input and column selector dropdown.
  3832. self.$row = $('<tr/>', {'class': 'footable-filtering'}).prependTo(self.ft.$el.children('thead'));
  3833. self.$cell = $('<th/>').attr('colspan', self.ft.columns.visibleColspan).appendTo(self.$row);
  3834. self.$container = self.$cell;
  3835. } else {
  3836. self.$container.addClass('footable-filtering-external').addClass(position);
  3837. }
  3838. self.$form = $('<form/>', {'class': 'form-inline'}).append($form_grp).appendTo(self.$container);
  3839. self.$input = $('<input/>', {type: 'text', 'class': 'form-control', placeholder: self.placeholder});
  3840. self.$button = $('<button/>', {type: 'button', 'class': 'btn btn-primary'})
  3841. .on('click', { self: self }, self._onSearchButtonClicked)
  3842. .append($('<span/>', {'class': 'fooicon fooicon-search'}));
  3843. self.$dropdown = $('<ul/>', {'class': 'dropdown-menu dropdown-menu-right'});
  3844. if (!F.is.emptyString(self.dropdownTitle)){
  3845. self.$dropdown.append($('<li/>', {'class': 'dropdown-header','text': self.dropdownTitle}));
  3846. }
  3847. self.$dropdown.append(
  3848. F.arr.map(self.ft.columns.array, function (col) {
  3849. return col.filterable ? $('<li/>').append(
  3850. $('<a/>', {'class': 'checkbox'}).append(
  3851. $('<label/>', {html: col.title}).prepend(
  3852. $('<input/>', {type: 'checkbox', checked: true}).data('__FooTableColumn__', col)
  3853. )
  3854. )
  3855. ) : null;
  3856. })
  3857. );
  3858. if (self.delay > 0){
  3859. self.$input.on('keypress keyup paste', { self: self }, self._onSearchInputChanged);
  3860. self.$dropdown.on('click', 'input[type="checkbox"]', {self: self}, self._onSearchColumnClicked);
  3861. }
  3862. $input_grp_btn.append(self.$button, $dropdown_toggle, self.$dropdown);
  3863. $input_grp.append(self.$input, $input_grp_btn);
  3864. },
  3865. /**
  3866. * Performs the filtering of rows before they are appended to the page.
  3867. * @instance
  3868. * @protected
  3869. */
  3870. predraw: function(){
  3871. if (F.is.emptyArray(this.filters))
  3872. return;
  3873. var self = this;
  3874. self.ft.rows.array = $.grep(self.ft.rows.array, function(r){
  3875. return r.filtered(self.filters);
  3876. });
  3877. },
  3878. /**
  3879. * As the rows are drawn by the {@link FooTable.Rows#draw} method this simply updates the colspan for the UI.
  3880. * @instance
  3881. * @protected
  3882. */
  3883. draw: function(){
  3884. if (F.is.jq(this.$cell)){
  3885. this.$cell.attr('colspan', this.ft.columns.visibleColspan);
  3886. }
  3887. var search = this.find('search');
  3888. if (search instanceof F.Filter){
  3889. var query = search.query.val();
  3890. if (this.exactMatch && this._exactRegExp.test(query)){
  3891. query = query.replace(this._exactRegExp, '$1');
  3892. }
  3893. this.$input.val(query);
  3894. } else {
  3895. this.$input.val(null);
  3896. }
  3897. this.setButton(!F.arr.any(this.filters, function(f){ return !f.hidden; }));
  3898. },
  3899. /* PUBLIC */
  3900. /**
  3901. * Adds or updates the filter using the supplied name, query and columns.
  3902. * @instance
  3903. * @param {(string|FooTable.Filter|object)} nameOrFilter - The name for the filter or the actual filter object itself.
  3904. * @param {(string|FooTable.Query)} [query] - The query for the filter. This is only optional when the first parameter is a filter object.
  3905. * @param {(Array.<number>|Array.<string>|Array.<FooTable.Column>)} [columns] - The columns to apply the filter to.
  3906. * If not supplied the filter will be applied to all selected columns in the search input dropdown.
  3907. * @param {boolean} [ignoreCase=true] - Whether or not ignore case when matching.
  3908. * @param {boolean} [connectors=true] - Whether or not to replace phrase connectors (+.-_) with spaces.
  3909. * @param {string} [space="AND"] - How the query treats space chars.
  3910. * @param {boolean} [hidden=true] - Whether or not this is a hidden filter.
  3911. */
  3912. addFilter: function(nameOrFilter, query, columns, ignoreCase, connectors, space, hidden){
  3913. var f = this.createFilter(nameOrFilter, query, columns, ignoreCase, connectors, space, hidden);
  3914. if (f instanceof F.Filter){
  3915. this.removeFilter(f.name);
  3916. this.filters.push(f);
  3917. }
  3918. },
  3919. /**
  3920. * Removes the filter using the supplied name if it exists.
  3921. * @instance
  3922. * @param {string} name - The name of the filter to remove.
  3923. */
  3924. removeFilter: function(name){
  3925. F.arr.remove(this.filters, function(f){ return f.name == name; });
  3926. },
  3927. /**
  3928. * Performs the required steps to handle filtering including the raising of the {@link FooTable.Filtering#"before.ft.filtering"} and {@link FooTable.Filtering#"after.ft.filtering"} events.
  3929. * @instance
  3930. * @param {boolean} [focus=false] - Whether or not to set the focus to the input once filtering is complete.
  3931. * @returns {jQuery.Promise}
  3932. * @fires FooTable.Filtering#"before.ft.filtering"
  3933. * @fires FooTable.Filtering#"after.ft.filtering"
  3934. */
  3935. filter: function(focus){
  3936. var self = this;
  3937. self.filters = self.ensure(self.filters);
  3938. /**
  3939. * The before.ft.filtering event is raised before a filter is applied and allows listeners to modify the filter or cancel it completely by calling preventDefault on the jQuery.Event object.
  3940. * @event FooTable.Filtering#"before.ft.filtering"
  3941. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3942. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  3943. * @param {Array.<FooTable.Filter>} filters - The filters that are about to be applied.
  3944. */
  3945. return self.ft.raise('before.ft.filtering', [self.filters]).then(function(){
  3946. self.filters = self.ensure(self.filters);
  3947. if (focus){
  3948. var start = self.$input.prop('selectionStart'),
  3949. end = self.$input.prop('selectionEnd');
  3950. }
  3951. return self.ft.draw().then(function(){
  3952. if (focus){
  3953. self.$input.focus().prop({
  3954. selectionStart: start,
  3955. selectionEnd: end
  3956. });
  3957. }
  3958. /**
  3959. * The after.ft.filtering event is raised after a filter has been applied.
  3960. * @event FooTable.Filtering#"after.ft.filtering"
  3961. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  3962. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  3963. * @param {FooTable.Filter} filter - The filters that were applied.
  3964. */
  3965. self.ft.raise('after.ft.filtering', [self.filters]);
  3966. });
  3967. });
  3968. },
  3969. /**
  3970. * Removes the current search filter.
  3971. * @instance
  3972. * @returns {jQuery.Promise}
  3973. * @fires FooTable.Filtering#"before.ft.filtering"
  3974. * @fires FooTable.Filtering#"after.ft.filtering"
  3975. */
  3976. clear: function(){
  3977. this.filters = F.arr.get(this.filters, function(f){ return f.hidden; });
  3978. return this.filter(this.focus);
  3979. },
  3980. /**
  3981. * Toggles the button icon between the search and clear icons based on the supplied value.
  3982. * @instance
  3983. * @param {boolean} search - Whether or not to display the search icon.
  3984. */
  3985. setButton: function(search){
  3986. if (!search){
  3987. this.$button.children('.fooicon').removeClass('fooicon-search').addClass('fooicon-remove');
  3988. } else {
  3989. this.$button.children('.fooicon').removeClass('fooicon-remove').addClass('fooicon-search');
  3990. }
  3991. },
  3992. /**
  3993. * Finds a filter by name.
  3994. * @param {string} name - The name of the filter to find.
  3995. * @returns {(FooTable.Filter|null)}
  3996. */
  3997. find: function(name){
  3998. return F.arr.first(this.filters, function(f){ return f.name == name; });
  3999. },
  4000. /**
  4001. * Gets an array of {@link FooTable.Column} to apply the search filter to. This also doubles as the default columns for filters which do not specify any columns.
  4002. * @instance
  4003. * @returns {Array.<FooTable.Column>}
  4004. */
  4005. columns: function(){
  4006. if (F.is.jq(this.$dropdown)){
  4007. // if we have a dropdown containing the column names get the selected columns from there
  4008. return this.$dropdown.find('input:checked').map(function(){
  4009. return $(this).data('__FooTableColumn__');
  4010. }).get();
  4011. } else {
  4012. // otherwise find all columns that are set to be filterable.
  4013. return this.ft.columns.get(function(c){ return c.filterable; });
  4014. }
  4015. },
  4016. /**
  4017. * Takes an array of plain objects containing the filter values or actual {@link FooTable.Filter} objects and ensures that an array of only {@link FooTable.Filter} is returned.
  4018. * If supplied a plain object that object must contain a name, query and columns properties which are used to create a new {@link FooTable.Filter}.
  4019. * @instance
  4020. * @param {({name: string, query: (string|FooTable.Query), columns: (Array.<string>|Array.<number>|Array.<FooTable.Column>)}|Array.<FooTable.Filter>)} filters - The array of filters to check.
  4021. * @returns {Array.<FooTable.Filter>}
  4022. */
  4023. ensure: function(filters){
  4024. var self = this, parsed = [], filterable = self.columns();
  4025. if (!F.is.emptyArray(filters)){
  4026. F.arr.each(filters, function(f){
  4027. f = self._ensure(f, filterable);
  4028. if (f instanceof F.Filter) parsed.push(f);
  4029. });
  4030. }
  4031. return parsed;
  4032. },
  4033. /**
  4034. * Creates a new filter using the supplied object or individual parameters to populate it.
  4035. * @instance
  4036. * @param {(string|FooTable.Filter|object)} nameOrObject - The name for the filter or the actual filter object itself.
  4037. * @param {(string|FooTable.Query)} [query] - The query for the filter. This is only optional when the first parameter is a filter object.
  4038. * @param {(Array.<number>|Array.<string>|Array.<FooTable.Column>)} [columns] - The columns to apply the filter to.
  4039. * If not supplied the filter will be applied to all selected columns in the search input dropdown.
  4040. * @param {boolean} [ignoreCase=true] - Whether or not ignore case when matching.
  4041. * @param {boolean} [connectors=true] - Whether or not to replace phrase connectors (+.-_) with spaces.
  4042. * @param {string} [space="AND"] - How the query treats space chars.
  4043. * @param {boolean} [hidden=true] - Whether or not this is a hidden filter.
  4044. * @returns {*}
  4045. */
  4046. createFilter: function(nameOrObject, query, columns, ignoreCase, connectors, space, hidden){
  4047. if (F.is.string(nameOrObject)){
  4048. nameOrObject = {name: nameOrObject, query: query, columns: columns, ignoreCase: ignoreCase, connectors: connectors, space: space, hidden: hidden};
  4049. }
  4050. return this._ensure(nameOrObject, this.columns());
  4051. },
  4052. /* PRIVATE */
  4053. _ensure: function(filter, selectedColumns){
  4054. if ((F.is.hash(filter) || filter instanceof F.Filter) && !F.is.emptyString(filter.name) && (!F.is.emptyString(filter.query) || filter.query instanceof F.Query)){
  4055. filter.columns = F.is.emptyArray(filter.columns) ? selectedColumns : this.ft.columns.ensure(filter.columns);
  4056. filter.ignoreCase = F.is.boolean(filter.ignoreCase) ? filter.ignoreCase : this.ignoreCase;
  4057. filter.connectors = F.is.boolean(filter.connectors) ? filter.connectors : this.connectors;
  4058. filter.hidden = F.is.boolean(filter.hidden) ? filter.hidden : false;
  4059. filter.space = F.is.string(filter.space) && (filter.space === 'AND' || filter.space === 'OR') ? filter.space : this.space;
  4060. filter.query = F.is.string(filter.query) ? new F.Query(filter.query, filter.space, filter.connectors, filter.ignoreCase) : filter.query;
  4061. return (filter instanceof F.Filter)
  4062. ? filter
  4063. : new F.Filter(filter.name, filter.query, filter.columns, filter.space, filter.connectors, filter.ignoreCase, filter.hidden);
  4064. }
  4065. return null;
  4066. },
  4067. /**
  4068. * Handles the change event for the {@link FooTable.Filtering#$input}.
  4069. * @instance
  4070. * @private
  4071. * @param {jQuery.Event} e - The event object for the event.
  4072. */
  4073. _onSearchInputChanged: function (e) {
  4074. var self = e.data.self;
  4075. var alpha = e.type == 'keypress' && !F.is.emptyString(String.fromCharCode(e.charCode)),
  4076. ctrl = e.type == 'keyup' && (e.which == 8 || e.which == 46),
  4077. paste = e.type == 'paste'; // backspace & delete
  4078. // if alphanumeric characters or specific control characters
  4079. if(alpha || ctrl || paste) {
  4080. if (e.which == 13) e.preventDefault();
  4081. if (self._filterTimeout != null) clearTimeout(self._filterTimeout);
  4082. self._filterTimeout = setTimeout(function(){
  4083. self._filterTimeout = null;
  4084. var query = self.$input.val();
  4085. if (query.length >= self.min){
  4086. if (self.exactMatch && !self._exactRegExp.test(query)){
  4087. query = '"' + query + '"';
  4088. }
  4089. self.addFilter('search', query);
  4090. self.filter(self.focus);
  4091. } else if (F.is.emptyString(query)){
  4092. self.clear();
  4093. }
  4094. }, self.delay);
  4095. }
  4096. },
  4097. /**
  4098. * Handles the click event for the {@link FooTable.Filtering#$button}.
  4099. * @instance
  4100. * @private
  4101. * @param {jQuery.Event} e - The event object for the event.
  4102. */
  4103. _onSearchButtonClicked: function (e) {
  4104. e.preventDefault();
  4105. var self = e.data.self;
  4106. if (self._filterTimeout != null) clearTimeout(self._filterTimeout);
  4107. var $icon = self.$button.children('.fooicon');
  4108. if ($icon.hasClass('fooicon-remove')) self.clear();
  4109. else {
  4110. var query = self.$input.val();
  4111. if (query.length >= self.min){
  4112. if (self.exactMatch && !self._exactRegExp.test(query)){
  4113. query = '"' + query + '"';
  4114. }
  4115. self.addFilter('search', query);
  4116. self.filter(self.focus);
  4117. }
  4118. }
  4119. },
  4120. /**
  4121. * Handles the click event for the column checkboxes in the {@link FooTable.Filtering#$dropdown}.
  4122. * @instance
  4123. * @private
  4124. * @param {jQuery.Event} e - The event object for the event.
  4125. */
  4126. _onSearchColumnClicked: function (e) {
  4127. var self = e.data.self;
  4128. if (self._filterTimeout != null) clearTimeout(self._filterTimeout);
  4129. self._filterTimeout = setTimeout(function(){
  4130. self._filterTimeout = null;
  4131. var $icon = self.$button.children('.fooicon');
  4132. if ($icon.hasClass('fooicon-remove')){
  4133. $icon.removeClass('fooicon-remove').addClass('fooicon-search');
  4134. self.addFilter('search', self.$input.val());
  4135. self.filter();
  4136. }
  4137. }, self.delay);
  4138. },
  4139. /**
  4140. * Handles the click event for the {@link FooTable.Filtering#$dropdown} toggle.
  4141. * @instance
  4142. * @private
  4143. * @param {jQuery.Event} e - The event object for the event.
  4144. */
  4145. _onDropdownToggleClicked: function (e) {
  4146. e.preventDefault();
  4147. e.stopPropagation();
  4148. var self = e.data.self;
  4149. self.$dropdown.parent().toggleClass('open');
  4150. if (self.$dropdown.parent().hasClass('open')) $(document).on('click.footable', { self: self }, self._onDocumentClicked);
  4151. else $(document).off('click.footable', self._onDocumentClicked);
  4152. },
  4153. /**
  4154. * Checks all click events when the dropdown is visible and closes the menu if the target is not the dropdown.
  4155. * @instance
  4156. * @private
  4157. * @param {jQuery.Event} e - The event object for the event.
  4158. */
  4159. _onDocumentClicked: function(e){
  4160. if ($(e.target).closest('.dropdown-menu').length == 0){
  4161. e.preventDefault();
  4162. var self = e.data.self;
  4163. self.$dropdown.parent().removeClass('open');
  4164. $(document).off('click.footable', self._onDocumentClicked);
  4165. }
  4166. }
  4167. });
  4168. F.components.register('filtering', F.Filtering, 500);
  4169. })(jQuery, FooTable);
  4170. (function(F){
  4171. F.Query = F.Class.extend(/** @lends FooTable.Query */{
  4172. /**
  4173. * The query object is used to parse and test the filtering component's queries
  4174. * @constructs
  4175. * @extends FooTable.Class
  4176. * @param {string} query - The string value of the query.
  4177. * @param {string} [space="AND"] - How the query treats whitespace.
  4178. * @param {boolean} [connectors=true] - Whether or not to replace phrase connectors (+.-_) with spaces.
  4179. * @param {boolean} [ignoreCase=true] - Whether or not ignore case when matching.
  4180. * @returns {FooTable.Query}
  4181. */
  4182. construct: function(query, space, connectors, ignoreCase){
  4183. /* PRIVATE */
  4184. /**
  4185. * Holds the previous value of the query and is used internally in the {@link FooTable.Query#val} method.
  4186. * @type {string}
  4187. * @private
  4188. */
  4189. this._original = null;
  4190. /**
  4191. * Holds the value for the query. Access to this variable is provided through the {@link FooTable.Query#val} method.
  4192. * @type {string}
  4193. * @private
  4194. */
  4195. this._value = null;
  4196. /* PUBLIC */
  4197. /**
  4198. * A string specifying how the query treats whitespace. Can be either "OR" or "AND".
  4199. * @type {string}
  4200. */
  4201. this.space = F.is.string(space) && (space == 'OR' || space == 'AND') ? space : 'AND';
  4202. /**
  4203. * Whether or not to replace phrase connectors (+.-_) with spaces before executing the query.
  4204. * @instance
  4205. * @type {boolean}
  4206. */
  4207. this.connectors = F.is.boolean(connectors) ? connectors : true;
  4208. /**
  4209. * Whether or not ignore case when matching.
  4210. * @instance
  4211. * @type {boolean}
  4212. */
  4213. this.ignoreCase = F.is.boolean(ignoreCase) ? ignoreCase : true;
  4214. /**
  4215. * The left side of the query if one exists. OR takes precedence over AND.
  4216. * @type {FooTable.Query}
  4217. * @example <caption>The below shows what is meant by the "left" side of a query</caption>
  4218. * query = "Dave AND Mary" - "Dave" is the left side of the query.
  4219. * query = "Dave AND Mary OR John" - "Dave and Mary" is the left side of the query.
  4220. */
  4221. this.left = null;
  4222. /**
  4223. * The right side of the query if one exists. OR takes precedence over AND.
  4224. * @type {FooTable.Query}
  4225. * @example <caption>The below shows what is meant by the "right" side of a query</caption>
  4226. * query = "Dave AND Mary" - "Mary" is the right side of the query.
  4227. * query = "Dave AND Mary OR John" - "John" is the right side of the query.
  4228. */
  4229. this.right = null;
  4230. /**
  4231. * The parsed parts of the query. This contains the information used to actually perform a match against a string.
  4232. * @type {Array}
  4233. */
  4234. this.parts = [];
  4235. /**
  4236. * The type of operand to apply to the results of the individual parts of the query.
  4237. * @type {string}
  4238. */
  4239. this.operator = null;
  4240. this.val(query);
  4241. },
  4242. /**
  4243. * Gets or sets the value for the query. During set the value is parsed setting all properties as required.
  4244. * @param {string} [value] - If supplied the value to set for this query.
  4245. * @returns {(string|undefined)}
  4246. */
  4247. val: function(value){
  4248. // get
  4249. if (F.is.emptyString(value)) return this._value;
  4250. // set
  4251. if (F.is.emptyString(this._original)) this._original = value;
  4252. else if (this._original == value) return;
  4253. this._value = value;
  4254. this._parse();
  4255. },
  4256. /**
  4257. * Tests the supplied string against the query.
  4258. * @param {string} str - The string to test.
  4259. * @returns {boolean}
  4260. */
  4261. match: function(str){
  4262. if (F.is.emptyString(this.operator) || this.operator === 'OR')
  4263. return this._left(str, false) || this._match(str, false) || this._right(str, false);
  4264. if (this.operator === 'AND')
  4265. return this._left(str, true) && this._match(str, true) && this._right(str, true);
  4266. },
  4267. /**
  4268. * Matches this queries parts array against the supplied string.
  4269. * @param {string} str - The string to test.
  4270. * @param {boolean} def - The default value to return based on the operand.
  4271. * @returns {boolean}
  4272. * @private
  4273. */
  4274. _match: function(str, def){
  4275. var self = this, result = false, empty = F.is.emptyString(str);
  4276. if (F.is.emptyArray(self.parts) && self.left instanceof F.Query) return def;
  4277. if (F.is.emptyArray(self.parts)) return result;
  4278. if (self.space === 'OR'){
  4279. // with OR we give the str every part to test and if any match it is a success, we do exit early if a negated match occurs
  4280. F.arr.each(self.parts, function(p){
  4281. if (p.empty && empty){
  4282. result = true;
  4283. if (p.negate){
  4284. result = false;
  4285. return result;
  4286. }
  4287. } else {
  4288. var match = (p.exact ? F.str.containsExact : F.str.contains)(str, p.query, self.ignoreCase);
  4289. if (match && !p.negate) result = true;
  4290. if (match && p.negate) {
  4291. result = false;
  4292. return result;
  4293. }
  4294. }
  4295. });
  4296. } else {
  4297. // otherwise with AND we check until the first failure and then exit
  4298. result = true;
  4299. F.arr.each(self.parts, function(p){
  4300. if (p.empty){
  4301. if ((!empty && !p.negate) || (empty && p.negate)) result = false;
  4302. return result;
  4303. } else {
  4304. var match = (p.exact ? F.str.containsExact : F.str.contains)(str, p.query, self.ignoreCase);
  4305. if ((!match && !p.negate) || (match && p.negate)) result = false;
  4306. return result;
  4307. }
  4308. });
  4309. }
  4310. return result;
  4311. },
  4312. /**
  4313. * Matches the left side of the query if one exists with the supplied string.
  4314. * @param {string} str - The string to test.
  4315. * @param {boolean} def - The default value to return based on the operand.
  4316. * @returns {boolean}
  4317. * @private
  4318. */
  4319. _left: function(str, def){
  4320. return (this.left instanceof F.Query) ? this.left.match(str) : def;
  4321. },
  4322. /**
  4323. * Matches the right side of the query if one exists with the supplied string.
  4324. * @param {string} str - The string to test.
  4325. * @param {boolean} def - The default value to return based on the operand.
  4326. * @returns {boolean}
  4327. * @private
  4328. */
  4329. _right: function(str, def){
  4330. return (this.right instanceof F.Query) ? this.right.match(str) : def;
  4331. },
  4332. /**
  4333. * Parses the private {@link FooTable.Query#_value} property and populates the object.
  4334. * @private
  4335. */
  4336. _parse: function(){
  4337. if (F.is.emptyString(this._value)) return;
  4338. // OR takes precedence so test for it first
  4339. if (/\sOR\s/.test(this._value)){
  4340. // we have an OR so split the value on the first occurrence of OR to get the left and right sides of the statement
  4341. this.operator = 'OR';
  4342. var or = this._value.split(/(?:\sOR\s)(.*)?/);
  4343. this.left = new F.Query(or[0], this.space, this.connectors, this.ignoreCase);
  4344. this.right = new F.Query(or[1], this.space, this.connectors, this.ignoreCase);
  4345. } else if (/\sAND\s/.test(this._value)) {
  4346. // there are no more OR's so start with AND
  4347. this.operator = 'AND';
  4348. var and = this._value.split(/(?:\sAND\s)(.*)?/);
  4349. this.left = new F.Query(and[0], this.space, this.connectors, this.ignoreCase);
  4350. this.right = new F.Query(and[1], this.space, this.connectors, this.ignoreCase);
  4351. } else {
  4352. // we have no more statements to parse so set the parts array by parsing each part of the remaining query
  4353. var self = this;
  4354. this.parts = F.arr.map(this._value.match(/(?:[^\s"]+|"[^"]*")+/g), function(str){
  4355. return self._part(str);
  4356. });
  4357. }
  4358. },
  4359. /**
  4360. * Parses a single part of a query into an object to use during matching.
  4361. * @param {string} str - The string representation of the part.
  4362. * @returns {{query: string, negate: boolean, phrase: boolean, exact: boolean}}
  4363. * @private
  4364. */
  4365. _part: function(str){
  4366. var p = {
  4367. query: str,
  4368. negate: false,
  4369. phrase: false,
  4370. exact: false,
  4371. empty: false
  4372. };
  4373. // support for NEGATE operand - (minus sign). Remove this first so we can get onto phrase checking
  4374. if (F.str.startsWith(p.query, '-')){
  4375. p.query = F.str.from(p.query, '-');
  4376. p.negate = true;
  4377. }
  4378. // support for PHRASES (exact matches)
  4379. if (/^"(.*?)"$/.test(p.query)){ // if surrounded in quotes strip them and nothing else
  4380. p.query = p.query.replace(/^"(.*?)"$/, '$1');
  4381. p.phrase = true;
  4382. p.exact = true;
  4383. } else if (this.connectors && /(?:\w)+?([-_\+\.])(?:\w)+?/.test(p.query)) { // otherwise replace supported phrase connectors (-_+.) with spaces
  4384. p.query = p.query.replace(/(?:\w)+?([-_\+\.])(?:\w)+?/g, function(match, p1){
  4385. return match.replace(p1, ' ');
  4386. });
  4387. p.phrase = true;
  4388. }
  4389. p.empty = p.phrase && F.is.emptyString(p.query);
  4390. return p;
  4391. }
  4392. });
  4393. })(FooTable);
  4394. (function(F){
  4395. /**
  4396. * The value used by the filtering component during filter operations. Must be a string and can be set using the data-filter-value attribute on the cell itself.
  4397. * If this is not supplied it is set to the result of the toString method called on the value for the cell. Added by the {@link FooTable.Filtering} component.
  4398. * @type {string}
  4399. * @default null
  4400. */
  4401. F.Cell.prototype.filterValue = null;
  4402. // this is used to define the filtering specific properties on cell creation
  4403. F.Cell.prototype.__filtering_define__ = function(valueOrElement){
  4404. this.filterValue = this.column.filterValue.call(this.column, valueOrElement);
  4405. };
  4406. // this is used to update the filterValue property whenever the cell value is changed
  4407. F.Cell.prototype.__filtering_val__ = function(value){
  4408. if (F.is.defined(value)){
  4409. // set only
  4410. this.filterValue = this.column.filterValue.call(this.column, value);
  4411. }
  4412. };
  4413. // overrides the public define method and replaces it with our own
  4414. F.Cell.extend('define', function(valueOrElement){
  4415. this._super(valueOrElement);
  4416. this.__filtering_define__(valueOrElement);
  4417. });
  4418. // overrides the public val method and replaces it with our own
  4419. F.Cell.extend('val', function(value, redraw, redrawSelf){
  4420. var val = this._super(value, redraw, redrawSelf);
  4421. this.__filtering_val__(value);
  4422. return val;
  4423. });
  4424. })(FooTable);
  4425. (function($, F){
  4426. /**
  4427. * Whether or not the column can be used during filtering. Added by the {@link FooTable.Filtering} component.
  4428. * @type {boolean}
  4429. * @default true
  4430. */
  4431. F.Column.prototype.filterable = true;
  4432. /**
  4433. * This is supplied either the cell value or jQuery object to parse. A string value must be returned from this method and will be used during filtering operations.
  4434. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  4435. * @returns {string}
  4436. * @this FooTable.Column
  4437. */
  4438. F.Column.prototype.filterValue = function(valueOrElement){
  4439. // if we have an element or a jQuery object use jQuery to get the value
  4440. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
  4441. var data = $(valueOrElement).data('filterValue');
  4442. return F.is.defined(data) ? ''+data : $(valueOrElement).text();
  4443. }
  4444. // if options are supplied with the value
  4445. if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
  4446. if (F.is.string(valueOrElement.options.filterValue)) return valueOrElement.options.filterValue;
  4447. if (F.is.defined(valueOrElement.value)) valueOrElement = valueOrElement.value;
  4448. }
  4449. if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement+''; // use the native toString of the value
  4450. return ''; // otherwise we have no value so return an empty string
  4451. };
  4452. // this is used to define the filtering specific properties on column creation
  4453. F.Column.prototype.__filtering_define__ = function(definition){
  4454. this.filterable = F.is.boolean(definition.filterable) ? definition.filterable : this.filterable;
  4455. this.filterValue = F.checkFnValue(this, definition.filterValue, this.filterValue);
  4456. };
  4457. // overrides the public define method and replaces it with our own
  4458. F.Column.extend('define', function(definition){
  4459. this._super(definition); // call the base so we don't have to redefine any previously set properties
  4460. this.__filtering_define__(definition); // then call our own
  4461. });
  4462. })(jQuery, FooTable);
  4463. (function(F){
  4464. /**
  4465. * An object containing the filtering options for the plugin. Added by the {@link FooTable.Filtering} component.
  4466. * @type {object}
  4467. * @prop {boolean} enabled=false - Whether or not to allow filtering on the table.
  4468. * @prop {({name: string, query: (string|FooTable.Query), columns: (Array.<string>|Array.<number>|Array.<FooTable.Column>)}|Array.<FooTable.Filter>)} filters - The filters to apply to the current {@link FooTable.Rows#array}.
  4469. * @prop {number} delay=1200 - The delay in milliseconds before the query is auto applied after a change (any value equal to or less than zero will disable this).
  4470. * @prop {number} min=1 - The minimum number of characters allowed in the search input before it is auto applied.
  4471. * @prop {string} space="AND" - Specifies how whitespace in a filter query is handled.
  4472. * @prop {string} placeholder="Search" - The string used as the placeholder for the search input.
  4473. * @prop {string} dropdownTitle=null - The title to display at the top of the search input column select.
  4474. * @prop {string} position="right" - The string used to specify the alignment of the search input.
  4475. * @prop {string} connectors=true - Whether or not to replace phrase connectors (+.-_) with space before executing the query.
  4476. * @prop {boolean} ignoreCase=true - Whether or not ignore case when matching.
  4477. * @prop {boolean} exactMatch=false - Whether or not search queries are treated as phrases when matching.
  4478. * @prop {boolean} focus=true - Whether or not to focus the search input after the search/clear button is clicked or after auto applying the search input query.
  4479. * @prop {string} container=null - A selector specifying where to place the filtering components form, if null the form is displayed within a row in the head of the table.
  4480. */
  4481. F.Defaults.prototype.filtering = {
  4482. enabled: false,
  4483. filters: [],
  4484. delay: 1200,
  4485. min: 1,
  4486. space: 'AND',
  4487. placeholder: 'Search',
  4488. dropdownTitle: null,
  4489. position: 'right',
  4490. connectors: true,
  4491. ignoreCase: true,
  4492. exactMatch: false,
  4493. focus: true,
  4494. container: null
  4495. };
  4496. })(FooTable);
  4497. (function(F){
  4498. /**
  4499. * Checks if the row is filtered using the supplied filters.
  4500. * @this FooTable.Row
  4501. * @param {Array.<FooTable.Filter>} filters - The filters to apply.
  4502. * @returns {boolean}
  4503. */
  4504. F.Row.prototype.filtered = function(filters){
  4505. var result = true, self = this;
  4506. F.arr.each(filters, function(f){
  4507. if ((result = f.matchRow(self)) == false) return false;
  4508. });
  4509. return result;
  4510. };
  4511. })(FooTable);
  4512. (function($, F){
  4513. F.Sorter = F.Class.extend(/** @lends FooTable.Sorter */{
  4514. /**
  4515. * The sorter object contains the column and direction to sort by.
  4516. * @constructs
  4517. * @extends FooTable.Class
  4518. * @param {FooTable.Column} column - The column to sort.
  4519. * @param {string} direction - The direction to sort by.
  4520. * @returns {FooTable.Sorter}
  4521. */
  4522. construct: function(column, direction){
  4523. /**
  4524. * The column to sort.
  4525. * @type {FooTable.Column}
  4526. */
  4527. this.column = column;
  4528. /**
  4529. * The direction to sort by.
  4530. * @type {string}
  4531. */
  4532. this.direction = direction;
  4533. }
  4534. });
  4535. })(jQuery, FooTable);
  4536. (function ($, F) {
  4537. F.Sorting = F.Component.extend(/** @lends FooTable.Sorting */{
  4538. /**
  4539. * The sorting component adds a small sort button to specified column headers allowing users to sort those columns in the table.
  4540. * @constructs
  4541. * @extends FooTable.Component
  4542. * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
  4543. * @returns {FooTable.Sorting}
  4544. */
  4545. construct: function (table) {
  4546. // call the constructor of the base class
  4547. this._super(table, table.o.sorting.enabled);
  4548. /* PROTECTED */
  4549. /**
  4550. * This provides a shortcut to the {@link FooTable.Table#options}.[sorting]{@link FooTable.Defaults#sorting} object.
  4551. * @instance
  4552. * @protected
  4553. * @type {object}
  4554. */
  4555. this.o = table.o.sorting;
  4556. /**
  4557. * The current sorted column.
  4558. * @instance
  4559. * @type {FooTable.Column}
  4560. */
  4561. this.column = null;
  4562. /**
  4563. * Whether or not to allow sorting to occur, should be set using the {@link FooTable.Sorting#toggleAllowed} method.
  4564. * @instance
  4565. * @type {boolean}
  4566. */
  4567. this.allowed = true;
  4568. /**
  4569. * The initial sort state of the table, this value is used for determining if the sorting has occurred or to reset the state to default.
  4570. * @instance
  4571. * @type {{isset: boolean, rows: Array.<FooTable.Row>, column: string, direction: ?string}}
  4572. */
  4573. this.initial = null;
  4574. },
  4575. /* PROTECTED */
  4576. /**
  4577. * Checks the supplied data and options for the sorting component.
  4578. * @instance
  4579. * @protected
  4580. * @param {object} data - The jQuery data object from the parent table.
  4581. * @fires FooTable.Sorting#"preinit.ft.sorting"
  4582. * @this FooTable.Sorting
  4583. */
  4584. preinit: function(data){
  4585. var self = this;
  4586. /**
  4587. * The preinit.ft.sorting event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
  4588. * Calling preventDefault on this event will disable the component.
  4589. * @event FooTable.Sorting#"preinit.ft.sorting"
  4590. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  4591. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  4592. * @param {object} data - The jQuery data object of the table raising the event.
  4593. */
  4594. this.ft.raise('preinit.ft.sorting', [data]).then(function(){
  4595. if (self.ft.$el.hasClass('footable-sorting'))
  4596. self.enabled = true;
  4597. self.enabled = F.is.boolean(data.sorting)
  4598. ? data.sorting
  4599. : self.enabled;
  4600. if (!self.enabled) return;
  4601. self.column = F.arr.first(self.ft.columns.array, function(col){ return col.sorted; });
  4602. }, function(){
  4603. self.enabled = false;
  4604. });
  4605. },
  4606. /**
  4607. * Initializes the sorting component for the plugin using the supplied table and options.
  4608. * @instance
  4609. * @protected
  4610. * @fires FooTable.Sorting#"init.ft.sorting"
  4611. * @this FooTable.Sorting
  4612. */
  4613. init: function () {
  4614. /**
  4615. * The init.ft.sorting event is raised before its UI is generated.
  4616. * Calling preventDefault on this event will disable the component.
  4617. * @event FooTable.Sorting#"init.ft.sorting"
  4618. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  4619. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  4620. */
  4621. var self = this;
  4622. this.ft.raise('init.ft.sorting').then(function(){
  4623. if (!self.initial){
  4624. var isset = !!self.column;
  4625. self.initial = {
  4626. isset: isset,
  4627. // grab a shallow copy of the rows array prior to sorting - allows us to reset without an initial sort
  4628. rows: self.ft.rows.all.slice(0),
  4629. // if there is a sorted column store its name and direction
  4630. column: isset ? self.column.name : null,
  4631. direction: isset ? self.column.direction : null
  4632. }
  4633. }
  4634. F.arr.each(self.ft.columns.array, function(col){
  4635. if (col.sortable){
  4636. col.$el.addClass('footable-sortable').append($('<span/>', {'class': 'fooicon fooicon-sort'}));
  4637. }
  4638. });
  4639. self.ft.$el.on('click.footable', '.footable-sortable', { self: self }, self._onSortClicked);
  4640. }, function(){
  4641. self.enabled = false;
  4642. });
  4643. },
  4644. /**
  4645. * Destroys the sorting component removing any UI generated from the table.
  4646. * @instance
  4647. * @protected
  4648. * @fires FooTable.Sorting#"destroy.ft.sorting"
  4649. */
  4650. destroy: function () {
  4651. /**
  4652. * The destroy.ft.sorting event is raised before its UI is removed.
  4653. * Calling preventDefault on this event will prevent the component from being destroyed.
  4654. * @event FooTable.Sorting#"destroy.ft.sorting"
  4655. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  4656. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  4657. */
  4658. var self = this;
  4659. this.ft.raise('destroy.ft.paging').then(function(){
  4660. self.ft.$el.off('click.footable', '.footable-sortable', self._onSortClicked);
  4661. self.ft.$el.children('thead').children('tr.footable-header')
  4662. .children('.footable-sortable').removeClass('footable-sortable footable-asc footable-desc')
  4663. .find('span.fooicon').remove();
  4664. });
  4665. },
  4666. /**
  4667. * Performs the actual sorting against the {@link FooTable.Rows#current} array.
  4668. * @instance
  4669. * @protected
  4670. */
  4671. predraw: function () {
  4672. if (!this.column) return;
  4673. var self = this, col = self.column;
  4674. self.ft.rows.array.sort(function (a, b) {
  4675. return col.direction == 'DESC'
  4676. ? col.sorter(b.cells[col.index].sortValue, a.cells[col.index].sortValue)
  4677. : col.sorter(a.cells[col.index].sortValue, b.cells[col.index].sortValue);
  4678. });
  4679. },
  4680. /**
  4681. * Updates the sorting UI setting the state of the sort buttons.
  4682. * @instance
  4683. * @protected
  4684. */
  4685. draw: function () {
  4686. if (!this.column) return;
  4687. var self = this,
  4688. $sortable = self.ft.$el.find('thead > tr > .footable-sortable'),
  4689. $active = self.column.$el;
  4690. $sortable.removeClass('footable-asc footable-desc').children('.fooicon').removeClass('fooicon-sort fooicon-sort-asc fooicon-sort-desc');
  4691. $sortable.not($active).children('.fooicon').addClass('fooicon-sort');
  4692. $active.addClass(self.column.direction == 'DESC' ? 'footable-desc' : 'footable-asc')
  4693. .children('.fooicon').addClass(self.column.direction == 'DESC' ? 'fooicon-sort-desc' : 'fooicon-sort-asc');
  4694. },
  4695. /* PUBLIC */
  4696. /**
  4697. * Sets the sorting options and calls the {@link FooTable.Table#draw} method to perform the actual sorting.
  4698. * @instance
  4699. * @param {(string|number|FooTable.Column)} column - The column name, index or the actual {@link FooTable.Column} object to sort by.
  4700. * @param {string} [direction="ASC"] - The direction to sort by, either ASC or DESC.
  4701. * @returns {jQuery.Promise}
  4702. * @fires FooTable.Sorting#"before.ft.sorting"
  4703. * @fires FooTable.Sorting#"after.ft.sorting"
  4704. */
  4705. sort: function(column, direction){
  4706. return this._sort(column, direction);
  4707. },
  4708. /**
  4709. * Toggles whether or not sorting is currently allowed.
  4710. * @param {boolean} [state] - You can optionally specify the state you want it to be, if not supplied the current value is flipped.
  4711. */
  4712. toggleAllowed: function(state){
  4713. state = F.is.boolean(state) ? state : !this.allowed;
  4714. this.allowed = state;
  4715. this.ft.$el.toggleClass('footable-sorting-disabled', !this.allowed);
  4716. },
  4717. /**
  4718. * Checks whether any sorting has occurred for the table.
  4719. * @returns {boolean}
  4720. */
  4721. hasChanged: function(){
  4722. return !(!this.initial || !this.column ||
  4723. (this.column.name === this.initial.column &&
  4724. (this.column.direction === this.initial.direction || (this.initial.direction === null && this.column.direction === 'ASC')))
  4725. );
  4726. },
  4727. /**
  4728. * Resets the table sorting to the initial state recorded in the components init method.
  4729. */
  4730. reset: function(){
  4731. if (!!this.initial){
  4732. if (this.initial.isset){
  4733. // if the initial value specified a column, sort by it
  4734. this.sort(this.initial.column, this.initial.direction);
  4735. } else {
  4736. // if there was no initial column then we need to reset the rows to there original order
  4737. if (!!this.column){
  4738. // if there is a currently sorted column remove the asc/desc classes and set it to null.
  4739. this.column.$el.removeClass('footable-asc footable-desc');
  4740. this.column = null;
  4741. }
  4742. // replace the current all rows array with the one stored in the initial value
  4743. this.ft.rows.all = this.initial.rows;
  4744. // force the table to redraw itself using the updated rows array
  4745. this.ft.draw();
  4746. }
  4747. }
  4748. },
  4749. /* PRIVATE */
  4750. /**
  4751. * Performs the required steps to handle sorting including the raising of the {@link FooTable.Sorting#"before.ft.sorting"} and {@link FooTable.Sorting#"after.ft.sorting"} events.
  4752. * @instance
  4753. * @private
  4754. * @param {(string|number|FooTable.Column)} column - The column name, index or the actual {@link FooTable.Column} object to sort by.
  4755. * @param {string} [direction="ASC"] - The direction to sort by, either ASC or DESC.
  4756. * @returns {jQuery.Promise}
  4757. * @fires FooTable.Sorting#"before.ft.sorting"
  4758. * @fires FooTable.Sorting#"after.ft.sorting"
  4759. */
  4760. _sort: function(column, direction){
  4761. if (!this.allowed) return $.Deferred().reject('sorting disabled');
  4762. var self = this;
  4763. var sorter = new F.Sorter(self.ft.columns.get(column), F.Sorting.dir(direction));
  4764. /**
  4765. * The before.ft.sorting event is raised before a sort is applied and allows listeners to modify the sorter or cancel it completely by calling preventDefault on the jQuery.Event object.
  4766. * @event FooTable.Sorting#"before.ft.sorting"
  4767. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  4768. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  4769. * @param {FooTable.Sorter} sorter - The sorter that is about to be applied.
  4770. */
  4771. return self.ft.raise('before.ft.sorting', [sorter]).then(function(){
  4772. F.arr.each(self.ft.columns.array, function(col){
  4773. if (col != self.column) col.direction = null;
  4774. });
  4775. self.column = self.ft.columns.get(sorter.column);
  4776. if (self.column) self.column.direction = F.Sorting.dir(sorter.direction);
  4777. return self.ft.draw().then(function(){
  4778. /**
  4779. * The after.ft.sorting event is raised after a sorter has been applied.
  4780. * @event FooTable.Sorting#"after.ft.sorting"
  4781. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  4782. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  4783. * @param {FooTable.Sorter} sorter - The sorter that has been applied.
  4784. */
  4785. self.ft.raise('after.ft.sorting', [sorter]);
  4786. });
  4787. });
  4788. },
  4789. /**
  4790. * Handles the sort button clicked event.
  4791. * @instance
  4792. * @private
  4793. * @param {jQuery.Event} e - The event object for the event.
  4794. */
  4795. _onSortClicked: function (e) {
  4796. var self = e.data.self, $header = $(this).closest('th,td'),
  4797. direction = $header.is('.footable-asc, .footable-desc')
  4798. ? ($header.hasClass('footable-desc') ? 'ASC' : 'DESC')
  4799. : 'ASC';
  4800. self._sort($header.index(), direction);
  4801. }
  4802. });
  4803. /**
  4804. * Checks the supplied string is a valid direction and if not returns ASC as default.
  4805. * @static
  4806. * @protected
  4807. * @param {string} str - The string to check.
  4808. */
  4809. F.Sorting.dir = function(str){
  4810. return F.is.string(str) && (str == 'ASC' || str == 'DESC') ? str : 'ASC';
  4811. };
  4812. F.components.register('sorting', F.Sorting, 600);
  4813. })(jQuery, FooTable);
  4814. (function(F){
  4815. /**
  4816. * The value used by the sorting component during sort operations. Can be set using the data-sort-value attribute on the cell itself.
  4817. * If this is not supplied it is set to the result of the toString method called on the value for the cell. Added by the {@link FooTable.Sorting} component.
  4818. * @type {string}
  4819. * @default null
  4820. */
  4821. F.Cell.prototype.sortValue = null;
  4822. // this is used to define the sorting specific properties on cell creation
  4823. F.Cell.prototype.__sorting_define__ = function(valueOrElement){
  4824. this.sortValue = this.column.sortValue.call(this.column, valueOrElement);
  4825. };
  4826. // this is used to update the sortValue property whenever the cell value is changed
  4827. F.Cell.prototype.__sorting_val__ = function(value){
  4828. if (F.is.defined(value)){
  4829. // set only
  4830. this.sortValue = this.column.sortValue.call(this.column, value);
  4831. }
  4832. };
  4833. // overrides the public define method and replaces it with our own
  4834. F.Cell.extend('define', function(valueOrElement){
  4835. this._super(valueOrElement);
  4836. this.__sorting_define__(valueOrElement);
  4837. });
  4838. // overrides the public val method and replaces it with our own
  4839. F.Cell.extend('val', function(value, redraw, redrawSelf){
  4840. var val = this._super(value, redraw, redrawSelf);
  4841. this.__sorting_val__(value);
  4842. return val;
  4843. });
  4844. })(FooTable);
  4845. (function($, F){
  4846. /**
  4847. * The direction to sort if the {@link FooTable.Column#sorted} property is set to true. Can be "ASC", "DESC" or NULL. Added by the {@link FooTable.Sorting} component.
  4848. * @type {string}
  4849. * @default null
  4850. */
  4851. F.Column.prototype.direction = null;
  4852. /**
  4853. * Whether or not the column can be sorted. Added by the {@link FooTable.Sorting} component.
  4854. * @type {boolean}
  4855. * @default true
  4856. */
  4857. F.Column.prototype.sortable = true;
  4858. /**
  4859. * Whether or not the column is sorted. Added by the {@link FooTable.Sorting} component.
  4860. * @type {boolean}
  4861. * @default false
  4862. */
  4863. F.Column.prototype.sorted = false;
  4864. /**
  4865. * This is supplied two values from the column for a comparison to be made and the result returned. Added by the {@link FooTable.Sorting} component.
  4866. * @param {*} a - The first value to be compared.
  4867. * @param {*} b - The second value to compare to the first.
  4868. * @returns {number}
  4869. * @example <caption>This example shows using pseudo code what a sort function would look like.</caption>
  4870. * "sorter": function(a, b){
  4871. * if (a is less than b by some ordering criterion) {
  4872. * return -1;
  4873. * }
  4874. * if (a is greater than b by the ordering criterion) {
  4875. * return 1;
  4876. * }
  4877. * // a must be equal to b
  4878. * return 0;
  4879. * }
  4880. */
  4881. F.Column.prototype.sorter = function(a, b){
  4882. if (typeof a === 'string') a = a.toLowerCase();
  4883. if (typeof b === 'string') b = b.toLowerCase();
  4884. if (a === b) return 0;
  4885. if (a < b) return -1;
  4886. return 1;
  4887. };
  4888. /**
  4889. * This is supplied either the cell value or jQuery object to parse. A value must be returned from this method and will be used during sorting operations.
  4890. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  4891. * @returns {*}
  4892. * @this FooTable.Column
  4893. */
  4894. F.Column.prototype.sortValue = function(valueOrElement){
  4895. // if we have an element or a jQuery object use jQuery to get the value
  4896. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
  4897. var data = $(valueOrElement).data('sortValue');
  4898. return F.is.defined(data) ? data : this.parser(valueOrElement);
  4899. }
  4900. // if options are supplied with the value
  4901. if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
  4902. if (F.is.string(valueOrElement.options.sortValue)) return valueOrElement.options.sortValue;
  4903. if (F.is.defined(valueOrElement.value)) valueOrElement = valueOrElement.value;
  4904. }
  4905. if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement;
  4906. return null;
  4907. };
  4908. // this is used to define the sorting specific properties on column creation
  4909. F.Column.prototype.__sorting_define__ = function(definition){
  4910. this.sorter = F.checkFnValue(this, definition.sorter, this.sorter);
  4911. this.direction = F.is.type(definition.direction, 'string') ? F.Sorting.dir(definition.direction) : null;
  4912. this.sortable = F.is.boolean(definition.sortable) ? definition.sortable : true;
  4913. this.sorted = F.is.boolean(definition.sorted) ? definition.sorted : false;
  4914. this.sortValue = F.checkFnValue(this, definition.sortValue, this.sortValue);
  4915. };
  4916. // overrides the public define method and replaces it with our own
  4917. F.Column.extend('define', function(definition){
  4918. this._super(definition);
  4919. this.__sorting_define__(definition);
  4920. });
  4921. })(jQuery, FooTable);
  4922. (function(F){
  4923. /**
  4924. * An object containing the sorting options for the plugin. Added by the {@link FooTable.Sorting} component.
  4925. * @type {object}
  4926. * @prop {boolean} enabled=false - Whether or not to allow sorting on the table.
  4927. */
  4928. F.Defaults.prototype.sorting = {
  4929. enabled: false
  4930. };
  4931. })(FooTable);
  4932. (function($, F){
  4933. F.HTMLColumn.extend('__sorting_define__', function(definition){
  4934. this._super(definition);
  4935. this.sortUse = F.is.string(definition.sortUse) && $.inArray(definition.sortUse, ['html','text']) !== -1 ? definition.sortUse : 'html';
  4936. });
  4937. /**
  4938. * This is supplied either the cell value or jQuery object to parse. A value must be returned from this method and will be used during sorting operations.
  4939. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  4940. * @returns {*}
  4941. * @this FooTable.HTMLColumn
  4942. */
  4943. F.HTMLColumn.prototype.sortValue = function(valueOrElement){
  4944. // if we have an element or a jQuery object use jQuery to get the data value or pass it off to the parser
  4945. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
  4946. var data = $(valueOrElement).data('sortValue');
  4947. return F.is.defined(data) ? data : this.parser(valueOrElement);
  4948. }
  4949. // if options are supplied with the value
  4950. if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
  4951. if (F.is.string(valueOrElement.options.sortValue)) return valueOrElement.options.sortValue;
  4952. if (F.is.defined(valueOrElement.value)) valueOrElement = valueOrElement.value;
  4953. }
  4954. if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement;
  4955. return null;
  4956. };
  4957. })(jQuery, FooTable);
  4958. (function($, F){
  4959. /**
  4960. * This is supplied either the cell value or jQuery object to parse. A value must be returned from this method and will be used during sorting operations.
  4961. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  4962. * @returns {*}
  4963. */
  4964. F.NumberColumn.prototype.sortValue = function(valueOrElement){
  4965. // if we have an element or a jQuery object use jQuery to get the data value or pass it off to the parser
  4966. if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
  4967. var data = $(valueOrElement).data('sortValue');
  4968. return F.is.number(data) ? data : this.parser(valueOrElement);
  4969. }
  4970. // if options are supplied with the value
  4971. if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
  4972. if (F.is.string(valueOrElement.options.sortValue)) return this.parser(valueOrElement);
  4973. if (F.is.number(valueOrElement.options.sortValue)) return valueOrElement.options.sortValue;
  4974. if (F.is.number(valueOrElement.value)) return valueOrElement.value;
  4975. }
  4976. if (F.is.string(valueOrElement)) return this.parser(valueOrElement);
  4977. if (F.is.number(valueOrElement)) return valueOrElement;
  4978. return null;
  4979. };
  4980. })(jQuery, FooTable);
  4981. (function(F){
  4982. /**
  4983. * Sort the table using the specified column and direction. Added by the {@link FooTable.Sorting} component.
  4984. * @instance
  4985. * @param {(string|number|FooTable.Column)} column - The column name, index or the actual {@link FooTable.Column} object to sort by.
  4986. * @param {string} [direction="ASC"] - The direction to sort by, either ASC or DESC.
  4987. * @returns {jQuery.Promise}
  4988. * @fires FooTable.Sorting#"change.ft.sorting"
  4989. * @fires FooTable.Sorting#"changed.ft.sorting"
  4990. * @see FooTable.Sorting#sort
  4991. */
  4992. F.Table.prototype.sort = function(column, direction){
  4993. return this.use(F.Sorting).sort(column, direction);
  4994. };
  4995. })(FooTable);
  4996. (function($, F){
  4997. F.Pager = F.Class.extend(/** @lends FooTable.Pager */{
  4998. /**
  4999. * The pager object contains the page number and direction to page to.
  5000. * @constructs
  5001. * @extends FooTable.Class
  5002. * @param {number} total - The total number of pages available.
  5003. * @param {number} current - The current page number.
  5004. * @param {number} size - The number of rows per page.
  5005. * @param {number} page - The page number to goto.
  5006. * @param {boolean} forward - A boolean indicating the direction of paging, TRUE = forward, FALSE = back.
  5007. * @returns {FooTable.Pager}
  5008. */
  5009. construct: function(total, current, size, page, forward){
  5010. /**
  5011. * The total number of pages available.
  5012. * @type {number}
  5013. */
  5014. this.total = total;
  5015. /**
  5016. * The current page number.
  5017. * @type {number}
  5018. */
  5019. this.current = current;
  5020. /**
  5021. * The number of rows per page.
  5022. * @type {number}
  5023. */
  5024. this.size = size;
  5025. /**
  5026. * The page number to goto.
  5027. * @type {number}
  5028. */
  5029. this.page = page;
  5030. /**
  5031. * A boolean indicating the direction of paging, TRUE = forward, FALSE = back.
  5032. * @type {boolean}
  5033. */
  5034. this.forward = forward;
  5035. }
  5036. });
  5037. })(jQuery, FooTable);
  5038. (function($, F){
  5039. F.Paging = F.Component.extend(/** @lends FooTable.Paging */{
  5040. /**
  5041. * The paging component adds a pagination control to the table allowing users to navigate table rows via pages.
  5042. * @constructs
  5043. * @extends FooTable.Component
  5044. * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
  5045. * @returns {FooTable.Filtering}
  5046. */
  5047. construct: function(table){
  5048. // call the base constructor
  5049. this._super(table, table.o.paging.enabled);
  5050. /* PROTECTED */
  5051. /**
  5052. * An object containing the strings used by the paging buttons.
  5053. * @type {{ first: string, prev: string, next: string, last: string }}
  5054. */
  5055. this.strings = table.o.paging.strings;
  5056. /* PUBLIC */
  5057. /**
  5058. * The current page number to display.
  5059. * @instance
  5060. * @type {number}
  5061. */
  5062. this.current = table.o.paging.current;
  5063. /**
  5064. * The number of rows to display per page.
  5065. * @instance
  5066. * @type {number}
  5067. */
  5068. this.size = table.o.paging.size;
  5069. /**
  5070. * The maximum number of page links to display at once.
  5071. * @instance
  5072. * @type {number}
  5073. */
  5074. this.limit = table.o.paging.limit;
  5075. /**
  5076. * The position of the pagination control within the paging rows cell.
  5077. * @instance
  5078. * @type {string}
  5079. */
  5080. this.position = table.o.paging.position;
  5081. /**
  5082. * The format string used to generate the text displayed under the pagination control.
  5083. * @instance
  5084. * @type {string}
  5085. */
  5086. this.countFormat = table.o.paging.countFormat;
  5087. /**
  5088. * A selector specifying where to place the paging components UI, if null the UI is displayed within a row in the foot of the table.
  5089. * @instance
  5090. * @type {string}
  5091. */
  5092. this.container = table.o.paging.container;
  5093. /**
  5094. * The total number of pages.
  5095. * @instance
  5096. * @type {number}
  5097. */
  5098. this.total = -1;
  5099. /**
  5100. * The number of rows in the {@link FooTable.Rows#array} before paging is applied.
  5101. * @instance
  5102. * @type {number}
  5103. */
  5104. this.totalRows = 0;
  5105. /**
  5106. * A number indicating the previous page displayed.
  5107. * @instance
  5108. * @type {number}
  5109. */
  5110. this.previous = -1;
  5111. /**
  5112. * The count string generated using the {@link FooTable.Filtering#countFormat} option. This value is only set after the first call to the {@link FooTable.Filtering#predraw} method.
  5113. * @instance
  5114. * @type {string}
  5115. */
  5116. this.formattedCount = null;
  5117. /**
  5118. * The jQuery object of the element containing the entire paging UI.
  5119. * @instance
  5120. * @type {jQuery}
  5121. */
  5122. this.$container = null;
  5123. /**
  5124. * The jQuery object of the element wrapping all the paging UI elements.
  5125. * @instance
  5126. * @type {jQuery}
  5127. */
  5128. this.$wrapper = null;
  5129. /** +
  5130. * The jQuery row object that contains all the paging specific elements.
  5131. * @instance
  5132. * @type {jQuery}
  5133. */
  5134. this.$row = null;
  5135. /**
  5136. * The jQuery cell object that contains the pagination control and total count.
  5137. * @instance
  5138. * @type {jQuery}
  5139. */
  5140. this.$cell = null;
  5141. /**
  5142. * The jQuery object that contains the links for the pagination control.
  5143. * @instance
  5144. * @type {jQuery}
  5145. */
  5146. this.$pagination = null;
  5147. /**
  5148. * The jQuery object that contains the row count.
  5149. * @instance
  5150. * @type {jQuery}
  5151. */
  5152. this.$count = null;
  5153. /**
  5154. * Whether or not the pagination row is detached from the table.
  5155. * @instance
  5156. * @type {boolean}
  5157. */
  5158. this.detached = true;
  5159. /* PRIVATE */
  5160. /**
  5161. * Used to hold the number of page links created.
  5162. * @instance
  5163. * @type {number}
  5164. * @private
  5165. */
  5166. this._createdLinks = 0;
  5167. },
  5168. /* PROTECTED */
  5169. /**
  5170. * Checks the supplied data and options for the paging component.
  5171. * @instance
  5172. * @protected
  5173. * @param {object} data - The jQuery data object from the parent table.
  5174. * @fires FooTable.Paging#"preinit.ft.paging"
  5175. */
  5176. preinit: function(data){
  5177. var self = this;
  5178. /**
  5179. * The preinit.ft.paging event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
  5180. * Calling preventDefault on this event will disable the component.
  5181. * @event FooTable.Paging#"preinit.ft.paging"
  5182. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  5183. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  5184. * @param {object} data - The jQuery data object of the table raising the event.
  5185. */
  5186. this.ft.raise('preinit.ft.paging', [data]).then(function(){
  5187. if (self.ft.$el.hasClass('footable-paging'))
  5188. self.enabled = true;
  5189. self.enabled = F.is.boolean(data.paging)
  5190. ? data.paging
  5191. : self.enabled;
  5192. if (!self.enabled) return;
  5193. self.size = F.is.number(data.pagingSize)
  5194. ? data.pagingSize
  5195. : self.size;
  5196. self.current = F.is.number(data.pagingCurrent)
  5197. ? data.pagingCurrent
  5198. : self.current;
  5199. self.limit = F.is.number(data.pagingLimit)
  5200. ? data.pagingLimit
  5201. : self.limit;
  5202. if (self.ft.$el.hasClass('footable-paging-left'))
  5203. self.position = 'left';
  5204. if (self.ft.$el.hasClass('footable-paging-center'))
  5205. self.position = 'center';
  5206. if (self.ft.$el.hasClass('footable-paging-right'))
  5207. self.position = 'right';
  5208. self.position = F.is.string(data.pagingPosition)
  5209. ? data.pagingPosition
  5210. : self.position;
  5211. self.countFormat = F.is.string(data.pagingCountFormat)
  5212. ? data.pagingCountFormat
  5213. : self.countFormat;
  5214. self.container = F.is.string(data.pagingContainer)
  5215. ? data.pagingContainer
  5216. : self.container;
  5217. self.total = Math.ceil(self.ft.rows.all.length / self.size);
  5218. }, function(){
  5219. self.enabled = false;
  5220. });
  5221. },
  5222. /**
  5223. * Initializes the paging component for the plugin using the supplied table and options.
  5224. * @instance
  5225. * @protected
  5226. * @fires FooTable.Paging#"init.ft.paging"
  5227. */
  5228. init: function(){
  5229. /**
  5230. * The init.ft.paging event is raised before its UI is generated.
  5231. * Calling preventDefault on this event will disable the component.
  5232. * @event FooTable.Paging#"init.ft.paging"
  5233. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  5234. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  5235. */
  5236. var self = this;
  5237. this.ft.raise('init.ft.paging').then(function(){
  5238. self.$create();
  5239. }, function(){
  5240. self.enabled = false;
  5241. });
  5242. },
  5243. /**
  5244. * Destroys the paging component removing any UI generated from the table.
  5245. * @instance
  5246. * @protected
  5247. * @fires FooTable.Paging#"destroy.ft.paging"
  5248. */
  5249. destroy: function () {
  5250. /**
  5251. * The destroy.ft.paging event is raised before its UI is removed.
  5252. * Calling preventDefault on this event will prevent the component from being destroyed.
  5253. * @event FooTable.Paging#"destroy.ft.paging"
  5254. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  5255. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  5256. */
  5257. var self = this;
  5258. this.ft.raise('destroy.ft.paging').then(function(){
  5259. self.ft.$el.removeClass('footable-paging')
  5260. .find('tfoot > tr.footable-paging').remove();
  5261. self.detached = true;
  5262. self._createdLinks = 0;
  5263. });
  5264. },
  5265. /**
  5266. * Performs the actual paging against the {@link FooTable.Rows#current} array removing all rows that are not on the current visible page.
  5267. * @instance
  5268. * @protected
  5269. */
  5270. predraw: function(){
  5271. this.total = Math.ceil(this.ft.rows.array.length / this.size);
  5272. this.current = this.current > this.total ? this.total : (this.current < 1 ? 1 : this.current);
  5273. this.totalRows = this.ft.rows.array.length;
  5274. if (this.totalRows > this.size){
  5275. this.ft.rows.array = this.ft.rows.array.splice((this.current - 1) * this.size, this.size);
  5276. }
  5277. this.formattedCount = this.format(this.countFormat);
  5278. },
  5279. /**
  5280. * Updates the paging UI setting the state of the pagination control.
  5281. * @instance
  5282. * @protected
  5283. */
  5284. draw: function(){
  5285. if (this.total <= 1){
  5286. if (!this.detached){
  5287. if (this.$row){
  5288. this.$row.detach();
  5289. } else {
  5290. this.$wrapper.detach();
  5291. }
  5292. this.detached = true;
  5293. }
  5294. } else {
  5295. if (this.detached){
  5296. if (this.$row){
  5297. var $tfoot = this.ft.$el.children('tfoot');
  5298. if ($tfoot.length == 0){
  5299. $tfoot = $('<tfoot/>');
  5300. this.ft.$el.append($tfoot);
  5301. }
  5302. this.$row.appendTo($tfoot);
  5303. } else {
  5304. this.$wrapper.appendTo(this.$container);
  5305. }
  5306. this.detached = false;
  5307. }
  5308. if (F.is.jq(this.$cell)){
  5309. this.$cell.attr('colspan', this.ft.columns.visibleColspan);
  5310. }
  5311. this._createLinks();
  5312. this._setVisible(this.current, this.current > this.previous);
  5313. this._setNavigation(true);
  5314. this.$count.text(this.formattedCount);
  5315. }
  5316. },
  5317. /**
  5318. * Creates the paging UI from the current options setting the various jQuery properties of this component.
  5319. * @instance
  5320. * @protected
  5321. */
  5322. $create: function(){
  5323. this._createdLinks = 0;
  5324. var position = 'footable-paging-center';
  5325. switch (this.position){
  5326. case 'left': position = 'footable-paging-left'; break;
  5327. case 'right': position = 'footable-paging-right'; break;
  5328. }
  5329. this.ft.$el.addClass('footable-paging').addClass(position);
  5330. this.$container = this.container === null ? null : $(this.container).first();
  5331. if (!F.is.jq(this.$container)){
  5332. var $tfoot = this.ft.$el.children('tfoot');
  5333. if ($tfoot.length == 0){
  5334. $tfoot = $('<tfoot/>');
  5335. this.ft.$el.append($tfoot);
  5336. }
  5337. // add it to a row and then populate it with the search input and column selector dropdown.
  5338. this.$row = $('<tr/>', {'class': 'footable-paging'}).prependTo($tfoot);
  5339. this.$container = this.$cell = $('<td/>').attr('colspan', this.ft.columns.visibleColspan).appendTo(this.$row);
  5340. } else {
  5341. this.$container.addClass('footable-paging-external').addClass(position);
  5342. }
  5343. this.$wrapper = $('<div/>', {'class': 'footable-pagination-wrapper'}).appendTo(this.$container);
  5344. this.$pagination = $('<ul/>', { 'class': 'pagination' }).on('click.footable', 'a.footable-page-link', { self: this }, this._onPageClicked);
  5345. this.$count = $('<span/>', { 'class': 'label label-default' });
  5346. this.$wrapper.append(this.$pagination, $('<div/>', {'class': 'divider'}), this.$count);
  5347. this.detached = false;
  5348. },
  5349. /* PUBLIC */
  5350. /**
  5351. * @summary Uses the supplied format string and replaces the placeholder strings with the current values.
  5352. * @description This method is used to generate the short description label for the pagination control. i.e. Showing X of Y records. The placeholders for this string are the following:
  5353. * * {CP} - The current page number.
  5354. * * {TP} - The total number of pages.
  5355. * * {PF} - The first row of the current page.
  5356. * * {PL} - The last row of the current page.
  5357. * * {TR} - The total rows available.
  5358. * These placeholders can be supplied in a string like; "Showing {PF} to {PL} of {TR} rows."
  5359. * @param {string} formatString - The string to be formatted with the paging specific variables.
  5360. * @returns {string}
  5361. */
  5362. format: function(formatString){
  5363. var firstRow = (this.size * (this.current - 1)) + 1,
  5364. lastRow = this.size * this.current;
  5365. if (this.ft.rows.array.length == 0){
  5366. firstRow = 0;
  5367. lastRow = 0;
  5368. } else {
  5369. lastRow = lastRow > this.totalRows ? this.totalRows : lastRow;
  5370. }
  5371. return formatString.replace(/\{CP}/g, this.current)
  5372. .replace(/\{TP}/g, this.total)
  5373. .replace(/\{PF}/g, firstRow)
  5374. .replace(/\{PL}/g, lastRow)
  5375. .replace(/\{TR}/g, this.totalRows);
  5376. },
  5377. /**
  5378. * Pages to the first page.
  5379. * @instance
  5380. * @returns {jQuery.Promise}
  5381. * @fires FooTable.Paging#"before.ft.paging"
  5382. * @fires FooTable.Paging#"after.ft.paging"
  5383. */
  5384. first: function(){
  5385. return this._set(1);
  5386. },
  5387. /**
  5388. * Pages to the previous page.
  5389. * @instance
  5390. * @returns {jQuery.Promise}
  5391. * @fires FooTable.Paging#"before.ft.paging"
  5392. * @fires FooTable.Paging#"after.ft.paging"
  5393. */
  5394. prev: function(){
  5395. return this._set(this.current - 1 > 0 ? this.current - 1 : 1);
  5396. },
  5397. /**
  5398. * Pages to the next page.
  5399. * @instance
  5400. * @returns {jQuery.Promise}
  5401. * @fires FooTable.Paging#"before.ft.paging"
  5402. * @fires FooTable.Paging#"after.ft.paging"
  5403. */
  5404. next: function(){
  5405. return this._set(this.current + 1 < this.total ? this.current + 1 : this.total);
  5406. },
  5407. /**
  5408. * Pages to the last page.
  5409. * @instance
  5410. * @returns {jQuery.Promise}
  5411. * @fires FooTable.Paging#"before.ft.paging"
  5412. * @fires FooTable.Paging#"after.ft.paging"
  5413. */
  5414. last: function(){
  5415. return this._set(this.total);
  5416. },
  5417. /**
  5418. * Pages to the specified page.
  5419. * @instance
  5420. * @param {number} page - The page number to go to.
  5421. * @returns {jQuery.Promise}
  5422. * @fires FooTable.Paging#"before.ft.paging"
  5423. * @fires FooTable.Paging#"after.ft.paging"
  5424. */
  5425. goto: function(page){
  5426. return this._set(page > this.total ? this.total : (page < 1 ? 1 : page));
  5427. },
  5428. /**
  5429. * Shows the previous X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit option value.
  5430. * @instance
  5431. */
  5432. prevPages: function(){
  5433. var page = this.$pagination.children('li.footable-page.visible:first').data('page') - 1;
  5434. this._setVisible(page, true);
  5435. this._setNavigation(false);
  5436. },
  5437. /**
  5438. * Shows the next X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit option value.
  5439. * @instance
  5440. */
  5441. nextPages: function(){
  5442. var page = this.$pagination.children('li.footable-page.visible:last').data('page') + 1;
  5443. this._setVisible(page, false);
  5444. this._setNavigation(false);
  5445. },
  5446. /**
  5447. * Gets or sets the current page size.
  5448. * @instance
  5449. * @param {(number|string)} [value] - The new page size to use, this value is supplied to `parseInt` so strings can be used. If not supplied or an invalid valid the current page size is returned.
  5450. * @returns {(number|undefined)}
  5451. */
  5452. pageSize: function(value){
  5453. value = parseInt(value);
  5454. if (isNaN(value)){
  5455. return this.size;
  5456. }
  5457. this.size = value;
  5458. this.total = Math.ceil(this.ft.rows.all.length / this.size);
  5459. if (F.is.jq(this.$wrapper)){
  5460. if (this.$container.is("td")){
  5461. this.$row.remove();
  5462. } else {
  5463. this.$wrapper.remove();
  5464. }
  5465. }
  5466. this.$create();
  5467. this.ft.draw();
  5468. },
  5469. /* PRIVATE */
  5470. /**
  5471. * Performs the required steps to handle paging including the raising of the {@link FooTable.Paging#"before.ft.paging"} and {@link FooTable.Paging#"after.ft.paging"} events.
  5472. * @instance
  5473. * @private
  5474. * @param {number} page - The page to set.
  5475. * @returns {jQuery.Promise}
  5476. * @fires FooTable.Paging#"before.ft.paging"
  5477. * @fires FooTable.Paging#"after.ft.paging"
  5478. */
  5479. _set: function(page){
  5480. var self = this,
  5481. pager = new F.Pager(self.total, self.current, self.size, page, page > self.current);
  5482. /**
  5483. * The before.ft.paging event is raised before a sort is applied and allows listeners to modify the pager or cancel it completely by calling preventDefault on the jQuery.Event object.
  5484. * @event FooTable.Paging#"before.ft.paging"
  5485. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  5486. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  5487. * @param {FooTable.Pager} pager - The pager that is about to be applied.
  5488. */
  5489. return self.ft.raise('before.ft.paging', [pager]).then(function(){
  5490. pager.page = pager.page > pager.total ? pager.total : pager.page;
  5491. pager.page = pager.page < 1 ? 1 : pager.page;
  5492. if (self.current == page) return $.when();
  5493. self.previous = self.current;
  5494. self.current = pager.page;
  5495. return self.ft.draw().then(function(){
  5496. /**
  5497. * The after.ft.paging event is raised after a pager has been applied.
  5498. * @event FooTable.Paging#"after.ft.paging"
  5499. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  5500. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  5501. * @param {FooTable.Pager} pager - The pager that has been applied.
  5502. */
  5503. self.ft.raise('after.ft.paging', [pager]);
  5504. });
  5505. });
  5506. },
  5507. /**
  5508. * Creates the pagination links using the current state of the plugin. If the total number of pages is the same as
  5509. * the last time this function was executed it does nothing.
  5510. * @instance
  5511. * @private
  5512. */
  5513. _createLinks: function(){
  5514. if (this._createdLinks === this.total) return;
  5515. var self = this,
  5516. multiple = self.total > 1,
  5517. link = function(attr, html, klass){
  5518. return $('<li/>', {
  5519. 'class': klass
  5520. }).attr('data-page', attr)
  5521. .append($('<a/>', {
  5522. 'class': 'footable-page-link',
  5523. href: '#'
  5524. }).data('page', attr).html(html));
  5525. };
  5526. self.$pagination.empty();
  5527. if (multiple) {
  5528. self.$pagination.append(link('first', self.strings.first, 'footable-page-nav'));
  5529. self.$pagination.append(link('prev', self.strings.prev, 'footable-page-nav'));
  5530. if (self.limit > 0 && self.limit < self.total){
  5531. self.$pagination.append(link('prev-limit', self.strings.prevPages, 'footable-page-nav'));
  5532. }
  5533. }
  5534. for (var i = 0, $li; i < self.total; i++){
  5535. $li = link(i + 1, i + 1, 'footable-page');
  5536. self.$pagination.append($li);
  5537. }
  5538. if (multiple){
  5539. if (self.limit > 0 && self.limit < self.total){
  5540. self.$pagination.append(link('next-limit', self.strings.nextPages, 'footable-page-nav'));
  5541. }
  5542. self.$pagination.append(link('next', self.strings.next, 'footable-page-nav'));
  5543. self.$pagination.append(link('last', self.strings.last, 'footable-page-nav'));
  5544. }
  5545. self._createdLinks = self.total;
  5546. },
  5547. /**
  5548. * Sets the state for the navigation links of the pagination control and optionally sets the active class state on the current page link.
  5549. * @instance
  5550. * @private
  5551. * @param {boolean} active - Whether or not to set the active class state on the individual page links.
  5552. */
  5553. _setNavigation: function(active){
  5554. if (this.current == 1) {
  5555. this.$pagination.children('li[data-page="first"],li[data-page="prev"]').addClass('disabled');
  5556. } else {
  5557. this.$pagination.children('li[data-page="first"],li[data-page="prev"]').removeClass('disabled');
  5558. }
  5559. if (this.current == this.total) {
  5560. this.$pagination.children('li[data-page="next"],li[data-page="last"]').addClass('disabled');
  5561. } else {
  5562. this.$pagination.children('li[data-page="next"],li[data-page="last"]').removeClass('disabled');
  5563. }
  5564. if ((this.$pagination.children('li.footable-page.visible:first').data('page') || 1) == 1) {
  5565. this.$pagination.children('li[data-page="prev-limit"]').addClass('disabled');
  5566. } else {
  5567. this.$pagination.children('li[data-page="prev-limit"]').removeClass('disabled');
  5568. }
  5569. if ((this.$pagination.children('li.footable-page.visible:last').data('page') || this.limit) == this.total) {
  5570. this.$pagination.children('li[data-page="next-limit"]').addClass('disabled');
  5571. } else {
  5572. this.$pagination.children('li[data-page="next-limit"]').removeClass('disabled');
  5573. }
  5574. if (this.limit > 0 && this.total < this.limit){
  5575. this.$pagination.children('li[data-page="prev-limit"],li[data-page="next-limit"]').css('display', 'none');
  5576. } else {
  5577. this.$pagination.children('li[data-page="prev-limit"],li[data-page="next-limit"]').css('display', '');
  5578. }
  5579. if (active){
  5580. this.$pagination.children('li.footable-page').removeClass('active').filter('li[data-page="' + this.current + '"]').addClass('active');
  5581. }
  5582. },
  5583. /**
  5584. * Sets the visible page using the supplied parameters.
  5585. * @instance
  5586. * @private
  5587. * @param {number} page - The page to make visible.
  5588. * @param {boolean} right - If set to true the supplied page will be the right most visible pagination link.
  5589. */
  5590. _setVisible: function(page, right){
  5591. if (this.limit > 0 && this.total > this.limit){
  5592. if (!this.$pagination.children('li.footable-page[data-page="'+page+'"]').hasClass('visible')){
  5593. var start = 0, end = 0;
  5594. if (right == true){
  5595. end = page > this.total ? this.total : page;
  5596. start = end - this.limit;
  5597. } else {
  5598. start = page < 1 ? 0 : page - 1;
  5599. end = start + this.limit;
  5600. }
  5601. if (start < 0){
  5602. start = 0;
  5603. end = this.limit > this.total ? this.total : this.limit;
  5604. }
  5605. if (end > this.total){
  5606. end = this.total;
  5607. start = this.total - this.limit < 0 ? 0 : this.total - this.limit;
  5608. }
  5609. this.$pagination.children('li.footable-page').removeClass('visible').slice(start, end).addClass('visible');
  5610. }
  5611. } else {
  5612. this.$pagination.children('li.footable-page').removeClass('visible').slice(0, this.total).addClass('visible');
  5613. }
  5614. },
  5615. /**
  5616. * Handles the click event for all links in the pagination control.
  5617. * @instance
  5618. * @private
  5619. * @param {jQuery.Event} e - The event object for the event.
  5620. */
  5621. _onPageClicked: function(e){
  5622. e.preventDefault();
  5623. if ($(e.target).closest('li').is('.active,.disabled')) return;
  5624. var self = e.data.self, page = $(this).data('page');
  5625. switch(page){
  5626. case 'first': self.first();
  5627. return;
  5628. case 'prev': self.prev();
  5629. return;
  5630. case 'next': self.next();
  5631. return;
  5632. case 'last': self.last();
  5633. return;
  5634. case 'prev-limit': self.prevPages();
  5635. return;
  5636. case 'next-limit': self.nextPages();
  5637. return;
  5638. default: self._set(page);
  5639. return;
  5640. }
  5641. }
  5642. });
  5643. F.components.register('paging', F.Paging, 400);
  5644. })(jQuery, FooTable);
  5645. (function(F){
  5646. /**
  5647. * An object containing the paging options for the plugin. Added by the {@link FooTable.Paging} component.
  5648. * @type {object}
  5649. * @prop {boolean} enabled=false - Whether or not to allow paging on the table.
  5650. * @prop {string} countFormat="{CP} of {TP}" - A string format used to generate the page count text.
  5651. * @prop {number} current=1 - The page number to display.
  5652. * @prop {number} limit=5 - The maximum number of page links to display at once.
  5653. * @prop {string} position="center" - The string used to specify the alignment of the pagination control.
  5654. * @prop {number} size=10 - The number of rows displayed per page.
  5655. * @prop {string} container=null - A selector specifying where to place the paging components UI, if null the UI is displayed within a row in the foot of the table.
  5656. * @prop {object} strings - An object containing the strings used by the paging buttons.
  5657. * @prop {string} strings.first="&laquo;" - The string used for the 'first' button.
  5658. * @prop {string} strings.prev="&lsaquo;" - The string used for the 'previous' button.
  5659. * @prop {string} strings.next="&rsaquo;" - The string used for the 'next' button.
  5660. * @prop {string} strings.last="&raquo;" - The string used for the 'last' button.
  5661. * @prop {string} strings.prevPages="..." - The string used for the 'previous X pages' button.
  5662. * @prop {string} strings.nextPages="..." - The string used for the 'next X pages' button.
  5663. */
  5664. F.Defaults.prototype.paging = {
  5665. enabled: false,
  5666. countFormat: '{CP} of {TP}',
  5667. current: 1,
  5668. limit: 5,
  5669. position: 'center',
  5670. size: 10,
  5671. container: null,
  5672. strings: {
  5673. first: '&laquo;',
  5674. prev: '&lsaquo;',
  5675. next: '&rsaquo;',
  5676. last: '&raquo;',
  5677. prevPages: '...',
  5678. nextPages: '...'
  5679. }
  5680. };
  5681. })(FooTable);
  5682. (function(F){
  5683. /**
  5684. * Navigates to the specified page number. Added by the {@link FooTable.Paging} component.
  5685. * @instance
  5686. * @param {number} num - The page number to go to.
  5687. * @returns {jQuery.Promise}
  5688. * @fires FooTable.Paging#paging_changing
  5689. * @fires FooTable.Paging#paging_changed
  5690. * @see FooTable.Paging#goto
  5691. */
  5692. F.Table.prototype.gotoPage = function(num){
  5693. return this.use(F.Paging).goto(num);
  5694. };
  5695. /**
  5696. * Navigates to the next page. Added by the {@link FooTable.Paging} component.
  5697. * @instance
  5698. * @returns {jQuery.Promise}
  5699. * @fires FooTable.Paging#paging_changing
  5700. * @fires FooTable.Paging#paging_changed
  5701. * @see FooTable.Paging#next
  5702. */
  5703. F.Table.prototype.nextPage = function(){
  5704. return this.use(F.Paging).next();
  5705. };
  5706. /**
  5707. * Navigates to the previous page. Added by the {@link FooTable.Paging} component.
  5708. * @instance
  5709. * @returns {jQuery.Promise}
  5710. * @fires FooTable.Paging#paging_changing
  5711. * @fires FooTable.Paging#paging_changed
  5712. * @see FooTable.Paging#prev
  5713. */
  5714. F.Table.prototype.prevPage = function(){
  5715. return this.use(F.Paging).prev();
  5716. };
  5717. /**
  5718. * Navigates to the first page. Added by the {@link FooTable.Paging} component.
  5719. * @instance
  5720. * @returns {jQuery.Promise}
  5721. * @fires FooTable.Paging#paging_changing
  5722. * @fires FooTable.Paging#paging_changed
  5723. * @see FooTable.Paging#first
  5724. */
  5725. F.Table.prototype.firstPage = function(){
  5726. return this.use(F.Paging).first();
  5727. };
  5728. /**
  5729. * Navigates to the last page. Added by the {@link FooTable.Paging} component.
  5730. * @instance
  5731. * @returns {jQuery.Promise}
  5732. * @fires FooTable.Paging#paging_changing
  5733. * @fires FooTable.Paging#paging_changed
  5734. * @see FooTable.Paging#last
  5735. */
  5736. F.Table.prototype.lastPage = function(){
  5737. return this.use(F.Paging).last();
  5738. };
  5739. /**
  5740. * Shows the next X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit.size option value. Added by the {@link FooTable.Paging} component.
  5741. * @instance
  5742. * @see FooTable.Paging#nextPages
  5743. */
  5744. F.Table.prototype.nextPages = function(){
  5745. return this.use(F.Paging).nextPages();
  5746. };
  5747. /**
  5748. * Shows the previous X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit.size option value. Added by the {@link FooTable.Paging} component.
  5749. * @instance
  5750. * @see FooTable.Paging#prevPages
  5751. */
  5752. F.Table.prototype.prevPages = function(){
  5753. return this.use(F.Paging).prevPages();
  5754. };
  5755. /**
  5756. * Gets or sets the current page size
  5757. * @instance
  5758. * @param {number} [value] - The new page size to use.
  5759. * @returns {(number|undefined)}
  5760. * @see FooTable.Paging#pageSize
  5761. */
  5762. F.Table.prototype.pageSize = function(value){
  5763. return this.use(F.Paging).pageSize(value);
  5764. };
  5765. })(FooTable);
  5766. (function($, F){
  5767. F.Editing = F.Component.extend(/** @lends FooTable.Editing */{
  5768. /**
  5769. * The editing component adds a column with edit and delete buttons to each row as well as a single add row button in the footer.
  5770. * @constructs
  5771. * @extends FooTable.Component
  5772. * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
  5773. * @returns {FooTable.Editing}
  5774. */
  5775. construct: function(table){
  5776. // call the base constructor
  5777. this._super(table, table.o.editing.enabled);
  5778. /**
  5779. * Whether or not to automatically page to a new row when it is added to the table.
  5780. * @type {boolean}
  5781. */
  5782. this.pageToNew = table.o.editing.pageToNew;
  5783. /**
  5784. * Whether or not the editing column and add row button are always visible.
  5785. * @type {boolean}
  5786. */
  5787. this.alwaysShow = table.o.editing.alwaysShow;
  5788. /**
  5789. * The options for the editing column. @see {@link FooTable.EditingColumn} for more info.
  5790. * @type {object}
  5791. * @prop {string} classes="footable-editing" - A space separated string of class names to apply to all cells in the column.
  5792. * @prop {string} name="editing" - The name of the column.
  5793. * @prop {string} title="" - The title displayed in the header row of the table for the column.
  5794. * @prop {boolean} filterable=false - Whether or not the column should be filterable when using the filtering component.
  5795. * @prop {boolean} sortable=false - Whether or not the column should be sortable when using the sorting component.
  5796. */
  5797. this.column = $.extend(true, {}, table.o.editing.column, {visible: this.alwaysShow});
  5798. /**
  5799. * The position of the editing column in the table as well as the alignment of the buttons.
  5800. * @type {string}
  5801. */
  5802. this.position = table.o.editing.position;
  5803. /**
  5804. * The text that appears in the show button. This can contain HTML.
  5805. * @type {string}
  5806. */
  5807. this.showText = table.o.editing.showText;
  5808. /**
  5809. * The text that appears in the hide button. This can contain HTML.
  5810. * @type {string}
  5811. */
  5812. this.hideText = table.o.editing.hideText;
  5813. /**
  5814. * The text that appears in the add button. This can contain HTML.
  5815. * @type {string}
  5816. */
  5817. this.addText = table.o.editing.addText;
  5818. /**
  5819. * The text that appears in the edit button. This can contain HTML.
  5820. * @type {string}
  5821. */
  5822. this.editText = table.o.editing.editText;
  5823. /**
  5824. * The text that appears in the delete button. This can contain HTML.
  5825. * @type {string}
  5826. */
  5827. this.deleteText = table.o.editing.deleteText;
  5828. /**
  5829. * The text that appears in the view button. This can contain HTML.
  5830. * @type {string}
  5831. */
  5832. this.viewText = table.o.editing.viewText;
  5833. /**
  5834. * Whether or not to show the Add Row button.
  5835. * @type {boolean}
  5836. */
  5837. this.allowAdd = table.o.editing.allowAdd;
  5838. /**
  5839. * Whether or not to show the Edit Row button.
  5840. * @type {boolean}
  5841. */
  5842. this.allowEdit = table.o.editing.allowEdit;
  5843. /**
  5844. * Whether or not to show the Delete Row button.
  5845. * @type {boolean}
  5846. */
  5847. this.allowDelete = table.o.editing.allowDelete;
  5848. /**
  5849. * Whether or not to show the View Row button.
  5850. * @type {boolean}
  5851. */
  5852. this.allowView = table.o.editing.allowView;
  5853. /**
  5854. * Caches the row button elements to help with performance.
  5855. * @type {(null|jQuery)}
  5856. * @private
  5857. */
  5858. this._$buttons = null;
  5859. /**
  5860. * This object is used to contain the callbacks for the add, edit and delete row buttons.
  5861. * @type {object}
  5862. * @prop {function} addRow
  5863. * @prop {function} editRow
  5864. * @prop {function} deleteRow
  5865. * @prop {function} viewRow
  5866. */
  5867. this.callbacks = {
  5868. addRow: F.checkFnValue(this, table.o.editing.addRow),
  5869. editRow: F.checkFnValue(this, table.o.editing.editRow),
  5870. deleteRow: F.checkFnValue(this, table.o.editing.deleteRow),
  5871. viewRow: F.checkFnValue(this, table.o.editing.viewRow)
  5872. };
  5873. },
  5874. /* PROTECTED */
  5875. /**
  5876. * Checks the supplied data and options for the editing component.
  5877. * @instance
  5878. * @protected
  5879. * @param {object} data - The jQuery data object from the parent table.
  5880. * @fires FooTable.Editing#"preinit.ft.editing"
  5881. */
  5882. preinit: function(data){
  5883. var self = this;
  5884. /**
  5885. * The preinit.ft.editing event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
  5886. * Calling preventDefault on this event will disable the component.
  5887. * @event FooTable.Editing#"preinit.ft.editing"
  5888. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  5889. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  5890. * @param {object} data - The jQuery data object of the table raising the event.
  5891. */
  5892. this.ft.raise('preinit.ft.editing', [data]).then(function(){
  5893. if (self.ft.$el.hasClass('footable-editing'))
  5894. self.enabled = true;
  5895. self.enabled = F.is.boolean(data.editing)
  5896. ? data.editing
  5897. : self.enabled;
  5898. if (!self.enabled) return;
  5899. self.pageToNew = F.is.boolean(data.editingPageToNew) ? data.editingPageToNew : self.pageToNew;
  5900. self.alwaysShow = F.is.boolean(data.editingAlwaysShow) ? data.editingAlwaysShow : self.alwaysShow;
  5901. self.position = F.is.string(data.editingPosition) ? data.editingPosition : self.position;
  5902. self.showText = F.is.string(data.editingShowText) ? data.editingShowText : self.showText;
  5903. self.hideText = F.is.string(data.editingHideText) ? data.editingHideText : self.hideText;
  5904. self.addText = F.is.string(data.editingAddText) ? data.editingAddText : self.addText;
  5905. self.editText = F.is.string(data.editingEditText) ? data.editingEditText : self.editText;
  5906. self.deleteText = F.is.string(data.editingDeleteText) ? data.editingDeleteText : self.deleteText;
  5907. self.viewText = F.is.string(data.editingViewText) ? data.editingViewText : self.viewText;
  5908. self.allowAdd = F.is.boolean(data.editingAllowAdd) ? data.editingAllowAdd : self.allowAdd;
  5909. self.allowEdit = F.is.boolean(data.editingAllowEdit) ? data.editingAllowEdit : self.allowEdit;
  5910. self.allowDelete = F.is.boolean(data.editingAllowDelete) ? data.editingAllowDelete : self.allowDelete;
  5911. self.allowView = F.is.boolean(data.editingAllowView) ? data.editingAllowView : self.allowView;
  5912. self.column = new F.EditingColumn(self.ft, self, $.extend(true, {}, self.column, data.editingColumn, {visible: self.alwaysShow}));
  5913. if (self.ft.$el.hasClass('footable-editing-left'))
  5914. self.position = 'left';
  5915. if (self.ft.$el.hasClass('footable-editing-right'))
  5916. self.position = 'right';
  5917. if (self.position === 'right'){
  5918. self.column.index = self.ft.columns.array.length;
  5919. } else {
  5920. self.column.index = 0;
  5921. for (var i = 0, len = self.ft.columns.array.length; i < len; i++){
  5922. self.ft.columns.array[i].index += 1;
  5923. }
  5924. }
  5925. self.ft.columns.array.push(self.column);
  5926. self.ft.columns.array.sort(function(a, b){ return a.index - b.index; });
  5927. self.callbacks.addRow = F.checkFnValue(self, data.editingAddRow, self.callbacks.addRow);
  5928. self.callbacks.editRow = F.checkFnValue(self, data.editingEditRow, self.callbacks.editRow);
  5929. self.callbacks.deleteRow = F.checkFnValue(self, data.editingDeleteRow, self.callbacks.deleteRow);
  5930. self.callbacks.viewRow = F.checkFnValue(self, data.editingViewRow, self.callbacks.viewRow);
  5931. }, function(){
  5932. self.enabled = false;
  5933. });
  5934. },
  5935. /**
  5936. * Initializes the editing component for the plugin using the supplied table and options.
  5937. * @instance
  5938. * @protected
  5939. * @fires FooTable.Editing#"init.ft.editing"
  5940. */
  5941. init: function(){
  5942. /**
  5943. * The init.ft.editing event is raised before its UI is generated.
  5944. * Calling preventDefault on this event will disable the component.
  5945. * @event FooTable.Editing#"init.ft.editing"
  5946. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  5947. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  5948. */
  5949. var self = this;
  5950. this.ft.raise('init.ft.editing').then(function(){
  5951. self.$create();
  5952. }, function(){
  5953. self.enabled = false;
  5954. });
  5955. },
  5956. /**
  5957. * Destroys the editing component removing any UI generated from the table.
  5958. * @instance
  5959. * @protected
  5960. * @fires FooTable.Editing#"destroy.ft.editing"
  5961. */
  5962. destroy: function () {
  5963. /**
  5964. * The destroy.ft.editing event is raised before its UI is removed.
  5965. * Calling preventDefault on this event will prevent the component from being destroyed.
  5966. * @event FooTable.Editing#"destroy.ft.editing"
  5967. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  5968. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  5969. */
  5970. var self = this;
  5971. this.ft.raise('destroy.ft.editing').then(function(){
  5972. self.ft.$el.removeClass('footable-editing footable-editing-always-show footable-editing-no-add footable-editing-no-edit footable-editing-no-delete footable-editing-no-view')
  5973. .off('click.ft.editing').find('tfoot > tr.footable-editing').remove();
  5974. });
  5975. },
  5976. /**
  5977. * Creates the editing UI from the current options setting the various jQuery properties of this component.
  5978. * @instance
  5979. * @protected
  5980. */
  5981. $create: function(){
  5982. var self = this, position = self.position === 'right' ? 'footable-editing-right' : 'footable-editing-left';
  5983. self.ft.$el.addClass('footable-editing').addClass(position)
  5984. .on('click.ft.editing', '.footable-show', {self: self}, self._onShowClick)
  5985. .on('click.ft.editing', '.footable-hide', {self: self}, self._onHideClick)
  5986. .on('click.ft.editing', '.footable-edit', {self: self}, self._onEditClick)
  5987. .on('click.ft.editing', '.footable-delete', {self: self}, self._onDeleteClick)
  5988. .on('click.ft.editing', '.footable-view', {self: self}, self._onViewClick)
  5989. .on('click.ft.editing', '.footable-add', {self: self}, self._onAddClick);
  5990. self.$cell = $('<td/>').attr('colspan', self.ft.columns.visibleColspan).append(self.$buttonShow());
  5991. if (self.allowAdd){
  5992. self.$cell.append(self.$buttonAdd());
  5993. }
  5994. self.$cell.append(self.$buttonHide());
  5995. if (self.alwaysShow){
  5996. self.ft.$el.addClass('footable-editing-always-show');
  5997. }
  5998. if (!self.allowAdd) self.ft.$el.addClass('footable-editing-no-add');
  5999. if (!self.allowEdit) self.ft.$el.addClass('footable-editing-no-edit');
  6000. if (!self.allowDelete) self.ft.$el.addClass('footable-editing-no-delete');
  6001. if (!self.allowView) self.ft.$el.addClass('footable-editing-no-view');
  6002. var $tfoot = self.ft.$el.children('tfoot');
  6003. if ($tfoot.length == 0){
  6004. $tfoot = $('<tfoot/>');
  6005. self.ft.$el.append($tfoot);
  6006. }
  6007. self.$row = $('<tr/>', { 'class': 'footable-editing' }).append(self.$cell).appendTo($tfoot);
  6008. },
  6009. /**
  6010. * Creates the show button for the editing component.
  6011. * @instance
  6012. * @protected
  6013. * @returns {(string|HTMLElement|jQuery)}
  6014. */
  6015. $buttonShow: function(){
  6016. return '<button type="button" class="btn btn-primary footable-show">' + this.showText + '</button>';
  6017. },
  6018. /**
  6019. * Creates the hide button for the editing component.
  6020. * @instance
  6021. * @protected
  6022. * @returns {(string|HTMLElement|jQuery)}
  6023. */
  6024. $buttonHide: function(){
  6025. return '<button type="button" class="btn btn-default footable-hide">' + this.hideText + '</button>';
  6026. },
  6027. /**
  6028. * Creates the add button for the editing component.
  6029. * @instance
  6030. * @protected
  6031. * @returns {(string|HTMLElement|jQuery)}
  6032. */
  6033. $buttonAdd: function(){
  6034. return '<button type="button" class="btn btn-primary footable-add">' + this.addText + '</button> ';
  6035. },
  6036. /**
  6037. * Creates the edit button for the editing component.
  6038. * @instance
  6039. * @protected
  6040. * @returns {(string|HTMLElement|jQuery)}
  6041. */
  6042. $buttonEdit: function(){
  6043. return '<button type="button" class="btn btn-default footable-edit">' + this.editText + '</button> ';
  6044. },
  6045. /**
  6046. * Creates the delete button for the editing component.
  6047. * @instance
  6048. * @protected
  6049. * @returns {(string|HTMLElement|jQuery)}
  6050. */
  6051. $buttonDelete: function(){
  6052. return '<button type="button" class="btn btn-default footable-delete">' + this.deleteText + '</button>';
  6053. },
  6054. /**
  6055. * Creates the view button for the editing component.
  6056. * @instance
  6057. * @protected
  6058. * @returns {(string|HTMLElement|jQuery)}
  6059. */
  6060. $buttonView: function(){
  6061. return '<button type="button" class="btn btn-default footable-view">' + this.viewText + '</button> ';
  6062. },
  6063. /**
  6064. * Creates the button group for the row buttons.
  6065. * @instance
  6066. * @protected
  6067. * @returns {(string|HTMLElement|jQuery)}
  6068. */
  6069. $rowButtons: function(){
  6070. if (F.is.jq(this._$buttons)) return this._$buttons.clone();
  6071. this._$buttons = $('<div class="btn-group btn-group-xs" role="group"></div>');
  6072. if (this.allowView) this._$buttons.append(this.$buttonView());
  6073. if (this.allowEdit) this._$buttons.append(this.$buttonEdit());
  6074. if (this.allowDelete) this._$buttons.append(this.$buttonDelete());
  6075. return this._$buttons;
  6076. },
  6077. /**
  6078. * Performs the drawing of the component.
  6079. */
  6080. draw: function(){
  6081. this.$cell.attr('colspan', this.ft.columns.visibleColspan);
  6082. },
  6083. /**
  6084. * Handles the edit button click event.
  6085. * @instance
  6086. * @private
  6087. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6088. * @fires FooTable.Editing#"edit.ft.editing"
  6089. */
  6090. _onEditClick: function(e){
  6091. e.preventDefault();
  6092. var self = e.data.self, row = $(this).closest('tr').data('__FooTableRow__');
  6093. if (row instanceof F.Row){
  6094. /**
  6095. * The edit.ft.editing event is raised before its callback is executed.
  6096. * Calling preventDefault on this event will prevent the callback from being executed.
  6097. * @event FooTable.Editing#"edit.ft.editing"
  6098. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6099. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  6100. * @param {FooTable.Row} row - The row to be edited.
  6101. */
  6102. self.ft.raise('edit.ft.editing', [row]).then(function(){
  6103. self.callbacks.editRow.call(self.ft, row);
  6104. });
  6105. }
  6106. },
  6107. /**
  6108. * Handles the delete button click event.
  6109. * @instance
  6110. * @private
  6111. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6112. * @fires FooTable.Editing#"delete.ft.editing"
  6113. */
  6114. _onDeleteClick: function(e){
  6115. e.preventDefault();
  6116. var self = e.data.self, row = $(this).closest('tr').data('__FooTableRow__');
  6117. if (row instanceof F.Row){
  6118. /**
  6119. * The delete.ft.editing event is raised before its callback is executed.
  6120. * Calling preventDefault on this event will prevent the callback from being executed.
  6121. * @event FooTable.Editing#"delete.ft.editing"
  6122. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6123. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  6124. * @param {FooTable.Row} row - The row to be deleted.
  6125. */
  6126. self.ft.raise('delete.ft.editing', [row]).then(function(){
  6127. self.callbacks.deleteRow.call(self.ft, row);
  6128. });
  6129. }
  6130. },
  6131. /**
  6132. * Handles the view button click event.
  6133. * @instance
  6134. * @private
  6135. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6136. * @fires FooTable.Editing#"view.ft.editing"
  6137. */
  6138. _onViewClick: function(e){
  6139. e.preventDefault();
  6140. var self = e.data.self, row = $(this).closest('tr').data('__FooTableRow__');
  6141. if (row instanceof F.Row){
  6142. /**
  6143. * The view.ft.editing event is raised before its callback is executed.
  6144. * Calling preventDefault on this event will prevent the callback from being executed.
  6145. * @event FooTable.Editing#"view.ft.editing"
  6146. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6147. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  6148. * @param {FooTable.Row} row - The row to be viewed.
  6149. */
  6150. self.ft.raise('view.ft.editing', [row]).then(function(){
  6151. self.callbacks.viewRow.call(self.ft, row);
  6152. });
  6153. }
  6154. },
  6155. /**
  6156. * Handles the add button click event.
  6157. * @instance
  6158. * @private
  6159. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6160. * @fires FooTable.Editing#"add.ft.editing"
  6161. */
  6162. _onAddClick: function(e){
  6163. e.preventDefault();
  6164. var self = e.data.self;
  6165. /**
  6166. * The add.ft.editing event is raised before its callback is executed.
  6167. * Calling preventDefault on this event will prevent the callback from being executed.
  6168. * @event FooTable.Editing#"add.ft.editing"
  6169. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6170. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  6171. */
  6172. self.ft.raise('add.ft.editing').then(function(){
  6173. self.callbacks.addRow.call(self.ft);
  6174. });
  6175. },
  6176. /**
  6177. * Handles the show button click event.
  6178. * @instance
  6179. * @private
  6180. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6181. * @fires FooTable.Editing#"show.ft.editing"
  6182. */
  6183. _onShowClick: function(e){
  6184. e.preventDefault();
  6185. var self = e.data.self;
  6186. /**
  6187. * The show.ft.editing event is raised before its callback is executed.
  6188. * Calling preventDefault on this event will prevent the callback from being executed.
  6189. * @event FooTable.Editing#"show.ft.editing"
  6190. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6191. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  6192. */
  6193. self.ft.raise('show.ft.editing').then(function(){
  6194. self.ft.$el.addClass('footable-editing-show');
  6195. self.column.visible = true;
  6196. self.ft.draw();
  6197. });
  6198. },
  6199. /**
  6200. * Handles the hide button click event.
  6201. * @instance
  6202. * @private
  6203. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6204. * @fires FooTable.Editing#"show.ft.editing"
  6205. */
  6206. _onHideClick: function(e){
  6207. e.preventDefault();
  6208. var self = e.data.self;
  6209. /**
  6210. * The hide.ft.editing event is raised before its callback is executed.
  6211. * Calling preventDefault on this event will prevent the callback from being executed.
  6212. * @event FooTable.Editing#"hide.ft.editing"
  6213. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6214. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  6215. */
  6216. self.ft.raise('hide.ft.editing').then(function(){
  6217. self.ft.$el.removeClass('footable-editing-show');
  6218. self.column.visible = false;
  6219. self.ft.draw();
  6220. });
  6221. }
  6222. });
  6223. F.components.register('editing', F.Editing, 850);
  6224. })(jQuery, FooTable);
  6225. (function($, F){
  6226. F.EditingColumn = F.Column.extend(/** @lends FooTable.EditingColumn */{
  6227. /**
  6228. * The Editing column class is used to create the column containing the editing buttons.
  6229. * @constructs
  6230. * @extends FooTable.Column
  6231. * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
  6232. * @param {FooTable.Editing} editing - The parent {@link FooTable.Editing} component this column is used with.
  6233. * @param {object} definition - An object containing all the properties to set for the column.
  6234. * @returns {FooTable.EditingColumn}
  6235. */
  6236. construct: function(instance, editing, definition){
  6237. this._super(instance, definition, 'editing');
  6238. this.editing = editing;
  6239. this.internal = true;
  6240. },
  6241. /**
  6242. * After the column has been defined this ensures that the $el property is a jQuery object by either creating or updating the current value.
  6243. * @instance
  6244. * @protected
  6245. * @this FooTable.Column
  6246. */
  6247. $create: function(){
  6248. (this.$el = !this.virtual && F.is.jq(this.$el) ? this.$el : $('<th/>', {'class': 'footable-editing'})).html(this.title);
  6249. },
  6250. /**
  6251. * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and
  6252. * will be provided to the {@link FooTable.EditingColumn#format} function
  6253. * to generate the cell contents.
  6254. * @instance
  6255. * @protected
  6256. * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
  6257. * @returns {(jQuery)}
  6258. */
  6259. parser: function(valueOrElement){
  6260. if (F.is.string(valueOrElement)) valueOrElement = $($.trim(valueOrElement));
  6261. if (F.is.element(valueOrElement)) valueOrElement = $(valueOrElement);
  6262. if (F.is.jq(valueOrElement)){
  6263. var tagName = valueOrElement.prop('tagName').toLowerCase();
  6264. if (tagName == 'td' || tagName == 'th') return valueOrElement.data('value') || valueOrElement.contents();
  6265. return valueOrElement;
  6266. }
  6267. return null;
  6268. },
  6269. /**
  6270. * Creates a cell to be used in the supplied row for this column.
  6271. * @param {FooTable.Row} row - The row to create the cell for.
  6272. * @returns {FooTable.Cell}
  6273. */
  6274. createCell: function(row){
  6275. var $buttons = this.editing.$rowButtons(), $cell = $('<td/>').append($buttons);
  6276. if (F.is.jq(row.$el)){
  6277. if (this.index === 0){
  6278. $cell.prependTo(row.$el);
  6279. } else {
  6280. $cell.insertAfter(row.$el.children().eq(this.index-1));
  6281. }
  6282. }
  6283. return new F.Cell(this.ft, row, this, $cell || $cell.html());
  6284. }
  6285. });
  6286. F.columns.register('editing', F.EditingColumn);
  6287. })(jQuery, FooTable);
  6288. (function($, F) {
  6289. /**
  6290. * An object containing the editing options for the plugin. Added by the {@link FooTable.Editing} component.
  6291. * @type {object}
  6292. * @prop {boolean} enabled=false - Whether or not to allow editing on the table.
  6293. * @prop {boolean} pageToNew=true - Whether or not to automatically page to a new row when it is added to the table.
  6294. * @prop {string} position="right" - The position of the editing column in the table as well as the alignment of the buttons.
  6295. * @prop {boolean} alwaysShow=false - Whether or not the editing column and add row button are always visible.
  6296. * @prop {function} addRow - The callback function to execute when the add row button is clicked.
  6297. * @prop {function} editRow - The callback function to execute when the edit row button is clicked.
  6298. * @prop {function} deleteRow - The callback function to execute when the delete row button is clicked.
  6299. * @prop {function} viewRow - The callback function to execute when the view row button is clicked.
  6300. * @prop {string} showText - The text that appears in the show button. This can contain HTML.
  6301. * @prop {string} hideText - The text that appears in the hide button. This can contain HTML.
  6302. * @prop {string} addText - The text that appears in the add button. This can contain HTML.
  6303. * @prop {string} editText - The text that appears in the edit button. This can contain HTML.
  6304. * @prop {string} deleteText - The text that appears in the delete button. This can contain HTML.
  6305. * @prop {string} viewText - The text that appears in the view button. This can contain HTML.
  6306. * @prop {boolean} allowAdd - Whether or not to show the Add Row button.
  6307. * @prop {boolean} allowEdit - Whether or not to show the Edit Row button.
  6308. * @prop {boolean} allowDelete - Whether or not to show the Delete Row button.
  6309. * @prop {boolean} allowView - Whether or not to show the View Row button.
  6310. * @prop {object} column - The options for the editing column. @see {@link FooTable.EditingColumn} for more info.
  6311. * @prop {string} column.classes="footable-editing" - A space separated string of class names to apply to all cells in the column.
  6312. * @prop {string} column.name="editing" - The name of the column.
  6313. * @prop {string} column.title="" - The title displayed in the header row of the table for the column.
  6314. * @prop {boolean} column.filterable=false - Whether or not the column should be filterable when using the filtering component.
  6315. * @prop {boolean} column.sortable=false - Whether or not the column should be sortable when using the sorting component.
  6316. */
  6317. F.Defaults.prototype.editing = {
  6318. enabled: false,
  6319. pageToNew: true,
  6320. position: 'right',
  6321. alwaysShow: false,
  6322. addRow: function(){},
  6323. editRow: function(row){},
  6324. deleteRow: function(row){},
  6325. viewRow: function(row){},
  6326. showText: '<span class="fooicon fooicon-pencil" aria-hidden="true"></span> Edit rows',
  6327. hideText: 'Cancel',
  6328. addText: 'New row',
  6329. editText: '<span class="fooicon fooicon-pencil" aria-hidden="true"></span>',
  6330. deleteText: '<span class="fooicon fooicon-trash" aria-hidden="true"></span>',
  6331. viewText: '<span class="fooicon fooicon-stats" aria-hidden="true"></span>',
  6332. allowAdd: true,
  6333. allowEdit: true,
  6334. allowDelete: true,
  6335. allowView: false,
  6336. column: {
  6337. classes: 'footable-editing',
  6338. name: 'editing',
  6339. title: '',
  6340. filterable: false,
  6341. sortable: false
  6342. }
  6343. };
  6344. })(jQuery, FooTable);
  6345. (function($, F){
  6346. if (F.is.defined(F.Paging)){
  6347. /**
  6348. * Holds a shallow clone of the un-paged {@link FooTable.Rows#array} value before paging occurs and superfluous rows are removed. Added by the {@link FooTable.Editing} component.
  6349. * @instance
  6350. * @public
  6351. * @type {Array<FooTable.Row>}
  6352. */
  6353. F.Paging.prototype.unpaged = [];
  6354. // override the default predraw method with one that sets the unpaged property.
  6355. F.Paging.extend('predraw', function(){
  6356. this.unpaged = this.ft.rows.array.slice(0); // create a shallow clone for later use
  6357. this._super(); // call the original method
  6358. });
  6359. }
  6360. })(jQuery, FooTable);
  6361. (function($, F){
  6362. /**
  6363. * Adds the row to the table.
  6364. * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
  6365. * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
  6366. * @returns {jQuery.Deferred}
  6367. */
  6368. F.Row.prototype.add = function(redraw){
  6369. redraw = F.is.boolean(redraw) ? redraw : true;
  6370. var self = this;
  6371. return $.Deferred(function(d){
  6372. var index = self.ft.rows.all.push(self) - 1;
  6373. if (redraw){
  6374. return self.ft.draw().then(function(){
  6375. d.resolve(index);
  6376. });
  6377. } else {
  6378. d.resolve(index);
  6379. }
  6380. });
  6381. };
  6382. /**
  6383. * Removes the row from the table.
  6384. * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
  6385. * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
  6386. * @returns {jQuery.Deferred}
  6387. */
  6388. F.Row.prototype.delete = function(redraw){
  6389. redraw = F.is.boolean(redraw) ? redraw : true;
  6390. var self = this;
  6391. return $.Deferred(function(d){
  6392. var index = self.ft.rows.all.indexOf(self);
  6393. if (F.is.number(index) && index >= 0 && index < self.ft.rows.all.length){
  6394. self.ft.rows.all.splice(index, 1);
  6395. if (redraw){
  6396. return self.ft.draw().then(function(){
  6397. d.resolve(self);
  6398. });
  6399. }
  6400. }
  6401. d.resolve(self);
  6402. });
  6403. };
  6404. if (F.is.defined(F.Paging)){
  6405. // override the default add method with one that supports paging
  6406. F.Row.extend('add', function(redraw){
  6407. redraw = F.is.boolean(redraw) ? redraw : true;
  6408. var self = this,
  6409. added = this._super(redraw),
  6410. editing = self.ft.use(F.Editing),
  6411. paging;
  6412. if (editing && editing.pageToNew && (paging = self.ft.use(F.Paging)) && redraw){
  6413. return added.then(function(){
  6414. var index = paging.unpaged.indexOf(self); // find this row in the unpaged array (this array will be sorted and filtered)
  6415. var page = Math.ceil((index + 1) / paging.size); // calculate the page the new row is on
  6416. if (paging.current !== page){ // goto the page if we need to
  6417. return paging.goto(page);
  6418. }
  6419. });
  6420. }
  6421. return added;
  6422. });
  6423. }
  6424. if (F.is.defined(F.Sorting)){
  6425. // override the default val method with one that supports sorting and paging
  6426. F.Row.extend('val', function(data, redraw){
  6427. redraw = F.is.boolean(redraw) ? redraw : true;
  6428. var result = this._super(data);
  6429. if (!F.is.hash(data)){
  6430. return result;
  6431. }
  6432. var self = this;
  6433. if (redraw){
  6434. self.ft.draw().then(function(){
  6435. var editing = self.ft.use(F.Editing), paging;
  6436. if (F.is.defined(F.Paging) && editing && editing.pageToNew && (paging = self.ft.use(F.Paging))){
  6437. var index = paging.unpaged.indexOf(self); // find this row in the unpaged array (this array will be sorted and filtered)
  6438. var page = Math.ceil((index + 1) / paging.size); // calculate the page the new row is on
  6439. if (paging.current !== page){ // goto the page if we need to
  6440. return paging.goto(page);
  6441. }
  6442. }
  6443. });
  6444. }
  6445. return result;
  6446. });
  6447. }
  6448. })(jQuery, FooTable);
  6449. (function(F){
  6450. /**
  6451. * Adds a row to the underlying {@link FooTable.Rows#all} array.
  6452. * @param {(object|FooTable.Row)} dataOrRow - A hash containing the row values or an actual {@link FooTable.Row} object.
  6453. * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
  6454. * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
  6455. */
  6456. F.Rows.prototype.add = function(dataOrRow, redraw){
  6457. var row = dataOrRow;
  6458. if (F.is.hash(dataOrRow)){
  6459. row = new FooTable.Row(this.ft, this.ft.columns.array, dataOrRow);
  6460. }
  6461. if (row instanceof FooTable.Row){
  6462. row.add(redraw);
  6463. }
  6464. };
  6465. /**
  6466. * Updates a row in the underlying {@link FooTable.Rows#all} array.
  6467. * @param {(number|FooTable.Row)} indexOrRow - The index to update or the actual {@link FooTable.Row} object.
  6468. * @param {object} data - A hash containing the new row values.
  6469. * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
  6470. * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
  6471. */
  6472. F.Rows.prototype.update = function(indexOrRow, data, redraw){
  6473. var len = this.ft.rows.all.length,
  6474. row = indexOrRow;
  6475. if (F.is.number(indexOrRow) && indexOrRow >= 0 && indexOrRow < len){
  6476. row = this.ft.rows.all[indexOrRow];
  6477. }
  6478. if (row instanceof FooTable.Row && F.is.hash(data)){
  6479. row.val(data, redraw);
  6480. }
  6481. };
  6482. /**
  6483. * Deletes a row from the underlying {@link FooTable.Rows#all} array.
  6484. * @param {(number|FooTable.Row)} indexOrRow - The index to delete or the actual {@link FooTable.Row} object.
  6485. * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
  6486. * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
  6487. */
  6488. F.Rows.prototype.delete = function(indexOrRow, redraw){
  6489. var len = this.ft.rows.all.length,
  6490. row = indexOrRow;
  6491. if (F.is.number(indexOrRow) && indexOrRow >= 0 && indexOrRow < len){
  6492. row = this.ft.rows.all[indexOrRow];
  6493. }
  6494. if (row instanceof FooTable.Row){
  6495. row.delete(redraw);
  6496. }
  6497. };
  6498. })(FooTable);
  6499. (function($, F){
  6500. // global int to use if the table has no ID
  6501. var _uid = 0,
  6502. // a hash value for the current url
  6503. _url_hash = (function(str){
  6504. var i, l, hval = 0x811c9dc5;
  6505. for (i = 0, l = str.length; i < l; i++) {
  6506. hval ^= str.charCodeAt(i);
  6507. hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
  6508. }
  6509. return hval >>> 0;
  6510. })(location.origin + location.pathname);
  6511. F.State = F.Component.extend(/** @lends FooTable.State */{
  6512. /**
  6513. * The state component adds the ability for the table to remember its basic state for filtering, paging and sorting.
  6514. * @constructs
  6515. * @extends FooTable.Component
  6516. * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
  6517. * @returns {FooTable.State}
  6518. */
  6519. construct: function(table){
  6520. // call the constructor of the base class
  6521. this._super(table, table.o.state.enabled);
  6522. // Change this value if an update to this component requires any stored data to be reset
  6523. this._key = '1';
  6524. /**
  6525. * The key to use to store the state for this table.
  6526. * @type {(null|string)}
  6527. */
  6528. this.key = this._key + (F.is.string(table.o.state.key) ? table.o.state.key : this._uid());
  6529. /**
  6530. * Whether or not to allow the filtering component to store it's state.
  6531. * @type {boolean}
  6532. */
  6533. this.filtering = F.is.boolean(table.o.state.filtering) ? table.o.state.filtering : true;
  6534. /**
  6535. * Whether or not to allow the paging component to store it's state.
  6536. * @type {boolean}
  6537. */
  6538. this.paging = F.is.boolean(table.o.state.paging) ? table.o.state.paging : true;
  6539. /**
  6540. * Whether or not to allow the sorting component to store it's state.
  6541. * @type {boolean}
  6542. */
  6543. this.sorting = F.is.boolean(table.o.state.sorting) ? table.o.state.sorting : true;
  6544. },
  6545. /* PROTECTED */
  6546. /**
  6547. * Checks the supplied data and options for the state component.
  6548. * @instance
  6549. * @protected
  6550. * @param {object} data - The jQuery data object from the parent table.
  6551. * @fires FooTable.State#"preinit.ft.state"
  6552. * @this FooTable.State
  6553. */
  6554. preinit: function(data){
  6555. var self = this;
  6556. /**
  6557. * The preinit.ft.state event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
  6558. * Calling preventDefault on this event will disable the component.
  6559. * @event FooTable.State#"preinit.ft.state"
  6560. * @param {jQuery.Event} e - The jQuery.Event object for the event.
  6561. * @param {FooTable.Table} ft - The instance of the plugin raising the event.
  6562. * @param {object} data - The jQuery data object of the table raising the event.
  6563. */
  6564. this.ft.raise('preinit.ft.state', [data]).then(function(){
  6565. self.enabled = F.is.boolean(data.state)
  6566. ? data.state
  6567. : self.enabled;
  6568. if (!self.enabled) return;
  6569. self.key = self._key + (F.is.string(data.stateKey) ? data.stateKey : self.key);
  6570. self.filtering = F.is.boolean(data.stateFiltering) ? data.stateFiltering : self.filtering;
  6571. self.paging = F.is.boolean(data.statePaging) ? data.statePaging : self.paging;
  6572. self.sorting = F.is.boolean(data.stateSorting) ? data.stateSorting : self.sorting;
  6573. }, function(){
  6574. self.enabled = false;
  6575. });
  6576. },
  6577. /**
  6578. * Gets the state value for the specified key for this table.
  6579. * @instance
  6580. * @param {string} key - The key to get the value for.
  6581. * @returns {(*|null)}
  6582. */
  6583. get: function(key){
  6584. return JSON.parse(localStorage.getItem(this.key + ':' + key));
  6585. },
  6586. /**
  6587. * Sets the state value for the specified key for this table.
  6588. * @instance
  6589. * @param {string} key - The key to set the value for.
  6590. * @param {*} data - The value to store for the key. This value must be JSON.stringify friendly.
  6591. */
  6592. set: function(key, data){
  6593. localStorage.setItem(this.key + ':' + key, JSON.stringify(data));
  6594. },
  6595. /**
  6596. * Clears the state value for the specified key for this table.
  6597. * @instance
  6598. * @param {string} key - The key to clear the value for.
  6599. */
  6600. remove: function(key){
  6601. localStorage.removeItem(this.key + ':' + key);
  6602. },
  6603. /**
  6604. * Executes the {@link FooTable.Component#readState} function on all components.
  6605. * @instance
  6606. */
  6607. read: function(){
  6608. this.ft.execute(false, true, 'readState');
  6609. },
  6610. /**
  6611. * Executes the {@link FooTable.Component#writeState} function on all components.
  6612. * @instance
  6613. */
  6614. write: function(){
  6615. this.ft.execute(false, true, 'writeState');
  6616. },
  6617. /**
  6618. * Executes the {@link FooTable.Component#clearState} function on all components.
  6619. * @instance
  6620. */
  6621. clear: function(){
  6622. this.ft.execute(false, true, 'clearState');
  6623. },
  6624. /**
  6625. * Generates a unique identifier for the current {@link FooTable.Table} if one is not supplied through the options.
  6626. * This value is a combination of the url hash and either the element ID or an incremented global int value.
  6627. * @instance
  6628. * @returns {*}
  6629. * @private
  6630. */
  6631. _uid: function(){
  6632. var id = this.ft.$el.attr('id');
  6633. return _url_hash + '_' + (F.is.string(id) ? id : ++_uid);
  6634. }
  6635. });
  6636. F.components.register('state', F.State, 700);
  6637. })(jQuery, FooTable);
  6638. (function(F){
  6639. /**
  6640. * This method is called from the {@link FooTable.State#read} method and allows a component to retrieve its' stored state.
  6641. * @instance
  6642. * @protected
  6643. * @function
  6644. */
  6645. F.Component.prototype.readState = function(){};
  6646. /**
  6647. * This method is called from the {@link FooTable.State#write} method and allows a component to write its' current state to the store.
  6648. * @instance
  6649. * @protected
  6650. * @function
  6651. */
  6652. F.Component.prototype.writeState = function(){};
  6653. /**
  6654. * This method is called from the {@link FooTable.State#clear} method and allows a component to clear any stored state.
  6655. * @instance
  6656. * @protected
  6657. * @function
  6658. */
  6659. F.Component.prototype.clearState = function(){};
  6660. })(FooTable);
  6661. (function(F){
  6662. /**
  6663. * An object containing the state options for the plugin. Added by the {@link FooTable.State} component.
  6664. * @type {object}
  6665. * @prop {boolean} enabled=false - Whether or not to allow state to be stored for the table. This overrides the individual component enable options.
  6666. * @prop {boolean} filtering=true - Whether or not to allow the filtering state to be stored.
  6667. * @prop {boolean} paging=true - Whether or not to allow the filtering state to be stored.
  6668. * @prop {boolean} sorting=true - Whether or not to allow the filtering state to be stored.
  6669. * @prop {string} key=null - The unique key to use to store the table's data.
  6670. */
  6671. F.Defaults.prototype.state = {
  6672. enabled: false,
  6673. filtering: true,
  6674. paging: true,
  6675. sorting: true,
  6676. key: null
  6677. };
  6678. })(FooTable);
  6679. (function(F){
  6680. if (!F.Filtering) return;
  6681. /**
  6682. * Allows the filtering component to retrieve its' stored state.
  6683. */
  6684. F.Filtering.prototype.readState = function(){
  6685. if (this.ft.state.filtering){
  6686. var state = this.ft.state.get('filtering');
  6687. if (F.is.hash(state) && !F.is.emptyArray(state.filters)){
  6688. this.filters = this.ensure(state.filters);
  6689. }
  6690. }
  6691. };
  6692. /**
  6693. * Allows the filtering component to write its' current state to the store.
  6694. */
  6695. F.Filtering.prototype.writeState = function(){
  6696. if (this.ft.state.filtering) {
  6697. var filters = F.arr.map(this.filters, function (f) {
  6698. return {
  6699. name: f.name,
  6700. query: f.query instanceof F.Query ? f.query.val() : f.query,
  6701. columns: F.arr.map(f.columns, function (c) {
  6702. return c.name;
  6703. }),
  6704. hidden: f.hidden,
  6705. space: f.space,
  6706. connectors: f.connectors,
  6707. ignoreCase: f.ignoreCase
  6708. };
  6709. });
  6710. this.ft.state.set('filtering', {filters: filters});
  6711. }
  6712. };
  6713. /**
  6714. * Allows the filtering component to clear any stored state.
  6715. */
  6716. F.Filtering.prototype.clearState = function(){
  6717. if (this.ft.state.filtering) {
  6718. this.ft.state.remove('filtering');
  6719. }
  6720. };
  6721. })(FooTable);
  6722. (function(F){
  6723. if (!F.Paging) return;
  6724. /**
  6725. * Allows the paging component to retrieve its' stored state.
  6726. */
  6727. F.Paging.prototype.readState = function(){
  6728. if (this.ft.state.paging) {
  6729. var state = this.ft.state.get('paging');
  6730. if (F.is.hash(state)) {
  6731. this.current = state.current;
  6732. this.size = state.size;
  6733. }
  6734. }
  6735. };
  6736. /**
  6737. * Allows the paging component to write its' current state to the store.
  6738. */
  6739. F.Paging.prototype.writeState = function(){
  6740. if (this.ft.state.paging) {
  6741. this.ft.state.set('paging', {
  6742. current: this.current,
  6743. size: this.size
  6744. });
  6745. }
  6746. };
  6747. /**
  6748. * Allows the paging component to clear any stored state.
  6749. */
  6750. F.Paging.prototype.clearState = function(){
  6751. if (this.ft.state.paging) {
  6752. this.ft.state.remove('paging');
  6753. }
  6754. };
  6755. })(FooTable);
  6756. (function(F){
  6757. if (!F.Sorting) return;
  6758. /**
  6759. * Allows the sorting component to retrieve its' stored state.
  6760. */
  6761. F.Sorting.prototype.readState = function(){
  6762. if (this.ft.state.sorting) {
  6763. var state = this.ft.state.get('sorting');
  6764. if (F.is.hash(state)) {
  6765. var column = this.ft.columns.get(state.column);
  6766. if (column instanceof F.Column) {
  6767. this.column = column;
  6768. this.column.direction = state.direction;
  6769. }
  6770. }
  6771. }
  6772. };
  6773. /**
  6774. * Allows the sorting component to write its' current state to the store.
  6775. */
  6776. F.Sorting.prototype.writeState = function(){
  6777. if (this.ft.state.sorting && this.column instanceof F.Column){
  6778. this.ft.state.set('sorting', {
  6779. column: this.column.name,
  6780. direction: this.column.direction
  6781. });
  6782. }
  6783. };
  6784. /**
  6785. * Allows the sorting component to clear any stored state.
  6786. */
  6787. F.Sorting.prototype.clearState = function(){
  6788. if (this.ft.state.sorting) {
  6789. this.ft.state.remove('sorting');
  6790. }
  6791. };
  6792. })(FooTable);
  6793. (function(F){
  6794. // hook into the _construct method so we can add the state property to the table.
  6795. F.Table.extend('_construct', function(ready){
  6796. this.state = this.use(FooTable.State);
  6797. return this._super(ready);
  6798. });
  6799. // hook into the _preinit method so we can trigger a plugin wide read state operation.
  6800. F.Table.extend('_preinit', function(){
  6801. var self = this;
  6802. return self._super().then(function(){
  6803. if (self.state.enabled){
  6804. self.state.read();
  6805. }
  6806. });
  6807. });
  6808. // hook into the draw method so we can trigger a plugin wide write state operation.
  6809. F.Table.extend('draw', function(){
  6810. var self = this;
  6811. return self._super().then(function(){
  6812. if (self.state.enabled){
  6813. self.state.write();
  6814. }
  6815. });
  6816. });
  6817. })(FooTable);
  6818. (function($, F){
  6819. F.Export = F.Component.extend(/** @lends FooTable.Export */{
  6820. /**
  6821. * @summary This component provides some basic export functionality.
  6822. * @memberof FooTable
  6823. * @constructs Export
  6824. * @param {FooTable.Table} table - The current instance of the plugin.
  6825. */
  6826. construct: function(table){
  6827. // call the constructor of the base class
  6828. this._super(table, true);
  6829. /**
  6830. * @summary A snapshot of the working set of rows prior to being trimmed by the paging component.
  6831. * @memberof FooTable.Export#
  6832. * @name snapshot
  6833. * @type {FooTable.Row[]}
  6834. */
  6835. this.snapshot = [];
  6836. },
  6837. /**
  6838. * @summary Hooks into the predraw pipeline after sorting and filtering have taken place but prior to paging.
  6839. * @memberof FooTable.Export#
  6840. * @function predraw
  6841. * @description This method allows us to take a snapshot of the working set of rows before they are trimmed by the paging component and is called by the plugin instance.
  6842. */
  6843. predraw: function(){
  6844. this.snapshot = this.ft.rows.array.slice(0);
  6845. },
  6846. /**
  6847. * @summary Return the columns as simple JavaScript objects in an array.
  6848. * @memberof FooTable.Export#
  6849. * @function columns
  6850. * @returns {Object[]}
  6851. */
  6852. columns: function(){
  6853. var result = [];
  6854. F.arr.each(this.ft.columns.array, function(column){
  6855. if (!column.internal){
  6856. result.push({
  6857. type: column.type,
  6858. name: column.name,
  6859. title: column.title,
  6860. visible: column.visible,
  6861. hidden: column.hidden,
  6862. classes: column.classes,
  6863. style: column.style
  6864. });
  6865. }
  6866. });
  6867. return result;
  6868. },
  6869. /**
  6870. * @summary Return the rows as simple JavaScript objects in an array.
  6871. * @memberof FooTable.Export#
  6872. * @function rows
  6873. * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
  6874. * @returns {Object[]}
  6875. */
  6876. rows: function(filtered){
  6877. filtered = F.is.boolean(filtered) ? filtered : false;
  6878. var rows = filtered ? this.ft.rows.all : this.snapshot, result = [];
  6879. F.arr.each(rows, function(row){
  6880. result.push(row.val());
  6881. });
  6882. return result;
  6883. },
  6884. /**
  6885. * @summary Return the columns and rows as a properly formatted JSON object.
  6886. * @memberof FooTable.Export#
  6887. * @function json
  6888. * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
  6889. * @returns {Object}
  6890. */
  6891. json: function(filtered){
  6892. return JSON.parse(JSON.stringify({columns: this.columns(),rows: this.rows(filtered)}));
  6893. },
  6894. /**
  6895. * @summary Return the columns and rows as a properly formatted CSV value.
  6896. * @memberof FooTable.Export#
  6897. * @function csv
  6898. * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
  6899. * @returns {string}
  6900. */
  6901. csv: function(filtered){
  6902. var csv = "", columns = this.columns(), value, escaped;
  6903. F.arr.each(columns, function(column, i){
  6904. escaped = '"' + column.title.replace(/"/g, '""') + '"';
  6905. csv += (i === 0 ? escaped : "," + escaped);
  6906. });
  6907. csv += "\n";
  6908. var rows = filtered ? this.ft.rows.all : this.snapshot;
  6909. F.arr.each(rows, function(row){
  6910. F.arr.each(row.cells, function(cell, i){
  6911. if (!cell.column.internal){
  6912. value = cell.column.stringify.call(cell.column, cell.value, cell.ft.o, cell.row.value);
  6913. escaped = '"' + value.replace(/"/g, '""') + '"';
  6914. csv += (i === 0 ? escaped : "," + escaped);
  6915. }
  6916. });
  6917. csv += "\n";
  6918. });
  6919. return csv;
  6920. }
  6921. });
  6922. // register the component using a priority of 490 which falls just after filtering (500) and before paging (400).
  6923. F.components.register("export", F.Export, 490);
  6924. })(jQuery, FooTable);
  6925. (function(F){
  6926. // this is used to define the filtering specific properties on column creation
  6927. F.Column.prototype.__export_define__ = function(definition){
  6928. this.stringify = F.checkFnValue(this, definition.stringify, this.stringify);
  6929. };
  6930. // overrides the public define method and replaces it with our own
  6931. F.Column.extend('define', function(definition){
  6932. this._super(definition); // call the base so we don't have to redefine any previously set properties
  6933. this.__export_define__(definition); // then call our own
  6934. });
  6935. /**
  6936. * @summary Return the supplied value as a string.
  6937. * @memberof FooTable.Column#
  6938. * @function stringify
  6939. * @returns {string}
  6940. */
  6941. F.Column.prototype.stringify = function(value, options, rowData){
  6942. return value + "";
  6943. };
  6944. if (F.is.defined(F.DateColumn)){
  6945. // override the base method for DateColumns
  6946. F.DateColumn.prototype.stringify = function(value, options, rowData){
  6947. return F.is.object(value) && F.is.boolean(value._isAMomentObject) && value.isValid() ? value.format(this.formatString) : '';
  6948. };
  6949. }
  6950. // override the base method for ObjectColumns
  6951. F.ObjectColumn.prototype.stringify = function(value, options, rowData){
  6952. return F.is.object(value) ? JSON.stringify(value) : "";
  6953. };
  6954. // override the base method for ArrayColumns
  6955. F.ArrayColumn.prototype.stringify = function(value, options, rowData){
  6956. return F.is.array(value) ? JSON.stringify(value) : "";
  6957. };
  6958. })(FooTable);
  6959. (function(F){
  6960. /**
  6961. * @summary Return the columns and rows as a properly formatted JSON object.
  6962. * @memberof FooTable.Table#
  6963. * @function toJSON
  6964. * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
  6965. * @returns {Object}
  6966. */
  6967. F.Table.prototype.toJSON = function(filtered){
  6968. return this.use(F.Export).json(filtered);
  6969. };
  6970. /**
  6971. * @summary Return the columns and rows as a properly formatted CSV value.
  6972. * @memberof FooTable.Table#
  6973. * @function toCSV
  6974. * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
  6975. * @returns {string}
  6976. */
  6977. F.Table.prototype.toCSV = function(filtered){
  6978. return this.use(F.Export).csv(filtered);
  6979. };
  6980. })(FooTable);