ui-grid的副本.js 1002 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813
  1. /*!
  2. * ui-grid - v3.0.6 - 2015-09-08
  3. * Copyright (c) 2015 ; License: MIT
  4. */
  5. (function () {
  6. 'use strict';
  7. angular.module('ui.grid.i18n', []);
  8. angular.module('ui.grid', ['ui.grid.i18n']);
  9. })();
  10. (function () {
  11. 'use strict';
  12. angular.module('ui.grid').constant('uiGridConstants', {
  13. LOG_DEBUG_MESSAGES: true,
  14. LOG_WARN_MESSAGES: true,
  15. LOG_ERROR_MESSAGES: true,
  16. CUSTOM_FILTERS: /CUSTOM_FILTERS/g,
  17. COL_FIELD: /COL_FIELD/g,
  18. MODEL_COL_FIELD: /MODEL_COL_FIELD/g,
  19. TOOLTIP: /title=\"TOOLTIP\"/g,
  20. DISPLAY_CELL_TEMPLATE: /DISPLAY_CELL_TEMPLATE/g,
  21. TEMPLATE_REGEXP: /<.+>/,
  22. FUNC_REGEXP: /(\([^)]*\))?$/,
  23. DOT_REGEXP: /\./g,
  24. APOS_REGEXP: /'/g,
  25. BRACKET_REGEXP: /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/,
  26. COL_CLASS_PREFIX: 'ui-grid-col',
  27. events: {
  28. GRID_SCROLL: 'uiGridScroll',
  29. COLUMN_MENU_SHOWN: 'uiGridColMenuShown',
  30. ITEM_DRAGGING: 'uiGridItemDragStart', // For any item being dragged
  31. COLUMN_HEADER_CLICK: 'uiGridColumnHeaderClick'
  32. },
  33. // copied from http://www.lsauer.com/2011/08/javascript-keymap-keycodes-in-json.html
  34. keymap: {
  35. TAB: 9,
  36. STRG: 17,
  37. CAPSLOCK: 20,
  38. CTRL: 17,
  39. CTRLRIGHT: 18,
  40. CTRLR: 18,
  41. SHIFT: 16,
  42. RETURN: 13,
  43. ENTER: 13,
  44. BACKSPACE: 8,
  45. BCKSP: 8,
  46. ALT: 18,
  47. ALTR: 17,
  48. ALTRIGHT: 17,
  49. SPACE: 32,
  50. WIN: 91,
  51. MAC: 91,
  52. FN: null,
  53. PG_UP: 33,
  54. PG_DOWN: 34,
  55. UP: 38,
  56. DOWN: 40,
  57. LEFT: 37,
  58. RIGHT: 39,
  59. ESC: 27,
  60. DEL: 46,
  61. F1: 112,
  62. F2: 113,
  63. F3: 114,
  64. F4: 115,
  65. F5: 116,
  66. F6: 117,
  67. F7: 118,
  68. F8: 119,
  69. F9: 120,
  70. F10: 121,
  71. F11: 122,
  72. F12: 123
  73. },
  74. ASC: 'asc',
  75. DESC: 'desc',
  76. filter: {
  77. STARTS_WITH: 2,
  78. ENDS_WITH: 4,
  79. EXACT: 8,
  80. CONTAINS: 16,
  81. GREATER_THAN: 32,
  82. GREATER_THAN_OR_EQUAL: 64,
  83. LESS_THAN: 128,
  84. LESS_THAN_OR_EQUAL: 256,
  85. NOT_EQUAL: 512,
  86. SELECT: 'select',
  87. INPUT: 'input'
  88. },
  89. aggregationTypes: {
  90. sum: 2,
  91. count: 4,
  92. avg: 8,
  93. min: 16,
  94. max: 32
  95. },
  96. // TODO(c0bra): Create full list of these somehow. NOTE: do any allow a space before or after them?
  97. CURRENCY_SYMBOLS: ['ƒ', '$', '£', '$', '¤', '¥', '៛', '₩', '₱', '฿', '₫'],
  98. scrollDirection: {
  99. UP: 'up',
  100. DOWN: 'down',
  101. LEFT: 'left',
  102. RIGHT: 'right',
  103. NONE: 'none'
  104. },
  105. dataChange: {
  106. ALL: 'all',
  107. EDIT: 'edit',
  108. ROW: 'row',
  109. COLUMN: 'column',
  110. OPTIONS: 'options'
  111. },
  112. scrollbars: {
  113. NEVER: 0,
  114. ALWAYS: 1
  115. //WHEN_NEEDED: 2
  116. }
  117. });
  118. })();
  119. angular.module('ui.grid').directive('uiGridCell', ['$compile', '$parse', 'gridUtil', 'uiGridConstants', function ($compile, $parse, gridUtil, uiGridConstants) {
  120. var uiGridCell = {
  121. priority: 0,
  122. scope: false,
  123. require: '?^uiGrid',
  124. compile: function() {
  125. return {
  126. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  127. function compileTemplate() {
  128. var compiledElementFn = $scope.col.compiledElementFn;
  129. compiledElementFn($scope, function(clonedElement, scope) {
  130. $elm.append(clonedElement);
  131. });
  132. }
  133. // If the grid controller is present, use it to get the compiled cell template function
  134. if (uiGridCtrl && $scope.col.compiledElementFn) {
  135. compileTemplate();
  136. }
  137. // No controller, compile the element manually (for unit tests)
  138. else {
  139. if ( uiGridCtrl && !$scope.col.compiledElementFn ){
  140. // gridUtil.logError('Render has been called before precompile. Please log a ui-grid issue');
  141. $scope.col.getCompiledElementFn()
  142. .then(function (compiledElementFn) {
  143. compiledElementFn($scope, function(clonedElement, scope) {
  144. $elm.append(clonedElement);
  145. });
  146. });
  147. }
  148. else {
  149. var html = $scope.col.cellTemplate
  150. .replace(uiGridConstants.MODEL_COL_FIELD, 'row.entity.' + gridUtil.preEval($scope.col.field))
  151. .replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
  152. var cellElement = $compile(html)($scope);
  153. $elm.append(cellElement);
  154. }
  155. }
  156. },
  157. post: function($scope, $elm, $attrs, uiGridCtrl) {
  158. var initColClass = $scope.col.getColClass(false);
  159. $elm.addClass(initColClass);
  160. var classAdded;
  161. var updateClass = function( grid ){
  162. var contents = $elm;
  163. if ( classAdded ){
  164. contents.removeClass( classAdded );
  165. classAdded = null;
  166. }
  167. if (angular.isFunction($scope.col.cellClass)) {
  168. classAdded = $scope.col.cellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex);
  169. }
  170. else {
  171. classAdded = $scope.col.cellClass;
  172. }
  173. contents.addClass(classAdded);
  174. };
  175. if ($scope.col.cellClass) {
  176. updateClass();
  177. }
  178. // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs
  179. var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateClass, [uiGridConstants.dataChange.COLUMN, uiGridConstants.dataChange.EDIT]);
  180. // watch the col and row to see if they change - which would indicate that we've scrolled or sorted or otherwise
  181. // changed the row/col that this cell relates to, and we need to re-evaluate cell classes and maybe other things
  182. var cellChangeFunction = function( n, o ){
  183. if ( n !== o ) {
  184. if ( classAdded || $scope.col.cellClass ){
  185. updateClass();
  186. }
  187. // See if the column's internal class has changed
  188. var newColClass = $scope.col.getColClass(false);
  189. if (newColClass !== initColClass) {
  190. $elm.removeClass(initColClass);
  191. $elm.addClass(newColClass);
  192. initColClass = newColClass;
  193. }
  194. }
  195. };
  196. // TODO(c0bra): Turn this into a deep array watch
  197. /* shouldn't be needed any more given track by col.name
  198. var colWatchDereg = $scope.$watch( 'col', cellChangeFunction );
  199. */
  200. var rowWatchDereg = $scope.$watch( 'row', cellChangeFunction );
  201. var deregisterFunction = function() {
  202. dataChangeDereg();
  203. // colWatchDereg();
  204. rowWatchDereg();
  205. };
  206. $scope.$on( '$destroy', deregisterFunction );
  207. $elm.on( '$destroy', deregisterFunction );
  208. }
  209. };
  210. }
  211. };
  212. return uiGridCell;
  213. }]);
  214. (function(){
  215. angular.module('ui.grid')
  216. .service('uiGridColumnMenuService', [ 'i18nService', 'uiGridConstants', 'gridUtil',
  217. function ( i18nService, uiGridConstants, gridUtil ) {
  218. /**
  219. * @ngdoc service
  220. * @name ui.grid.service:uiGridColumnMenuService
  221. *
  222. * @description Services for working with column menus, factored out
  223. * to make the code easier to understand
  224. */
  225. var service = {
  226. /**
  227. * @ngdoc method
  228. * @methodOf ui.grid.service:uiGridColumnMenuService
  229. * @name initialize
  230. * @description Sets defaults, puts a reference to the $scope on
  231. * the uiGridController
  232. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  233. * @param {controller} uiGridCtrl the uiGridController for the grid
  234. * we're on
  235. *
  236. */
  237. initialize: function( $scope, uiGridCtrl ){
  238. $scope.grid = uiGridCtrl.grid;
  239. // Store a reference to this link/controller in the main uiGrid controller
  240. // to allow showMenu later
  241. uiGridCtrl.columnMenuScope = $scope;
  242. // Save whether we're shown or not so the columns can check
  243. $scope.menuShown = false;
  244. },
  245. /**
  246. * @ngdoc method
  247. * @methodOf ui.grid.service:uiGridColumnMenuService
  248. * @name setColMenuItemWatch
  249. * @description Setup a watch on $scope.col.menuItems, and update
  250. * menuItems based on this. $scope.col needs to be set by the column
  251. * before calling the menu.
  252. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  253. * @param {controller} uiGridCtrl the uiGridController for the grid
  254. * we're on
  255. *
  256. */
  257. setColMenuItemWatch: function ( $scope ){
  258. var deregFunction = $scope.$watch('col.menuItems', function (n, o) {
  259. if (typeof(n) !== 'undefined' && n && angular.isArray(n)) {
  260. n.forEach(function (item) {
  261. if (typeof(item.context) === 'undefined' || !item.context) {
  262. item.context = {};
  263. }
  264. item.context.col = $scope.col;
  265. });
  266. $scope.menuItems = $scope.defaultMenuItems.concat(n);
  267. }
  268. else {
  269. $scope.menuItems = $scope.defaultMenuItems;
  270. }
  271. });
  272. $scope.$on( '$destroy', deregFunction );
  273. },
  274. /**
  275. * @ngdoc boolean
  276. * @name enableSorting
  277. * @propertyOf ui.grid.class:GridOptions.columnDef
  278. * @description (optional) True by default. When enabled, this setting adds sort
  279. * widgets to the column header, allowing sorting of the data in the individual column.
  280. */
  281. /**
  282. * @ngdoc method
  283. * @methodOf ui.grid.service:uiGridColumnMenuService
  284. * @name sortable
  285. * @description determines whether this column is sortable
  286. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  287. *
  288. */
  289. sortable: function( $scope ) {
  290. if ( $scope.grid.options.enableSorting && typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.enableSorting) {
  291. return true;
  292. }
  293. else {
  294. return false;
  295. }
  296. },
  297. /**
  298. * @ngdoc method
  299. * @methodOf ui.grid.service:uiGridColumnMenuService
  300. * @name isActiveSort
  301. * @description determines whether the requested sort direction is current active, to
  302. * allow highlighting in the menu
  303. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  304. * @param {string} direction the direction that we'd have selected for us to be active
  305. *
  306. */
  307. isActiveSort: function( $scope, direction ){
  308. return (typeof($scope.col) !== 'undefined' && typeof($scope.col.sort) !== 'undefined' &&
  309. typeof($scope.col.sort.direction) !== 'undefined' && $scope.col.sort.direction === direction);
  310. },
  311. /**
  312. * @ngdoc method
  313. * @methodOf ui.grid.service:uiGridColumnMenuService
  314. * @name suppressRemoveSort
  315. * @description determines whether we should suppress the removeSort option
  316. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  317. *
  318. */
  319. suppressRemoveSort: function( $scope ) {
  320. if ($scope.col && $scope.col.suppressRemoveSort) {
  321. return true;
  322. }
  323. else {
  324. return false;
  325. }
  326. },
  327. /**
  328. * @ngdoc boolean
  329. * @name enableHiding
  330. * @propertyOf ui.grid.class:GridOptions.columnDef
  331. * @description (optional) True by default. When set to false, this setting prevents a user from hiding the column
  332. * using the column menu or the grid menu.
  333. */
  334. /**
  335. * @ngdoc method
  336. * @methodOf ui.grid.service:uiGridColumnMenuService
  337. * @name hideable
  338. * @description determines whether a column can be hidden, by checking the enableHiding columnDef option
  339. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  340. *
  341. */
  342. hideable: function( $scope ) {
  343. if (typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.colDef && $scope.col.colDef.enableHiding === false ) {
  344. return false;
  345. }
  346. else {
  347. return true;
  348. }
  349. },
  350. /**
  351. * @ngdoc method
  352. * @methodOf ui.grid.service:uiGridColumnMenuService
  353. * @name getDefaultMenuItems
  354. * @description returns the default menu items for a column menu
  355. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  356. *
  357. */
  358. getDefaultMenuItems: function( $scope ){
  359. return [
  360. {
  361. title: i18nService.getSafeText('sort.ascending'),
  362. icon: 'ui-grid-icon-sort-alt-up',
  363. action: function($event) {
  364. $event.stopPropagation();
  365. $scope.sortColumn($event, uiGridConstants.ASC);
  366. },
  367. shown: function () {
  368. return service.sortable( $scope );
  369. },
  370. active: function() {
  371. return service.isActiveSort( $scope, uiGridConstants.ASC);
  372. }
  373. },
  374. {
  375. title: i18nService.getSafeText('sort.descending'),
  376. icon: 'ui-grid-icon-sort-alt-down',
  377. action: function($event) {
  378. $event.stopPropagation();
  379. $scope.sortColumn($event, uiGridConstants.DESC);
  380. },
  381. shown: function() {
  382. return service.sortable( $scope );
  383. },
  384. active: function() {
  385. return service.isActiveSort( $scope, uiGridConstants.DESC);
  386. }
  387. },
  388. {
  389. title: i18nService.getSafeText('sort.remove'),
  390. icon: 'ui-grid-icon-cancel',
  391. action: function ($event) {
  392. $event.stopPropagation();
  393. $scope.unsortColumn();
  394. },
  395. shown: function() {
  396. return service.sortable( $scope ) &&
  397. typeof($scope.col) !== 'undefined' && (typeof($scope.col.sort) !== 'undefined' &&
  398. typeof($scope.col.sort.direction) !== 'undefined') && $scope.col.sort.direction !== null &&
  399. !service.suppressRemoveSort( $scope );
  400. }
  401. },
  402. {
  403. title: i18nService.getSafeText('column.hide'),
  404. icon: 'ui-grid-icon-cancel',
  405. shown: function() {
  406. return service.hideable( $scope );
  407. },
  408. action: function ($event) {
  409. $event.stopPropagation();
  410. $scope.hideColumn();
  411. }
  412. },
  413. {
  414. title: i18nService.getSafeText('columnMenu.close'),
  415. screenReaderOnly: true,
  416. shown: function(){
  417. return true;
  418. },
  419. action: function($event){
  420. $event.stopPropagation();
  421. }
  422. }
  423. ];
  424. },
  425. /**
  426. * @ngdoc method
  427. * @methodOf ui.grid.service:uiGridColumnMenuService
  428. * @name getColumnElementPosition
  429. * @description gets the position information needed to place the column
  430. * menu below the column header
  431. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  432. * @param {GridCol} column the column we want to position below
  433. * @param {element} $columnElement the column element we want to position below
  434. * @returns {hash} containing left, top, offset, height, width
  435. *
  436. */
  437. getColumnElementPosition: function( $scope, column, $columnElement ){
  438. var positionData = {};
  439. positionData.left = $columnElement[0].offsetLeft;
  440. positionData.top = $columnElement[0].offsetTop;
  441. positionData.parentLeft = $columnElement[0].offsetParent.offsetLeft;
  442. // Get the grid scrollLeft
  443. positionData.offset = 0;
  444. if (column.grid.options.offsetLeft) {
  445. positionData.offset = column.grid.options.offsetLeft;
  446. }
  447. positionData.height = gridUtil.elementHeight($columnElement, true);
  448. positionData.width = gridUtil.elementWidth($columnElement, true);
  449. return positionData;
  450. },
  451. /**
  452. * @ngdoc method
  453. * @methodOf ui.grid.service:uiGridColumnMenuService
  454. * @name repositionMenu
  455. * @description Reposition the menu below the new column. If the menu has no child nodes
  456. * (i.e. it's not currently visible) then we guess it's width at 100, we'll be called again
  457. * later to fix it
  458. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  459. * @param {GridCol} column the column we want to position below
  460. * @param {hash} positionData a hash containing left, top, offset, height, width
  461. * @param {element} $elm the column menu element that we want to reposition
  462. * @param {element} $columnElement the column element that we want to reposition underneath
  463. *
  464. */
  465. repositionMenu: function( $scope, column, positionData, $elm, $columnElement ) {
  466. var menu = $elm[0].querySelectorAll('.ui-grid-menu');
  467. var containerId = column.renderContainer ? column.renderContainer : 'body';
  468. var renderContainer = column.grid.renderContainers[containerId];
  469. // It's possible that the render container of the column we're attaching to is
  470. // offset from the grid (i.e. pinned containers), we need to get the difference in the offsetLeft
  471. // between the render container and the grid
  472. var renderContainerElm = gridUtil.closestElm($columnElement, '.ui-grid-render-container');
  473. var renderContainerOffset = renderContainerElm.getBoundingClientRect().left - $scope.grid.element[0].getBoundingClientRect().left;
  474. var containerScrollLeft = renderContainerElm.querySelectorAll('.ui-grid-viewport')[0].scrollLeft;
  475. // default value the last width for _this_ column, otherwise last width for _any_ column, otherwise default to 170
  476. var myWidth = column.lastMenuWidth ? column.lastMenuWidth : ( $scope.lastMenuWidth ? $scope.lastMenuWidth : 170);
  477. var paddingRight = column.lastMenuPaddingRight ? column.lastMenuPaddingRight : ( $scope.lastMenuPaddingRight ? $scope.lastMenuPaddingRight : 10);
  478. if ( menu.length !== 0 ){
  479. var mid = menu[0].querySelectorAll('.ui-grid-menu-mid');
  480. if ( mid.length !== 0 && !angular.element(mid).hasClass('ng-hide') ) {
  481. myWidth = gridUtil.elementWidth(menu, true);
  482. $scope.lastMenuWidth = myWidth;
  483. column.lastMenuWidth = myWidth;
  484. // TODO(c0bra): use padding-left/padding-right based on document direction (ltr/rtl), place menu on proper side
  485. // Get the column menu right padding
  486. paddingRight = parseInt(gridUtil.getStyles(angular.element(menu)[0])['paddingRight'], 10);
  487. $scope.lastMenuPaddingRight = paddingRight;
  488. column.lastMenuPaddingRight = paddingRight;
  489. }
  490. }
  491. var left = positionData.left + renderContainerOffset - containerScrollLeft + positionData.parentLeft + positionData.width - myWidth + paddingRight;
  492. if (left < positionData.offset){
  493. left = positionData.offset;
  494. }
  495. $elm.css('left', left + 'px');
  496. $elm.css('top', (positionData.top + positionData.height) + 'px');
  497. }
  498. };
  499. return service;
  500. }])
  501. .directive('uiGridColumnMenu', ['$timeout', 'gridUtil', 'uiGridConstants', 'uiGridColumnMenuService', '$document',
  502. function ($timeout, gridUtil, uiGridConstants, uiGridColumnMenuService, $document) {
  503. /**
  504. * @ngdoc directive
  505. * @name ui.grid.directive:uiGridColumnMenu
  506. * @description Provides the column menu framework, leverages uiGridMenu underneath
  507. *
  508. */
  509. var uiGridColumnMenu = {
  510. priority: 0,
  511. scope: true,
  512. require: '^uiGrid',
  513. templateUrl: 'ui-grid/uiGridColumnMenu',
  514. replace: true,
  515. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  516. var self = this;
  517. uiGridColumnMenuService.initialize( $scope, uiGridCtrl );
  518. $scope.defaultMenuItems = uiGridColumnMenuService.getDefaultMenuItems( $scope );
  519. // Set the menu items for use with the column menu. The user can later add additional items via the watch
  520. $scope.menuItems = $scope.defaultMenuItems;
  521. uiGridColumnMenuService.setColMenuItemWatch( $scope );
  522. /**
  523. * @ngdoc method
  524. * @methodOf ui.grid.directive:uiGridColumnMenu
  525. * @name showMenu
  526. * @description Shows the column menu. If the menu is already displayed it
  527. * calls the menu to ask it to hide (it will animate), then it repositions the menu
  528. * to the right place whilst hidden (it will make an assumption on menu width),
  529. * then it asks the menu to show (it will animate), then it repositions the menu again
  530. * once we can calculate it's size.
  531. * @param {GridCol} column the column we want to position below
  532. * @param {element} $columnElement the column element we want to position below
  533. */
  534. $scope.showMenu = function(column, $columnElement, event) {
  535. // Swap to this column
  536. $scope.col = column;
  537. // Get the position information for the column element
  538. var colElementPosition = uiGridColumnMenuService.getColumnElementPosition( $scope, column, $columnElement );
  539. if ($scope.menuShown) {
  540. // we want to hide, then reposition, then show, but we want to wait for animations
  541. // we set a variable, and then rely on the menu-hidden event to call the reposition and show
  542. $scope.colElement = $columnElement;
  543. $scope.colElementPosition = colElementPosition;
  544. $scope.hideThenShow = true;
  545. $scope.$broadcast('hide-menu', { originalEvent: event });
  546. } else {
  547. self.shown = $scope.menuShown = true;
  548. uiGridColumnMenuService.repositionMenu( $scope, column, colElementPosition, $elm, $columnElement );
  549. $scope.colElement = $columnElement;
  550. $scope.colElementPosition = colElementPosition;
  551. $scope.$broadcast('show-menu', { originalEvent: event });
  552. }
  553. };
  554. /**
  555. * @ngdoc method
  556. * @methodOf ui.grid.directive:uiGridColumnMenu
  557. * @name hideMenu
  558. * @description Hides the column menu.
  559. * @param {boolean} broadcastTrigger true if we were triggered by a broadcast
  560. * from the menu itself - in which case don't broadcast again as we'll get
  561. * an infinite loop
  562. */
  563. $scope.hideMenu = function( broadcastTrigger ) {
  564. $scope.menuShown = false;
  565. if ( !broadcastTrigger ){
  566. $scope.$broadcast('hide-menu');
  567. }
  568. };
  569. $scope.$on('menu-hidden', function() {
  570. if ( $scope.hideThenShow ){
  571. delete $scope.hideThenShow;
  572. uiGridColumnMenuService.repositionMenu( $scope, $scope.col, $scope.colElementPosition, $elm, $scope.colElement );
  573. $scope.$broadcast('show-menu');
  574. $scope.menuShown = true;
  575. } else {
  576. $scope.hideMenu( true );
  577. if ($scope.col) {
  578. //Focus on the menu button
  579. gridUtil.focus.bySelector($document, '.ui-grid-header-cell.' + $scope.col.getColClass()+ ' .ui-grid-column-menu-button', $scope.col.grid, false);
  580. }
  581. }
  582. });
  583. $scope.$on('menu-shown', function() {
  584. $timeout( function() {
  585. uiGridColumnMenuService.repositionMenu( $scope, $scope.col, $scope.colElementPosition, $elm, $scope.colElement );
  586. delete $scope.colElementPosition;
  587. delete $scope.columnElement;
  588. }, 200);
  589. });
  590. /* Column methods */
  591. $scope.sortColumn = function (event, dir) {
  592. event.stopPropagation();
  593. $scope.grid.sortColumn($scope.col, dir, true)
  594. .then(function () {
  595. $scope.grid.refresh();
  596. $scope.hideMenu();
  597. });
  598. };
  599. $scope.unsortColumn = function () {
  600. $scope.col.unsort();
  601. $scope.grid.refresh();
  602. $scope.hideMenu();
  603. };
  604. //Since we are hiding this column the default hide action will fail so we need to focus somewhere else.
  605. var setFocusOnHideColumn = function(){
  606. $timeout(function(){
  607. // Get the UID of the first
  608. var focusToGridMenu = function(){
  609. return gridUtil.focus.byId('grid-menu', $scope.grid);
  610. };
  611. var thisIndex;
  612. $scope.grid.columns.some(function(element, index){
  613. if (angular.equals(element, $scope.col)) {
  614. thisIndex = index;
  615. return true;
  616. }
  617. });
  618. var previousVisibleCol;
  619. // Try and find the next lower or nearest column to focus on
  620. $scope.grid.columns.some(function(element, index){
  621. if (!element.visible){
  622. return false;
  623. } // This columns index is below the current column index
  624. else if ( index < thisIndex){
  625. previousVisibleCol = element;
  626. } // This elements index is above this column index and we haven't found one that is lower
  627. else if ( index > thisIndex && !previousVisibleCol) {
  628. // This is the next best thing
  629. previousVisibleCol = element;
  630. // We've found one so use it.
  631. return true;
  632. } // We've reached an element with an index above this column and the previousVisibleCol variable has been set
  633. else if (index > thisIndex && previousVisibleCol) {
  634. // We are done.
  635. return true;
  636. }
  637. });
  638. // If found then focus on it
  639. if (previousVisibleCol){
  640. var colClass = previousVisibleCol.getColClass();
  641. gridUtil.focus.bySelector($document, '.ui-grid-header-cell.' + colClass+ ' .ui-grid-header-cell-primary-focus', true).then(angular.noop, function(reason){
  642. if (reason !== 'canceled'){ // If this is canceled then don't perform the action
  643. //The fallback action is to focus on the grid menu
  644. return focusToGridMenu();
  645. }
  646. });
  647. } else {
  648. // Fallback action to focus on the grid menu
  649. focusToGridMenu();
  650. }
  651. });
  652. };
  653. $scope.hideColumn = function () {
  654. $scope.col.colDef.visible = false;
  655. $scope.col.visible = false;
  656. $scope.grid.queueGridRefresh();
  657. $scope.hideMenu();
  658. $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
  659. $scope.grid.api.core.raise.columnVisibilityChanged( $scope.col );
  660. // We are hiding so the default action of focusing on the button that opened this menu will fail.
  661. setFocusOnHideColumn();
  662. };
  663. },
  664. controller: ['$scope', function ($scope) {
  665. var self = this;
  666. $scope.$watch('menuItems', function (n, o) {
  667. self.menuItems = n;
  668. });
  669. }]
  670. };
  671. return uiGridColumnMenu;
  672. }]);
  673. })();
  674. (function(){
  675. 'use strict';
  676. angular.module('ui.grid').directive('uiGridFilter', ['$compile', '$templateCache', 'i18nService', 'gridUtil', function ($compile, $templateCache, i18nService, gridUtil) {
  677. return {
  678. compile: function() {
  679. return {
  680. pre: function ($scope, $elm, $attrs, controllers) {
  681. $scope.col.updateFilters = function( filterable ){
  682. $elm.children().remove();
  683. if ( filterable ){
  684. var template = $scope.col.filterHeaderTemplate;
  685. $elm.append($compile(template)($scope));
  686. }
  687. };
  688. $scope.$on( '$destroy', function() {
  689. delete $scope.col.updateFilters;
  690. });
  691. },
  692. post: function ($scope, $elm, $attrs, controllers){
  693. $scope.aria = i18nService.getSafeText('headerCell.aria');
  694. $scope.removeFilter = function(colFilter, index){
  695. colFilter.term = null;
  696. //Set the focus to the filter input after the action disables the button
  697. gridUtil.focus.bySelector($elm, '.ui-grid-filter-input-' + index);
  698. };
  699. }
  700. };
  701. }
  702. };
  703. }]);
  704. })();
  705. (function () {
  706. 'use strict';
  707. angular.module('ui.grid').directive('uiGridFooterCell', ['$timeout', 'gridUtil', 'uiGridConstants', '$compile',
  708. function ($timeout, gridUtil, uiGridConstants, $compile) {
  709. var uiGridFooterCell = {
  710. priority: 0,
  711. scope: {
  712. col: '=',
  713. row: '=',
  714. renderIndex: '='
  715. },
  716. replace: true,
  717. require: '^uiGrid',
  718. compile: function compile(tElement, tAttrs, transclude) {
  719. return {
  720. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  721. var cellFooter = $compile($scope.col.footerCellTemplate)($scope);
  722. $elm.append(cellFooter);
  723. },
  724. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  725. //$elm.addClass($scope.col.getColClass(false));
  726. $scope.grid = uiGridCtrl.grid;
  727. var initColClass = $scope.col.getColClass(false);
  728. $elm.addClass(initColClass);
  729. // apply any footerCellClass
  730. var classAdded;
  731. var updateClass = function( grid ){
  732. var contents = $elm;
  733. if ( classAdded ){
  734. contents.removeClass( classAdded );
  735. classAdded = null;
  736. }
  737. if (angular.isFunction($scope.col.footerCellClass)) {
  738. classAdded = $scope.col.footerCellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex);
  739. }
  740. else {
  741. classAdded = $scope.col.footerCellClass;
  742. }
  743. contents.addClass(classAdded);
  744. };
  745. if ($scope.col.footerCellClass) {
  746. updateClass();
  747. }
  748. $scope.col.updateAggregationValue();
  749. // Watch for column changes so we can alter the col cell class properly
  750. /* shouldn't be needed any more, given track by col.name
  751. $scope.$watch('col', function (n, o) {
  752. if (n !== o) {
  753. // See if the column's internal class has changed
  754. var newColClass = $scope.col.getColClass(false);
  755. if (newColClass !== initColClass) {
  756. $elm.removeClass(initColClass);
  757. $elm.addClass(newColClass);
  758. initColClass = newColClass;
  759. }
  760. }
  761. });
  762. */
  763. // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs
  764. var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateClass, [uiGridConstants.dataChange.COLUMN]);
  765. // listen for visible rows change and update aggregation values
  766. $scope.grid.api.core.on.rowsRendered( $scope, $scope.col.updateAggregationValue );
  767. $scope.grid.api.core.on.rowsRendered( $scope, updateClass );
  768. $scope.$on( '$destroy', dataChangeDereg );
  769. }
  770. };
  771. }
  772. };
  773. return uiGridFooterCell;
  774. }]);
  775. })();
  776. (function () {
  777. 'use strict';
  778. angular.module('ui.grid').directive('uiGridFooter', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function ($templateCache, $compile, uiGridConstants, gridUtil, $timeout) {
  779. return {
  780. restrict: 'EA',
  781. replace: true,
  782. // priority: 1000,
  783. require: ['^uiGrid', '^uiGridRenderContainer'],
  784. scope: true,
  785. compile: function ($elm, $attrs) {
  786. return {
  787. pre: function ($scope, $elm, $attrs, controllers) {
  788. var uiGridCtrl = controllers[0];
  789. var containerCtrl = controllers[1];
  790. $scope.grid = uiGridCtrl.grid;
  791. $scope.colContainer = containerCtrl.colContainer;
  792. containerCtrl.footer = $elm;
  793. var footerTemplate = $scope.grid.options.footerTemplate;
  794. gridUtil.getTemplate(footerTemplate)
  795. .then(function (contents) {
  796. var template = angular.element(contents);
  797. var newElm = $compile(template)($scope);
  798. $elm.append(newElm);
  799. if (containerCtrl) {
  800. // Inject a reference to the footer viewport (if it exists) into the grid controller for use in the horizontal scroll handler below
  801. var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0];
  802. if (footerViewport) {
  803. containerCtrl.footerViewport = footerViewport;
  804. }
  805. }
  806. });
  807. },
  808. post: function ($scope, $elm, $attrs, controllers) {
  809. var uiGridCtrl = controllers[0];
  810. var containerCtrl = controllers[1];
  811. // gridUtil.logDebug('ui-grid-footer link');
  812. var grid = uiGridCtrl.grid;
  813. // Don't animate footer cells
  814. gridUtil.disableAnimations($elm);
  815. containerCtrl.footer = $elm;
  816. var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0];
  817. if (footerViewport) {
  818. containerCtrl.footerViewport = footerViewport;
  819. }
  820. }
  821. };
  822. }
  823. };
  824. }]);
  825. })();
  826. (function () {
  827. 'use strict';
  828. angular.module('ui.grid').directive('uiGridGridFooter', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function ($templateCache, $compile, uiGridConstants, gridUtil, $timeout) {
  829. return {
  830. restrict: 'EA',
  831. replace: true,
  832. // priority: 1000,
  833. require: '^uiGrid',
  834. scope: true,
  835. compile: function ($elm, $attrs) {
  836. return {
  837. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  838. $scope.grid = uiGridCtrl.grid;
  839. var footerTemplate = $scope.grid.options.gridFooterTemplate;
  840. gridUtil.getTemplate(footerTemplate)
  841. .then(function (contents) {
  842. var template = angular.element(contents);
  843. var newElm = $compile(template)($scope);
  844. $elm.append(newElm);
  845. });
  846. },
  847. post: function ($scope, $elm, $attrs, controllers) {
  848. }
  849. };
  850. }
  851. };
  852. }]);
  853. })();
  854. (function(){
  855. 'use strict';
  856. angular.module('ui.grid').directive('uiGridGroupPanel', ["$compile", "uiGridConstants", "gridUtil", function($compile, uiGridConstants, gridUtil) {
  857. var defaultTemplate = 'ui-grid/ui-grid-group-panel';
  858. return {
  859. restrict: 'EA',
  860. replace: true,
  861. require: '?^uiGrid',
  862. scope: false,
  863. compile: function($elm, $attrs) {
  864. return {
  865. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  866. var groupPanelTemplate = $scope.grid.options.groupPanelTemplate || defaultTemplate;
  867. gridUtil.getTemplate(groupPanelTemplate)
  868. .then(function (contents) {
  869. var template = angular.element(contents);
  870. var newElm = $compile(template)($scope);
  871. $elm.append(newElm);
  872. });
  873. },
  874. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  875. $elm.bind('$destroy', function() {
  876. // scrollUnbinder();
  877. });
  878. }
  879. };
  880. }
  881. };
  882. }]);
  883. })();
  884. (function(){
  885. 'use strict';
  886. angular.module('ui.grid').directive('uiGridHeaderCell', ['$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', 'ScrollEvent', 'i18nService','uiGridGridMenuService',
  887. function ($compile, $timeout, $window, $document, gridUtil, uiGridConstants, ScrollEvent, i18nService,uiGridGridMenuService) {
  888. // Do stuff after mouse has been down this many ms on the header cell
  889. var mousedownTimeout = 500;
  890. var changeModeTimeout = 500; // length of time between a touch event and a mouse event being recognised again, and vice versa
  891. var uiGridHeaderCell = {
  892. priority: 0,
  893. scope: {
  894. col: '=',
  895. row: '=',
  896. renderIndex: '='
  897. },
  898. require: ['^uiGrid', '^uiGridRenderContainer'],
  899. replace: true,
  900. compile: function() {
  901. return {
  902. pre: function ($scope, $elm, $attrs) {
  903. var cellHeader = $compile($scope.col.headerCellTemplate)($scope);
  904. $elm.append(cellHeader);
  905. },
  906. post: function ($scope, $elm, $attrs, controllers) {
  907. var uiGridCtrl = controllers[0];
  908. var renderContainerCtrl = controllers[1];
  909. $scope.i18n = {
  910. headerCell: i18nService.getSafeText('headerCell'),
  911. sort: i18nService.getSafeText('sort')
  912. };
  913. $scope.getSortDirectionAriaLabel = function(){
  914. var col = $scope.col;
  915. //Trying to recreate this sort of thing but it was getting messy having it in the template.
  916. //Sort direction {{col.sort.direction == asc ? 'ascending' : ( col.sort.direction == desc ? 'descending':'none')}}. {{col.sort.priority ? {{columnPriorityText}} {{col.sort.priority}} : ''}
  917. var sortDirectionText = col.sort.direction === uiGridConstants.ASC ? $scope.i18n.sort.ascending : ( col.sort.direction === uiGridConstants.DESC ? $scope.i18n.sort.descending : $scope.i18n.sort.none);
  918. var label = sortDirectionText;
  919. //Append the priority if it exists
  920. if (col.sort.priority) {
  921. label = label + '. ' + $scope.i18n.headerCell.priority + ' ' + col.sort.priority;
  922. }
  923. return label;
  924. };
  925. $scope.grid = uiGridCtrl.grid;
  926. $scope.renderContainer = uiGridCtrl.grid.renderContainers[renderContainerCtrl.containerId];
  927. var initColClass = $scope.col.getColClass(false);
  928. $elm.addClass(initColClass);
  929. // Hide the menu by default
  930. $scope.menuShown = false;
  931. // Put asc and desc sort directions in scope
  932. $scope.asc = uiGridConstants.ASC;
  933. $scope.desc = uiGridConstants.DESC;
  934. // Store a reference to menu element
  935. var $colMenu = angular.element( $elm[0].querySelectorAll('.ui-grid-header-cell-menu') );
  936. var $contentsElm = angular.element( $elm[0].querySelectorAll('.ui-grid-cell-contents') );
  937. // apply any headerCellClass
  938. var classAdded;
  939. var previousMouseX;
  940. // filter watchers
  941. var filterDeregisters = [];
  942. /*
  943. * Our basic approach here for event handlers is that we listen for a down event (mousedown or touchstart).
  944. * Once we have a down event, we need to work out whether we have a click, a drag, or a
  945. * hold. A click would sort the grid (if sortable). A drag would be used by moveable, so
  946. * we ignore it. A hold would open the menu.
  947. *
  948. * So, on down event, we put in place handlers for move and up events, and a timer. If the
  949. * timer expires before we see a move or up, then we have a long press and hence a column menu open.
  950. * If the up happens before the timer, then we have a click, and we sort if the column is sortable.
  951. * If a move happens before the timer, then we are doing column move, so we do nothing, the moveable feature
  952. * will handle it.
  953. *
  954. * To deal with touch enabled devices that also have mice, we only create our handlers when
  955. * we get the down event, and we create the corresponding handlers - if we're touchstart then
  956. * we get touchmove and touchend, if we're mousedown then we get mousemove and mouseup.
  957. *
  958. * We also suppress the click action whilst this is happening - otherwise after the mouseup there
  959. * will be a click event and that can cause the column menu to close
  960. *
  961. */
  962. $scope.downFn = function( event ){
  963. event.stopPropagation();
  964. if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) {
  965. event = event.originalEvent;
  966. }
  967. // Don't show the menu if it's not the left button
  968. if (event.button && event.button !== 0) {
  969. return;
  970. }
  971. previousMouseX = event.pageX;
  972. $scope.mousedownStartTime = (new Date()).getTime();
  973. $scope.mousedownTimeout = $timeout(function() { }, mousedownTimeout);
  974. $scope.mousedownTimeout.then(function () {
  975. if ( $scope.colMenu ) {
  976. uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm, event);
  977. }
  978. });
  979. uiGridCtrl.fireEvent(uiGridConstants.events.COLUMN_HEADER_CLICK, {event: event, columnName: $scope.col.colDef.name});
  980. $scope.offAllEvents();
  981. if ( event.type === 'touchstart'){
  982. $document.on('touchend', $scope.upFn);
  983. $document.on('touchmove', $scope.moveFn);
  984. } else if ( event.type === 'mousedown' ){
  985. $document.on('mouseup', $scope.upFn);
  986. $document.on('mousemove', $scope.moveFn);
  987. }
  988. };
  989. $scope.upFn = function( event ){
  990. event.stopPropagation();
  991. $timeout.cancel($scope.mousedownTimeout);
  992. $scope.offAllEvents();
  993. $scope.onDownEvents(event.type);
  994. var mousedownEndTime = (new Date()).getTime();
  995. var mousedownTime = mousedownEndTime - $scope.mousedownStartTime;
  996. if (mousedownTime > mousedownTimeout) {
  997. // long click, handled above with mousedown
  998. }
  999. else {
  1000. // short click
  1001. if ( $scope.sortable ){
  1002. $scope.handleClick(event);
  1003. }
  1004. }
  1005. };
  1006. $scope.moveFn = function( event ){
  1007. // Chrome is known to fire some bogus move events.
  1008. var changeValue = event.pageX - previousMouseX;
  1009. if ( changeValue === 0 ){ return; }
  1010. // we're a move, so do nothing and leave for column move (if enabled) to take over
  1011. $timeout.cancel($scope.mousedownTimeout);
  1012. $scope.offAllEvents();
  1013. $scope.onDownEvents(event.type);
  1014. };
  1015. $scope.clickFn = function ( event ){
  1016. event.stopPropagation();
  1017. $contentsElm.off('click', $scope.clickFn);
  1018. };
  1019. $scope.offAllEvents = function(){
  1020. $contentsElm.off('touchstart', $scope.downFn);
  1021. $contentsElm.off('mousedown', $scope.downFn);
  1022. $document.off('touchend', $scope.upFn);
  1023. $document.off('mouseup', $scope.upFn);
  1024. $document.off('touchmove', $scope.moveFn);
  1025. $document.off('mousemove', $scope.moveFn);
  1026. $contentsElm.off('click', $scope.clickFn);
  1027. };
  1028. $scope.onDownEvents = function( type ){
  1029. // If there is a previous event, then wait a while before
  1030. // activating the other mode - i.e. if the last event was a touch event then
  1031. // don't enable mouse events for a wee while (500ms or so)
  1032. // Avoids problems with devices that emulate mouse events when you have touch events
  1033. switch (type){
  1034. case 'touchmove':
  1035. case 'touchend':
  1036. $contentsElm.on('click', $scope.clickFn);
  1037. $contentsElm.on('touchstart', $scope.downFn);
  1038. $timeout(function(){
  1039. $contentsElm.on('mousedown', $scope.downFn);
  1040. }, changeModeTimeout);
  1041. break;
  1042. case 'mousemove':
  1043. case 'mouseup':
  1044. $contentsElm.on('click', $scope.clickFn);
  1045. $contentsElm.on('mousedown', $scope.downFn);
  1046. $timeout(function(){
  1047. $contentsElm.on('touchstart', $scope.downFn);
  1048. }, changeModeTimeout);
  1049. break;
  1050. default:
  1051. $contentsElm.on('click', $scope.clickFn);
  1052. $contentsElm.on('touchstart', $scope.downFn);
  1053. $contentsElm.on('mousedown', $scope.downFn);
  1054. }
  1055. };
  1056. var updateHeaderOptions = function( grid ){
  1057. var contents = $elm;
  1058. if ( classAdded ){
  1059. contents.removeClass( classAdded );
  1060. classAdded = null;
  1061. }
  1062. if (angular.isFunction($scope.col.headerCellClass)) {
  1063. classAdded = $scope.col.headerCellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex);
  1064. }
  1065. else {
  1066. classAdded = $scope.col.headerCellClass;
  1067. }
  1068. contents.addClass(classAdded);
  1069. var rightMostContainer = $scope.grid.renderContainers['right'] ? $scope.grid.renderContainers['right'] : $scope.grid.renderContainers['body'];
  1070. $scope.isLastCol = ( $scope.col === rightMostContainer.visibleColumnCache[ rightMostContainer.visibleColumnCache.length - 1 ] );
  1071. // Figure out whether this column is sortable or not
  1072. if (uiGridCtrl.grid.options.enableSorting && $scope.col.enableSorting) {
  1073. $scope.sortable = true;
  1074. }
  1075. else {
  1076. $scope.sortable = false;
  1077. }
  1078. // Figure out whether this column is filterable or not
  1079. var oldFilterable = $scope.filterable;
  1080. if (uiGridCtrl.grid.options.enableFiltering && $scope.col.enableFiltering) {
  1081. $scope.filterable = true;
  1082. }
  1083. else {
  1084. $scope.filterable = false;
  1085. }
  1086. if ( oldFilterable !== $scope.filterable){
  1087. if ( typeof($scope.col.updateFilters) !== 'undefined' ){
  1088. $scope.col.updateFilters($scope.filterable);
  1089. }
  1090. // if column is filterable add a filter watcher
  1091. if ($scope.filterable) {
  1092. $scope.col.filters.forEach( function(filter, i) {
  1093. filterDeregisters.push($scope.$watch('col.filters[' + i + '].term', function(n, o) {
  1094. if (n !== o) {
  1095. uiGridCtrl.grid.api.core.raise.filterChanged();
  1096. uiGridCtrl.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
  1097. uiGridCtrl.grid.queueGridRefresh();
  1098. }
  1099. }));
  1100. });
  1101. $scope.$on('$destroy', function() {
  1102. filterDeregisters.forEach( function(filterDeregister) {
  1103. filterDeregister();
  1104. });
  1105. });
  1106. } else {
  1107. filterDeregisters.forEach( function(filterDeregister) {
  1108. filterDeregister();
  1109. });
  1110. }
  1111. }
  1112. // figure out whether we support column menus
  1113. if ($scope.col.grid.options && $scope.col.grid.options.enableColumnMenus !== false &&
  1114. $scope.col.colDef && $scope.col.colDef.enableColumnMenu !== false){
  1115. $scope.colMenu = true;
  1116. } else {
  1117. $scope.colMenu = false;
  1118. }
  1119. /**
  1120. * @ngdoc property
  1121. * @name enableColumnMenu
  1122. * @propertyOf ui.grid.class:GridOptions.columnDef
  1123. * @description if column menus are enabled, controls the column menus for this specific
  1124. * column (i.e. if gridOptions.enableColumnMenus, then you can control column menus
  1125. * using this option. If gridOptions.enableColumnMenus === false then you get no column
  1126. * menus irrespective of the value of this option ). Defaults to true.
  1127. *
  1128. */
  1129. /**
  1130. * @ngdoc property
  1131. * @name enableColumnMenus
  1132. * @propertyOf ui.grid.class:GridOptions.columnDef
  1133. * @description Override for column menus everywhere - if set to false then you get no
  1134. * column menus. Defaults to true.
  1135. *
  1136. */
  1137. $scope.offAllEvents();
  1138. if ($scope.sortable || $scope.colMenu) {
  1139. $scope.onDownEvents();
  1140. $scope.$on('$destroy', function () {
  1141. $scope.offAllEvents();
  1142. });
  1143. }
  1144. };
  1145. /*
  1146. $scope.$watch('col', function (n, o) {
  1147. if (n !== o) {
  1148. // See if the column's internal class has changed
  1149. var newColClass = $scope.col.getColClass(false);
  1150. if (newColClass !== initColClass) {
  1151. $elm.removeClass(initColClass);
  1152. $elm.addClass(newColClass);
  1153. initColClass = newColClass;
  1154. }
  1155. }
  1156. });
  1157. */
  1158. updateHeaderOptions();
  1159. // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs
  1160. var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateHeaderOptions, [uiGridConstants.dataChange.COLUMN]);
  1161. $scope.$on( '$destroy', dataChangeDereg );
  1162. $scope.handleClick = function(event) {
  1163. // If the shift key is being held down, add this column to the sort
  1164. var add = false;
  1165. if (event.shiftKey) {
  1166. add = true;
  1167. }
  1168. // Sort this column then rebuild the grid's rows
  1169. uiGridCtrl.grid.sortColumn($scope.col, add)
  1170. .then(function () {
  1171. if (uiGridCtrl.columnMenuScope) { uiGridCtrl.columnMenuScope.hideMenu(); }
  1172. uiGridCtrl.grid.refresh();
  1173. });
  1174. };
  1175. $scope.decrement = function () {
  1176. if ($scope.shown){
  1177. $scope.$broadcast('hide-menu');
  1178. $scope.shown = false;
  1179. } else {
  1180. console.log($scope.menuItems)
  1181. $scope.menuItems = uiGridGridMenuService.getMenuItems( $scope );
  1182. $scope.$broadcast('show-menu');
  1183. $scope.shown = true;
  1184. }
  1185. };
  1186. $scope.toggleMenu = function(event) {
  1187. event.stopPropagation();
  1188. // If the menu is already showing...
  1189. if (uiGridCtrl.columnMenuScope.menuShown) {
  1190. // ... and we're the column the menu is on...
  1191. if (uiGridCtrl.columnMenuScope.col === $scope.col) {
  1192. // ... hide it
  1193. uiGridCtrl.columnMenuScope.hideMenu();
  1194. }
  1195. // ... and we're NOT the column the menu is on
  1196. else {
  1197. // ... move the menu to our column
  1198. uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);
  1199. }
  1200. }
  1201. // If the menu is NOT showing
  1202. else {
  1203. // ... show it on our column
  1204. uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);
  1205. }
  1206. };
  1207. }
  1208. };
  1209. }
  1210. };
  1211. return uiGridHeaderCell;
  1212. }]);
  1213. })();
  1214. (function(){
  1215. 'use strict';
  1216. angular.module('ui.grid').directive('uiGridHeader', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', 'ScrollEvent',
  1217. function($templateCache, $compile, uiGridConstants, gridUtil, $timeout, ScrollEvent) {
  1218. var defaultTemplate = 'ui-grid/ui-grid-header';
  1219. var emptyTemplate = 'ui-grid/ui-grid-no-header';
  1220. return {
  1221. restrict: 'EA',
  1222. // templateUrl: 'ui-grid/ui-grid-header',
  1223. replace: true,
  1224. // priority: 1000,
  1225. require: ['^uiGrid', '^uiGridRenderContainer'],
  1226. scope: true,
  1227. compile: function($elm, $attrs) {
  1228. return {
  1229. pre: function ($scope, $elm, $attrs, controllers) {
  1230. var uiGridCtrl = controllers[0];
  1231. var containerCtrl = controllers[1];
  1232. $scope.grid = uiGridCtrl.grid;
  1233. $scope.colContainer = containerCtrl.colContainer;
  1234. updateHeaderReferences();
  1235. var headerTemplate;
  1236. if (!$scope.grid.options.showHeader) {
  1237. headerTemplate = emptyTemplate;
  1238. }
  1239. else {
  1240. headerTemplate = ($scope.grid.options.headerTemplate) ? $scope.grid.options.headerTemplate : defaultTemplate;
  1241. }
  1242. gridUtil.getTemplate(headerTemplate)
  1243. .then(function (contents) {
  1244. var template = angular.element(contents);
  1245. var newElm = $compile(template)($scope);
  1246. $elm.replaceWith(newElm);
  1247. // And update $elm to be the new element
  1248. $elm = newElm;
  1249. updateHeaderReferences();
  1250. if (containerCtrl) {
  1251. // Inject a reference to the header viewport (if it exists) into the grid controller for use in the horizontal scroll handler below
  1252. var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0];
  1253. if (headerViewport) {
  1254. containerCtrl.headerViewport = headerViewport;
  1255. angular.element(headerViewport).on('scroll', scrollHandler);
  1256. $scope.$on('$destroy', function () {
  1257. angular.element(headerViewport).off('scroll', scrollHandler);
  1258. });
  1259. }
  1260. }
  1261. $scope.grid.queueRefresh();
  1262. });
  1263. function updateHeaderReferences() {
  1264. containerCtrl.header = containerCtrl.colContainer.header = $elm;
  1265. var headerCanvases = $elm[0].getElementsByClassName('ui-grid-header-canvas');
  1266. if (headerCanvases.length > 0) {
  1267. containerCtrl.headerCanvas = containerCtrl.colContainer.headerCanvas = headerCanvases[0];
  1268. }
  1269. else {
  1270. containerCtrl.headerCanvas = null;
  1271. }
  1272. }
  1273. function scrollHandler(evt) {
  1274. if (uiGridCtrl.grid.isScrollingHorizontally) {
  1275. return;
  1276. }
  1277. var newScrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.headerViewport, uiGridCtrl.grid);
  1278. var horizScrollPercentage = containerCtrl.colContainer.scrollHorizontal(newScrollLeft);
  1279. var scrollEvent = new ScrollEvent(uiGridCtrl.grid, null, containerCtrl.colContainer, ScrollEvent.Sources.ViewPortScroll);
  1280. scrollEvent.newScrollLeft = newScrollLeft;
  1281. if ( horizScrollPercentage > -1 ){
  1282. scrollEvent.x = { percentage: horizScrollPercentage };
  1283. }
  1284. uiGridCtrl.grid.scrollContainers(null, scrollEvent);
  1285. }
  1286. },
  1287. post: function ($scope, $elm, $attrs, controllers) {
  1288. var uiGridCtrl = controllers[0];
  1289. var containerCtrl = controllers[1];
  1290. // gridUtil.logDebug('ui-grid-header link');
  1291. var grid = uiGridCtrl.grid;
  1292. // Don't animate header cells
  1293. gridUtil.disableAnimations($elm);
  1294. function updateColumnWidths() {
  1295. // this styleBuilder always runs after the renderContainer, so we can rely on the column widths
  1296. // already being populated correctly
  1297. var columnCache = containerCtrl.colContainer.visibleColumnCache;
  1298. // Build the CSS
  1299. // uiGridCtrl.grid.columns.forEach(function (column) {
  1300. var ret = '';
  1301. var canvasWidth = 0;
  1302. columnCache.forEach(function (column) {
  1303. ret = ret + column.getColClassDefinition();
  1304. canvasWidth += column.drawnWidth;
  1305. });
  1306. containerCtrl.colContainer.canvasWidth = canvasWidth;
  1307. // Return the styles back to buildStyles which pops them into the `customStyles` scope variable
  1308. return ret;
  1309. }
  1310. containerCtrl.header = $elm;
  1311. var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0];
  1312. if (headerViewport) {
  1313. containerCtrl.headerViewport = headerViewport;
  1314. }
  1315. //todo: remove this if by injecting gridCtrl into unit tests
  1316. if (uiGridCtrl) {
  1317. uiGridCtrl.grid.registerStyleComputation({
  1318. priority: 15,
  1319. func: updateColumnWidths
  1320. });
  1321. }
  1322. }
  1323. };
  1324. }
  1325. };
  1326. }]);
  1327. })();
  1328. (function(){
  1329. angular.module('ui.grid')
  1330. .service('uiGridGridMenuService', [ 'gridUtil', 'i18nService', 'uiGridConstants', function( gridUtil, i18nService, uiGridConstants ) {
  1331. /**
  1332. * @ngdoc service
  1333. * @name ui.grid.gridMenuService
  1334. *
  1335. * @description Methods for working with the grid menu
  1336. */
  1337. var service = {
  1338. /**
  1339. * @ngdoc method
  1340. * @methodOf ui.grid.gridMenuService
  1341. * @name initialize
  1342. * @description Sets up the gridMenu. Most importantly, sets our
  1343. * scope onto the grid object as grid.gridMenuScope, allowing us
  1344. * to operate when passed only the grid. Second most importantly,
  1345. * we register the 'addToGridMenu' and 'removeFromGridMenu' methods
  1346. * on the core api.
  1347. * @param {$scope} $scope the scope of this gridMenu
  1348. * @param {Grid} grid the grid to which this gridMenu is associated
  1349. */
  1350. initialize: function( $scope, grid ){
  1351. grid.gridMenuScope = $scope;
  1352. $scope.grid = grid;
  1353. $scope.registeredMenuItems = [];
  1354. // not certain this is needed, but would be bad to create a memory leak
  1355. $scope.$on('$destroy', function() {
  1356. if ( $scope.grid && $scope.grid.gridMenuScope ){
  1357. $scope.grid.gridMenuScope = null;
  1358. }
  1359. if ( $scope.grid ){
  1360. $scope.grid = null;
  1361. }
  1362. if ( $scope.registeredMenuItems ){
  1363. $scope.registeredMenuItems = null;
  1364. }
  1365. });
  1366. $scope.registeredMenuItems = [];
  1367. /**
  1368. * @ngdoc function
  1369. * @name addToGridMenu
  1370. * @methodOf ui.grid.core.api:PublicApi
  1371. * @description add items to the grid menu. Used by features
  1372. * to add their menu items if they are enabled, can also be used by
  1373. * end users to add menu items. This method has the advantage of allowing
  1374. * remove again, which can simplify management of which items are included
  1375. * in the menu when. (Noting that in most cases the shown and active functions
  1376. * provide a better way to handle visibility of menu items)
  1377. * @param {Grid} grid the grid on which we are acting
  1378. * @param {array} items menu items in the format as described in the tutorial, with
  1379. * the added note that if you want to use remove you must also specify an `id` field,
  1380. * which is provided when you want to remove an item. The id should be unique.
  1381. *
  1382. */
  1383. grid.api.registerMethod( 'core', 'addToGridMenu', service.addToGridMenu );
  1384. /**
  1385. * @ngdoc function
  1386. * @name removeFromGridMenu
  1387. * @methodOf ui.grid.core.api:PublicApi
  1388. * @description Remove an item from the grid menu based on a provided id. Assumes
  1389. * that the id is unique, removes only the last instance of that id. Does nothing if
  1390. * the specified id is not found
  1391. * @param {Grid} grid the grid on which we are acting
  1392. * @param {string} id the id we'd like to remove from the menu
  1393. *
  1394. */
  1395. grid.api.registerMethod( 'core', 'removeFromGridMenu', service.removeFromGridMenu );
  1396. },
  1397. /**
  1398. * @ngdoc function
  1399. * @name addToGridMenu
  1400. * @propertyOf ui.grid.gridMenuService
  1401. * @description add items to the grid menu. Used by features
  1402. * to add their menu items if they are enabled, can also be used by
  1403. * end users to add menu items. This method has the advantage of allowing
  1404. * remove again, which can simplify management of which items are included
  1405. * in the menu when. (Noting that in most cases the shown and active functions
  1406. * provide a better way to handle visibility of menu items)
  1407. * @param {Grid} grid the grid on which we are acting
  1408. * @param {array} items menu items in the format as described in the tutorial, with
  1409. * the added note that if you want to use remove you must also specify an `id` field,
  1410. * which is provided when you want to remove an item. The id should be unique.
  1411. *
  1412. */
  1413. addToGridMenu: function( grid, menuItems ) {
  1414. if ( !angular.isArray( menuItems ) ) {
  1415. gridUtil.logError( 'addToGridMenu: menuItems must be an array, and is not, not adding any items');
  1416. } else {
  1417. if ( grid.gridMenuScope ){
  1418. grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems ? grid.gridMenuScope.registeredMenuItems : [];
  1419. grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems.concat( menuItems );
  1420. } else {
  1421. gridUtil.logError( 'Asked to addToGridMenu, but gridMenuScope not present. Timing issue? Please log issue with ui-grid');
  1422. }
  1423. }
  1424. },
  1425. /**
  1426. * @ngdoc function
  1427. * @name removeFromGridMenu
  1428. * @methodOf ui.grid.gridMenuService
  1429. * @description Remove an item from the grid menu based on a provided id. Assumes
  1430. * that the id is unique, removes only the last instance of that id. Does nothing if
  1431. * the specified id is not found. If there is no gridMenuScope or registeredMenuItems
  1432. * then do nothing silently - the desired result is those menu items not be present and they
  1433. * aren't.
  1434. * @param {Grid} grid the grid on which we are acting
  1435. * @param {string} id the id we'd like to remove from the menu
  1436. *
  1437. */
  1438. removeFromGridMenu: function( grid, id ){
  1439. var foundIndex = -1;
  1440. if ( grid && grid.gridMenuScope ){
  1441. grid.gridMenuScope.registeredMenuItems.forEach( function( value, index ) {
  1442. if ( value.id === id ){
  1443. if (foundIndex > -1) {
  1444. gridUtil.logError( 'removeFromGridMenu: found multiple items with the same id, removing only the last' );
  1445. } else {
  1446. foundIndex = index;
  1447. }
  1448. }
  1449. });
  1450. }
  1451. if ( foundIndex > -1 ){
  1452. grid.gridMenuScope.registeredMenuItems.splice( foundIndex, 1 );
  1453. }
  1454. },
  1455. /**
  1456. * @ngdoc array
  1457. * @name gridMenuCustomItems
  1458. * @propertyOf ui.grid.class:GridOptions
  1459. * @description (optional) An array of menu items that should be added to
  1460. * the gridMenu. Follow the format documented in the tutorial for column
  1461. * menu customisation. The context provided to the action function will
  1462. * include context.grid. An alternative if working with dynamic menus is to use the
  1463. * provided api - core.addToGridMenu and core.removeFromGridMenu, which handles
  1464. * some of the management of items for you.
  1465. *
  1466. */
  1467. /**
  1468. * @ngdoc boolean
  1469. * @name gridMenuShowHideColumns
  1470. * @propertyOf ui.grid.class:GridOptions
  1471. * @description true by default, whether the grid menu should allow hide/show
  1472. * of columns
  1473. *
  1474. */
  1475. /**
  1476. * @ngdoc method
  1477. * @methodOf ui.grid.gridMenuService
  1478. * @name getMenuItems
  1479. * @description Decides the menu items to show in the menu. This is a
  1480. * combination of:
  1481. *
  1482. * - the default menu items that are always included,
  1483. * - any menu items that have been provided through the addMenuItem api. These
  1484. * are typically added by features within the grid
  1485. * - any menu items included in grid.options.gridMenuCustomItems. These can be
  1486. * changed dynamically, as they're always recalculated whenever we show the
  1487. * menu
  1488. * @param {$scope} $scope the scope of this gridMenu, from which we can find all
  1489. * the information that we need
  1490. * @returns {array} an array of menu items that can be shown
  1491. */
  1492. getMenuItems: function( $scope ) {
  1493. var menuItems = [
  1494. // this is where we add any menu items we want to always include
  1495. ];
  1496. if ( $scope.grid.options.gridMenuCustomItems ){
  1497. if ( !angular.isArray( $scope.grid.options.gridMenuCustomItems ) ){
  1498. gridUtil.logError( 'gridOptions.gridMenuCustomItems must be an array, and is not');
  1499. } else {
  1500. menuItems = menuItems.concat( $scope.grid.options.gridMenuCustomItems );
  1501. }
  1502. }
  1503. var clearFilters = [{
  1504. title: i18nService.getSafeText('gridMenu.clearAllFilters'),
  1505. action: function ($event) {
  1506. $scope.grid.clearAllFilters(undefined, true, undefined);
  1507. },
  1508. shown: function() {
  1509. return $scope.grid.options.enableFiltering;
  1510. },
  1511. order: 100
  1512. }];
  1513. menuItems = menuItems.concat( clearFilters );
  1514. menuItems = menuItems.concat( $scope.registeredMenuItems );
  1515. if ( $scope.grid.options.gridMenuShowHideColumns !== false ){
  1516. menuItems = menuItems.concat( service.showHideColumns( $scope ) );
  1517. }
  1518. menuItems.sort(function(a, b){
  1519. return a.order - b.order;
  1520. });
  1521. return menuItems;
  1522. },
  1523. /**
  1524. * @ngdoc array
  1525. * @name gridMenuTitleFilter
  1526. * @propertyOf ui.grid.class:GridOptions
  1527. * @description (optional) A function that takes a title string
  1528. * (usually the col.displayName), and converts it into a display value. The function
  1529. * must return either a string or a promise.
  1530. *
  1531. * Used for internationalization of the grid menu column names - for angular-translate
  1532. * you can pass $translate as the function, for i18nService you can pass getSafeText as the
  1533. * function
  1534. * @example
  1535. * <pre>
  1536. * gridOptions = {
  1537. * gridMenuTitleFilter: $translate
  1538. * }
  1539. * </pre>
  1540. */
  1541. /**
  1542. * @ngdoc method
  1543. * @methodOf ui.grid.gridMenuService
  1544. * @name showHideColumns
  1545. * @description Adds two menu items for each of the columns in columnDefs. One
  1546. * menu item for hide, one menu item for show. Each is visible when appropriate
  1547. * (show when column is not visible, hide when column is visible). Each toggles
  1548. * the visible property on the columnDef using toggleColumnVisibility
  1549. * @param {$scope} $scope of a gridMenu, which contains a reference to the grid
  1550. */
  1551. showHideColumns: function( $scope ){
  1552. var showHideColumns = [];
  1553. if ( !$scope.grid.options.columnDefs || $scope.grid.options.columnDefs.length === 0 || $scope.grid.columns.length === 0 ) {
  1554. return showHideColumns;
  1555. }
  1556. // add header for columns
  1557. showHideColumns.push({
  1558. title: i18nService.getSafeText('gridMenu.columns'),
  1559. order: 300
  1560. });
  1561. $scope.grid.options.gridMenuTitleFilter = $scope.grid.options.gridMenuTitleFilter ? $scope.grid.options.gridMenuTitleFilter : function( title ) { return title; };
  1562. $scope.grid.options.columnDefs.forEach( function( colDef, index ){
  1563. if ( colDef.enableHiding !== false ){
  1564. // add hide menu item - shows an OK icon as we only show when column is already visible
  1565. var menuItem = {
  1566. icon: 'ui-grid-icon-ok',
  1567. action: function($event) {
  1568. $event.stopPropagation();
  1569. service.toggleColumnVisibility( this.context.gridCol );
  1570. },
  1571. shown: function() {
  1572. return this.context.gridCol.colDef.visible === true || this.context.gridCol.colDef.visible === undefined;
  1573. },
  1574. context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) },
  1575. leaveOpen: true,
  1576. order: 301 + index * 2
  1577. };
  1578. service.setMenuItemTitle( menuItem, colDef, $scope.grid );
  1579. showHideColumns.push( menuItem );
  1580. // add show menu item - shows no icon as we only show when column is invisible
  1581. menuItem = {
  1582. icon: 'ui-grid-icon-cancel',
  1583. action: function($event) {
  1584. $event.stopPropagation();
  1585. service.toggleColumnVisibility( this.context.gridCol );
  1586. },
  1587. shown: function() {
  1588. return !(this.context.gridCol.colDef.visible === true || this.context.gridCol.colDef.visible === undefined);
  1589. },
  1590. context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) },
  1591. leaveOpen: true,
  1592. order: 301 + index * 2 + 1
  1593. };
  1594. service.setMenuItemTitle( menuItem, colDef, $scope.grid );
  1595. showHideColumns.push( menuItem );
  1596. }
  1597. });
  1598. return showHideColumns;
  1599. },
  1600. /**
  1601. * @ngdoc method
  1602. * @methodOf ui.grid.gridMenuService
  1603. * @name setMenuItemTitle
  1604. * @description Handles the response from gridMenuTitleFilter, adding it directly to the menu
  1605. * item if it returns a string, otherwise waiting for the promise to resolve or reject then
  1606. * putting the result into the title
  1607. * @param {object} menuItem the menuItem we want to put the title on
  1608. * @param {object} colDef the colDef from which we can get displayName, name or field
  1609. * @param {Grid} grid the grid, from which we can get the options.gridMenuTitleFilter
  1610. *
  1611. */
  1612. setMenuItemTitle: function( menuItem, colDef, grid ){
  1613. var title = grid.options.gridMenuTitleFilter( colDef.displayName || gridUtil.readableColumnName(colDef.name) || colDef.field );
  1614. if ( typeof(title) === 'string' ){
  1615. menuItem.title = title;
  1616. } else if ( title.then ){
  1617. // must be a promise
  1618. menuItem.title = "";
  1619. title.then( function( successValue ) {
  1620. menuItem.title = successValue;
  1621. }, function( errorValue ) {
  1622. menuItem.title = errorValue;
  1623. });
  1624. } else {
  1625. gridUtil.logError('Expected gridMenuTitleFilter to return a string or a promise, it has returned neither, bad config');
  1626. menuItem.title = 'badconfig';
  1627. }
  1628. },
  1629. /**
  1630. * @ngdoc method
  1631. * @methodOf ui.grid.gridMenuService
  1632. * @name toggleColumnVisibility
  1633. * @description Toggles the visibility of an individual column. Expects to be
  1634. * provided a context that has on it a gridColumn, which is the column that
  1635. * we'll operate upon. We change the visibility, and refresh the grid as appropriate
  1636. * @param {GridCol} gridCol the column that we want to toggle
  1637. *
  1638. */
  1639. toggleColumnVisibility: function( gridCol ) {
  1640. gridCol.colDef.visible = !( gridCol.colDef.visible === true || gridCol.colDef.visible === undefined );
  1641. gridCol.grid.refresh();
  1642. gridCol.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
  1643. gridCol.grid.api.core.raise.columnVisibilityChanged( gridCol );
  1644. }
  1645. };
  1646. return service;
  1647. }])
  1648. .directive('uiGridMenuButton', ['gridUtil', 'uiGridConstants', 'uiGridGridMenuService', 'i18nService',
  1649. function (gridUtil, uiGridConstants, uiGridGridMenuService, i18nService) {
  1650. return {
  1651. priority: 0,
  1652. scope: true,
  1653. require: ['^uiGrid'],
  1654. templateUrl: 'ui-grid/ui-grid-menu-button',
  1655. replace: true,
  1656. link: function ($scope, $elm, $attrs, controllers) {
  1657. var uiGridCtrl = controllers[0];
  1658. // For the aria label
  1659. $scope.i18n = {
  1660. aria: i18nService.getSafeText('gridMenu.aria')
  1661. };
  1662. uiGridGridMenuService.initialize($scope, uiGridCtrl.grid);
  1663. $scope.shown = false;
  1664. // $scope.decrement = function () {
  1665. // if ( $scope.shown ){
  1666. // $scope.$broadcast('hide-menu');
  1667. // $scope.shown = false;
  1668. // } else {
  1669. // console.log($scope.menuItems)
  1670. // // $scope.menuItems = uiGridGridMenuService.getMenuItems( $scope );
  1671. // $scope.$broadcast('show-menu');
  1672. // $scope.shown = true;
  1673. // }
  1674. // };
  1675. $scope.toggleMenu = function () {
  1676. if ( $scope.shown ){
  1677. $scope.$broadcast('hide-menu');
  1678. $scope.shown = false;
  1679. } else {
  1680. $scope.menuItems = uiGridGridMenuService.getMenuItems( $scope );
  1681. $scope.$broadcast('show-menu');
  1682. $scope.shown = true;
  1683. }
  1684. };
  1685. $scope.$on('menu-hidden', function() {
  1686. $scope.shown = false;
  1687. gridUtil.focus.bySelector($elm, '.ui-grid-icon-container');
  1688. });
  1689. }
  1690. };
  1691. }]);
  1692. })();
  1693. (function(){
  1694. /**
  1695. * @ngdoc directive
  1696. * @name ui.grid.directive:uiGridMenu
  1697. * @element style
  1698. * @restrict A
  1699. *
  1700. * @description
  1701. * Allows us to interpolate expressions in `<style>` elements. Angular doesn't do this by default as it can/will/might? break in IE8.
  1702. *
  1703. * @example
  1704. <doc:example module="app">
  1705. <doc:source>
  1706. <script>
  1707. var app = angular.module('app', ['ui.grid']);
  1708. app.controller('MainCtrl', ['$scope', function ($scope) {
  1709. }]);
  1710. </script>
  1711. <div ng-controller="MainCtrl">
  1712. <div ui-grid-menu shown="true" ></div>
  1713. </div>
  1714. </doc:source>
  1715. <doc:scenario>
  1716. </doc:scenario>
  1717. </doc:example>
  1718. */
  1719. angular.module('ui.grid')
  1720. .directive('uiGridMenu', ['$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', 'i18nService',
  1721. function ($compile, $timeout, $window, $document, gridUtil, uiGridConstants, i18nService) {
  1722. var uiGridMenu = {
  1723. priority: 0,
  1724. scope: {
  1725. // shown: '&',
  1726. menuItems: '=',
  1727. autoHide: '=?'
  1728. },
  1729. require: '?^uiGrid',
  1730. templateUrl: 'ui-grid/uiGridMenu',
  1731. replace: false,
  1732. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  1733. var self = this;
  1734. var menuMid;
  1735. var $animate;
  1736. $scope.i18n = {
  1737. close: i18nService.getSafeText('columnMenu.close')
  1738. };
  1739. // *** Show/Hide functions ******
  1740. self.showMenu = $scope.showMenu = function(event, args) {
  1741. if ( !$scope.shown ){
  1742. /*
  1743. * In order to animate cleanly we remove the ng-if, wait a digest cycle, then
  1744. * animate the removal of the ng-hide. We can't successfully (so far as I can tell)
  1745. * animate removal of the ng-if, as the menu items aren't there yet. And we don't want
  1746. * to rely on ng-show only, as that leaves elements in the DOM that are needlessly evaluated
  1747. * on scroll events.
  1748. *
  1749. * Note when testing animation that animations don't run on the tutorials. When debugging it looks
  1750. * like they do, but angular has a default $animate provider that is just a stub, and that's what's
  1751. * being called. ALso don't be fooled by the fact that your browser has actually loaded the
  1752. * angular-translate.js, it's not using it. You need to test animations in an external application.
  1753. */
  1754. $scope.shown = true;
  1755. $timeout( function() {
  1756. $scope.shownMid = true;
  1757. $scope.$emit('menu-shown');
  1758. });
  1759. } else if ( !$scope.shownMid ) {
  1760. // we're probably doing a hide then show, so we don't need to wait for ng-if
  1761. $scope.shownMid = true;
  1762. $scope.$emit('menu-shown');
  1763. }
  1764. var docEventType = 'click';
  1765. if (args && args.originalEvent && args.originalEvent.type && args.originalEvent.type === 'touchstart') {
  1766. docEventType = args.originalEvent.type;
  1767. }
  1768. // Turn off an existing document click handler
  1769. angular.element(document).off('click touchstart', applyHideMenu);
  1770. // Turn on the document click handler, but in a timeout so it doesn't apply to THIS click if there is one
  1771. $timeout(function() {
  1772. angular.element(document).on(docEventType, applyHideMenu);
  1773. });
  1774. //automatically set the focus to the first button element in the now open menu.
  1775. gridUtil.focus.bySelector($elm, 'button[type=button]', true);
  1776. };
  1777. self.hideMenu = $scope.hideMenu = function(event, args) {
  1778. if ( $scope.shown ){
  1779. /*
  1780. * In order to animate cleanly we animate the addition of ng-hide, then use a $timeout to
  1781. * set the ng-if (shown = false) after the animation runs. In theory we can cascade off the
  1782. * callback on the addClass method, but it is very unreliable with unit tests for no discernable reason.
  1783. *
  1784. * The user may have clicked on the menu again whilst
  1785. * we're waiting, so we check that the mid isn't shown before applying the ng-if.
  1786. */
  1787. $scope.shownMid = false;
  1788. $timeout( function() {
  1789. if ( !$scope.shownMid ){
  1790. $scope.shown = false;
  1791. $scope.$emit('menu-hidden');
  1792. }
  1793. }, 200);
  1794. }
  1795. angular.element(document).off('click touchstart', applyHideMenu);
  1796. };
  1797. $scope.$on('hide-menu', function (event, args) {
  1798. $scope.hideMenu(event, args);
  1799. });
  1800. $scope.$on('show-menu', function (event, args) {
  1801. $scope.showMenu(event, args);
  1802. });
  1803. // *** Auto hide when click elsewhere ******
  1804. var applyHideMenu = function(){
  1805. if ($scope.shown) {
  1806. $scope.$apply(function () {
  1807. $scope.hideMenu();
  1808. });
  1809. }
  1810. };
  1811. if (typeof($scope.autoHide) === 'undefined' || $scope.autoHide === undefined) {
  1812. $scope.autoHide = true;
  1813. }
  1814. if ($scope.autoHide) {
  1815. angular.element($window).on('resize', applyHideMenu);
  1816. }
  1817. $scope.$on('$destroy', function () {
  1818. angular.element(document).off('click touchstart', applyHideMenu);
  1819. });
  1820. $scope.$on('$destroy', function() {
  1821. angular.element($window).off('resize', applyHideMenu);
  1822. });
  1823. if (uiGridCtrl) {
  1824. $scope.$on('$destroy', uiGridCtrl.grid.api.core.on.scrollBegin($scope, applyHideMenu ));
  1825. }
  1826. $scope.$on('$destroy', $scope.$on(uiGridConstants.events.ITEM_DRAGGING, applyHideMenu ));
  1827. },
  1828. controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
  1829. var self = this;
  1830. }]
  1831. };
  1832. return uiGridMenu;
  1833. }])
  1834. .directive('uiGridMenuItem', ['gridUtil', '$compile', 'i18nService', function (gridUtil, $compile, i18nService) {
  1835. var uiGridMenuItem = {
  1836. priority: 0,
  1837. scope: {
  1838. name: '=',
  1839. active: '=',
  1840. action: '=',
  1841. icon: '=',
  1842. shown: '=',
  1843. context: '=',
  1844. templateUrl: '=',
  1845. leaveOpen: '=',
  1846. screenReaderOnly: '='
  1847. },
  1848. require: ['?^uiGrid', '^uiGridMenu'],
  1849. templateUrl: 'ui-grid/uiGridMenuItem',
  1850. replace: false,
  1851. compile: function($elm, $attrs) {
  1852. return {
  1853. pre: function ($scope, $elm, $attrs, controllers) {
  1854. var uiGridCtrl = controllers[0],
  1855. uiGridMenuCtrl = controllers[1];
  1856. if ($scope.templateUrl) {
  1857. gridUtil.getTemplate($scope.templateUrl)
  1858. .then(function (contents) {
  1859. var template = angular.element(contents);
  1860. var newElm = $compile(template)($scope);
  1861. $elm.replaceWith(newElm);
  1862. });
  1863. }
  1864. },
  1865. post: function ($scope, $elm, $attrs, controllers) {
  1866. var uiGridCtrl = controllers[0],
  1867. uiGridMenuCtrl = controllers[1];
  1868. // TODO(c0bra): validate that shown and active are functions if they're defined. An exception is already thrown above this though
  1869. // if (typeof($scope.shown) !== 'undefined' && $scope.shown && typeof($scope.shown) !== 'function') {
  1870. // throw new TypeError("$scope.shown is defined but not a function");
  1871. // }
  1872. if (typeof($scope.shown) === 'undefined' || $scope.shown === null) {
  1873. $scope.shown = function() { return true; };
  1874. }
  1875. $scope.itemShown = function () {
  1876. var context = {};
  1877. if ($scope.context) {
  1878. context.context = $scope.context;
  1879. }
  1880. if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) {
  1881. context.grid = uiGridCtrl.grid;
  1882. }
  1883. return $scope.shown.call(context);
  1884. };
  1885. $scope.itemAction = function($event,title) {
  1886. gridUtil.logDebug('itemAction');
  1887. $event.stopPropagation();
  1888. if (typeof($scope.action) === 'function') {
  1889. var context = {};
  1890. if ($scope.context) {
  1891. context.context = $scope.context;
  1892. }
  1893. // Add the grid to the function call context if the uiGrid controller is present
  1894. if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) {
  1895. context.grid = uiGridCtrl.grid;
  1896. }
  1897. $scope.action.call(context, $event, title);
  1898. if ( !$scope.leaveOpen ){
  1899. $scope.$emit('hide-menu');
  1900. } else {
  1901. /*
  1902. * XXX: Fix after column refactor
  1903. * Ideally the focus would remain on the item.
  1904. * However, since there are two menu items that have their 'show' property toggled instead. This is a quick fix.
  1905. */
  1906. gridUtil.focus.bySelector(angular.element(gridUtil.closestElm($elm, ".ui-grid-menu-items")), 'button[type=button]', true);
  1907. }
  1908. }
  1909. };
  1910. $scope.i18n = i18nService.get();
  1911. }
  1912. };
  1913. }
  1914. };
  1915. return uiGridMenuItem;
  1916. }]);
  1917. })();
  1918. (function(){
  1919. 'use strict';
  1920. /**
  1921. * @ngdoc overview
  1922. * @name ui.grid.directive:uiGridOneBind
  1923. * @summary A group of directives that provide a one time bind to a dom element.
  1924. * @description A group of directives that provide a one time bind to a dom element.
  1925. * As one time bindings are not supported in Angular 1.2.* this directive provdes this capability.
  1926. * This is done to reduce the number of watchers on the dom.
  1927. * <br/>
  1928. * <h2>Short Example ({@link ui.grid.directive:uiGridOneBindSrc ui-grid-one-bind-src})</h2>
  1929. * <pre>
  1930. <div ng-init="imageName = 'myImageDir.jpg'">
  1931. <img ui-grid-one-bind-src="imageName"></img>
  1932. </div>
  1933. </pre>
  1934. * Will become:
  1935. * <pre>
  1936. <div ng-init="imageName = 'myImageDir.jpg'">
  1937. <img ui-grid-one-bind-src="imageName" src="myImageDir.jpg"></img>
  1938. </div>
  1939. </pre>
  1940. </br>
  1941. <h2>Short Example ({@link ui.grid.directive:uiGridOneBindText ui-grid-one-bind-text})</h2>
  1942. * <pre>
  1943. <div ng-init="text='Add this text'" ui-grid-one-bind-text="text"></div>
  1944. </pre>
  1945. * Will become:
  1946. * <pre>
  1947. <div ng-init="text='Add this text'" ui-grid-one-bind-text="text">Add this text</div>
  1948. </pre>
  1949. </br>
  1950. * <b>Note:</b> This behavior is slightly different for the {@link ui.grid.directive:uiGridOneBindIdGrid uiGridOneBindIdGrid}
  1951. * and {@link ui.grid.directive:uiGridOneBindAriaLabelledbyGrid uiGridOneBindAriaLabelledbyGrid} directives.
  1952. *
  1953. */
  1954. //https://github.com/joshkurz/Black-Belt-AngularJS-Directives/blob/master/directives/Optimization/oneBind.js
  1955. var oneBinders = angular.module('ui.grid');
  1956. angular.forEach([
  1957. /**
  1958. * @ngdoc directive
  1959. * @name ui.grid.directive:uiGridOneBindSrc
  1960. * @memberof ui.grid.directive:uiGridOneBind
  1961. * @element img
  1962. * @restrict A
  1963. * @param {String} uiGridOneBindSrc The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  1964. * @description One time binding for the src dom tag.
  1965. *
  1966. */
  1967. {tag: 'Src', method: 'attr'},
  1968. /**
  1969. * @ngdoc directive
  1970. * @name ui.grid.directive:uiGridOneBindText
  1971. * @element div
  1972. * @restrict A
  1973. * @param {String} uiGridOneBindText The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  1974. * @description One time binding for the text dom tag.
  1975. */
  1976. {tag: 'Text', method: 'text'},
  1977. /**
  1978. * @ngdoc directive
  1979. * @name ui.grid.directive:uiGridOneBindHref
  1980. * @element div
  1981. * @restrict A
  1982. * @param {String} uiGridOneBindHref The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  1983. * @description One time binding for the href dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  1984. */
  1985. {tag: 'Href', method: 'attr'},
  1986. /**
  1987. * @ngdoc directive
  1988. * @name ui.grid.directive:uiGridOneBindClass
  1989. * @element div
  1990. * @restrict A
  1991. * @param {String} uiGridOneBindClass The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  1992. * @param {Object} uiGridOneBindClass The object that you want to bind. At least one of the values in the object must be something other than null or undefined for the watcher to be removed.
  1993. * this is to prevent the watcher from being removed before the scope is initialized.
  1994. * @param {Array} uiGridOneBindClass An array of classes to bind to this element.
  1995. * @description One time binding for the class dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  1996. */
  1997. {tag: 'Class', method: 'addClass'},
  1998. /**
  1999. * @ngdoc directive
  2000. * @name ui.grid.directive:uiGridOneBindHtml
  2001. * @element div
  2002. * @restrict A
  2003. * @param {String} uiGridOneBindHtml The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2004. * @description One time binding for the html method on a dom element. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2005. */
  2006. {tag: 'Html', method: 'html'},
  2007. /**
  2008. * @ngdoc directive
  2009. * @name ui.grid.directive:uiGridOneBindAlt
  2010. * @element div
  2011. * @restrict A
  2012. * @param {String} uiGridOneBindAlt The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2013. * @description One time binding for the alt dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2014. */
  2015. {tag: 'Alt', method: 'attr'},
  2016. /**
  2017. * @ngdoc directive
  2018. * @name ui.grid.directive:uiGridOneBindStyle
  2019. * @element div
  2020. * @restrict A
  2021. * @param {String} uiGridOneBindStyle The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2022. * @description One time binding for the style dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2023. */
  2024. {tag: 'Style', method: 'css'},
  2025. /**
  2026. * @ngdoc directive
  2027. * @name ui.grid.directive:uiGridOneBindValue
  2028. * @element div
  2029. * @restrict A
  2030. * @param {String} uiGridOneBindValue The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2031. * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2032. */
  2033. {tag: 'Value', method: 'attr'},
  2034. /**
  2035. * @ngdoc directive
  2036. * @name ui.grid.directive:uiGridOneBindId
  2037. * @element div
  2038. * @restrict A
  2039. * @param {String} uiGridOneBindId The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2040. * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2041. */
  2042. {tag: 'Id', method: 'attr'},
  2043. /**
  2044. * @ngdoc directive
  2045. * @name ui.grid.directive:uiGridOneBindIdGrid
  2046. * @element div
  2047. * @restrict A
  2048. * @param {String} uiGridOneBindIdGrid The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2049. * @description One time binding for the id dom tag.
  2050. * <h1>Important Note!</h1>
  2051. * If the id tag passed as a parameter does <b>not</b> contain the grid id as a substring
  2052. * then the directive will search the scope and the parent controller (if it is a uiGridController) for the grid.id value.
  2053. * If this value is found then it is appended to the begining of the id tag. If the grid is not found then the directive throws an error.
  2054. * This is done in order to ensure uniqueness of id tags across the grid.
  2055. * This is to prevent two grids in the same document having duplicate id tags.
  2056. */
  2057. {tag: 'Id', directiveName:'IdGrid', method: 'attr', appendGridId: true},
  2058. /**
  2059. * @ngdoc directive
  2060. * @name ui.grid.directive:uiGridOneBindTitle
  2061. * @element div
  2062. * @restrict A
  2063. * @param {String} uiGridOneBindTitle The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2064. * @description One time binding for the title dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2065. */
  2066. {tag: 'Title', method: 'attr'},
  2067. /**
  2068. * @ngdoc directive
  2069. * @name ui.grid.directive:uiGridOneBindAriaLabel
  2070. * @element div
  2071. * @restrict A
  2072. * @param {String} uiGridOneBindAriaLabel The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2073. * @description One time binding for the aria-label dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2074. *<br/>
  2075. * <pre>
  2076. <div ng-init="text='Add this text'" ui-grid-one-bind-aria-label="text"></div>
  2077. </pre>
  2078. * Will become:
  2079. * <pre>
  2080. <div ng-init="text='Add this text'" ui-grid-one-bind-aria-label="text" aria-label="Add this text"></div>
  2081. </pre>
  2082. */
  2083. {tag: 'Label', method: 'attr', aria:true},
  2084. /**
  2085. * @ngdoc directive
  2086. * @name ui.grid.directive:uiGridOneBindAriaLabelledby
  2087. * @element div
  2088. * @restrict A
  2089. * @param {String} uiGridOneBindAriaLabelledby The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2090. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2091. *<br/>
  2092. * <pre>
  2093. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby="anId"></div>
  2094. </pre>
  2095. * Will become:
  2096. * <pre>
  2097. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby="anId" aria-labelledby="gridID32"></div>
  2098. </pre>
  2099. */
  2100. {tag: 'Labelledby', method: 'attr', aria:true},
  2101. /**
  2102. * @ngdoc directive
  2103. * @name ui.grid.directive:uiGridOneBindAriaLabelledbyGrid
  2104. * @element div
  2105. * @restrict A
  2106. * @param {String} uiGridOneBindAriaLabelledbyGrid The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2107. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2108. * Works somewhat like {@link ui.grid.directive:uiGridOneBindIdGrid} however this one supports a list of ids (seperated by a space) and will dynamically add the
  2109. * grid id to each one.
  2110. *<br/>
  2111. * <pre>
  2112. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby-grid="anId"></div>
  2113. </pre>
  2114. * Will become ([grid.id] will be replaced by the actual grid id):
  2115. * <pre>
  2116. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby-grid="anId" aria-labelledby-Grid="[grid.id]-gridID32"></div>
  2117. </pre>
  2118. */
  2119. {tag: 'Labelledby', directiveName:'LabelledbyGrid', appendGridId:true, method: 'attr', aria:true},
  2120. /**
  2121. * @ngdoc directive
  2122. * @name ui.grid.directive:uiGridOneBindAriaDescribedby
  2123. * @element ANY
  2124. * @restrict A
  2125. * @param {String} uiGridOneBindAriaDescribedby The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2126. * @description One time binding for the aria-describedby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2127. *<br/>
  2128. * <pre>
  2129. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby="anId"></div>
  2130. </pre>
  2131. * Will become:
  2132. * <pre>
  2133. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby="anId" aria-describedby="gridID32"></div>
  2134. </pre>
  2135. */
  2136. {tag: 'Describedby', method: 'attr', aria:true},
  2137. /**
  2138. * @ngdoc directive
  2139. * @name ui.grid.directive:uiGridOneBindAriaDescribedbyGrid
  2140. * @element ANY
  2141. * @restrict A
  2142. * @param {String} uiGridOneBindAriaDescribedbyGrid The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>.
  2143. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2144. * Works somewhat like {@link ui.grid.directive:uiGridOneBindIdGrid} however this one supports a list of ids (seperated by a space) and will dynamically add the
  2145. * grid id to each one.
  2146. *<br/>
  2147. * <pre>
  2148. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby-grid="anId"></div>
  2149. </pre>
  2150. * Will become ([grid.id] will be replaced by the actual grid id):
  2151. * <pre>
  2152. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby-grid="anId" aria-describedby="[grid.id]-gridID32"></div>
  2153. </pre>
  2154. */
  2155. {tag: 'Describedby', directiveName:'DescribedbyGrid', appendGridId:true, method: 'attr', aria:true}],
  2156. function(v){
  2157. var baseDirectiveName = 'uiGridOneBind';
  2158. //If it is an aria tag then append the aria label seperately
  2159. //This is done because the aria tags are formatted aria-* and the directive name can't have a '-' character in it.
  2160. //If the diretiveName has to be overridden then it does so here. This is because the tag being modified and the directive sometimes don't match up.
  2161. var directiveName = (v.aria ? baseDirectiveName + 'Aria' : baseDirectiveName) + (v.directiveName ? v.directiveName : v.tag);
  2162. oneBinders.directive(directiveName, ['gridUtil', function(gridUtil){
  2163. return {
  2164. restrict: 'A',
  2165. require: ['?uiGrid','?^uiGrid'],
  2166. link: function(scope, iElement, iAttrs, controllers){
  2167. /* Appends the grid id to the beginnig of the value. */
  2168. var appendGridId = function(val){
  2169. var grid; //Get an instance of the grid if its available
  2170. //If its available in the scope then we don't need to try to find it elsewhere
  2171. if (scope.grid) {
  2172. grid = scope.grid;
  2173. }
  2174. //Another possible location to try to find the grid
  2175. else if (scope.col && scope.col.grid){
  2176. grid = scope.col.grid;
  2177. }
  2178. //Last ditch effort: Search through the provided controllers.
  2179. else if (!controllers.some( //Go through the controllers till one has the element we need
  2180. function(controller){
  2181. if (controller && controller.grid) {
  2182. grid = controller.grid;
  2183. return true; //We've found the grid
  2184. }
  2185. })){
  2186. //We tried our best to find it for you
  2187. gridUtil.logError("["+directiveName+"] A valid grid could not be found to bind id. Are you using this directive " +
  2188. "within the correct scope? Trying to generate id: [gridID]-" + val);
  2189. throw new Error("No valid grid could be found");
  2190. }
  2191. if (grid){
  2192. var idRegex = new RegExp(grid.id.toString());
  2193. //If the grid id hasn't been appended already in the template declaration
  2194. if (!idRegex.test(val)){
  2195. val = grid.id.toString() + '-' + val;
  2196. }
  2197. }
  2198. return val;
  2199. };
  2200. // The watch returns a function to remove itself.
  2201. var rmWatcher = scope.$watch(iAttrs[directiveName], function(newV){
  2202. if (newV){
  2203. //If we are trying to add an id element then we also apply the grid id if it isn't already there
  2204. if (v.appendGridId) {
  2205. var newIdString = null;
  2206. //Append the id to all of the new ids.
  2207. angular.forEach( newV.split(' '), function(s){
  2208. newIdString = (newIdString ? (newIdString + ' ') : '') + appendGridId(s);
  2209. });
  2210. newV = newIdString;
  2211. }
  2212. // Append this newValue to the dom element.
  2213. switch (v.method) {
  2214. case 'attr': //The attr method takes two paraams the tag and the value
  2215. if (v.aria) {
  2216. //If it is an aria element then append the aria prefix
  2217. iElement[v.method]('aria-' + v.tag.toLowerCase(),newV);
  2218. } else {
  2219. iElement[v.method](v.tag.toLowerCase(),newV);
  2220. }
  2221. break;
  2222. case 'addClass':
  2223. //Pulled from https://github.com/Pasvaz/bindonce/blob/master/bindonce.js
  2224. if (angular.isObject(newV) && !angular.isArray(newV)) {
  2225. var results = [];
  2226. var nonNullFound = false; //We don't want to remove the binding unless the key is actually defined
  2227. angular.forEach(newV, function (value, index) {
  2228. if (value !== null && typeof(value) !== "undefined"){
  2229. nonNullFound = true; //A non null value for a key was found so the object must have been initialized
  2230. if (value) {results.push(index);}
  2231. }
  2232. });
  2233. //A non null value for a key wasn't found so assume that the scope values haven't been fully initialized
  2234. if (!nonNullFound){
  2235. return; // If not initialized then the watcher should not be removed yet.
  2236. }
  2237. newV = results;
  2238. }
  2239. if (newV) {
  2240. iElement.addClass(angular.isArray(newV) ? newV.join(' ') : newV);
  2241. } else {
  2242. return;
  2243. }
  2244. break;
  2245. default:
  2246. iElement[v.method](newV);
  2247. break;
  2248. }
  2249. //Removes the watcher on itself after the bind
  2250. rmWatcher();
  2251. }
  2252. // True ensures that equality is determined using angular.equals instead of ===
  2253. }, true); //End rm watchers
  2254. } //End compile function
  2255. }; //End directive return
  2256. } // End directive function
  2257. ]); //End directive
  2258. }); // End angular foreach
  2259. })();
  2260. (function () {
  2261. 'use strict';
  2262. var module = angular.module('ui.grid');
  2263. module.directive('uiGridRenderContainer', ['$timeout', '$document', 'uiGridConstants', 'gridUtil', 'ScrollEvent',
  2264. function($timeout, $document, uiGridConstants, gridUtil, ScrollEvent) {
  2265. return {
  2266. replace: true,
  2267. transclude: true,
  2268. templateUrl: 'ui-grid/uiGridRenderContainer',
  2269. require: ['^uiGrid', 'uiGridRenderContainer'],
  2270. scope: {
  2271. containerId: '=',
  2272. rowContainerName: '=',
  2273. colContainerName: '=',
  2274. bindScrollHorizontal: '=',
  2275. bindScrollVertical: '=',
  2276. enableVerticalScrollbar: '=',
  2277. enableHorizontalScrollbar: '='
  2278. },
  2279. controller: 'uiGridRenderContainer as RenderContainer',
  2280. compile: function () {
  2281. return {
  2282. pre: function prelink($scope, $elm, $attrs, controllers) {
  2283. var uiGridCtrl = controllers[0];
  2284. var containerCtrl = controllers[1];
  2285. var grid = $scope.grid = uiGridCtrl.grid;
  2286. // Verify that the render container for this element exists
  2287. if (!$scope.rowContainerName) {
  2288. throw "No row render container name specified";
  2289. }
  2290. if (!$scope.colContainerName) {
  2291. throw "No column render container name specified";
  2292. }
  2293. if (!grid.renderContainers[$scope.rowContainerName]) {
  2294. throw "Row render container '" + $scope.rowContainerName + "' is not registered.";
  2295. }
  2296. if (!grid.renderContainers[$scope.colContainerName]) {
  2297. throw "Column render container '" + $scope.colContainerName + "' is not registered.";
  2298. }
  2299. var rowContainer = $scope.rowContainer = grid.renderContainers[$scope.rowContainerName];
  2300. var colContainer = $scope.colContainer = grid.renderContainers[$scope.colContainerName];
  2301. containerCtrl.containerId = $scope.containerId;
  2302. containerCtrl.rowContainer = rowContainer;
  2303. containerCtrl.colContainer = colContainer;
  2304. },
  2305. post: function postlink($scope, $elm, $attrs, controllers) {
  2306. var uiGridCtrl = controllers[0];
  2307. var containerCtrl = controllers[1];
  2308. var grid = uiGridCtrl.grid;
  2309. var rowContainer = containerCtrl.rowContainer;
  2310. var colContainer = containerCtrl.colContainer;
  2311. var scrollTop = null;
  2312. var scrollLeft = null;
  2313. var renderContainer = grid.renderContainers[$scope.containerId];
  2314. // Put the container name on this element as a class
  2315. $elm.addClass('ui-grid-render-container-' + $scope.containerId);
  2316. // Scroll the render container viewport when the mousewheel is used
  2317. gridUtil.on.mousewheel($elm, function (event) {
  2318. var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.RenderContainerMouseWheel);
  2319. if (event.deltaY !== 0) {
  2320. var scrollYAmount = event.deltaY * -1 * event.deltaFactor;
  2321. scrollTop = containerCtrl.viewport[0].scrollTop;
  2322. // Get the scroll percentage
  2323. scrollEvent.verticalScrollLength = rowContainer.getVerticalScrollLength();
  2324. var scrollYPercentage = (scrollTop + scrollYAmount) / scrollEvent.verticalScrollLength;
  2325. // If we should be scrolled 100%, make sure the scrollTop matches the maximum scroll length
  2326. // Viewports that have "overflow: hidden" don't let the mousewheel scroll all the way to the bottom without this check
  2327. if (scrollYPercentage >= 1 && scrollTop < scrollEvent.verticalScrollLength) {
  2328. containerCtrl.viewport[0].scrollTop = scrollEvent.verticalScrollLength;
  2329. }
  2330. // Keep scrollPercentage within the range 0-1.
  2331. if (scrollYPercentage < 0) { scrollYPercentage = 0; }
  2332. else if (scrollYPercentage > 1) { scrollYPercentage = 1; }
  2333. scrollEvent.y = { percentage: scrollYPercentage, pixels: scrollYAmount };
  2334. }
  2335. if (event.deltaX !== 0) {
  2336. var scrollXAmount = event.deltaX * event.deltaFactor;
  2337. // Get the scroll percentage
  2338. scrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.viewport, grid);
  2339. scrollEvent.horizontalScrollLength = (colContainer.getCanvasWidth() - colContainer.getViewportWidth());
  2340. var scrollXPercentage = (scrollLeft + scrollXAmount) / scrollEvent.horizontalScrollLength;
  2341. // Keep scrollPercentage within the range 0-1.
  2342. if (scrollXPercentage < 0) { scrollXPercentage = 0; }
  2343. else if (scrollXPercentage > 1) { scrollXPercentage = 1; }
  2344. scrollEvent.x = { percentage: scrollXPercentage, pixels: scrollXAmount };
  2345. }
  2346. // Let the parent container scroll if the grid is already at the top/bottom
  2347. if ((event.deltaY !== 0 && (scrollEvent.atTop(scrollTop) || scrollEvent.atBottom(scrollTop))) ||
  2348. (event.deltaX !== 0 && (scrollEvent.atLeft(scrollLeft) || scrollEvent.atRight(scrollLeft)))) {
  2349. //parent controller scrolls
  2350. }
  2351. else {
  2352. event.preventDefault();
  2353. event.stopPropagation();
  2354. scrollEvent.fireThrottledScrollingEvent('', scrollEvent);
  2355. }
  2356. });
  2357. $elm.bind('$destroy', function() {
  2358. $elm.unbind('keydown');
  2359. ['touchstart', 'touchmove', 'touchend','keydown', 'wheel', 'mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'].forEach(function (eventName) {
  2360. $elm.unbind(eventName);
  2361. });
  2362. });
  2363. // TODO(c0bra): Handle resizing the inner canvas based on the number of elements
  2364. function update() {
  2365. var ret = '';
  2366. var canvasWidth = colContainer.canvasWidth;
  2367. var viewportWidth = colContainer.getViewportWidth();
  2368. var canvasHeight = rowContainer.getCanvasHeight();
  2369. //add additional height for scrollbar on left and right container
  2370. //if ($scope.containerId !== 'body') {
  2371. // canvasHeight -= grid.scrollbarHeight;
  2372. //}
  2373. var viewportHeight = rowContainer.getViewportHeight();
  2374. //shorten the height to make room for a scrollbar placeholder
  2375. if (colContainer.needsHScrollbarPlaceholder()) {
  2376. viewportHeight -= grid.scrollbarHeight;
  2377. }
  2378. var headerViewportWidth,
  2379. footerViewportWidth;
  2380. headerViewportWidth = footerViewportWidth = colContainer.getHeaderViewportWidth();
  2381. // Set canvas dimensions
  2382. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-canvas { width: ' + canvasWidth + 'px; height: ' + canvasHeight + 'px; }';
  2383. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }';
  2384. if (renderContainer.explicitHeaderCanvasHeight) {
  2385. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: ' + renderContainer.explicitHeaderCanvasHeight + 'px; }';
  2386. }
  2387. else {
  2388. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: inherit; }';
  2389. }
  2390. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-viewport { width: ' + viewportWidth + 'px; height: ' + viewportHeight + 'px; }';
  2391. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-viewport { width: ' + headerViewportWidth + 'px; }';
  2392. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-footer-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }';
  2393. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-footer-viewport { width: ' + footerViewportWidth + 'px; }';
  2394. return ret;
  2395. }
  2396. uiGridCtrl.grid.registerStyleComputation({
  2397. priority: 6,
  2398. func: update
  2399. });
  2400. }
  2401. };
  2402. }
  2403. };
  2404. }]);
  2405. module.controller('uiGridRenderContainer', ['$scope', 'gridUtil', function ($scope, gridUtil) {
  2406. }]);
  2407. })();
  2408. (function(){
  2409. 'use strict';
  2410. angular.module('ui.grid').directive('uiGridRow', ['gridUtil', function(gridUtil) {
  2411. return {
  2412. replace: true,
  2413. // priority: 2001,
  2414. // templateUrl: 'ui-grid/ui-grid-row',
  2415. require: ['^uiGrid', '^uiGridRenderContainer'],
  2416. scope: {
  2417. row: '=uiGridRow',
  2418. //rowRenderIndex is added to scope to give the true visual index of the row to any directives that need it
  2419. rowRenderIndex: '='
  2420. },
  2421. compile: function() {
  2422. return {
  2423. pre: function($scope, $elm, $attrs, controllers) {
  2424. var uiGridCtrl = controllers[0];
  2425. var containerCtrl = controllers[1];
  2426. var grid = uiGridCtrl.grid;
  2427. $scope.grid = uiGridCtrl.grid;
  2428. $scope.colContainer = containerCtrl.colContainer;
  2429. // Function for attaching the template to this scope
  2430. var clonedElement, cloneScope;
  2431. function compileTemplate() {
  2432. $scope.row.getRowTemplateFn.then(function (compiledElementFn) {
  2433. // var compiledElementFn = $scope.row.compiledElementFn;
  2434. // Create a new scope for the contents of this row, so we can destroy it later if need be
  2435. var newScope = $scope.$new();
  2436. compiledElementFn(newScope, function (newElm, scope) {
  2437. // If we already have a cloned element, we need to remove it and destroy its scope
  2438. if (clonedElement) {
  2439. clonedElement.remove();
  2440. cloneScope.$destroy();
  2441. }
  2442. // Empty the row and append the new element
  2443. $elm.empty().append(newElm);
  2444. // Save the new cloned element and scope
  2445. clonedElement = newElm;
  2446. cloneScope = newScope;
  2447. });
  2448. });
  2449. }
  2450. // Initially attach the compiled template to this scope
  2451. compileTemplate();
  2452. // If the row's compiled element function changes, we need to replace this element's contents with the new compiled template
  2453. $scope.$watch('row.getRowTemplateFn', function (newFunc, oldFunc) {
  2454. if (newFunc !== oldFunc) {
  2455. compileTemplate();
  2456. }
  2457. });
  2458. },
  2459. post: function($scope, $elm, $attrs, controllers) {
  2460. }
  2461. };
  2462. }
  2463. };
  2464. }]);
  2465. })();
  2466. (function(){
  2467. // 'use strict';
  2468. /**
  2469. * @ngdoc directive
  2470. * @name ui.grid.directive:uiGridStyle
  2471. * @element style
  2472. * @restrict A
  2473. *
  2474. * @description
  2475. * Allows us to interpolate expressions in `<style>` elements. Angular doesn't do this by default as it can/will/might? break in IE8.
  2476. *
  2477. * @example
  2478. <doc:example module="app">
  2479. <doc:source>
  2480. <script>
  2481. var app = angular.module('app', ['ui.grid']);
  2482. app.controller('MainCtrl', ['$scope', function ($scope) {
  2483. $scope.myStyle = '.blah { border: 1px solid }';
  2484. }]);
  2485. </script>
  2486. <div ng-controller="MainCtrl">
  2487. <style ui-grid-style>{{ myStyle }}</style>
  2488. <span class="blah">I am in a box.</span>
  2489. </div>
  2490. </doc:source>
  2491. <doc:scenario>
  2492. it('should apply the right class to the element', function () {
  2493. element(by.css('.blah')).getCssValue('border-top-width')
  2494. .then(function(c) {
  2495. expect(c).toContain('1px');
  2496. });
  2497. });
  2498. </doc:scenario>
  2499. </doc:example>
  2500. */
  2501. angular.module('ui.grid').directive('uiGridStyle', ['gridUtil', '$interpolate', function(gridUtil, $interpolate) {
  2502. return {
  2503. // restrict: 'A',
  2504. // priority: 1000,
  2505. // require: '?^uiGrid',
  2506. link: function($scope, $elm, $attrs, uiGridCtrl) {
  2507. // gridUtil.logDebug('ui-grid-style link');
  2508. // if (uiGridCtrl === undefined) {
  2509. // gridUtil.logWarn('[ui-grid-style link] uiGridCtrl is undefined!');
  2510. // }
  2511. var interpolateFn = $interpolate($elm.text(), true);
  2512. if (interpolateFn) {
  2513. $scope.$watch(interpolateFn, function(value) {
  2514. $elm.text(value);
  2515. });
  2516. }
  2517. // uiGridCtrl.recalcRowStyles = function() {
  2518. // var offset = (scope.options.offsetTop || 0) - (scope.options.excessRows * scope.options.rowHeight);
  2519. // var rowHeight = scope.options.rowHeight;
  2520. // var ret = '';
  2521. // var rowStyleCount = uiGridCtrl.minRowsToRender() + (scope.options.excessRows * 2);
  2522. // for (var i = 1; i <= rowStyleCount; i++) {
  2523. // ret = ret + ' .grid' + scope.gridId + ' .ui-grid-row:nth-child(' + i + ') { top: ' + offset + 'px; }';
  2524. // offset = offset + rowHeight;
  2525. // }
  2526. // scope.rowStyles = ret;
  2527. // };
  2528. // uiGridCtrl.styleComputions.push(uiGridCtrl.recalcRowStyles);
  2529. }
  2530. };
  2531. }]);
  2532. })();
  2533. (function(){
  2534. 'use strict';
  2535. angular.module('ui.grid').directive('uiGridViewport', ['gridUtil','ScrollEvent','uiGridConstants', '$log',
  2536. function(gridUtil, ScrollEvent, uiGridConstants, $log) {
  2537. return {
  2538. replace: true,
  2539. scope: {},
  2540. controllerAs: 'Viewport',
  2541. templateUrl: 'ui-grid/uiGridViewport',
  2542. require: ['^uiGrid', '^uiGridRenderContainer'],
  2543. link: function($scope, $elm, $attrs, controllers) {
  2544. // gridUtil.logDebug('viewport post-link');
  2545. var uiGridCtrl = controllers[0];
  2546. var containerCtrl = controllers[1];
  2547. $scope.containerCtrl = containerCtrl;
  2548. var rowContainer = containerCtrl.rowContainer;
  2549. var colContainer = containerCtrl.colContainer;
  2550. var grid = uiGridCtrl.grid;
  2551. $scope.grid = uiGridCtrl.grid;
  2552. // Put the containers in scope so we can get rows and columns from them
  2553. $scope.rowContainer = containerCtrl.rowContainer;
  2554. $scope.colContainer = containerCtrl.colContainer;
  2555. // Register this viewport with its container
  2556. containerCtrl.viewport = $elm;
  2557. $elm.on('scroll', scrollHandler);
  2558. var ignoreScroll = false;
  2559. function scrollHandler(evt) {
  2560. //Leaving in this commented code in case it can someday be used
  2561. //It does improve performance, but because the horizontal scroll is normalized,
  2562. // using this code will lead to the column header getting slightly out of line with columns
  2563. //
  2564. //if (ignoreScroll && (grid.isScrollingHorizontally || grid.isScrollingHorizontally)) {
  2565. // //don't ask for scrollTop if we just set it
  2566. // ignoreScroll = false;
  2567. // return;
  2568. //}
  2569. //ignoreScroll = true;
  2570. var newScrollTop = $elm[0].scrollTop;
  2571. var newScrollLeft = gridUtil.normalizeScrollLeft($elm, grid);
  2572. var vertScrollPercentage = rowContainer.scrollVertical(newScrollTop);
  2573. var horizScrollPercentage = colContainer.scrollHorizontal(newScrollLeft);
  2574. var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.ViewPortScroll);
  2575. scrollEvent.newScrollLeft = newScrollLeft;
  2576. scrollEvent.newScrollTop = newScrollTop;
  2577. if ( horizScrollPercentage > -1 ){
  2578. scrollEvent.x = { percentage: horizScrollPercentage };
  2579. }
  2580. if ( vertScrollPercentage > -1 ){
  2581. scrollEvent.y = { percentage: vertScrollPercentage };
  2582. }
  2583. grid.scrollContainers($scope.$parent.containerId, scrollEvent);
  2584. }
  2585. if ($scope.$parent.bindScrollVertical) {
  2586. grid.addVerticalScrollSync($scope.$parent.containerId, syncVerticalScroll);
  2587. }
  2588. if ($scope.$parent.bindScrollHorizontal) {
  2589. grid.addHorizontalScrollSync($scope.$parent.containerId, syncHorizontalScroll);
  2590. grid.addHorizontalScrollSync($scope.$parent.containerId + 'header', syncHorizontalHeader);
  2591. grid.addHorizontalScrollSync($scope.$parent.containerId + 'footer', syncHorizontalFooter);
  2592. }
  2593. function syncVerticalScroll(scrollEvent){
  2594. containerCtrl.prevScrollArgs = scrollEvent;
  2595. var newScrollTop = scrollEvent.getNewScrollTop(rowContainer,containerCtrl.viewport);
  2596. $elm[0].scrollTop = newScrollTop;
  2597. }
  2598. function syncHorizontalScroll(scrollEvent){
  2599. containerCtrl.prevScrollArgs = scrollEvent;
  2600. var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
  2601. $elm[0].scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid);
  2602. }
  2603. function syncHorizontalHeader(scrollEvent){
  2604. var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
  2605. if (containerCtrl.headerViewport) {
  2606. containerCtrl.headerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid);
  2607. }
  2608. }
  2609. function syncHorizontalFooter(scrollEvent){
  2610. var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
  2611. if (containerCtrl.footerViewport) {
  2612. containerCtrl.footerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid);
  2613. }
  2614. }
  2615. },
  2616. controller: ['$scope', function ($scope) {
  2617. this.rowStyle = function (index) {
  2618. var rowContainer = $scope.rowContainer;
  2619. var colContainer = $scope.colContainer;
  2620. var styles = {};
  2621. if (index === 0 && rowContainer.currentTopRow !== 0) {
  2622. // The row offset-top is just the height of the rows above the current top-most row, which are no longer rendered
  2623. var hiddenRowWidth = (rowContainer.currentTopRow) * rowContainer.grid.options.rowHeight;
  2624. // return { 'margin-top': hiddenRowWidth + 'px' };
  2625. styles['margin-top'] = hiddenRowWidth + 'px';
  2626. }
  2627. if (colContainer.currentFirstColumn !== 0) {
  2628. if (colContainer.grid.isRTL()) {
  2629. styles['margin-right'] = colContainer.columnOffset + 'px';
  2630. }
  2631. else {
  2632. styles['margin-left'] = colContainer.columnOffset + 'px';
  2633. }
  2634. }
  2635. return styles;
  2636. };
  2637. }]
  2638. };
  2639. }
  2640. ]);
  2641. })();
  2642. (function() {
  2643. angular.module('ui.grid')
  2644. .directive('uiGridVisible', function uiGridVisibleAction() {
  2645. return function ($scope, $elm, $attr) {
  2646. $scope.$watch($attr.uiGridVisible, function (visible) {
  2647. // $elm.css('visibility', visible ? 'visible' : 'hidden');
  2648. $elm[visible ? 'removeClass' : 'addClass']('ui-grid-invisible');
  2649. });
  2650. };
  2651. });
  2652. })();
  2653. (function () {
  2654. 'use strict';
  2655. angular.module('ui.grid').controller('uiGridController', ['$scope', '$element', '$attrs', 'gridUtil', '$q', 'uiGridConstants',
  2656. '$templateCache', 'gridClassFactory', '$timeout', '$parse', '$compile',
  2657. function ($scope, $elm, $attrs, gridUtil, $q, uiGridConstants,
  2658. $templateCache, gridClassFactory, $timeout, $parse, $compile) {
  2659. // gridUtil.logDebug('ui-grid controller');
  2660. var self = this;
  2661. self.grid = gridClassFactory.createGrid($scope.uiGrid);
  2662. //assign $scope.$parent if appScope not already assigned
  2663. self.grid.appScope = self.grid.appScope || $scope.$parent;
  2664. $elm.addClass('grid' + self.grid.id);
  2665. self.grid.rtl = gridUtil.getStyles($elm[0])['direction'] === 'rtl';
  2666. // angular.extend(self.grid.options, );
  2667. //all properties of grid are available on scope
  2668. $scope.grid = self.grid;
  2669. if ($attrs.uiGridColumns) {
  2670. $attrs.$observe('uiGridColumns', function(value) {
  2671. self.grid.options.columnDefs = value;
  2672. self.grid.buildColumns()
  2673. .then(function(){
  2674. self.grid.preCompileCellTemplates();
  2675. self.grid.refreshCanvas(true);
  2676. });
  2677. });
  2678. }
  2679. // if fastWatch is set we watch only the length and the reference, not every individual object
  2680. var deregFunctions = [];
  2681. if (self.grid.options.fastWatch) {
  2682. self.uiGrid = $scope.uiGrid;
  2683. if (angular.isString($scope.uiGrid.data)) {
  2684. deregFunctions.push( $scope.$parent.$watch($scope.uiGrid.data, dataWatchFunction) );
  2685. deregFunctions.push( $scope.$parent.$watch(function() {
  2686. if ( self.grid.appScope[$scope.uiGrid.data] ){
  2687. return self.grid.appScope[$scope.uiGrid.data].length;
  2688. } else {
  2689. return undefined;
  2690. }
  2691. }, dataWatchFunction) );
  2692. } else {
  2693. deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.data; }, dataWatchFunction) );
  2694. deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.data.length; }, dataWatchFunction) );
  2695. }
  2696. deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) );
  2697. deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs.length; }, columnDefsWatchFunction) );
  2698. } else {
  2699. if (angular.isString($scope.uiGrid.data)) {
  2700. deregFunctions.push( $scope.$parent.$watchCollection($scope.uiGrid.data, dataWatchFunction) );
  2701. } else {
  2702. deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.data; }, dataWatchFunction) );
  2703. }
  2704. deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) );
  2705. }
  2706. function columnDefsWatchFunction(n, o) {
  2707. if (n && n !== o) {
  2708. self.grid.options.columnDefs = n;
  2709. self.grid.buildColumns({ orderByColumnDefs: true })
  2710. .then(function(){
  2711. self.grid.preCompileCellTemplates();
  2712. self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.COLUMN);
  2713. });
  2714. }
  2715. }
  2716. function dataWatchFunction(newData) {
  2717. // gridUtil.logDebug('dataWatch fired');
  2718. var promises = [];
  2719. if ( self.grid.options.fastWatch ){
  2720. if (angular.isString($scope.uiGrid.data)) {
  2721. newData = self.grid.appScope[$scope.uiGrid.data];
  2722. } else {
  2723. newData = $scope.uiGrid.data;
  2724. }
  2725. }
  2726. if (newData) {
  2727. if (
  2728. // If we have no columns (i.e. columns length is either 0 or equal to the number of row header columns, which don't count because they're created automatically)
  2729. self.grid.columns.length === (self.grid.rowHeaderColumns ? self.grid.rowHeaderColumns.length : 0) &&
  2730. // ... and we don't have a ui-grid-columns attribute, which would define columns for us
  2731. !$attrs.uiGridColumns &&
  2732. // ... and we have no pre-defined columns
  2733. self.grid.options.columnDefs.length === 0 &&
  2734. // ... but we DO have data
  2735. newData.length > 0
  2736. ) {
  2737. // ... then build the column definitions from the data that we have
  2738. self.grid.buildColumnDefsFromData(newData);
  2739. }
  2740. // If we either have some columns defined, or some data defined
  2741. if (self.grid.options.columnDefs.length > 0 || newData.length > 0) {
  2742. // Build the column set, then pre-compile the column cell templates
  2743. promises.push(self.grid.buildColumns()
  2744. .then(function() {
  2745. self.grid.preCompileCellTemplates();
  2746. }));
  2747. }
  2748. $q.all(promises).then(function() {
  2749. self.grid.modifyRows(newData)
  2750. .then(function () {
  2751. // if (self.viewport) {
  2752. self.grid.redrawInPlace(true);
  2753. // }
  2754. $scope.$evalAsync(function() {
  2755. self.grid.refreshCanvas(true);
  2756. self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.ROW);
  2757. });
  2758. });
  2759. });
  2760. }
  2761. }
  2762. var styleWatchDereg = $scope.$watch(function () { return self.grid.styleComputations; }, function() {
  2763. self.grid.refreshCanvas(true);
  2764. });
  2765. $scope.$on('$destroy', function() {
  2766. deregFunctions.forEach( function( deregFn ){ deregFn(); });
  2767. styleWatchDereg();
  2768. });
  2769. self.fireEvent = function(eventName, args) {
  2770. // Add the grid to the event arguments if it's not there
  2771. if (typeof(args) === 'undefined' || args === undefined) {
  2772. args = {};
  2773. }
  2774. if (typeof(args.grid) === 'undefined' || args.grid === undefined) {
  2775. args.grid = self.grid;
  2776. }
  2777. $scope.$broadcast(eventName, args);
  2778. };
  2779. self.innerCompile = function innerCompile(elm) {
  2780. $compile(elm)($scope);
  2781. };
  2782. }]);
  2783. /**
  2784. * @ngdoc directive
  2785. * @name ui.grid.directive:uiGrid
  2786. * @element div
  2787. * @restrict EA
  2788. * @param {Object} uiGrid Options for the grid to use
  2789. *
  2790. * @description Create a very basic grid.
  2791. *
  2792. * @example
  2793. <example module="app">
  2794. <file name="app.js">
  2795. var app = angular.module('app', ['ui.grid']);
  2796. app.controller('MainCtrl', ['$scope', function ($scope) {
  2797. $scope.data = [
  2798. { name: 'Bob', title: 'CEO' },
  2799. { name: 'Frank', title: 'Lowly Developer' }
  2800. ];
  2801. }]);
  2802. </file>
  2803. <file name="index.html">
  2804. <div ng-controller="MainCtrl">
  2805. <div ui-grid="{ data: data }"></div>
  2806. </div>
  2807. </file>
  2808. </example>
  2809. */
  2810. angular.module('ui.grid').directive('uiGrid', uiGridDirective);
  2811. uiGridDirective.$inject = ['$compile', '$templateCache', '$timeout', '$window', 'gridUtil', 'uiGridConstants'];
  2812. function uiGridDirective($compile, $templateCache, $timeout, $window, gridUtil, uiGridConstants) {
  2813. return {
  2814. templateUrl: 'ui-grid/ui-grid',
  2815. scope: {
  2816. uiGrid: '='
  2817. },
  2818. replace: true,
  2819. transclude: true,
  2820. controller: 'uiGridController',
  2821. compile: function () {
  2822. return {
  2823. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  2824. var grid = uiGridCtrl.grid;
  2825. // Initialize scrollbars (TODO: move to controller??)
  2826. uiGridCtrl.scrollbars = [];
  2827. grid.element = $elm;
  2828. // See if the grid has a rendered width, if not, wait a bit and try again
  2829. var sizeCheckInterval = 100; // ms
  2830. var maxSizeChecks = 20; // 2 seconds total
  2831. var sizeChecks = 0;
  2832. // Setup (event listeners) the grid
  2833. setup();
  2834. // And initialize it
  2835. init();
  2836. // Mark rendering complete so API events can happen
  2837. grid.renderingComplete();
  2838. // If the grid doesn't have size currently, wait for a bit to see if it gets size
  2839. checkSize();
  2840. /*-- Methods --*/
  2841. function checkSize() {
  2842. // If the grid has no width and we haven't checked more than <maxSizeChecks> times, check again in <sizeCheckInterval> milliseconds
  2843. if ($elm[0].offsetWidth <= 0 && sizeChecks < maxSizeChecks) {
  2844. setTimeout(checkSize, sizeCheckInterval);
  2845. sizeChecks++;
  2846. }
  2847. else {
  2848. $timeout(init);
  2849. }
  2850. }
  2851. // Setup event listeners and watchers
  2852. function setup() {
  2853. // Bind to window resize events
  2854. angular.element($window).on('resize', gridResize);
  2855. // Unbind from window resize events when the grid is destroyed
  2856. $elm.on('$destroy', function () {
  2857. angular.element($window).off('resize', gridResize);
  2858. });
  2859. // If we add a left container after render, we need to watch and react
  2860. $scope.$watch(function () { return grid.hasLeftContainer();}, function (newValue, oldValue) {
  2861. if (newValue === oldValue) {
  2862. return;
  2863. }
  2864. grid.refreshCanvas(true);
  2865. });
  2866. // If we add a right container after render, we need to watch and react
  2867. $scope.$watch(function () { return grid.hasRightContainer();}, function (newValue, oldValue) {
  2868. if (newValue === oldValue) {
  2869. return;
  2870. }
  2871. grid.refreshCanvas(true);
  2872. });
  2873. }
  2874. // Initialize the directive
  2875. function init() {
  2876. grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm);
  2877. // Default canvasWidth to the grid width, in case we don't get any column definitions to calculate it from
  2878. grid.canvasWidth = uiGridCtrl.grid.gridWidth;
  2879. grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);
  2880. // If the grid isn't tall enough to fit a single row, it's kind of useless. Resize it to fit a minimum number of rows
  2881. if (grid.gridHeight < grid.options.rowHeight && grid.options.enableMinHeightCheck) {
  2882. autoAdjustHeight();
  2883. }
  2884. // Run initial canvas refresh
  2885. grid.refreshCanvas(true);
  2886. }
  2887. // Set the grid's height ourselves in the case that its height would be unusably small
  2888. function autoAdjustHeight() {
  2889. // Figure out the new height
  2890. var contentHeight = grid.options.minRowsToShow * grid.options.rowHeight;
  2891. var headerHeight = grid.options.showHeader ? grid.options.headerRowHeight : 0;
  2892. var footerHeight = grid.calcFooterHeight();
  2893. var scrollbarHeight = 0;
  2894. if (grid.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) {
  2895. scrollbarHeight = gridUtil.getScrollbarWidth();
  2896. }
  2897. var maxNumberOfFilters = 0;
  2898. // Calculates the maximum number of filters in the columns
  2899. angular.forEach(grid.options.columnDefs, function(col) {
  2900. if (col.hasOwnProperty('filter')) {
  2901. if (maxNumberOfFilters < 1) {
  2902. maxNumberOfFilters = 1;
  2903. }
  2904. }
  2905. else if (col.hasOwnProperty('filters')) {
  2906. if (maxNumberOfFilters < col.filters.length) {
  2907. maxNumberOfFilters = col.filters.length;
  2908. }
  2909. }
  2910. });
  2911. if (grid.options.enableFiltering) {
  2912. var allColumnsHaveFilteringTurnedOff = grid.options.columnDefs.every(function(col) {
  2913. return col.enableFiltering === false;
  2914. });
  2915. if (!allColumnsHaveFilteringTurnedOff) {
  2916. maxNumberOfFilters++;
  2917. }
  2918. }
  2919. var filterHeight = maxNumberOfFilters * headerHeight;
  2920. var newHeight = headerHeight + contentHeight + footerHeight + scrollbarHeight + filterHeight;
  2921. $elm.css('height', newHeight + 'px');
  2922. grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);
  2923. }
  2924. // Resize the grid on window resize events
  2925. function gridResize($event) {
  2926. grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm);
  2927. grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);
  2928. grid.refreshCanvas(true);
  2929. }
  2930. }
  2931. };
  2932. }
  2933. };
  2934. }
  2935. })();
  2936. (function(){
  2937. 'use strict';
  2938. // TODO: rename this file to ui-grid-pinned-container.js
  2939. angular.module('ui.grid').directive('uiGridPinnedContainer', ['gridUtil', function (gridUtil) {
  2940. return {
  2941. restrict: 'EA',
  2942. replace: true,
  2943. template: '<div class="ui-grid-pinned-container"><div ui-grid-render-container container-id="side" row-container-name="\'body\'" col-container-name="side" bind-scroll-vertical="true" class="{{ side }} ui-grid-render-container-{{ side }}"></div></div>',
  2944. scope: {
  2945. side: '=uiGridPinnedContainer'
  2946. },
  2947. require: '^uiGrid',
  2948. compile: function compile() {
  2949. return {
  2950. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  2951. // gridUtil.logDebug('ui-grid-pinned-container ' + $scope.side + ' link');
  2952. var grid = uiGridCtrl.grid;
  2953. var myWidth = 0;
  2954. $elm.addClass('ui-grid-pinned-container-' + $scope.side);
  2955. // Monkey-patch the viewport width function
  2956. if ($scope.side === 'left' || $scope.side === 'right') {
  2957. grid.renderContainers[$scope.side].getViewportWidth = monkeyPatchedGetViewportWidth;
  2958. }
  2959. function monkeyPatchedGetViewportWidth() {
  2960. /*jshint validthis: true */
  2961. var self = this;
  2962. var viewportWidth = 0;
  2963. self.visibleColumnCache.forEach(function (column) {
  2964. viewportWidth += column.drawnWidth;
  2965. });
  2966. var adjustment = self.getViewportAdjustment();
  2967. viewportWidth = viewportWidth + adjustment.width;
  2968. return viewportWidth;
  2969. }
  2970. function updateContainerWidth() {
  2971. if ($scope.side === 'left' || $scope.side === 'right') {
  2972. var cols = grid.renderContainers[$scope.side].visibleColumnCache;
  2973. var width = 0;
  2974. for (var i = 0; i < cols.length; i++) {
  2975. var col = cols[i];
  2976. width += col.drawnWidth || col.width || 0;
  2977. }
  2978. return width;
  2979. }
  2980. }
  2981. function updateContainerDimensions() {
  2982. var ret = '';
  2983. // Column containers
  2984. if ($scope.side === 'left' || $scope.side === 'right') {
  2985. myWidth = updateContainerWidth();
  2986. // gridUtil.logDebug('myWidth', myWidth);
  2987. // TODO(c0bra): Subtract sum of col widths from grid viewport width and update it
  2988. $elm.attr('style', null);
  2989. // var myHeight = grid.renderContainers.body.getViewportHeight(); // + grid.horizontalScrollbarHeight;
  2990. ret += '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.side + ', .grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.side + ' .ui-grid-render-container-' + $scope.side + ' .ui-grid-viewport { width: ' + myWidth + 'px; } ';
  2991. }
  2992. return ret;
  2993. }
  2994. grid.renderContainers.body.registerViewportAdjuster(function (adjustment) {
  2995. myWidth = updateContainerWidth();
  2996. // Subtract our own width
  2997. adjustment.width -= myWidth;
  2998. adjustment.side = $scope.side;
  2999. return adjustment;
  3000. });
  3001. // Register style computation to adjust for columns in `side`'s render container
  3002. grid.registerStyleComputation({
  3003. priority: 15,
  3004. func: updateContainerDimensions
  3005. });
  3006. }
  3007. };
  3008. }
  3009. };
  3010. }]);
  3011. })();
  3012. (function(){
  3013. angular.module('ui.grid')
  3014. .factory('Grid', ['$q', '$compile', '$parse', 'gridUtil', 'uiGridConstants', 'GridOptions', 'GridColumn', 'GridRow', 'GridApi', 'rowSorter', 'rowSearcher', 'GridRenderContainer', '$timeout','ScrollEvent',
  3015. function($q, $compile, $parse, gridUtil, uiGridConstants, GridOptions, GridColumn, GridRow, GridApi, rowSorter, rowSearcher, GridRenderContainer, $timeout, ScrollEvent) {
  3016. /**
  3017. * @ngdoc object
  3018. * @name ui.grid.core.api:PublicApi
  3019. * @description Public Api for the core grid features
  3020. *
  3021. */
  3022. /**
  3023. * @ngdoc function
  3024. * @name ui.grid.class:Grid
  3025. * @description Grid is the main viewModel. Any properties or methods needed to maintain state are defined in
  3026. * this prototype. One instance of Grid is created per Grid directive instance.
  3027. * @param {object} options Object map of options to pass into the grid. An 'id' property is expected.
  3028. */
  3029. var Grid = function Grid(options) {
  3030. var self = this;
  3031. // Get the id out of the options, then remove it
  3032. if (options !== undefined && typeof(options.id) !== 'undefined' && options.id) {
  3033. if (!/^[_a-zA-Z0-9-]+$/.test(options.id)) {
  3034. throw new Error("Grid id '" + options.id + '" is invalid. It must follow CSS selector syntax rules.');
  3035. }
  3036. }
  3037. else {
  3038. throw new Error('No ID provided. An ID must be given when creating a grid.');
  3039. }
  3040. self.id = options.id;
  3041. delete options.id;
  3042. // Get default options
  3043. self.options = GridOptions.initialize( options );
  3044. /**
  3045. * @ngdoc object
  3046. * @name appScope
  3047. * @propertyOf ui.grid.class:Grid
  3048. * @description reference to the application scope (the parent scope of the ui-grid element). Assigned in ui-grid controller
  3049. * <br/>
  3050. * use gridOptions.appScopeProvider to override the default assignment of $scope.$parent with any reference
  3051. */
  3052. self.appScope = self.options.appScopeProvider;
  3053. self.headerHeight = self.options.headerRowHeight;
  3054. /**
  3055. * @ngdoc object
  3056. * @name footerHeight
  3057. * @propertyOf ui.grid.class:Grid
  3058. * @description returns the total footer height gridFooter + columnFooter
  3059. */
  3060. self.footerHeight = self.calcFooterHeight();
  3061. /**
  3062. * @ngdoc object
  3063. * @name columnFooterHeight
  3064. * @propertyOf ui.grid.class:Grid
  3065. * @description returns the total column footer height
  3066. */
  3067. self.columnFooterHeight = self.calcColumnFooterHeight();
  3068. self.rtl = false;
  3069. self.gridHeight = 0;
  3070. self.gridWidth = 0;
  3071. self.columnBuilders = [];
  3072. self.rowBuilders = [];
  3073. self.rowsProcessors = [];
  3074. self.columnsProcessors = [];
  3075. self.styleComputations = [];
  3076. self.viewportAdjusters = [];
  3077. self.rowHeaderColumns = [];
  3078. self.dataChangeCallbacks = {};
  3079. self.verticalScrollSyncCallBackFns = {};
  3080. self.horizontalScrollSyncCallBackFns = {};
  3081. // self.visibleRowCache = [];
  3082. // Set of 'render' containers for self grid, which can render sets of rows
  3083. self.renderContainers = {};
  3084. // Create a
  3085. self.renderContainers.body = new GridRenderContainer('body', self);
  3086. self.cellValueGetterCache = {};
  3087. // Cached function to use with custom row templates
  3088. self.getRowTemplateFn = null;
  3089. //representation of the rows on the grid.
  3090. //these are wrapped references to the actual data rows (options.data)
  3091. self.rows = [];
  3092. //represents the columns on the grid
  3093. self.columns = [];
  3094. /**
  3095. * @ngdoc boolean
  3096. * @name isScrollingVertically
  3097. * @propertyOf ui.grid.class:Grid
  3098. * @description set to true when Grid is scrolling vertically. Set to false via debounced method
  3099. */
  3100. self.isScrollingVertically = false;
  3101. /**
  3102. * @ngdoc boolean
  3103. * @name isScrollingHorizontally
  3104. * @propertyOf ui.grid.class:Grid
  3105. * @description set to true when Grid is scrolling horizontally. Set to false via debounced method
  3106. */
  3107. self.isScrollingHorizontally = false;
  3108. /**
  3109. * @ngdoc property
  3110. * @name scrollDirection
  3111. * @propertyOf ui.grid.class:Grid
  3112. * @description set one of the uiGridConstants.scrollDirection values (UP, DOWN, LEFT, RIGHT, NONE), which tells
  3113. * us which direction we are scrolling. Set to NONE via debounced method
  3114. */
  3115. self.scrollDirection = uiGridConstants.scrollDirection.NONE;
  3116. //if true, grid will not respond to any scroll events
  3117. self.disableScrolling = false;
  3118. function vertical (scrollEvent) {
  3119. self.isScrollingVertically = false;
  3120. self.api.core.raise.scrollEnd(scrollEvent);
  3121. self.scrollDirection = uiGridConstants.scrollDirection.NONE;
  3122. }
  3123. var debouncedVertical = gridUtil.debounce(vertical, self.options.scrollDebounce);
  3124. var debouncedVerticalMinDelay = gridUtil.debounce(vertical, 0);
  3125. function horizontal (scrollEvent) {
  3126. self.isScrollingHorizontally = false;
  3127. self.api.core.raise.scrollEnd(scrollEvent);
  3128. self.scrollDirection = uiGridConstants.scrollDirection.NONE;
  3129. }
  3130. var debouncedHorizontal = gridUtil.debounce(horizontal, self.options.scrollDebounce);
  3131. var debouncedHorizontalMinDelay = gridUtil.debounce(horizontal, 0);
  3132. /**
  3133. * @ngdoc function
  3134. * @name flagScrollingVertically
  3135. * @methodOf ui.grid.class:Grid
  3136. * @description sets isScrollingVertically to true and sets it to false in a debounced function
  3137. */
  3138. self.flagScrollingVertically = function(scrollEvent) {
  3139. if (!self.isScrollingVertically && !self.isScrollingHorizontally) {
  3140. self.api.core.raise.scrollBegin(scrollEvent);
  3141. }
  3142. self.isScrollingVertically = true;
  3143. if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) {
  3144. debouncedVerticalMinDelay(scrollEvent);
  3145. }
  3146. else {
  3147. debouncedVertical(scrollEvent);
  3148. }
  3149. };
  3150. /**
  3151. * @ngdoc function
  3152. * @name flagScrollingHorizontally
  3153. * @methodOf ui.grid.class:Grid
  3154. * @description sets isScrollingHorizontally to true and sets it to false in a debounced function
  3155. */
  3156. self.flagScrollingHorizontally = function(scrollEvent) {
  3157. if (!self.isScrollingVertically && !self.isScrollingHorizontally) {
  3158. self.api.core.raise.scrollBegin(scrollEvent);
  3159. }
  3160. self.isScrollingHorizontally = true;
  3161. if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) {
  3162. debouncedHorizontalMinDelay(scrollEvent);
  3163. }
  3164. else {
  3165. debouncedHorizontal(scrollEvent);
  3166. }
  3167. };
  3168. self.scrollbarHeight = 0;
  3169. self.scrollbarWidth = 0;
  3170. if (self.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) {
  3171. self.scrollbarHeight = gridUtil.getScrollbarWidth();
  3172. }
  3173. if (self.options.enableVerticalScrollbar === uiGridConstants.scrollbars.ALWAYS) {
  3174. self.scrollbarWidth = gridUtil.getScrollbarWidth();
  3175. }
  3176. self.api = new GridApi(self);
  3177. /**
  3178. * @ngdoc function
  3179. * @name refresh
  3180. * @methodOf ui.grid.core.api:PublicApi
  3181. * @description Refresh the rendered grid on screen.
  3182. * The refresh method re-runs both the columnProcessors and the
  3183. * rowProcessors, as well as calling refreshCanvas to update all
  3184. * the grid sizing. In general you should prefer to use queueGridRefresh
  3185. * instead, which is basically a debounced version of refresh.
  3186. *
  3187. * If you only want to resize the grid, not regenerate all the rows
  3188. * and columns, you should consider directly calling refreshCanvas instead.
  3189. *
  3190. */
  3191. self.api.registerMethod( 'core', 'refresh', this.refresh );
  3192. /**
  3193. * @ngdoc function
  3194. * @name queueGridRefresh
  3195. * @methodOf ui.grid.core.api:PublicApi
  3196. * @description Request a refresh of the rendered grid on screen, if multiple
  3197. * calls to queueGridRefresh are made within a digest cycle only one will execute.
  3198. * The refresh method re-runs both the columnProcessors and the
  3199. * rowProcessors, as well as calling refreshCanvas to update all
  3200. * the grid sizing. In general you should prefer to use queueGridRefresh
  3201. * instead, which is basically a debounced version of refresh.
  3202. *
  3203. */
  3204. self.api.registerMethod( 'core', 'queueGridRefresh', this.queueGridRefresh );
  3205. /**
  3206. * @ngdoc function
  3207. * @name refreshRows
  3208. * @methodOf ui.grid.core.api:PublicApi
  3209. * @description Runs only the rowProcessors, columns remain as they were.
  3210. * It then calls redrawInPlace and refreshCanvas, which adjust the grid sizing.
  3211. * @returns {promise} promise that is resolved when render completes?
  3212. *
  3213. */
  3214. self.api.registerMethod( 'core', 'refreshRows', this.refreshRows );
  3215. /**
  3216. * @ngdoc function
  3217. * @name queueRefresh
  3218. * @methodOf ui.grid.core.api:PublicApi
  3219. * @description Requests execution of refreshCanvas, if multiple requests are made
  3220. * during a digest cycle only one will run. RefreshCanvas updates the grid sizing.
  3221. * @returns {promise} promise that is resolved when render completes?
  3222. *
  3223. */
  3224. self.api.registerMethod( 'core', 'queueRefresh', this.queueRefresh );
  3225. /**
  3226. * @ngdoc function
  3227. * @name handleWindowResize
  3228. * @methodOf ui.grid.core.api:PublicApi
  3229. * @description Trigger a grid resize, normally this would be picked
  3230. * up by a watch on window size, but in some circumstances it is necessary
  3231. * to call this manually
  3232. * @returns {promise} promise that is resolved when render completes?
  3233. *
  3234. */
  3235. self.api.registerMethod( 'core', 'handleWindowResize', this.handleWindowResize );
  3236. /**
  3237. * @ngdoc function
  3238. * @name addRowHeaderColumn
  3239. * @methodOf ui.grid.core.api:PublicApi
  3240. * @description adds a row header column to the grid
  3241. * @param {object} column def
  3242. *
  3243. */
  3244. self.api.registerMethod( 'core', 'addRowHeaderColumn', this.addRowHeaderColumn );
  3245. /**
  3246. * @ngdoc function
  3247. * @name scrollToIfNecessary
  3248. * @methodOf ui.grid.core.api:PublicApi
  3249. * @description Scrolls the grid to make a certain row and column combo visible,
  3250. * in the case that it is not completely visible on the screen already.
  3251. * @param {GridRow} gridRow row to make visible
  3252. * @param {GridCol} gridCol column to make visible
  3253. * @returns {promise} a promise that is resolved when scrolling is complete
  3254. *
  3255. */
  3256. self.api.registerMethod( 'core', 'scrollToIfNecessary', function(gridRow, gridCol) { return self.scrollToIfNecessary(gridRow, gridCol);} );
  3257. /**
  3258. * @ngdoc function
  3259. * @name scrollTo
  3260. * @methodOf ui.grid.core.api:PublicApi
  3261. * @description Scroll the grid such that the specified
  3262. * row and column is in view
  3263. * @param {object} rowEntity gridOptions.data[] array instance to make visible
  3264. * @param {object} colDef to make visible
  3265. * @returns {promise} a promise that is resolved after any scrolling is finished
  3266. */
  3267. self.api.registerMethod( 'core', 'scrollTo', function (rowEntity, colDef) { return self.scrollTo(rowEntity, colDef);} );
  3268. /**
  3269. * @ngdoc function
  3270. * @name registerRowsProcessor
  3271. * @methodOf ui.grid.core.api:PublicApi
  3272. * @description
  3273. * Register a "rows processor" function. When the rows are updated,
  3274. * the grid calls each registered "rows processor", which has a chance
  3275. * to alter the set of rows (sorting, etc) as long as the count is not
  3276. * modified.
  3277. *
  3278. * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which
  3279. * is run in the context of the grid (i.e. this for the function will be the grid), and must
  3280. * return the updated rows list, which is passed to the next processor in the chain
  3281. * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
  3282. * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier.
  3283. *
  3284. * At present allRowsVisible is running at 50, sort manipulations running at 60-65, filter is running at 100,
  3285. * sort is at 200, grouping and treeview at 400-410, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
  3286. */
  3287. self.api.registerMethod( 'core', 'registerRowsProcessor', this.registerRowsProcessor );
  3288. /**
  3289. * @ngdoc function
  3290. * @name registerColumnsProcessor
  3291. * @methodOf ui.grid.core.api:PublicApi
  3292. * @description
  3293. * Register a "columns processor" function. When the columns are updated,
  3294. * the grid calls each registered "columns processor", which has a chance
  3295. * to alter the set of columns as long as the count is not
  3296. * modified.
  3297. *
  3298. * @param {function(renderedColumnsToProcess, rows )} processorFunction columns processor function, which
  3299. * is run in the context of the grid (i.e. this for the function will be the grid), and must
  3300. * return the updated columns list, which is passed to the next processor in the chain
  3301. * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
  3302. * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier.
  3303. *
  3304. * At present allRowsVisible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
  3305. */
  3306. self.api.registerMethod( 'core', 'registerColumnsProcessor', this.registerColumnsProcessor );
  3307. /**
  3308. * @ngdoc function
  3309. * @name sortHandleNulls
  3310. * @methodOf ui.grid.core.api:PublicApi
  3311. * @description A null handling method that can be used when building custom sort
  3312. * functions
  3313. * @example
  3314. * <pre>
  3315. * mySortFn = function(a, b) {
  3316. * var nulls = $scope.gridApi.core.sortHandleNulls(a, b);
  3317. * if ( nulls !== null ){
  3318. * return nulls;
  3319. * } else {
  3320. * // your code for sorting here
  3321. * };
  3322. * </pre>
  3323. * @param {object} a sort value a
  3324. * @param {object} b sort value b
  3325. * @returns {number} null if there were no nulls/undefineds, otherwise returns
  3326. * a sort value that should be passed back from the sort function
  3327. *
  3328. */
  3329. self.api.registerMethod( 'core', 'sortHandleNulls', rowSorter.handleNulls );
  3330. /**
  3331. * @ngdoc function
  3332. * @name sortChanged
  3333. * @methodOf ui.grid.core.api:PublicApi
  3334. * @description The sort criteria on one or more columns has
  3335. * changed. Provides as parameters the grid and the output of
  3336. * getColumnSorting, which is an array of gridColumns
  3337. * that have sorting on them, sorted in priority order.
  3338. *
  3339. * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed.
  3340. * @param {Function} callBack Will be called when the event is emited. The function passes back an array of columns with
  3341. * sorts on them, in priority order.
  3342. *
  3343. * @example
  3344. * <pre>
  3345. * gridApi.core.on.sortChanged( $scope, function(sortColumns){
  3346. * // do something
  3347. * });
  3348. * </pre>
  3349. */
  3350. self.api.registerEvent( 'core', 'sortChanged' );
  3351. /**
  3352. * @ngdoc function
  3353. * @name columnVisibilityChanged
  3354. * @methodOf ui.grid.core.api:PublicApi
  3355. * @description The visibility of a column has changed,
  3356. * the column itself is passed out as a parameter of the event.
  3357. *
  3358. * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed.
  3359. * @param {Function} callBack Will be called when the event is emited. The function passes back the GridCol that has changed.
  3360. *
  3361. * @example
  3362. * <pre>
  3363. * gridApi.core.on.columnVisibilityChanged( $scope, function (column) {
  3364. * // do something
  3365. * } );
  3366. * </pre>
  3367. */
  3368. self.api.registerEvent( 'core', 'columnVisibilityChanged' );
  3369. /**
  3370. * @ngdoc method
  3371. * @name notifyDataChange
  3372. * @methodOf ui.grid.core.api:PublicApi
  3373. * @description Notify the grid that a data or config change has occurred,
  3374. * where that change isn't something the grid was otherwise noticing. This
  3375. * might be particularly relevant where you've changed values within the data
  3376. * and you'd like cell classes to be re-evaluated, or changed config within
  3377. * the columnDef and you'd like headerCellClasses to be re-evaluated.
  3378. * @param {string} type one of the
  3379. * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN), which tells
  3380. * us which refreshes to fire.
  3381. *
  3382. */
  3383. self.api.registerMethod( 'core', 'notifyDataChange', this.notifyDataChange );
  3384. /**
  3385. * @ngdoc method
  3386. * @name clearAllFilters
  3387. * @methodOf ui.grid.core.api:PublicApi
  3388. * @description Clears all filters and optionally refreshes the visible rows.
  3389. * @param {object} refreshRows Defaults to true.
  3390. * @param {object} clearConditions Defaults to false.
  3391. * @param {object} clearFlags Defaults to false.
  3392. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing.
  3393. */
  3394. self.api.registerMethod('core', 'clearAllFilters', this.clearAllFilters);
  3395. self.registerDataChangeCallback( self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]);
  3396. self.registerDataChangeCallback( self.processRowsCallback, [uiGridConstants.dataChange.EDIT]);
  3397. self.registerDataChangeCallback( self.updateFooterHeightCallback, [uiGridConstants.dataChange.OPTIONS]);
  3398. self.registerStyleComputation({
  3399. priority: 10,
  3400. func: self.getFooterStyles
  3401. });
  3402. };
  3403. Grid.prototype.calcFooterHeight = function () {
  3404. if (!this.hasFooter()) {
  3405. return 0;
  3406. }
  3407. var height = 0;
  3408. if (this.options.showGridFooter) {
  3409. height += this.options.gridFooterHeight;
  3410. }
  3411. height += this.calcColumnFooterHeight();
  3412. return height;
  3413. };
  3414. Grid.prototype.calcColumnFooterHeight = function () {
  3415. var height = 0;
  3416. if (this.options.showColumnFooter) {
  3417. height += this.options.columnFooterHeight;
  3418. }
  3419. return height;
  3420. };
  3421. Grid.prototype.getFooterStyles = function () {
  3422. var style = '.grid' + this.id + ' .ui-grid-footer-aggregates-row { height: ' + this.options.columnFooterHeight + 'px; }';
  3423. style += ' .grid' + this.id + ' .ui-grid-footer-info { height: ' + this.options.gridFooterHeight + 'px; }';
  3424. return style;
  3425. };
  3426. Grid.prototype.hasFooter = function () {
  3427. return this.options.showGridFooter || this.options.showColumnFooter;
  3428. };
  3429. /**
  3430. * @ngdoc function
  3431. * @name isRTL
  3432. * @methodOf ui.grid.class:Grid
  3433. * @description Returns true if grid is RightToLeft
  3434. */
  3435. Grid.prototype.isRTL = function () {
  3436. return this.rtl;
  3437. };
  3438. /**
  3439. * @ngdoc function
  3440. * @name registerColumnBuilder
  3441. * @methodOf ui.grid.class:Grid
  3442. * @description When the build creates columns from column definitions, the columnbuilders will be called to add
  3443. * additional properties to the column.
  3444. * @param {function(colDef, col, gridOptions)} columnBuilder function to be called
  3445. */
  3446. Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) {
  3447. this.columnBuilders.push(columnBuilder);
  3448. };
  3449. /**
  3450. * @ngdoc function
  3451. * @name buildColumnDefsFromData
  3452. * @methodOf ui.grid.class:Grid
  3453. * @description Populates columnDefs from the provided data
  3454. * @param {function(colDef, col, gridOptions)} rowBuilder function to be called
  3455. */
  3456. Grid.prototype.buildColumnDefsFromData = function (dataRows){
  3457. this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties);
  3458. };
  3459. /**
  3460. * @ngdoc function
  3461. * @name registerRowBuilder
  3462. * @methodOf ui.grid.class:Grid
  3463. * @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add
  3464. * additional properties to the row.
  3465. * @param {function(row, gridOptions)} rowBuilder function to be called
  3466. */
  3467. Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) {
  3468. this.rowBuilders.push(rowBuilder);
  3469. };
  3470. /**
  3471. * @ngdoc function
  3472. * @name registerDataChangeCallback
  3473. * @methodOf ui.grid.class:Grid
  3474. * @description When a data change occurs, the data change callbacks of the specified type
  3475. * will be called. The rules are:
  3476. *
  3477. * - when the data watch fires, that is considered a ROW change (the data watch only notices
  3478. * added or removed rows)
  3479. * - when the api is called to inform us of a change, the declared type of that change is used
  3480. * - when a cell edit completes, the EDIT callbacks are triggered
  3481. * - when the columnDef watch fires, the COLUMN callbacks are triggered
  3482. * - when the options watch fires, the OPTIONS callbacks are triggered
  3483. *
  3484. * For a given event:
  3485. * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks
  3486. * - ROW calls ROW and ALL callbacks
  3487. * - EDIT calls EDIT and ALL callbacks
  3488. * - COLUMN calls COLUMN and ALL callbacks
  3489. * - OPTIONS calls OPTIONS and ALL callbacks
  3490. *
  3491. * @param {function(grid)} callback function to be called
  3492. * @param {array} types the types of data change you want to be informed of. Values from
  3493. * the uiGridConstants.dataChange values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to
  3494. * ALL
  3495. * @returns {function} deregister function - a function that can be called to deregister this callback
  3496. */
  3497. Grid.prototype.registerDataChangeCallback = function registerDataChangeCallback(callback, types, _this) {
  3498. var uid = gridUtil.nextUid();
  3499. if ( !types ){
  3500. types = [uiGridConstants.dataChange.ALL];
  3501. }
  3502. if ( !Array.isArray(types)){
  3503. gridUtil.logError("Expected types to be an array or null in registerDataChangeCallback, value passed was: " + types );
  3504. }
  3505. this.dataChangeCallbacks[uid] = { callback: callback, types: types, _this:_this };
  3506. var self = this;
  3507. var deregisterFunction = function() {
  3508. delete self.dataChangeCallbacks[uid];
  3509. };
  3510. return deregisterFunction;
  3511. };
  3512. /**
  3513. * @ngdoc function
  3514. * @name callDataChangeCallbacks
  3515. * @methodOf ui.grid.class:Grid
  3516. * @description Calls the callbacks based on the type of data change that
  3517. * has occurred. Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks if the
  3518. * event type is matching, or if the type is ALL.
  3519. * @param {number} type the type of event that occurred - one of the
  3520. * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN, OPTIONS)
  3521. */
  3522. Grid.prototype.callDataChangeCallbacks = function callDataChangeCallbacks(type, options) {
  3523. angular.forEach( this.dataChangeCallbacks, function( callback, uid ){
  3524. if ( callback.types.indexOf( uiGridConstants.dataChange.ALL ) !== -1 ||
  3525. callback.types.indexOf( type ) !== -1 ||
  3526. type === uiGridConstants.dataChange.ALL ) {
  3527. if (callback._this) {
  3528. callback.callback.apply(callback._this,this);
  3529. }
  3530. else {
  3531. callback.callback( this );
  3532. }
  3533. }
  3534. }, this);
  3535. };
  3536. /**
  3537. * @ngdoc function
  3538. * @name notifyDataChange
  3539. * @methodOf ui.grid.class:Grid
  3540. * @description Notifies us that a data change has occurred, used in the public
  3541. * api for users to tell us when they've changed data or some other event that
  3542. * our watches cannot pick up
  3543. * @param {string} type the type of event that occurred - one of the
  3544. * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN)
  3545. */
  3546. Grid.prototype.notifyDataChange = function notifyDataChange(type) {
  3547. var constants = uiGridConstants.dataChange;
  3548. if ( type === constants.ALL ||
  3549. type === constants.COLUMN ||
  3550. type === constants.EDIT ||
  3551. type === constants.ROW ||
  3552. type === constants.OPTIONS ){
  3553. this.callDataChangeCallbacks( type );
  3554. } else {
  3555. gridUtil.logError("Notified of a data change, but the type was not recognised, so no action taken, type was: " + type);
  3556. }
  3557. };
  3558. /**
  3559. * @ngdoc function
  3560. * @name columnRefreshCallback
  3561. * @methodOf ui.grid.class:Grid
  3562. * @description refreshes the grid when a column refresh
  3563. * is notified, which triggers handling of the visible flag.
  3564. * This is called on uiGridConstants.dataChange.COLUMN, and is
  3565. * registered as a dataChangeCallback in grid.js
  3566. * @param {string} name column name
  3567. */
  3568. Grid.prototype.columnRefreshCallback = function columnRefreshCallback( grid ){
  3569. grid.buildColumns();
  3570. grid.queueGridRefresh();
  3571. };
  3572. /**
  3573. * @ngdoc function
  3574. * @name processRowsCallback
  3575. * @methodOf ui.grid.class:Grid
  3576. * @description calls the row processors, specifically
  3577. * intended to reset the sorting when an edit is called,
  3578. * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT
  3579. * @param {string} name column name
  3580. */
  3581. Grid.prototype.processRowsCallback = function processRowsCallback( grid ){
  3582. grid.queueGridRefresh();
  3583. };
  3584. /**
  3585. * @ngdoc function
  3586. * @name updateFooterHeightCallback
  3587. * @methodOf ui.grid.class:Grid
  3588. * @description recalculates the footer height,
  3589. * registered as a dataChangeCallback on uiGridConstants.dataChange.OPTIONS
  3590. * @param {string} name column name
  3591. */
  3592. Grid.prototype.updateFooterHeightCallback = function updateFooterHeightCallback( grid ){
  3593. grid.footerHeight = grid.calcFooterHeight();
  3594. grid.columnFooterHeight = grid.calcColumnFooterHeight();
  3595. };
  3596. /**
  3597. * @ngdoc function
  3598. * @name getColumn
  3599. * @methodOf ui.grid.class:Grid
  3600. * @description returns a grid column for the column name
  3601. * @param {string} name column name
  3602. */
  3603. Grid.prototype.getColumn = function getColumn(name) {
  3604. var columns = this.columns.filter(function (column) {
  3605. return column.colDef.name === name;
  3606. });
  3607. return columns.length > 0 ? columns[0] : null;
  3608. };
  3609. /**
  3610. * @ngdoc function
  3611. * @name getColDef
  3612. * @methodOf ui.grid.class:Grid
  3613. * @description returns a grid colDef for the column name
  3614. * @param {string} name column.field
  3615. */
  3616. Grid.prototype.getColDef = function getColDef(name) {
  3617. var colDefs = this.options.columnDefs.filter(function (colDef) {
  3618. return colDef.name === name;
  3619. });
  3620. return colDefs.length > 0 ? colDefs[0] : null;
  3621. };
  3622. /**
  3623. * @ngdoc function
  3624. * @name assignTypes
  3625. * @methodOf ui.grid.class:Grid
  3626. * @description uses the first row of data to assign colDef.type for any types not defined.
  3627. */
  3628. /**
  3629. * @ngdoc property
  3630. * @name type
  3631. * @propertyOf ui.grid.class:GridOptions.columnDef
  3632. * @description the type of the column, used in sorting. If not provided then the
  3633. * grid will guess the type. Add this only if the grid guessing is not to your
  3634. * satisfaction. One of:
  3635. * - 'string'
  3636. * - 'boolean'
  3637. * - 'number'
  3638. * - 'date'
  3639. * - 'object'
  3640. * - 'numberStr'
  3641. * Note that if you choose date, your dates should be in a javascript date type
  3642. *
  3643. */
  3644. Grid.prototype.assignTypes = function(){
  3645. var self = this;
  3646. self.options.columnDefs.forEach(function (colDef, index) {
  3647. //Assign colDef type if not specified
  3648. if (!colDef.type) {
  3649. var col = new GridColumn(colDef, index, self);
  3650. var firstRow = self.rows.length > 0 ? self.rows[0] : null;
  3651. if (firstRow) {
  3652. colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col));
  3653. }
  3654. else {
  3655. colDef.type = 'string';
  3656. }
  3657. }
  3658. });
  3659. };
  3660. /**
  3661. * @ngdoc function
  3662. * @name isRowHeaderColumn
  3663. * @methodOf ui.grid.class:Grid
  3664. * @description returns true if the column is a row Header
  3665. * @param {object} column column
  3666. */
  3667. Grid.prototype.isRowHeaderColumn = function isRowHeaderColumn(column) {
  3668. return this.rowHeaderColumns.indexOf(column) !== -1;
  3669. };
  3670. /**
  3671. * @ngdoc function
  3672. * @name addRowHeaderColumn
  3673. * @methodOf ui.grid.class:Grid
  3674. * @description adds a row header column to the grid
  3675. * @param {object} column def
  3676. */
  3677. Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef) {
  3678. var self = this;
  3679. var rowHeaderCol = new GridColumn(colDef, gridUtil.nextUid(), self);
  3680. rowHeaderCol.isRowHeader = true;
  3681. if (self.isRTL()) {
  3682. self.createRightContainer();
  3683. rowHeaderCol.renderContainer = 'right';
  3684. }
  3685. else {
  3686. self.createLeftContainer();
  3687. rowHeaderCol.renderContainer = 'left';
  3688. }
  3689. // relies on the default column builder being first in array, as it is instantiated
  3690. // as part of grid creation
  3691. self.columnBuilders[0](colDef,rowHeaderCol,self.options)
  3692. .then(function(){
  3693. rowHeaderCol.enableFiltering = false;
  3694. rowHeaderCol.enableSorting = false;
  3695. rowHeaderCol.enableHiding = false;
  3696. self.rowHeaderColumns.push(rowHeaderCol);
  3697. self.buildColumns()
  3698. .then( function() {
  3699. self.preCompileCellTemplates();
  3700. self.queueGridRefresh();
  3701. });
  3702. });
  3703. };
  3704. /**
  3705. * @ngdoc function
  3706. * @name getOnlyDataColumns
  3707. * @methodOf ui.grid.class:Grid
  3708. * @description returns all columns except for rowHeader columns
  3709. */
  3710. Grid.prototype.getOnlyDataColumns = function getOnlyDataColumns() {
  3711. var self = this;
  3712. var cols = [];
  3713. self.columns.forEach(function (col) {
  3714. if (self.rowHeaderColumns.indexOf(col) === -1) {
  3715. cols.push(col);
  3716. }
  3717. });
  3718. return cols;
  3719. };
  3720. /**
  3721. * @ngdoc function
  3722. * @name buildColumns
  3723. * @methodOf ui.grid.class:Grid
  3724. * @description creates GridColumn objects from the columnDefinition. Calls each registered
  3725. * columnBuilder to further process the column
  3726. * @param {object} options An object contains options to use when building columns
  3727. *
  3728. * * **orderByColumnDefs**: defaults to **false**. When true, `buildColumns` will reorder existing columns according to the order within the column definitions.
  3729. *
  3730. * @returns {Promise} a promise to load any needed column resources
  3731. */
  3732. Grid.prototype.buildColumns = function buildColumns(opts) {
  3733. var options = {
  3734. orderByColumnDefs: false
  3735. };
  3736. angular.extend(options, opts);
  3737. // gridUtil.logDebug('buildColumns');
  3738. var self = this;
  3739. var builderPromises = [];
  3740. var headerOffset = self.rowHeaderColumns.length;
  3741. var i;
  3742. // Remove any columns for which a columnDef cannot be found
  3743. // Deliberately don't use forEach, as it doesn't like splice being called in the middle
  3744. // Also don't cache columns.length, as it will change during this operation
  3745. for (i = 0; i < self.columns.length; i++){
  3746. if (!self.getColDef(self.columns[i].name)) {
  3747. self.columns.splice(i, 1);
  3748. i--;
  3749. }
  3750. }
  3751. //add row header columns to the grid columns array _after_ columns without columnDefs have been removed
  3752. self.rowHeaderColumns.forEach(function (rowHeaderColumn) {
  3753. self.columns.unshift(rowHeaderColumn);
  3754. });
  3755. // look at each column def, and update column properties to match. If the column def
  3756. // doesn't have a column, then splice in a new gridCol
  3757. self.options.columnDefs.forEach(function (colDef, index) {
  3758. self.preprocessColDef(colDef);
  3759. var col = self.getColumn(colDef.name);
  3760. if (!col) {
  3761. col = new GridColumn(colDef, gridUtil.nextUid(), self);
  3762. self.columns.splice(index + headerOffset, 0, col);
  3763. }
  3764. else {
  3765. // tell updateColumnDef that the column was pre-existing
  3766. col.updateColumnDef(colDef, false);
  3767. }
  3768. self.columnBuilders.forEach(function (builder) {
  3769. builderPromises.push(builder.call(self, colDef, col, self.options));
  3770. });
  3771. });
  3772. /*** Reorder columns if necessary ***/
  3773. if (!!options.orderByColumnDefs) {
  3774. // Create a shallow copy of the columns as a cache
  3775. var columnCache = self.columns.slice(0);
  3776. // We need to allow for the "row headers" when mapping from the column defs array to the columns array
  3777. // If we have a row header in columns[0] and don't account for it we'll overwrite it with the column in columnDefs[0]
  3778. // Go through all the column defs, use the shorter of columns length and colDefs.length because if a user has given two columns the same name then
  3779. // columns will be shorter than columnDefs. In this situation we'll avoid an error, but the user will still get an unexpected result
  3780. var len = Math.min(self.options.columnDefs.length, self.columns.length);
  3781. for (i = 0; i < len; i++) {
  3782. // If the column at this index has a different name than the column at the same index in the column defs...
  3783. if (self.columns[i + headerOffset].name !== self.options.columnDefs[i].name) {
  3784. // Replace the one in the cache with the appropriate column
  3785. columnCache[i + headerOffset] = self.getColumn(self.options.columnDefs[i].name);
  3786. }
  3787. else {
  3788. // Otherwise just copy over the one from the initial columns
  3789. columnCache[i + headerOffset] = self.columns[i + headerOffset];
  3790. }
  3791. }
  3792. // Empty out the columns array, non-destructively
  3793. self.columns.length = 0;
  3794. // And splice in the updated, ordered columns from the cache
  3795. Array.prototype.splice.apply(self.columns, [0, 0].concat(columnCache));
  3796. }
  3797. return $q.all(builderPromises).then(function(){
  3798. if (self.rows.length > 0){
  3799. self.assignTypes();
  3800. }
  3801. });
  3802. };
  3803. /**
  3804. * @ngdoc function
  3805. * @name preCompileCellTemplates
  3806. * @methodOf ui.grid.class:Grid
  3807. * @description precompiles all cell templates
  3808. */
  3809. Grid.prototype.preCompileCellTemplates = function() {
  3810. var self = this;
  3811. var preCompileTemplate = function( col ) {
  3812. var html = col.cellTemplate.replace(uiGridConstants.MODEL_COL_FIELD, self.getQualifiedColField(col));
  3813. html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
  3814. var compiledElementFn = $compile(html);
  3815. col.compiledElementFn = compiledElementFn;
  3816. if (col.compiledElementFnDefer) {
  3817. col.compiledElementFnDefer.resolve(col.compiledElementFn);
  3818. }
  3819. };
  3820. this.columns.forEach(function (col) {
  3821. if ( col.cellTemplate ){
  3822. preCompileTemplate( col );
  3823. } else if ( col.cellTemplatePromise ){
  3824. col.cellTemplatePromise.then( function() {
  3825. preCompileTemplate( col );
  3826. });
  3827. }
  3828. });
  3829. };
  3830. /**
  3831. * @ngdoc function
  3832. * @name getGridQualifiedColField
  3833. * @methodOf ui.grid.class:Grid
  3834. * @description Returns the $parse-able accessor for a column within its $scope
  3835. * @param {GridColumn} col col object
  3836. */
  3837. Grid.prototype.getQualifiedColField = function (col) {
  3838. return 'row.entity.' + gridUtil.preEval(col.field);
  3839. };
  3840. /**
  3841. * @ngdoc function
  3842. * @name createLeftContainer
  3843. * @methodOf ui.grid.class:Grid
  3844. * @description creates the left render container if it doesn't already exist
  3845. */
  3846. Grid.prototype.createLeftContainer = function() {
  3847. if (!this.hasLeftContainer()) {
  3848. this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true });
  3849. }
  3850. };
  3851. /**
  3852. * @ngdoc function
  3853. * @name createRightContainer
  3854. * @methodOf ui.grid.class:Grid
  3855. * @description creates the right render container if it doesn't already exist
  3856. */
  3857. Grid.prototype.createRightContainer = function() {
  3858. if (!this.hasRightContainer()) {
  3859. this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true });
  3860. }
  3861. };
  3862. /**
  3863. * @ngdoc function
  3864. * @name hasLeftContainer
  3865. * @methodOf ui.grid.class:Grid
  3866. * @description returns true if leftContainer exists
  3867. */
  3868. Grid.prototype.hasLeftContainer = function() {
  3869. return this.renderContainers.left !== undefined;
  3870. };
  3871. /**
  3872. * @ngdoc function
  3873. * @name hasRightContainer
  3874. * @methodOf ui.grid.class:Grid
  3875. * @description returns true if rightContainer exists
  3876. */
  3877. Grid.prototype.hasRightContainer = function() {
  3878. return this.renderContainers.right !== undefined;
  3879. };
  3880. /**
  3881. * undocumented function
  3882. * @name preprocessColDef
  3883. * @methodOf ui.grid.class:Grid
  3884. * @description defaults the name property from field to maintain backwards compatibility with 2.x
  3885. * validates that name or field is present
  3886. */
  3887. Grid.prototype.preprocessColDef = function preprocessColDef(colDef) {
  3888. var self = this;
  3889. if (!colDef.field && !colDef.name) {
  3890. throw new Error('colDef.name or colDef.field property is required');
  3891. }
  3892. //maintain backwards compatibility with 2.x
  3893. //field was required in 2.x. now name is required
  3894. if (colDef.name === undefined && colDef.field !== undefined) {
  3895. // See if the column name already exists:
  3896. var newName = colDef.field,
  3897. counter = 2;
  3898. while (self.getColumn(newName)) {
  3899. newName = colDef.field + counter.toString();
  3900. counter++;
  3901. }
  3902. colDef.name = newName;
  3903. }
  3904. };
  3905. // Return a list of items that exist in the `n` array but not the `o` array. Uses optional property accessors passed as third & fourth parameters
  3906. Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) {
  3907. var self = this;
  3908. var t = [];
  3909. for (var i = 0; i < n.length; i++) {
  3910. var nV = nAccessor ? n[i][nAccessor] : n[i];
  3911. var found = false;
  3912. for (var j = 0; j < o.length; j++) {
  3913. var oV = oAccessor ? o[j][oAccessor] : o[j];
  3914. if (self.options.rowEquality(nV, oV)) {
  3915. found = true;
  3916. break;
  3917. }
  3918. }
  3919. if (!found) {
  3920. t.push(nV);
  3921. }
  3922. }
  3923. return t;
  3924. };
  3925. /**
  3926. * @ngdoc function
  3927. * @name getRow
  3928. * @methodOf ui.grid.class:Grid
  3929. * @description returns the GridRow that contains the rowEntity
  3930. * @param {object} rowEntity the gridOptions.data array element instance
  3931. * @param {array} rows [optional] the rows to look in - if not provided then
  3932. * looks in grid.rows
  3933. */
  3934. Grid.prototype.getRow = function getRow(rowEntity, lookInRows) {
  3935. var self = this;
  3936. lookInRows = typeof(lookInRows) === 'undefined' ? self.rows : lookInRows;
  3937. var rows = lookInRows.filter(function (row) {
  3938. return self.options.rowEquality(row.entity, rowEntity);
  3939. });
  3940. return rows.length > 0 ? rows[0] : null;
  3941. };
  3942. /**
  3943. * @ngdoc function
  3944. * @name modifyRows
  3945. * @methodOf ui.grid.class:Grid
  3946. * @description creates or removes GridRow objects from the newRawData array. Calls each registered
  3947. * rowBuilder to further process the row
  3948. *
  3949. * This method aims to achieve three things:
  3950. * 1. the resulting rows array is in the same order as the newRawData, we'll call
  3951. * rowsProcessors immediately after to sort the data anyway
  3952. * 2. if we have row hashing available, we try to use the rowHash to find the row
  3953. * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected
  3954. *
  3955. * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates
  3956. * the newRows and newHash
  3957. *
  3958. * ```
  3959. * newRawData.forEach newEntity
  3960. * if (hashing enabled)
  3961. * check oldHash for newEntity
  3962. * else
  3963. * look for old row directly in oldRows
  3964. * if !oldRowFound // must be a new row
  3965. * create newRow
  3966. * append to the newRows and add to newHash
  3967. * run the processors
  3968. *
  3969. * Rows are identified using the hashKey if configured. If not configured, then rows
  3970. * are identified using the gridOptions.rowEquality function
  3971. */
  3972. Grid.prototype.modifyRows = function modifyRows(newRawData) {
  3973. var self = this;
  3974. var oldRows = self.rows.slice(0);
  3975. var oldRowHash = self.rowHashMap || self.createRowHashMap();
  3976. self.rowHashMap = self.createRowHashMap();
  3977. self.rows.length = 0;
  3978. newRawData.forEach( function( newEntity, i ) {
  3979. var newRow;
  3980. if ( self.options.enableRowHashing ){
  3981. // if hashing is enabled, then this row will be in the hash if we already know about it
  3982. newRow = oldRowHash.get( newEntity );
  3983. } else {
  3984. // otherwise, manually search the oldRows to see if we can find this row
  3985. newRow = self.getRow(newEntity, oldRows);
  3986. }
  3987. // if we didn't find the row, it must be new, so create it
  3988. if ( !newRow ){
  3989. newRow = self.processRowBuilders(new GridRow(newEntity, i, self));
  3990. }
  3991. self.rows.push( newRow );
  3992. self.rowHashMap.put( newEntity, newRow );
  3993. });
  3994. self.assignTypes();
  3995. var p1 = $q.when(self.processRowsProcessors(self.rows))
  3996. .then(function (renderableRows) {
  3997. return self.setVisibleRows(renderableRows);
  3998. });
  3999. var p2 = $q.when(self.processColumnsProcessors(self.columns))
  4000. .then(function (renderableColumns) {
  4001. return self.setVisibleColumns(renderableColumns);
  4002. });
  4003. return $q.all([p1, p2]);
  4004. };
  4005. /**
  4006. * Private Undocumented Method
  4007. * @name addRows
  4008. * @methodOf ui.grid.class:Grid
  4009. * @description adds the newRawData array of rows to the grid and calls all registered
  4010. * rowBuilders. this keyword will reference the grid
  4011. */
  4012. Grid.prototype.addRows = function addRows(newRawData) {
  4013. var self = this;
  4014. var existingRowCount = self.rows.length;
  4015. for (var i = 0; i < newRawData.length; i++) {
  4016. var newRow = self.processRowBuilders(new GridRow(newRawData[i], i + existingRowCount, self));
  4017. if (self.options.enableRowHashing) {
  4018. var found = self.rowHashMap.get(newRow.entity);
  4019. if (found) {
  4020. found.row = newRow;
  4021. }
  4022. }
  4023. self.rows.push(newRow);
  4024. }
  4025. };
  4026. /**
  4027. * @ngdoc function
  4028. * @name processRowBuilders
  4029. * @methodOf ui.grid.class:Grid
  4030. * @description processes all RowBuilders for the gridRow
  4031. * @param {GridRow} gridRow reference to gridRow
  4032. * @returns {GridRow} the gridRow with all additional behavior added
  4033. */
  4034. Grid.prototype.processRowBuilders = function processRowBuilders(gridRow) {
  4035. var self = this;
  4036. self.rowBuilders.forEach(function (builder) {
  4037. builder.call(self, gridRow, self.options);
  4038. });
  4039. return gridRow;
  4040. };
  4041. /**
  4042. * @ngdoc function
  4043. * @name registerStyleComputation
  4044. * @methodOf ui.grid.class:Grid
  4045. * @description registered a styleComputation function
  4046. *
  4047. * If the function returns a value it will be appended into the grid's `<style>` block
  4048. * @param {function($scope)} styleComputation function
  4049. */
  4050. Grid.prototype.registerStyleComputation = function registerStyleComputation(styleComputationInfo) {
  4051. this.styleComputations.push(styleComputationInfo);
  4052. };
  4053. // NOTE (c0bra): We already have rowBuilders. I think these do exactly the same thing...
  4054. // Grid.prototype.registerRowFilter = function(filter) {
  4055. // // TODO(c0bra): validate filter?
  4056. // this.rowFilters.push(filter);
  4057. // };
  4058. // Grid.prototype.removeRowFilter = function(filter) {
  4059. // var idx = this.rowFilters.indexOf(filter);
  4060. // if (typeof(idx) !== 'undefined' && idx !== undefined) {
  4061. // this.rowFilters.slice(idx, 1);
  4062. // }
  4063. // };
  4064. // Grid.prototype.processRowFilters = function(rows) {
  4065. // var self = this;
  4066. // self.rowFilters.forEach(function (filter) {
  4067. // filter.call(self, rows);
  4068. // });
  4069. // };
  4070. /**
  4071. * @ngdoc function
  4072. * @name registerRowsProcessor
  4073. * @methodOf ui.grid.class:Grid
  4074. * @description
  4075. *
  4076. * Register a "rows processor" function. When the rows are updated,
  4077. * the grid calls each registered "rows processor", which has a chance
  4078. * to alter the set of rows (sorting, etc) as long as the count is not
  4079. * modified.
  4080. *
  4081. * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which
  4082. * is run in the context of the grid (i.e. this for the function will be the grid), and must
  4083. * return the updated rows list, which is passed to the next processor in the chain
  4084. * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
  4085. * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier.
  4086. *
  4087. * At present all rows visible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
  4088. *
  4089. */
  4090. Grid.prototype.registerRowsProcessor = function registerRowsProcessor(processor, priority) {
  4091. if (!angular.isFunction(processor)) {
  4092. throw 'Attempt to register non-function rows processor: ' + processor;
  4093. }
  4094. this.rowsProcessors.push({processor: processor, priority: priority});
  4095. this.rowsProcessors.sort(function sortByPriority( a, b ){
  4096. return a.priority - b.priority;
  4097. });
  4098. };
  4099. /**
  4100. * @ngdoc function
  4101. * @name removeRowsProcessor
  4102. * @methodOf ui.grid.class:Grid
  4103. * @param {function(renderableRows)} rows processor function
  4104. * @description Remove a registered rows processor
  4105. */
  4106. Grid.prototype.removeRowsProcessor = function removeRowsProcessor(processor) {
  4107. var idx = -1;
  4108. this.rowsProcessors.forEach(function(rowsProcessor, index){
  4109. if ( rowsProcessor.processor === processor ){
  4110. idx = index;
  4111. }
  4112. });
  4113. if ( idx !== -1 ) {
  4114. this.rowsProcessors.splice(idx, 1);
  4115. }
  4116. };
  4117. /**
  4118. * Private Undocumented Method
  4119. * @name processRowsProcessors
  4120. * @methodOf ui.grid.class:Grid
  4121. * @param {Array[GridRow]} The array of "renderable" rows
  4122. * @param {Array[GridColumn]} The array of columns
  4123. * @description Run all the registered rows processors on the array of renderable rows
  4124. */
  4125. Grid.prototype.processRowsProcessors = function processRowsProcessors(renderableRows) {
  4126. var self = this;
  4127. // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order
  4128. var myRenderableRows = renderableRows.slice(0);
  4129. // Return myRenderableRows with no processing if we have no rows processors
  4130. if (self.rowsProcessors.length === 0) {
  4131. return $q.when(myRenderableRows);
  4132. }
  4133. // Counter for iterating through rows processors
  4134. var i = 0;
  4135. // Promise for when we're done with all the processors
  4136. var finished = $q.defer();
  4137. // This function will call the processor in self.rowsProcessors at index 'i', and then
  4138. // when done will call the next processor in the list, using the output from the processor
  4139. // at i as the argument for 'renderedRowsToProcess' on the next iteration.
  4140. //
  4141. // If we're at the end of the list of processors, we resolve our 'finished' callback with
  4142. // the result.
  4143. function startProcessor(i, renderedRowsToProcess) {
  4144. // Get the processor at 'i'
  4145. var processor = self.rowsProcessors[i].processor;
  4146. // Call the processor, passing in the rows to process and the current columns
  4147. // (note: it's wrapped in $q.when() in case the processor does not return a promise)
  4148. return $q.when( processor.call(self, renderedRowsToProcess, self.columns) )
  4149. .then(function handleProcessedRows(processedRows) {
  4150. // Check for errors
  4151. if (!processedRows) {
  4152. throw "Processor at index " + i + " did not return a set of renderable rows";
  4153. }
  4154. if (!angular.isArray(processedRows)) {
  4155. throw "Processor at index " + i + " did not return an array";
  4156. }
  4157. // Processor is done, increment the counter
  4158. i++;
  4159. // If we're not done with the processors, call the next one
  4160. if (i <= self.rowsProcessors.length - 1) {
  4161. return startProcessor(i, processedRows);
  4162. }
  4163. // We're done! Resolve the 'finished' promise
  4164. else {
  4165. finished.resolve(processedRows);
  4166. }
  4167. });
  4168. }
  4169. // Start on the first processor
  4170. startProcessor(0, myRenderableRows);
  4171. return finished.promise;
  4172. };
  4173. Grid.prototype.setVisibleRows = function setVisibleRows(rows) {
  4174. var self = this;
  4175. // Reset all the render container row caches
  4176. for (var i in self.renderContainers) {
  4177. var container = self.renderContainers[i];
  4178. container.canvasHeightShouldUpdate = true;
  4179. if ( typeof(container.visibleRowCache) === 'undefined' ){
  4180. container.visibleRowCache = [];
  4181. } else {
  4182. container.visibleRowCache.length = 0;
  4183. }
  4184. }
  4185. // rows.forEach(function (row) {
  4186. for (var ri = 0; ri < rows.length; ri++) {
  4187. var row = rows[ri];
  4188. var targetContainer = (typeof(row.renderContainer) !== 'undefined' && row.renderContainer) ? row.renderContainer : 'body';
  4189. // If the row is visible
  4190. if (row.visible) {
  4191. self.renderContainers[targetContainer].visibleRowCache.push(row);
  4192. }
  4193. }
  4194. self.api.core.raise.rowsRendered(this.api);
  4195. };
  4196. /**
  4197. * @ngdoc function
  4198. * @name registerColumnsProcessor
  4199. * @methodOf ui.grid.class:Grid
  4200. * @param {function(renderedColumnsToProcess, rows)} columnProcessor column processor function, which
  4201. * is run in the context of the grid (i.e. this for the function will be the grid), and
  4202. * which must return an updated renderedColumnsToProcess which can be passed to the next processor
  4203. * in the chain
  4204. * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
  4205. * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier.
  4206. *
  4207. * At present all rows visible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
  4208. * @description
  4209. Register a "columns processor" function. When the columns are updated,
  4210. the grid calls each registered "columns processor", which has a chance
  4211. to alter the set of columns, as long as the count is not modified.
  4212. */
  4213. Grid.prototype.registerColumnsProcessor = function registerColumnsProcessor(processor, priority) {
  4214. if (!angular.isFunction(processor)) {
  4215. throw 'Attempt to register non-function rows processor: ' + processor;
  4216. }
  4217. this.columnsProcessors.push({processor: processor, priority: priority});
  4218. this.columnsProcessors.sort(function sortByPriority( a, b ){
  4219. return a.priority - b.priority;
  4220. });
  4221. };
  4222. Grid.prototype.removeColumnsProcessor = function removeColumnsProcessor(processor) {
  4223. var idx = this.columnsProcessors.indexOf(processor);
  4224. if (typeof(idx) !== 'undefined' && idx !== undefined) {
  4225. this.columnsProcessors.splice(idx, 1);
  4226. }
  4227. };
  4228. Grid.prototype.processColumnsProcessors = function processColumnsProcessors(renderableColumns) {
  4229. var self = this;
  4230. // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order
  4231. var myRenderableColumns = renderableColumns.slice(0);
  4232. // Return myRenderableRows with no processing if we have no rows processors
  4233. if (self.columnsProcessors.length === 0) {
  4234. return $q.when(myRenderableColumns);
  4235. }
  4236. // Counter for iterating through rows processors
  4237. var i = 0;
  4238. // Promise for when we're done with all the processors
  4239. var finished = $q.defer();
  4240. // This function will call the processor in self.rowsProcessors at index 'i', and then
  4241. // when done will call the next processor in the list, using the output from the processor
  4242. // at i as the argument for 'renderedRowsToProcess' on the next iteration.
  4243. //
  4244. // If we're at the end of the list of processors, we resolve our 'finished' callback with
  4245. // the result.
  4246. function startProcessor(i, renderedColumnsToProcess) {
  4247. // Get the processor at 'i'
  4248. var processor = self.columnsProcessors[i].processor;
  4249. // Call the processor, passing in the rows to process and the current columns
  4250. // (note: it's wrapped in $q.when() in case the processor does not return a promise)
  4251. return $q.when( processor.call(self, renderedColumnsToProcess, self.rows) )
  4252. .then(function handleProcessedRows(processedColumns) {
  4253. // Check for errors
  4254. if (!processedColumns) {
  4255. throw "Processor at index " + i + " did not return a set of renderable rows";
  4256. }
  4257. if (!angular.isArray(processedColumns)) {
  4258. throw "Processor at index " + i + " did not return an array";
  4259. }
  4260. // Processor is done, increment the counter
  4261. i++;
  4262. // If we're not done with the processors, call the next one
  4263. if (i <= self.columnsProcessors.length - 1) {
  4264. return startProcessor(i, myRenderableColumns);
  4265. }
  4266. // We're done! Resolve the 'finished' promise
  4267. else {
  4268. finished.resolve(myRenderableColumns);
  4269. }
  4270. });
  4271. }
  4272. // Start on the first processor
  4273. startProcessor(0, myRenderableColumns);
  4274. return finished.promise;
  4275. };
  4276. Grid.prototype.setVisibleColumns = function setVisibleColumns(columns) {
  4277. // gridUtil.logDebug('setVisibleColumns');
  4278. var self = this;
  4279. // Reset all the render container row caches
  4280. for (var i in self.renderContainers) {
  4281. var container = self.renderContainers[i];
  4282. container.visibleColumnCache.length = 0;
  4283. }
  4284. for (var ci = 0; ci < columns.length; ci++) {
  4285. var column = columns[ci];
  4286. // If the column is visible
  4287. if (column.visible) {
  4288. // If the column has a container specified
  4289. if (typeof(column.renderContainer) !== 'undefined' && column.renderContainer) {
  4290. self.renderContainers[column.renderContainer].visibleColumnCache.push(column);
  4291. }
  4292. // If not, put it into the body container
  4293. else {
  4294. self.renderContainers.body.visibleColumnCache.push(column);
  4295. }
  4296. }
  4297. }
  4298. };
  4299. /**
  4300. * @ngdoc function
  4301. * @name handleWindowResize
  4302. * @methodOf ui.grid.class:Grid
  4303. * @description Triggered when the browser window resizes; automatically resizes the grid
  4304. */
  4305. Grid.prototype.handleWindowResize = function handleWindowResize($event) {
  4306. var self = this;
  4307. self.gridWidth = gridUtil.elementWidth(self.element);
  4308. self.gridHeight = gridUtil.elementHeight(self.element);
  4309. self.queueRefresh();
  4310. };
  4311. /**
  4312. * @ngdoc function
  4313. * @name queueRefresh
  4314. * @methodOf ui.grid.class:Grid
  4315. * @description queues a grid refreshCanvas, a way of debouncing all the refreshes we might otherwise issue
  4316. */
  4317. Grid.prototype.queueRefresh = function queueRefresh() {
  4318. var self = this;
  4319. if (self.refreshCanceller) {
  4320. $timeout.cancel(self.refreshCanceller);
  4321. }
  4322. self.refreshCanceller = $timeout(function () {
  4323. self.refreshCanvas(true);
  4324. });
  4325. self.refreshCanceller.then(function () {
  4326. self.refreshCanceller = null;
  4327. });
  4328. return self.refreshCanceller;
  4329. };
  4330. /**
  4331. * @ngdoc function
  4332. * @name queueGridRefresh
  4333. * @methodOf ui.grid.class:Grid
  4334. * @description queues a grid refresh, a way of debouncing all the refreshes we might otherwise issue
  4335. */
  4336. Grid.prototype.queueGridRefresh = function queueGridRefresh() {
  4337. var self = this;
  4338. if (self.gridRefreshCanceller) {
  4339. $timeout.cancel(self.gridRefreshCanceller);
  4340. }
  4341. self.gridRefreshCanceller = $timeout(function () {
  4342. self.refresh(true);
  4343. });
  4344. self.gridRefreshCanceller.then(function () {
  4345. self.gridRefreshCanceller = null;
  4346. });
  4347. return self.gridRefreshCanceller;
  4348. };
  4349. /**
  4350. * @ngdoc function
  4351. * @name updateCanvasHeight
  4352. * @methodOf ui.grid.class:Grid
  4353. * @description flags all render containers to update their canvas height
  4354. */
  4355. Grid.prototype.updateCanvasHeight = function updateCanvasHeight() {
  4356. var self = this;
  4357. for (var containerId in self.renderContainers) {
  4358. if (self.renderContainers.hasOwnProperty(containerId)) {
  4359. var container = self.renderContainers[containerId];
  4360. container.canvasHeightShouldUpdate = true;
  4361. }
  4362. }
  4363. };
  4364. /**
  4365. * @ngdoc function
  4366. * @name buildStyles
  4367. * @methodOf ui.grid.class:Grid
  4368. * @description calls each styleComputation function
  4369. */
  4370. // TODO: this used to take $scope, but couldn't see that it was used
  4371. Grid.prototype.buildStyles = function buildStyles() {
  4372. // gridUtil.logDebug('buildStyles');
  4373. var self = this;
  4374. self.customStyles = '';
  4375. self.styleComputations
  4376. .sort(function(a, b) {
  4377. if (a.priority === null) { return 1; }
  4378. if (b.priority === null) { return -1; }
  4379. if (a.priority === null && b.priority === null) { return 0; }
  4380. return a.priority - b.priority;
  4381. })
  4382. .forEach(function (compInfo) {
  4383. // this used to provide $scope as a second parameter, but I couldn't find any
  4384. // style builders that used it, so removed it as part of moving to grid from controller
  4385. var ret = compInfo.func.call(self);
  4386. if (angular.isString(ret)) {
  4387. self.customStyles += '\n' + ret;
  4388. }
  4389. });
  4390. };
  4391. Grid.prototype.minColumnsToRender = function minColumnsToRender() {
  4392. var self = this;
  4393. var viewport = this.getViewportWidth();
  4394. var min = 0;
  4395. var totalWidth = 0;
  4396. self.columns.forEach(function(col, i) {
  4397. if (totalWidth < viewport) {
  4398. totalWidth += col.drawnWidth;
  4399. min++;
  4400. }
  4401. else {
  4402. var currWidth = 0;
  4403. for (var j = i; j >= i - min; j--) {
  4404. currWidth += self.columns[j].drawnWidth;
  4405. }
  4406. if (currWidth < viewport) {
  4407. min++;
  4408. }
  4409. }
  4410. });
  4411. return min;
  4412. };
  4413. Grid.prototype.getBodyHeight = function getBodyHeight() {
  4414. // Start with the viewportHeight
  4415. var bodyHeight = this.getViewportHeight();
  4416. // Add the horizontal scrollbar height if there is one
  4417. //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) {
  4418. // bodyHeight = bodyHeight + this.horizontalScrollbarHeight;
  4419. //}
  4420. return bodyHeight;
  4421. };
  4422. // NOTE: viewport drawable height is the height of the grid minus the header row height (including any border)
  4423. // TODO(c0bra): account for footer height
  4424. Grid.prototype.getViewportHeight = function getViewportHeight() {
  4425. var self = this;
  4426. var viewPortHeight = this.gridHeight - this.headerHeight - this.footerHeight;
  4427. // Account for native horizontal scrollbar, if present
  4428. //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) {
  4429. // viewPortHeight = viewPortHeight - this.horizontalScrollbarHeight;
  4430. //}
  4431. var adjustment = self.getViewportAdjustment();
  4432. viewPortHeight = viewPortHeight + adjustment.height;
  4433. //gridUtil.logDebug('viewPortHeight', viewPortHeight);
  4434. return viewPortHeight;
  4435. };
  4436. Grid.prototype.getViewportWidth = function getViewportWidth() {
  4437. var self = this;
  4438. var viewPortWidth = this.gridWidth;
  4439. //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) {
  4440. // viewPortWidth = viewPortWidth - this.verticalScrollbarWidth;
  4441. //}
  4442. var adjustment = self.getViewportAdjustment();
  4443. viewPortWidth = viewPortWidth + adjustment.width;
  4444. //gridUtil.logDebug('getviewPortWidth', viewPortWidth);
  4445. return viewPortWidth;
  4446. };
  4447. Grid.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() {
  4448. var viewPortWidth = this.getViewportWidth();
  4449. //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) {
  4450. // viewPortWidth = viewPortWidth + this.verticalScrollbarWidth;
  4451. //}
  4452. return viewPortWidth;
  4453. };
  4454. Grid.prototype.addVerticalScrollSync = function (containerId, callBackFn) {
  4455. this.verticalScrollSyncCallBackFns[containerId] = callBackFn;
  4456. };
  4457. Grid.prototype.addHorizontalScrollSync = function (containerId, callBackFn) {
  4458. this.horizontalScrollSyncCallBackFns[containerId] = callBackFn;
  4459. };
  4460. /**
  4461. * Scroll needed containers by calling their ScrollSyncs
  4462. * @param sourceContainerId the containerId that has already set it's top/left.
  4463. * can be empty string which means all containers need to set top/left
  4464. * @param scrollEvent
  4465. */
  4466. Grid.prototype.scrollContainers = function (sourceContainerId, scrollEvent) {
  4467. if (scrollEvent.y) {
  4468. //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left)
  4469. var verts = ['body','left', 'right'];
  4470. this.flagScrollingVertically(scrollEvent);
  4471. if (sourceContainerId === 'body') {
  4472. verts = ['left', 'right'];
  4473. }
  4474. else if (sourceContainerId === 'left') {
  4475. verts = ['body', 'right'];
  4476. }
  4477. else if (sourceContainerId === 'right') {
  4478. verts = ['body', 'left'];
  4479. }
  4480. for (var i = 0; i < verts.length; i++) {
  4481. var id = verts[i];
  4482. if (this.verticalScrollSyncCallBackFns[id]) {
  4483. this.verticalScrollSyncCallBackFns[id](scrollEvent);
  4484. }
  4485. }
  4486. }
  4487. if (scrollEvent.x) {
  4488. //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left)
  4489. var horizs = ['body','bodyheader', 'bodyfooter'];
  4490. this.flagScrollingHorizontally(scrollEvent);
  4491. if (sourceContainerId === 'body') {
  4492. horizs = ['bodyheader', 'bodyfooter'];
  4493. }
  4494. for (var j = 0; j < horizs.length; j++) {
  4495. var idh = horizs[j];
  4496. if (this.horizontalScrollSyncCallBackFns[idh]) {
  4497. this.horizontalScrollSyncCallBackFns[idh](scrollEvent);
  4498. }
  4499. }
  4500. }
  4501. };
  4502. Grid.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) {
  4503. this.viewportAdjusters.push(func);
  4504. };
  4505. Grid.prototype.removeViewportAdjuster = function registerViewportAdjuster(func) {
  4506. var idx = this.viewportAdjusters.indexOf(func);
  4507. if (typeof(idx) !== 'undefined' && idx !== undefined) {
  4508. this.viewportAdjusters.splice(idx, 1);
  4509. }
  4510. };
  4511. Grid.prototype.getViewportAdjustment = function getViewportAdjustment() {
  4512. var self = this;
  4513. var adjustment = { height: 0, width: 0 };
  4514. self.viewportAdjusters.forEach(function (func) {
  4515. adjustment = func.call(this, adjustment);
  4516. });
  4517. return adjustment;
  4518. };
  4519. Grid.prototype.getVisibleRowCount = function getVisibleRowCount() {
  4520. // var count = 0;
  4521. // this.rows.forEach(function (row) {
  4522. // if (row.visible) {
  4523. // count++;
  4524. // }
  4525. // });
  4526. // return this.visibleRowCache.length;
  4527. return this.renderContainers.body.visibleRowCache.length;
  4528. };
  4529. Grid.prototype.getVisibleRows = function getVisibleRows() {
  4530. return this.renderContainers.body.visibleRowCache;
  4531. };
  4532. Grid.prototype.getVisibleColumnCount = function getVisibleColumnCount() {
  4533. // var count = 0;
  4534. // this.rows.forEach(function (row) {
  4535. // if (row.visible) {
  4536. // count++;
  4537. // }
  4538. // });
  4539. // return this.visibleRowCache.length;
  4540. return this.renderContainers.body.visibleColumnCache.length;
  4541. };
  4542. Grid.prototype.searchRows = function searchRows(renderableRows) {
  4543. return rowSearcher.search(this, renderableRows, this.columns);
  4544. };
  4545. Grid.prototype.sortByColumn = function sortByColumn(renderableRows) {
  4546. return rowSorter.sort(this, renderableRows, this.columns);
  4547. };
  4548. /**
  4549. * @ngdoc function
  4550. * @name getCellValue
  4551. * @methodOf ui.grid.class:Grid
  4552. * @description Gets the value of a cell for a particular row and column
  4553. * @param {GridRow} row Row to access
  4554. * @param {GridColumn} col Column to access
  4555. */
  4556. Grid.prototype.getCellValue = function getCellValue(row, col){
  4557. if ( typeof(row.entity[ '$$' + col.uid ]) !== 'undefined' ) {
  4558. return row.entity[ '$$' + col.uid].rendered;
  4559. } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined' ){
  4560. return row.entity[col.field];
  4561. } else {
  4562. if (!col.cellValueGetterCache) {
  4563. col.cellValueGetterCache = $parse(row.getEntityQualifiedColField(col));
  4564. }
  4565. return col.cellValueGetterCache(row);
  4566. }
  4567. };
  4568. /**
  4569. * @ngdoc function
  4570. * @name getCellDisplayValue
  4571. * @methodOf ui.grid.class:Grid
  4572. * @description Gets the displayed value of a cell after applying any the `cellFilter`
  4573. * @param {GridRow} row Row to access
  4574. * @param {GridColumn} col Column to access
  4575. */
  4576. Grid.prototype.getCellDisplayValue = function getCellDisplayValue(row, col) {
  4577. if ( !col.cellDisplayGetterCache ) {
  4578. var custom_filter = col.cellFilter ? " | " + col.cellFilter : "";
  4579. if (typeof(row.entity['$$' + col.uid]) !== 'undefined') {
  4580. col.cellDisplayGetterCache = $parse(row.entity['$$' + col.uid].rendered + custom_filter);
  4581. } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined') {
  4582. col.cellDisplayGetterCache = $parse(row.entity[col.field] + custom_filter);
  4583. } else {
  4584. col.cellDisplayGetterCache = $parse(row.getEntityQualifiedColField(col) + custom_filter);
  4585. }
  4586. }
  4587. return col.cellDisplayGetterCache(row);
  4588. };
  4589. Grid.prototype.getNextColumnSortPriority = function getNextColumnSortPriority() {
  4590. var self = this,
  4591. p = 0;
  4592. self.columns.forEach(function (col) {
  4593. if (col.sort && col.sort.priority && col.sort.priority > p) {
  4594. p = col.sort.priority;
  4595. }
  4596. });
  4597. return p + 1;
  4598. };
  4599. /**
  4600. * @ngdoc function
  4601. * @name resetColumnSorting
  4602. * @methodOf ui.grid.class:Grid
  4603. * @description Return the columns that the grid is currently being sorted by
  4604. * @param {GridColumn} [excludedColumn] Optional GridColumn to exclude from having its sorting reset
  4605. */
  4606. Grid.prototype.resetColumnSorting = function resetColumnSorting(excludeCol) {
  4607. var self = this;
  4608. self.columns.forEach(function (col) {
  4609. if (col !== excludeCol && !col.suppressRemoveSort) {
  4610. col.sort = {};
  4611. }
  4612. });
  4613. };
  4614. /**
  4615. * @ngdoc function
  4616. * @name getColumnSorting
  4617. * @methodOf ui.grid.class:Grid
  4618. * @description Return the columns that the grid is currently being sorted by
  4619. * @returns {Array[GridColumn]} An array of GridColumn objects
  4620. */
  4621. Grid.prototype.getColumnSorting = function getColumnSorting() {
  4622. var self = this;
  4623. var sortedCols = [], myCols;
  4624. // Iterate through all the columns, sorted by priority
  4625. // Make local copy of column list, because sorting is in-place and we do not want to
  4626. // change the original sequence of columns
  4627. myCols = self.columns.slice(0);
  4628. myCols.sort(rowSorter.prioritySort).forEach(function (col) {
  4629. if (col.sort && typeof(col.sort.direction) !== 'undefined' && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) {
  4630. sortedCols.push(col);
  4631. }
  4632. });
  4633. return sortedCols;
  4634. };
  4635. /**
  4636. * @ngdoc function
  4637. * @name sortColumn
  4638. * @methodOf ui.grid.class:Grid
  4639. * @description Set the sorting on a given column, optionally resetting any existing sorting on the Grid.
  4640. * Emits the sortChanged event whenever the sort criteria are changed.
  4641. * @param {GridColumn} column Column to set the sorting on
  4642. * @param {uiGridConstants.ASC|uiGridConstants.DESC} [direction] Direction to sort by, either descending or ascending.
  4643. * If not provided, the column will iterate through the sort directions: ascending, descending, unsorted.
  4644. * @param {boolean} [add] Add this column to the sorting. If not provided or set to `false`, the Grid will reset any existing sorting and sort
  4645. * by this column only
  4646. * @returns {Promise} A resolved promise that supplies the column.
  4647. */
  4648. Grid.prototype.sortColumn = function sortColumn(column, directionOrAdd, add) {
  4649. var self = this,
  4650. direction = null;
  4651. if (typeof(column) === 'undefined' || !column) {
  4652. throw new Error('No column parameter provided');
  4653. }
  4654. // Second argument can either be a direction or whether to add this column to the existing sort.
  4655. // If it's a boolean, it's an add, otherwise, it's a direction
  4656. if (typeof(directionOrAdd) === 'boolean') {
  4657. add = directionOrAdd;
  4658. }
  4659. else {
  4660. direction = directionOrAdd;
  4661. }
  4662. if (!add) {
  4663. self.resetColumnSorting(column);
  4664. column.sort.priority = 0;
  4665. // Get the actual priority since there may be columns which have suppressRemoveSort set
  4666. column.sort.priority = self.getNextColumnSortPriority();
  4667. }
  4668. else if (!column.sort.priority){
  4669. column.sort.priority = self.getNextColumnSortPriority();
  4670. }
  4671. if (!direction) {
  4672. // Figure out the sort direction
  4673. if (column.sort.direction && column.sort.direction === uiGridConstants.ASC) {
  4674. column.sort.direction = uiGridConstants.DESC;
  4675. }
  4676. else if (column.sort.direction && column.sort.direction === uiGridConstants.DESC) {
  4677. if ( column.colDef && column.suppressRemoveSort ){
  4678. column.sort.direction = uiGridConstants.ASC;
  4679. } else {
  4680. column.sort = {};
  4681. }
  4682. }
  4683. else {
  4684. column.sort.direction = uiGridConstants.ASC;
  4685. }
  4686. }
  4687. else {
  4688. column.sort.direction = direction;
  4689. }
  4690. self.api.core.raise.sortChanged( self, self.getColumnSorting() );
  4691. return $q.when(column);
  4692. };
  4693. /**
  4694. * communicate to outside world that we are done with initial rendering
  4695. */
  4696. Grid.prototype.renderingComplete = function(){
  4697. if (angular.isFunction(this.options.onRegisterApi)) {
  4698. this.options.onRegisterApi(this.api);
  4699. }
  4700. this.api.core.raise.renderingComplete( this.api );
  4701. };
  4702. Grid.prototype.createRowHashMap = function createRowHashMap() {
  4703. var self = this;
  4704. var hashMap = new RowHashMap();
  4705. hashMap.grid = self;
  4706. return hashMap;
  4707. };
  4708. /**
  4709. * @ngdoc function
  4710. * @name refresh
  4711. * @methodOf ui.grid.class:Grid
  4712. * @description Refresh the rendered grid on screen.
  4713. * @param {boolean} [rowsAltered] Optional flag for refreshing when the number of rows has changed.
  4714. */
  4715. Grid.prototype.refresh = function refresh(rowsAltered) {
  4716. var self = this;
  4717. var p1 = self.processRowsProcessors(self.rows).then(function (renderableRows) {
  4718. self.setVisibleRows(renderableRows);
  4719. });
  4720. var p2 = self.processColumnsProcessors(self.columns).then(function (renderableColumns) {
  4721. self.setVisibleColumns(renderableColumns);
  4722. });
  4723. return $q.all([p1, p2]).then(function () {
  4724. self.redrawInPlace(rowsAltered);
  4725. self.refreshCanvas(true);
  4726. });
  4727. };
  4728. /**
  4729. * @ngdoc function
  4730. * @name refreshRows
  4731. * @methodOf ui.grid.class:Grid
  4732. * @description Refresh the rendered rows on screen? Note: not functional at present
  4733. * @returns {promise} promise that is resolved when render completes?
  4734. *
  4735. */
  4736. Grid.prototype.refreshRows = function refreshRows() {
  4737. var self = this;
  4738. return self.processRowsProcessors(self.rows)
  4739. .then(function (renderableRows) {
  4740. self.setVisibleRows(renderableRows);
  4741. self.redrawInPlace();
  4742. self.refreshCanvas( true );
  4743. });
  4744. };
  4745. /**
  4746. * @ngdoc function
  4747. * @name refreshCanvas
  4748. * @methodOf ui.grid.class:Grid
  4749. * @description Builds all styles and recalculates much of the grid sizing
  4750. * @param {object} buildStyles optional parameter. Use TBD
  4751. * @returns {promise} promise that is resolved when the canvas
  4752. * has been refreshed
  4753. *
  4754. */
  4755. Grid.prototype.refreshCanvas = function(buildStyles) {
  4756. var self = this;
  4757. if (buildStyles) {
  4758. self.buildStyles();
  4759. }
  4760. var p = $q.defer();
  4761. // Get all the header heights
  4762. var containerHeadersToRecalc = [];
  4763. for (var containerId in self.renderContainers) {
  4764. if (self.renderContainers.hasOwnProperty(containerId)) {
  4765. var container = self.renderContainers[containerId];
  4766. // Skip containers that have no canvasWidth set yet
  4767. if (container.canvasWidth === null || isNaN(container.canvasWidth)) {
  4768. continue;
  4769. }
  4770. if (container.header || container.headerCanvas) {
  4771. container.explicitHeaderHeight = container.explicitHeaderHeight || null;
  4772. container.explicitHeaderCanvasHeight = container.explicitHeaderCanvasHeight || null;
  4773. containerHeadersToRecalc.push(container);
  4774. }
  4775. }
  4776. }
  4777. /*
  4778. *
  4779. * Here we loop through the headers, measuring each element as well as any header "canvas" it has within it.
  4780. *
  4781. * If any header is less than the largest header height, it will be resized to that so that we don't have headers
  4782. * with different heights, which looks like a rendering problem
  4783. *
  4784. * We'll do the same thing with the header canvases, and give the header CELLS an explicit height if their canvas
  4785. * is smaller than the largest canvas height. That was header cells without extra controls like filtering don't
  4786. * appear shorter than other cells.
  4787. *
  4788. */
  4789. if (containerHeadersToRecalc.length > 0) {
  4790. // Build the styles without the explicit header heights
  4791. if (buildStyles) {
  4792. self.buildStyles();
  4793. }
  4794. // Putting in a timeout as it's not calculating after the grid element is rendered and filled out
  4795. $timeout(function() {
  4796. // var oldHeaderHeight = self.grid.headerHeight;
  4797. // self.grid.headerHeight = gridUtil.outerElementHeight(self.header);
  4798. var rebuildStyles = false;
  4799. // Get all the header heights
  4800. var maxHeaderHeight = 0;
  4801. var maxHeaderCanvasHeight = 0;
  4802. var i, container;
  4803. var getHeight = function(oldVal, newVal){
  4804. if ( oldVal !== newVal){
  4805. rebuildStyles = true;
  4806. }
  4807. return newVal;
  4808. };
  4809. for (i = 0; i < containerHeadersToRecalc.length; i++) {
  4810. container = containerHeadersToRecalc[i];
  4811. // Skip containers that have no canvasWidth set yet
  4812. if (container.canvasWidth === null || isNaN(container.canvasWidth)) {
  4813. continue;
  4814. }
  4815. if (container.header) {
  4816. var headerHeight = container.headerHeight = getHeight(container.headerHeight, parseInt(gridUtil.outerElementHeight(container.header), 10));
  4817. // Get the "inner" header height, that is the height minus the top and bottom borders, if present. We'll use it to make sure all the headers have a consistent height
  4818. var topBorder = gridUtil.getBorderSize(container.header, 'top');
  4819. var bottomBorder = gridUtil.getBorderSize(container.header, 'bottom');
  4820. var innerHeaderHeight = parseInt(headerHeight - topBorder - bottomBorder, 10);
  4821. innerHeaderHeight = innerHeaderHeight < 0 ? 0 : innerHeaderHeight;
  4822. container.innerHeaderHeight = innerHeaderHeight;
  4823. // If the header doesn't have an explicit height set, save the largest header height for use later
  4824. // Explicit header heights are based off of the max we are calculating here. We never want to base the max on something we're setting explicitly
  4825. if (!container.explicitHeaderHeight && innerHeaderHeight > maxHeaderHeight) {
  4826. maxHeaderHeight = innerHeaderHeight;
  4827. }
  4828. }
  4829. if (container.headerCanvas) {
  4830. var headerCanvasHeight = container.headerCanvasHeight = getHeight(container.headerCanvasHeight, parseInt(gridUtil.outerElementHeight(container.headerCanvas), 10));
  4831. // If the header doesn't have an explicit canvas height, save the largest header canvas height for use later
  4832. // Explicit header heights are based off of the max we are calculating here. We never want to base the max on something we're setting explicitly
  4833. if (!container.explicitHeaderCanvasHeight && headerCanvasHeight > maxHeaderCanvasHeight) {
  4834. maxHeaderCanvasHeight = headerCanvasHeight;
  4835. }
  4836. }
  4837. }
  4838. // Go through all the headers
  4839. for (i = 0; i < containerHeadersToRecalc.length; i++) {
  4840. container = containerHeadersToRecalc[i];
  4841. /* If:
  4842. 1. We have a max header height
  4843. 2. This container has a header height defined
  4844. 3. And either this container has an explicit header height set, OR its header height is less than the max
  4845. then:
  4846. Give this container's header an explicit height so it will line up with the tallest header
  4847. */
  4848. if (
  4849. maxHeaderHeight > 0 && typeof(container.headerHeight) !== 'undefined' && container.headerHeight !== null &&
  4850. (container.explicitHeaderHeight || container.headerHeight < maxHeaderHeight)
  4851. ) {
  4852. container.explicitHeaderHeight = getHeight(container.explicitHeaderHeight, maxHeaderHeight);
  4853. }
  4854. // Do the same as above except for the header canvas
  4855. if (
  4856. maxHeaderCanvasHeight > 0 && typeof(container.headerCanvasHeight) !== 'undefined' && container.headerCanvasHeight !== null &&
  4857. (container.explicitHeaderCanvasHeight || container.headerCanvasHeight < maxHeaderCanvasHeight)
  4858. ) {
  4859. container.explicitHeaderCanvasHeight = getHeight(container.explicitHeaderCanvasHeight, maxHeaderCanvasHeight);
  4860. }
  4861. }
  4862. // Rebuild styles if the header height has changed
  4863. // The header height is used in body/viewport calculations and those are then used in other styles so we need it to be available
  4864. if (buildStyles && rebuildStyles) {
  4865. self.buildStyles();
  4866. }
  4867. p.resolve();
  4868. });
  4869. }
  4870. else {
  4871. // Timeout still needs to be here to trigger digest after styles have been rebuilt
  4872. $timeout(function() {
  4873. p.resolve();
  4874. });
  4875. }
  4876. return p.promise;
  4877. };
  4878. /**
  4879. * @ngdoc function
  4880. * @name redrawCanvas
  4881. * @methodOf ui.grid.class:Grid
  4882. * @description Redraw the rows and columns based on our current scroll position
  4883. * @param {boolean} [rowsAdded] Optional to indicate rows are added and the scroll percentage must be recalculated
  4884. *
  4885. */
  4886. Grid.prototype.redrawInPlace = function redrawInPlace(rowsAdded) {
  4887. // gridUtil.logDebug('redrawInPlace');
  4888. var self = this;
  4889. for (var i in self.renderContainers) {
  4890. var container = self.renderContainers[i];
  4891. // gridUtil.logDebug('redrawing container', i);
  4892. if (rowsAdded) {
  4893. container.adjustRows(container.prevScrollTop, null);
  4894. container.adjustColumns(container.prevScrollLeft, null);
  4895. }
  4896. else {
  4897. container.adjustRows(null, container.prevScrolltopPercentage);
  4898. container.adjustColumns(null, container.prevScrollleftPercentage);
  4899. }
  4900. }
  4901. };
  4902. /**
  4903. * @ngdoc function
  4904. * @name hasLeftContainerColumns
  4905. * @methodOf ui.grid.class:Grid
  4906. * @description returns true if leftContainer has columns
  4907. */
  4908. Grid.prototype.hasLeftContainerColumns = function () {
  4909. return this.hasLeftContainer() && this.renderContainers.left.renderedColumns.length > 0;
  4910. };
  4911. /**
  4912. * @ngdoc function
  4913. * @name hasRightContainerColumns
  4914. * @methodOf ui.grid.class:Grid
  4915. * @description returns true if rightContainer has columns
  4916. */
  4917. Grid.prototype.hasRightContainerColumns = function () {
  4918. return this.hasRightContainer() && this.renderContainers.right.renderedColumns.length > 0;
  4919. };
  4920. /**
  4921. * @ngdoc method
  4922. * @methodOf ui.grid.class:Grid
  4923. * @name scrollToIfNecessary
  4924. * @description Scrolls the grid to make a certain row and column combo visible,
  4925. * in the case that it is not completely visible on the screen already.
  4926. * @param {GridRow} gridRow row to make visible
  4927. * @param {GridCol} gridCol column to make visible
  4928. * @returns {promise} a promise that is resolved when scrolling is complete
  4929. */
  4930. Grid.prototype.scrollToIfNecessary = function (gridRow, gridCol) {
  4931. var self = this;
  4932. var scrollEvent = new ScrollEvent(self, 'uiGrid.scrollToIfNecessary');
  4933. // Alias the visible row and column caches
  4934. var visRowCache = self.renderContainers.body.visibleRowCache;
  4935. var visColCache = self.renderContainers.body.visibleColumnCache;
  4936. /*-- Get the top, left, right, and bottom "scrolled" edges of the grid --*/
  4937. // The top boundary is the current Y scroll position PLUS the header height, because the header can obscure rows when the grid is scrolled downwards
  4938. var topBound = self.renderContainers.body.prevScrollTop + self.headerHeight;
  4939. // Don't the let top boundary be less than 0
  4940. topBound = (topBound < 0) ? 0 : topBound;
  4941. // The left boundary is the current X scroll position
  4942. var leftBound = self.renderContainers.body.prevScrollLeft;
  4943. // The bottom boundary is the current Y scroll position, plus the height of the grid, but minus the header height.
  4944. // Basically this is the viewport height added on to the scroll position
  4945. var bottomBound = self.renderContainers.body.prevScrollTop + self.gridHeight - self.renderContainers.body.headerHeight - self.footerHeight - self.scrollbarWidth;
  4946. // If there's a horizontal scrollbar, remove its height from the bottom boundary, otherwise we'll be letting it obscure rows
  4947. //if (self.horizontalScrollbarHeight) {
  4948. // bottomBound = bottomBound - self.horizontalScrollbarHeight;
  4949. //}
  4950. // The right position is the current X scroll position minus the grid width
  4951. var rightBound = self.renderContainers.body.prevScrollLeft + Math.ceil(self.gridWidth);
  4952. // If there's a vertical scrollbar, subtract it from the right boundary or we'll allow it to obscure cells
  4953. //if (self.verticalScrollbarWidth) {
  4954. // rightBound = rightBound - self.verticalScrollbarWidth;
  4955. //}
  4956. // We were given a row to scroll to
  4957. if (gridRow !== null) {
  4958. // This is the index of the row we want to scroll to, within the list of rows that can be visible
  4959. var seekRowIndex = visRowCache.indexOf(gridRow);
  4960. // Total vertical scroll length of the grid
  4961. var scrollLength = (self.renderContainers.body.getCanvasHeight() - self.renderContainers.body.getViewportHeight());
  4962. // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row
  4963. //if (self.horizontalScrollbarHeight && self.horizontalScrollbarHeight > 0) {
  4964. // scrollLength = scrollLength + self.horizontalScrollbarHeight;
  4965. //}
  4966. // This is the minimum amount of pixels we need to scroll vertical in order to see this row.
  4967. var pixelsToSeeRow = ((seekRowIndex + 1) * self.options.rowHeight);
  4968. // Don't let the pixels required to see the row be less than zero
  4969. pixelsToSeeRow = (pixelsToSeeRow < 0) ? 0 : pixelsToSeeRow;
  4970. var scrollPixels, percentage;
  4971. // If the scroll position we need to see the row is LESS than the top boundary, i.e. obscured above the top of the self...
  4972. if (pixelsToSeeRow < topBound) {
  4973. // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\
  4974. // to get the full position we need
  4975. scrollPixels = self.renderContainers.body.prevScrollTop - (topBound - pixelsToSeeRow);
  4976. // Turn the scroll position into a percentage and make it an argument for a scroll event
  4977. percentage = scrollPixels / scrollLength;
  4978. scrollEvent.y = { percentage: percentage };
  4979. }
  4980. // Otherwise if the scroll position we need to see the row is MORE than the bottom boundary, i.e. obscured below the bottom of the self...
  4981. else if (pixelsToSeeRow > bottomBound) {
  4982. // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position
  4983. // to get the full position we need
  4984. scrollPixels = pixelsToSeeRow - bottomBound + self.renderContainers.body.prevScrollTop;
  4985. // Turn the scroll position into a percentage and make it an argument for a scroll event
  4986. percentage = scrollPixels / scrollLength;
  4987. scrollEvent.y = { percentage: percentage };
  4988. }
  4989. }
  4990. // We were given a column to scroll to
  4991. if (gridCol !== null) {
  4992. // This is the index of the row we want to scroll to, within the list of rows that can be visible
  4993. var seekColumnIndex = visColCache.indexOf(gridCol);
  4994. // Total vertical scroll length of the grid
  4995. var horizScrollLength = (self.renderContainers.body.getCanvasWidth() - self.renderContainers.body.getViewportWidth());
  4996. // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row
  4997. // if (self.verticalScrollbarWidth && self.verticalScrollbarWidth > 0) {
  4998. // horizScrollLength = horizScrollLength + self.verticalScrollbarWidth;
  4999. // }
  5000. // This is the minimum amount of pixels we need to scroll vertical in order to see this column
  5001. var columnLeftEdge = 0;
  5002. for (var i = 0; i < seekColumnIndex; i++) {
  5003. var col = visColCache[i];
  5004. columnLeftEdge += col.drawnWidth;
  5005. }
  5006. columnLeftEdge = (columnLeftEdge < 0) ? 0 : columnLeftEdge;
  5007. var columnRightEdge = columnLeftEdge + gridCol.drawnWidth;
  5008. // Don't let the pixels required to see the column be less than zero
  5009. columnRightEdge = (columnRightEdge < 0) ? 0 : columnRightEdge;
  5010. var horizScrollPixels, horizPercentage;
  5011. // If the scroll position we need to see the row is LESS than the top boundary, i.e. obscured above the top of the self...
  5012. if (columnLeftEdge < leftBound) {
  5013. // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\
  5014. // to get the full position we need
  5015. horizScrollPixels = self.renderContainers.body.prevScrollLeft - (leftBound - columnLeftEdge);
  5016. // Turn the scroll position into a percentage and make it an argument for a scroll event
  5017. horizPercentage = horizScrollPixels / horizScrollLength;
  5018. horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage;
  5019. scrollEvent.x = { percentage: horizPercentage };
  5020. }
  5021. // Otherwise if the scroll position we need to see the row is MORE than the bottom boundary, i.e. obscured below the bottom of the self...
  5022. else if (columnRightEdge > rightBound) {
  5023. // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position
  5024. // to get the full position we need
  5025. horizScrollPixels = columnRightEdge - rightBound + self.renderContainers.body.prevScrollLeft;
  5026. // Turn the scroll position into a percentage and make it an argument for a scroll event
  5027. horizPercentage = horizScrollPixels / horizScrollLength;
  5028. horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage;
  5029. scrollEvent.x = { percentage: horizPercentage };
  5030. }
  5031. }
  5032. var deferred = $q.defer();
  5033. // If we need to scroll on either the x or y axes, fire a scroll event
  5034. if (scrollEvent.y || scrollEvent.x) {
  5035. scrollEvent.withDelay = false;
  5036. self.scrollContainers('',scrollEvent);
  5037. var dereg = self.api.core.on.scrollEnd(null,function() {
  5038. deferred.resolve(scrollEvent);
  5039. dereg();
  5040. });
  5041. }
  5042. else {
  5043. deferred.resolve();
  5044. }
  5045. return deferred.promise;
  5046. };
  5047. /**
  5048. * @ngdoc method
  5049. * @methodOf ui.grid.class:Grid
  5050. * @name scrollTo
  5051. * @description Scroll the grid such that the specified
  5052. * row and column is in view
  5053. * @param {object} rowEntity gridOptions.data[] array instance to make visible
  5054. * @param {object} colDef to make visible
  5055. * @returns {promise} a promise that is resolved after any scrolling is finished
  5056. */
  5057. Grid.prototype.scrollTo = function (rowEntity, colDef) {
  5058. var gridRow = null, gridCol = null;
  5059. if (rowEntity !== null && typeof(rowEntity) !== 'undefined' ) {
  5060. gridRow = this.getRow(rowEntity);
  5061. }
  5062. if (colDef !== null && typeof(colDef) !== 'undefined' ) {
  5063. gridCol = this.getColumn(colDef.name ? colDef.name : colDef.field);
  5064. }
  5065. return this.scrollToIfNecessary(gridRow, gridCol);
  5066. };
  5067. /**
  5068. * @ngdoc function
  5069. * @name clearAllFilters
  5070. * @methodOf ui.grid.class:Grid
  5071. * @description Clears all filters and optionally refreshes the visible rows.
  5072. * @param {object} refreshRows Defaults to true.
  5073. * @param {object} clearConditions Defaults to false.
  5074. * @param {object} clearFlags Defaults to false.
  5075. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing.
  5076. */
  5077. Grid.prototype.clearAllFilters = function clearAllFilters(refreshRows, clearConditions, clearFlags) {
  5078. // Default `refreshRows` to true because it will be the most commonly desired behaviour.
  5079. if (refreshRows === undefined) {
  5080. refreshRows = true;
  5081. }
  5082. if (clearConditions === undefined) {
  5083. clearConditions = false;
  5084. }
  5085. if (clearFlags === undefined) {
  5086. clearFlags = false;
  5087. }
  5088. this.columns.forEach(function(column) {
  5089. column.filters.forEach(function(filter) {
  5090. filter.term = undefined;
  5091. if (clearConditions) {
  5092. filter.condition = undefined;
  5093. }
  5094. if (clearFlags) {
  5095. filter.flags = undefined;
  5096. }
  5097. });
  5098. });
  5099. if (refreshRows) {
  5100. return this.refreshRows();
  5101. }
  5102. };
  5103. // Blatantly stolen from Angular as it isn't exposed (yet? 2.0?)
  5104. function RowHashMap() {}
  5105. RowHashMap.prototype = {
  5106. /**
  5107. * Store key value pair
  5108. * @param key key to store can be any type
  5109. * @param value value to store can be any type
  5110. */
  5111. put: function(key, value) {
  5112. this[this.grid.options.rowIdentity(key)] = value;
  5113. },
  5114. /**
  5115. * @param key
  5116. * @returns {Object} the value for the key
  5117. */
  5118. get: function(key) {
  5119. return this[this.grid.options.rowIdentity(key)];
  5120. },
  5121. /**
  5122. * Remove the key/value pair
  5123. * @param key
  5124. */
  5125. remove: function(key) {
  5126. var value = this[key = this.grid.options.rowIdentity(key)];
  5127. delete this[key];
  5128. return value;
  5129. }
  5130. };
  5131. return Grid;
  5132. }]);
  5133. })();
  5134. (function () {
  5135. angular.module('ui.grid')
  5136. .factory('GridApi', ['$q', '$rootScope', 'gridUtil', 'uiGridConstants', 'GridRow', 'uiGridGridMenuService',
  5137. function ($q, $rootScope, gridUtil, uiGridConstants, GridRow, uiGridGridMenuService) {
  5138. /**
  5139. * @ngdoc function
  5140. * @name ui.grid.class:GridApi
  5141. * @description GridApi provides the ability to register public methods events inside the grid and allow
  5142. * for other components to use the api via featureName.raise.methodName and featureName.on.eventName(function(args){}.
  5143. * <br/>
  5144. * To listen to events, you must add a callback to gridOptions.onRegisterApi
  5145. * <pre>
  5146. * $scope.gridOptions.onRegisterApi = function(gridApi){
  5147. * gridApi.cellNav.on.navigate($scope,function(newRowCol, oldRowCol){
  5148. * $log.log('navigation event');
  5149. * });
  5150. * };
  5151. * </pre>
  5152. * @param {object} grid grid that owns api
  5153. */
  5154. var GridApi = function GridApi(grid) {
  5155. this.grid = grid;
  5156. this.listeners = [];
  5157. /**
  5158. * @ngdoc function
  5159. * @name renderingComplete
  5160. * @methodOf ui.grid.core.api:PublicApi
  5161. * @description Rendering is complete, called at the same
  5162. * time as `onRegisterApi`, but provides a way to obtain
  5163. * that same event within features without stopping end
  5164. * users from getting at the onRegisterApi method.
  5165. *
  5166. * Included in gridApi so that it's always there - otherwise
  5167. * there is still a timing problem with when a feature can
  5168. * call this.
  5169. *
  5170. * @param {GridApi} gridApi the grid api, as normally
  5171. * returned in the onRegisterApi method
  5172. *
  5173. * @example
  5174. * <pre>
  5175. * gridApi.core.on.renderingComplete( grid );
  5176. * </pre>
  5177. */
  5178. this.registerEvent( 'core', 'renderingComplete' );
  5179. /**
  5180. * @ngdoc event
  5181. * @name filterChanged
  5182. * @eventOf ui.grid.core.api:PublicApi
  5183. * @description is raised after the filter is changed. The nature
  5184. * of the watch expression doesn't allow notification of what changed,
  5185. * so the receiver of this event will need to re-extract the filter
  5186. * conditions from the columns.
  5187. *
  5188. */
  5189. this.registerEvent( 'core', 'filterChanged' );
  5190. /**
  5191. * @ngdoc function
  5192. * @name setRowInvisible
  5193. * @methodOf ui.grid.core.api:PublicApi
  5194. * @description Sets an override on the row to make it always invisible,
  5195. * which will override any filtering or other visibility calculations.
  5196. * If the row is currently visible then sets it to invisible and calls
  5197. * both grid refresh and emits the rowsVisibleChanged event
  5198. * @param {object} rowEntity gridOptions.data[] array instance
  5199. */
  5200. this.registerMethod( 'core', 'setRowInvisible', GridRow.prototype.setRowInvisible );
  5201. /**
  5202. * @ngdoc function
  5203. * @name clearRowInvisible
  5204. * @methodOf ui.grid.core.api:PublicApi
  5205. * @description Clears any override on visibility for the row so that it returns to
  5206. * using normal filtering and other visibility calculations.
  5207. * If the row is currently invisible then sets it to visible and calls
  5208. * both grid refresh and emits the rowsVisibleChanged event
  5209. * TODO: if a filter is active then we can't just set it to visible?
  5210. * @param {object} rowEntity gridOptions.data[] array instance
  5211. */
  5212. this.registerMethod( 'core', 'clearRowInvisible', GridRow.prototype.clearRowInvisible );
  5213. /**
  5214. * @ngdoc function
  5215. * @name getVisibleRows
  5216. * @methodOf ui.grid.core.api:PublicApi
  5217. * @description Returns all visible rows
  5218. * @param {Grid} grid the grid you want to get visible rows from
  5219. * @returns {array} an array of gridRow
  5220. */
  5221. this.registerMethod( 'core', 'getVisibleRows', this.grid.getVisibleRows );
  5222. /**
  5223. * @ngdoc event
  5224. * @name rowsVisibleChanged
  5225. * @eventOf ui.grid.core.api:PublicApi
  5226. * @description is raised after the rows that are visible
  5227. * change. The filtering is zero-based, so it isn't possible
  5228. * to say which rows changed (unlike in the selection feature).
  5229. * We can plausibly know which row was changed when setRowInvisible
  5230. * is called, but in that situation the user already knows which row
  5231. * they changed. When a filter runs we don't know what changed,
  5232. * and that is the one that would have been useful.
  5233. *
  5234. */
  5235. this.registerEvent( 'core', 'rowsVisibleChanged' );
  5236. /**
  5237. * @ngdoc event
  5238. * @name rowsRendered
  5239. * @eventOf ui.grid.core.api:PublicApi
  5240. * @description is raised after the cache of visible rows is changed.
  5241. */
  5242. this.registerEvent( 'core', 'rowsRendered' );
  5243. /**
  5244. * @ngdoc event
  5245. * @name scrollBegin
  5246. * @eventOf ui.grid.core.api:PublicApi
  5247. * @description is raised when scroll begins. Is throttled, so won't be raised too frequently
  5248. */
  5249. this.registerEvent( 'core', 'scrollBegin' );
  5250. /**
  5251. * @ngdoc event
  5252. * @name scrollEnd
  5253. * @eventOf ui.grid.core.api:PublicApi
  5254. * @description is raised when scroll has finished. Is throttled, so won't be raised too frequently
  5255. */
  5256. this.registerEvent( 'core', 'scrollEnd' );
  5257. /**
  5258. * @ngdoc event
  5259. * @name canvasHeightChanged
  5260. * @eventOf ui.grid.core.api:PublicApi
  5261. * @description is raised when the canvas height has changed
  5262. * <br/>
  5263. * arguments: oldHeight, newHeight
  5264. */
  5265. this.registerEvent( 'core', 'canvasHeightChanged');
  5266. };
  5267. /**
  5268. * @ngdoc function
  5269. * @name ui.grid.class:suppressEvents
  5270. * @methodOf ui.grid.class:GridApi
  5271. * @description Used to execute a function while disabling the specified event listeners.
  5272. * Disables the listenerFunctions, executes the callbackFn, and then enables
  5273. * the listenerFunctions again
  5274. * @param {object} listenerFuncs listenerFunc or array of listenerFuncs to suppress. These must be the same
  5275. * functions that were used in the .on.eventName method
  5276. * @param {object} callBackFn function to execute
  5277. * @example
  5278. * <pre>
  5279. * var navigate = function (newRowCol, oldRowCol){
  5280. * //do something on navigate
  5281. * }
  5282. *
  5283. * gridApi.cellNav.on.navigate(scope,navigate);
  5284. *
  5285. *
  5286. * //call the scrollTo event and suppress our navigate listener
  5287. * //scrollTo will still raise the event for other listeners
  5288. * gridApi.suppressEvents(navigate, function(){
  5289. * gridApi.cellNav.scrollTo(aRow, aCol);
  5290. * });
  5291. *
  5292. * </pre>
  5293. */
  5294. GridApi.prototype.suppressEvents = function (listenerFuncs, callBackFn) {
  5295. var self = this;
  5296. var listeners = angular.isArray(listenerFuncs) ? listenerFuncs : [listenerFuncs];
  5297. //find all registered listeners
  5298. var foundListeners = self.listeners.filter(function(listener) {
  5299. return listeners.some(function(l) {
  5300. return listener.handler === l;
  5301. });
  5302. });
  5303. //deregister all the listeners
  5304. foundListeners.forEach(function(l){
  5305. l.dereg();
  5306. });
  5307. callBackFn();
  5308. //reregister all the listeners
  5309. foundListeners.forEach(function(l){
  5310. l.dereg = registerEventWithAngular(l.eventId, l.handler, self.grid, l._this);
  5311. });
  5312. };
  5313. /**
  5314. * @ngdoc function
  5315. * @name registerEvent
  5316. * @methodOf ui.grid.class:GridApi
  5317. * @description Registers a new event for the given feature. The event will get a
  5318. * .raise and .on prepended to it
  5319. * <br>
  5320. * .raise.eventName() - takes no arguments
  5321. * <br/>
  5322. * <br/>
  5323. * .on.eventName(scope, callBackFn, _this)
  5324. * <br/>
  5325. * scope - a scope reference to add a deregister call to the scopes .$on('destroy'). Scope is optional and can be a null value,
  5326. * but in this case you must deregister it yourself via the returned deregister function
  5327. * <br/>
  5328. * callBackFn - The function to call
  5329. * <br/>
  5330. * _this - optional this context variable for callbackFn. If omitted, grid.api will be used for the context
  5331. * <br/>
  5332. * .on.eventName returns a dereg funtion that will remove the listener. It's not necessary to use it as the listener
  5333. * will be removed when the scope is destroyed.
  5334. * @param {string} featureName name of the feature that raises the event
  5335. * @param {string} eventName name of the event
  5336. */
  5337. GridApi.prototype.registerEvent = function (featureName, eventName) {
  5338. var self = this;
  5339. if (!self[featureName]) {
  5340. self[featureName] = {};
  5341. }
  5342. var feature = self[featureName];
  5343. if (!feature.on) {
  5344. feature.on = {};
  5345. feature.raise = {};
  5346. }
  5347. var eventId = self.grid.id + featureName + eventName;
  5348. // gridUtil.logDebug('Creating raise event method ' + featureName + '.raise.' + eventName);
  5349. feature.raise[eventName] = function () {
  5350. $rootScope.$emit.apply($rootScope, [eventId].concat(Array.prototype.slice.call(arguments)));
  5351. };
  5352. // gridUtil.logDebug('Creating on event method ' + featureName + '.on.' + eventName);
  5353. feature.on[eventName] = function (scope, handler, _this) {
  5354. if ( scope !== null && typeof(scope.$on) === 'undefined' ){
  5355. gridUtil.logError('asked to listen on ' + featureName + '.on.' + eventName + ' but scope wasn\'t passed in the input parameters. It is legitimate to pass null, but you\'ve passed something else, so you probably forgot to provide scope rather than did it deliberately, not registering');
  5356. return;
  5357. }
  5358. var deregAngularOn = registerEventWithAngular(eventId, handler, self.grid, _this);
  5359. //track our listener so we can turn off and on
  5360. var listener = {handler: handler, dereg: deregAngularOn, eventId: eventId, scope: scope, _this:_this};
  5361. self.listeners.push(listener);
  5362. var removeListener = function(){
  5363. listener.dereg();
  5364. var index = self.listeners.indexOf(listener);
  5365. self.listeners.splice(index,1);
  5366. };
  5367. //destroy tracking when scope is destroyed
  5368. if (scope) {
  5369. scope.$on('$destroy', function() {
  5370. removeListener();
  5371. });
  5372. }
  5373. return removeListener;
  5374. };
  5375. };
  5376. function registerEventWithAngular(eventId, handler, grid, _this) {
  5377. return $rootScope.$on(eventId, function (event) {
  5378. var args = Array.prototype.slice.call(arguments);
  5379. args.splice(0, 1); //remove evt argument
  5380. handler.apply(_this ? _this : grid.api, args);
  5381. });
  5382. }
  5383. /**
  5384. * @ngdoc function
  5385. * @name registerEventsFromObject
  5386. * @methodOf ui.grid.class:GridApi
  5387. * @description Registers features and events from a simple objectMap.
  5388. * eventObjectMap must be in this format (multiple features allowed)
  5389. * <pre>
  5390. * {featureName:
  5391. * {
  5392. * eventNameOne:function(args){},
  5393. * eventNameTwo:function(args){}
  5394. * }
  5395. * }
  5396. * </pre>
  5397. * @param {object} eventObjectMap map of feature/event names
  5398. */
  5399. GridApi.prototype.registerEventsFromObject = function (eventObjectMap) {
  5400. var self = this;
  5401. var features = [];
  5402. angular.forEach(eventObjectMap, function (featProp, featPropName) {
  5403. var feature = {name: featPropName, events: []};
  5404. angular.forEach(featProp, function (prop, propName) {
  5405. feature.events.push(propName);
  5406. });
  5407. features.push(feature);
  5408. });
  5409. features.forEach(function (feature) {
  5410. feature.events.forEach(function (event) {
  5411. self.registerEvent(feature.name, event);
  5412. });
  5413. });
  5414. };
  5415. /**
  5416. * @ngdoc function
  5417. * @name registerMethod
  5418. * @methodOf ui.grid.class:GridApi
  5419. * @description Registers a new event for the given feature
  5420. * @param {string} featureName name of the feature
  5421. * @param {string} methodName name of the method
  5422. * @param {object} callBackFn function to execute
  5423. * @param {object} _this binds callBackFn 'this' to _this. Defaults to gridApi.grid
  5424. */
  5425. GridApi.prototype.registerMethod = function (featureName, methodName, callBackFn, _this) {
  5426. if (!this[featureName]) {
  5427. this[featureName] = {};
  5428. }
  5429. var feature = this[featureName];
  5430. feature[methodName] = gridUtil.createBoundedWrapper(_this || this.grid, callBackFn);
  5431. };
  5432. /**
  5433. * @ngdoc function
  5434. * @name registerMethodsFromObject
  5435. * @methodOf ui.grid.class:GridApi
  5436. * @description Registers features and methods from a simple objectMap.
  5437. * eventObjectMap must be in this format (multiple features allowed)
  5438. * <br>
  5439. * {featureName:
  5440. * {
  5441. * methodNameOne:function(args){},
  5442. * methodNameTwo:function(args){}
  5443. * }
  5444. * @param {object} eventObjectMap map of feature/event names
  5445. * @param {object} _this binds this to _this for all functions. Defaults to gridApi.grid
  5446. */
  5447. GridApi.prototype.registerMethodsFromObject = function (methodMap, _this) {
  5448. var self = this;
  5449. var features = [];
  5450. angular.forEach(methodMap, function (featProp, featPropName) {
  5451. var feature = {name: featPropName, methods: []};
  5452. angular.forEach(featProp, function (prop, propName) {
  5453. feature.methods.push({name: propName, fn: prop});
  5454. });
  5455. features.push(feature);
  5456. });
  5457. features.forEach(function (feature) {
  5458. feature.methods.forEach(function (method) {
  5459. self.registerMethod(feature.name, method.name, method.fn, _this);
  5460. });
  5461. });
  5462. };
  5463. return GridApi;
  5464. }]);
  5465. })();
  5466. (function(){
  5467. angular.module('ui.grid')
  5468. .factory('GridColumn', ['gridUtil', 'uiGridConstants', 'i18nService', function(gridUtil, uiGridConstants, i18nService) {
  5469. /**
  5470. * ******************************************************************************************
  5471. * PaulL1: Ugly hack here in documentation. These properties are clearly properties of GridColumn,
  5472. * and need to be noted as such for those extending and building ui-grid itself.
  5473. * However, from an end-developer perspective, they interact with all these through columnDefs,
  5474. * and they really need to be documented there. I feel like they're relatively static, and
  5475. * I can't find an elegant way for ngDoc to reference to both....so I've duplicated each
  5476. * comment block. Ugh.
  5477. *
  5478. */
  5479. /**
  5480. * @ngdoc property
  5481. * @name name
  5482. * @propertyOf ui.grid.class:GridColumn
  5483. * @description (mandatory) each column should have a name, although for backward
  5484. * compatibility with 2.x name can be omitted if field is present
  5485. *
  5486. */
  5487. /**
  5488. * @ngdoc property
  5489. * @name name
  5490. * @propertyOf ui.grid.class:GridOptions.columnDef
  5491. * @description (mandatory) each column should have a name, although for backward
  5492. * compatibility with 2.x name can be omitted if field is present
  5493. *
  5494. */
  5495. /**
  5496. * @ngdoc property
  5497. * @name displayName
  5498. * @propertyOf ui.grid.class:GridColumn
  5499. * @description Column name that will be shown in the header. If displayName is not
  5500. * provided then one is generated using the name.
  5501. *
  5502. */
  5503. /**
  5504. * @ngdoc property
  5505. * @name displayName
  5506. * @propertyOf ui.grid.class:GridOptions.columnDef
  5507. * @description Column name that will be shown in the header. If displayName is not
  5508. * provided then one is generated using the name.
  5509. *
  5510. */
  5511. /**
  5512. * @ngdoc property
  5513. * @name field
  5514. * @propertyOf ui.grid.class:GridColumn
  5515. * @description field must be provided if you wish to bind to a
  5516. * property in the data source. Should be an angular expression that evaluates against grid.options.data
  5517. * array element. Can be a complex expression: <code>employee.address.city</code>, or can be a function: <code>employee.getFullAddress()</code>.
  5518. * See the angular docs on binding expressions.
  5519. *
  5520. */
  5521. /**
  5522. * @ngdoc property
  5523. * @name field
  5524. * @propertyOf ui.grid.class:GridOptions.columnDef
  5525. * @description field must be provided if you wish to bind to a
  5526. * property in the data source. Should be an angular expression that evaluates against grid.options.data
  5527. * array element. Can be a complex expression: <code>employee.address.city</code>, or can be a function: <code>employee.getFullAddress()</code>. * See the angular docs on binding expressions. *
  5528. */
  5529. /**
  5530. * @ngdoc property
  5531. * @name filter
  5532. * @propertyOf ui.grid.class:GridColumn
  5533. * @description Filter on this column.
  5534. * @example
  5535. * <pre>{ term: 'text', condition: uiGridConstants.filter.STARTS_WITH, placeholder: 'type to filter...', ariaLabel: 'Filter for text, flags: { caseSensitive: false }, type: uiGridConstants.filter.SELECT, [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ] }</pre>
  5536. *
  5537. */
  5538. /**
  5539. * @ngdoc object
  5540. * @name ui.grid.class:GridColumn
  5541. * @description Represents the viewModel for each column. Any state or methods needed for a Grid Column
  5542. * are defined on this prototype
  5543. * @param {ColumnDef} colDef the column def to associate with this column
  5544. * @param {number} uid the unique and immutable uid we'd like to allocate to this column
  5545. * @param {Grid} grid the grid we'd like to create this column in
  5546. */
  5547. function GridColumn(colDef, uid, grid) {
  5548. var self = this;
  5549. self.grid = grid;
  5550. self.uid = uid;
  5551. self.updateColumnDef(colDef, true);
  5552. /**
  5553. * @ngdoc function
  5554. * @name hideColumn
  5555. * @methodOf ui.grid.class:GridColumn
  5556. * @description Hides the column by setting colDef.visible = false
  5557. */
  5558. GridColumn.prototype.hideColumn = function() {
  5559. this.colDef.visible = false;
  5560. };
  5561. self.aggregationValue = undefined;
  5562. // The footer cell registers to listen for the rowsRendered event, and calls this. Needed to be
  5563. // in something with a scope so that the dereg would get called
  5564. self.updateAggregationValue = function() {
  5565. // gridUtil.logDebug('getAggregationValue for Column ' + self.colDef.name);
  5566. /**
  5567. * @ngdoc property
  5568. * @name aggregationType
  5569. * @propertyOf ui.grid.class:GridOptions.columnDef
  5570. * @description The aggregation that you'd like to show in the columnFooter for this
  5571. * column. Valid values are in uiGridConstants, and currently include `uiGridConstants.aggregationTypes.count`,
  5572. * `uiGridConstants.aggregationTypes.sum`, `uiGridConstants.aggregationTypes.avg`, `uiGridConstants.aggregationTypes.min`,
  5573. * `uiGridConstants.aggregationTypes.max`.
  5574. *
  5575. * You can also provide a function as the aggregation type, in this case your function needs to accept the full
  5576. * set of visible rows, and return a value that should be shown
  5577. */
  5578. if (!self.aggregationType) {
  5579. self.aggregationValue = undefined;
  5580. return;
  5581. }
  5582. var result = 0;
  5583. var visibleRows = self.grid.getVisibleRows();
  5584. var cellValues = function(){
  5585. var values = [];
  5586. visibleRows.forEach(function (row) {
  5587. var cellValue = self.grid.getCellValue(row, self);
  5588. var cellNumber = Number(cellValue);
  5589. if (!isNaN(cellNumber)) {
  5590. values.push(cellNumber);
  5591. }
  5592. });
  5593. return values;
  5594. };
  5595. if (angular.isFunction(self.aggregationType)) {
  5596. self.aggregationValue = self.aggregationType(visibleRows, self);
  5597. }
  5598. else if (self.aggregationType === uiGridConstants.aggregationTypes.count) {
  5599. self.aggregationValue = self.grid.getVisibleRowCount();
  5600. }
  5601. else if (self.aggregationType === uiGridConstants.aggregationTypes.sum) {
  5602. cellValues().forEach(function (value) {
  5603. result += value;
  5604. });
  5605. self.aggregationValue = result;
  5606. }
  5607. else if (self.aggregationType === uiGridConstants.aggregationTypes.avg) {
  5608. cellValues().forEach(function (value) {
  5609. result += value;
  5610. });
  5611. result = result / cellValues().length;
  5612. self.aggregationValue = result;
  5613. }
  5614. else if (self.aggregationType === uiGridConstants.aggregationTypes.min) {
  5615. self.aggregationValue = Math.min.apply(null, cellValues());
  5616. }
  5617. else if (self.aggregationType === uiGridConstants.aggregationTypes.max) {
  5618. self.aggregationValue = Math.max.apply(null, cellValues());
  5619. }
  5620. else {
  5621. self.aggregationValue = '\u00A0';
  5622. }
  5623. };
  5624. // var throttledUpdateAggregationValue = gridUtil.throttle(updateAggregationValue, self.grid.options.aggregationCalcThrottle, { trailing: true, context: self.name });
  5625. /**
  5626. * @ngdoc function
  5627. * @name getAggregationValue
  5628. * @methodOf ui.grid.class:GridColumn
  5629. * @description gets the aggregation value based on the aggregation type for this column.
  5630. * Debounced using scrollDebounce option setting
  5631. */
  5632. this.getAggregationValue = function() {
  5633. // if (!self.grid.isScrollingVertically && !self.grid.isScrollingHorizontally) {
  5634. // throttledUpdateAggregationValue();
  5635. // }
  5636. return self.aggregationValue;
  5637. };
  5638. }
  5639. /**
  5640. * @ngdoc method
  5641. * @methodOf ui.grid.class:GridColumn
  5642. * @name setPropertyOrDefault
  5643. * @description Sets a property on the column using the passed in columnDef, and
  5644. * setting the defaultValue if the value cannot be found on the colDef
  5645. * @param {ColumnDef} colDef the column def to look in for the property value
  5646. * @param {string} propName the property name we'd like to set
  5647. * @param {object} defaultValue the value to use if the colDef doesn't provide the setting
  5648. */
  5649. GridColumn.prototype.setPropertyOrDefault = function (colDef, propName, defaultValue) {
  5650. var self = this;
  5651. // Use the column definition filter if we were passed it
  5652. if (typeof(colDef[propName]) !== 'undefined' && colDef[propName]) {
  5653. self[propName] = colDef[propName];
  5654. }
  5655. // Otherwise use our own if it's set
  5656. else if (typeof(self[propName]) !== 'undefined') {
  5657. self[propName] = self[propName];
  5658. }
  5659. // Default to empty object for the filter
  5660. else {
  5661. self[propName] = defaultValue ? defaultValue : {};
  5662. }
  5663. };
  5664. /**
  5665. * @ngdoc property
  5666. * @name width
  5667. * @propertyOf ui.grid.class:GridOptions.columnDef
  5668. * @description sets the column width. Can be either
  5669. * a number or a percentage, or an * for auto.
  5670. * @example
  5671. * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', width: 100},
  5672. * { field: 'field2', width: '20%'},
  5673. * { field: 'field3', width: '*' }]; </pre>
  5674. *
  5675. */
  5676. /**
  5677. * @ngdoc property
  5678. * @name minWidth
  5679. * @propertyOf ui.grid.class:GridOptions.columnDef
  5680. * @description sets the minimum column width. Should be a number.
  5681. * @example
  5682. * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', minWidth: 100}]; </pre>
  5683. *
  5684. */
  5685. /**
  5686. * @ngdoc property
  5687. * @name maxWidth
  5688. * @propertyOf ui.grid.class:GridOptions.columnDef
  5689. * @description sets the maximum column width. Should be a number.
  5690. * @example
  5691. * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', maxWidth: 100}]; </pre>
  5692. *
  5693. */
  5694. /**
  5695. * @ngdoc property
  5696. * @name visible
  5697. * @propertyOf ui.grid.class:GridOptions.columnDef
  5698. * @description sets whether or not the column is visible
  5699. * </br>Default is true
  5700. * @example
  5701. * <pre> $scope.gridOptions.columnDefs = [
  5702. * { field: 'field1', visible: true},
  5703. * { field: 'field2', visible: false }
  5704. * ]; </pre>
  5705. *
  5706. */
  5707. /**
  5708. * @ngdoc property
  5709. * @name sort
  5710. * @propertyOf ui.grid.class:GridOptions.columnDef
  5711. * @description An object of sort information, attributes are:
  5712. *
  5713. * - direction: values are uiGridConstants.ASC or uiGridConstants.DESC
  5714. * - ignoreSort: if set to true this sort is ignored (used by tree to manipulate the sort functionality)
  5715. * - priority: says what order to sort the columns in (lower priority gets sorted first).
  5716. * @example
  5717. * <pre>
  5718. * $scope.gridOptions.columnDefs = [{
  5719. * field: 'field1',
  5720. * sort: {
  5721. * direction: uiGridConstants.ASC,
  5722. * ignoreSort: true,
  5723. * priority: 0
  5724. * }
  5725. * }];
  5726. * </pre>
  5727. */
  5728. /**
  5729. * @ngdoc property
  5730. * @name sortingAlgorithm
  5731. * @propertyOf ui.grid.class:GridColumn
  5732. * @description Algorithm to use for sorting this column. Takes 'a' and 'b' parameters
  5733. * like any normal sorting function.
  5734. *
  5735. */
  5736. /**
  5737. * @ngdoc property
  5738. * @name sortingAlgorithm
  5739. * @propertyOf ui.grid.class:GridOptions.columnDef
  5740. * @description Algorithm to use for sorting this column. Takes 'a' and 'b' parameters
  5741. * like any normal sorting function.
  5742. *
  5743. */
  5744. /**
  5745. * @ngdoc array
  5746. * @name filters
  5747. * @propertyOf ui.grid.class:GridOptions.columnDef
  5748. * @description Specify multiple filter fields.
  5749. * @example
  5750. * <pre>$scope.gridOptions.columnDefs = [
  5751. * {
  5752. * field: 'field1', filters: [
  5753. * {
  5754. * term: 'aa',
  5755. * condition: uiGridConstants.filter.STARTS_WITH,
  5756. * placeholder: 'starts with...',
  5757. * ariaLabel: 'Filter for field1',
  5758. * flags: { caseSensitive: false },
  5759. * type: uiGridConstants.filter.SELECT,
  5760. * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ]
  5761. * },
  5762. * {
  5763. * condition: uiGridConstants.filter.ENDS_WITH,
  5764. * placeholder: 'ends with...'
  5765. * }
  5766. * ]
  5767. * }
  5768. * ]; </pre>
  5769. *
  5770. *
  5771. */
  5772. /**
  5773. * @ngdoc array
  5774. * @name filters
  5775. * @propertyOf ui.grid.class:GridColumn
  5776. * @description Filters for this column. Includes 'term' property bound to filter input elements.
  5777. * @example
  5778. * <pre>[
  5779. * {
  5780. * term: 'foo', // ngModel for <input>
  5781. * condition: uiGridConstants.filter.STARTS_WITH,
  5782. * placeholder: 'starts with...',
  5783. * ariaLabel: 'Filter for foo',
  5784. * flags: { caseSensitive: false },
  5785. * type: uiGridConstants.filter.SELECT,
  5786. * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ]
  5787. * },
  5788. * {
  5789. * term: 'baz',
  5790. * condition: uiGridConstants.filter.ENDS_WITH,
  5791. * placeholder: 'ends with...'
  5792. * }
  5793. * ] </pre>
  5794. *
  5795. *
  5796. */
  5797. /**
  5798. * @ngdoc array
  5799. * @name menuItems
  5800. * @propertyOf ui.grid.class:GridOptions.columnDef
  5801. * @description used to add menu items to a column. Refer to the tutorial on this
  5802. * functionality. A number of settings are supported:
  5803. *
  5804. * - title: controls the title that is displayed in the menu
  5805. * - icon: the icon shown alongside that title
  5806. * - action: the method to call when the menu is clicked
  5807. * - shown: a function to evaluate to determine whether or not to show the item
  5808. * - active: a function to evaluate to determine whether or not the item is currently selected
  5809. * - context: context to pass to the action function, available in this.context in your handler
  5810. * - leaveOpen: if set to true, the menu should stay open after the action, defaults to false
  5811. * @example
  5812. * <pre> $scope.gridOptions.columnDefs = [
  5813. * { field: 'field1', menuItems: [
  5814. * {
  5815. * title: 'Outer Scope Alert',
  5816. * icon: 'ui-grid-icon-info-circled',
  5817. * action: function($event) {
  5818. * this.context.blargh(); // $scope.blargh() would work too, this is just an example
  5819. * },
  5820. * shown: function() { return true; },
  5821. * active: function() { return true; },
  5822. * context: $scope
  5823. * },
  5824. * {
  5825. * title: 'Grid ID',
  5826. * action: function() {
  5827. * alert('Grid ID: ' + this.grid.id);
  5828. * }
  5829. * }
  5830. * ] }]; </pre>
  5831. *
  5832. */
  5833. /**
  5834. * @ngdoc method
  5835. * @methodOf ui.grid.class:GridColumn
  5836. * @name updateColumnDef
  5837. * @description Moves settings from the columnDef down onto the column,
  5838. * and sets properties as appropriate
  5839. * @param {ColumnDef} colDef the column def to look in for the property value
  5840. * @param {boolean} isNew whether the column is being newly created, if not
  5841. * we're updating an existing column, and some items such as the sort shouldn't
  5842. * be copied down
  5843. */
  5844. GridColumn.prototype.updateColumnDef = function(colDef, isNew) {
  5845. var self = this;
  5846. self.colDef = colDef;
  5847. if (colDef.name === undefined) {
  5848. throw new Error('colDef.name is required for column at index ' + self.grid.options.columnDefs.indexOf(colDef));
  5849. }
  5850. self.displayName = (colDef.displayName === undefined) ? gridUtil.readableColumnName(colDef.name) : colDef.displayName;
  5851. if (!angular.isNumber(self.width) || !self.hasCustomWidth || colDef.allowCustomWidthOverride) {
  5852. var colDefWidth = colDef.width;
  5853. var parseErrorMsg = "Cannot parse column width '" + colDefWidth + "' for column named '" + colDef.name + "'";
  5854. self.hasCustomWidth = false;
  5855. if (!angular.isString(colDefWidth) && !angular.isNumber(colDefWidth)) {
  5856. self.width = '*';
  5857. } else if (angular.isString(colDefWidth)) {
  5858. // See if it ends with a percent
  5859. if (gridUtil.endsWith(colDefWidth, '%')) {
  5860. // If so we should be able to parse the non-percent-sign part to a number
  5861. var percentStr = colDefWidth.replace(/%/g, '');
  5862. var percent = parseInt(percentStr, 10);
  5863. if (isNaN(percent)) {
  5864. throw new Error(parseErrorMsg);
  5865. }
  5866. self.width = colDefWidth;
  5867. }
  5868. // And see if it's a number string
  5869. else if (colDefWidth.match(/^(\d+)$/)) {
  5870. self.width = parseInt(colDefWidth.match(/^(\d+)$/)[1], 10);
  5871. }
  5872. // Otherwise it should be a string of asterisks
  5873. else if (colDefWidth.match(/^\*+$/)) {
  5874. self.width = colDefWidth;
  5875. }
  5876. // No idea, throw an Error
  5877. else {
  5878. throw new Error(parseErrorMsg);
  5879. }
  5880. }
  5881. // Is a number, use it as the width
  5882. else {
  5883. self.width = colDefWidth;
  5884. }
  5885. }
  5886. ['minWidth', 'maxWidth'].forEach(function (name) {
  5887. var minOrMaxWidth = colDef[name];
  5888. var parseErrorMsg = "Cannot parse column " + name + " '" + minOrMaxWidth + "' for column named '" + colDef.name + "'";
  5889. if (!angular.isString(minOrMaxWidth) && !angular.isNumber(minOrMaxWidth)) {
  5890. //Sets default minWidth and maxWidth values
  5891. self[name] = ((name === 'minWidth') ? 30 : 9000);
  5892. } else if (angular.isString(minOrMaxWidth)) {
  5893. if (minOrMaxWidth.match(/^(\d+)$/)) {
  5894. self[name] = parseInt(minOrMaxWidth.match(/^(\d+)$/)[1], 10);
  5895. } else {
  5896. throw new Error(parseErrorMsg);
  5897. }
  5898. } else {
  5899. self[name] = minOrMaxWidth;
  5900. }
  5901. });
  5902. //use field if it is defined; name if it is not
  5903. self.field = (colDef.field === undefined) ? colDef.name : colDef.field;
  5904. if ( typeof( self.field ) !== 'string' ){
  5905. gridUtil.logError( 'Field is not a string, this is likely to break the code, Field is: ' + self.field );
  5906. }
  5907. self.name = colDef.name;
  5908. // Use colDef.displayName as long as it's not undefined, otherwise default to the field name
  5909. self.displayName = (colDef.displayName === undefined) ? gridUtil.readableColumnName(colDef.name) : colDef.displayName;
  5910. //self.originalIndex = index;
  5911. self.aggregationType = angular.isDefined(colDef.aggregationType) ? colDef.aggregationType : null;
  5912. self.footerCellTemplate = angular.isDefined(colDef.footerCellTemplate) ? colDef.footerCellTemplate : null;
  5913. /**
  5914. * @ngdoc property
  5915. * @name cellTooltip
  5916. * @propertyOf ui.grid.class:GridOptions.columnDef
  5917. * @description Whether or not to show a tooltip when a user hovers over the cell.
  5918. * If set to false, no tooltip. If true, the cell value is shown in the tooltip (useful
  5919. * if you have long values in your cells), if a function then that function is called
  5920. * passing in the row and the col `cellTooltip( row, col )`, and the return value is shown in the tooltip,
  5921. * if it is a static string then displays that static string.
  5922. *
  5923. * Defaults to false
  5924. *
  5925. */
  5926. if ( typeof(colDef.cellTooltip) === 'undefined' || colDef.cellTooltip === false ) {
  5927. self.cellTooltip = false;
  5928. } else if ( colDef.cellTooltip === true ){
  5929. self.cellTooltip = function(row, col) {
  5930. return self.grid.getCellValue( row, col );
  5931. };
  5932. } else if (typeof(colDef.cellTooltip) === 'function' ){
  5933. self.cellTooltip = colDef.cellTooltip;
  5934. } else {
  5935. self.cellTooltip = function ( row, col ){
  5936. return col.colDef.cellTooltip;
  5937. };
  5938. }
  5939. /**
  5940. * @ngdoc property
  5941. * @name headerTooltip
  5942. * @propertyOf ui.grid.class:GridOptions.columnDef
  5943. * @description Whether or not to show a tooltip when a user hovers over the header cell.
  5944. * If set to false, no tooltip. If true, the displayName is shown in the tooltip (useful
  5945. * if you have long values in your headers), if a function then that function is called
  5946. * passing in the row and the col `headerTooltip( col )`, and the return value is shown in the tooltip,
  5947. * if a static string then shows that static string.
  5948. *
  5949. * Defaults to false
  5950. *
  5951. */
  5952. if ( typeof(colDef.headerTooltip) === 'undefined' || colDef.headerTooltip === false ) {
  5953. self.headerTooltip = false;
  5954. } else if ( colDef.headerTooltip === true ){
  5955. self.headerTooltip = function(col) {
  5956. return col.displayName;
  5957. };
  5958. } else if (typeof(colDef.headerTooltip) === 'function' ){
  5959. self.headerTooltip = colDef.headerTooltip;
  5960. } else {
  5961. self.headerTooltip = function ( col ) {
  5962. return col.colDef.headerTooltip;
  5963. };
  5964. }
  5965. /**
  5966. * @ngdoc property
  5967. * @name footerCellClass
  5968. * @propertyOf ui.grid.class:GridOptions.columnDef
  5969. * @description footerCellClass can be a string specifying the class to append to a cell
  5970. * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name
  5971. *
  5972. */
  5973. self.footerCellClass = colDef.footerCellClass;
  5974. /**
  5975. * @ngdoc property
  5976. * @name cellClass
  5977. * @propertyOf ui.grid.class:GridOptions.columnDef
  5978. * @description cellClass can be a string specifying the class to append to a cell
  5979. * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name
  5980. *
  5981. */
  5982. self.cellClass = colDef.cellClass;
  5983. /**
  5984. * @ngdoc property
  5985. * @name headerCellClass
  5986. * @propertyOf ui.grid.class:GridOptions.columnDef
  5987. * @description headerCellClass can be a string specifying the class to append to a cell
  5988. * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name
  5989. *
  5990. */
  5991. self.headerCellClass = colDef.headerCellClass;
  5992. /**
  5993. * @ngdoc property
  5994. * @name cellFilter
  5995. * @propertyOf ui.grid.class:GridOptions.columnDef
  5996. * @description cellFilter is a filter to apply to the content of each cell
  5997. * @example
  5998. * <pre>
  5999. * gridOptions.columnDefs[0].cellFilter = 'date'
  6000. *
  6001. */
  6002. self.cellFilter = colDef.cellFilter ? colDef.cellFilter : "";
  6003. /**
  6004. * @ngdoc boolean
  6005. * @name sortCellFiltered
  6006. * @propertyOf ui.grid.class:GridOptions.columnDef
  6007. * @description (optional) False by default. When `true` uiGrid will apply the cellFilter before
  6008. * sorting the data. Note that when using this option uiGrid will assume that the displayed value is
  6009. * a string, and use the {@link ui.grid.class:RowSorter#sortAlpha sortAlpha} `sortFn`. It is possible
  6010. * to return a non-string value from an angularjs filter, in which case you should define a {@link ui.grid.class:GridOptions.columnDef#sortingAlgorithm sortingAlgorithm}
  6011. * for the column which hanldes the returned type. You may specify one of the `sortingAlgorithms`
  6012. * found in the {@link ui.grid.RowSorter rowSorter} service.
  6013. */
  6014. self.sortCellFiltered = colDef.sortCellFiltered ? true : false;
  6015. /**
  6016. * @ngdoc boolean
  6017. * @name filterCellFiltered
  6018. * @propertyOf ui.grid.class:GridOptions.columnDef
  6019. * @description (optional) False by default. When `true` uiGrid will apply the cellFilter before
  6020. * applying "search" `filters`.
  6021. */
  6022. self.filterCellFiltered = colDef.filterCellFiltered ? true : false;
  6023. /**
  6024. * @ngdoc property
  6025. * @name headerCellFilter
  6026. * @propertyOf ui.grid.class:GridOptions.columnDef
  6027. * @description headerCellFilter is a filter to apply to the content of the column header
  6028. * @example
  6029. * <pre>
  6030. * gridOptions.columnDefs[0].headerCellFilter = 'translate'
  6031. *
  6032. */
  6033. self.headerCellFilter = colDef.headerCellFilter ? colDef.headerCellFilter : "";
  6034. /**
  6035. * @ngdoc property
  6036. * @name footerCellFilter
  6037. * @propertyOf ui.grid.class:GridOptions.columnDef
  6038. * @description footerCellFilter is a filter to apply to the content of the column footer
  6039. * @example
  6040. * <pre>
  6041. * gridOptions.columnDefs[0].footerCellFilter = 'date'
  6042. *
  6043. */
  6044. self.footerCellFilter = colDef.footerCellFilter ? colDef.footerCellFilter : "";
  6045. self.visible = gridUtil.isNullOrUndefined(colDef.visible) || colDef.visible;
  6046. self.headerClass = colDef.headerClass;
  6047. //self.cursor = self.sortable ? 'pointer' : 'default';
  6048. // Turn on sorting by default
  6049. self.enableSorting = typeof(colDef.enableSorting) !== 'undefined' ? colDef.enableSorting : true;
  6050. self.sortingAlgorithm = colDef.sortingAlgorithm;
  6051. /**
  6052. * @ngdoc boolean
  6053. * @name suppressRemoveSort
  6054. * @propertyOf ui.grid.class:GridOptions.columnDef
  6055. * @description (optional) False by default. When enabled, this setting hides the removeSort option
  6056. * in the menu, and prevents users from manually removing the sort
  6057. */
  6058. if ( typeof(self.suppressRemoveSort) === 'undefined'){
  6059. self.suppressRemoveSort = typeof(colDef.suppressRemoveSort) !== 'undefined' ? colDef.suppressRemoveSort : false;
  6060. }
  6061. /**
  6062. * @ngdoc property
  6063. * @name enableFiltering
  6064. * @propertyOf ui.grid.class:GridOptions.columnDef
  6065. * @description turn off filtering for an individual column, where
  6066. * you've turned on filtering for the overall grid
  6067. * @example
  6068. * <pre>
  6069. * gridOptions.columnDefs[0].enableFiltering = false;
  6070. *
  6071. */
  6072. // Turn on filtering by default (it's disabled by default at the Grid level)
  6073. self.enableFiltering = typeof(colDef.enableFiltering) !== 'undefined' ? colDef.enableFiltering : true;
  6074. // self.menuItems = colDef.menuItems;
  6075. self.setPropertyOrDefault(colDef, 'menuItems', []);
  6076. // Use the column definition sort if we were passed it, but only if this is a newly added column
  6077. if ( isNew ){
  6078. self.setPropertyOrDefault(colDef, 'sort');
  6079. }
  6080. // Set up default filters array for when one is not provided.
  6081. // In other words, this (in column def):
  6082. //
  6083. // filter: { term: 'something', flags: {}, condition: [CONDITION] }
  6084. //
  6085. // is just shorthand for this:
  6086. //
  6087. // filters: [{ term: 'something', flags: {}, condition: [CONDITION] }]
  6088. //
  6089. var defaultFilters = [];
  6090. if (colDef.filter) {
  6091. defaultFilters.push(colDef.filter);
  6092. }
  6093. else if ( colDef.filters ){
  6094. defaultFilters = colDef.filters;
  6095. } else {
  6096. // Add an empty filter definition object, which will
  6097. // translate to a guessed condition and no pre-populated
  6098. // value for the filter <input>.
  6099. defaultFilters.push({});
  6100. }
  6101. /**
  6102. * @ngdoc property
  6103. * @name filter
  6104. * @propertyOf ui.grid.class:GridOptions.columnDef
  6105. * @description Specify a single filter field on this column.
  6106. *
  6107. * A filter consists of a condition, a term, and a placeholder:
  6108. *
  6109. * - condition defines how rows are chosen as matching the filter term. This can be set to
  6110. * one of the constants in uiGridConstants.filter, or you can supply a custom filter function
  6111. * that gets passed the following arguments: [searchTerm, cellValue, row, column].
  6112. * - term: If set, the filter field will be pre-populated
  6113. * with this value.
  6114. * - placeholder: String that will be set to the `<input>.placeholder` attribute.
  6115. * - ariaLabel: String that will be set to the `<input>.ariaLabel` attribute. This is what is read as a label to screen reader users.
  6116. * - noTerm: set this to true if you have defined a custom function in condition, and
  6117. * your custom function doesn't require a term (so it can run even when the term is null)
  6118. * - flags: only flag currently available is `caseSensitive`, set to false if you don't want
  6119. * case sensitive matching
  6120. * - type: defaults to uiGridConstants.filter.INPUT, which gives a text box. If set to uiGridConstants.filter.SELECT
  6121. * then a select box will be shown with options selectOptions
  6122. * - selectOptions: options in the format `[ { value: 1, label: 'male' }]`. No i18n filter is provided, you need
  6123. * to perform the i18n on the values before you provide them
  6124. * - disableCancelFilterButton: defaults to false. If set to true then the 'x' button that cancels/clears the filter
  6125. * will not be shown.
  6126. * @example
  6127. * <pre>$scope.gridOptions.columnDefs = [
  6128. * {
  6129. * field: 'field1',
  6130. * filter: {
  6131. * term: 'xx',
  6132. * condition: uiGridConstants.filter.STARTS_WITH,
  6133. * placeholder: 'starts with...',
  6134. * ariaLabel: 'Starts with filter for field1',
  6135. * flags: { caseSensitive: false },
  6136. * type: uiGridConstants.filter.SELECT,
  6137. * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ],
  6138. * disableCancelFilterButton: true
  6139. * }
  6140. * }
  6141. * ]; </pre>
  6142. *
  6143. */
  6144. /*
  6145. /*
  6146. self.filters = [
  6147. {
  6148. term: 'search term'
  6149. condition: uiGridConstants.filter.CONTAINS,
  6150. placeholder: 'my placeholder',
  6151. ariaLabel: 'Starts with filter for field1',
  6152. flags: {
  6153. caseSensitive: true
  6154. }
  6155. }
  6156. ]
  6157. */
  6158. // Only set filter if this is a newly added column, if we're updating an existing
  6159. // column then we don't want to put the default filter back if the user may have already
  6160. // removed it.
  6161. // However, we do want to keep the settings if they change, just not the term
  6162. if ( isNew ) {
  6163. self.setPropertyOrDefault(colDef, 'filter');
  6164. self.setPropertyOrDefault(colDef, 'filters', defaultFilters);
  6165. } else if ( self.filters.length === defaultFilters.length ) {
  6166. self.filters.forEach( function( filter, index ){
  6167. if (typeof(defaultFilters[index].placeholder) !== 'undefined') {
  6168. filter.placeholder = defaultFilters[index].placeholder;
  6169. }
  6170. if (typeof(defaultFilters[index].ariaLabel) !== 'undefined') {
  6171. filter.ariaLabel = defaultFilters[index].ariaLabel;
  6172. }
  6173. if (typeof(defaultFilters[index].flags) !== 'undefined') {
  6174. filter.flags = defaultFilters[index].flags;
  6175. }
  6176. if (typeof(defaultFilters[index].type) !== 'undefined') {
  6177. filter.type = defaultFilters[index].type;
  6178. }
  6179. if (typeof(defaultFilters[index].selectOptions) !== 'undefined') {
  6180. filter.selectOptions = defaultFilters[index].selectOptions;
  6181. }
  6182. });
  6183. }
  6184. // Remove this column from the grid sorting, include inside build columns so has
  6185. // access to self - all seems a bit dodgy but doesn't work otherwise so have left
  6186. // as is
  6187. GridColumn.prototype.unsort = function () {
  6188. this.sort = {};
  6189. self.grid.api.core.raise.sortChanged( self.grid, self.grid.getColumnSorting() );
  6190. };
  6191. };
  6192. /**
  6193. * @ngdoc function
  6194. * @name getColClass
  6195. * @methodOf ui.grid.class:GridColumn
  6196. * @description Returns the class name for the column
  6197. * @param {bool} prefixDot if true, will return .className instead of className
  6198. */
  6199. GridColumn.prototype.getColClass = function (prefixDot) {
  6200. var cls = uiGridConstants.COL_CLASS_PREFIX + this.uid;
  6201. return prefixDot ? '.' + cls : cls;
  6202. };
  6203. /**
  6204. * @ngdoc function
  6205. * @name isPinnedLeft
  6206. * @methodOf ui.grid.class:GridColumn
  6207. * @description Returns true if column is in the left render container
  6208. */
  6209. GridColumn.prototype.isPinnedLeft = function () {
  6210. return this.renderContainer === 'left';
  6211. };
  6212. /**
  6213. * @ngdoc function
  6214. * @name isPinnedRight
  6215. * @methodOf ui.grid.class:GridColumn
  6216. * @description Returns true if column is in the right render container
  6217. */
  6218. GridColumn.prototype.isPinnedRight = function () {
  6219. return this.renderContainer === 'right';
  6220. };
  6221. /**
  6222. * @ngdoc function
  6223. * @name getColClassDefinition
  6224. * @methodOf ui.grid.class:GridColumn
  6225. * @description Returns the class definition for th column
  6226. */
  6227. GridColumn.prototype.getColClassDefinition = function () {
  6228. return ' .grid' + this.grid.id + ' ' + this.getColClass(true) + ' { min-width: ' + this.drawnWidth + 'px; max-width: ' + this.drawnWidth + 'px; }';
  6229. };
  6230. /**
  6231. * @ngdoc function
  6232. * @name getRenderContainer
  6233. * @methodOf ui.grid.class:GridColumn
  6234. * @description Returns the render container object that this column belongs to.
  6235. *
  6236. * Columns will be default be in the `body` render container if they aren't allocated to one specifically.
  6237. */
  6238. GridColumn.prototype.getRenderContainer = function getRenderContainer() {
  6239. var self = this;
  6240. var containerId = self.renderContainer;
  6241. if (containerId === null || containerId === '' || containerId === undefined) {
  6242. containerId = 'body';
  6243. }
  6244. return self.grid.renderContainers[containerId];
  6245. };
  6246. /**
  6247. * @ngdoc function
  6248. * @name showColumn
  6249. * @methodOf ui.grid.class:GridColumn
  6250. * @description Makes the column visible by setting colDef.visible = true
  6251. */
  6252. GridColumn.prototype.showColumn = function() {
  6253. this.colDef.visible = true;
  6254. };
  6255. /**
  6256. * @ngdoc property
  6257. * @name aggregationHideLabel
  6258. * @propertyOf ui.grid.class:GridOptions.columnDef
  6259. * @description defaults to false, if set to true hides the label text
  6260. * in the aggregation footer, so only the value is displayed.
  6261. *
  6262. */
  6263. /**
  6264. * @ngdoc function
  6265. * @name getAggregationText
  6266. * @methodOf ui.grid.class:GridColumn
  6267. * @description Gets the aggregation label from colDef.aggregationLabel if
  6268. * specified or by using i18n, including deciding whether or not to display
  6269. * based on colDef.aggregationHideLabel.
  6270. *
  6271. * @param {string} label the i18n lookup value to use for the column label
  6272. *
  6273. */
  6274. GridColumn.prototype.getAggregationText = function () {
  6275. var self = this;
  6276. if ( self.colDef.aggregationHideLabel ){
  6277. return '';
  6278. }
  6279. else if ( self.colDef.aggregationLabel ) {
  6280. return self.colDef.aggregationLabel;
  6281. }
  6282. else {
  6283. switch ( self.colDef.aggregationType ){
  6284. case uiGridConstants.aggregationTypes.count:
  6285. return i18nService.getSafeText('aggregation.count');
  6286. case uiGridConstants.aggregationTypes.sum:
  6287. return i18nService.getSafeText('aggregation.sum');
  6288. case uiGridConstants.aggregationTypes.avg:
  6289. return i18nService.getSafeText('aggregation.avg');
  6290. case uiGridConstants.aggregationTypes.min:
  6291. return i18nService.getSafeText('aggregation.min');
  6292. case uiGridConstants.aggregationTypes.max:
  6293. return i18nService.getSafeText('aggregation.max');
  6294. default:
  6295. return '';
  6296. }
  6297. }
  6298. };
  6299. GridColumn.prototype.getCellTemplate = function () {
  6300. var self = this;
  6301. return self.cellTemplatePromise;
  6302. };
  6303. GridColumn.prototype.getCompiledElementFn = function () {
  6304. var self = this;
  6305. return self.compiledElementFnDefer.promise;
  6306. };
  6307. return GridColumn;
  6308. }]);
  6309. })();
  6310. (function(){
  6311. angular.module('ui.grid')
  6312. .factory('GridOptions', ['gridUtil','uiGridConstants', function(gridUtil,uiGridConstants) {
  6313. /**
  6314. * @ngdoc function
  6315. * @name ui.grid.class:GridOptions
  6316. * @description Default GridOptions class. GridOptions are defined by the application developer and overlaid
  6317. * over this object. Setting gridOptions within your controller is the most common method for an application
  6318. * developer to configure the behaviour of their ui-grid
  6319. *
  6320. * @example To define your gridOptions within your controller:
  6321. * <pre>$scope.gridOptions = {
  6322. * data: $scope.myData,
  6323. * columnDefs: [
  6324. * { name: 'field1', displayName: 'pretty display name' },
  6325. * { name: 'field2', visible: false }
  6326. * ]
  6327. * };</pre>
  6328. *
  6329. * You can then use this within your html template, when you define your grid:
  6330. * <pre>&lt;div ui-grid="gridOptions"&gt;&lt;/div&gt;</pre>
  6331. *
  6332. * To provide default options for all of the grids within your application, use an angular
  6333. * decorator to modify the GridOptions factory.
  6334. * <pre>
  6335. * app.config(function($provide){
  6336. * $provide.decorator('GridOptions',function($delegate){
  6337. * var gridOptions;
  6338. * gridOptions = angular.copy($delegate);
  6339. * gridOptions.initialize = function(options) {
  6340. * var initOptions;
  6341. * initOptions = $delegate.initialize(options);
  6342. * initOptions.enableColumnMenus = false;
  6343. * return initOptions;
  6344. * };
  6345. * return gridOptions;
  6346. * });
  6347. * });
  6348. * </pre>
  6349. */
  6350. return {
  6351. initialize: function( baseOptions ){
  6352. /**
  6353. * @ngdoc function
  6354. * @name onRegisterApi
  6355. * @propertyOf ui.grid.class:GridOptions
  6356. * @description A callback that returns the gridApi once the grid is instantiated, which is
  6357. * then used to interact with the grid programatically.
  6358. *
  6359. * Note that the gridApi.core.renderingComplete event is identical to this
  6360. * callback, but has the advantage that it can be called from multiple places
  6361. * if needed
  6362. *
  6363. * @example
  6364. * <pre>
  6365. * $scope.gridOptions.onRegisterApi = function ( gridApi ) {
  6366. * $scope.gridApi = gridApi;
  6367. * $scope.gridApi.selection.selectAllRows( $scope.gridApi.grid );
  6368. * };
  6369. * </pre>
  6370. *
  6371. */
  6372. baseOptions.onRegisterApi = baseOptions.onRegisterApi || angular.noop();
  6373. /**
  6374. * @ngdoc object
  6375. * @name data
  6376. * @propertyOf ui.grid.class:GridOptions
  6377. * @description (mandatory) Array of data to be rendered into the grid, providing the data source or data binding for
  6378. * the grid.
  6379. *
  6380. * Most commonly the data is an array of objects, where each object has a number of attributes.
  6381. * Each attribute automatically becomes a column in your grid. This array could, for example, be sourced from
  6382. * an angularJS $resource query request. The array can also contain complex objects, refer the binding tutorial
  6383. * for examples of that.
  6384. *
  6385. * The most flexible usage is to set your data on $scope:
  6386. *
  6387. * `$scope.data = data;`
  6388. *
  6389. * And then direct the grid to resolve whatever is in $scope.data:
  6390. *
  6391. * `$scope.gridOptions.data = 'data';`
  6392. *
  6393. * This is the most flexible approach as it allows you to replace $scope.data whenever you feel like it without
  6394. * getting pointer issues.
  6395. *
  6396. * Alternatively you can directly set the data array:
  6397. *
  6398. * `$scope.gridOptions.data = [ ];`
  6399. * or
  6400. *
  6401. * `$http.get('/data/100.json')
  6402. * .success(function(data) {
  6403. * $scope.myData = data;
  6404. * $scope.gridOptions.data = $scope.myData;
  6405. * });`
  6406. *
  6407. * Where you do this, you need to take care in updating the data - you can't just update `$scope.myData` to some other
  6408. * array, you need to update $scope.gridOptions.data to point to that new array as well.
  6409. *
  6410. */
  6411. baseOptions.data = baseOptions.data || [];
  6412. /**
  6413. * @ngdoc array
  6414. * @name columnDefs
  6415. * @propertyOf ui.grid.class:GridOptions
  6416. * @description Array of columnDef objects. Only required property is name.
  6417. * The individual options available in columnDefs are documented in the
  6418. * {@link ui.grid.class:GridOptions.columnDef columnDef} section
  6419. * </br>_field property can be used in place of name for backwards compatibility with 2.x_
  6420. * @example
  6421. *
  6422. * <pre>var columnDefs = [{name:'field1'}, {name:'field2'}];</pre>
  6423. *
  6424. */
  6425. baseOptions.columnDefs = baseOptions.columnDefs || [];
  6426. /**
  6427. * @ngdoc object
  6428. * @name ui.grid.class:GridOptions.columnDef
  6429. * @description Definition / configuration of an individual column, which would typically be
  6430. * one of many column definitions within the gridOptions.columnDefs array
  6431. * @example
  6432. * <pre>{name:'field1', field: 'field1', filter: { term: 'xxx' }}</pre>
  6433. *
  6434. */
  6435. /**
  6436. * @ngdoc array
  6437. * @name excludeProperties
  6438. * @propertyOf ui.grid.class:GridOptions
  6439. * @description Array of property names in data to ignore when auto-generating column names. Provides the
  6440. * inverse of columnDefs - columnDefs is a list of columns to include, excludeProperties is a list of columns
  6441. * to exclude.
  6442. *
  6443. * If columnDefs is defined, this will be ignored.
  6444. *
  6445. * Defaults to ['$$hashKey']
  6446. */
  6447. baseOptions.excludeProperties = baseOptions.excludeProperties || ['$$hashKey'];
  6448. /**
  6449. * @ngdoc boolean
  6450. * @name enableRowHashing
  6451. * @propertyOf ui.grid.class:GridOptions
  6452. * @description True by default. When enabled, this setting allows uiGrid to add
  6453. * `$$hashKey`-type properties (similar to Angular) to elements in the `data` array. This allows
  6454. * the grid to maintain state while vastly speeding up the process of altering `data` by adding/moving/removing rows.
  6455. *
  6456. * Note that this DOES add properties to your data that you may not want, but they are stripped out when using `angular.toJson()`. IF
  6457. * you do not want this at all you can disable this setting but you will take a performance hit if you are using large numbers of rows
  6458. * and are altering the data set often.
  6459. */
  6460. baseOptions.enableRowHashing = baseOptions.enableRowHashing !== false;
  6461. /**
  6462. * @ngdoc function
  6463. * @name rowIdentity
  6464. * @methodOf ui.grid.class:GridOptions
  6465. * @description This function is used to get and, if necessary, set the value uniquely identifying this row (i.e. if an identity is not present it will set one).
  6466. *
  6467. * By default it returns the `$$hashKey` property if it exists. If it doesn't it uses gridUtil.nextUid() to generate one
  6468. */
  6469. baseOptions.rowIdentity = baseOptions.rowIdentity || function rowIdentity(row) {
  6470. return gridUtil.hashKey(row);
  6471. };
  6472. /**
  6473. * @ngdoc function
  6474. * @name getRowIdentity
  6475. * @methodOf ui.grid.class:GridOptions
  6476. * @description This function returns the identity value uniquely identifying this row, if one is not present it does not set it.
  6477. *
  6478. * By default it returns the `$$hashKey` property but can be overridden to use any property or set of properties you want.
  6479. */
  6480. baseOptions.getRowIdentity = baseOptions.getRowIdentity || function getRowIdentity(row) {
  6481. return row.$$hashKey;
  6482. };
  6483. /**
  6484. * @ngdoc property
  6485. * @name flatEntityAccess
  6486. * @propertyOf ui.grid.class:GridOptions
  6487. * @description Set to true if your columns are all related directly to fields in a flat object structure - i.e.
  6488. * each of your columns associate directly with a property on each of the entities in your data array.
  6489. *
  6490. * In that situation we can avoid all the logic associated with complex binding to functions or to properties of sub-objects,
  6491. * which can provide a significant speed improvement with large data sets when filtering or sorting.
  6492. *
  6493. * By default false
  6494. */
  6495. baseOptions.flatEntityAccess = baseOptions.flatEntityAccess === true;
  6496. /**
  6497. * @ngdoc property
  6498. * @name showHeader
  6499. * @propertyOf ui.grid.class:GridOptions
  6500. * @description True by default. When set to false, this setting will replace the
  6501. * standard header template with '<div></div>', resulting in no header being shown.
  6502. */
  6503. baseOptions.showHeader = typeof(baseOptions.showHeader) !== "undefined" ? baseOptions.showHeader : true;
  6504. /* (NOTE): Don't show this in the docs. We only use it internally
  6505. * @ngdoc property
  6506. * @name headerRowHeight
  6507. * @propertyOf ui.grid.class:GridOptions
  6508. * @description The height of the header in pixels, defaults to 30
  6509. *
  6510. */
  6511. if (!baseOptions.showHeader) {
  6512. baseOptions.headerRowHeight = 0;
  6513. }
  6514. else {
  6515. baseOptions.headerRowHeight = typeof(baseOptions.headerRowHeight) !== "undefined" ? baseOptions.headerRowHeight : 30;
  6516. }
  6517. /**
  6518. * @ngdoc property
  6519. * @name rowHeight
  6520. * @propertyOf ui.grid.class:GridOptions
  6521. * @description The height of the row in pixels, defaults to 30
  6522. *
  6523. */
  6524. baseOptions.rowHeight = baseOptions.rowHeight || 30;
  6525. /**
  6526. * @ngdoc integer
  6527. * @name minRowsToShow
  6528. * @propertyOf ui.grid.class:GridOptions
  6529. * @description Minimum number of rows to show when the grid doesn't have a defined height. Defaults to "10".
  6530. */
  6531. baseOptions.minRowsToShow = typeof(baseOptions.minRowsToShow) !== "undefined" ? baseOptions.minRowsToShow : 10;
  6532. /**
  6533. * @ngdoc property
  6534. * @name showGridFooter
  6535. * @propertyOf ui.grid.class:GridOptions
  6536. * @description Whether or not to show the footer, defaults to false
  6537. * The footer display Total Rows and Visible Rows (filtered rows)
  6538. */
  6539. baseOptions.showGridFooter = baseOptions.showGridFooter === true;
  6540. /**
  6541. * @ngdoc property
  6542. * @name showColumnFooter
  6543. * @propertyOf ui.grid.class:GridOptions
  6544. * @description Whether or not to show the column footer, defaults to false
  6545. * The column footer displays column aggregates
  6546. */
  6547. baseOptions.showColumnFooter = baseOptions.showColumnFooter === true;
  6548. /**
  6549. * @ngdoc property
  6550. * @name columnFooterHeight
  6551. * @propertyOf ui.grid.class:GridOptions
  6552. * @description The height of the footer rows (column footer and grid footer) in pixels
  6553. *
  6554. */
  6555. baseOptions.columnFooterHeight = typeof(baseOptions.columnFooterHeight) !== "undefined" ? baseOptions.columnFooterHeight : 30;
  6556. baseOptions.gridFooterHeight = typeof(baseOptions.gridFooterHeight) !== "undefined" ? baseOptions.gridFooterHeight : 30;
  6557. baseOptions.columnWidth = typeof(baseOptions.columnWidth) !== "undefined" ? baseOptions.columnWidth : 50;
  6558. /**
  6559. * @ngdoc property
  6560. * @name maxVisibleColumnCount
  6561. * @propertyOf ui.grid.class:GridOptions
  6562. * @description Defaults to 200
  6563. *
  6564. */
  6565. baseOptions.maxVisibleColumnCount = typeof(baseOptions.maxVisibleColumnCount) !== "undefined" ? baseOptions.maxVisibleColumnCount : 200;
  6566. /**
  6567. * @ngdoc property
  6568. * @name virtualizationThreshold
  6569. * @propertyOf ui.grid.class:GridOptions
  6570. * @description Turn virtualization on when number of data elements goes over this number, defaults to 20
  6571. */
  6572. baseOptions.virtualizationThreshold = typeof(baseOptions.virtualizationThreshold) !== "undefined" ? baseOptions.virtualizationThreshold : 20;
  6573. /**
  6574. * @ngdoc property
  6575. * @name columnVirtualizationThreshold
  6576. * @propertyOf ui.grid.class:GridOptions
  6577. * @description Turn virtualization on when number of columns goes over this number, defaults to 10
  6578. */
  6579. baseOptions.columnVirtualizationThreshold = typeof(baseOptions.columnVirtualizationThreshold) !== "undefined" ? baseOptions.columnVirtualizationThreshold : 10;
  6580. /**
  6581. * @ngdoc property
  6582. * @name excessRows
  6583. * @propertyOf ui.grid.class:GridOptions
  6584. * @description Extra rows to to render outside of the viewport, which helps with smoothness of scrolling.
  6585. * Defaults to 4
  6586. */
  6587. baseOptions.excessRows = typeof(baseOptions.excessRows) !== "undefined" ? baseOptions.excessRows : 4;
  6588. /**
  6589. * @ngdoc property
  6590. * @name scrollThreshold
  6591. * @propertyOf ui.grid.class:GridOptions
  6592. * @description Defaults to 4
  6593. */
  6594. baseOptions.scrollThreshold = typeof(baseOptions.scrollThreshold) !== "undefined" ? baseOptions.scrollThreshold : 4;
  6595. /**
  6596. * @ngdoc property
  6597. * @name excessColumns
  6598. * @propertyOf ui.grid.class:GridOptions
  6599. * @description Extra columns to to render outside of the viewport, which helps with smoothness of scrolling.
  6600. * Defaults to 4
  6601. */
  6602. baseOptions.excessColumns = typeof(baseOptions.excessColumns) !== "undefined" ? baseOptions.excessColumns : 4;
  6603. /**
  6604. * @ngdoc property
  6605. * @name horizontalScrollThreshold
  6606. * @propertyOf ui.grid.class:GridOptions
  6607. * @description Defaults to 4
  6608. */
  6609. baseOptions.horizontalScrollThreshold = typeof(baseOptions.horizontalScrollThreshold) !== "undefined" ? baseOptions.horizontalScrollThreshold : 2;
  6610. /**
  6611. * @ngdoc property
  6612. * @name aggregationCalcThrottle
  6613. * @propertyOf ui.grid.class:GridOptions
  6614. * @description Default time in milliseconds to throttle aggregation calcuations, defaults to 500ms
  6615. */
  6616. baseOptions.aggregationCalcThrottle = typeof(baseOptions.aggregationCalcThrottle) !== "undefined" ? baseOptions.aggregationCalcThrottle : 500;
  6617. /**
  6618. * @ngdoc property
  6619. * @name wheelScrollThrottle
  6620. * @propertyOf ui.grid.class:GridOptions
  6621. * @description Default time in milliseconds to throttle scroll events to, defaults to 70ms
  6622. */
  6623. baseOptions.wheelScrollThrottle = typeof(baseOptions.wheelScrollThrottle) !== "undefined" ? baseOptions.wheelScrollThrottle : 70;
  6624. /**
  6625. * @ngdoc property
  6626. * @name scrollDebounce
  6627. * @propertyOf ui.grid.class:GridOptions
  6628. * @description Default time in milliseconds to debounce scroll events, defaults to 300ms
  6629. */
  6630. baseOptions.scrollDebounce = typeof(baseOptions.scrollDebounce) !== "undefined" ? baseOptions.scrollDebounce : 300;
  6631. /**
  6632. * @ngdoc boolean
  6633. * @name enableSorting
  6634. * @propertyOf ui.grid.class:GridOptions
  6635. * @description True by default. When enabled, this setting adds sort
  6636. * widgets to the column headers, allowing sorting of the data for the entire grid.
  6637. * Sorting can then be disabled on individual columns using the columnDefs.
  6638. */
  6639. baseOptions.enableSorting = baseOptions.enableSorting !== false;
  6640. /**
  6641. * @ngdoc boolean
  6642. * @name enableFiltering
  6643. * @propertyOf ui.grid.class:GridOptions
  6644. * @description False by default. When enabled, this setting adds filter
  6645. * boxes to each column header, allowing filtering within the column for the entire grid.
  6646. * Filtering can then be disabled on individual columns using the columnDefs.
  6647. */
  6648. baseOptions.enableFiltering = baseOptions.enableFiltering === true;
  6649. /**
  6650. * @ngdoc boolean
  6651. * @name enableColumnMenus
  6652. * @propertyOf ui.grid.class:GridOptions
  6653. * @description True by default. When enabled, this setting displays a column
  6654. * menu within each column.
  6655. */
  6656. baseOptions.enableColumnMenus = baseOptions.enableColumnMenus !== false;
  6657. /**
  6658. * @ngdoc boolean
  6659. * @name enableVerticalScrollbar
  6660. * @propertyOf ui.grid.class:GridOptions
  6661. * @description uiGridConstants.scrollbars.ALWAYS by default. This settings controls the vertical scrollbar for the grid.
  6662. * Supported values: uiGridConstants.scrollbars.ALWAYS, uiGridConstants.scrollbars.NEVER
  6663. */
  6664. baseOptions.enableVerticalScrollbar = typeof(baseOptions.enableVerticalScrollbar) !== "undefined" ? baseOptions.enableVerticalScrollbar : uiGridConstants.scrollbars.ALWAYS;
  6665. /**
  6666. * @ngdoc boolean
  6667. * @name enableHorizontalScrollbar
  6668. * @propertyOf ui.grid.class:GridOptions
  6669. * @description uiGridConstants.scrollbars.ALWAYS by default. This settings controls the horizontal scrollbar for the grid.
  6670. * Supported values: uiGridConstants.scrollbars.ALWAYS, uiGridConstants.scrollbars.NEVER
  6671. */
  6672. baseOptions.enableHorizontalScrollbar = typeof(baseOptions.enableHorizontalScrollbar) !== "undefined" ? baseOptions.enableHorizontalScrollbar : uiGridConstants.scrollbars.ALWAYS;
  6673. /**
  6674. * @ngdoc boolean
  6675. * @name enableMinHeightCheck
  6676. * @propertyOf ui.grid.class:GridOptions
  6677. * @description True by default. When enabled, a newly initialized grid will check to see if it is tall enough to display
  6678. * at least one row of data. If the grid is not tall enough, it will resize the DOM element to display minRowsToShow number
  6679. * of rows.
  6680. */
  6681. baseOptions.enableMinHeightCheck = baseOptions.enableMinHeightCheck !== false;
  6682. /**
  6683. * @ngdoc boolean
  6684. * @name minimumColumnSize
  6685. * @propertyOf ui.grid.class:GridOptions
  6686. * @description Columns can't be smaller than this, defaults to 10 pixels
  6687. */
  6688. baseOptions.minimumColumnSize = typeof(baseOptions.minimumColumnSize) !== "undefined" ? baseOptions.minimumColumnSize : 10;
  6689. /**
  6690. * @ngdoc function
  6691. * @name rowEquality
  6692. * @methodOf ui.grid.class:GridOptions
  6693. * @description By default, rows are compared using object equality. This option can be overridden
  6694. * to compare on any data item property or function
  6695. * @param {object} entityA First Data Item to compare
  6696. * @param {object} entityB Second Data Item to compare
  6697. */
  6698. baseOptions.rowEquality = baseOptions.rowEquality || function(entityA, entityB) {
  6699. return entityA === entityB;
  6700. };
  6701. /**
  6702. * @ngdoc string
  6703. * @name headerTemplate
  6704. * @propertyOf ui.grid.class:GridOptions
  6705. * @description Null by default. When provided, this setting uses a custom header
  6706. * template, rather than the default template. Can be set to either the name of a template file:
  6707. * <pre> $scope.gridOptions.headerTemplate = 'header_template.html';</pre>
  6708. * inline html
  6709. * <pre> $scope.gridOptions.headerTemplate = '<div class="ui-grid-top-panel" style="text-align: center">I am a Custom Grid Header</div>'</pre>
  6710. * or the id of a precompiled template (TBD how to use this).
  6711. * </br>Refer to the custom header tutorial for more information.
  6712. * If you want no header at all, you can set to an empty div:
  6713. * <pre> $scope.gridOptions.headerTemplate = '<div></div>';</pre>
  6714. *
  6715. * If you want to only have a static header, then you can set to static content. If
  6716. * you want to tailor the existing column headers, then you should look at the
  6717. * current 'ui-grid-header.html' template in github as your starting point.
  6718. *
  6719. */
  6720. baseOptions.headerTemplate = baseOptions.headerTemplate || null;
  6721. /**
  6722. * @ngdoc string
  6723. * @name footerTemplate
  6724. * @propertyOf ui.grid.class:GridOptions
  6725. * @description (optional) ui-grid/ui-grid-footer by default. This footer shows the per-column
  6726. * aggregation totals.
  6727. * When provided, this setting uses a custom footer template. Can be set to either the name of a template file 'footer_template.html', inline html
  6728. * <pre>'<div class="ui-grid-bottom-panel" style="text-align: center">I am a Custom Grid Footer</div>'</pre>, or the id
  6729. * of a precompiled template (TBD how to use this). Refer to the custom footer tutorial for more information.
  6730. */
  6731. baseOptions.footerTemplate = baseOptions.footerTemplate || 'ui-grid/ui-grid-footer';
  6732. /**
  6733. * @ngdoc string
  6734. * @name gridFooterTemplate
  6735. * @propertyOf ui.grid.class:GridOptions
  6736. * @description (optional) ui-grid/ui-grid-grid-footer by default. This template by default shows the
  6737. * total items at the bottom of the grid, and the selected items if selection is enabled.
  6738. */
  6739. baseOptions.gridFooterTemplate = baseOptions.gridFooterTemplate || 'ui-grid/ui-grid-grid-footer';
  6740. /**
  6741. * @ngdoc string
  6742. * @name rowTemplate
  6743. * @propertyOf ui.grid.class:GridOptions
  6744. * @description 'ui-grid/ui-grid-row' by default. When provided, this setting uses a
  6745. * custom row template. Can be set to either the name of a template file:
  6746. * <pre> $scope.gridOptions.rowTemplate = 'row_template.html';</pre>
  6747. * inline html
  6748. * <pre> $scope.gridOptions.rowTemplate = '<div style="background-color: aquamarine" ng-click="grid.appScope.fnOne(row)" ng-repeat="col in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ui-grid-cell></div>';</pre>
  6749. * or the id of a precompiled template (TBD how to use this) can be provided.
  6750. * </br>Refer to the custom row template tutorial for more information.
  6751. */
  6752. baseOptions.rowTemplate = baseOptions.rowTemplate || 'ui-grid/ui-grid-row';
  6753. /**
  6754. * @ngdoc object
  6755. * @name appScopeProvider
  6756. * @propertyOf ui.grid.class:GridOptions
  6757. * @description by default, the parent scope of the ui-grid element will be assigned to grid.appScope
  6758. * this property allows you to assign any reference you want to grid.appScope
  6759. */
  6760. baseOptions.appScopeProvider = baseOptions.appScopeProvider || null;
  6761. return baseOptions;
  6762. }
  6763. };
  6764. }]);
  6765. })();
  6766. (function(){
  6767. angular.module('ui.grid')
  6768. /**
  6769. * @ngdoc function
  6770. * @name ui.grid.class:GridRenderContainer
  6771. * @description The grid has render containers, allowing the ability to have pinned columns. If the grid
  6772. * is right-to-left then there may be a right render container, if left-to-right then there may
  6773. * be a left render container. There is always a body render container.
  6774. * @param {string} name The name of the render container ('body', 'left', or 'right')
  6775. * @param {Grid} grid the grid the render container is in
  6776. * @param {object} options the render container options
  6777. */
  6778. .factory('GridRenderContainer', ['gridUtil', 'uiGridConstants', function(gridUtil, uiGridConstants) {
  6779. function GridRenderContainer(name, grid, options) {
  6780. var self = this;
  6781. // if (gridUtil.type(grid) !== 'Grid') {
  6782. // throw new Error('Grid argument is not a Grid object');
  6783. // }
  6784. self.name = name;
  6785. self.grid = grid;
  6786. // self.rowCache = [];
  6787. // self.columnCache = [];
  6788. self.visibleRowCache = [];
  6789. self.visibleColumnCache = [];
  6790. self.renderedRows = [];
  6791. self.renderedColumns = [];
  6792. self.prevScrollTop = 0;
  6793. self.prevScrolltopPercentage = 0;
  6794. self.prevRowScrollIndex = 0;
  6795. self.prevScrollLeft = 0;
  6796. self.prevScrollleftPercentage = 0;
  6797. self.prevColumnScrollIndex = 0;
  6798. self.columnStyles = "";
  6799. self.viewportAdjusters = [];
  6800. /**
  6801. * @ngdoc boolean
  6802. * @name hasHScrollbar
  6803. * @propertyOf ui.grid.class:GridRenderContainer
  6804. * @description flag to signal that container has a horizontal scrollbar
  6805. */
  6806. self.hasHScrollbar = false;
  6807. /**
  6808. * @ngdoc boolean
  6809. * @name hasVScrollbar
  6810. * @propertyOf ui.grid.class:GridRenderContainer
  6811. * @description flag to signal that container has a vertical scrollbar
  6812. */
  6813. self.hasVScrollbar = false;
  6814. /**
  6815. * @ngdoc boolean
  6816. * @name canvasHeightShouldUpdate
  6817. * @propertyOf ui.grid.class:GridRenderContainer
  6818. * @description flag to signal that container should recalculate the canvas size
  6819. */
  6820. self.canvasHeightShouldUpdate = true;
  6821. /**
  6822. * @ngdoc boolean
  6823. * @name canvasHeight
  6824. * @propertyOf ui.grid.class:GridRenderContainer
  6825. * @description last calculated canvas height value
  6826. */
  6827. self.$$canvasHeight = 0;
  6828. if (options && angular.isObject(options)) {
  6829. angular.extend(self, options);
  6830. }
  6831. grid.registerStyleComputation({
  6832. priority: 5,
  6833. func: function () {
  6834. self.updateColumnWidths();
  6835. return self.columnStyles;
  6836. }
  6837. });
  6838. }
  6839. GridRenderContainer.prototype.reset = function reset() {
  6840. // this.rowCache.length = 0;
  6841. // this.columnCache.length = 0;
  6842. this.visibleColumnCache.length = 0;
  6843. this.visibleRowCache.length = 0;
  6844. this.renderedRows.length = 0;
  6845. this.renderedColumns.length = 0;
  6846. };
  6847. // TODO(c0bra): calculate size?? Should this be in a stackable directive?
  6848. GridRenderContainer.prototype.containsColumn = function (col) {
  6849. return this.visibleColumnCache.indexOf(col) !== -1;
  6850. };
  6851. GridRenderContainer.prototype.minRowsToRender = function minRowsToRender() {
  6852. var self = this;
  6853. var minRows = 0;
  6854. var rowAddedHeight = 0;
  6855. var viewPortHeight = self.getViewportHeight();
  6856. for (var i = self.visibleRowCache.length - 1; rowAddedHeight < viewPortHeight && i >= 0; i--) {
  6857. rowAddedHeight += self.visibleRowCache[i].height;
  6858. minRows++;
  6859. }
  6860. return minRows;
  6861. };
  6862. GridRenderContainer.prototype.minColumnsToRender = function minColumnsToRender() {
  6863. var self = this;
  6864. var viewportWidth = this.getViewportWidth();
  6865. var min = 0;
  6866. var totalWidth = 0;
  6867. // self.columns.forEach(function(col, i) {
  6868. for (var i = 0; i < self.visibleColumnCache.length; i++) {
  6869. var col = self.visibleColumnCache[i];
  6870. if (totalWidth < viewportWidth) {
  6871. totalWidth += col.drawnWidth ? col.drawnWidth : 0;
  6872. min++;
  6873. }
  6874. else {
  6875. var currWidth = 0;
  6876. for (var j = i; j >= i - min; j--) {
  6877. currWidth += self.visibleColumnCache[j].drawnWidth ? self.visibleColumnCache[j].drawnWidth : 0;
  6878. }
  6879. if (currWidth < viewportWidth) {
  6880. min++;
  6881. }
  6882. }
  6883. }
  6884. return min;
  6885. };
  6886. GridRenderContainer.prototype.getVisibleRowCount = function getVisibleRowCount() {
  6887. return this.visibleRowCache.length;
  6888. };
  6889. /**
  6890. * @ngdoc function
  6891. * @name registerViewportAdjuster
  6892. * @methodOf ui.grid.class:GridRenderContainer
  6893. * @description Registers an adjuster to the render container's available width or height. Adjusters are used
  6894. * to tell the render container that there is something else consuming space, and to adjust it's size
  6895. * appropriately.
  6896. * @param {function} func the adjuster function we want to register
  6897. */
  6898. GridRenderContainer.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) {
  6899. this.viewportAdjusters.push(func);
  6900. };
  6901. /**
  6902. * @ngdoc function
  6903. * @name removeViewportAdjuster
  6904. * @methodOf ui.grid.class:GridRenderContainer
  6905. * @description Removes an adjuster, should be used when your element is destroyed
  6906. * @param {function} func the adjuster function we want to remove
  6907. */
  6908. GridRenderContainer.prototype.removeViewportAdjuster = function removeViewportAdjuster(func) {
  6909. var idx = this.viewportAdjusters.indexOf(func);
  6910. if (idx > -1) {
  6911. this.viewportAdjusters.splice(idx, 1);
  6912. }
  6913. };
  6914. /**
  6915. * @ngdoc function
  6916. * @name getViewportAdjustment
  6917. * @methodOf ui.grid.class:GridRenderContainer
  6918. * @description Gets the adjustment based on the viewportAdjusters.
  6919. * @returns {object} a hash of { height: x, width: y }. Usually the values will be negative
  6920. */
  6921. GridRenderContainer.prototype.getViewportAdjustment = function getViewportAdjustment() {
  6922. var self = this;
  6923. var adjustment = { height: 0, width: 0 };
  6924. self.viewportAdjusters.forEach(function (func) {
  6925. adjustment = func.call(this, adjustment);
  6926. });
  6927. return adjustment;
  6928. };
  6929. GridRenderContainer.prototype.getMargin = function getMargin(side) {
  6930. var self = this;
  6931. var amount = 0;
  6932. self.viewportAdjusters.forEach(function (func) {
  6933. var adjustment = func.call(this, { height: 0, width: 0 });
  6934. if (adjustment.side && adjustment.side === side) {
  6935. amount += adjustment.width * -1;
  6936. }
  6937. });
  6938. return amount;
  6939. };
  6940. GridRenderContainer.prototype.getViewportHeight = function getViewportHeight() {
  6941. var self = this;
  6942. var headerHeight = (self.headerHeight) ? self.headerHeight : self.grid.headerHeight;
  6943. var viewPortHeight = self.grid.gridHeight - headerHeight - self.grid.footerHeight;
  6944. var adjustment = self.getViewportAdjustment();
  6945. viewPortHeight = viewPortHeight + adjustment.height;
  6946. return viewPortHeight;
  6947. };
  6948. GridRenderContainer.prototype.getViewportWidth = function getViewportWidth() {
  6949. var self = this;
  6950. var viewportWidth = self.grid.gridWidth;
  6951. //if (typeof(self.grid.verticalScrollbarWidth) !== 'undefined' && self.grid.verticalScrollbarWidth !== undefined && self.grid.verticalScrollbarWidth > 0) {
  6952. // viewPortWidth = viewPortWidth - self.grid.verticalScrollbarWidth;
  6953. //}
  6954. // var viewportWidth = 0;\
  6955. // self.visibleColumnCache.forEach(function (column) {
  6956. // viewportWidth += column.drawnWidth;
  6957. // });
  6958. var adjustment = self.getViewportAdjustment();
  6959. viewportWidth = viewportWidth + adjustment.width;
  6960. return viewportWidth;
  6961. };
  6962. GridRenderContainer.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() {
  6963. var self = this;
  6964. var viewportWidth = this.getViewportWidth();
  6965. //if (typeof(self.grid.verticalScrollbarWidth) !== 'undefined' && self.grid.verticalScrollbarWidth !== undefined && self.grid.verticalScrollbarWidth > 0) {
  6966. // viewPortWidth = viewPortWidth + self.grid.verticalScrollbarWidth;
  6967. //}
  6968. // var adjustment = self.getViewportAdjustment();
  6969. // viewPortWidth = viewPortWidth + adjustment.width;
  6970. return viewportWidth;
  6971. };
  6972. /**
  6973. * @ngdoc function
  6974. * @name getCanvasHeight
  6975. * @methodOf ui.grid.class:GridRenderContainer
  6976. * @description Returns the total canvas height. Only recalculates if canvasHeightShouldUpdate = false
  6977. * @returns {number} total height of all the visible rows in the container
  6978. */
  6979. GridRenderContainer.prototype.getCanvasHeight = function getCanvasHeight() {
  6980. var self = this;
  6981. if (!self.canvasHeightShouldUpdate) {
  6982. return self.$$canvasHeight;
  6983. }
  6984. var oldCanvasHeight = self.$$canvasHeight;
  6985. self.$$canvasHeight = 0;
  6986. self.visibleRowCache.forEach(function(row){
  6987. self.$$canvasHeight += row.height;
  6988. });
  6989. self.canvasHeightShouldUpdate = false;
  6990. self.grid.api.core.raise.canvasHeightChanged(oldCanvasHeight, self.$$canvasHeight);
  6991. return self.$$canvasHeight;
  6992. };
  6993. GridRenderContainer.prototype.getVerticalScrollLength = function getVerticalScrollLength() {
  6994. return this.getCanvasHeight() - this.getViewportHeight() + this.grid.scrollbarHeight;
  6995. };
  6996. GridRenderContainer.prototype.getCanvasWidth = function getCanvasWidth() {
  6997. var self = this;
  6998. var ret = self.canvasWidth;
  6999. return ret;
  7000. };
  7001. GridRenderContainer.prototype.setRenderedRows = function setRenderedRows(newRows) {
  7002. this.renderedRows.length = newRows.length;
  7003. for (var i = 0; i < newRows.length; i++) {
  7004. this.renderedRows[i] = newRows[i];
  7005. }
  7006. };
  7007. GridRenderContainer.prototype.setRenderedColumns = function setRenderedColumns(newColumns) {
  7008. var self = this;
  7009. // OLD:
  7010. this.renderedColumns.length = newColumns.length;
  7011. for (var i = 0; i < newColumns.length; i++) {
  7012. this.renderedColumns[i] = newColumns[i];
  7013. }
  7014. this.updateColumnOffset();
  7015. };
  7016. GridRenderContainer.prototype.updateColumnOffset = function updateColumnOffset() {
  7017. // Calculate the width of the columns on the left side that are no longer rendered.
  7018. // That will be the offset for the columns as we scroll horizontally.
  7019. var hiddenColumnsWidth = 0;
  7020. for (var i = 0; i < this.currentFirstColumn; i++) {
  7021. hiddenColumnsWidth += this.visibleColumnCache[i].drawnWidth;
  7022. }
  7023. this.columnOffset = hiddenColumnsWidth;
  7024. };
  7025. GridRenderContainer.prototype.scrollVertical = function (newScrollTop) {
  7026. var vertScrollPercentage = -1;
  7027. if (newScrollTop !== this.prevScrollTop) {
  7028. var yDiff = newScrollTop - this.prevScrollTop;
  7029. if (yDiff > 0 ) { this.grid.scrollDirection = uiGridConstants.scrollDirection.DOWN; }
  7030. if (yDiff < 0 ) { this.grid.scrollDirection = uiGridConstants.scrollDirection.UP; }
  7031. var vertScrollLength = this.getVerticalScrollLength();
  7032. vertScrollPercentage = newScrollTop / vertScrollLength;
  7033. // console.log('vert', vertScrollPercentage, newScrollTop, vertScrollLength);
  7034. if (vertScrollPercentage > 1) { vertScrollPercentage = 1; }
  7035. if (vertScrollPercentage < 0) { vertScrollPercentage = 0; }
  7036. this.adjustScrollVertical(newScrollTop, vertScrollPercentage);
  7037. return vertScrollPercentage;
  7038. }
  7039. };
  7040. GridRenderContainer.prototype.scrollHorizontal = function(newScrollLeft){
  7041. var horizScrollPercentage = -1;
  7042. // Handle RTL here
  7043. if (newScrollLeft !== this.prevScrollLeft) {
  7044. var xDiff = newScrollLeft - this.prevScrollLeft;
  7045. if (xDiff > 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.RIGHT; }
  7046. if (xDiff < 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.LEFT; }
  7047. var horizScrollLength = (this.canvasWidth - this.getViewportWidth());
  7048. if (horizScrollLength !== 0) {
  7049. horizScrollPercentage = newScrollLeft / horizScrollLength;
  7050. }
  7051. else {
  7052. horizScrollPercentage = 0;
  7053. }
  7054. this.adjustScrollHorizontal(newScrollLeft, horizScrollPercentage);
  7055. return horizScrollPercentage;
  7056. }
  7057. };
  7058. GridRenderContainer.prototype.adjustScrollVertical = function adjustScrollVertical(scrollTop, scrollPercentage, force) {
  7059. if (this.prevScrollTop === scrollTop && !force) {
  7060. return;
  7061. }
  7062. if (typeof(scrollTop) === 'undefined' || scrollTop === undefined || scrollTop === null) {
  7063. scrollTop = (this.getCanvasHeight() - this.getViewportHeight()) * scrollPercentage;
  7064. }
  7065. this.adjustRows(scrollTop, scrollPercentage, false);
  7066. this.prevScrollTop = scrollTop;
  7067. this.prevScrolltopPercentage = scrollPercentage;
  7068. this.grid.queueRefresh();
  7069. };
  7070. GridRenderContainer.prototype.adjustScrollHorizontal = function adjustScrollHorizontal(scrollLeft, scrollPercentage, force) {
  7071. if (this.prevScrollLeft === scrollLeft && !force) {
  7072. return;
  7073. }
  7074. if (typeof(scrollLeft) === 'undefined' || scrollLeft === undefined || scrollLeft === null) {
  7075. scrollLeft = (this.getCanvasWidth() - this.getViewportWidth()) * scrollPercentage;
  7076. }
  7077. this.adjustColumns(scrollLeft, scrollPercentage);
  7078. this.prevScrollLeft = scrollLeft;
  7079. this.prevScrollleftPercentage = scrollPercentage;
  7080. this.grid.queueRefresh();
  7081. };
  7082. GridRenderContainer.prototype.adjustRows = function adjustRows(scrollTop, scrollPercentage, postDataLoaded) {
  7083. var self = this;
  7084. var minRows = self.minRowsToRender();
  7085. var rowCache = self.visibleRowCache;
  7086. var maxRowIndex = rowCache.length - minRows;
  7087. // console.log('scroll%1', scrollPercentage);
  7088. // Calculate the scroll percentage according to the scrollTop location, if no percentage was provided
  7089. if ((typeof(scrollPercentage) === 'undefined' || scrollPercentage === null) && scrollTop) {
  7090. scrollPercentage = scrollTop / self.getVerticalScrollLength();
  7091. }
  7092. var rowIndex = Math.ceil(Math.min(maxRowIndex, maxRowIndex * scrollPercentage));
  7093. // console.log('maxRowIndex / scroll%', maxRowIndex, scrollPercentage, rowIndex);
  7094. // Define a max row index that we can't scroll past
  7095. if (rowIndex > maxRowIndex) {
  7096. rowIndex = maxRowIndex;
  7097. }
  7098. var newRange = [];
  7099. if (rowCache.length > self.grid.options.virtualizationThreshold) {
  7100. if (!(typeof(scrollTop) === 'undefined' || scrollTop === null)) {
  7101. // Have we hit the threshold going down?
  7102. if ( !self.grid.suppressParentScrollDown && self.prevScrollTop < scrollTop && rowIndex < self.prevRowScrollIndex + self.grid.options.scrollThreshold && rowIndex < maxRowIndex) {
  7103. return;
  7104. }
  7105. //Have we hit the threshold going up?
  7106. if ( !self.grid.suppressParentScrollUp && self.prevScrollTop > scrollTop && rowIndex > self.prevRowScrollIndex - self.grid.options.scrollThreshold && rowIndex < maxRowIndex) {
  7107. return;
  7108. }
  7109. }
  7110. var rangeStart = {};
  7111. var rangeEnd = {};
  7112. rangeStart = Math.max(0, rowIndex - self.grid.options.excessRows);
  7113. rangeEnd = Math.min(rowCache.length, rowIndex + minRows + self.grid.options.excessRows);
  7114. newRange = [rangeStart, rangeEnd];
  7115. }
  7116. else {
  7117. var maxLen = self.visibleRowCache.length;
  7118. newRange = [0, Math.max(maxLen, minRows + self.grid.options.excessRows)];
  7119. }
  7120. self.updateViewableRowRange(newRange);
  7121. self.prevRowScrollIndex = rowIndex;
  7122. };
  7123. GridRenderContainer.prototype.adjustColumns = function adjustColumns(scrollLeft, scrollPercentage) {
  7124. var self = this;
  7125. var minCols = self.minColumnsToRender();
  7126. var columnCache = self.visibleColumnCache;
  7127. var maxColumnIndex = columnCache.length - minCols;
  7128. // Calculate the scroll percentage according to the scrollLeft location, if no percentage was provided
  7129. if ((typeof(scrollPercentage) === 'undefined' || scrollPercentage === null) && scrollLeft) {
  7130. var horizScrollLength = (self.getCanvasWidth() - self.getViewportWidth());
  7131. scrollPercentage = scrollLeft / horizScrollLength;
  7132. }
  7133. var colIndex = Math.ceil(Math.min(maxColumnIndex, maxColumnIndex * scrollPercentage));
  7134. // Define a max row index that we can't scroll past
  7135. if (colIndex > maxColumnIndex) {
  7136. colIndex = maxColumnIndex;
  7137. }
  7138. var newRange = [];
  7139. if (columnCache.length > self.grid.options.columnVirtualizationThreshold && self.getCanvasWidth() > self.getViewportWidth()) {
  7140. /* Commented the following lines because otherwise the moved column wasn't visible immediately on the new position
  7141. * in the case of many columns with horizontal scroll, one had to scroll left or right and then return in order to see it
  7142. // Have we hit the threshold going down?
  7143. if (self.prevScrollLeft < scrollLeft && colIndex < self.prevColumnScrollIndex + self.grid.options.horizontalScrollThreshold && colIndex < maxColumnIndex) {
  7144. return;
  7145. }
  7146. //Have we hit the threshold going up?
  7147. if (self.prevScrollLeft > scrollLeft && colIndex > self.prevColumnScrollIndex - self.grid.options.horizontalScrollThreshold && colIndex < maxColumnIndex) {
  7148. return;
  7149. }*/
  7150. var rangeStart = Math.max(0, colIndex - self.grid.options.excessColumns);
  7151. var rangeEnd = Math.min(columnCache.length, colIndex + minCols + self.grid.options.excessColumns);
  7152. newRange = [rangeStart, rangeEnd];
  7153. }
  7154. else {
  7155. var maxLen = self.visibleColumnCache.length;
  7156. newRange = [0, Math.max(maxLen, minCols + self.grid.options.excessColumns)];
  7157. }
  7158. self.updateViewableColumnRange(newRange);
  7159. self.prevColumnScrollIndex = colIndex;
  7160. };
  7161. // Method for updating the visible rows
  7162. GridRenderContainer.prototype.updateViewableRowRange = function updateViewableRowRange(renderedRange) {
  7163. // Slice out the range of rows from the data
  7164. // var rowArr = uiGridCtrl.grid.rows.slice(renderedRange[0], renderedRange[1]);
  7165. var rowArr = this.visibleRowCache.slice(renderedRange[0], renderedRange[1]);
  7166. // Define the top-most rendered row
  7167. this.currentTopRow = renderedRange[0];
  7168. this.setRenderedRows(rowArr);
  7169. };
  7170. // Method for updating the visible columns
  7171. GridRenderContainer.prototype.updateViewableColumnRange = function updateViewableColumnRange(renderedRange) {
  7172. // Slice out the range of rows from the data
  7173. // var columnArr = uiGridCtrl.grid.columns.slice(renderedRange[0], renderedRange[1]);
  7174. var columnArr = this.visibleColumnCache.slice(renderedRange[0], renderedRange[1]);
  7175. // Define the left-most rendered columns
  7176. this.currentFirstColumn = renderedRange[0];
  7177. this.setRenderedColumns(columnArr);
  7178. };
  7179. GridRenderContainer.prototype.headerCellWrapperStyle = function () {
  7180. var self = this;
  7181. if (self.currentFirstColumn !== 0) {
  7182. var offset = self.columnOffset;
  7183. if (self.grid.isRTL()) {
  7184. return { 'margin-right': offset + 'px' };
  7185. }
  7186. else {
  7187. return { 'margin-left': offset + 'px' };
  7188. }
  7189. }
  7190. return null;
  7191. };
  7192. /**
  7193. * @ngdoc boolean
  7194. * @name updateColumnWidths
  7195. * @propertyOf ui.grid.class:GridRenderContainer
  7196. * @description Determine the appropriate column width of each column across all render containers.
  7197. *
  7198. * Column width is easy when each column has a specified width. When columns are variable width (i.e.
  7199. * have an * or % of the viewport) then we try to calculate so that things fit in. The problem is that
  7200. * we have multiple render containers, and we don't want one render container to just take the whole viewport
  7201. * when it doesn't need to - we want things to balance out across the render containers.
  7202. *
  7203. * To do this, we use this method to calculate all the renderContainers, recognising that in a given render
  7204. * cycle it'll get called once per render container, so it needs to return the same values each time.
  7205. *
  7206. * The constraints on this method are therefore:
  7207. * - must return the same value when called multiple times, to do this it needs to rely on properties of the
  7208. * columns, but not properties that change when this is called (so it shouldn't rely on drawnWidth)
  7209. *
  7210. * The general logic of this method is:
  7211. * - calculate our total available width
  7212. * - look at all the columns across all render containers, and work out which have widths and which have
  7213. * constraints such as % or * or something else
  7214. * - for those with *, count the total number of * we see and add it onto a running total, add this column to an * array
  7215. * - for those with a %, allocate the % as a percentage of the viewport, having consideration of min and max
  7216. * - for those with manual width (in pixels) we set the drawnWidth to the specified width
  7217. * - we end up with an asterisks array still to process
  7218. * - we look at our remaining width. If it's greater than zero, we divide it up among the asterisk columns, then process
  7219. * them for min and max width constraints
  7220. * - if it's zero or less, we set the asterisk columns to their minimum widths
  7221. * - we use parseInt quite a bit, as we try to make all our column widths integers
  7222. */
  7223. GridRenderContainer.prototype.updateColumnWidths = function () {
  7224. var self = this;
  7225. var asterisksArray = [],
  7226. asteriskNum = 0,
  7227. usedWidthSum = 0,
  7228. ret = '';
  7229. // Get the width of the viewport
  7230. var availableWidth = self.grid.getViewportWidth() - self.grid.scrollbarWidth;
  7231. // get all the columns across all render containers, we have to calculate them all or one render container
  7232. // could consume the whole viewport
  7233. var columnCache = [];
  7234. angular.forEach(self.grid.renderContainers, function( container, name){
  7235. columnCache = columnCache.concat(container.visibleColumnCache);
  7236. });
  7237. // look at each column, process any manual values or %, put the * into an array to look at later
  7238. columnCache.forEach(function(column, i) {
  7239. var width = 0;
  7240. // Skip hidden columns
  7241. if (!column.visible) { return; }
  7242. if (angular.isNumber(column.width)) {
  7243. // pixel width, set to this value
  7244. width = parseInt(column.width, 10);
  7245. usedWidthSum = usedWidthSum + width;
  7246. column.drawnWidth = width;
  7247. } else if (gridUtil.endsWith(column.width, "%")) {
  7248. // percentage width, set to percentage of the viewport
  7249. width = parseInt(parseInt(column.width.replace(/%/g, ''), 10) / 100 * availableWidth);
  7250. if ( width > column.maxWidth ){
  7251. width = column.maxWidth;
  7252. }
  7253. if ( width < column.minWidth ){
  7254. width = column.minWidth;
  7255. }
  7256. usedWidthSum = usedWidthSum + width;
  7257. column.drawnWidth = width;
  7258. } else if (angular.isString(column.width) && column.width.indexOf('*') !== -1) {
  7259. // is an asterisk column, the gridColumn already checked the string consists only of '****'
  7260. asteriskNum = asteriskNum + column.width.length;
  7261. asterisksArray.push(column);
  7262. }
  7263. });
  7264. // Get the remaining width (available width subtracted by the used widths sum)
  7265. var remainingWidth = availableWidth - usedWidthSum;
  7266. var i, column, colWidth;
  7267. if (asterisksArray.length > 0) {
  7268. // the width that each asterisk value would be assigned (this can be negative)
  7269. var asteriskVal = remainingWidth / asteriskNum;
  7270. asterisksArray.forEach(function( column ){
  7271. var width = parseInt(column.width.length * asteriskVal, 10);
  7272. if ( width > column.maxWidth ){
  7273. width = column.maxWidth;
  7274. }
  7275. if ( width < column.minWidth ){
  7276. width = column.minWidth;
  7277. }
  7278. usedWidthSum = usedWidthSum + width;
  7279. column.drawnWidth = width;
  7280. });
  7281. }
  7282. // If the grid width didn't divide evenly into the column widths and we have pixels left over, or our
  7283. // calculated widths would have the grid narrower than the available space,
  7284. // dole the remainder out one by one to make everything fit
  7285. var processColumnUpwards = function(column){
  7286. if ( column.drawnWidth < column.maxWidth && leftoverWidth > 0) {
  7287. column.drawnWidth++;
  7288. usedWidthSum++;
  7289. leftoverWidth--;
  7290. columnsToChange = true;
  7291. }
  7292. };
  7293. var leftoverWidth = availableWidth - usedWidthSum;
  7294. var columnsToChange = true;
  7295. while (leftoverWidth > 0 && columnsToChange) {
  7296. columnsToChange = false;
  7297. asterisksArray.forEach(processColumnUpwards);
  7298. }
  7299. // We can end up with too much width even though some columns aren't at their max width, in this situation
  7300. // we can trim the columns a little
  7301. var processColumnDownwards = function(column){
  7302. if ( column.drawnWidth > column.minWidth && excessWidth > 0) {
  7303. column.drawnWidth--;
  7304. usedWidthSum--;
  7305. excessWidth--;
  7306. columnsToChange = true;
  7307. }
  7308. };
  7309. var excessWidth = usedWidthSum - availableWidth;
  7310. columnsToChange = true;
  7311. while (excessWidth > 0 && columnsToChange) {
  7312. columnsToChange = false;
  7313. asterisksArray.forEach(processColumnDownwards);
  7314. }
  7315. // all that was across all the renderContainers, now we need to work out what that calculation decided for
  7316. // our renderContainer
  7317. var canvasWidth = 0;
  7318. self.visibleColumnCache.forEach(function(column){
  7319. if ( column.visible ){
  7320. canvasWidth = canvasWidth + column.drawnWidth;
  7321. }
  7322. });
  7323. // Build the CSS
  7324. columnCache.forEach(function (column) {
  7325. ret = ret + column.getColClassDefinition();
  7326. });
  7327. self.canvasWidth = canvasWidth;
  7328. // Return the styles back to buildStyles which pops them into the `customStyles` scope variable
  7329. // return ret;
  7330. // Set this render container's column styles so they can be used in style computation
  7331. this.columnStyles = ret;
  7332. };
  7333. GridRenderContainer.prototype.needsHScrollbarPlaceholder = function () {
  7334. return this.grid.options.enableHorizontalScrollbar && !this.hasHScrollbar;
  7335. };
  7336. GridRenderContainer.prototype.getViewportStyle = function () {
  7337. var self = this;
  7338. var styles = {};
  7339. self.hasHScrollbar = false;
  7340. self.hasVScrollbar = false;
  7341. if (self.grid.disableScrolling) {
  7342. styles['overflow-x'] = 'hidden';
  7343. styles['overflow-y'] = 'hidden';
  7344. return styles;
  7345. }
  7346. if (self.name === 'body') {
  7347. self.hasHScrollbar = self.grid.options.enableHorizontalScrollbar !== uiGridConstants.scrollbars.NEVER;
  7348. if (!self.grid.isRTL()) {
  7349. if (!self.grid.hasRightContainerColumns()) {
  7350. self.hasVScrollbar = self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER;
  7351. }
  7352. }
  7353. else {
  7354. if (!self.grid.hasLeftContainerColumns()) {
  7355. self.hasVScrollbar = self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER;
  7356. }
  7357. }
  7358. }
  7359. else if (self.name === 'left') {
  7360. self.hasVScrollbar = self.grid.isRTL() ? self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER : false;
  7361. }
  7362. else {
  7363. self.hasVScrollbar = !self.grid.isRTL() ? self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER : false;
  7364. }
  7365. styles['overflow-x'] = self.hasHScrollbar ? 'scroll' : 'hidden';
  7366. styles['overflow-y'] = self.hasVScrollbar ? 'scroll' : 'hidden';
  7367. return styles;
  7368. };
  7369. return GridRenderContainer;
  7370. }]);
  7371. })();
  7372. (function(){
  7373. angular.module('ui.grid')
  7374. .factory('GridRow', ['gridUtil', function(gridUtil) {
  7375. /**
  7376. * @ngdoc function
  7377. * @name ui.grid.class:GridRow
  7378. * @description GridRow is the viewModel for one logical row on the grid. A grid Row is not necessarily a one-to-one
  7379. * relation to gridOptions.data.
  7380. * @param {object} entity the array item from GridOptions.data
  7381. * @param {number} index the current position of the row in the array
  7382. * @param {Grid} reference to the parent grid
  7383. */
  7384. function GridRow(entity, index, grid) {
  7385. /**
  7386. * @ngdoc object
  7387. * @name grid
  7388. * @propertyOf ui.grid.class:GridRow
  7389. * @description A reference back to the grid
  7390. */
  7391. this.grid = grid;
  7392. /**
  7393. * @ngdoc object
  7394. * @name entity
  7395. * @propertyOf ui.grid.class:GridRow
  7396. * @description A reference to an item in gridOptions.data[]
  7397. */
  7398. this.entity = entity;
  7399. /**
  7400. * @ngdoc object
  7401. * @name uid
  7402. * @propertyOf ui.grid.class:GridRow
  7403. * @description UniqueId of row
  7404. */
  7405. this.uid = gridUtil.nextUid();
  7406. /**
  7407. * @ngdoc object
  7408. * @name visible
  7409. * @propertyOf ui.grid.class:GridRow
  7410. * @description If true, the row will be rendered
  7411. */
  7412. // Default to true
  7413. this.visible = true;
  7414. this.$$height = grid.options.rowHeight;
  7415. }
  7416. /**
  7417. * @ngdoc object
  7418. * @name height
  7419. * @propertyOf ui.grid.class:GridRow
  7420. * @description height of each individual row. changing the height will flag all
  7421. * row renderContainers to recalculate their canvas height
  7422. */
  7423. Object.defineProperty(GridRow.prototype, 'height', {
  7424. get: function() {
  7425. return this.$$height;
  7426. },
  7427. set: function(height) {
  7428. if (height !== this.$$height) {
  7429. this.grid.updateCanvasHeight();
  7430. this.$$height = height;
  7431. }
  7432. }
  7433. });
  7434. /**
  7435. * @ngdoc function
  7436. * @name getQualifiedColField
  7437. * @methodOf ui.grid.class:GridRow
  7438. * @description returns the qualified field name as it exists on scope
  7439. * ie: row.entity.fieldA
  7440. * @param {GridCol} col column instance
  7441. * @returns {string} resulting name that can be evaluated on scope
  7442. */
  7443. GridRow.prototype.getQualifiedColField = function(col) {
  7444. return 'row.' + this.getEntityQualifiedColField(col);
  7445. };
  7446. /**
  7447. * @ngdoc function
  7448. * @name getEntityQualifiedColField
  7449. * @methodOf ui.grid.class:GridRow
  7450. * @description returns the qualified field name minus the row path
  7451. * ie: entity.fieldA
  7452. * @param {GridCol} col column instance
  7453. * @returns {string} resulting name that can be evaluated against a row
  7454. */
  7455. GridRow.prototype.getEntityQualifiedColField = function(col) {
  7456. return gridUtil.preEval('entity.' + col.field);
  7457. };
  7458. /**
  7459. * @ngdoc function
  7460. * @name setRowInvisible
  7461. * @methodOf ui.grid.class:GridRow
  7462. * @description Sets an override on the row that forces it to always
  7463. * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility.
  7464. *
  7465. * This method can be called from the api, passing in the gridRow we want
  7466. * altered. It should really work by calling gridRow.setRowInvisible, but that's
  7467. * not the way I coded it, and too late to change now. Changed to just call
  7468. * the internal function row.setThisRowInvisible().
  7469. *
  7470. * @param {GridRow} row the row we want to set to invisible
  7471. *
  7472. */
  7473. GridRow.prototype.setRowInvisible = function ( row ) {
  7474. if (row && row.setThisRowInvisible){
  7475. row.setThisRowInvisible( 'user' );
  7476. }
  7477. };
  7478. /**
  7479. * @ngdoc function
  7480. * @name clearRowInvisible
  7481. * @methodOf ui.grid.class:GridRow
  7482. * @description Clears an override on the row that forces it to always
  7483. * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility.
  7484. *
  7485. * This method can be called from the api, passing in the gridRow we want
  7486. * altered. It should really work by calling gridRow.clearRowInvisible, but that's
  7487. * not the way I coded it, and too late to change now. Changed to just call
  7488. * the internal function row.clearThisRowInvisible().
  7489. *
  7490. * @param {GridRow} row the row we want to clear the invisible flag
  7491. *
  7492. */
  7493. GridRow.prototype.clearRowInvisible = function ( row ) {
  7494. if (row && row.clearThisRowInvisible){
  7495. row.clearThisRowInvisible( 'user' );
  7496. }
  7497. };
  7498. /**
  7499. * @ngdoc function
  7500. * @name setThisRowInvisible
  7501. * @methodOf ui.grid.class:GridRow
  7502. * @description Sets an override on the row that forces it to always
  7503. * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility
  7504. *
  7505. * @param {string} reason the reason (usually the module) for the row to be invisible.
  7506. * E.g. grouping, user, filter
  7507. * @param {boolean} fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility
  7508. */
  7509. GridRow.prototype.setThisRowInvisible = function ( reason, fromRowsProcessor ) {
  7510. if ( !this.invisibleReason ){
  7511. this.invisibleReason = {};
  7512. }
  7513. this.invisibleReason[reason] = true;
  7514. this.evaluateRowVisibility( fromRowsProcessor);
  7515. };
  7516. /**
  7517. * @ngdoc function
  7518. * @name clearRowInvisible
  7519. * @methodOf ui.grid.class:GridRow
  7520. * @description Clears any override on the row visibility, returning it
  7521. * to normal visibility calculations. Emits the rowsVisibleChanged
  7522. * event
  7523. *
  7524. * @param {string} reason the reason (usually the module) for the row to be invisible.
  7525. * E.g. grouping, user, filter
  7526. * @param {boolean} fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility
  7527. */
  7528. GridRow.prototype.clearThisRowInvisible = function ( reason, fromRowsProcessor ) {
  7529. if (typeof(this.invisibleReason) !== 'undefined' ) {
  7530. delete this.invisibleReason[reason];
  7531. }
  7532. this.evaluateRowVisibility( fromRowsProcessor );
  7533. };
  7534. /**
  7535. * @ngdoc function
  7536. * @name evaluateRowVisibility
  7537. * @methodOf ui.grid.class:GridRow
  7538. * @description Determines whether the row should be visible based on invisibleReason,
  7539. * and if it changes the row visibility, then emits the rowsVisibleChanged event.
  7540. *
  7541. * Queues a grid refresh, but doesn't call it directly to avoid hitting lots of grid refreshes.
  7542. * @param {boolean} fromRowProcessor if true, then it won't raise events or queue the refresh, the
  7543. * row processor does that already
  7544. */
  7545. GridRow.prototype.evaluateRowVisibility = function ( fromRowProcessor ) {
  7546. var newVisibility = true;
  7547. if ( typeof(this.invisibleReason) !== 'undefined' ){
  7548. angular.forEach(this.invisibleReason, function( value, key ){
  7549. if ( value ){
  7550. newVisibility = false;
  7551. }
  7552. });
  7553. }
  7554. if ( typeof(this.visible) === 'undefined' || this.visible !== newVisibility ){
  7555. this.visible = newVisibility;
  7556. if ( !fromRowProcessor ){
  7557. this.grid.queueGridRefresh();
  7558. this.grid.api.core.raise.rowsVisibleChanged(this);
  7559. }
  7560. }
  7561. };
  7562. return GridRow;
  7563. }]);
  7564. })();
  7565. (function(){
  7566. 'use strict';
  7567. /**
  7568. * @ngdoc object
  7569. * @name ui.grid.class:GridRowColumn
  7570. * @param {GridRow} row The row for this pair
  7571. * @param {GridColumn} column The column for this pair
  7572. * @description A row and column pair that represents the intersection of these two entities.
  7573. * Must be instantiated as a constructor using the `new` keyword.
  7574. */
  7575. angular.module('ui.grid')
  7576. .factory('GridRowColumn', ['$parse', '$filter',
  7577. function GridRowColumnFactory($parse, $filter){
  7578. var GridRowColumn = function GridRowColumn(row, col) {
  7579. if ( !(this instanceof GridRowColumn)){
  7580. throw "Using GridRowColumn as a function insead of as a constructor. Must be called with `new` keyword";
  7581. }
  7582. /**
  7583. * @ngdoc object
  7584. * @name row
  7585. * @propertyOf ui.grid.class:GridRowColumn
  7586. * @description {@link ui.grid.class:GridRow }
  7587. */
  7588. this.row = row;
  7589. /**
  7590. * @ngdoc object
  7591. * @name col
  7592. * @propertyOf ui.grid.class:GridRowColumn
  7593. * @description {@link ui.grid.class:GridColumn }
  7594. */
  7595. this.col = col;
  7596. };
  7597. /**
  7598. * @ngdoc function
  7599. * @name getIntersectionValueRaw
  7600. * @methodOf ui.grid.class:GridRowColumn
  7601. * @description Gets the intersection of where the row and column meet.
  7602. * @returns {String|Number|Object} The value from the grid data that this GridRowColumn points too.
  7603. * If the column has a cellFilter this will NOT return the filtered value.
  7604. */
  7605. GridRowColumn.prototype.getIntersectionValueRaw = function(){
  7606. var getter = $parse(this.row.getEntityQualifiedColField(this.col));
  7607. var context = this.row;
  7608. return getter(context);
  7609. };
  7610. /**
  7611. * @ngdoc function
  7612. * @name getIntersectionValueFiltered
  7613. * @methodOf ui.grid.class:GridRowColumn
  7614. * @description Gets the intersection of where the row and column meet.
  7615. * @returns {String|Number|Object} The value from the grid data that this GridRowColumn points too.
  7616. * If the column has a cellFilter this will also apply the filter to it and return the value that the filter displays.
  7617. */
  7618. GridRowColumn.prototype.getIntersectionValueFiltered = function(){
  7619. var value = this.getIntersectionValueRaw();
  7620. if (this.col.cellFilter && this.col.cellFilter !== ''){
  7621. var getFilterIfExists = function(filterName){
  7622. try {
  7623. return $filter(filterName);
  7624. } catch (e){
  7625. return null;
  7626. }
  7627. };
  7628. var filter = getFilterIfExists(this.col.cellFilter);
  7629. if (filter) { // Check if this is filter name or a filter string
  7630. value = filter(value);
  7631. } else { // We have the template version of a filter so we need to parse it apart
  7632. // Get the filter params out using a regex
  7633. // Test out this regex here https://regex101.com/r/rC5eR5/2
  7634. var re = /([^:]*):([^:]*):?([\s\S]+)?/;
  7635. var matches;
  7636. if ((matches = re.exec(this.col.cellFilter)) !== null) {
  7637. // View your result using the matches-variable.
  7638. // eg matches[0] etc.
  7639. value = $filter(matches[1])(value, matches[2], matches[3]);
  7640. }
  7641. }
  7642. }
  7643. return value;
  7644. };
  7645. return GridRowColumn;
  7646. }
  7647. ]);
  7648. })();
  7649. (function () {
  7650. angular.module('ui.grid')
  7651. .factory('ScrollEvent', ['gridUtil', function (gridUtil) {
  7652. /**
  7653. * @ngdoc function
  7654. * @name ui.grid.class:ScrollEvent
  7655. * @description Model for all scrollEvents
  7656. * @param {Grid} grid that owns the scroll event
  7657. * @param {GridRenderContainer} sourceRowContainer that owns the scroll event. Can be null
  7658. * @param {GridRenderContainer} sourceColContainer that owns the scroll event. Can be null
  7659. * @param {string} source the source of the event - from uiGridConstants.scrollEventSources or a string value of directive/service/factory.functionName
  7660. */
  7661. function ScrollEvent(grid, sourceRowContainer, sourceColContainer, source) {
  7662. var self = this;
  7663. if (!grid) {
  7664. throw new Error("grid argument is required");
  7665. }
  7666. /**
  7667. * @ngdoc object
  7668. * @name grid
  7669. * @propertyOf ui.grid.class:ScrollEvent
  7670. * @description A reference back to the grid
  7671. */
  7672. self.grid = grid;
  7673. /**
  7674. * @ngdoc object
  7675. * @name source
  7676. * @propertyOf ui.grid.class:ScrollEvent
  7677. * @description the source of the scroll event. limited to values from uiGridConstants.scrollEventSources
  7678. */
  7679. self.source = source;
  7680. /**
  7681. * @ngdoc object
  7682. * @name noDelay
  7683. * @propertyOf ui.grid.class:ScrollEvent
  7684. * @description most scroll events from the mouse or trackpad require delay to operate properly
  7685. * set to false to eliminate delay. Useful for scroll events that the grid causes, such as scrolling to make a row visible.
  7686. */
  7687. self.withDelay = true;
  7688. self.sourceRowContainer = sourceRowContainer;
  7689. self.sourceColContainer = sourceColContainer;
  7690. self.newScrollLeft = null;
  7691. self.newScrollTop = null;
  7692. self.x = null;
  7693. self.y = null;
  7694. self.verticalScrollLength = -9999999;
  7695. self.horizontalScrollLength = -999999;
  7696. /**
  7697. * @ngdoc function
  7698. * @name fireThrottledScrollingEvent
  7699. * @methodOf ui.grid.class:ScrollEvent
  7700. * @description fires a throttled event using grid.api.core.raise.scrollEvent
  7701. */
  7702. self.fireThrottledScrollingEvent = gridUtil.throttle(function(sourceContainerId) {
  7703. self.grid.scrollContainers(sourceContainerId, self);
  7704. }, self.grid.options.wheelScrollThrottle, {trailing: true});
  7705. }
  7706. /**
  7707. * @ngdoc function
  7708. * @name getNewScrollLeft
  7709. * @methodOf ui.grid.class:ScrollEvent
  7710. * @description returns newScrollLeft property if available; calculates a new value if it isn't
  7711. */
  7712. ScrollEvent.prototype.getNewScrollLeft = function(colContainer, viewport){
  7713. var self = this;
  7714. if (!self.newScrollLeft){
  7715. var scrollWidth = (colContainer.getCanvasWidth() - colContainer.getViewportWidth());
  7716. var oldScrollLeft = gridUtil.normalizeScrollLeft(viewport, self.grid);
  7717. var scrollXPercentage;
  7718. if (typeof(self.x.percentage) !== 'undefined' && self.x.percentage !== undefined) {
  7719. scrollXPercentage = self.x.percentage;
  7720. }
  7721. else if (typeof(self.x.pixels) !== 'undefined' && self.x.pixels !== undefined) {
  7722. scrollXPercentage = self.x.percentage = (oldScrollLeft + self.x.pixels) / scrollWidth;
  7723. }
  7724. else {
  7725. throw new Error("No percentage or pixel value provided for scroll event X axis");
  7726. }
  7727. return Math.max(0, scrollXPercentage * scrollWidth);
  7728. }
  7729. return self.newScrollLeft;
  7730. };
  7731. /**
  7732. * @ngdoc function
  7733. * @name getNewScrollTop
  7734. * @methodOf ui.grid.class:ScrollEvent
  7735. * @description returns newScrollTop property if available; calculates a new value if it isn't
  7736. */
  7737. ScrollEvent.prototype.getNewScrollTop = function(rowContainer, viewport){
  7738. var self = this;
  7739. if (!self.newScrollTop){
  7740. var scrollLength = rowContainer.getVerticalScrollLength();
  7741. var oldScrollTop = viewport[0].scrollTop;
  7742. var scrollYPercentage;
  7743. if (typeof(self.y.percentage) !== 'undefined' && self.y.percentage !== undefined) {
  7744. scrollYPercentage = self.y.percentage;
  7745. }
  7746. else if (typeof(self.y.pixels) !== 'undefined' && self.y.pixels !== undefined) {
  7747. scrollYPercentage = self.y.percentage = (oldScrollTop + self.y.pixels) / scrollLength;
  7748. }
  7749. else {
  7750. throw new Error("No percentage or pixel value provided for scroll event Y axis");
  7751. }
  7752. return Math.max(0, scrollYPercentage * scrollLength);
  7753. }
  7754. return self.newScrollTop;
  7755. };
  7756. ScrollEvent.prototype.atTop = function(scrollTop) {
  7757. return (this.y && (this.y.percentage === 0 || this.verticalScrollLength < 0) && scrollTop === 0);
  7758. };
  7759. ScrollEvent.prototype.atBottom = function(scrollTop) {
  7760. return (this.y && (this.y.percentage === 1 || this.verticalScrollLength === 0) && scrollTop > 0);
  7761. };
  7762. ScrollEvent.prototype.atLeft = function(scrollLeft) {
  7763. return (this.x && (this.x.percentage === 0 || this.horizontalScrollLength < 0) && scrollLeft === 0);
  7764. };
  7765. ScrollEvent.prototype.atRight = function(scrollLeft) {
  7766. return (this.x && (this.x.percentage === 1 || this.horizontalScrollLength ===0) && scrollLeft > 0);
  7767. };
  7768. ScrollEvent.Sources = {
  7769. ViewPortScroll: 'ViewPortScroll',
  7770. RenderContainerMouseWheel: 'RenderContainerMouseWheel',
  7771. RenderContainerTouchMove: 'RenderContainerTouchMove',
  7772. Other: 99
  7773. };
  7774. return ScrollEvent;
  7775. }]);
  7776. })();
  7777. (function () {
  7778. 'use strict';
  7779. /**
  7780. * @ngdoc object
  7781. * @name ui.grid.service:gridClassFactory
  7782. *
  7783. * @description factory to return dom specific instances of a grid
  7784. *
  7785. */
  7786. angular.module('ui.grid').service('gridClassFactory', ['gridUtil', '$q', '$compile', '$templateCache', 'uiGridConstants', 'Grid', 'GridColumn', 'GridRow',
  7787. function (gridUtil, $q, $compile, $templateCache, uiGridConstants, Grid, GridColumn, GridRow) {
  7788. var service = {
  7789. /**
  7790. * @ngdoc method
  7791. * @name createGrid
  7792. * @methodOf ui.grid.service:gridClassFactory
  7793. * @description Creates a new grid instance. Each instance will have a unique id
  7794. * @param {object} options An object map of options to pass into the created grid instance.
  7795. * @returns {Grid} grid
  7796. */
  7797. createGrid : function(options) {
  7798. options = (typeof(options) !== 'undefined') ? options : {};
  7799. options.id = gridUtil.newId();
  7800. var grid = new Grid(options);
  7801. // NOTE/TODO: rowTemplate should always be defined...
  7802. if (grid.options.rowTemplate) {
  7803. var rowTemplateFnPromise = $q.defer();
  7804. grid.getRowTemplateFn = rowTemplateFnPromise.promise;
  7805. gridUtil.getTemplate(grid.options.rowTemplate)
  7806. .then(
  7807. function (template) {
  7808. var rowTemplateFn = $compile(template);
  7809. rowTemplateFnPromise.resolve(rowTemplateFn);
  7810. },
  7811. function (res) {
  7812. // Todo handle response error here?
  7813. throw new Error("Couldn't fetch/use row template '" + grid.options.rowTemplate + "'");
  7814. });
  7815. }
  7816. grid.registerColumnBuilder(service.defaultColumnBuilder);
  7817. // Row builder for custom row templates
  7818. grid.registerRowBuilder(service.rowTemplateAssigner);
  7819. // Reset all rows to visible initially
  7820. grid.registerRowsProcessor(function allRowsVisible(rows) {
  7821. rows.forEach(function (row) {
  7822. row.evaluateRowVisibility( true );
  7823. }, 50);
  7824. return rows;
  7825. });
  7826. grid.registerColumnsProcessor(function allColumnsVisible(columns) {
  7827. columns.forEach(function (column) {
  7828. column.visible = true;
  7829. });
  7830. return columns;
  7831. }, 50);
  7832. grid.registerColumnsProcessor(function(renderableColumns) {
  7833. renderableColumns.forEach(function (column) {
  7834. if (column.colDef.visible === false) {
  7835. column.visible = false;
  7836. }
  7837. });
  7838. return renderableColumns;
  7839. }, 50);
  7840. grid.registerRowsProcessor(grid.searchRows, 100);
  7841. // Register the default row processor, it sorts rows by selected columns
  7842. if (grid.options.externalSort && angular.isFunction(grid.options.externalSort)) {
  7843. grid.registerRowsProcessor(grid.options.externalSort, 200);
  7844. }
  7845. else {
  7846. grid.registerRowsProcessor(grid.sortByColumn, 200);
  7847. }
  7848. return grid;
  7849. },
  7850. /**
  7851. * @ngdoc function
  7852. * @name defaultColumnBuilder
  7853. * @methodOf ui.grid.service:gridClassFactory
  7854. * @description Processes designTime column definitions and applies them to col for the
  7855. * core grid features
  7856. * @param {object} colDef reference to column definition
  7857. * @param {GridColumn} col reference to gridCol
  7858. * @param {object} gridOptions reference to grid options
  7859. */
  7860. defaultColumnBuilder: function (colDef, col, gridOptions) {
  7861. var templateGetPromises = [];
  7862. // Abstracts the standard template processing we do for every template type.
  7863. var processTemplate = function( templateType, providedType, defaultTemplate, filterType, tooltipType ) {
  7864. if ( !colDef[templateType] ){
  7865. col[providedType] = defaultTemplate;
  7866. } else {
  7867. col[providedType] = colDef[templateType];
  7868. }
  7869. templateGetPromises.push(gridUtil.getTemplate(col[providedType])
  7870. .then(
  7871. function (template) {
  7872. if ( angular.isFunction(template) ) { template = template(); }
  7873. var tooltipCall = ( tooltipType === 'cellTooltip' ) ? 'col.cellTooltip(row,col)' : 'col.headerTooltip(col)';
  7874. if ( tooltipType && col[tooltipType] === false ){
  7875. template = template.replace(uiGridConstants.TOOLTIP, '');
  7876. } else if ( tooltipType && col[tooltipType] ){
  7877. template = template.replace(uiGridConstants.TOOLTIP, 'title="{{' + tooltipCall + ' CUSTOM_FILTERS }}"');
  7878. }
  7879. if ( filterType ){
  7880. col[templateType] = template.replace(uiGridConstants.CUSTOM_FILTERS, function() {
  7881. return col[filterType] ? "|" + col[filterType] : "";
  7882. });
  7883. } else {
  7884. col[templateType] = template;
  7885. }
  7886. },
  7887. function (res) {
  7888. throw new Error("Couldn't fetch/use colDef." + templateType + " '" + colDef[templateType] + "'");
  7889. })
  7890. );
  7891. };
  7892. /**
  7893. * @ngdoc property
  7894. * @name cellTemplate
  7895. * @propertyOf ui.grid.class:GridOptions.columnDef
  7896. * @description a custom template for each cell in this column. The default
  7897. * is ui-grid/uiGridCell. If you are using the cellNav feature, this template
  7898. * must contain a div that can receive focus.
  7899. *
  7900. */
  7901. processTemplate( 'cellTemplate', 'providedCellTemplate', 'ui-grid/uiGridCell', 'cellFilter', 'cellTooltip' );
  7902. col.cellTemplatePromise = templateGetPromises[0];
  7903. /**
  7904. * @ngdoc property
  7905. * @name headerCellTemplate
  7906. * @propertyOf ui.grid.class:GridOptions.columnDef
  7907. * @description a custom template for the header for this column. The default
  7908. * is ui-grid/uiGridHeaderCell
  7909. *
  7910. */
  7911. processTemplate( 'headerCellTemplate', 'providedHeaderCellTemplate', 'ui-grid/uiGridHeaderCell', 'headerCellFilter', 'headerTooltip' );
  7912. /**
  7913. * @ngdoc property
  7914. * @name footerCellTemplate
  7915. * @propertyOf ui.grid.class:GridOptions.columnDef
  7916. * @description a custom template for the footer for this column. The default
  7917. * is ui-grid/uiGridFooterCell
  7918. *
  7919. */
  7920. processTemplate( 'footerCellTemplate', 'providedFooterCellTemplate', 'ui-grid/uiGridFooterCell', 'footerCellFilter' );
  7921. /**
  7922. * @ngdoc property
  7923. * @name filterHeaderTemplate
  7924. * @propertyOf ui.grid.class:GridOptions.columnDef
  7925. * @description a custom template for the filter input. The default is ui-grid/ui-grid-filter
  7926. *
  7927. */
  7928. processTemplate( 'filterHeaderTemplate', 'providedFilterHeaderTemplate', 'ui-grid/ui-grid-filter' );
  7929. // Create a promise for the compiled element function
  7930. col.compiledElementFnDefer = $q.defer();
  7931. return $q.all(templateGetPromises);
  7932. },
  7933. rowTemplateAssigner: function rowTemplateAssigner(row) {
  7934. var grid = this;
  7935. // Row has no template assigned to it
  7936. if (!row.rowTemplate) {
  7937. // Use the default row template from the grid
  7938. row.rowTemplate = grid.options.rowTemplate;
  7939. // Use the grid's function for fetching the compiled row template function
  7940. row.getRowTemplateFn = grid.getRowTemplateFn;
  7941. }
  7942. // Row has its own template assigned
  7943. else {
  7944. // Create a promise for the compiled row template function
  7945. var perRowTemplateFnPromise = $q.defer();
  7946. row.getRowTemplateFn = perRowTemplateFnPromise.promise;
  7947. // Get the row template
  7948. gridUtil.getTemplate(row.rowTemplate)
  7949. .then(function (template) {
  7950. // Compile the template
  7951. var rowTemplateFn = $compile(template);
  7952. // Resolve the compiled template function promise
  7953. perRowTemplateFnPromise.resolve(rowTemplateFn);
  7954. },
  7955. function (res) {
  7956. // Todo handle response error here?
  7957. throw new Error("Couldn't fetch/use row template '" + row.rowTemplate + "'");
  7958. });
  7959. }
  7960. return row.getRowTemplateFn;
  7961. }
  7962. };
  7963. //class definitions (moved to separate factories)
  7964. return service;
  7965. }]);
  7966. })();
  7967. (function() {
  7968. var module = angular.module('ui.grid');
  7969. function escapeRegExp(str) {
  7970. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  7971. }
  7972. /**
  7973. * @ngdoc service
  7974. * @name ui.grid.service:rowSearcher
  7975. *
  7976. * @description Service for searching/filtering rows based on column value conditions.
  7977. */
  7978. module.service('rowSearcher', ['gridUtil', 'uiGridConstants', function (gridUtil, uiGridConstants) {
  7979. var defaultCondition = uiGridConstants.filter.CONTAINS;
  7980. var rowSearcher = {};
  7981. /**
  7982. * @ngdoc function
  7983. * @name getTerm
  7984. * @methodOf ui.grid.service:rowSearcher
  7985. * @description Get the term from a filter
  7986. * Trims leading and trailing whitespace
  7987. * @param {object} filter object to use
  7988. * @returns {object} Parsed term
  7989. */
  7990. rowSearcher.getTerm = function getTerm(filter) {
  7991. if (typeof(filter.term) === 'undefined') { return filter.term; }
  7992. var term = filter.term;
  7993. // Strip leading and trailing whitespace if the term is a string
  7994. if (typeof(term) === 'string') {
  7995. term = term.trim();
  7996. }
  7997. return term;
  7998. };
  7999. /**
  8000. * @ngdoc function
  8001. * @name stripTerm
  8002. * @methodOf ui.grid.service:rowSearcher
  8003. * @description Remove leading and trailing asterisk (*) from the filter's term
  8004. * @param {object} filter object to use
  8005. * @returns {uiGridConstants.filter<int>} Value representing the condition constant value
  8006. */
  8007. rowSearcher.stripTerm = function stripTerm(filter) {
  8008. var term = rowSearcher.getTerm(filter);
  8009. if (typeof(term) === 'string') {
  8010. return escapeRegExp(term.replace(/(^\*|\*$)/g, ''));
  8011. }
  8012. else {
  8013. return term;
  8014. }
  8015. };
  8016. /**
  8017. * @ngdoc function
  8018. * @name guessCondition
  8019. * @methodOf ui.grid.service:rowSearcher
  8020. * @description Guess the condition for a filter based on its term
  8021. * <br>
  8022. * Defaults to STARTS_WITH. Uses CONTAINS for strings beginning and ending with *s (*bob*).
  8023. * Uses STARTS_WITH for strings ending with * (bo*). Uses ENDS_WITH for strings starting with * (*ob).
  8024. * @param {object} filter object to use
  8025. * @returns {uiGridConstants.filter<int>} Value representing the condition constant value
  8026. */
  8027. rowSearcher.guessCondition = function guessCondition(filter) {
  8028. if (typeof(filter.term) === 'undefined' || !filter.term) {
  8029. return defaultCondition;
  8030. }
  8031. var term = rowSearcher.getTerm(filter);
  8032. if (/\*/.test(term)) {
  8033. var regexpFlags = '';
  8034. if (!filter.flags || !filter.flags.caseSensitive) {
  8035. regexpFlags += 'i';
  8036. }
  8037. var reText = term.replace(/(\\)?\*/g, function ($0, $1) { return $1 ? $0 : '[\\s\\S]*?'; });
  8038. return new RegExp('^' + reText + '$', regexpFlags);
  8039. }
  8040. // Otherwise default to default condition
  8041. else {
  8042. return defaultCondition;
  8043. }
  8044. };
  8045. /**
  8046. * @ngdoc function
  8047. * @name setupFilters
  8048. * @methodOf ui.grid.service:rowSearcher
  8049. * @description For a given columns filters (either col.filters, or [col.filter] can be passed in),
  8050. * do all the parsing and pre-processing and store that data into a new filters object. The object
  8051. * has the condition, the flags, the stripped term, and a parsed reg exp if there was one.
  8052. *
  8053. * We could use a forEach in here, since it's much less performance sensitive, but since we're using
  8054. * for loops everywhere else in this module...
  8055. *
  8056. * @param {array} filters the filters from the column (col.filters or [col.filter])
  8057. * @returns {array} An array of parsed/preprocessed filters
  8058. */
  8059. rowSearcher.setupFilters = function setupFilters( filters ){
  8060. var newFilters = [];
  8061. var filtersLength = filters.length;
  8062. for ( var i = 0; i < filtersLength; i++ ){
  8063. var filter = filters[i];
  8064. if ( filter.noTerm || !gridUtil.isNullOrUndefined(filter.term) ){
  8065. var newFilter = {};
  8066. var regexpFlags = '';
  8067. if (!filter.flags || !filter.flags.caseSensitive) {
  8068. regexpFlags += 'i';
  8069. }
  8070. if ( !gridUtil.isNullOrUndefined(filter.term) ){
  8071. // it is possible to have noTerm. We don't need to copy that across, it was just a flag to avoid
  8072. // getting the filter ignored if the filter was a function that didn't use a term
  8073. newFilter.term = rowSearcher.stripTerm(filter);
  8074. }
  8075. if ( filter.condition ){
  8076. newFilter.condition = filter.condition;
  8077. } else {
  8078. newFilter.condition = rowSearcher.guessCondition(filter);
  8079. }
  8080. newFilter.flags = angular.extend( { caseSensitive: false, date: false }, filter.flags );
  8081. if (newFilter.condition === uiGridConstants.filter.STARTS_WITH) {
  8082. newFilter.startswithRE = new RegExp('^' + newFilter.term, regexpFlags);
  8083. }
  8084. if (newFilter.condition === uiGridConstants.filter.ENDS_WITH) {
  8085. newFilter.endswithRE = new RegExp(newFilter.term + '$', regexpFlags);
  8086. }
  8087. if (newFilter.condition === uiGridConstants.filter.CONTAINS) {
  8088. newFilter.containsRE = new RegExp(newFilter.term, regexpFlags);
  8089. }
  8090. if (newFilter.condition === uiGridConstants.filter.EXACT) {
  8091. newFilter.exactRE = new RegExp('^' + newFilter.term + '$', regexpFlags);
  8092. }
  8093. newFilters.push(newFilter);
  8094. }
  8095. }
  8096. return newFilters;
  8097. };
  8098. /**
  8099. * @ngdoc function
  8100. * @name runColumnFilter
  8101. * @methodOf ui.grid.service:rowSearcher
  8102. * @description Runs a single pre-parsed filter against a cell, returning true
  8103. * if the cell matches that one filter.
  8104. *
  8105. * @param {Grid} grid the grid we're working against
  8106. * @param {GridRow} row the row we're matching against
  8107. * @param {GridCol} column the column that we're working against
  8108. * @param {object} filter the specific, preparsed, filter that we want to test
  8109. * @returns {boolean} true if we match (row stays visible)
  8110. */
  8111. rowSearcher.runColumnFilter = function runColumnFilter(grid, row, column, filter) {
  8112. // Cache typeof condition
  8113. var conditionType = typeof(filter.condition);
  8114. // Term to search for.
  8115. var term = filter.term;
  8116. // Get the column value for this row
  8117. var value;
  8118. if ( column.filterCellFiltered ){
  8119. value = grid.getCellDisplayValue(row, column);
  8120. } else {
  8121. value = grid.getCellValue(row, column);
  8122. }
  8123. // If the filter's condition is a RegExp, then use it
  8124. if (filter.condition instanceof RegExp) {
  8125. return filter.condition.test(value);
  8126. }
  8127. // If the filter's condition is a function, run it
  8128. if (conditionType === 'function') {
  8129. return filter.condition(term, value, row, column);
  8130. }
  8131. if (filter.startswithRE) {
  8132. return filter.startswithRE.test(value);
  8133. }
  8134. if (filter.endswithRE) {
  8135. return filter.endswithRE.test(value);
  8136. }
  8137. if (filter.containsRE) {
  8138. return filter.containsRE.test(value);
  8139. }
  8140. if (filter.exactRE) {
  8141. return filter.exactRE.test(value);
  8142. }
  8143. if (filter.condition === uiGridConstants.filter.NOT_EQUAL) {
  8144. var regex = new RegExp('^' + term + '$');
  8145. return !regex.exec(value);
  8146. }
  8147. if (typeof(value) === 'number' && typeof(term) === 'string' ){
  8148. // if the term has a decimal in it, it comes through as '9\.4', we need to take out the \
  8149. // the same for negative numbers
  8150. // TODO: I suspect the right answer is to look at escapeRegExp at the top of this code file, maybe it's not needed?
  8151. var tempFloat = parseFloat(term.replace(/\\\./,'.').replace(/\\\-/,'-'));
  8152. if (!isNaN(tempFloat)) {
  8153. term = tempFloat;
  8154. }
  8155. }
  8156. if (filter.flags.date === true) {
  8157. value = new Date(value);
  8158. // If the term has a dash in it, it comes through as '\-' -- we need to take out the '\'.
  8159. term = new Date(term.replace(/\\/g, ''));
  8160. }
  8161. if (filter.condition === uiGridConstants.filter.GREATER_THAN) {
  8162. return (value > term);
  8163. }
  8164. if (filter.condition === uiGridConstants.filter.GREATER_THAN_OR_EQUAL) {
  8165. return (value >= term);
  8166. }
  8167. if (filter.condition === uiGridConstants.filter.LESS_THAN) {
  8168. return (value < term);
  8169. }
  8170. if (filter.condition === uiGridConstants.filter.LESS_THAN_OR_EQUAL) {
  8171. return (value <= term);
  8172. }
  8173. return true;
  8174. };
  8175. /**
  8176. * @ngdoc boolean
  8177. * @name useExternalFiltering
  8178. * @propertyOf ui.grid.class:GridOptions
  8179. * @description False by default. When enabled, this setting suppresses the internal filtering.
  8180. * All UI logic will still operate, allowing filter conditions to be set and modified.
  8181. *
  8182. * The external filter logic can listen for the `filterChange` event, which fires whenever
  8183. * a filter has been adjusted.
  8184. */
  8185. /**
  8186. * @ngdoc function
  8187. * @name searchColumn
  8188. * @methodOf ui.grid.service:rowSearcher
  8189. * @description Process provided filters on provided column against a given row. If the row meets
  8190. * the conditions on all the filters, return true.
  8191. * @param {Grid} grid Grid to search in
  8192. * @param {GridRow} row Row to search on
  8193. * @param {GridCol} column Column with the filters to use
  8194. * @param {array} filters array of pre-parsed/preprocessed filters to apply
  8195. * @returns {boolean} Whether the column matches or not.
  8196. */
  8197. rowSearcher.searchColumn = function searchColumn(grid, row, column, filters) {
  8198. if (grid.options.useExternalFiltering) {
  8199. return true;
  8200. }
  8201. var filtersLength = filters.length;
  8202. for (var i = 0; i < filtersLength; i++) {
  8203. var filter = filters[i];
  8204. var ret = rowSearcher.runColumnFilter(grid, row, column, filter);
  8205. if (!ret) {
  8206. return false;
  8207. }
  8208. }
  8209. return true;
  8210. };
  8211. /**
  8212. * @ngdoc function
  8213. * @name search
  8214. * @methodOf ui.grid.service:rowSearcher
  8215. * @description Run a search across the given rows and columns, marking any rows that don't
  8216. * match the stored col.filters or col.filter as invisible.
  8217. * @param {Grid} grid Grid instance to search inside
  8218. * @param {Array[GridRow]} rows GridRows to filter
  8219. * @param {Array[GridColumn]} columns GridColumns with filters to process
  8220. */
  8221. rowSearcher.search = function search(grid, rows, columns) {
  8222. /*
  8223. * Added performance optimisations into this code base, as this logic creates deeply nested
  8224. * loops and is therefore very performance sensitive. In particular, avoiding forEach as
  8225. * this impacts some browser optimisers (particularly Chrome), using iterators instead
  8226. */
  8227. // Don't do anything if we weren't passed any rows
  8228. if (!rows) {
  8229. return;
  8230. }
  8231. // don't filter if filtering currently disabled
  8232. if (!grid.options.enableFiltering){
  8233. return rows;
  8234. }
  8235. // Build list of filters to apply
  8236. var filterData = [];
  8237. var colsLength = columns.length;
  8238. var hasTerm = function( filters ) {
  8239. var hasTerm = false;
  8240. filters.forEach( function (filter) {
  8241. if ( !gridUtil.isNullOrUndefined(filter.term) && filter.term !== '' || filter.noTerm ){
  8242. hasTerm = true;
  8243. }
  8244. });
  8245. return hasTerm;
  8246. };
  8247. for (var i = 0; i < colsLength; i++) {
  8248. var col = columns[i];
  8249. if (typeof(col.filters) !== 'undefined' && hasTerm(col.filters) ) {
  8250. filterData.push( { col: col, filters: rowSearcher.setupFilters(col.filters) } );
  8251. }
  8252. }
  8253. if (filterData.length > 0) {
  8254. // define functions outside the loop, performance optimisation
  8255. var foreachRow = function(grid, row, col, filters){
  8256. if ( row.visible && !rowSearcher.searchColumn(grid, row, col, filters) ) {
  8257. row.visible = false;
  8258. }
  8259. };
  8260. var foreachFilterCol = function(grid, filterData){
  8261. var rowsLength = rows.length;
  8262. for ( var i = 0; i < rowsLength; i++){
  8263. foreachRow(grid, rows[i], filterData.col, filterData.filters);
  8264. }
  8265. };
  8266. // nested loop itself - foreachFilterCol, which in turn calls foreachRow
  8267. var filterDataLength = filterData.length;
  8268. for ( var j = 0; j < filterDataLength; j++){
  8269. foreachFilterCol( grid, filterData[j] );
  8270. }
  8271. if (grid.api.core.raise.rowsVisibleChanged) {
  8272. grid.api.core.raise.rowsVisibleChanged();
  8273. }
  8274. // drop any invisible rows
  8275. // keeping these, as needed with filtering for trees - we have to come back and make parent nodes visible if child nodes are selected in the filter
  8276. // rows = rows.filter(function(row){ return row.visible; });
  8277. }
  8278. return rows;
  8279. };
  8280. return rowSearcher;
  8281. }]);
  8282. })();
  8283. (function() {
  8284. var module = angular.module('ui.grid');
  8285. /**
  8286. * @ngdoc object
  8287. * @name ui.grid.class:RowSorter
  8288. * @description RowSorter provides the default sorting mechanisms,
  8289. * including guessing column types and applying appropriate sort
  8290. * algorithms
  8291. *
  8292. */
  8293. module.service('rowSorter', ['$parse', 'uiGridConstants', function ($parse, uiGridConstants) {
  8294. var currencyRegexStr =
  8295. '(' +
  8296. uiGridConstants.CURRENCY_SYMBOLS
  8297. .map(function (a) { return '\\' + a; }) // Escape all the currency symbols ($ at least will jack up this regex)
  8298. .join('|') + // Join all the symbols together with |s
  8299. ')?';
  8300. // /^[-+]?[£$¤¥]?[\d,.]+%?$/
  8301. var numberStrRegex = new RegExp('^[-+]?' + currencyRegexStr + '[\\d,.]+' + currencyRegexStr + '%?$');
  8302. var rowSorter = {
  8303. // Cache of sorting functions. Once we create them, we don't want to keep re-doing it
  8304. // this takes a piece of data from the cell and tries to determine its type and what sorting
  8305. // function to use for it
  8306. colSortFnCache: {}
  8307. };
  8308. /**
  8309. * @ngdoc method
  8310. * @methodOf ui.grid.class:RowSorter
  8311. * @name guessSortFn
  8312. * @description Assigns a sort function to use based on the itemType in the column
  8313. * @param {string} itemType one of 'number', 'boolean', 'string', 'date', 'object'. And
  8314. * error will be thrown for any other type.
  8315. * @returns {function} a sort function that will sort that type
  8316. */
  8317. rowSorter.guessSortFn = function guessSortFn(itemType) {
  8318. switch (itemType) {
  8319. case "number":
  8320. return rowSorter.sortNumber;
  8321. case "numberStr":
  8322. return rowSorter.sortNumberStr;
  8323. case "boolean":
  8324. return rowSorter.sortBool;
  8325. case "string":
  8326. return rowSorter.sortAlpha;
  8327. case "date":
  8328. return rowSorter.sortDate;
  8329. case "object":
  8330. return rowSorter.basicSort;
  8331. default:
  8332. throw new Error('No sorting function found for type:' + itemType);
  8333. }
  8334. };
  8335. /**
  8336. * @ngdoc method
  8337. * @methodOf ui.grid.class:RowSorter
  8338. * @name handleNulls
  8339. * @description Sorts nulls and undefined to the bottom (top when
  8340. * descending). Called by each of the internal sorters before
  8341. * attempting to sort. Note that this method is available on the core api
  8342. * via gridApi.core.sortHandleNulls
  8343. * @param {object} a sort value a
  8344. * @param {object} b sort value b
  8345. * @returns {number} null if there were no nulls/undefineds, otherwise returns
  8346. * a sort value that should be passed back from the sort function
  8347. */
  8348. rowSorter.handleNulls = function handleNulls(a, b) {
  8349. // We want to allow zero values and false values to be evaluated in the sort function
  8350. if ((!a && a !== 0 && a !== false) || (!b && b !== 0 && b !== false)) {
  8351. // We want to force nulls and such to the bottom when we sort... which effectively is "greater than"
  8352. if ((!a && a !== 0 && a !== false) && (!b && b !== 0 && b !== false)) {
  8353. return 0;
  8354. }
  8355. else if (!a && a !== 0 && a !== false) {
  8356. return 1;
  8357. }
  8358. else if (!b && b !== 0 && b !== false) {
  8359. return -1;
  8360. }
  8361. }
  8362. return null;
  8363. };
  8364. /**
  8365. * @ngdoc method
  8366. * @methodOf ui.grid.class:RowSorter
  8367. * @name basicSort
  8368. * @description Sorts any values that provide the < method, including strings
  8369. * or numbers. Handles nulls and undefined through calling handleNulls
  8370. * @param {object} a sort value a
  8371. * @param {object} b sort value b
  8372. * @returns {number} normal sort function, returns -ve, 0, +ve
  8373. */
  8374. rowSorter.basicSort = function basicSort(a, b) {
  8375. var nulls = rowSorter.handleNulls(a, b);
  8376. if ( nulls !== null ){
  8377. return nulls;
  8378. } else {
  8379. if (a === b) {
  8380. return 0;
  8381. }
  8382. if (a < b) {
  8383. return -1;
  8384. }
  8385. return 1;
  8386. }
  8387. };
  8388. /**
  8389. * @ngdoc method
  8390. * @methodOf ui.grid.class:RowSorter
  8391. * @name sortNumber
  8392. * @description Sorts numerical values. Handles nulls and undefined through calling handleNulls
  8393. * @param {object} a sort value a
  8394. * @param {object} b sort value b
  8395. * @returns {number} normal sort function, returns -ve, 0, +ve
  8396. */
  8397. rowSorter.sortNumber = function sortNumber(a, b) {
  8398. var nulls = rowSorter.handleNulls(a, b);
  8399. if ( nulls !== null ){
  8400. return nulls;
  8401. } else {
  8402. return a - b;
  8403. }
  8404. };
  8405. /**
  8406. * @ngdoc method
  8407. * @methodOf ui.grid.class:RowSorter
  8408. * @name sortNumberStr
  8409. * @description Sorts numerical values that are stored in a string (i.e. parses them to numbers first).
  8410. * Handles nulls and undefined through calling handleNulls
  8411. * @param {object} a sort value a
  8412. * @param {object} b sort value b
  8413. * @returns {number} normal sort function, returns -ve, 0, +ve
  8414. */
  8415. rowSorter.sortNumberStr = function sortNumberStr(a, b) {
  8416. var nulls = rowSorter.handleNulls(a, b);
  8417. if ( nulls !== null ){
  8418. return nulls;
  8419. } else {
  8420. var numA, // The parsed number form of 'a'
  8421. numB, // The parsed number form of 'b'
  8422. badA = false,
  8423. badB = false;
  8424. // Try to parse 'a' to a float
  8425. numA = parseFloat(a.replace(/[^0-9.-]/g, ''));
  8426. // If 'a' couldn't be parsed to float, flag it as bad
  8427. if (isNaN(numA)) {
  8428. badA = true;
  8429. }
  8430. // Try to parse 'b' to a float
  8431. numB = parseFloat(b.replace(/[^0-9.-]/g, ''));
  8432. // If 'b' couldn't be parsed to float, flag it as bad
  8433. if (isNaN(numB)) {
  8434. badB = true;
  8435. }
  8436. // We want bad ones to get pushed to the bottom... which effectively is "greater than"
  8437. if (badA && badB) {
  8438. return 0;
  8439. }
  8440. if (badA) {
  8441. return 1;
  8442. }
  8443. if (badB) {
  8444. return -1;
  8445. }
  8446. return numA - numB;
  8447. }
  8448. };
  8449. /**
  8450. * @ngdoc method
  8451. * @methodOf ui.grid.class:RowSorter
  8452. * @name sortAlpha
  8453. * @description Sorts string values. Handles nulls and undefined through calling handleNulls
  8454. * @param {object} a sort value a
  8455. * @param {object} b sort value b
  8456. * @returns {number} normal sort function, returns -ve, 0, +ve
  8457. */
  8458. rowSorter.sortAlpha = function sortAlpha(a, b) {
  8459. var nulls = rowSorter.handleNulls(a, b);
  8460. if ( nulls !== null ){
  8461. return nulls;
  8462. } else {
  8463. var strA = a.toString().toLowerCase(),
  8464. strB = b.toString().toLowerCase();
  8465. return strA === strB ? 0 : (strA < strB ? -1 : 1);
  8466. }
  8467. };
  8468. /**
  8469. * @ngdoc method
  8470. * @methodOf ui.grid.class:RowSorter
  8471. * @name sortDate
  8472. * @description Sorts date values. Handles nulls and undefined through calling handleNulls.
  8473. * Handles date strings by converting to Date object if not already an instance of Date
  8474. * @param {object} a sort value a
  8475. * @param {object} b sort value b
  8476. * @returns {number} normal sort function, returns -ve, 0, +ve
  8477. */
  8478. rowSorter.sortDate = function sortDate(a, b) {
  8479. var nulls = rowSorter.handleNulls(a, b);
  8480. if ( nulls !== null ){
  8481. return nulls;
  8482. } else {
  8483. if (!(a instanceof Date)) {
  8484. a = new Date(a);
  8485. }
  8486. if (!(b instanceof Date)){
  8487. b = new Date(b);
  8488. }
  8489. var timeA = a.getTime(),
  8490. timeB = b.getTime();
  8491. return timeA === timeB ? 0 : (timeA < timeB ? -1 : 1);
  8492. }
  8493. };
  8494. /**
  8495. * @ngdoc method
  8496. * @methodOf ui.grid.class:RowSorter
  8497. * @name sortBool
  8498. * @description Sorts boolean values, true is considered larger than false.
  8499. * Handles nulls and undefined through calling handleNulls
  8500. * @param {object} a sort value a
  8501. * @param {object} b sort value b
  8502. * @returns {number} normal sort function, returns -ve, 0, +ve
  8503. */
  8504. rowSorter.sortBool = function sortBool(a, b) {
  8505. var nulls = rowSorter.handleNulls(a, b);
  8506. if ( nulls !== null ){
  8507. return nulls;
  8508. } else {
  8509. if (a && b) {
  8510. return 0;
  8511. }
  8512. if (!a && !b) {
  8513. return 0;
  8514. }
  8515. else {
  8516. return a ? 1 : -1;
  8517. }
  8518. }
  8519. };
  8520. /**
  8521. * @ngdoc method
  8522. * @methodOf ui.grid.class:RowSorter
  8523. * @name getSortFn
  8524. * @description Get the sort function for the column. Looks first in
  8525. * rowSorter.colSortFnCache using the column name, failing that it
  8526. * looks at col.sortingAlgorithm (and puts it in the cache), failing that
  8527. * it guesses the sort algorithm based on the data type.
  8528. *
  8529. * The cache currently seems a bit pointless, as none of the work we do is
  8530. * processor intensive enough to need caching. Presumably in future we might
  8531. * inspect the row data itself to guess the sort function, and in that case
  8532. * it would make sense to have a cache, the infrastructure is in place to allow
  8533. * that.
  8534. *
  8535. * @param {Grid} grid the grid to consider
  8536. * @param {GridCol} col the column to find a function for
  8537. * @param {array} rows an array of grid rows. Currently unused, but presumably in future
  8538. * we might inspect the rows themselves to decide what sort of data might be there
  8539. * @returns {function} the sort function chosen for the column
  8540. */
  8541. rowSorter.getSortFn = function getSortFn(grid, col, rows) {
  8542. var sortFn, item;
  8543. // See if we already figured out what to use to sort the column and have it in the cache
  8544. if (rowSorter.colSortFnCache[col.colDef.name]) {
  8545. sortFn = rowSorter.colSortFnCache[col.colDef.name];
  8546. }
  8547. // If the column has its OWN sorting algorithm, use that
  8548. else if (col.sortingAlgorithm !== undefined) {
  8549. sortFn = col.sortingAlgorithm;
  8550. rowSorter.colSortFnCache[col.colDef.name] = col.sortingAlgorithm;
  8551. }
  8552. // Always default to sortAlpha when sorting after a cellFilter
  8553. else if ( col.sortCellFiltered && col.cellFilter ){
  8554. sortFn = rowSorter.sortAlpha;
  8555. rowSorter.colSortFnCache[col.colDef.name] = sortFn;
  8556. }
  8557. // Try and guess what sort function to use
  8558. else {
  8559. // Guess the sort function
  8560. sortFn = rowSorter.guessSortFn(col.colDef.type);
  8561. // If we found a sort function, cache it
  8562. if (sortFn) {
  8563. rowSorter.colSortFnCache[col.colDef.name] = sortFn;
  8564. }
  8565. else {
  8566. // We assign the alpha sort because anything that is null/undefined will never get passed to
  8567. // the actual sorting function. It will get caught in our null check and returned to be sorted
  8568. // down to the bottom
  8569. sortFn = rowSorter.sortAlpha;
  8570. }
  8571. }
  8572. return sortFn;
  8573. };
  8574. /**
  8575. * @ngdoc method
  8576. * @methodOf ui.grid.class:RowSorter
  8577. * @name prioritySort
  8578. * @description Used where multiple columns are present in the sort criteria,
  8579. * we determine which column should take precedence in the sort by sorting
  8580. * the columns based on their sort.priority
  8581. *
  8582. * @param {gridColumn} a column a
  8583. * @param {gridColumn} b column b
  8584. * @returns {number} normal sort function, returns -ve, 0, +ve
  8585. */
  8586. rowSorter.prioritySort = function (a, b) {
  8587. // Both columns have a sort priority
  8588. if (a.sort.priority !== undefined && b.sort.priority !== undefined) {
  8589. // A is higher priority
  8590. if (a.sort.priority < b.sort.priority) {
  8591. return -1;
  8592. }
  8593. // Equal
  8594. else if (a.sort.priority === b.sort.priority) {
  8595. return 0;
  8596. }
  8597. // B is higher
  8598. else {
  8599. return 1;
  8600. }
  8601. }
  8602. // Only A has a priority
  8603. else if (a.sort.priority || a.sort.priority === 0) {
  8604. return -1;
  8605. }
  8606. // Only B has a priority
  8607. else if (b.sort.priority || b.sort.priority === 0) {
  8608. return 1;
  8609. }
  8610. // Neither has a priority
  8611. else {
  8612. return 0;
  8613. }
  8614. };
  8615. /**
  8616. * @ngdoc object
  8617. * @name useExternalSorting
  8618. * @propertyOf ui.grid.class:GridOptions
  8619. * @description Prevents the internal sorting from executing. Events will
  8620. * still be fired when the sort changes, and the sort information on
  8621. * the columns will be updated, allowing an external sorter (for example,
  8622. * server sorting) to be implemented. Defaults to false.
  8623. *
  8624. */
  8625. /**
  8626. * @ngdoc method
  8627. * @methodOf ui.grid.class:RowSorter
  8628. * @name sort
  8629. * @description sorts the grid
  8630. * @param {Object} grid the grid itself
  8631. * @param {array} rows the rows to be sorted
  8632. * @param {array} columns the columns in which to look
  8633. * for sort criteria
  8634. * @returns {array} sorted rows
  8635. */
  8636. rowSorter.sort = function rowSorterSort(grid, rows, columns) {
  8637. // first make sure we are even supposed to do work
  8638. if (!rows) {
  8639. return;
  8640. }
  8641. if (grid.options.useExternalSorting){
  8642. return rows;
  8643. }
  8644. // Build the list of columns to sort by
  8645. var sortCols = [];
  8646. columns.forEach(function (col) {
  8647. if (col.sort && !col.sort.ignoreSort && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) {
  8648. sortCols.push(col);
  8649. }
  8650. });
  8651. // Sort the "sort columns" by their sort priority
  8652. sortCols = sortCols.sort(rowSorter.prioritySort);
  8653. // Now rows to sort by, maintain original order
  8654. if (sortCols.length === 0) {
  8655. return rows;
  8656. }
  8657. // Re-usable variables
  8658. var col, direction;
  8659. // put a custom index field on each row, used to make a stable sort out of unstable sorts (e.g. Chrome)
  8660. var setIndex = function( row, idx ){
  8661. row.entity.$$uiGridIndex = idx;
  8662. };
  8663. rows.forEach(setIndex);
  8664. // IE9-11 HACK.... the 'rows' variable would be empty where we call rowSorter.getSortFn(...) below. We have to use a separate reference
  8665. // var d = data.slice(0);
  8666. var r = rows.slice(0);
  8667. // Now actually sort the data
  8668. var rowSortFn = function (rowA, rowB) {
  8669. var tem = 0,
  8670. idx = 0,
  8671. sortFn;
  8672. while (tem === 0 && idx < sortCols.length) {
  8673. // grab the metadata for the rest of the logic
  8674. col = sortCols[idx];
  8675. direction = sortCols[idx].sort.direction;
  8676. sortFn = rowSorter.getSortFn(grid, col, r);
  8677. var propA, propB;
  8678. if ( col.sortCellFiltered ){
  8679. propA = grid.getCellDisplayValue(rowA, col);
  8680. propB = grid.getCellDisplayValue(rowB, col);
  8681. } else {
  8682. propA = grid.getCellValue(rowA, col);
  8683. propB = grid.getCellValue(rowB, col);
  8684. }
  8685. tem = sortFn(propA, propB);
  8686. idx++;
  8687. }
  8688. // Chrome doesn't implement a stable sort function. If our sort returns 0
  8689. // (i.e. the items are equal), and we're at the last sort column in the list,
  8690. // then return the previous order using our custom
  8691. // index variable
  8692. if (tem === 0 ) {
  8693. return rowA.entity.$$uiGridIndex - rowB.entity.$$uiGridIndex;
  8694. }
  8695. // Made it this far, we don't have to worry about null & undefined
  8696. if (direction === uiGridConstants.ASC) {
  8697. return tem;
  8698. } else {
  8699. return 0 - tem;
  8700. }
  8701. };
  8702. var newRows = rows.sort(rowSortFn);
  8703. // remove the custom index field on each row, used to make a stable sort out of unstable sorts (e.g. Chrome)
  8704. var clearIndex = function( row, idx ){
  8705. delete row.entity.$$uiGridIndex;
  8706. };
  8707. rows.forEach(clearIndex);
  8708. return newRows;
  8709. };
  8710. return rowSorter;
  8711. }]);
  8712. })();
  8713. (function() {
  8714. var module = angular.module('ui.grid');
  8715. var bindPolyfill;
  8716. if (typeof Function.prototype.bind !== "function") {
  8717. bindPolyfill = function() {
  8718. var slice = Array.prototype.slice;
  8719. return function(context) {
  8720. var fn = this,
  8721. args = slice.call(arguments, 1);
  8722. if (args.length) {
  8723. return function() {
  8724. return arguments.length ? fn.apply(context, args.concat(slice.call(arguments))) : fn.apply(context, args);
  8725. };
  8726. }
  8727. return function() {
  8728. return arguments.length ? fn.apply(context, arguments) : fn.call(context);
  8729. };
  8730. };
  8731. };
  8732. }
  8733. function getStyles (elem) {
  8734. var e = elem;
  8735. if (typeof(e.length) !== 'undefined' && e.length) {
  8736. e = elem[0];
  8737. }
  8738. return e.ownerDocument.defaultView.getComputedStyle(e, null);
  8739. }
  8740. var rnumnonpx = new RegExp( "^(" + (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source + ")(?!px)[a-z%]+$", "i" ),
  8741. // swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
  8742. // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
  8743. rdisplayswap = /^(block|none|table(?!-c[ea]).+)/,
  8744. cssShow = { position: "absolute", visibility: "hidden", display: "block" };
  8745. function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
  8746. var i = extra === ( isBorderBox ? 'border' : 'content' ) ?
  8747. // If we already have the right measurement, avoid augmentation
  8748. 4 :
  8749. // Otherwise initialize for horizontal or vertical properties
  8750. name === 'width' ? 1 : 0,
  8751. val = 0;
  8752. var sides = ['Top', 'Right', 'Bottom', 'Left'];
  8753. for ( ; i < 4; i += 2 ) {
  8754. var side = sides[i];
  8755. // dump('side', side);
  8756. // both box models exclude margin, so add it if we want it
  8757. if ( extra === 'margin' ) {
  8758. var marg = parseFloat(styles[extra + side]);
  8759. if (!isNaN(marg)) {
  8760. val += marg;
  8761. }
  8762. }
  8763. // dump('val1', val);
  8764. if ( isBorderBox ) {
  8765. // border-box includes padding, so remove it if we want content
  8766. if ( extra === 'content' ) {
  8767. var padd = parseFloat(styles['padding' + side]);
  8768. if (!isNaN(padd)) {
  8769. val -= padd;
  8770. // dump('val2', val);
  8771. }
  8772. }
  8773. // at this point, extra isn't border nor margin, so remove border
  8774. if ( extra !== 'margin' ) {
  8775. var bordermarg = parseFloat(styles['border' + side + 'Width']);
  8776. if (!isNaN(bordermarg)) {
  8777. val -= bordermarg;
  8778. // dump('val3', val);
  8779. }
  8780. }
  8781. }
  8782. else {
  8783. // at this point, extra isn't content, so add padding
  8784. var nocontentPad = parseFloat(styles['padding' + side]);
  8785. if (!isNaN(nocontentPad)) {
  8786. val += nocontentPad;
  8787. // dump('val4', val);
  8788. }
  8789. // at this point, extra isn't content nor padding, so add border
  8790. if ( extra !== 'padding') {
  8791. var nocontentnopad = parseFloat(styles['border' + side + 'Width']);
  8792. if (!isNaN(nocontentnopad)) {
  8793. val += nocontentnopad;
  8794. // dump('val5', val);
  8795. }
  8796. }
  8797. }
  8798. }
  8799. // dump('augVal', val);
  8800. return val;
  8801. }
  8802. function getWidthOrHeight( elem, name, extra ) {
  8803. // Start with offset property, which is equivalent to the border-box value
  8804. var valueIsBorderBox = true,
  8805. val, // = name === 'width' ? elem.offsetWidth : elem.offsetHeight,
  8806. styles = getStyles(elem),
  8807. isBorderBox = styles['boxSizing'] === 'border-box';
  8808. // some non-html elements return undefined for offsetWidth, so check for null/undefined
  8809. // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
  8810. // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
  8811. if ( val <= 0 || val == null ) {
  8812. // Fall back to computed then uncomputed css if necessary
  8813. val = styles[name];
  8814. if ( val < 0 || val == null ) {
  8815. val = elem.style[ name ];
  8816. }
  8817. // Computed unit is not pixels. Stop here and return.
  8818. if ( rnumnonpx.test(val) ) {
  8819. return val;
  8820. }
  8821. // we need the check for style in case a browser which returns unreliable values
  8822. // for getComputedStyle silently falls back to the reliable elem.style
  8823. valueIsBorderBox = isBorderBox &&
  8824. ( true || val === elem.style[ name ] ); // use 'true' instead of 'support.boxSizingReliable()'
  8825. // Normalize "", auto, and prepare for extra
  8826. val = parseFloat( val ) || 0;
  8827. }
  8828. // use the active box-sizing model to add/subtract irrelevant styles
  8829. var ret = ( val +
  8830. augmentWidthOrHeight(
  8831. elem,
  8832. name,
  8833. extra || ( isBorderBox ? "border" : "content" ),
  8834. valueIsBorderBox,
  8835. styles
  8836. )
  8837. );
  8838. // dump('ret', ret, val);
  8839. return ret;
  8840. }
  8841. function getLineHeight(elm) {
  8842. elm = angular.element(elm)[0];
  8843. var parent = elm.parentElement;
  8844. if (!parent) {
  8845. parent = document.getElementsByTagName('body')[0];
  8846. }
  8847. return parseInt( getStyles(parent).fontSize ) || parseInt( getStyles(elm).fontSize ) || 16;
  8848. }
  8849. var uid = ['0', '0', '0', '0'];
  8850. var uidPrefix = 'uiGrid-';
  8851. /**
  8852. * @ngdoc service
  8853. * @name ui.grid.service:GridUtil
  8854. *
  8855. * @description Grid utility functions
  8856. */
  8857. module.service('gridUtil', ['$log', '$window', '$document', '$http', '$templateCache', '$timeout', '$interval', '$injector', '$q', '$interpolate', 'uiGridConstants',
  8858. function ($log, $window, $document, $http, $templateCache, $timeout, $interval, $injector, $q, $interpolate, uiGridConstants) {
  8859. var s = {
  8860. augmentWidthOrHeight: augmentWidthOrHeight,
  8861. getStyles: getStyles,
  8862. /**
  8863. * @ngdoc method
  8864. * @name createBoundedWrapper
  8865. * @methodOf ui.grid.service:GridUtil
  8866. *
  8867. * @param {object} Object to bind 'this' to
  8868. * @param {method} Method to bind
  8869. * @returns {Function} The wrapper that performs the binding
  8870. *
  8871. * @description
  8872. * Binds given method to given object.
  8873. *
  8874. * By means of a wrapper, ensures that ``method`` is always bound to
  8875. * ``object`` regardless of its calling environment.
  8876. * Iow, inside ``method``, ``this`` always points to ``object``.
  8877. *
  8878. * See http://alistapart.com/article/getoutbindingsituations
  8879. *
  8880. */
  8881. createBoundedWrapper: function(object, method) {
  8882. return function() {
  8883. return method.apply(object, arguments);
  8884. };
  8885. },
  8886. /**
  8887. * @ngdoc method
  8888. * @name readableColumnName
  8889. * @methodOf ui.grid.service:GridUtil
  8890. *
  8891. * @param {string} columnName Column name as a string
  8892. * @returns {string} Column name appropriately capitalized and split apart
  8893. *
  8894. @example
  8895. <example module="app">
  8896. <file name="app.js">
  8897. var app = angular.module('app', ['ui.grid']);
  8898. app.controller('MainCtrl', ['$scope', 'gridUtil', function ($scope, gridUtil) {
  8899. $scope.name = 'firstName';
  8900. $scope.columnName = function(name) {
  8901. return gridUtil.readableColumnName(name);
  8902. };
  8903. }]);
  8904. </file>
  8905. <file name="index.html">
  8906. <div ng-controller="MainCtrl">
  8907. <strong>Column name:</strong> <input ng-model="name" />
  8908. <br>
  8909. <strong>Output:</strong> <span ng-bind="columnName(name)"></span>
  8910. </div>
  8911. </file>
  8912. </example>
  8913. */
  8914. readableColumnName: function (columnName) {
  8915. // Convert underscores to spaces
  8916. if (typeof(columnName) === 'undefined' || columnName === undefined || columnName === null) { return columnName; }
  8917. if (typeof(columnName) !== 'string') {
  8918. columnName = String(columnName);
  8919. }
  8920. return columnName.replace(/_+/g, ' ')
  8921. // Replace a completely all-capsed word with a first-letter-capitalized version
  8922. .replace(/^[A-Z]+$/, function (match) {
  8923. return angular.lowercase(angular.uppercase(match.charAt(0)) + match.slice(1));
  8924. })
  8925. // Capitalize the first letter of words
  8926. .replace(/([\w\u00C0-\u017F]+)/g, function (match) {
  8927. return angular.uppercase(match.charAt(0)) + match.slice(1);
  8928. })
  8929. // Put a space in between words that have partial capilizations (i.e. 'firstName' becomes 'First Name')
  8930. // .replace(/([A-Z]|[A-Z]\w+)([A-Z])/g, "$1 $2");
  8931. // .replace(/(\w+?|\w)([A-Z])/g, "$1 $2");
  8932. .replace(/(\w+?(?=[A-Z]))/g, '$1 ');
  8933. },
  8934. /**
  8935. * @ngdoc method
  8936. * @name getColumnsFromData
  8937. * @methodOf ui.grid.service:GridUtil
  8938. * @description Return a list of column names, given a data set
  8939. *
  8940. * @param {string} data Data array for grid
  8941. * @returns {Object} Column definitions with field accessor and column name
  8942. *
  8943. * @example
  8944. <pre>
  8945. var data = [
  8946. { firstName: 'Bob', lastName: 'Jones' },
  8947. { firstName: 'Frank', lastName: 'Smith' }
  8948. ];
  8949. var columnDefs = GridUtil.getColumnsFromData(data, excludeProperties);
  8950. columnDefs == [
  8951. {
  8952. field: 'firstName',
  8953. name: 'First Name'
  8954. },
  8955. {
  8956. field: 'lastName',
  8957. name: 'Last Name'
  8958. }
  8959. ];
  8960. </pre>
  8961. */
  8962. getColumnsFromData: function (data, excludeProperties) {
  8963. var columnDefs = [];
  8964. if (!data || typeof(data[0]) === 'undefined' || data[0] === undefined) { return []; }
  8965. if (angular.isUndefined(excludeProperties)) { excludeProperties = []; }
  8966. var item = data[0];
  8967. angular.forEach(item,function (prop, propName) {
  8968. if ( excludeProperties.indexOf(propName) === -1){
  8969. columnDefs.push({
  8970. name: propName
  8971. });
  8972. }
  8973. });
  8974. return columnDefs;
  8975. },
  8976. /**
  8977. * @ngdoc method
  8978. * @name newId
  8979. * @methodOf ui.grid.service:GridUtil
  8980. * @description Return a unique ID string
  8981. *
  8982. * @returns {string} Unique string
  8983. *
  8984. * @example
  8985. <pre>
  8986. var id = GridUtil.newId();
  8987. # 1387305700482;
  8988. </pre>
  8989. */
  8990. newId: (function() {
  8991. var seedId = new Date().getTime();
  8992. return function() {
  8993. return seedId += 1;
  8994. };
  8995. })(),
  8996. /**
  8997. * @ngdoc method
  8998. * @name getTemplate
  8999. * @methodOf ui.grid.service:GridUtil
  9000. * @description Get's template from cache / element / url
  9001. *
  9002. * @param {string|element|promise} Either a string representing the template id, a string representing the template url,
  9003. * an jQuery/Angualr element, or a promise that returns the template contents to use.
  9004. * @returns {object} a promise resolving to template contents
  9005. *
  9006. * @example
  9007. <pre>
  9008. GridUtil.getTemplate(url).then(function (contents) {
  9009. alert(contents);
  9010. })
  9011. </pre>
  9012. */
  9013. getTemplate: function (template) {
  9014. // Try to fetch the template out of the templateCache
  9015. if ($templateCache.get(template)) {
  9016. return s.postProcessTemplate($templateCache.get(template));
  9017. }
  9018. // See if the template is itself a promise
  9019. if (template.hasOwnProperty('then')) {
  9020. return template.then(s.postProcessTemplate);
  9021. }
  9022. // If the template is an element, return the element
  9023. try {
  9024. if (angular.element(template).length > 0) {
  9025. return $q.when(template).then(s.postProcessTemplate);
  9026. }
  9027. }
  9028. catch (err){
  9029. //do nothing; not valid html
  9030. }
  9031. s.logDebug('fetching url', template);
  9032. // Default to trying to fetch the template as a url with $http
  9033. return $http({ method: 'GET', url: template})
  9034. .then(
  9035. function (result) {
  9036. var templateHtml = result.data.trim();
  9037. //put in templateCache for next call
  9038. $templateCache.put(template, templateHtml);
  9039. return templateHtml;
  9040. },
  9041. function (err) {
  9042. throw new Error("Could not get template " + template + ": " + err);
  9043. }
  9044. )
  9045. .then(s.postProcessTemplate);
  9046. },
  9047. //
  9048. postProcessTemplate: function (template) {
  9049. var startSym = $interpolate.startSymbol(),
  9050. endSym = $interpolate.endSymbol();
  9051. // If either of the interpolation symbols have been changed, we need to alter this template
  9052. if (startSym !== '{{' || endSym !== '}}') {
  9053. template = template.replace(/\{\{/g, startSym);
  9054. template = template.replace(/\}\}/g, endSym);
  9055. }
  9056. return $q.when(template);
  9057. },
  9058. /**
  9059. * @ngdoc method
  9060. * @name guessType
  9061. * @methodOf ui.grid.service:GridUtil
  9062. * @description guesses the type of an argument
  9063. *
  9064. * @param {string/number/bool/object} item variable to examine
  9065. * @returns {string} one of the following
  9066. * - 'string'
  9067. * - 'boolean'
  9068. * - 'number'
  9069. * - 'date'
  9070. * - 'object'
  9071. */
  9072. guessType : function (item) {
  9073. var itemType = typeof(item);
  9074. // Check for numbers and booleans
  9075. switch (itemType) {
  9076. case "number":
  9077. case "boolean":
  9078. case "string":
  9079. return itemType;
  9080. default:
  9081. if (angular.isDate(item)) {
  9082. return "date";
  9083. }
  9084. return "object";
  9085. }
  9086. },
  9087. /**
  9088. * @ngdoc method
  9089. * @name elementWidth
  9090. * @methodOf ui.grid.service:GridUtil
  9091. *
  9092. * @param {element} element DOM element
  9093. * @param {string} [extra] Optional modifier for calculation. Use 'margin' to account for margins on element
  9094. *
  9095. * @returns {number} Element width in pixels, accounting for any borders, etc.
  9096. */
  9097. elementWidth: function (elem) {
  9098. },
  9099. /**
  9100. * @ngdoc method
  9101. * @name elementHeight
  9102. * @methodOf ui.grid.service:GridUtil
  9103. *
  9104. * @param {element} element DOM element
  9105. * @param {string} [extra] Optional modifier for calculation. Use 'margin' to account for margins on element
  9106. *
  9107. * @returns {number} Element height in pixels, accounting for any borders, etc.
  9108. */
  9109. elementHeight: function (elem) {
  9110. },
  9111. // Thanks to http://stackoverflow.com/a/13382873/888165
  9112. getScrollbarWidth: function() {
  9113. var outer = document.createElement("div");
  9114. outer.style.visibility = "hidden";
  9115. outer.style.width = "100px";
  9116. outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
  9117. document.body.appendChild(outer);
  9118. var widthNoScroll = outer.offsetWidth;
  9119. // force scrollbars
  9120. outer.style.overflow = "scroll";
  9121. // add innerdiv
  9122. var inner = document.createElement("div");
  9123. inner.style.width = "100%";
  9124. outer.appendChild(inner);
  9125. var widthWithScroll = inner.offsetWidth;
  9126. // remove divs
  9127. outer.parentNode.removeChild(outer);
  9128. return widthNoScroll - widthWithScroll;
  9129. },
  9130. swap: function( elem, options, callback, args ) {
  9131. var ret, name,
  9132. old = {};
  9133. // Remember the old values, and insert the new ones
  9134. for ( name in options ) {
  9135. old[ name ] = elem.style[ name ];
  9136. elem.style[ name ] = options[ name ];
  9137. }
  9138. ret = callback.apply( elem, args || [] );
  9139. // Revert the old values
  9140. for ( name in options ) {
  9141. elem.style[ name ] = old[ name ];
  9142. }
  9143. return ret;
  9144. },
  9145. fakeElement: function( elem, options, callback, args ) {
  9146. var ret, name,
  9147. newElement = angular.element(elem).clone()[0];
  9148. for ( name in options ) {
  9149. newElement.style[ name ] = options[ name ];
  9150. }
  9151. angular.element(document.body).append(newElement);
  9152. ret = callback.call( newElement, newElement );
  9153. angular.element(newElement).remove();
  9154. return ret;
  9155. },
  9156. /**
  9157. * @ngdoc method
  9158. * @name normalizeWheelEvent
  9159. * @methodOf ui.grid.service:GridUtil
  9160. *
  9161. * @param {event} event A mouse wheel event
  9162. *
  9163. * @returns {event} A normalized event
  9164. *
  9165. * @description
  9166. * Given an event from this list:
  9167. *
  9168. * `wheel, mousewheel, DomMouseScroll, MozMousePixelScroll`
  9169. *
  9170. * "normalize" it
  9171. * so that it stays consistent no matter what browser it comes from (i.e. scale it correctly and make sure the direction is right.)
  9172. */
  9173. normalizeWheelEvent: function (event) {
  9174. // var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
  9175. // var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
  9176. var lowestDelta, lowestDeltaXY;
  9177. var orgEvent = event || window.event,
  9178. args = [].slice.call(arguments, 1),
  9179. delta = 0,
  9180. deltaX = 0,
  9181. deltaY = 0,
  9182. absDelta = 0,
  9183. absDeltaXY = 0,
  9184. fn;
  9185. // event = $.event.fix(orgEvent);
  9186. // event.type = 'mousewheel';
  9187. // NOTE: jQuery masks the event and stores it in the event as originalEvent
  9188. if (orgEvent.originalEvent) {
  9189. orgEvent = orgEvent.originalEvent;
  9190. }
  9191. // Old school scrollwheel delta
  9192. if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
  9193. if ( orgEvent.detail ) { delta = orgEvent.detail * -1; }
  9194. // At a minimum, setup the deltaY to be delta
  9195. deltaY = delta;
  9196. // Firefox < 17 related to DOMMouseScroll event
  9197. if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
  9198. deltaY = 0;
  9199. deltaX = delta * -1;
  9200. }
  9201. // New school wheel delta (wheel event)
  9202. if ( orgEvent.deltaY ) {
  9203. deltaY = orgEvent.deltaY * -1;
  9204. delta = deltaY;
  9205. }
  9206. if ( orgEvent.deltaX ) {
  9207. deltaX = orgEvent.deltaX;
  9208. delta = deltaX * -1;
  9209. }
  9210. // Webkit
  9211. if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
  9212. if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX; }
  9213. // Look for lowest delta to normalize the delta values
  9214. absDelta = Math.abs(delta);
  9215. if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
  9216. absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
  9217. if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }
  9218. // Get a whole value for the deltas
  9219. fn = delta > 0 ? 'floor' : 'ceil';
  9220. delta = Math[fn](delta / lowestDelta);
  9221. deltaX = Math[fn](deltaX / lowestDeltaXY);
  9222. deltaY = Math[fn](deltaY / lowestDeltaXY);
  9223. return {
  9224. delta: delta,
  9225. deltaX: deltaX,
  9226. deltaY: deltaY
  9227. };
  9228. },
  9229. // Stolen from Modernizr
  9230. // TODO: make this, and everythign that flows from it, robust
  9231. //http://www.stucox.com/blog/you-cant-detect-a-touchscreen/
  9232. isTouchEnabled: function() {
  9233. var bool;
  9234. if (('ontouchstart' in $window) || $window.DocumentTouch && $document instanceof DocumentTouch) {
  9235. bool = true;
  9236. }
  9237. return bool;
  9238. },
  9239. isNullOrUndefined: function(obj) {
  9240. if (obj === undefined || obj === null) {
  9241. return true;
  9242. }
  9243. return false;
  9244. },
  9245. endsWith: function(str, suffix) {
  9246. if (!str || !suffix || typeof str !== "string") {
  9247. return false;
  9248. }
  9249. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  9250. },
  9251. arrayContainsObjectWithProperty: function(array, propertyName, propertyValue) {
  9252. var found = false;
  9253. angular.forEach(array, function (object) {
  9254. if (object[propertyName] === propertyValue) {
  9255. found = true;
  9256. }
  9257. });
  9258. return found;
  9259. },
  9260. //// Shim requestAnimationFrame
  9261. //requestAnimationFrame: $window.requestAnimationFrame && $window.requestAnimationFrame.bind($window) ||
  9262. // $window.webkitRequestAnimationFrame && $window.webkitRequestAnimationFrame.bind($window) ||
  9263. // function(fn) {
  9264. // return $timeout(fn, 10, false);
  9265. // },
  9266. numericAndNullSort: function (a, b) {
  9267. if (a === null) { return 1; }
  9268. if (b === null) { return -1; }
  9269. if (a === null && b === null) { return 0; }
  9270. return a - b;
  9271. },
  9272. // Disable ngAnimate animations on an element
  9273. disableAnimations: function (element) {
  9274. var $animate;
  9275. try {
  9276. $animate = $injector.get('$animate');
  9277. // See: http://brianhann.com/angular-1-4-breaking-changes-to-be-aware-of/#animate
  9278. if (angular.version.major > 1 || (angular.version.major === 1 && angular.version.minor >= 4)) {
  9279. $animate.enabled(element, false);
  9280. } else {
  9281. $animate.enabled(false, element);
  9282. }
  9283. }
  9284. catch (e) {}
  9285. },
  9286. enableAnimations: function (element) {
  9287. var $animate;
  9288. try {
  9289. $animate = $injector.get('$animate');
  9290. // See: http://brianhann.com/angular-1-4-breaking-changes-to-be-aware-of/#animate
  9291. if (angular.version.major > 1 || (angular.version.major === 1 && angular.version.minor >= 4)) {
  9292. $animate.enabled(element, true);
  9293. } else {
  9294. $animate.enabled(true, element);
  9295. }
  9296. return $animate;
  9297. }
  9298. catch (e) {}
  9299. },
  9300. // Blatantly stolen from Angular as it isn't exposed (yet. 2.0 maybe?)
  9301. nextUid: function nextUid() {
  9302. var index = uid.length;
  9303. var digit;
  9304. while (index) {
  9305. index--;
  9306. digit = uid[index].charCodeAt(0);
  9307. if (digit === 57 /*'9'*/) {
  9308. uid[index] = 'A';
  9309. return uidPrefix + uid.join('');
  9310. }
  9311. if (digit === 90 /*'Z'*/) {
  9312. uid[index] = '0';
  9313. } else {
  9314. uid[index] = String.fromCharCode(digit + 1);
  9315. return uidPrefix + uid.join('');
  9316. }
  9317. }
  9318. uid.unshift('0');
  9319. return uidPrefix + uid.join('');
  9320. },
  9321. // Blatantly stolen from Angular as it isn't exposed (yet. 2.0 maybe?)
  9322. hashKey: function hashKey(obj) {
  9323. var objType = typeof obj,
  9324. key;
  9325. if (objType === 'object' && obj !== null) {
  9326. if (typeof (key = obj.$$hashKey) === 'function') {
  9327. // must invoke on object to keep the right this
  9328. key = obj.$$hashKey();
  9329. }
  9330. else if (typeof(obj.$$hashKey) !== 'undefined' && obj.$$hashKey) {
  9331. key = obj.$$hashKey;
  9332. }
  9333. else if (key === undefined) {
  9334. key = obj.$$hashKey = s.nextUid();
  9335. }
  9336. }
  9337. else {
  9338. key = obj;
  9339. }
  9340. return objType + ':' + key;
  9341. },
  9342. resetUids: function () {
  9343. uid = ['0', '0', '0'];
  9344. },
  9345. /**
  9346. * @ngdoc method
  9347. * @methodOf ui.grid.service:GridUtil
  9348. * @name logError
  9349. * @description wraps the $log method, allowing us to choose different
  9350. * treatment within ui-grid if we so desired. At present we only log
  9351. * error messages if uiGridConstants.LOG_ERROR_MESSAGES is set to true
  9352. * @param {string} logMessage message to be logged to the console
  9353. *
  9354. */
  9355. logError: function( logMessage ){
  9356. if ( uiGridConstants.LOG_ERROR_MESSAGES ){
  9357. $log.error( logMessage );
  9358. }
  9359. },
  9360. /**
  9361. * @ngdoc method
  9362. * @methodOf ui.grid.service:GridUtil
  9363. * @name logWarn
  9364. * @description wraps the $log method, allowing us to choose different
  9365. * treatment within ui-grid if we so desired. At present we only log
  9366. * warning messages if uiGridConstants.LOG_WARN_MESSAGES is set to true
  9367. * @param {string} logMessage message to be logged to the console
  9368. *
  9369. */
  9370. logWarn: function( logMessage ){
  9371. if ( uiGridConstants.LOG_WARN_MESSAGES ){
  9372. $log.warn( logMessage );
  9373. }
  9374. },
  9375. /**
  9376. * @ngdoc method
  9377. * @methodOf ui.grid.service:GridUtil
  9378. * @name logDebug
  9379. * @description wraps the $log method, allowing us to choose different
  9380. * treatment within ui-grid if we so desired. At present we only log
  9381. * debug messages if uiGridConstants.LOG_DEBUG_MESSAGES is set to true
  9382. *
  9383. */
  9384. logDebug: function() {
  9385. if ( uiGridConstants.LOG_DEBUG_MESSAGES ){
  9386. $log.debug.apply($log, arguments);
  9387. }
  9388. }
  9389. };
  9390. /**
  9391. * @ngdoc object
  9392. * @name focus
  9393. * @propertyOf ui.grid.service:GridUtil
  9394. * @description Provies a set of methods to set the document focus inside the grid.
  9395. * See {@link ui.grid.service:GridUtil.focus} for more information.
  9396. */
  9397. /**
  9398. * @ngdoc object
  9399. * @name ui.grid.service:GridUtil.focus
  9400. * @description Provies a set of methods to set the document focus inside the grid.
  9401. * Timeouts are utilized to ensure that the focus is invoked after any other event has been triggered.
  9402. * e.g. click events that need to run before the focus or
  9403. * inputs elements that are in a disabled state but are enabled when those events
  9404. * are triggered.
  9405. */
  9406. s.focus = {
  9407. queue: [],
  9408. //http://stackoverflow.com/questions/25596399/set-element-focus-in-angular-way
  9409. /**
  9410. * @ngdoc method
  9411. * @methodOf ui.grid.service:GridUtil.focus
  9412. * @name byId
  9413. * @description Sets the focus of the document to the given id value.
  9414. * If provided with the grid object it will automatically append the grid id.
  9415. * This is done to encourage unique dom id's as it allows for multiple grids on a
  9416. * page.
  9417. * @param {String} id the id of the dom element to set the focus on
  9418. * @param {Object=} Grid the grid object for this grid instance. See: {@link ui.grid.class:Grid}
  9419. * @param {Number} Grid.id the unique id for this grid. Already set on an initialized grid object.
  9420. * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated.
  9421. * then the promise will fail with the `'canceled'` reason.
  9422. */
  9423. byId: function (id, Grid) {
  9424. this._purgeQueue();
  9425. var promise = $timeout(function() {
  9426. var elementID = (Grid && Grid.id ? Grid.id + '-' : '') + id;
  9427. var element = $window.document.getElementById(elementID);
  9428. if (element) {
  9429. element.focus();
  9430. } else {
  9431. s.logWarn('[focus.byId] Element id ' + elementID + ' was not found.');
  9432. }
  9433. });
  9434. this.queue.push(promise);
  9435. return promise;
  9436. },
  9437. /**
  9438. * @ngdoc method
  9439. * @methodOf ui.grid.service:GridUtil.focus
  9440. * @name byElement
  9441. * @description Sets the focus of the document to the given dom element.
  9442. * @param {(element|angular.element)} element the DOM element to set the focus on
  9443. * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated.
  9444. * then the promise will fail with the `'canceled'` reason.
  9445. */
  9446. byElement: function(element){
  9447. if (!angular.isElement(element)){
  9448. s.logWarn("Trying to focus on an element that isn\'t an element.");
  9449. return $q.reject('not-element');
  9450. }
  9451. element = angular.element(element);
  9452. this._purgeQueue();
  9453. var promise = $timeout(function(){
  9454. if (element){
  9455. element[0].focus();
  9456. }
  9457. });
  9458. this.queue.push(promise);
  9459. return promise;
  9460. },
  9461. /**
  9462. * @ngdoc method
  9463. * @methodOf ui.grid.service:GridUtil.focus
  9464. * @name bySelector
  9465. * @description Sets the focus of the document to the given dom element.
  9466. * @param {(element|angular.element)} parentElement the parent/ancestor of the dom element that you are selecting using the query selector
  9467. * @param {String} querySelector finds the dom element using the {@link http://www.w3schools.com/jsref/met_document_queryselector.asp querySelector}
  9468. * @param {boolean} [aSync=false] If true then the selector will be querried inside of a timeout. Otherwise the selector will be querried imidately
  9469. * then the focus will be called.
  9470. * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated.
  9471. * then the promise will fail with the `'canceled'` reason.
  9472. */
  9473. bySelector: function(parentElement, querySelector, aSync){
  9474. var self = this;
  9475. if (!angular.isElement(parentElement)){
  9476. throw new Error("The parent element is not an element.");
  9477. }
  9478. // Ensure that this is an angular element.
  9479. // It is fine if this is already an angular element.
  9480. parentElement = angular.element(parentElement);
  9481. var focusBySelector = function(){
  9482. var element = parentElement[0].querySelector(querySelector);
  9483. return self.byElement(element);
  9484. };
  9485. this._purgeQueue();
  9486. if (aSync){ //Do this asynchronysly
  9487. var promise = $timeout(focusBySelector);
  9488. this.queue.push($timeout(focusBySelector));
  9489. return promise;
  9490. } else {
  9491. return focusBySelector();
  9492. }
  9493. },
  9494. _purgeQueue: function(){
  9495. this.queue.forEach(function(element){
  9496. $timeout.cancel(element);
  9497. });
  9498. this.queue = [];
  9499. }
  9500. };
  9501. ['width', 'height'].forEach(function (name) {
  9502. var capsName = angular.uppercase(name.charAt(0)) + name.substr(1);
  9503. s['element' + capsName] = function (elem, extra) {
  9504. var e = elem;
  9505. if (e && typeof(e.length) !== 'undefined' && e.length) {
  9506. e = elem[0];
  9507. }
  9508. if (e) {
  9509. var styles = getStyles(e);
  9510. return e.offsetWidth === 0 && rdisplayswap.test(styles.display) ?
  9511. s.swap(e, cssShow, function() {
  9512. return getWidthOrHeight(e, name, extra );
  9513. }) :
  9514. getWidthOrHeight( e, name, extra );
  9515. }
  9516. else {
  9517. return null;
  9518. }
  9519. };
  9520. s['outerElement' + capsName] = function (elem, margin) {
  9521. return elem ? s['element' + capsName].call(this, elem, margin ? 'margin' : 'border') : null;
  9522. };
  9523. });
  9524. // http://stackoverflow.com/a/24107550/888165
  9525. s.closestElm = function closestElm(el, selector) {
  9526. if (typeof(el.length) !== 'undefined' && el.length) {
  9527. el = el[0];
  9528. }
  9529. var matchesFn;
  9530. // find vendor prefix
  9531. ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
  9532. if (typeof document.body[fn] === 'function') {
  9533. matchesFn = fn;
  9534. return true;
  9535. }
  9536. return false;
  9537. });
  9538. // traverse parents
  9539. var parent;
  9540. while (el !== null) {
  9541. parent = el.parentElement;
  9542. if (parent !== null && parent[matchesFn](selector)) {
  9543. return parent;
  9544. }
  9545. el = parent;
  9546. }
  9547. return null;
  9548. };
  9549. s.type = function (obj) {
  9550. var text = Function.prototype.toString.call(obj.constructor);
  9551. return text.match(/function (.*?)\(/)[1];
  9552. };
  9553. s.getBorderSize = function getBorderSize(elem, borderType) {
  9554. if (typeof(elem.length) !== 'undefined' && elem.length) {
  9555. elem = elem[0];
  9556. }
  9557. var styles = getStyles(elem);
  9558. // If a specific border is supplied, like 'top', read the 'borderTop' style property
  9559. if (borderType) {
  9560. borderType = 'border' + borderType.charAt(0).toUpperCase() + borderType.slice(1);
  9561. }
  9562. else {
  9563. borderType = 'border';
  9564. }
  9565. borderType += 'Width';
  9566. var val = parseInt(styles[borderType], 10);
  9567. if (isNaN(val)) {
  9568. return 0;
  9569. }
  9570. else {
  9571. return val;
  9572. }
  9573. };
  9574. // http://stackoverflow.com/a/22948274/888165
  9575. // TODO: Opera? Mobile?
  9576. s.detectBrowser = function detectBrowser() {
  9577. var userAgent = $window.navigator.userAgent;
  9578. var browsers = {chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer|trident\//i};
  9579. for (var key in browsers) {
  9580. if (browsers[key].test(userAgent)) {
  9581. return key;
  9582. }
  9583. }
  9584. return 'unknown';
  9585. };
  9586. // Borrowed from https://github.com/othree/jquery.rtl-scroll-type
  9587. // Determine the scroll "type" this browser is using for RTL
  9588. s.rtlScrollType = function rtlScrollType() {
  9589. if (rtlScrollType.type) {
  9590. return rtlScrollType.type;
  9591. }
  9592. var definer = angular.element('<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>')[0],
  9593. type = 'reverse';
  9594. document.body.appendChild(definer);
  9595. if (definer.scrollLeft > 0) {
  9596. type = 'default';
  9597. }
  9598. else {
  9599. definer.scrollLeft = 1;
  9600. if (definer.scrollLeft === 0) {
  9601. type = 'negative';
  9602. }
  9603. }
  9604. angular.element(definer).remove();
  9605. rtlScrollType.type = type;
  9606. return type;
  9607. };
  9608. /**
  9609. * @ngdoc method
  9610. * @name normalizeScrollLeft
  9611. * @methodOf ui.grid.service:GridUtil
  9612. *
  9613. * @param {element} element The element to get the `scrollLeft` from.
  9614. * @param {grid} grid - grid used to normalize (uses the rtl property)
  9615. *
  9616. * @returns {number} A normalized scrollLeft value for the current browser.
  9617. *
  9618. * @description
  9619. * Browsers currently handle RTL in different ways, resulting in inconsistent scrollLeft values. This method normalizes them
  9620. */
  9621. s.normalizeScrollLeft = function normalizeScrollLeft(element, grid) {
  9622. if (typeof(element.length) !== 'undefined' && element.length) {
  9623. element = element[0];
  9624. }
  9625. var scrollLeft = element.scrollLeft;
  9626. if (grid.isRTL()) {
  9627. switch (s.rtlScrollType()) {
  9628. case 'default':
  9629. return element.scrollWidth - scrollLeft - element.clientWidth;
  9630. case 'negative':
  9631. return Math.abs(scrollLeft);
  9632. case 'reverse':
  9633. return scrollLeft;
  9634. }
  9635. }
  9636. return scrollLeft;
  9637. };
  9638. /**
  9639. * @ngdoc method
  9640. * @name denormalizeScrollLeft
  9641. * @methodOf ui.grid.service:GridUtil
  9642. *
  9643. * @param {element} element The element to normalize the `scrollLeft` value for
  9644. * @param {number} scrollLeft The `scrollLeft` value to denormalize.
  9645. * @param {grid} grid The grid that owns the scroll event.
  9646. *
  9647. * @returns {number} A normalized scrollLeft value for the current browser.
  9648. *
  9649. * @description
  9650. * Browsers currently handle RTL in different ways, resulting in inconsistent scrollLeft values. This method denormalizes a value for the current browser.
  9651. */
  9652. s.denormalizeScrollLeft = function denormalizeScrollLeft(element, scrollLeft, grid) {
  9653. if (typeof(element.length) !== 'undefined' && element.length) {
  9654. element = element[0];
  9655. }
  9656. if (grid.isRTL()) {
  9657. switch (s.rtlScrollType()) {
  9658. case 'default':
  9659. // Get the max scroll for the element
  9660. var maxScrollLeft = element.scrollWidth - element.clientWidth;
  9661. // Subtract the current scroll amount from the max scroll
  9662. return maxScrollLeft - scrollLeft;
  9663. case 'negative':
  9664. return scrollLeft * -1;
  9665. case 'reverse':
  9666. return scrollLeft;
  9667. }
  9668. }
  9669. return scrollLeft;
  9670. };
  9671. /**
  9672. * @ngdoc method
  9673. * @name preEval
  9674. * @methodOf ui.grid.service:GridUtil
  9675. *
  9676. * @param {string} path Path to evaluate
  9677. *
  9678. * @returns {string} A path that is normalized.
  9679. *
  9680. * @description
  9681. * Takes a field path and converts it to bracket notation to allow for special characters in path
  9682. * @example
  9683. * <pre>
  9684. * gridUtil.preEval('property') == 'property'
  9685. * gridUtil.preEval('nested.deep.prop-erty') = "nested['deep']['prop-erty']"
  9686. * </pre>
  9687. */
  9688. s.preEval = function (path) {
  9689. var m = uiGridConstants.BRACKET_REGEXP.exec(path);
  9690. if (m) {
  9691. return (m[1] ? s.preEval(m[1]) : m[1]) + m[2] + (m[3] ? s.preEval(m[3]) : m[3]);
  9692. } else {
  9693. path = path.replace(uiGridConstants.APOS_REGEXP, '\\\'');
  9694. var parts = path.split(uiGridConstants.DOT_REGEXP);
  9695. var preparsed = [parts.shift()]; // first item must be var notation, thus skip
  9696. angular.forEach(parts, function (part) {
  9697. preparsed.push(part.replace(uiGridConstants.FUNC_REGEXP, '\']$1'));
  9698. });
  9699. return preparsed.join('[\'');
  9700. }
  9701. };
  9702. /**
  9703. * @ngdoc method
  9704. * @name debounce
  9705. * @methodOf ui.grid.service:GridUtil
  9706. *
  9707. * @param {function} func function to debounce
  9708. * @param {number} wait milliseconds to delay
  9709. * @param {boolean} immediate execute before delay
  9710. *
  9711. * @returns {function} A function that can be executed as debounced function
  9712. *
  9713. * @description
  9714. * Copied from https://github.com/shahata/angular-debounce
  9715. * Takes a function, decorates it to execute only 1 time after multiple calls, and returns the decorated function
  9716. * @example
  9717. * <pre>
  9718. * var debouncedFunc = gridUtil.debounce(function(){alert('debounced');}, 500);
  9719. * debouncedFunc();
  9720. * debouncedFunc();
  9721. * debouncedFunc();
  9722. * </pre>
  9723. */
  9724. s.debounce = function (func, wait, immediate) {
  9725. var timeout, args, context, result;
  9726. function debounce() {
  9727. /* jshint validthis:true */
  9728. context = this;
  9729. args = arguments;
  9730. var later = function () {
  9731. timeout = null;
  9732. if (!immediate) {
  9733. result = func.apply(context, args);
  9734. }
  9735. };
  9736. var callNow = immediate && !timeout;
  9737. if (timeout) {
  9738. $timeout.cancel(timeout);
  9739. }
  9740. timeout = $timeout(later, wait);
  9741. if (callNow) {
  9742. result = func.apply(context, args);
  9743. }
  9744. return result;
  9745. }
  9746. debounce.cancel = function () {
  9747. $timeout.cancel(timeout);
  9748. timeout = null;
  9749. };
  9750. return debounce;
  9751. };
  9752. /**
  9753. * @ngdoc method
  9754. * @name throttle
  9755. * @methodOf ui.grid.service:GridUtil
  9756. *
  9757. * @param {function} func function to throttle
  9758. * @param {number} wait milliseconds to delay after first trigger
  9759. * @param {Object} params to use in throttle.
  9760. *
  9761. * @returns {function} A function that can be executed as throttled function
  9762. *
  9763. * @description
  9764. * Adapted from debounce function (above)
  9765. * Potential keys for Params Object are:
  9766. * trailing (bool) - whether to trigger after throttle time ends if called multiple times
  9767. * Updated to use $interval rather than $timeout, as protractor (e2e tests) is able to work with $interval,
  9768. * but not with $timeout
  9769. *
  9770. * Note that when using throttle, you need to use throttle to create a new function upfront, then use the function
  9771. * return from that call each time you need to call throttle. If you call throttle itself repeatedly, the lastCall
  9772. * variable will get overwritten and the throttling won't work
  9773. *
  9774. * @example
  9775. * <pre>
  9776. * var throttledFunc = gridUtil.throttle(function(){console.log('throttled');}, 500, {trailing: true});
  9777. * throttledFunc(); //=> logs throttled
  9778. * throttledFunc(); //=> queues attempt to log throttled for ~500ms (since trailing param is truthy)
  9779. * throttledFunc(); //=> updates arguments to keep most-recent request, but does not do anything else.
  9780. * </pre>
  9781. */
  9782. s.throttle = function(func, wait, options){
  9783. options = options || {};
  9784. var lastCall = 0, queued = null, context, args;
  9785. function runFunc(endDate){
  9786. lastCall = +new Date();
  9787. func.apply(context, args);
  9788. $interval(function(){ queued = null; }, 0, 1);
  9789. }
  9790. return function(){
  9791. /* jshint validthis:true */
  9792. context = this;
  9793. args = arguments;
  9794. if (queued === null){
  9795. var sinceLast = +new Date() - lastCall;
  9796. if (sinceLast > wait){
  9797. runFunc();
  9798. }
  9799. else if (options.trailing){
  9800. queued = $interval(runFunc, wait - sinceLast, 1);
  9801. }
  9802. }
  9803. };
  9804. };
  9805. s.on = {};
  9806. s.off = {};
  9807. s._events = {};
  9808. s.addOff = function (eventName) {
  9809. s.off[eventName] = function (elm, fn) {
  9810. var idx = s._events[eventName].indexOf(fn);
  9811. if (idx > 0) {
  9812. s._events[eventName].removeAt(idx);
  9813. }
  9814. };
  9815. };
  9816. var mouseWheeltoBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
  9817. nullLowestDeltaTimeout,
  9818. lowestDelta;
  9819. s.on.mousewheel = function (elm, fn) {
  9820. if (!elm || !fn) { return; }
  9821. var $elm = angular.element(elm);
  9822. // Store the line height and page height for this particular element
  9823. $elm.data('mousewheel-line-height', getLineHeight($elm));
  9824. $elm.data('mousewheel-page-height', s.elementHeight($elm));
  9825. if (!$elm.data('mousewheel-callbacks')) { $elm.data('mousewheel-callbacks', {}); }
  9826. var cbs = $elm.data('mousewheel-callbacks');
  9827. cbs[fn] = (Function.prototype.bind || bindPolyfill).call(mousewheelHandler, $elm[0], fn);
  9828. // Bind all the mousew heel events
  9829. for ( var i = mouseWheeltoBind.length; i; ) {
  9830. $elm.on(mouseWheeltoBind[--i], cbs[fn]);
  9831. }
  9832. };
  9833. s.off.mousewheel = function (elm, fn) {
  9834. var $elm = angular.element(elm);
  9835. var cbs = $elm.data('mousewheel-callbacks');
  9836. var handler = cbs[fn];
  9837. if (handler) {
  9838. for ( var i = mouseWheeltoBind.length; i; ) {
  9839. $elm.off(mouseWheeltoBind[--i], handler);
  9840. }
  9841. }
  9842. delete cbs[fn];
  9843. if (Object.keys(cbs).length === 0) {
  9844. $elm.removeData('mousewheel-line-height');
  9845. $elm.removeData('mousewheel-page-height');
  9846. $elm.removeData('mousewheel-callbacks');
  9847. }
  9848. };
  9849. function mousewheelHandler(fn, event) {
  9850. var $elm = angular.element(this);
  9851. var delta = 0,
  9852. deltaX = 0,
  9853. deltaY = 0,
  9854. absDelta = 0,
  9855. offsetX = 0,
  9856. offsetY = 0;
  9857. // jQuery masks events
  9858. if (event.originalEvent) { event = event.originalEvent; }
  9859. if ( 'detail' in event ) { deltaY = event.detail * -1; }
  9860. if ( 'wheelDelta' in event ) { deltaY = event.wheelDelta; }
  9861. if ( 'wheelDeltaY' in event ) { deltaY = event.wheelDeltaY; }
  9862. if ( 'wheelDeltaX' in event ) { deltaX = event.wheelDeltaX * -1; }
  9863. // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
  9864. if ( 'axis' in event && event.axis === event.HORIZONTAL_AXIS ) {
  9865. deltaX = deltaY * -1;
  9866. deltaY = 0;
  9867. }
  9868. // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
  9869. delta = deltaY === 0 ? deltaX : deltaY;
  9870. // New school wheel delta (wheel event)
  9871. if ( 'deltaY' in event ) {
  9872. deltaY = event.deltaY * -1;
  9873. delta = deltaY;
  9874. }
  9875. if ( 'deltaX' in event ) {
  9876. deltaX = event.deltaX;
  9877. if ( deltaY === 0 ) { delta = deltaX * -1; }
  9878. }
  9879. // No change actually happened, no reason to go any further
  9880. if ( deltaY === 0 && deltaX === 0 ) { return; }
  9881. // Need to convert lines and pages to pixels if we aren't already in pixels
  9882. // There are three delta modes:
  9883. // * deltaMode 0 is by pixels, nothing to do
  9884. // * deltaMode 1 is by lines
  9885. // * deltaMode 2 is by pages
  9886. if ( event.deltaMode === 1 ) {
  9887. var lineHeight = $elm.data('mousewheel-line-height');
  9888. delta *= lineHeight;
  9889. deltaY *= lineHeight;
  9890. deltaX *= lineHeight;
  9891. }
  9892. else if ( event.deltaMode === 2 ) {
  9893. var pageHeight = $elm.data('mousewheel-page-height');
  9894. delta *= pageHeight;
  9895. deltaY *= pageHeight;
  9896. deltaX *= pageHeight;
  9897. }
  9898. // Store lowest absolute delta to normalize the delta values
  9899. absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );
  9900. if ( !lowestDelta || absDelta < lowestDelta ) {
  9901. lowestDelta = absDelta;
  9902. // Adjust older deltas if necessary
  9903. if ( shouldAdjustOldDeltas(event, absDelta) ) {
  9904. lowestDelta /= 40;
  9905. }
  9906. }
  9907. // Get a whole, normalized value for the deltas
  9908. delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta);
  9909. deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
  9910. deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);
  9911. event.deltaMode = 0;
  9912. // Normalise offsetX and offsetY properties
  9913. // if ($elm[0].getBoundingClientRect ) {
  9914. // var boundingRect = $(elm)[0].getBoundingClientRect();
  9915. // offsetX = event.clientX - boundingRect.left;
  9916. // offsetY = event.clientY - boundingRect.top;
  9917. // }
  9918. // event.deltaX = deltaX;
  9919. // event.deltaY = deltaY;
  9920. // event.deltaFactor = lowestDelta;
  9921. var newEvent = {
  9922. originalEvent: event,
  9923. deltaX: deltaX,
  9924. deltaY: deltaY,
  9925. deltaFactor: lowestDelta,
  9926. preventDefault: function () { event.preventDefault(); },
  9927. stopPropagation: function () { event.stopPropagation(); }
  9928. };
  9929. // Clearout lowestDelta after sometime to better
  9930. // handle multiple device types that give
  9931. // a different lowestDelta
  9932. // Ex: trackpad = 3 and mouse wheel = 120
  9933. if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
  9934. nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);
  9935. fn.call($elm[0], newEvent);
  9936. }
  9937. function nullLowestDelta() {
  9938. lowestDelta = null;
  9939. }
  9940. function shouldAdjustOldDeltas(orgEvent, absDelta) {
  9941. // If this is an older event and the delta is divisable by 120,
  9942. // then we are assuming that the browser is treating this as an
  9943. // older mouse wheel event and that we should divide the deltas
  9944. // by 40 to try and get a more usable deltaFactor.
  9945. // Side note, this actually impacts the reported scroll distance
  9946. // in older browsers and can cause scrolling to be slower than native.
  9947. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
  9948. return orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
  9949. }
  9950. return s;
  9951. }]);
  9952. // Add 'px' to the end of a number string if it doesn't have it already
  9953. module.filter('px', function() {
  9954. return function(str) {
  9955. if (str.match(/^[\d\.]+$/)) {
  9956. return str + 'px';
  9957. }
  9958. else {
  9959. return str;
  9960. }
  9961. };
  9962. });
  9963. })();
  9964. (function () {
  9965. angular.module('ui.grid').config(['$provide', function($provide) {
  9966. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  9967. var lang = {
  9968. aggregate: {
  9969. label: 'položky'
  9970. },
  9971. groupPanel: {
  9972. description: 'Přesuntě záhlaví zde pro vytvoření skupiny dle sloupce.'
  9973. },
  9974. search: {
  9975. placeholder: 'Hledat...',
  9976. showingItems: 'Zobrazuji položky:',
  9977. selectedItems: 'Vybrané položky:',
  9978. totalItems: 'Celkem položek:',
  9979. size: 'Velikost strany:',
  9980. first: 'První strana',
  9981. next: 'Další strana',
  9982. previous: 'Předchozí strana',
  9983. last: 'Poslední strana'
  9984. },
  9985. menu: {
  9986. text: 'Vyberte sloupec:'
  9987. },
  9988. sort: {
  9989. ascending: 'Seřadit od A-Z',
  9990. descending: 'Seřadit od Z-A',
  9991. remove: 'Odebrat seřazení'
  9992. },
  9993. column: {
  9994. hide: 'Schovat sloupec'
  9995. },
  9996. aggregation: {
  9997. count: 'celkem řádků: ',
  9998. sum: 'celkem: ',
  9999. avg: 'avg: ',
  10000. min: 'min.: ',
  10001. max: 'max.: '
  10002. },
  10003. pinning: {
  10004. pinLeft: 'Zamknout v levo',
  10005. pinRight: 'Zamknout v pravo',
  10006. unpin: 'Odemknout'
  10007. },
  10008. gridMenu: {
  10009. columns: 'Sloupce:',
  10010. importerTitle: 'Importovat soubor',
  10011. exporterAllAsCsv: 'Exportovat všechny data do csv',
  10012. exporterVisibleAsCsv: 'Exportovat viditelné data do csv',
  10013. exporterSelectedAsCsv: 'Exportovat vybranné data do csv',
  10014. exporterAllAsPdf: 'Exportovat všechny data do pdf',
  10015. exporterVisibleAsPdf: 'Exportovat viditelné data do pdf',
  10016. exporterSelectedAsPdf: 'Exportovat vybranné data do pdf',
  10017. clearAllFilters: 'Vyčistěte všechny filtry'
  10018. },
  10019. importer: {
  10020. noHeaders: 'Názvy sloupců se nepodařilo získat, obsahuje soubor záhlaví?',
  10021. noObjects: 'Data se nepodařilo zpracovat, obsahuje soubor řádky mimo záhlaví?',
  10022. invalidCsv: 'Soubor nelze zpracovat, jedná se CSV?',
  10023. invalidJson: 'Soubor nelze zpracovat, je to JSON?',
  10024. jsonNotArray: 'Soubor musí obsahovat json. Ukončuji..'
  10025. },
  10026. pagination: {
  10027. sizes: 'položek na stránku',
  10028. totalItems: 'položek'
  10029. },
  10030. grouping: {
  10031. group: 'Seskupit',
  10032. ungroup: 'Odebrat seskupení',
  10033. aggregate_count: 'Agregace: Count',
  10034. aggregate_sum: 'Agregace: Sum',
  10035. aggregate_max: 'Agregace: Max',
  10036. aggregate_min: 'Agregace: Min',
  10037. aggregate_avg: 'Agregace: Avg',
  10038. aggregate_remove: 'Agregace: Odebrat'
  10039. }
  10040. };
  10041. // support varianty of different czech keys.
  10042. $delegate.add('cs', lang);
  10043. $delegate.add('cz', lang);
  10044. $delegate.add('cs-cz', lang);
  10045. $delegate.add('cs-CZ', lang);
  10046. return $delegate;
  10047. }]);
  10048. }]);
  10049. })();
  10050. (function(){
  10051. angular.module('ui.grid').config(['$provide', function($provide) {
  10052. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10053. $delegate.add('da', {
  10054. aggregate:{
  10055. label: 'artikler'
  10056. },
  10057. groupPanel:{
  10058. description: 'Grupér rækker udfra en kolonne ved at trække dens overskift hertil.'
  10059. },
  10060. search:{
  10061. placeholder: 'Søg...',
  10062. showingItems: 'Viste rækker:',
  10063. selectedItems: 'Valgte rækker:',
  10064. totalItems: 'Rækker totalt:',
  10065. size: 'Side størrelse:',
  10066. first: 'Første side',
  10067. next: 'Næste side',
  10068. previous: 'Forrige side',
  10069. last: 'Sidste side'
  10070. },
  10071. menu:{
  10072. text: 'Vælg kolonner:'
  10073. },
  10074. column: {
  10075. hide: 'Skjul kolonne'
  10076. },
  10077. aggregation: {
  10078. count: 'samlede rækker: ',
  10079. sum: 'smalede: ',
  10080. avg: 'gns: ',
  10081. min: 'min: ',
  10082. max: 'max: '
  10083. },
  10084. gridMenu: {
  10085. columns: 'Columns:',
  10086. importerTitle: 'Import file',
  10087. exporterAllAsCsv: 'Export all data as csv',
  10088. exporterVisibleAsCsv: 'Export visible data as csv',
  10089. exporterSelectedAsCsv: 'Export selected data as csv',
  10090. exporterAllAsPdf: 'Export all data as pdf',
  10091. exporterVisibleAsPdf: 'Export visible data as pdf',
  10092. exporterSelectedAsPdf: 'Export selected data as pdf',
  10093. clearAllFilters: 'Clear all filters'
  10094. },
  10095. importer: {
  10096. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  10097. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  10098. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  10099. invalidJson: 'File was unable to be processed, is it valid Json?',
  10100. jsonNotArray: 'Imported json file must contain an array, aborting.'
  10101. }
  10102. });
  10103. return $delegate;
  10104. }]);
  10105. }]);
  10106. })();
  10107. (function () {
  10108. angular.module('ui.grid').config(['$provide', function ($provide) {
  10109. $provide.decorator('i18nService', ['$delegate', function ($delegate) {
  10110. $delegate.add('de', {
  10111. aggregate: {
  10112. label: 'Eintrag'
  10113. },
  10114. groupPanel: {
  10115. description: 'Ziehen Sie eine Spaltenüberschrift hierhin, um nach dieser Spalte zu gruppieren.'
  10116. },
  10117. search: {
  10118. placeholder: 'Suche...',
  10119. showingItems: 'Zeige Einträge:',
  10120. selectedItems: 'Ausgewählte Einträge:',
  10121. totalItems: 'Einträge gesamt:',
  10122. size: 'Einträge pro Seite:',
  10123. first: 'Erste Seite',
  10124. next: 'Nächste Seite',
  10125. previous: 'Vorherige Seite',
  10126. last: 'Letzte Seite'
  10127. },
  10128. menu: {
  10129. text: 'Spalten auswählen:'
  10130. },
  10131. sort: {
  10132. ascending: 'aufsteigend sortieren',
  10133. descending: 'absteigend sortieren',
  10134. remove: 'Sortierung zurücksetzen'
  10135. },
  10136. column: {
  10137. hide: 'Spalte ausblenden'
  10138. },
  10139. aggregation: {
  10140. count: 'Zeilen insgesamt: ',
  10141. sum: 'gesamt: ',
  10142. avg: 'Durchschnitt: ',
  10143. min: 'min: ',
  10144. max: 'max: '
  10145. },
  10146. pinning: {
  10147. pinLeft: 'Links anheften',
  10148. pinRight: 'Rechts anheften',
  10149. unpin: 'Lösen'
  10150. },
  10151. gridMenu: {
  10152. columns: 'Spalten:',
  10153. importerTitle: 'Datei importieren',
  10154. exporterAllAsCsv: 'Alle Daten als CSV exportieren',
  10155. exporterVisibleAsCsv: 'sichtbare Daten als CSV exportieren',
  10156. exporterSelectedAsCsv: 'markierte Daten als CSV exportieren',
  10157. exporterAllAsPdf: 'Alle Daten als PDF exportieren',
  10158. exporterVisibleAsPdf: 'sichtbare Daten als PDF exportieren',
  10159. exporterSelectedAsPdf: 'markierte Daten als CSV exportieren',
  10160. clearAllFilters: 'Alle filter reinigen'
  10161. },
  10162. importer: {
  10163. noHeaders: 'Es konnten keine Spaltennamen ermittelt werden. Sind in der Datei Spaltendefinitionen enthalten?',
  10164. noObjects: 'Es konnten keine Zeileninformationen gelesen werden, Sind in der Datei außer den Spaltendefinitionen auch Daten enthalten?',
  10165. invalidCsv: 'Die Datei konnte nicht eingelesen werden, ist es eine gültige CSV-Datei?',
  10166. invalidJson: 'Die Datei konnte nicht eingelesen werden. Enthält sie gültiges JSON?',
  10167. jsonNotArray: 'Die importierte JSON-Datei muß ein Array enthalten. Breche Import ab.'
  10168. },
  10169. pagination: {
  10170. sizes: 'Einträge pro Seite',
  10171. totalItems: 'Einträge'
  10172. },
  10173. grouping: {
  10174. group: 'Gruppieren',
  10175. ungroup: 'Gruppierung aufheben',
  10176. aggregate_count: 'Agg: Anzahl',
  10177. aggregate_sum: 'Agg: Summe',
  10178. aggregate_max: 'Agg: Maximum',
  10179. aggregate_min: 'Agg: Minimum',
  10180. aggregate_avg: 'Agg: Mittelwert',
  10181. aggregate_remove: 'Aggregation entfernen'
  10182. }
  10183. });
  10184. return $delegate;
  10185. }]);
  10186. }]);
  10187. })();
  10188. (function () {
  10189. angular.module('ui.grid').config(['$provide', function($provide) {
  10190. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10191. // $delegate.add('zh-cn', {
  10192. // headerCell: {
  10193. // aria: {
  10194. // defaultFilterLabel: '过滤列',
  10195. // removeFilter: '重置过滤项',
  10196. // columnMenuButtonLabel: '列菜单'
  10197. // },
  10198. // priority: '优先:',
  10199. // filterLabel: "过滤: "
  10200. // },
  10201. // aggregate: {
  10202. // label: '项'
  10203. // },
  10204. // groupPanel: {
  10205. // description: '拖动表头按表头分组.'
  10206. // },
  10207. // search: {
  10208. // placeholder: '查询...',
  10209. // showingItems: '显示项:',
  10210. // selectedItems: '选择了:',
  10211. // totalItems: '总共查询记录数:',
  10212. // size: '总页数:',
  10213. // first: '第一页',
  10214. // next: '下一页',
  10215. // previous: '前一页',
  10216. // last: '最后一页'
  10217. // },
  10218. // menu: {
  10219. // text: '选择列:'
  10220. // },
  10221. // sort: {
  10222. // ascending: '顺序排序',
  10223. // descending: '逆序排序',
  10224. // none: '不排序',
  10225. // remove: '去除排序'
  10226. // },
  10227. // column: {
  10228. // hide: '隐藏列'
  10229. // },
  10230. // aggregation: {
  10231. // count: '总行数: ',
  10232. // sum: '合计: ',
  10233. // avg: '平均: ',
  10234. // min: '最小: ',
  10235. // max: '最大: '
  10236. // },
  10237. // pinning: {
  10238. // pinLeft: 'Pin Left',
  10239. // pinRight: 'Pin Right',
  10240. // unpin: 'Unpin'
  10241. // },
  10242. // columnMenu: {
  10243. // close: 'Close'
  10244. // },
  10245. // gridMenu: {
  10246. // aria: {
  10247. // buttonLabel: 'Grid Menu'
  10248. // },
  10249. // columns: 'Columns:',
  10250. // importerTitle: 'Import file',
  10251. // exporterAllAsCsv: 'Export all data as csv',
  10252. // exporterVisibleAsCsv: 'Export visible data as csv',
  10253. // exporterSelectedAsCsv: 'Export selected data as csv',
  10254. // exporterAllAsPdf: 'Export all data as pdf',
  10255. // exporterVisibleAsPdf: 'Export visible data as pdf',
  10256. // exporterSelectedAsPdf: 'Export selected data as pdf',
  10257. // clearAllFilters: 'Clear all filters'
  10258. // },
  10259. // importer: {
  10260. // noHeaders: 'Column names were unable to be derived, does the file have a header?',
  10261. // noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  10262. // invalidCsv: 'File was unable to be processed, is it valid CSV?',
  10263. // invalidJson: 'File was unable to be processed, is it valid Json?',
  10264. // jsonNotArray: 'Imported json file must contain an array, aborting.'
  10265. // },
  10266. // pagination: {
  10267. // aria: {
  10268. // pageToFirst: 'Page to first',
  10269. // pageBack: 'Page back',
  10270. // pageSelected: 'Selected page',
  10271. // pageForward: 'Page forward',
  10272. // pageToLast: 'Page to last'
  10273. // },
  10274. // sizes: '行每页',
  10275. // totalItems: '条',
  10276. // through: 'through',
  10277. // of: 'of'
  10278. // },
  10279. // grouping: {
  10280. // group: 'Group',
  10281. // ungroup: 'Ungroup',
  10282. // aggregate_count: 'Agg: Count',
  10283. // aggregate_sum: 'Agg: Sum',
  10284. // aggregate_max: 'Agg: Max',
  10285. // aggregate_min: 'Agg: Min',
  10286. // aggregate_avg: 'Agg: Avg',
  10287. // aggregate_remove: 'Agg: Remove'
  10288. // }
  10289. // });
  10290. $delegate.add('en', {
  10291. headerCell: {
  10292. aria: {
  10293. defaultFilterLabel: 'Filter for column',
  10294. removeFilter: 'Remove Filter',
  10295. columnMenuButtonLabel: 'Column Menu'
  10296. },
  10297. priority: 'Priority:',
  10298. filterLabel: "Filter for column: "
  10299. },
  10300. aggregate: {
  10301. label: 'items'
  10302. },
  10303. groupPanel: {
  10304. description: 'Drag a column header here and drop it to group by that column.'
  10305. },
  10306. search: {
  10307. placeholder: 'Search...',
  10308. showingItems: 'Showing Items:',
  10309. selectedItems: 'Selected Items:',
  10310. totalItems: 'Total Items:',
  10311. size: 'Page Size:',
  10312. first: 'First Page',
  10313. next: 'Next Page',
  10314. previous: 'Previous Page',
  10315. last: 'Last Page'
  10316. },
  10317. menu: {
  10318. text: 'Choose Columns:'
  10319. },
  10320. sort: {
  10321. ascending: 'Sort Ascending',
  10322. descending: 'Sort Descending',
  10323. none: 'Sort None',
  10324. remove: 'Remove Sort'
  10325. },
  10326. column: {
  10327. hide: 'Hide Column'
  10328. },
  10329. aggregation: {
  10330. count: 'total rows: ',
  10331. sum: 'total: ',
  10332. avg: 'avg: ',
  10333. min: 'min: ',
  10334. max: 'max: '
  10335. },
  10336. pinning: {
  10337. pinLeft: 'Pin Left',
  10338. pinRight: 'Pin Right',
  10339. unpin: 'Unpin'
  10340. },
  10341. columnMenu: {
  10342. close: 'Close'
  10343. },
  10344. gridMenu: {
  10345. aria: {
  10346. buttonLabel: 'Grid Menu'
  10347. },
  10348. columns: 'Columns:',
  10349. importerTitle: 'Import file',
  10350. exporterAllAsCsv: 'Export all data as csv',
  10351. exporterVisibleAsCsv: 'Export visible data as csv',
  10352. exporterSelectedAsCsv: 'Export selected data as csv',
  10353. exporterAllAsPdf: 'Export all data as pdf',
  10354. exporterVisibleAsPdf: 'Export visible data as pdf',
  10355. exporterSelectedAsPdf: 'Export selected data as pdf',
  10356. clearAllFilters: 'Clear all filters'
  10357. },
  10358. importer: {
  10359. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  10360. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  10361. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  10362. invalidJson: 'File was unable to be processed, is it valid Json?',
  10363. jsonNotArray: 'Imported json file must contain an array, aborting.'
  10364. },
  10365. pagination: {
  10366. aria: {
  10367. pageToFirst: 'Page to first',
  10368. pageBack: 'Page back',
  10369. pageSelected: 'Selected page',
  10370. pageForward: 'Page forward',
  10371. pageToLast: 'Page to last'
  10372. },
  10373. sizes: 'items per page',
  10374. totalItems: 'items',
  10375. through: 'through',
  10376. of: 'of'
  10377. },
  10378. grouping: {
  10379. group: 'Group',
  10380. ungroup: 'Ungroup',
  10381. aggregate_count: 'Agg: Count',
  10382. aggregate_sum: 'Agg: Sum',
  10383. aggregate_max: 'Agg: Max',
  10384. aggregate_min: 'Agg: Min',
  10385. aggregate_avg: 'Agg: Avg',
  10386. aggregate_remove: 'Agg: Remove'
  10387. }
  10388. });
  10389. return $delegate;
  10390. }]);
  10391. }]);
  10392. })();
  10393. (function () {
  10394. angular.module('ui.grid').config(['$provide', function($provide) {
  10395. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10396. $delegate.add('es', {
  10397. aggregate: {
  10398. label: 'Artículos'
  10399. },
  10400. groupPanel: {
  10401. description: 'Arrastre un encabezado de columna aquí y suéltelo para agrupar por esa columna.'
  10402. },
  10403. search: {
  10404. placeholder: 'Buscar...',
  10405. showingItems: 'Artículos Mostrados:',
  10406. selectedItems: 'Artículos Seleccionados:',
  10407. totalItems: 'Artículos Totales:',
  10408. size: 'Tamaño de Página:',
  10409. first: 'Primera Página',
  10410. next: 'Página Siguiente',
  10411. previous: 'Página Anterior',
  10412. last: 'Última Página'
  10413. },
  10414. menu: {
  10415. text: 'Elegir columnas:'
  10416. },
  10417. sort: {
  10418. ascending: 'Orden Ascendente',
  10419. descending: 'Orden Descendente',
  10420. remove: 'Sin Ordenar'
  10421. },
  10422. column: {
  10423. hide: 'Ocultar la columna'
  10424. },
  10425. aggregation: {
  10426. count: 'filas totales: ',
  10427. sum: 'total: ',
  10428. avg: 'media: ',
  10429. min: 'min: ',
  10430. max: 'max: '
  10431. },
  10432. pinning: {
  10433. pinLeft: 'Fijar a la Izquierda',
  10434. pinRight: 'Fijar a la Derecha',
  10435. unpin: 'Quitar Fijación'
  10436. },
  10437. gridMenu: {
  10438. columns: 'Columnas:',
  10439. importerTitle: 'Importar archivo',
  10440. exporterAllAsCsv: 'Exportar todo como csv',
  10441. exporterVisibleAsCsv: 'Exportar vista como csv',
  10442. exporterSelectedAsCsv: 'Exportar selección como csv',
  10443. exporterAllAsPdf: 'Exportar todo como pdf',
  10444. exporterVisibleAsPdf: 'Exportar vista como pdf',
  10445. exporterSelectedAsPdf: 'Exportar selección como pdf',
  10446. clearAllFilters: 'Limpiar todos los filtros'
  10447. },
  10448. importer: {
  10449. noHeaders: 'No fue posible derivar los nombres de las columnas, ¿tiene encabezados el archivo?',
  10450. noObjects: 'No fue posible obtener registros, ¿contiene datos el archivo, aparte de los encabezados?',
  10451. invalidCsv: 'No fue posible procesar el archivo, ¿es un CSV válido?',
  10452. invalidJson: 'No fue posible procesar el archivo, ¿es un Json válido?',
  10453. jsonNotArray: 'El archivo json importado debe contener un array, abortando.'
  10454. },
  10455. pagination: {
  10456. sizes: 'registros por página',
  10457. totalItems: 'registros',
  10458. of: 'de'
  10459. },
  10460. grouping: {
  10461. group: 'Agrupar',
  10462. ungroup: 'Desagrupar',
  10463. aggregate_count: 'Agr: Cont',
  10464. aggregate_sum: 'Agr: Sum',
  10465. aggregate_max: 'Agr: Máx',
  10466. aggregate_min: 'Agr: Min',
  10467. aggregate_avg: 'Agr: Prom',
  10468. aggregate_remove: 'Agr: Quitar'
  10469. }
  10470. });
  10471. return $delegate;
  10472. }]);
  10473. }]);
  10474. })();
  10475. /**
  10476. * Translated by: R. Salarmehr
  10477. * M. Hosseynzade
  10478. * Using Vajje.com online dictionary.
  10479. */
  10480. (function () {
  10481. angular.module('ui.grid').config(['$provide', function ($provide) {
  10482. $provide.decorator('i18nService', ['$delegate', function ($delegate) {
  10483. $delegate.add('fa', {
  10484. aggregate: {
  10485. label: 'قلم'
  10486. },
  10487. groupPanel: {
  10488. description: 'عنوان یک ستون را بگیر و به گروهی از آن ستون رها کن.'
  10489. },
  10490. search: {
  10491. placeholder: 'جستجو...',
  10492. showingItems: 'نمایش اقلام:',
  10493. selectedItems: 'قلم\u200cهای انتخاب شده:',
  10494. totalItems: 'مجموع اقلام:',
  10495. size: 'اندازه\u200cی صفحه:',
  10496. first: 'اولین صفحه',
  10497. next: 'صفحه\u200cی\u200cبعدی',
  10498. previous: 'صفحه\u200cی\u200c قبلی',
  10499. last: 'آخرین صفحه'
  10500. },
  10501. menu: {
  10502. text: 'ستون\u200cهای انتخابی:'
  10503. },
  10504. sort: {
  10505. ascending: 'ترتیب صعودی',
  10506. descending: 'ترتیب نزولی',
  10507. remove: 'حذف مرتب کردن'
  10508. },
  10509. column: {
  10510. hide: 'پنهان\u200cکردن ستون'
  10511. },
  10512. aggregation: {
  10513. count: 'تعداد: ',
  10514. sum: 'مجموع: ',
  10515. avg: 'میانگین: ',
  10516. min: 'کمترین: ',
  10517. max: 'بیشترین: '
  10518. },
  10519. pinning: {
  10520. pinLeft: 'پین کردن سمت چپ',
  10521. pinRight: 'پین کردن سمت راست',
  10522. unpin: 'حذف پین'
  10523. },
  10524. gridMenu: {
  10525. columns: 'ستون\u200cها:',
  10526. importerTitle: 'وارد کردن فایل',
  10527. exporterAllAsCsv: 'خروجی تمام داده\u200cها در فایل csv',
  10528. exporterVisibleAsCsv: 'خروجی داده\u200cهای قابل مشاهده در فایل csv',
  10529. exporterSelectedAsCsv: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل csv',
  10530. exporterAllAsPdf: 'خروجی تمام داده\u200cها در فایل pdf',
  10531. exporterVisibleAsPdf: 'خروجی داده\u200cهای قابل مشاهده در فایل pdf',
  10532. exporterSelectedAsPdf: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل pdf',
  10533. clearAllFilters: 'پاک کردن تمام فیلتر'
  10534. },
  10535. importer: {
  10536. noHeaders: 'نام ستون قابل استخراج نیست. آیا فایل عنوان دارد؟',
  10537. noObjects: 'اشیا قابل استخراج نیستند. آیا به جز عنوان\u200cها در فایل داده وجود دارد؟',
  10538. invalidCsv: 'فایل قابل پردازش نیست. آیا فرمت csv معتبر است؟',
  10539. invalidJson: 'فایل قابل پردازش نیست. آیا فرمت json معتبر است؟',
  10540. jsonNotArray: 'فایل json وارد شده باید حاوی آرایه باشد. عملیات ساقط شد.'
  10541. },
  10542. pagination: {
  10543. sizes: 'اقلام در هر صفحه',
  10544. totalItems: 'اقلام',
  10545. of: 'از'
  10546. },
  10547. grouping: {
  10548. group: 'گروه\u200cبندی',
  10549. ungroup: 'حذف گروه\u200cبندی',
  10550. aggregate_count: 'Agg: تعداد',
  10551. aggregate_sum: 'Agg: جمع',
  10552. aggregate_max: 'Agg: بیشینه',
  10553. aggregate_min: 'Agg: کمینه',
  10554. aggregate_avg: 'Agg: میانگین',
  10555. aggregate_remove: 'Agg: حذف'
  10556. }
  10557. });
  10558. return $delegate;
  10559. }]);
  10560. }]);
  10561. })();
  10562. (function () {
  10563. angular.module('ui.grid').config(['$provide', function($provide) {
  10564. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10565. $delegate.add('fi', {
  10566. aggregate: {
  10567. label: 'rivit'
  10568. },
  10569. groupPanel: {
  10570. description: 'Raahaa ja pudota otsikko tähän ryhmittääksesi sarakkeen mukaan.'
  10571. },
  10572. search: {
  10573. placeholder: 'Hae...',
  10574. showingItems: 'Näytetään rivejä:',
  10575. selectedItems: 'Valitut rivit:',
  10576. totalItems: 'Rivejä yht.:',
  10577. size: 'Näytä:',
  10578. first: 'Ensimmäinen sivu',
  10579. next: 'Seuraava sivu',
  10580. previous: 'Edellinen sivu',
  10581. last: 'Viimeinen sivu'
  10582. },
  10583. menu: {
  10584. text: 'Valitse sarakkeet:'
  10585. },
  10586. sort: {
  10587. ascending: 'Järjestä nouseva',
  10588. descending: 'Järjestä laskeva',
  10589. remove: 'Poista järjestys'
  10590. },
  10591. column: {
  10592. hide: 'Piilota sarake'
  10593. },
  10594. aggregation: {
  10595. count: 'Rivejä yht.: ',
  10596. sum: 'Summa: ',
  10597. avg: 'K.a.: ',
  10598. min: 'Min: ',
  10599. max: 'Max: '
  10600. },
  10601. pinning: {
  10602. pinLeft: 'Lukitse vasemmalle',
  10603. pinRight: 'Lukitse oikealle',
  10604. unpin: 'Poista lukitus'
  10605. },
  10606. gridMenu: {
  10607. columns: 'Sarakkeet:',
  10608. importerTitle: 'Tuo tiedosto',
  10609. exporterAllAsCsv: 'Vie tiedot csv-muodossa',
  10610. exporterVisibleAsCsv: 'Vie näkyvä tieto csv-muodossa',
  10611. exporterSelectedAsCsv: 'Vie valittu tieto csv-muodossa',
  10612. exporterAllAsPdf: 'Vie tiedot pdf-muodossa',
  10613. exporterVisibleAsPdf: 'Vie näkyvä tieto pdf-muodossa',
  10614. exporterSelectedAsPdf: 'Vie valittu tieto pdf-muodossa',
  10615. clearAllFilters: 'Puhdista kaikki suodattimet'
  10616. },
  10617. importer: {
  10618. noHeaders: 'Sarakkeen nimiä ei voitu päätellä, onko tiedostossa otsikkoriviä?',
  10619. noObjects: 'Tietoja ei voitu lukea, onko tiedostossa muuta kuin otsikkot?',
  10620. invalidCsv: 'Tiedostoa ei voitu käsitellä, oliko se CSV-muodossa?',
  10621. invalidJson: 'Tiedostoa ei voitu käsitellä, oliko se JSON-muodossa?',
  10622. jsonNotArray: 'Tiedosto ei sisältänyt taulukkoa, lopetetaan.'
  10623. }
  10624. });
  10625. return $delegate;
  10626. }]);
  10627. }]);
  10628. })();
  10629. (function () {
  10630. angular.module('ui.grid').config(['$provide', function($provide) {
  10631. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10632. $delegate.add('fr', {
  10633. aggregate: {
  10634. label: 'éléments'
  10635. },
  10636. groupPanel: {
  10637. description: 'Faites glisser une en-tête de colonne ici pour créer un groupe de colonnes.'
  10638. },
  10639. search: {
  10640. placeholder: 'Recherche...',
  10641. showingItems: 'Affichage des éléments :',
  10642. selectedItems: 'Éléments sélectionnés :',
  10643. totalItems: 'Nombre total d\'éléments:',
  10644. size: 'Taille de page:',
  10645. first: 'Première page',
  10646. next: 'Page Suivante',
  10647. previous: 'Page précédente',
  10648. last: 'Dernière page'
  10649. },
  10650. menu: {
  10651. text: 'Choisir des colonnes :'
  10652. },
  10653. sort: {
  10654. ascending: 'Trier par ordre croissant',
  10655. descending: 'Trier par ordre décroissant',
  10656. remove: 'Enlever le tri'
  10657. },
  10658. column: {
  10659. hide: 'Cacher la colonne'
  10660. },
  10661. aggregation: {
  10662. count: 'lignes totales: ',
  10663. sum: 'total: ',
  10664. avg: 'moy: ',
  10665. min: 'min: ',
  10666. max: 'max: '
  10667. },
  10668. pinning: {
  10669. pinLeft: 'Épingler à gauche',
  10670. pinRight: 'Épingler à droite',
  10671. unpin: 'Détacher'
  10672. },
  10673. gridMenu: {
  10674. columns: 'Colonnes:',
  10675. importerTitle: 'Importer un fichier',
  10676. exporterAllAsCsv: 'Exporter toutes les données en CSV',
  10677. exporterVisibleAsCsv: 'Exporter les données visibles en CSV',
  10678. exporterSelectedAsCsv: 'Exporter les données sélectionnées en CSV',
  10679. exporterAllAsPdf: 'Exporter toutes les données en PDF',
  10680. exporterVisibleAsPdf: 'Exporter les données visibles en PDF',
  10681. exporterSelectedAsPdf: 'Exporter les données sélectionnées en PDF',
  10682. clearAllFilters: 'Nettoyez tous les filtres'
  10683. },
  10684. importer: {
  10685. noHeaders: 'Impossible de déterminer le nom des colonnes, le fichier possède-t-il une en-tête ?',
  10686. noObjects: 'Aucun objet trouvé, le fichier possède-t-il des données autres que l\'en-tête ?',
  10687. invalidCsv: 'Le fichier n\'a pas pu être traité, le CSV est-il valide ?',
  10688. invalidJson: 'Le fichier n\'a pas pu être traité, le JSON est-il valide ?',
  10689. jsonNotArray: 'Le fichier JSON importé doit contenir un tableau, abandon.'
  10690. },
  10691. pagination: {
  10692. sizes: 'éléments par page',
  10693. totalItems: 'éléments',
  10694. of: 'sur'
  10695. },
  10696. grouping: {
  10697. group: 'Grouper',
  10698. ungroup: 'Dégrouper',
  10699. aggregate_count: 'Agg: Compte',
  10700. aggregate_sum: 'Agg: Somme',
  10701. aggregate_max: 'Agg: Max',
  10702. aggregate_min: 'Agg: Min',
  10703. aggregate_avg: 'Agg: Moy',
  10704. aggregate_remove: 'Agg: Retirer'
  10705. }
  10706. });
  10707. return $delegate;
  10708. }]);
  10709. }]);
  10710. })();
  10711. (function () {
  10712. angular.module('ui.grid').config(['$provide', function ($provide) {
  10713. $provide.decorator('i18nService', ['$delegate', function ($delegate) {
  10714. $delegate.add('he', {
  10715. aggregate: {
  10716. label: 'items'
  10717. },
  10718. groupPanel: {
  10719. description: 'גרור עמודה לכאן ושחרר בכדי לקבץ עמודה זו.'
  10720. },
  10721. search: {
  10722. placeholder: 'חפש...',
  10723. showingItems: 'מציג:',
  10724. selectedItems: 'סה"כ נבחרו:',
  10725. totalItems: 'סה"כ רשומות:',
  10726. size: 'תוצאות בדף:',
  10727. first: 'דף ראשון',
  10728. next: 'דף הבא',
  10729. previous: 'דף קודם',
  10730. last: 'דף אחרון'
  10731. },
  10732. menu: {
  10733. text: 'בחר עמודות:'
  10734. },
  10735. sort: {
  10736. ascending: 'סדר עולה',
  10737. descending: 'סדר יורד',
  10738. remove: 'בטל'
  10739. },
  10740. column: {
  10741. hide: 'טור הסתר'
  10742. },
  10743. aggregation: {
  10744. count: 'total rows: ',
  10745. sum: 'total: ',
  10746. avg: 'avg: ',
  10747. min: 'min: ',
  10748. max: 'max: '
  10749. },
  10750. gridMenu: {
  10751. columns: 'Columns:',
  10752. importerTitle: 'Import file',
  10753. exporterAllAsCsv: 'Export all data as csv',
  10754. exporterVisibleAsCsv: 'Export visible data as csv',
  10755. exporterSelectedAsCsv: 'Export selected data as csv',
  10756. exporterAllAsPdf: 'Export all data as pdf',
  10757. exporterVisibleAsPdf: 'Export visible data as pdf',
  10758. exporterSelectedAsPdf: 'Export selected data as pdf',
  10759. clearAllFilters: 'Clean all filters'
  10760. },
  10761. importer: {
  10762. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  10763. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  10764. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  10765. invalidJson: 'File was unable to be processed, is it valid Json?',
  10766. jsonNotArray: 'Imported json file must contain an array, aborting.'
  10767. }
  10768. });
  10769. return $delegate;
  10770. }]);
  10771. }]);
  10772. })();
  10773. (function () {
  10774. angular.module('ui.grid').config(['$provide', function($provide) {
  10775. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10776. $delegate.add('hy', {
  10777. aggregate: {
  10778. label: 'տվյալներ'
  10779. },
  10780. groupPanel: {
  10781. description: 'Ըստ սյան խմբավորելու համար քաշեք և գցեք վերնագիրն այստեղ։'
  10782. },
  10783. search: {
  10784. placeholder: 'Փնտրում...',
  10785. showingItems: 'Ցուցադրված տվյալներ՝',
  10786. selectedItems: 'Ընտրված:',
  10787. totalItems: 'Ընդամենը՝',
  10788. size: 'Տողերի քանակը էջում՝',
  10789. first: 'Առաջին էջ',
  10790. next: 'Հաջորդ էջ',
  10791. previous: 'Նախորդ էջ',
  10792. last: 'Վերջին էջ'
  10793. },
  10794. menu: {
  10795. text: 'Ընտրել սյուները:'
  10796. },
  10797. sort: {
  10798. ascending: 'Աճման կարգով',
  10799. descending: 'Նվազման կարգով',
  10800. remove: 'Հանել '
  10801. },
  10802. column: {
  10803. hide: 'Թաքցնել սյունը'
  10804. },
  10805. aggregation: {
  10806. count: 'ընդամենը տող՝ ',
  10807. sum: 'ընդամենը՝ ',
  10808. avg: 'միջին՝ ',
  10809. min: 'մին՝ ',
  10810. max: 'մաքս՝ '
  10811. },
  10812. pinning: {
  10813. pinLeft: 'Կպցնել ձախ կողմում',
  10814. pinRight: 'Կպցնել աջ կողմում',
  10815. unpin: 'Արձակել'
  10816. },
  10817. gridMenu: {
  10818. columns: 'Սյուներ:',
  10819. importerTitle: 'Ներմուծել ֆայլ',
  10820. exporterAllAsCsv: 'Արտահանել ամբողջը CSV',
  10821. exporterVisibleAsCsv: 'Արտահանել երևացող տվյալները CSV',
  10822. exporterSelectedAsCsv: 'Արտահանել ընտրված տվյալները CSV',
  10823. exporterAllAsPdf: 'Արտահանել PDF',
  10824. exporterVisibleAsPdf: 'Արտահանել երևացող տվյալները PDF',
  10825. exporterSelectedAsPdf: 'Արտահանել ընտրված տվյալները PDF',
  10826. clearAllFilters: 'Մաքրել բոլոր ֆիլտրերը'
  10827. },
  10828. importer: {
  10829. noHeaders: 'Հնարավոր չեղավ որոշել սյան վերնագրերը։ Արդյո՞ք ֆայլը ունի վերնագրեր։',
  10830. noObjects: 'Հնարավոր չեղավ կարդալ տվյալները։ Արդյո՞ք ֆայլում կան տվյալներ։',
  10831. invalidCsv: 'Հնարավոր չեղավ մշակել ֆայլը։ Արդյո՞ք այն վավեր CSV է։',
  10832. invalidJson: 'Հնարավոր չեղավ մշակել ֆայլը։ Արդյո՞ք այն վավեր Json է։',
  10833. jsonNotArray: 'Ներմուծված json ֆայլը պետք է պարունակի զանգված, կասեցվում է։'
  10834. }
  10835. });
  10836. return $delegate;
  10837. }]);
  10838. }]);
  10839. })();
  10840. (function () {
  10841. angular.module('ui.grid').config(['$provide', function($provide) {
  10842. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10843. $delegate.add('it', {
  10844. aggregate: {
  10845. label: 'elementi'
  10846. },
  10847. groupPanel: {
  10848. description: 'Trascina un\'intestazione all\'interno del gruppo della colonna.'
  10849. },
  10850. search: {
  10851. placeholder: 'Ricerca...',
  10852. showingItems: 'Mostra:',
  10853. selectedItems: 'Selezionati:',
  10854. totalItems: 'Totali:',
  10855. size: 'Tot Pagine:',
  10856. first: 'Prima',
  10857. next: 'Prossima',
  10858. previous: 'Precedente',
  10859. last: 'Ultima'
  10860. },
  10861. menu: {
  10862. text: 'Scegli le colonne:'
  10863. },
  10864. sort: {
  10865. ascending: 'Asc.',
  10866. descending: 'Desc.',
  10867. remove: 'Annulla ordinamento'
  10868. },
  10869. column: {
  10870. hide: 'Nascondi'
  10871. },
  10872. aggregation: {
  10873. count: 'righe totali: ',
  10874. sum: 'tot: ',
  10875. avg: 'media: ',
  10876. min: 'minimo: ',
  10877. max: 'massimo: '
  10878. },
  10879. pinning: {
  10880. pinLeft: 'Blocca a sx',
  10881. pinRight: 'Blocca a dx',
  10882. unpin: 'Blocca in alto'
  10883. },
  10884. gridMenu: {
  10885. columns: 'Colonne:',
  10886. importerTitle: 'Importa',
  10887. exporterAllAsCsv: 'Esporta tutti i dati in CSV',
  10888. exporterVisibleAsCsv: 'Esporta i dati visibili in CSV',
  10889. exporterSelectedAsCsv: 'Esporta i dati selezionati in CSV',
  10890. exporterAllAsPdf: 'Esporta tutti i dati in PDF',
  10891. exporterVisibleAsPdf: 'Esporta i dati visibili in PDF',
  10892. exporterSelectedAsPdf: 'Esporta i dati selezionati in PDF',
  10893. clearAllFilters: 'Pulire tutti i filtri'
  10894. },
  10895. importer: {
  10896. noHeaders: 'Impossibile reperire i nomi delle colonne, sicuro che siano indicati all\'interno del file?',
  10897. noObjects: 'Impossibile reperire gli oggetti, sicuro che siano indicati all\'interno del file?',
  10898. invalidCsv: 'Impossibile elaborare il file, sicuro che sia un CSV?',
  10899. invalidJson: 'Impossibile elaborare il file, sicuro che sia un JSON valido?',
  10900. jsonNotArray: 'Errore! Il file JSON da importare deve contenere un array.'
  10901. },
  10902. grouping: {
  10903. group: 'Raggruppa',
  10904. ungroup: 'Separa',
  10905. aggregate_count: 'Agg: N. Elem.',
  10906. aggregate_sum: 'Agg: Somma',
  10907. aggregate_max: 'Agg: Massimo',
  10908. aggregate_min: 'Agg: Minimo',
  10909. aggregate_avg: 'Agg: Media',
  10910. aggregate_remove: 'Agg: Rimuovi'
  10911. }
  10912. });
  10913. return $delegate;
  10914. }]);
  10915. }]);
  10916. })();
  10917. (function() {
  10918. angular.module('ui.grid').config(['$provide', function($provide) {
  10919. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10920. $delegate.add('ja', {
  10921. aggregate: {
  10922. label: '項目'
  10923. },
  10924. groupPanel: {
  10925. description: 'ここに列ヘッダをドラッグアンドドロップして、その列でグループ化します。'
  10926. },
  10927. search: {
  10928. placeholder: '検索...',
  10929. showingItems: '表示中の項目:',
  10930. selectedItems: '選択した項目:',
  10931. totalItems: '項目の総数:',
  10932. size: 'ページサイズ:',
  10933. first: '最初のページ',
  10934. next: '次のページ',
  10935. previous: '前のページ',
  10936. last: '前のページ'
  10937. },
  10938. menu: {
  10939. text: '列の選択:'
  10940. },
  10941. sort: {
  10942. ascending: '昇順に並べ替え',
  10943. descending: '降順に並べ替え',
  10944. remove: '並べ替えの解除'
  10945. },
  10946. column: {
  10947. hide: '列の非表示'
  10948. },
  10949. aggregation: {
  10950. count: '合計行数: ',
  10951. sum: '合計: ',
  10952. avg: '平均: ',
  10953. min: '最小: ',
  10954. max: '最大: '
  10955. },
  10956. pinning: {
  10957. pinLeft: '左に固定',
  10958. pinRight: '右に固定',
  10959. unpin: '固定解除'
  10960. },
  10961. gridMenu: {
  10962. columns: '列:',
  10963. importerTitle: 'ファイルのインポート',
  10964. exporterAllAsCsv: 'すべてのデータをCSV形式でエクスポート',
  10965. exporterVisibleAsCsv: '表示中のデータをCSV形式でエクスポート',
  10966. exporterSelectedAsCsv: '選択したデータをCSV形式でエクスポート',
  10967. exporterAllAsPdf: 'すべてのデータをPDF形式でエクスポート',
  10968. exporterVisibleAsPdf: '表示中のデータをPDF形式でエクスポート',
  10969. exporterSelectedAsPdf: '選択したデータをPDF形式でエクスポート',
  10970. clearAllFilters: 'すべてのフィルタを清掃してください'
  10971. },
  10972. importer: {
  10973. noHeaders: '列名を取得できません。ファイルにヘッダが含まれていることを確認してください。',
  10974. noObjects: 'オブジェクトを取得できません。ファイルにヘッダ以外のデータが含まれていることを確認してください。',
  10975. invalidCsv: 'ファイルを処理できません。ファイルが有効なCSV形式であることを確認してください。',
  10976. invalidJson: 'ファイルを処理できません。ファイルが有効なJSON形式であることを確認してください。',
  10977. jsonNotArray: 'インポートしたJSONファイルには配列が含まれている必要があります。処理を中止します。'
  10978. },
  10979. pagination: {
  10980. sizes: '項目/ページ',
  10981. totalItems: '項目'
  10982. }
  10983. });
  10984. return $delegate;
  10985. }]);
  10986. }]);
  10987. })();
  10988. (function () {
  10989. angular.module('ui.grid').config(['$provide', function($provide) {
  10990. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10991. $delegate.add('ko', {
  10992. aggregate: {
  10993. label: '아이템'
  10994. },
  10995. groupPanel: {
  10996. description: '컬럼으로 그룹핑하기 위해서는 컬럼 헤더를 끌어 떨어뜨려 주세요.'
  10997. },
  10998. search: {
  10999. placeholder: '검색...',
  11000. showingItems: '항목 보여주기:',
  11001. selectedItems: '선택 항목:',
  11002. totalItems: '전체 항목:',
  11003. size: '페이지 크기:',
  11004. first: '첫번째 페이지',
  11005. next: '다음 페이지',
  11006. previous: '이전 페이지',
  11007. last: '마지막 페이지'
  11008. },
  11009. menu: {
  11010. text: '컬럼을 선택하세요:'
  11011. },
  11012. sort: {
  11013. ascending: '오름차순 정렬',
  11014. descending: '내림차순 정렬',
  11015. remove: '소팅 제거'
  11016. },
  11017. column: {
  11018. hide: '컬럼 제거'
  11019. },
  11020. aggregation: {
  11021. count: '전체 갯수: ',
  11022. sum: '전체: ',
  11023. avg: '평균: ',
  11024. min: '최소: ',
  11025. max: '최대: '
  11026. },
  11027. pinning: {
  11028. pinLeft: '왼쪽 핀',
  11029. pinRight: '오른쪽 핀',
  11030. unpin: '핀 제거'
  11031. },
  11032. gridMenu: {
  11033. columns: '컬럼:',
  11034. importerTitle: '파일 가져오기',
  11035. exporterAllAsCsv: 'csv로 모든 데이터 내보내기',
  11036. exporterVisibleAsCsv: 'csv로 보이는 데이터 내보내기',
  11037. exporterSelectedAsCsv: 'csv로 선택된 데이터 내보내기',
  11038. exporterAllAsPdf: 'pdf로 모든 데이터 내보내기',
  11039. exporterVisibleAsPdf: 'pdf로 보이는 데이터 내보내기',
  11040. exporterSelectedAsPdf: 'pdf로 선택 데이터 내보내기',
  11041. clearAllFilters: '모든 필터를 청소'
  11042. },
  11043. importer: {
  11044. noHeaders: '컬럼명이 지정되어 있지 않습니다. 파일에 헤더가 명시되어 있는지 확인해 주세요.',
  11045. noObjects: '데이터가 지정되어 있지 않습니다. 데이터가 파일에 있는지 확인해 주세요.',
  11046. invalidCsv: '파일을 처리할 수 없습니다. 올바른 csv인지 확인해 주세요.',
  11047. invalidJson: '파일을 처리할 수 없습니다. 올바른 json인지 확인해 주세요.',
  11048. jsonNotArray: 'json 파일은 배열을 포함해야 합니다.'
  11049. },
  11050. pagination: {
  11051. sizes: '페이지당 항목',
  11052. totalItems: '전체 항목'
  11053. }
  11054. });
  11055. return $delegate;
  11056. }]);
  11057. }]);
  11058. })();
  11059. (function () {
  11060. angular.module('ui.grid').config(['$provide', function($provide) {
  11061. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11062. $delegate.add('nl', {
  11063. aggregate: {
  11064. label: 'items'
  11065. },
  11066. groupPanel: {
  11067. description: 'Sleep hier een kolomnaam heen om op te groeperen.'
  11068. },
  11069. search: {
  11070. placeholder: 'Zoeken...',
  11071. showingItems: 'Getoonde items:',
  11072. selectedItems: 'Geselecteerde items:',
  11073. totalItems: 'Totaal aantal items:',
  11074. size: 'Items per pagina:',
  11075. first: 'Eerste pagina',
  11076. next: 'Volgende pagina',
  11077. previous: 'Vorige pagina',
  11078. last: 'Laatste pagina'
  11079. },
  11080. menu: {
  11081. text: 'Kies kolommen:'
  11082. },
  11083. sort: {
  11084. ascending: 'Sorteer oplopend',
  11085. descending: 'Sorteer aflopend',
  11086. remove: 'Verwijder sortering'
  11087. },
  11088. column: {
  11089. hide: 'Verberg kolom'
  11090. },
  11091. aggregation: {
  11092. count: 'Aantal rijen: ',
  11093. sum: 'Som: ',
  11094. avg: 'Gemiddelde: ',
  11095. min: 'Min: ',
  11096. max: 'Max: '
  11097. },
  11098. pinning: {
  11099. pinLeft: 'Zet links vast',
  11100. pinRight: 'Zet rechts vast',
  11101. unpin: 'Maak los'
  11102. },
  11103. gridMenu: {
  11104. columns: 'Kolommen:',
  11105. importerTitle: 'Importeer bestand',
  11106. exporterAllAsCsv: 'Exporteer alle data als csv',
  11107. exporterVisibleAsCsv: 'Exporteer zichtbare data als csv',
  11108. exporterSelectedAsCsv: 'Exporteer geselecteerde data als csv',
  11109. exporterAllAsPdf: 'Exporteer alle data als pdf',
  11110. exporterVisibleAsPdf: 'Exporteer zichtbare data als pdf',
  11111. exporterSelectedAsPdf: 'Exporteer geselecteerde data als pdf',
  11112. clearAllFilters: 'Reinig alle filters'
  11113. },
  11114. importer: {
  11115. noHeaders: 'Kolomnamen kunnen niet worden afgeleid. Heeft het bestand een header?',
  11116. noObjects: 'Objecten kunnen niet worden afgeleid. Bevat het bestand data naast de headers?',
  11117. invalidCsv: 'Het bestand kan niet verwerkt worden. Is het een valide csv bestand?',
  11118. invalidJson: 'Het bestand kan niet verwerkt worden. Is het valide json?',
  11119. jsonNotArray: 'Het json bestand moet een array bevatten. De actie wordt geannuleerd.'
  11120. },
  11121. pagination: {
  11122. sizes: 'items per pagina',
  11123. totalItems: 'items'
  11124. },
  11125. grouping: {
  11126. group: 'Groepeer',
  11127. ungroup: 'Groepering opheffen',
  11128. aggregate_count: 'Agg: Aantal',
  11129. aggregate_sum: 'Agg: Som',
  11130. aggregate_max: 'Agg: Max',
  11131. aggregate_min: 'Agg: Min',
  11132. aggregate_avg: 'Agg: Gem',
  11133. aggregate_remove: 'Agg: Verwijder'
  11134. }
  11135. });
  11136. return $delegate;
  11137. }]);
  11138. }]);
  11139. })();
  11140. (function () {
  11141. angular.module('ui.grid').config(['$provide', function($provide) {
  11142. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11143. $delegate.add('pt-br', {
  11144. aggregate: {
  11145. label: 'itens'
  11146. },
  11147. groupPanel: {
  11148. description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna'
  11149. },
  11150. search: {
  11151. placeholder: 'Procurar...',
  11152. showingItems: 'Mostrando os Itens:',
  11153. selectedItems: 'Items Selecionados:',
  11154. totalItems: 'Total de Itens:',
  11155. size: 'Tamanho da Página:',
  11156. first: 'Primeira Página',
  11157. next: 'Próxima Página',
  11158. previous: 'Página Anterior',
  11159. last: 'Última Página'
  11160. },
  11161. menu: {
  11162. text: 'Selecione as colunas:'
  11163. },
  11164. sort: {
  11165. ascending: 'Ordenar Ascendente',
  11166. descending: 'Ordenar Descendente',
  11167. remove: 'Remover Ordenação'
  11168. },
  11169. column: {
  11170. hide: 'Esconder coluna'
  11171. },
  11172. aggregation: {
  11173. count: 'total de linhas: ',
  11174. sum: 'total: ',
  11175. avg: 'med: ',
  11176. min: 'min: ',
  11177. max: 'max: '
  11178. },
  11179. pinning: {
  11180. pinLeft: 'Fixar Esquerda',
  11181. pinRight: 'Fixar Direita',
  11182. unpin: 'Desprender'
  11183. },
  11184. gridMenu: {
  11185. columns: 'Colunas:',
  11186. importerTitle: 'Importar arquivo',
  11187. exporterAllAsCsv: 'Exportar todos os dados como csv',
  11188. exporterVisibleAsCsv: 'Exportar dados visíveis como csv',
  11189. exporterSelectedAsCsv: 'Exportar dados selecionados como csv',
  11190. exporterAllAsPdf: 'Exportar todos os dados como pdf',
  11191. exporterVisibleAsPdf: 'Exportar dados visíveis como pdf',
  11192. exporterSelectedAsPdf: 'Exportar dados selecionados como pdf',
  11193. clearAllFilters: 'Limpar todos os filtros'
  11194. },
  11195. importer: {
  11196. noHeaders: 'Nomes de colunas não puderam ser derivados. O arquivo tem um cabeçalho?',
  11197. noObjects: 'Objetos não puderam ser derivados. Havia dados no arquivo, além dos cabeçalhos?',
  11198. invalidCsv: 'Arquivo não pode ser processado. É um CSV válido?',
  11199. invalidJson: 'Arquivo não pode ser processado. É um Json válido?',
  11200. jsonNotArray: 'Arquivo json importado tem que conter um array. Abortando.'
  11201. },
  11202. pagination: {
  11203. sizes: 'itens por página',
  11204. totalItems: 'itens'
  11205. },
  11206. grouping: {
  11207. group: 'Agrupar',
  11208. ungroup: 'Desagrupar',
  11209. aggregate_count: 'Agr: Contar',
  11210. aggregate_sum: 'Agr: Soma',
  11211. aggregate_max: 'Agr: Max',
  11212. aggregate_min: 'Agr: Min',
  11213. aggregate_avg: 'Agr: Med',
  11214. aggregate_remove: 'Agr: Remover'
  11215. }
  11216. });
  11217. return $delegate;
  11218. }]);
  11219. }]);
  11220. })();
  11221. (function () {
  11222. angular.module('ui.grid').config(['$provide', function($provide) {
  11223. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11224. $delegate.add('pt', {
  11225. aggregate: {
  11226. label: 'itens'
  11227. },
  11228. groupPanel: {
  11229. description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna'
  11230. },
  11231. search: {
  11232. placeholder: 'Procurar...',
  11233. showingItems: 'Mostrando os Itens:',
  11234. selectedItems: 'Itens Selecionados:',
  11235. totalItems: 'Total de Itens:',
  11236. size: 'Tamanho da Página:',
  11237. first: 'Primeira Página',
  11238. next: 'Próxima Página',
  11239. previous: 'Página Anterior',
  11240. last: 'Última Página'
  11241. },
  11242. menu: {
  11243. text: 'Selecione as colunas:'
  11244. },
  11245. sort: {
  11246. ascending: 'Ordenar Ascendente',
  11247. descending: 'Ordenar Descendente',
  11248. remove: 'Remover Ordenação'
  11249. },
  11250. column: {
  11251. hide: 'Esconder coluna'
  11252. },
  11253. aggregation: {
  11254. count: 'total de linhas: ',
  11255. sum: 'total: ',
  11256. avg: 'med: ',
  11257. min: 'min: ',
  11258. max: 'max: '
  11259. },
  11260. pinning: {
  11261. pinLeft: 'Fixar Esquerda',
  11262. pinRight: 'Fixar Direita',
  11263. unpin: 'Desprender'
  11264. },
  11265. gridMenu: {
  11266. columns: 'Colunas:',
  11267. importerTitle: 'Importar ficheiro',
  11268. exporterAllAsCsv: 'Exportar todos os dados como csv',
  11269. exporterVisibleAsCsv: 'Exportar dados visíveis como csv',
  11270. exporterSelectedAsCsv: 'Exportar dados selecionados como csv',
  11271. exporterAllAsPdf: 'Exportar todos os dados como pdf',
  11272. exporterVisibleAsPdf: 'Exportar dados visíveis como pdf',
  11273. exporterSelectedAsPdf: 'Exportar dados selecionados como pdf',
  11274. clearAllFilters: 'Limpar todos os filtros'
  11275. },
  11276. importer: {
  11277. noHeaders: 'Nomes de colunas não puderam ser derivados. O ficheiro tem um cabeçalho?',
  11278. noObjects: 'Objetos não puderam ser derivados. Havia dados no ficheiro, além dos cabeçalhos?',
  11279. invalidCsv: 'Ficheiro não pode ser processado. É um CSV válido?',
  11280. invalidJson: 'Ficheiro não pode ser processado. É um Json válido?',
  11281. jsonNotArray: 'Ficheiro json importado tem que conter um array. Interrompendo.'
  11282. },
  11283. pagination: {
  11284. sizes: 'itens por página',
  11285. totalItems: 'itens',
  11286. of: 'de'
  11287. },
  11288. grouping: {
  11289. group: 'Agrupar',
  11290. ungroup: 'Desagrupar',
  11291. aggregate_count: 'Agr: Contar',
  11292. aggregate_sum: 'Agr: Soma',
  11293. aggregate_max: 'Agr: Max',
  11294. aggregate_min: 'Agr: Min',
  11295. aggregate_avg: 'Agr: Med',
  11296. aggregate_remove: 'Agr: Remover'
  11297. }
  11298. });
  11299. return $delegate;
  11300. }]);
  11301. }]);
  11302. })();
  11303. (function () {
  11304. angular.module('ui.grid').config(['$provide', function($provide) {
  11305. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11306. $delegate.add('ru', {
  11307. aggregate: {
  11308. label: 'элементы'
  11309. },
  11310. groupPanel: {
  11311. description: 'Для группировки по столбцу перетащите сюда его название.'
  11312. },
  11313. search: {
  11314. placeholder: 'Поиск...',
  11315. showingItems: 'Показать элементы:',
  11316. selectedItems: 'Выбранные элементы:',
  11317. totalItems: 'Всего элементов:',
  11318. size: 'Размер страницы:',
  11319. first: 'Первая страница',
  11320. next: 'Следующая страница',
  11321. previous: 'Предыдущая страница',
  11322. last: 'Последняя страница'
  11323. },
  11324. menu: {
  11325. text: 'Выбрать столбцы:'
  11326. },
  11327. sort: {
  11328. ascending: 'По возрастанию',
  11329. descending: 'По убыванию',
  11330. remove: 'Убрать сортировку'
  11331. },
  11332. column: {
  11333. hide: 'Спрятать столбец'
  11334. },
  11335. aggregation: {
  11336. count: 'всего строк: ',
  11337. sum: 'итого: ',
  11338. avg: 'среднее: ',
  11339. min: 'мин: ',
  11340. max: 'макс: '
  11341. },
  11342. pinning: {
  11343. pinLeft: 'Закрепить слева',
  11344. pinRight: 'Закрепить справа',
  11345. unpin: 'Открепить'
  11346. },
  11347. gridMenu: {
  11348. columns: 'Столбцы:',
  11349. importerTitle: 'Import file',
  11350. exporterAllAsCsv: 'Экспортировать всё в CSV',
  11351. exporterVisibleAsCsv: 'Экспортировать видимые данные в CSV',
  11352. exporterSelectedAsCsv: 'Экспортировать выбранные данные в CSV',
  11353. exporterAllAsPdf: 'Экспортировать всё в PDF',
  11354. exporterVisibleAsPdf: 'Экспортировать видимые данные в PDF',
  11355. exporterSelectedAsPdf: 'Экспортировать выбранные данные в PDF',
  11356. clearAllFilters: 'Очистите все фильтры'
  11357. },
  11358. importer: {
  11359. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  11360. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  11361. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  11362. invalidJson: 'File was unable to be processed, is it valid Json?',
  11363. jsonNotArray: 'Imported json file must contain an array, aborting.'
  11364. }
  11365. });
  11366. return $delegate;
  11367. }]);
  11368. }]);
  11369. })();
  11370. (function () {
  11371. angular.module('ui.grid').config(['$provide', function($provide) {
  11372. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11373. $delegate.add('sk', {
  11374. aggregate: {
  11375. label: 'items'
  11376. },
  11377. groupPanel: {
  11378. description: 'Pretiahni sem názov stĺpca pre zoskupenie podľa toho stĺpca.'
  11379. },
  11380. search: {
  11381. placeholder: 'Hľadaj...',
  11382. showingItems: 'Zobrazujem položky:',
  11383. selectedItems: 'Vybraté položky:',
  11384. totalItems: 'Počet položiek:',
  11385. size: 'Počet:',
  11386. first: 'Prvá strana',
  11387. next: 'Ďalšia strana',
  11388. previous: 'Predchádzajúca strana',
  11389. last: 'Posledná strana'
  11390. },
  11391. menu: {
  11392. text: 'Vyberte stĺpce:'
  11393. },
  11394. sort: {
  11395. ascending: 'Zotriediť vzostupne',
  11396. descending: 'Zotriediť zostupne',
  11397. remove: 'Vymazať triedenie'
  11398. },
  11399. aggregation: {
  11400. count: 'total rows: ',
  11401. sum: 'total: ',
  11402. avg: 'avg: ',
  11403. min: 'min: ',
  11404. max: 'max: '
  11405. },
  11406. gridMenu: {
  11407. columns: 'Columns:',
  11408. importerTitle: 'Import file',
  11409. exporterAllAsCsv: 'Export all data as csv',
  11410. exporterVisibleAsCsv: 'Export visible data as csv',
  11411. exporterSelectedAsCsv: 'Export selected data as csv',
  11412. exporterAllAsPdf: 'Export all data as pdf',
  11413. exporterVisibleAsPdf: 'Export visible data as pdf',
  11414. exporterSelectedAsPdf: 'Export selected data as pdf',
  11415. clearAllFilters: 'Clear all filters'
  11416. },
  11417. importer: {
  11418. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  11419. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  11420. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  11421. invalidJson: 'File was unable to be processed, is it valid Json?',
  11422. jsonNotArray: 'Imported json file must contain an array, aborting.'
  11423. }
  11424. });
  11425. return $delegate;
  11426. }]);
  11427. }]);
  11428. })();
  11429. (function () {
  11430. angular.module('ui.grid').config(['$provide', function($provide) {
  11431. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11432. $delegate.add('sv', {
  11433. aggregate: {
  11434. label: 'Artiklar'
  11435. },
  11436. groupPanel: {
  11437. description: 'Dra en kolumnrubrik hit och släpp den för att gruppera efter den kolumnen.'
  11438. },
  11439. search: {
  11440. placeholder: 'Sök...',
  11441. showingItems: 'Visar artiklar:',
  11442. selectedItems: 'Valda artiklar:',
  11443. totalItems: 'Antal artiklar:',
  11444. size: 'Sidstorlek:',
  11445. first: 'Första sidan',
  11446. next: 'Nästa sida',
  11447. previous: 'Föregående sida',
  11448. last: 'Sista sidan'
  11449. },
  11450. menu: {
  11451. text: 'Välj kolumner:'
  11452. },
  11453. sort: {
  11454. ascending: 'Sortera stigande',
  11455. descending: 'Sortera fallande',
  11456. remove: 'Inaktivera sortering'
  11457. },
  11458. column: {
  11459. hide: 'Göm kolumn'
  11460. },
  11461. aggregation: {
  11462. count: 'Antal rader: ',
  11463. sum: 'Summa: ',
  11464. avg: 'Genomsnitt: ',
  11465. min: 'Min: ',
  11466. max: 'Max: '
  11467. },
  11468. pinning: {
  11469. pinLeft: 'Fäst vänster',
  11470. pinRight: 'Fäst höger',
  11471. unpin: 'Lösgör'
  11472. },
  11473. gridMenu: {
  11474. columns: 'Kolumner:',
  11475. importerTitle: 'Importera fil',
  11476. exporterAllAsCsv: 'Exportera all data som CSV',
  11477. exporterVisibleAsCsv: 'Exportera synlig data som CSV',
  11478. exporterSelectedAsCsv: 'Exportera markerad data som CSV',
  11479. exporterAllAsPdf: 'Exportera all data som PDF',
  11480. exporterVisibleAsPdf: 'Exportera synlig data som PDF',
  11481. exporterSelectedAsPdf: 'Exportera markerad data som PDF',
  11482. clearAllFilters: 'Rengör alla filter'
  11483. },
  11484. importer: {
  11485. noHeaders: 'Kolumnnamn kunde inte härledas. Har filen ett sidhuvud?',
  11486. noObjects: 'Objekt kunde inte härledas. Har filen data undantaget sidhuvud?',
  11487. invalidCsv: 'Filen kunde inte behandlas, är den en giltig CSV?',
  11488. invalidJson: 'Filen kunde inte behandlas, är den en giltig JSON?',
  11489. jsonNotArray: 'Importerad JSON-fil måste innehålla ett fält. Import avbruten.'
  11490. },
  11491. pagination: {
  11492. sizes: 'Artiklar per sida',
  11493. totalItems: 'Artiklar'
  11494. }
  11495. });
  11496. return $delegate;
  11497. }]);
  11498. }]);
  11499. })();
  11500. (function () {
  11501. angular.module('ui.grid').config(['$provide', function($provide) {
  11502. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11503. $delegate.add('ta', {
  11504. aggregate: {
  11505. label: 'உருப்படிகள்'
  11506. },
  11507. groupPanel: {
  11508. description: 'ஒரு பத்தியை குழுவாக அமைக்க அப்பத்தியின் தலைப்பை இங்கே இழுத்து வரவும் '
  11509. },
  11510. search: {
  11511. placeholder: 'தேடல் ...',
  11512. showingItems: 'உருப்படிகளை காண்பித்தல்:',
  11513. selectedItems: 'தேர்ந்தெடுக்கப்பட்ட உருப்படிகள்:',
  11514. totalItems: 'மொத்த உருப்படிகள்:',
  11515. size: 'பக்க அளவு: ',
  11516. first: 'முதல் பக்கம்',
  11517. next: 'அடுத்த பக்கம்',
  11518. previous: 'முந்தைய பக்கம் ',
  11519. last: 'இறுதி பக்கம்'
  11520. },
  11521. menu: {
  11522. text: 'பத்திகளை தேர்ந்தெடு:'
  11523. },
  11524. sort: {
  11525. ascending: 'மேலிருந்து கீழாக',
  11526. descending: 'கீழிருந்து மேலாக',
  11527. remove: 'வரிசையை நீக்கு'
  11528. },
  11529. column: {
  11530. hide: 'பத்தியை மறைத்து வை '
  11531. },
  11532. aggregation: {
  11533. count: 'மொத்த வரிகள்:',
  11534. sum: 'மொத்தம்: ',
  11535. avg: 'சராசரி: ',
  11536. min: 'குறைந்தபட்ச: ',
  11537. max: 'அதிகபட்ச: '
  11538. },
  11539. pinning: {
  11540. pinLeft: 'இடதுபுறமாக தைக்க ',
  11541. pinRight: 'வலதுபுறமாக தைக்க',
  11542. unpin: 'பிரி'
  11543. },
  11544. gridMenu: {
  11545. columns: 'பத்திகள்:',
  11546. importerTitle: 'கோப்பு : படித்தல்',
  11547. exporterAllAsCsv: 'எல்லா தரவுகளையும் கோப்பாக்கு: csv',
  11548. exporterVisibleAsCsv: 'இருக்கும் தரவுகளை கோப்பாக்கு: csv',
  11549. exporterSelectedAsCsv: 'தேர்ந்தெடுத்த தரவுகளை கோப்பாக்கு: csv',
  11550. exporterAllAsPdf: 'எல்லா தரவுகளையும் கோப்பாக்கு: pdf',
  11551. exporterVisibleAsPdf: 'இருக்கும் தரவுகளை கோப்பாக்கு: pdf',
  11552. exporterSelectedAsPdf: 'தேர்ந்தெடுத்த தரவுகளை கோப்பாக்கு: pdf',
  11553. clearAllFilters: 'Clear all filters'
  11554. },
  11555. importer: {
  11556. noHeaders: 'பத்தியின் தலைப்புகளை பெற இயலவில்லை, கோப்பிற்கு தலைப்பு உள்ளதா?',
  11557. noObjects: 'இலக்குகளை உருவாக்க முடியவில்லை, கோப்பில் தலைப்புகளை தவிர தரவு ஏதேனும் உள்ளதா? ',
  11558. invalidCsv: 'சரிவர நடைமுறை படுத்த இயலவில்லை, கோப்பு சரிதானா? - csv',
  11559. invalidJson: 'சரிவர நடைமுறை படுத்த இயலவில்லை, கோப்பு சரிதானா? - json',
  11560. jsonNotArray: 'படித்த கோப்பில் வரிசைகள் உள்ளது, நடைமுறை ரத்து செய் : json'
  11561. },
  11562. pagination: {
  11563. sizes : 'உருப்படிகள் / பக்கம்',
  11564. totalItems : 'உருப்படிகள் '
  11565. },
  11566. grouping: {
  11567. group : 'குழு',
  11568. ungroup : 'பிரி',
  11569. aggregate_count : 'மதிப்பீட்டு : எண்ணு',
  11570. aggregate_sum : 'மதிப்பீட்டு : கூட்டல்',
  11571. aggregate_max : 'மதிப்பீட்டு : அதிகபட்சம்',
  11572. aggregate_min : 'மதிப்பீட்டு : குறைந்தபட்சம்',
  11573. aggregate_avg : 'மதிப்பீட்டு : சராசரி',
  11574. aggregate_remove : 'மதிப்பீட்டு : நீக்கு'
  11575. }
  11576. });
  11577. return $delegate;
  11578. }]);
  11579. }]);
  11580. })();
  11581. /**
  11582. * @ngdoc overview
  11583. * @name ui.grid.i18n
  11584. * @description
  11585. *
  11586. * # ui.grid.i18n
  11587. * This module provides i18n functions to ui.grid and any application that wants to use it
  11588. *
  11589. * <div doc-module-components="ui.grid.i18n"></div>
  11590. */
  11591. (function () {
  11592. var DIRECTIVE_ALIASES = ['uiT', 'uiTranslate'];
  11593. var FILTER_ALIASES = ['t', 'uiTranslate'];
  11594. var module = angular.module('ui.grid.i18n');
  11595. /**
  11596. * @ngdoc object
  11597. * @name ui.grid.i18n.constant:i18nConstants
  11598. *
  11599. * @description constants available in i18n module
  11600. */
  11601. module.constant('i18nConstants', {
  11602. MISSING: '[MISSING]',
  11603. UPDATE_EVENT: '$uiI18n',
  11604. LOCALE_DIRECTIVE_ALIAS: 'uiI18n',
  11605. // default to english
  11606. DEFAULT_LANG: 'en'
  11607. });
  11608. // module.config(['$provide', function($provide) {
  11609. // $provide.decorator('i18nService', ['$delegate', function($delegate) {}])}]);
  11610. /**
  11611. * @ngdoc service
  11612. * @name ui.grid.i18n.service:i18nService
  11613. *
  11614. * @description Services for i18n
  11615. */
  11616. module.service('i18nService', ['$log', 'i18nConstants', '$rootScope',
  11617. function ($log, i18nConstants, $rootScope) {
  11618. var langCache = {
  11619. _langs: {},
  11620. current: null,
  11621. get: function (lang) {
  11622. return this._langs[lang.toLowerCase()];
  11623. },
  11624. add: function (lang, strings) {
  11625. var lower = lang.toLowerCase();
  11626. if (!this._langs[lower]) {
  11627. this._langs[lower] = {};
  11628. }
  11629. angular.extend(this._langs[lower], strings);
  11630. },
  11631. getAllLangs: function () {
  11632. var langs = [];
  11633. if (!this._langs) {
  11634. return langs;
  11635. }
  11636. for (var key in this._langs) {
  11637. langs.push(key);
  11638. }
  11639. return langs;
  11640. },
  11641. setCurrent: function (lang) {
  11642. this.current = lang.toLowerCase();
  11643. },
  11644. getCurrentLang: function () {
  11645. return this.current;
  11646. }
  11647. };
  11648. var service = {
  11649. /**
  11650. * @ngdoc service
  11651. * @name add
  11652. * @methodOf ui.grid.i18n.service:i18nService
  11653. * @description Adds the languages and strings to the cache. Decorate this service to
  11654. * add more translation strings
  11655. * @param {string} lang language to add
  11656. * @param {object} stringMaps of strings to add grouped by property names
  11657. * @example
  11658. * <pre>
  11659. * i18nService.add('en', {
  11660. * aggregate: {
  11661. * label1: 'items',
  11662. * label2: 'some more items'
  11663. * }
  11664. * },
  11665. * groupPanel: {
  11666. * description: 'Drag a column header here and drop it to group by that column.'
  11667. * }
  11668. * }
  11669. * </pre>
  11670. */
  11671. add: function (langs, stringMaps) {
  11672. if (typeof(langs) === 'object') {
  11673. angular.forEach(langs, function (lang) {
  11674. if (lang) {
  11675. langCache.add(lang, stringMaps);
  11676. }
  11677. });
  11678. } else {
  11679. langCache.add(langs, stringMaps);
  11680. }
  11681. },
  11682. /**
  11683. * @ngdoc service
  11684. * @name getAllLangs
  11685. * @methodOf ui.grid.i18n.service:i18nService
  11686. * @description return all currently loaded languages
  11687. * @returns {array} string
  11688. */
  11689. getAllLangs: function () {
  11690. return langCache.getAllLangs();
  11691. },
  11692. /**
  11693. * @ngdoc service
  11694. * @name get
  11695. * @methodOf ui.grid.i18n.service:i18nService
  11696. * @description return all currently loaded languages
  11697. * @param {string} lang to return. If not specified, returns current language
  11698. * @returns {object} the translation string maps for the language
  11699. */
  11700. get: function (lang) {
  11701. var language = lang ? lang : service.getCurrentLang();
  11702. return langCache.get(language);
  11703. },
  11704. /**
  11705. * @ngdoc service
  11706. * @name getSafeText
  11707. * @methodOf ui.grid.i18n.service:i18nService
  11708. * @description returns the text specified in the path or a Missing text if text is not found
  11709. * @param {string} path property path to use for retrieving text from string map
  11710. * @param {string} lang to return. If not specified, returns current language
  11711. * @returns {object} the translation for the path
  11712. * @example
  11713. * <pre>
  11714. * i18nService.getSafeText('sort.ascending')
  11715. * </pre>
  11716. */
  11717. getSafeText: function (path, lang) {
  11718. var language = lang ? lang : service.getCurrentLang();
  11719. var trans = langCache.get(language);
  11720. if (!trans) {
  11721. return i18nConstants.MISSING;
  11722. }
  11723. var paths = path.split('.');
  11724. var current = trans;
  11725. for (var i = 0; i < paths.length; ++i) {
  11726. if (current[paths[i]] === undefined || current[paths[i]] === null) {
  11727. return i18nConstants.MISSING;
  11728. } else {
  11729. current = current[paths[i]];
  11730. }
  11731. }
  11732. return current;
  11733. },
  11734. /**
  11735. * @ngdoc service
  11736. * @name setCurrentLang
  11737. * @methodOf ui.grid.i18n.service:i18nService
  11738. * @description sets the current language to use in the application
  11739. * $broadcasts the Update_Event on the $rootScope
  11740. * @param {string} lang to set
  11741. * @example
  11742. * <pre>
  11743. * i18nService.setCurrentLang('fr');
  11744. * </pre>
  11745. */
  11746. setCurrentLang: function (lang) {
  11747. if (lang) {
  11748. langCache.setCurrent(lang);
  11749. $rootScope.$broadcast(i18nConstants.UPDATE_EVENT);
  11750. }
  11751. },
  11752. /**
  11753. * @ngdoc service
  11754. * @name getCurrentLang
  11755. * @methodOf ui.grid.i18n.service:i18nService
  11756. * @description returns the current language used in the application
  11757. */
  11758. getCurrentLang: function () {
  11759. var lang = langCache.getCurrentLang();
  11760. if (!lang) {
  11761. lang = i18nConstants.DEFAULT_LANG;
  11762. langCache.setCurrent(lang);
  11763. }
  11764. return lang;
  11765. }
  11766. };
  11767. return service;
  11768. }]);
  11769. var localeDirective = function (i18nService, i18nConstants) {
  11770. return {
  11771. compile: function () {
  11772. return {
  11773. pre: function ($scope, $elm, $attrs) {
  11774. var alias = i18nConstants.LOCALE_DIRECTIVE_ALIAS;
  11775. // check for watchable property
  11776. var lang = $scope.$eval($attrs[alias]);
  11777. if (lang) {
  11778. $scope.$watch($attrs[alias], function () {
  11779. i18nService.setCurrentLang(lang);
  11780. });
  11781. } else if ($attrs.$$observers) {
  11782. $attrs.$observe(alias, function () {
  11783. i18nService.setCurrentLang($attrs[alias] || i18nConstants.DEFAULT_LANG);
  11784. });
  11785. }
  11786. }
  11787. };
  11788. }
  11789. };
  11790. };
  11791. module.directive('uiI18n', ['i18nService', 'i18nConstants', localeDirective]);
  11792. // directive syntax
  11793. var uitDirective = function ($parse, i18nService, i18nConstants) {
  11794. return {
  11795. restrict: 'EA',
  11796. compile: function () {
  11797. return {
  11798. pre: function ($scope, $elm, $attrs) {
  11799. var alias1 = DIRECTIVE_ALIASES[0],
  11800. alias2 = DIRECTIVE_ALIASES[1];
  11801. var token = $attrs[alias1] || $attrs[alias2] || $elm.html();
  11802. var missing = i18nConstants.MISSING + token;
  11803. var observer;
  11804. if ($attrs.$$observers) {
  11805. var prop = $attrs[alias1] ? alias1 : alias2;
  11806. observer = $attrs.$observe(prop, function (result) {
  11807. if (result) {
  11808. $elm.html($parse(result)(i18nService.getCurrentLang()) || missing);
  11809. }
  11810. });
  11811. }
  11812. var getter = $parse(token);
  11813. var listener = $scope.$on(i18nConstants.UPDATE_EVENT, function (evt) {
  11814. if (observer) {
  11815. observer($attrs[alias1] || $attrs[alias2]);
  11816. } else {
  11817. // set text based on i18n current language
  11818. $elm.html(getter(i18nService.get()) || missing);
  11819. }
  11820. });
  11821. $scope.$on('$destroy', listener);
  11822. $elm.html(getter(i18nService.get()) || missing);
  11823. }
  11824. };
  11825. }
  11826. };
  11827. };
  11828. angular.forEach( DIRECTIVE_ALIASES, function ( alias ) {
  11829. module.directive( alias, ['$parse', 'i18nService', 'i18nConstants', uitDirective] );
  11830. } );
  11831. // optional filter syntax
  11832. var uitFilter = function ($parse, i18nService, i18nConstants) {
  11833. return function (data) {
  11834. var getter = $parse(data);
  11835. // set text based on i18n current language
  11836. return getter(i18nService.get()) || i18nConstants.MISSING + data;
  11837. };
  11838. };
  11839. angular.forEach( FILTER_ALIASES, function ( alias ) {
  11840. module.filter( alias, ['$parse', 'i18nService', 'i18nConstants', uitFilter] );
  11841. } );
  11842. })();
  11843. (function() {
  11844. angular.module('ui.grid').config(['$provide', function($provide) {
  11845. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11846. $delegate.add('zh-cn', {
  11847. headerCell: {
  11848. aria: {
  11849. defaultFilterLabel: '列过滤器',
  11850. removeFilter: '移除过滤器',
  11851. columnMenuButtonLabel: '列菜单'
  11852. },
  11853. priority: '优先级:',
  11854. filterLabel: "列过滤器: "
  11855. },
  11856. aggregate: {
  11857. label: '行'
  11858. },
  11859. groupPanel: {
  11860. description: '拖曳表头到此处进行分组'
  11861. },
  11862. search: {
  11863. placeholder: '查找',
  11864. showingItems: '已显示行数:',
  11865. selectedItems: '已选择行数:',
  11866. totalItems: '总行数:',
  11867. size: '每页显示行数:',
  11868. first: '首页',
  11869. next: '下一页',
  11870. previous: '上一页',
  11871. last: '末页'
  11872. },
  11873. menu: {
  11874. text: '选择列:'
  11875. },
  11876. sort: {
  11877. ascending: '升序',
  11878. descending: '降序',
  11879. none: '无序',
  11880. remove: '取消排序'
  11881. },
  11882. column: {
  11883. hide: '隐藏列'
  11884. },
  11885. aggregation: {
  11886. count: '计数:',
  11887. sum: '求和:',
  11888. avg: '均值:',
  11889. min: '最小值:',
  11890. max: '最大值:'
  11891. },
  11892. pinning: {
  11893. pinLeft: '左侧固定',
  11894. pinRight: '右侧固定',
  11895. unpin: '取消固定'
  11896. },
  11897. columnMenu: {
  11898. close: '关闭'
  11899. },
  11900. gridMenu: {
  11901. aria: {
  11902. buttonLabel: '表格菜单'
  11903. },
  11904. columns: '列:',
  11905. importerTitle: '导入文件',
  11906. exporterAllAsCsv: '导出全部数据到CSV',
  11907. exporterVisibleAsCsv: '导出可见数据到CSV',
  11908. exporterSelectedAsCsv: '导出已选数据到CSV',
  11909. exporterAllAsPdf: '导出全部数据到PDF',
  11910. exporterVisibleAsPdf: '导出可见数据到PDF',
  11911. exporterSelectedAsPdf: '导出已选数据到PDF',
  11912. clearAllFilters: '清除所有过滤器'
  11913. },
  11914. importer: {
  11915. noHeaders: '无法获取列名,确定文件包含表头?',
  11916. noObjects: '无法获取数据,确定文件包含数据?',
  11917. invalidCsv: '无法处理文件,确定是合法的CSV文件?',
  11918. invalidJson: '无法处理文件,确定是合法的JSON文件?',
  11919. jsonNotArray: '导入的文件不是JSON数组!'
  11920. },
  11921. pagination: {
  11922. aria: {
  11923. pageToFirst: '第一页',
  11924. pageBack: '上一页',
  11925. pageSelected: '当前页',
  11926. pageForward: '下一页',
  11927. pageToLast: '最后一页'
  11928. },
  11929. sizes: '行每页',
  11930. totalItems: '行',
  11931. through: '至',
  11932. of: '共'
  11933. },
  11934. grouping: {
  11935. group: '分组',
  11936. ungroup: '取消分组',
  11937. aggregate_count: '合计: 计数',
  11938. aggregate_sum: '合计: 求和',
  11939. aggregate_max: '合计: 最大',
  11940. aggregate_min: '合计: 最小',
  11941. aggregate_avg: '合计: 平均',
  11942. aggregate_remove: '合计: 移除'
  11943. }
  11944. });
  11945. return $delegate;
  11946. }]);
  11947. }]);
  11948. })();
  11949. (function() {
  11950. angular.module('ui.grid').config(['$provide', function($provide) {
  11951. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11952. $delegate.add('zh-tw', {
  11953. aggregate: {
  11954. label: '行'
  11955. },
  11956. groupPanel: {
  11957. description: '拖曳表頭到此處進行分組'
  11958. },
  11959. search: {
  11960. placeholder: '查找',
  11961. showingItems: '已顯示行數:',
  11962. selectedItems: '已選擇行數:',
  11963. totalItems: '總行數:',
  11964. size: '每頁顯示行數:',
  11965. first: '首頁',
  11966. next: '下壹頁',
  11967. previous: '上壹頁',
  11968. last: '末頁'
  11969. },
  11970. menu: {
  11971. text: '選擇列:'
  11972. },
  11973. sort: {
  11974. ascending: '升序',
  11975. descending: '降序',
  11976. remove: '取消排序'
  11977. },
  11978. column: {
  11979. hide: '隱藏列'
  11980. },
  11981. aggregation: {
  11982. count: '計數:',
  11983. sum: '求和:',
  11984. avg: '均值:',
  11985. min: '最小值:',
  11986. max: '最大值:'
  11987. },
  11988. pinning: {
  11989. pinLeft: '左側固定',
  11990. pinRight: '右側固定',
  11991. unpin: '取消固定'
  11992. },
  11993. gridMenu: {
  11994. columns: '列:',
  11995. importerTitle: '導入文件',
  11996. exporterAllAsCsv: '導出全部數據到CSV',
  11997. exporterVisibleAsCsv: '導出可見數據到CSV',
  11998. exporterSelectedAsCsv: '導出已選數據到CSV',
  11999. exporterAllAsPdf: '導出全部數據到PDF',
  12000. exporterVisibleAsPdf: '導出可見數據到PDF',
  12001. exporterSelectedAsPdf: '導出已選數據到PDF',
  12002. clearAllFilters: '清除所有过滤器'
  12003. },
  12004. importer: {
  12005. noHeaders: '無法獲取列名,確定文件包含表頭?',
  12006. noObjects: '無法獲取數據,確定文件包含數據?',
  12007. invalidCsv: '無法處理文件,確定是合法的CSV文件?',
  12008. invalidJson: '無法處理文件,確定是合法的JSON文件?',
  12009. jsonNotArray: '導入的文件不是JSON數組!'
  12010. },
  12011. pagination: {
  12012. sizes: '行每頁',
  12013. totalItems: '行'
  12014. }
  12015. });
  12016. return $delegate;
  12017. }]);
  12018. }]);
  12019. })();
  12020. (function() {
  12021. 'use strict';
  12022. /**
  12023. * @ngdoc overview
  12024. * @name ui.grid.autoResize
  12025. *
  12026. * @description
  12027. *
  12028. * #ui.grid.autoResize
  12029. *
  12030. * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div>
  12031. *
  12032. * This module provides auto-resizing functionality to UI-Grid.
  12033. */
  12034. var module = angular.module('ui.grid.autoResize', ['ui.grid']);
  12035. module.directive('uiGridAutoResize', ['$timeout', 'gridUtil', function ($timeout, gridUtil) {
  12036. return {
  12037. require: 'uiGrid',
  12038. scope: false,
  12039. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  12040. var prevGridWidth, prevGridHeight;
  12041. function getDimensions() {
  12042. prevGridHeight = gridUtil.elementHeight($elm);
  12043. prevGridWidth = gridUtil.elementWidth($elm);
  12044. }
  12045. // Initialize the dimensions
  12046. getDimensions();
  12047. var resizeTimeoutId;
  12048. function startTimeout() {
  12049. clearTimeout(resizeTimeoutId);
  12050. resizeTimeoutId = setTimeout(function () {
  12051. var newGridHeight = gridUtil.elementHeight($elm);
  12052. var newGridWidth = gridUtil.elementWidth($elm);
  12053. if (newGridHeight !== prevGridHeight || newGridWidth !== prevGridWidth) {
  12054. uiGridCtrl.grid.gridHeight = newGridHeight;
  12055. uiGridCtrl.grid.gridWidth = newGridWidth;
  12056. $scope.$apply(function () {
  12057. uiGridCtrl.grid.refresh()
  12058. .then(function () {
  12059. getDimensions();
  12060. startTimeout();
  12061. });
  12062. });
  12063. }
  12064. else {
  12065. startTimeout();
  12066. }
  12067. }, 250);
  12068. }
  12069. startTimeout();
  12070. $scope.$on('$destroy', function() {
  12071. clearTimeout(resizeTimeoutId);
  12072. });
  12073. }
  12074. };
  12075. }]);
  12076. })();
  12077. (function () {
  12078. 'use strict';
  12079. /**
  12080. * @ngdoc overview
  12081. * @name ui.grid.cellNav
  12082. *
  12083. * @description
  12084. #ui.grid.cellNav
  12085. <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  12086. This module provides auto-resizing functionality to UI-Grid.
  12087. */
  12088. var module = angular.module('ui.grid.cellNav', ['ui.grid']);
  12089. /**
  12090. * @ngdoc object
  12091. * @name ui.grid.cellNav.constant:uiGridCellNavConstants
  12092. *
  12093. * @description constants available in cellNav
  12094. */
  12095. module.constant('uiGridCellNavConstants', {
  12096. FEATURE_NAME: 'gridCellNav',
  12097. CELL_NAV_EVENT: 'cellNav',
  12098. direction: {LEFT: 0, RIGHT: 1, UP: 2, DOWN: 3, PG_UP: 4, PG_DOWN: 5},
  12099. EVENT_TYPE: {
  12100. KEYDOWN: 0,
  12101. CLICK: 1,
  12102. CLEAR: 2
  12103. }
  12104. });
  12105. module.factory('uiGridCellNavFactory', ['gridUtil', 'uiGridConstants', 'uiGridCellNavConstants', 'GridRowColumn', '$q',
  12106. function (gridUtil, uiGridConstants, uiGridCellNavConstants, GridRowColumn, $q) {
  12107. /**
  12108. * @ngdoc object
  12109. * @name ui.grid.cellNav.object:CellNav
  12110. * @description returns a CellNav prototype function
  12111. * @param {object} rowContainer container for rows
  12112. * @param {object} colContainer parent column container
  12113. * @param {object} leftColContainer column container to the left of parent
  12114. * @param {object} rightColContainer column container to the right of parent
  12115. */
  12116. var UiGridCellNav = function UiGridCellNav(rowContainer, colContainer, leftColContainer, rightColContainer) {
  12117. this.rows = rowContainer.visibleRowCache;
  12118. this.columns = colContainer.visibleColumnCache;
  12119. this.leftColumns = leftColContainer ? leftColContainer.visibleColumnCache : [];
  12120. this.rightColumns = rightColContainer ? rightColContainer.visibleColumnCache : [];
  12121. this.bodyContainer = rowContainer;
  12122. };
  12123. /** returns focusable columns of all containers */
  12124. UiGridCellNav.prototype.getFocusableCols = function () {
  12125. var allColumns = this.leftColumns.concat(this.columns, this.rightColumns);
  12126. return allColumns.filter(function (col) {
  12127. return col.colDef.allowCellFocus;
  12128. });
  12129. };
  12130. /**
  12131. * @ngdoc object
  12132. * @name ui.grid.cellNav.api:GridRow
  12133. *
  12134. * @description GridRow settings for cellNav feature, these are available to be
  12135. * set only internally (for example, by other features)
  12136. */
  12137. /**
  12138. * @ngdoc object
  12139. * @name allowCellFocus
  12140. * @propertyOf ui.grid.cellNav.api:GridRow
  12141. * @description Enable focus on a cell within this row. If set to false then no cells
  12142. * in this row can be focused - group header rows as an example would set this to false.
  12143. * <br/>Defaults to true
  12144. */
  12145. /** returns focusable rows */
  12146. UiGridCellNav.prototype.getFocusableRows = function () {
  12147. return this.rows.filter(function(row) {
  12148. return row.allowCellFocus !== false;
  12149. });
  12150. };
  12151. UiGridCellNav.prototype.getNextRowCol = function (direction, curRow, curCol) {
  12152. switch (direction) {
  12153. case uiGridCellNavConstants.direction.LEFT:
  12154. return this.getRowColLeft(curRow, curCol);
  12155. case uiGridCellNavConstants.direction.RIGHT:
  12156. return this.getRowColRight(curRow, curCol);
  12157. case uiGridCellNavConstants.direction.UP:
  12158. return this.getRowColUp(curRow, curCol);
  12159. case uiGridCellNavConstants.direction.DOWN:
  12160. return this.getRowColDown(curRow, curCol);
  12161. case uiGridCellNavConstants.direction.PG_UP:
  12162. return this.getRowColPageUp(curRow, curCol);
  12163. case uiGridCellNavConstants.direction.PG_DOWN:
  12164. return this.getRowColPageDown(curRow, curCol);
  12165. }
  12166. };
  12167. UiGridCellNav.prototype.initializeSelection = function () {
  12168. var focusableCols = this.getFocusableCols();
  12169. var focusableRows = this.getFocusableRows();
  12170. if (focusableCols.length === 0 || focusableRows.length === 0) {
  12171. return null;
  12172. }
  12173. var curRowIndex = 0;
  12174. var curColIndex = 0;
  12175. return new GridRowColumn(focusableRows[0], focusableCols[0]); //return same row
  12176. };
  12177. UiGridCellNav.prototype.getRowColLeft = function (curRow, curCol) {
  12178. var focusableCols = this.getFocusableCols();
  12179. var focusableRows = this.getFocusableRows();
  12180. var curColIndex = focusableCols.indexOf(curCol);
  12181. var curRowIndex = focusableRows.indexOf(curRow);
  12182. //could not find column in focusable Columns so set it to 1
  12183. if (curColIndex === -1) {
  12184. curColIndex = 1;
  12185. }
  12186. var nextColIndex = curColIndex === 0 ? focusableCols.length - 1 : curColIndex - 1;
  12187. //get column to left
  12188. if (nextColIndex > curColIndex) {
  12189. // On the first row
  12190. // if (curRowIndex === 0 && curColIndex === 0) {
  12191. // return null;
  12192. // }
  12193. if (curRowIndex === 0) {
  12194. return new GridRowColumn(curRow, focusableCols[nextColIndex]); //return same row
  12195. }
  12196. else {
  12197. //up one row and far right column
  12198. return new GridRowColumn(focusableRows[curRowIndex - 1], focusableCols[nextColIndex]);
  12199. }
  12200. }
  12201. else {
  12202. return new GridRowColumn(curRow, focusableCols[nextColIndex]);
  12203. }
  12204. };
  12205. UiGridCellNav.prototype.getRowColRight = function (curRow, curCol) {
  12206. var focusableCols = this.getFocusableCols();
  12207. var focusableRows = this.getFocusableRows();
  12208. var curColIndex = focusableCols.indexOf(curCol);
  12209. var curRowIndex = focusableRows.indexOf(curRow);
  12210. //could not find column in focusable Columns so set it to 0
  12211. if (curColIndex === -1) {
  12212. curColIndex = 0;
  12213. }
  12214. var nextColIndex = curColIndex === focusableCols.length - 1 ? 0 : curColIndex + 1;
  12215. if (nextColIndex < curColIndex) {
  12216. if (curRowIndex === focusableRows.length - 1) {
  12217. return new GridRowColumn(curRow, focusableCols[nextColIndex]); //return same row
  12218. }
  12219. else {
  12220. //down one row and far left column
  12221. return new GridRowColumn(focusableRows[curRowIndex + 1], focusableCols[nextColIndex]);
  12222. }
  12223. }
  12224. else {
  12225. return new GridRowColumn(curRow, focusableCols[nextColIndex]);
  12226. }
  12227. };
  12228. UiGridCellNav.prototype.getRowColDown = function (curRow, curCol) {
  12229. var focusableCols = this.getFocusableCols();
  12230. var focusableRows = this.getFocusableRows();
  12231. var curColIndex = focusableCols.indexOf(curCol);
  12232. var curRowIndex = focusableRows.indexOf(curRow);
  12233. //could not find column in focusable Columns so set it to 0
  12234. if (curColIndex === -1) {
  12235. curColIndex = 0;
  12236. }
  12237. if (curRowIndex === focusableRows.length - 1) {
  12238. return new GridRowColumn(curRow, focusableCols[curColIndex]); //return same row
  12239. }
  12240. else {
  12241. //down one row
  12242. return new GridRowColumn(focusableRows[curRowIndex + 1], focusableCols[curColIndex]);
  12243. }
  12244. };
  12245. UiGridCellNav.prototype.getRowColPageDown = function (curRow, curCol) {
  12246. var focusableCols = this.getFocusableCols();
  12247. var focusableRows = this.getFocusableRows();
  12248. var curColIndex = focusableCols.indexOf(curCol);
  12249. var curRowIndex = focusableRows.indexOf(curRow);
  12250. //could not find column in focusable Columns so set it to 0
  12251. if (curColIndex === -1) {
  12252. curColIndex = 0;
  12253. }
  12254. var pageSize = this.bodyContainer.minRowsToRender();
  12255. if (curRowIndex >= focusableRows.length - pageSize) {
  12256. return new GridRowColumn(focusableRows[focusableRows.length - 1], focusableCols[curColIndex]); //return last row
  12257. }
  12258. else {
  12259. //down one page
  12260. return new GridRowColumn(focusableRows[curRowIndex + pageSize], focusableCols[curColIndex]);
  12261. }
  12262. };
  12263. UiGridCellNav.prototype.getRowColUp = function (curRow, curCol) {
  12264. var focusableCols = this.getFocusableCols();
  12265. var focusableRows = this.getFocusableRows();
  12266. var curColIndex = focusableCols.indexOf(curCol);
  12267. var curRowIndex = focusableRows.indexOf(curRow);
  12268. //could not find column in focusable Columns so set it to 0
  12269. if (curColIndex === -1) {
  12270. curColIndex = 0;
  12271. }
  12272. if (curRowIndex === 0) {
  12273. return new GridRowColumn(curRow, focusableCols[curColIndex]); //return same row
  12274. }
  12275. else {
  12276. //up one row
  12277. return new GridRowColumn(focusableRows[curRowIndex - 1], focusableCols[curColIndex]);
  12278. }
  12279. };
  12280. UiGridCellNav.prototype.getRowColPageUp = function (curRow, curCol) {
  12281. var focusableCols = this.getFocusableCols();
  12282. var focusableRows = this.getFocusableRows();
  12283. var curColIndex = focusableCols.indexOf(curCol);
  12284. var curRowIndex = focusableRows.indexOf(curRow);
  12285. //could not find column in focusable Columns so set it to 0
  12286. if (curColIndex === -1) {
  12287. curColIndex = 0;
  12288. }
  12289. var pageSize = this.bodyContainer.minRowsToRender();
  12290. if (curRowIndex - pageSize < 0) {
  12291. return new GridRowColumn(focusableRows[0], focusableCols[curColIndex]); //return first row
  12292. }
  12293. else {
  12294. //up one page
  12295. return new GridRowColumn(focusableRows[curRowIndex - pageSize], focusableCols[curColIndex]);
  12296. }
  12297. };
  12298. return UiGridCellNav;
  12299. }]);
  12300. /**
  12301. * @ngdoc service
  12302. * @name ui.grid.cellNav.service:uiGridCellNavService
  12303. *
  12304. * @description Services for cell navigation features. If you don't like the key maps we use,
  12305. * or the direction cells navigation, override with a service decorator (see angular docs)
  12306. */
  12307. module.service('uiGridCellNavService', ['gridUtil', 'uiGridConstants', 'uiGridCellNavConstants', '$q', 'uiGridCellNavFactory', 'GridRowColumn', 'ScrollEvent',
  12308. function (gridUtil, uiGridConstants, uiGridCellNavConstants, $q, UiGridCellNav, GridRowColumn, ScrollEvent) {
  12309. var service = {
  12310. initializeGrid: function (grid) {
  12311. grid.registerColumnBuilder(service.cellNavColumnBuilder);
  12312. /**
  12313. * @ngdoc object
  12314. * @name ui.grid.cellNav:Grid.cellNav
  12315. * @description cellNav properties added to grid class
  12316. */
  12317. grid.cellNav = {};
  12318. grid.cellNav.lastRowCol = null;
  12319. grid.cellNav.focusedCells = [];
  12320. service.defaultGridOptions(grid.options);
  12321. /**
  12322. * @ngdoc object
  12323. * @name ui.grid.cellNav.api:PublicApi
  12324. *
  12325. * @description Public Api for cellNav feature
  12326. */
  12327. var publicApi = {
  12328. events: {
  12329. cellNav: {
  12330. /**
  12331. * @ngdoc event
  12332. * @name navigate
  12333. * @eventOf ui.grid.cellNav.api:PublicApi
  12334. * @description raised when the active cell is changed
  12335. * <pre>
  12336. * gridApi.cellNav.on.navigate(scope,function(newRowcol, oldRowCol){})
  12337. * </pre>
  12338. * @param {object} newRowCol new position
  12339. * @param {object} oldRowCol old position
  12340. */
  12341. navigate: function (newRowCol, oldRowCol) {},
  12342. /**
  12343. * @ngdoc event
  12344. * @name viewPortKeyDown
  12345. * @eventOf ui.grid.cellNav.api:PublicApi
  12346. * @description is raised when the viewPort receives a keyDown event. Cells never get focus in uiGrid
  12347. * due to the difficulties of setting focus on a cell that is not visible in the viewport. Use this
  12348. * event whenever you need a keydown event on a cell
  12349. * <br/>
  12350. * @param {object} event keydown event
  12351. * @param {object} rowCol current rowCol position
  12352. */
  12353. viewPortKeyDown: function (event, rowCol) {},
  12354. /**
  12355. * @ngdoc event
  12356. * @name viewPortKeyPress
  12357. * @eventOf ui.grid.cellNav.api:PublicApi
  12358. * @description is raised when the viewPort receives a keyPress event. Cells never get focus in uiGrid
  12359. * due to the difficulties of setting focus on a cell that is not visible in the viewport. Use this
  12360. * event whenever you need a keypress event on a cell
  12361. * <br/>
  12362. * @param {object} event keypress event
  12363. * @param {object} rowCol current rowCol position
  12364. */
  12365. viewPortKeyPress: function (event, rowCol) {}
  12366. }
  12367. },
  12368. methods: {
  12369. cellNav: {
  12370. /**
  12371. * @ngdoc function
  12372. * @name scrollToFocus
  12373. * @methodOf ui.grid.cellNav.api:PublicApi
  12374. * @description brings the specified row and column into view, and sets focus
  12375. * to that cell
  12376. * @param {object} rowEntity gridOptions.data[] array instance to make visible and set focus
  12377. * @param {object} colDef to make visible and set focus
  12378. * @returns {promise} a promise that is resolved after any scrolling is finished
  12379. */
  12380. scrollToFocus: function (rowEntity, colDef) {
  12381. return service.scrollToFocus(grid, rowEntity, colDef);
  12382. },
  12383. /**
  12384. * @ngdoc function
  12385. * @name getFocusedCell
  12386. * @methodOf ui.grid.cellNav.api:PublicApi
  12387. * @description returns the current (or last if Grid does not have focus) focused row and column
  12388. * <br> value is null if no selection has occurred
  12389. */
  12390. getFocusedCell: function () {
  12391. return grid.cellNav.lastRowCol;
  12392. },
  12393. /**
  12394. * @ngdoc function
  12395. * @name getCurrentSelection
  12396. * @methodOf ui.grid.cellNav.api:PublicApi
  12397. * @description returns an array containing the current selection
  12398. * <br> array is empty if no selection has occurred
  12399. */
  12400. getCurrentSelection: function () {
  12401. return grid.cellNav.focusedCells;
  12402. },
  12403. /**
  12404. * @ngdoc function
  12405. * @name rowColSelectIndex
  12406. * @methodOf ui.grid.cellNav.api:PublicApi
  12407. * @description returns the index in the order in which the GridRowColumn was selected, returns -1 if the GridRowColumn
  12408. * isn't selected
  12409. * @param {object} rowCol the rowCol to evaluate
  12410. */
  12411. rowColSelectIndex: function (rowCol) {
  12412. //return gridUtil.arrayContainsObjectWithProperty(grid.cellNav.focusedCells, 'col.uid', rowCol.col.uid) &&
  12413. var index = -1;
  12414. for (var i = 0; i < grid.cellNav.focusedCells.length; i++) {
  12415. if (grid.cellNav.focusedCells[i].col.uid === rowCol.col.uid &&
  12416. grid.cellNav.focusedCells[i].row.uid === rowCol.row.uid) {
  12417. index = i;
  12418. break;
  12419. }
  12420. }
  12421. return index;
  12422. }
  12423. }
  12424. }
  12425. };
  12426. grid.api.registerEventsFromObject(publicApi.events);
  12427. grid.api.registerMethodsFromObject(publicApi.methods);
  12428. },
  12429. defaultGridOptions: function (gridOptions) {
  12430. /**
  12431. * @ngdoc object
  12432. * @name ui.grid.cellNav.api:GridOptions
  12433. *
  12434. * @description GridOptions for cellNav feature, these are available to be
  12435. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  12436. */
  12437. /**
  12438. * @ngdoc object
  12439. * @name modifierKeysToMultiSelectCells
  12440. * @propertyOf ui.grid.cellNav.api:GridOptions
  12441. * @description Enable multiple cell selection only when using the ctrlKey or shiftKey.
  12442. * <br/>Defaults to false
  12443. */
  12444. gridOptions.modifierKeysToMultiSelectCells = gridOptions.modifierKeysToMultiSelectCells === true;
  12445. },
  12446. /**
  12447. * @ngdoc service
  12448. * @name decorateRenderContainers
  12449. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12450. * @description decorates grid renderContainers with cellNav functions
  12451. */
  12452. decorateRenderContainers: function (grid) {
  12453. var rightContainer = grid.hasRightContainer() ? grid.renderContainers.right : null;
  12454. var leftContainer = grid.hasLeftContainer() ? grid.renderContainers.left : null;
  12455. if (leftContainer !== null) {
  12456. grid.renderContainers.left.cellNav = new UiGridCellNav(grid.renderContainers.body, leftContainer, rightContainer, grid.renderContainers.body);
  12457. }
  12458. if (rightContainer !== null) {
  12459. grid.renderContainers.right.cellNav = new UiGridCellNav(grid.renderContainers.body, rightContainer, grid.renderContainers.body, leftContainer);
  12460. }
  12461. grid.renderContainers.body.cellNav = new UiGridCellNav(grid.renderContainers.body, grid.renderContainers.body, leftContainer, rightContainer);
  12462. },
  12463. /**
  12464. * @ngdoc service
  12465. * @name getDirection
  12466. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12467. * @description determines which direction to for a given keyDown event
  12468. * @returns {uiGridCellNavConstants.direction} direction
  12469. */
  12470. getDirection: function (evt) {
  12471. if (evt.keyCode === uiGridConstants.keymap.LEFT ||
  12472. (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey)) {
  12473. return uiGridCellNavConstants.direction.LEFT;
  12474. }
  12475. if (evt.keyCode === uiGridConstants.keymap.RIGHT ||
  12476. evt.keyCode === uiGridConstants.keymap.TAB) {
  12477. return uiGridCellNavConstants.direction.RIGHT;
  12478. }
  12479. if (evt.keyCode === uiGridConstants.keymap.UP ||
  12480. (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) ) {
  12481. return uiGridCellNavConstants.direction.UP;
  12482. }
  12483. if (evt.keyCode === uiGridConstants.keymap.PG_UP){
  12484. return uiGridCellNavConstants.direction.PG_UP;
  12485. }
  12486. if (evt.keyCode === uiGridConstants.keymap.DOWN ||
  12487. evt.keyCode === uiGridConstants.keymap.ENTER && !(evt.ctrlKey || evt.altKey)) {
  12488. return uiGridCellNavConstants.direction.DOWN;
  12489. }
  12490. if (evt.keyCode === uiGridConstants.keymap.PG_DOWN){
  12491. return uiGridCellNavConstants.direction.PG_DOWN;
  12492. }
  12493. return null;
  12494. },
  12495. /**
  12496. * @ngdoc service
  12497. * @name cellNavColumnBuilder
  12498. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12499. * @description columnBuilder function that adds cell navigation properties to grid column
  12500. * @returns {promise} promise that will load any needed templates when resolved
  12501. */
  12502. cellNavColumnBuilder: function (colDef, col, gridOptions) {
  12503. var promises = [];
  12504. /**
  12505. * @ngdoc object
  12506. * @name ui.grid.cellNav.api:ColumnDef
  12507. *
  12508. * @description Column Definitions for cellNav feature, these are available to be
  12509. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  12510. */
  12511. /**
  12512. * @ngdoc object
  12513. * @name allowCellFocus
  12514. * @propertyOf ui.grid.cellNav.api:ColumnDef
  12515. * @description Enable focus on a cell within this column.
  12516. * <br/>Defaults to true
  12517. */
  12518. colDef.allowCellFocus = colDef.allowCellFocus === undefined ? true : colDef.allowCellFocus;
  12519. return $q.all(promises);
  12520. },
  12521. /**
  12522. * @ngdoc method
  12523. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12524. * @name scrollToFocus
  12525. * @description Scroll the grid such that the specified
  12526. * row and column is in view, and set focus to the cell in that row and column
  12527. * @param {Grid} grid the grid you'd like to act upon, usually available
  12528. * from gridApi.grid
  12529. * @param {object} rowEntity gridOptions.data[] array instance to make visible and set focus to
  12530. * @param {object} colDef to make visible and set focus to
  12531. * @returns {promise} a promise that is resolved after any scrolling is finished
  12532. */
  12533. scrollToFocus: function (grid, rowEntity, colDef) {
  12534. var gridRow = null, gridCol = null;
  12535. if (typeof(rowEntity) !== 'undefined' && rowEntity !== null) {
  12536. gridRow = grid.getRow(rowEntity);
  12537. }
  12538. if (typeof(colDef) !== 'undefined' && colDef !== null) {
  12539. gridCol = grid.getColumn(colDef.name ? colDef.name : colDef.field);
  12540. }
  12541. return grid.api.core.scrollToIfNecessary(gridRow, gridCol).then(function () {
  12542. var rowCol = { row: gridRow, col: gridCol };
  12543. // Broadcast the navigation
  12544. if (gridRow !== null && gridCol !== null) {
  12545. grid.cellNav.broadcastCellNav(rowCol);
  12546. }
  12547. });
  12548. },
  12549. /**
  12550. * @ngdoc method
  12551. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12552. * @name getLeftWidth
  12553. * @description Get the current drawn width of the columns in the
  12554. * grid up to the numbered column, and add an apportionment for the
  12555. * column that we're on. So if we are on column 0, we want to scroll
  12556. * 0% (i.e. exclude this column from calc). If we're on the last column
  12557. * we want to scroll to 100% (i.e. include this column in the calc). So
  12558. * we include (thisColIndex / totalNumberCols) % of this column width
  12559. * @param {Grid} grid the grid you'd like to act upon, usually available
  12560. * from gridApi.grid
  12561. * @param {gridCol} upToCol the column to total up to and including
  12562. */
  12563. getLeftWidth: function (grid, upToCol) {
  12564. var width = 0;
  12565. if (!upToCol) {
  12566. return width;
  12567. }
  12568. var lastIndex = grid.renderContainers.body.visibleColumnCache.indexOf( upToCol );
  12569. // total column widths up-to but not including the passed in column
  12570. grid.renderContainers.body.visibleColumnCache.forEach( function( col, index ) {
  12571. if ( index < lastIndex ){
  12572. width += col.drawnWidth;
  12573. }
  12574. });
  12575. // pro-rata the final column based on % of total columns.
  12576. var percentage = lastIndex === 0 ? 0 : (lastIndex + 1) / grid.renderContainers.body.visibleColumnCache.length;
  12577. width += upToCol.drawnWidth * percentage;
  12578. return width;
  12579. }
  12580. };
  12581. return service;
  12582. }]);
  12583. /**
  12584. * @ngdoc directive
  12585. * @name ui.grid.cellNav.directive:uiCellNav
  12586. * @element div
  12587. * @restrict EA
  12588. *
  12589. * @description Adds cell navigation features to the grid columns
  12590. *
  12591. * @example
  12592. <example module="app">
  12593. <file name="app.js">
  12594. var app = angular.module('app', ['ui.grid', 'ui.grid.cellNav']);
  12595. app.controller('MainCtrl', ['$scope', function ($scope) {
  12596. $scope.data = [
  12597. { name: 'Bob', title: 'CEO' },
  12598. { name: 'Frank', title: 'Lowly Developer' }
  12599. ];
  12600. $scope.columnDefs = [
  12601. {name: 'name'},
  12602. {name: 'title'}
  12603. ];
  12604. }]);
  12605. </file>
  12606. <file name="index.html">
  12607. <div ng-controller="MainCtrl">
  12608. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-cellnav></div>
  12609. </div>
  12610. </file>
  12611. </example>
  12612. */
  12613. module.directive('uiGridCellnav', ['gridUtil', 'uiGridCellNavService', 'uiGridCellNavConstants', 'uiGridConstants', 'GridRowColumn', '$timeout', '$compile',
  12614. function (gridUtil, uiGridCellNavService, uiGridCellNavConstants, uiGridConstants, GridRowColumn, $timeout, $compile) {
  12615. return {
  12616. replace: true,
  12617. priority: -150,
  12618. require: '^uiGrid',
  12619. scope: false,
  12620. controller: function () {},
  12621. compile: function () {
  12622. return {
  12623. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  12624. var _scope = $scope;
  12625. var grid = uiGridCtrl.grid;
  12626. uiGridCellNavService.initializeGrid(grid);
  12627. uiGridCtrl.cellNav = {};
  12628. //Ensure that the object has all of the methods we expect it to
  12629. uiGridCtrl.cellNav.makeRowCol = function (obj) {
  12630. if (!(obj instanceof GridRowColumn)) {
  12631. obj = new GridRowColumn(obj.row, obj.col);
  12632. }
  12633. return obj;
  12634. };
  12635. uiGridCtrl.cellNav.getActiveCell = function () {
  12636. var elms = $elm[0].getElementsByClassName('ui-grid-cell-focus');
  12637. if (elms.length > 0){
  12638. return elms[0];
  12639. }
  12640. return undefined;
  12641. };
  12642. uiGridCtrl.cellNav.broadcastCellNav = grid.cellNav.broadcastCellNav = function (newRowCol, modifierDown, originEvt) {
  12643. modifierDown = !(modifierDown === undefined || !modifierDown);
  12644. newRowCol = uiGridCtrl.cellNav.makeRowCol(newRowCol);
  12645. uiGridCtrl.cellNav.broadcastFocus(newRowCol, modifierDown, originEvt);
  12646. _scope.$broadcast(uiGridCellNavConstants.CELL_NAV_EVENT, newRowCol, modifierDown, originEvt);
  12647. };
  12648. uiGridCtrl.cellNav.clearFocus = grid.cellNav.clearFocus = function () {
  12649. grid.cellNav.focusedCells = [];
  12650. _scope.$broadcast(uiGridCellNavConstants.CELL_NAV_EVENT);
  12651. };
  12652. uiGridCtrl.cellNav.broadcastFocus = function (rowCol, modifierDown, originEvt) {
  12653. modifierDown = !(modifierDown === undefined || !modifierDown);
  12654. rowCol = uiGridCtrl.cellNav.makeRowCol(rowCol);
  12655. var row = rowCol.row,
  12656. col = rowCol.col;
  12657. var rowColSelectIndex = uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol);
  12658. if (grid.cellNav.lastRowCol === null || rowColSelectIndex === -1) {
  12659. var newRowCol = new GridRowColumn(row, col);
  12660. grid.api.cellNav.raise.navigate(newRowCol, grid.cellNav.lastRowCol);
  12661. grid.cellNav.lastRowCol = newRowCol;
  12662. if (uiGridCtrl.grid.options.modifierKeysToMultiSelectCells && modifierDown) {
  12663. grid.cellNav.focusedCells.push(rowCol);
  12664. } else {
  12665. grid.cellNav.focusedCells = [rowCol];
  12666. }
  12667. } else if (grid.options.modifierKeysToMultiSelectCells && modifierDown &&
  12668. rowColSelectIndex >= 0) {
  12669. grid.cellNav.focusedCells.splice(rowColSelectIndex, 1);
  12670. }
  12671. };
  12672. uiGridCtrl.cellNav.handleKeyDown = function (evt) {
  12673. var direction = uiGridCellNavService.getDirection(evt);
  12674. if (direction === null) {
  12675. return null;
  12676. }
  12677. var containerId = 'body';
  12678. if (evt.uiGridTargetRenderContainerId) {
  12679. containerId = evt.uiGridTargetRenderContainerId;
  12680. }
  12681. // Get the last-focused row+col combo
  12682. var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12683. if (lastRowCol) {
  12684. // Figure out which new row+combo we're navigating to
  12685. var rowCol = uiGridCtrl.grid.renderContainers[containerId].cellNav.getNextRowCol(direction, lastRowCol.row, lastRowCol.col);
  12686. var focusableCols = uiGridCtrl.grid.renderContainers[containerId].cellNav.getFocusableCols();
  12687. var rowColSelectIndex = uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol);
  12688. // Shift+tab on top-left cell should exit cellnav on render container
  12689. if (
  12690. // Navigating left
  12691. direction === uiGridCellNavConstants.direction.LEFT &&
  12692. // New col is last col (i.e. wrap around)
  12693. rowCol.col === focusableCols[focusableCols.length - 1] &&
  12694. // Staying on same row, which means we're at first row
  12695. rowCol.row === lastRowCol.row &&
  12696. evt.keyCode === uiGridConstants.keymap.TAB &&
  12697. evt.shiftKey
  12698. ) {
  12699. grid.cellNav.focusedCells.splice(rowColSelectIndex, 1);
  12700. uiGridCtrl.cellNav.clearFocus();
  12701. return true;
  12702. }
  12703. // Tab on bottom-right cell should exit cellnav on render container
  12704. else if (
  12705. direction === uiGridCellNavConstants.direction.RIGHT &&
  12706. // New col is first col (i.e. wrap around)
  12707. rowCol.col === focusableCols[0] &&
  12708. // Staying on same row, which means we're at first row
  12709. rowCol.row === lastRowCol.row &&
  12710. evt.keyCode === uiGridConstants.keymap.TAB &&
  12711. !evt.shiftKey
  12712. ) {
  12713. grid.cellNav.focusedCells.splice(rowColSelectIndex, 1);
  12714. uiGridCtrl.cellNav.clearFocus();
  12715. return true;
  12716. }
  12717. // Scroll to the new cell, if it's not completely visible within the render container's viewport
  12718. grid.scrollToIfNecessary(rowCol.row, rowCol.col).then(function () {
  12719. uiGridCtrl.cellNav.broadcastCellNav(rowCol);
  12720. });
  12721. evt.stopPropagation();
  12722. evt.preventDefault();
  12723. return false;
  12724. }
  12725. };
  12726. },
  12727. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  12728. var _scope = $scope;
  12729. var grid = uiGridCtrl.grid;
  12730. function addAriaLiveRegion(){
  12731. // Thanks to google docs for the inspiration behind how to do this
  12732. // XXX: Why is this entire mess nessasary?
  12733. // Because browsers take a lot of coercing to get them to read out live regions
  12734. //http://www.paciellogroup.com/blog/2012/06/html5-accessibility-chops-aria-rolealert-browser-support/
  12735. var ariaNotifierDomElt = '<div ' +
  12736. 'id="' + grid.id +'-aria-speakable" ' +
  12737. 'class="ui-grid-a11y-ariascreenreader-speakable ui-grid-offscreen" ' +
  12738. 'aria-live="assertive" ' +
  12739. 'role="region" ' +
  12740. 'aria-atomic="true" ' +
  12741. 'aria-hidden="false" ' +
  12742. 'aria-relevant="additions" ' +
  12743. '>' +
  12744. '&nbsp;' +
  12745. '</div>';
  12746. var ariaNotifier = $compile(ariaNotifierDomElt)($scope);
  12747. $elm.prepend(ariaNotifier);
  12748. $scope.$on(uiGridCellNavConstants.CELL_NAV_EVENT, function (evt, rowCol, modifierDown, originEvt) {
  12749. /*
  12750. * If the cell nav event was because of a focus event then we don't want to
  12751. * change the notifier text.
  12752. * Reasoning: Voice Over fires a focus events when moving arround the grid.
  12753. * If the screen reader is handing the grid nav properly then we don't need to
  12754. * use the alert to notify the user of the movement.
  12755. * In all other cases we do want a notification event.
  12756. */
  12757. if (originEvt && originEvt.type === 'focus'){return;}
  12758. function setNotifyText(text){
  12759. if (text === ariaNotifier.text()){return;}
  12760. ariaNotifier[0].style.clip = 'rect(0px,0px,0px,0px)';
  12761. /*
  12762. * This is how google docs handles clearing the div. Seems to work better than setting the text of the div to ''
  12763. */
  12764. ariaNotifier[0].innerHTML = "";
  12765. ariaNotifier[0].style.visibility = 'hidden';
  12766. ariaNotifier[0].style.visibility = 'visible';
  12767. if (text !== ''){
  12768. ariaNotifier[0].style.clip = 'auto';
  12769. /*
  12770. * The space after the text is something that google docs does.
  12771. */
  12772. ariaNotifier[0].appendChild(document.createTextNode(text + " "));
  12773. ariaNotifier[0].style.visibility = 'hidden';
  12774. ariaNotifier[0].style.visibility = 'visible';
  12775. }
  12776. }
  12777. var values = [];
  12778. var currentSelection = grid.api.cellNav.getCurrentSelection();
  12779. for (var i = 0; i < currentSelection.length; i++) {
  12780. values.push(currentSelection[i].getIntersectionValueFiltered());
  12781. }
  12782. var cellText = values.toString();
  12783. setNotifyText(cellText);
  12784. });
  12785. }
  12786. addAriaLiveRegion();
  12787. }
  12788. };
  12789. }
  12790. };
  12791. }]);
  12792. module.directive('uiGridRenderContainer', ['$timeout', '$document', 'gridUtil', 'uiGridConstants', 'uiGridCellNavService', '$compile','uiGridCellNavConstants',
  12793. function ($timeout, $document, gridUtil, uiGridConstants, uiGridCellNavService, $compile, uiGridCellNavConstants) {
  12794. return {
  12795. replace: true,
  12796. priority: -99999, //this needs to run very last
  12797. require: ['^uiGrid', 'uiGridRenderContainer', '?^uiGridCellnav'],
  12798. scope: false,
  12799. compile: function () {
  12800. return {
  12801. post: function ($scope, $elm, $attrs, controllers) {
  12802. var uiGridCtrl = controllers[0],
  12803. renderContainerCtrl = controllers[1],
  12804. uiGridCellnavCtrl = controllers[2];
  12805. // Skip attaching cell-nav specific logic if the directive is not attached above us
  12806. if (!uiGridCtrl.grid.api.cellNav) { return; }
  12807. var containerId = renderContainerCtrl.containerId;
  12808. var grid = uiGridCtrl.grid;
  12809. //run each time a render container is created
  12810. uiGridCellNavService.decorateRenderContainers(grid);
  12811. // focusser only created for body
  12812. if (containerId !== 'body') {
  12813. return;
  12814. }
  12815. if (uiGridCtrl.grid.options.modifierKeysToMultiSelectCells){
  12816. $elm.attr('aria-multiselectable', true);
  12817. } else {
  12818. $elm.attr('aria-multiselectable', false);
  12819. }
  12820. //add an element with no dimensions that can be used to set focus and capture keystrokes
  12821. var focuser = $compile('<div class="ui-grid-focuser" role="region" aria-live="assertive" aria-atomic="false" tabindex="0" aria-controls="' + grid.id +'-aria-speakable '+ grid.id + '-grid-container' +'" aria-owns="' + grid.id + '-grid-container' + '"></div>')($scope);
  12822. $elm.append(focuser);
  12823. focuser.on('focus', function (evt) {
  12824. evt.uiGridTargetRenderContainerId = containerId;
  12825. var rowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12826. if (rowCol === null) {
  12827. rowCol = uiGridCtrl.grid.renderContainers[containerId].cellNav.getNextRowCol(uiGridCellNavConstants.direction.DOWN, null, null);
  12828. if (rowCol.row && rowCol.col) {
  12829. uiGridCtrl.cellNav.broadcastCellNav(rowCol);
  12830. }
  12831. }
  12832. });
  12833. uiGridCellnavCtrl.setAriaActivedescendant = function(id){
  12834. $elm.attr('aria-activedescendant', id);
  12835. };
  12836. uiGridCellnavCtrl.removeAriaActivedescendant = function(id){
  12837. if ($elm.attr('aria-activedescendant') === id){
  12838. $elm.attr('aria-activedescendant', '');
  12839. }
  12840. };
  12841. uiGridCtrl.focus = function () {
  12842. gridUtil.focus.byElement(focuser[0]);
  12843. //allow for first time grid focus
  12844. };
  12845. var viewPortKeyDownWasRaisedForRowCol = null;
  12846. // Bind to keydown events in the render container
  12847. focuser.on('keydown', function (evt) {
  12848. evt.uiGridTargetRenderContainerId = containerId;
  12849. var rowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12850. var result = uiGridCtrl.cellNav.handleKeyDown(evt);
  12851. if (result === null) {
  12852. uiGridCtrl.grid.api.cellNav.raise.viewPortKeyDown(evt, rowCol);
  12853. viewPortKeyDownWasRaisedForRowCol = rowCol;
  12854. }
  12855. });
  12856. //Bind to keypress events in the render container
  12857. //keypress events are needed by edit function so the key press
  12858. //that initiated an edit is not lost
  12859. //must fire the event in a timeout so the editor can
  12860. //initialize and subscribe to the event on another event loop
  12861. focuser.on('keypress', function (evt) {
  12862. if (viewPortKeyDownWasRaisedForRowCol) {
  12863. $timeout(function () {
  12864. uiGridCtrl.grid.api.cellNav.raise.viewPortKeyPress(evt, viewPortKeyDownWasRaisedForRowCol);
  12865. },4);
  12866. viewPortKeyDownWasRaisedForRowCol = null;
  12867. }
  12868. });
  12869. $scope.$on('$destroy', function(){
  12870. //Remove all event handlers associated with this focuser.
  12871. focuser.off();
  12872. });
  12873. }
  12874. };
  12875. }
  12876. };
  12877. }]);
  12878. module.directive('uiGridViewport', ['$timeout', '$document', 'gridUtil', 'uiGridConstants', 'uiGridCellNavService', 'uiGridCellNavConstants','$log','$compile',
  12879. function ($timeout, $document, gridUtil, uiGridConstants, uiGridCellNavService, uiGridCellNavConstants, $log, $compile) {
  12880. return {
  12881. replace: true,
  12882. priority: -99999, //this needs to run very last
  12883. require: ['^uiGrid', '^uiGridRenderContainer', '?^uiGridCellnav'],
  12884. scope: false,
  12885. compile: function () {
  12886. return {
  12887. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  12888. },
  12889. post: function ($scope, $elm, $attrs, controllers) {
  12890. var uiGridCtrl = controllers[0],
  12891. renderContainerCtrl = controllers[1];
  12892. // Skip attaching cell-nav specific logic if the directive is not attached above us
  12893. if (!uiGridCtrl.grid.api.cellNav) { return; }
  12894. var containerId = renderContainerCtrl.containerId;
  12895. //no need to process for other containers
  12896. if (containerId !== 'body') {
  12897. return;
  12898. }
  12899. var grid = uiGridCtrl.grid;
  12900. grid.api.core.on.scrollBegin($scope, function (args) {
  12901. // Skip if there's no currently-focused cell
  12902. var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12903. if (lastRowCol === null) {
  12904. return;
  12905. }
  12906. //if not in my container, move on
  12907. //todo: worry about horiz scroll
  12908. if (!renderContainerCtrl.colContainer.containsColumn(lastRowCol.col)) {
  12909. return;
  12910. }
  12911. uiGridCtrl.cellNav.clearFocus();
  12912. });
  12913. grid.api.core.on.scrollEnd($scope, function (args) {
  12914. // Skip if there's no currently-focused cell
  12915. var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12916. if (lastRowCol === null) {
  12917. return;
  12918. }
  12919. //if not in my container, move on
  12920. //todo: worry about horiz scroll
  12921. if (!renderContainerCtrl.colContainer.containsColumn(lastRowCol.col)) {
  12922. return;
  12923. }
  12924. uiGridCtrl.cellNav.broadcastCellNav(lastRowCol);
  12925. });
  12926. grid.api.cellNav.on.navigate($scope, function () {
  12927. //focus again because it can be lost
  12928. uiGridCtrl.focus();
  12929. });
  12930. }
  12931. };
  12932. }
  12933. };
  12934. }]);
  12935. /**
  12936. * @ngdoc directive
  12937. * @name ui.grid.cellNav.directive:uiGridCell
  12938. * @element div
  12939. * @restrict A
  12940. * @description Stacks on top of ui.grid.uiGridCell to provide cell navigation
  12941. */
  12942. module.directive('uiGridCell', ['$timeout', '$document', 'uiGridCellNavService', 'gridUtil', 'uiGridCellNavConstants', 'uiGridConstants', 'GridRowColumn',
  12943. function ($timeout, $document, uiGridCellNavService, gridUtil, uiGridCellNavConstants, uiGridConstants, GridRowColumn) {
  12944. return {
  12945. priority: -150, // run after default uiGridCell directive and ui.grid.edit uiGridCell
  12946. restrict: 'A',
  12947. require: ['^uiGrid', '?^uiGridCellnav'],
  12948. scope: false,
  12949. link: function ($scope, $elm, $attrs, controllers) {
  12950. var uiGridCtrl = controllers[0],
  12951. uiGridCellnavCtrl = controllers[1];
  12952. // Skip attaching cell-nav specific logic if the directive is not attached above us
  12953. if (!uiGridCtrl.grid.api.cellNav) { return; }
  12954. if (!$scope.col.colDef.allowCellFocus) {
  12955. return;
  12956. }
  12957. //Convinience local variables
  12958. var grid = uiGridCtrl.grid;
  12959. $scope.focused = false;
  12960. // Make this cell focusable but only with javascript/a mouse click
  12961. $elm.attr('tabindex', -1);
  12962. // When a cell is clicked, broadcast a cellNav event saying that this row+col combo is now focused
  12963. $elm.find('div').on('click', function (evt) {
  12964. uiGridCtrl.cellNav.broadcastCellNav(new GridRowColumn($scope.row, $scope.col), evt.ctrlKey || evt.metaKey, evt);
  12965. evt.stopPropagation();
  12966. $scope.$apply();
  12967. });
  12968. /*
  12969. * XXX Hack for screen readers.
  12970. * This allows the grid to focus using only the screen reader cursor.
  12971. * Since the focus event doesn't include key press information we can't use it
  12972. * as our primary source of the event.
  12973. */
  12974. $elm.on('mousedown', preventMouseDown);
  12975. //turn on and off for edit events
  12976. if (uiGridCtrl.grid.api.edit) {
  12977. uiGridCtrl.grid.api.edit.on.beginCellEdit($scope, function () {
  12978. $elm.off('mousedown', preventMouseDown);
  12979. });
  12980. uiGridCtrl.grid.api.edit.on.afterCellEdit($scope, function () {
  12981. $elm.on('mousedown', preventMouseDown);
  12982. });
  12983. uiGridCtrl.grid.api.edit.on.cancelCellEdit($scope, function () {
  12984. $elm.on('mousedown', preventMouseDown);
  12985. });
  12986. }
  12987. function preventMouseDown(evt) {
  12988. //Prevents the foucus event from firing if the click event is already going to fire.
  12989. //If both events fire it will cause bouncing behavior.
  12990. evt.preventDefault();
  12991. }
  12992. //You can only focus on elements with a tabindex value
  12993. $elm.on('focus', function (evt) {
  12994. uiGridCtrl.cellNav.broadcastCellNav(new GridRowColumn($scope.row, $scope.col), false, evt);
  12995. evt.stopPropagation();
  12996. $scope.$apply();
  12997. });
  12998. // This event is fired for all cells. If the cell matches, then focus is set
  12999. $scope.$on(uiGridCellNavConstants.CELL_NAV_EVENT, function (evt, rowCol, modifierDown) {
  13000. var isFocused = grid.cellNav.focusedCells.some(function(focusedRowCol, index){
  13001. return (focusedRowCol.row === $scope.row && focusedRowCol.col === $scope.col);
  13002. });
  13003. if (isFocused){
  13004. setFocused();
  13005. } else {
  13006. clearFocus();
  13007. }
  13008. });
  13009. function setFocused() {
  13010. if (!$scope.focused){
  13011. var div = $elm.find('div');
  13012. // div.addClass('ui-grid-cell-focus');
  13013. $elm.attr('aria-selected', true);
  13014. uiGridCellnavCtrl.setAriaActivedescendant($elm.attr('id'));
  13015. $scope.focused = true;
  13016. }
  13017. }
  13018. function clearFocus() {
  13019. if ($scope.focused){
  13020. var div = $elm.find('div');
  13021. div.removeClass('ui-grid-cell-focus');
  13022. $elm.attr('aria-selected', false);
  13023. uiGridCellnavCtrl.removeAriaActivedescendant($elm.attr('id'));
  13024. $scope.focused = false;
  13025. }
  13026. }
  13027. $scope.$on('$destroy', function () {
  13028. //.off withouth paramaters removes all handlers
  13029. $elm.find('div').off();
  13030. $elm.off();
  13031. });
  13032. }
  13033. };
  13034. }]);
  13035. })();
  13036. (function () {
  13037. 'use strict';
  13038. /**
  13039. * @ngdoc overview
  13040. * @name ui.grid.edit
  13041. * @description
  13042. *
  13043. * # ui.grid.edit
  13044. *
  13045. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  13046. *
  13047. * This module provides cell editing capability to ui.grid. The goal was to emulate keying data in a spreadsheet via
  13048. * a keyboard.
  13049. * <br/>
  13050. * <br/>
  13051. * To really get the full spreadsheet-like data entry, the ui.grid.cellNav module should be used. This will allow the
  13052. * user to key data and then tab, arrow, or enter to the cells beside or below.
  13053. *
  13054. * <div doc-module-components="ui.grid.edit"></div>
  13055. */
  13056. var module = angular.module('ui.grid.edit', ['ui.grid']);
  13057. /**
  13058. * @ngdoc object
  13059. * @name ui.grid.edit.constant:uiGridEditConstants
  13060. *
  13061. * @description constants available in edit module
  13062. */
  13063. module.constant('uiGridEditConstants', {
  13064. EDITABLE_CELL_TEMPLATE: /EDITABLE_CELL_TEMPLATE/g,
  13065. //must be lowercase because template bulder converts to lower
  13066. EDITABLE_CELL_DIRECTIVE: /editable_cell_directive/g,
  13067. events: {
  13068. BEGIN_CELL_EDIT: 'uiGridEventBeginCellEdit',
  13069. END_CELL_EDIT: 'uiGridEventEndCellEdit',
  13070. CANCEL_CELL_EDIT: 'uiGridEventCancelCellEdit'
  13071. }
  13072. });
  13073. /**
  13074. * @ngdoc service
  13075. * @name ui.grid.edit.service:uiGridEditService
  13076. *
  13077. * @description Services for editing features
  13078. */
  13079. module.service('uiGridEditService', ['$q', 'uiGridConstants', 'gridUtil',
  13080. function ($q, uiGridConstants, gridUtil) {
  13081. var service = {
  13082. initializeGrid: function (grid) {
  13083. service.defaultGridOptions(grid.options);
  13084. grid.registerColumnBuilder(service.editColumnBuilder);
  13085. grid.edit = {};
  13086. /**
  13087. * @ngdoc object
  13088. * @name ui.grid.edit.api:PublicApi
  13089. *
  13090. * @description Public Api for edit feature
  13091. */
  13092. var publicApi = {
  13093. events: {
  13094. edit: {
  13095. /**
  13096. * @ngdoc event
  13097. * @name afterCellEdit
  13098. * @eventOf ui.grid.edit.api:PublicApi
  13099. * @description raised when cell editing is complete
  13100. * <pre>
  13101. * gridApi.edit.on.afterCellEdit(scope,function(rowEntity, colDef){})
  13102. * </pre>
  13103. * @param {object} rowEntity the options.data element that was edited
  13104. * @param {object} colDef the column that was edited
  13105. * @param {object} newValue new value
  13106. * @param {object} oldValue old value
  13107. */
  13108. afterCellEdit: function (rowEntity, colDef, newValue, oldValue) {
  13109. },
  13110. /**
  13111. * @ngdoc event
  13112. * @name beginCellEdit
  13113. * @eventOf ui.grid.edit.api:PublicApi
  13114. * @description raised when cell editing starts on a cell
  13115. * <pre>
  13116. * gridApi.edit.on.beginCellEdit(scope,function(rowEntity, colDef){})
  13117. * </pre>
  13118. * @param {object} rowEntity the options.data element that was edited
  13119. * @param {object} colDef the column that was edited
  13120. * @param {object} triggerEvent the event that triggered the edit. Useful to prevent losing keystrokes on some
  13121. * complex editors
  13122. */
  13123. beginCellEdit: function (rowEntity, colDef, triggerEvent) {
  13124. },
  13125. /**
  13126. * @ngdoc event
  13127. * @name cancelCellEdit
  13128. * @eventOf ui.grid.edit.api:PublicApi
  13129. * @description raised when cell editing is cancelled on a cell
  13130. * <pre>
  13131. * gridApi.edit.on.cancelCellEdit(scope,function(rowEntity, colDef){})
  13132. * </pre>
  13133. * @param {object} rowEntity the options.data element that was edited
  13134. * @param {object} colDef the column that was edited
  13135. */
  13136. cancelCellEdit: function (rowEntity, colDef) {
  13137. }
  13138. }
  13139. },
  13140. methods: {
  13141. edit: { }
  13142. }
  13143. };
  13144. grid.api.registerEventsFromObject(publicApi.events);
  13145. //grid.api.registerMethodsFromObject(publicApi.methods);
  13146. },
  13147. defaultGridOptions: function (gridOptions) {
  13148. /**
  13149. * @ngdoc object
  13150. * @name ui.grid.edit.api:GridOptions
  13151. *
  13152. * @description Options for configuring the edit feature, these are available to be
  13153. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  13154. */
  13155. /**
  13156. * @ngdoc object
  13157. * @name enableCellEdit
  13158. * @propertyOf ui.grid.edit.api:GridOptions
  13159. * @description If defined, sets the default value for the editable flag on each individual colDefs
  13160. * if their individual enableCellEdit configuration is not defined. Defaults to undefined.
  13161. */
  13162. /**
  13163. * @ngdoc object
  13164. * @name cellEditableCondition
  13165. * @propertyOf ui.grid.edit.api:GridOptions
  13166. * @description If specified, either a value or function to be used by all columns before editing.
  13167. * If falsy, then editing of cell is not allowed.
  13168. * @example
  13169. * <pre>
  13170. * function($scope){
  13171. * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed
  13172. * return true;
  13173. * }
  13174. * </pre>
  13175. */
  13176. gridOptions.cellEditableCondition = gridOptions.cellEditableCondition === undefined ? true : gridOptions.cellEditableCondition;
  13177. /**
  13178. * @ngdoc object
  13179. * @name editableCellTemplate
  13180. * @propertyOf ui.grid.edit.api:GridOptions
  13181. * @description If specified, cellTemplate to use as the editor for all columns.
  13182. * <br/> defaults to 'ui-grid/cellTextEditor'
  13183. */
  13184. /**
  13185. * @ngdoc object
  13186. * @name enableCellEditOnFocus
  13187. * @propertyOf ui.grid.edit.api:GridOptions
  13188. * @description If true, then editor is invoked as soon as cell receives focus. Default false.
  13189. * <br/>_requires cellNav feature and the edit feature to be enabled_
  13190. */
  13191. //enableCellEditOnFocus can only be used if cellnav module is used
  13192. gridOptions.enableCellEditOnFocus = gridOptions.enableCellEditOnFocus === undefined ? false : gridOptions.enableCellEditOnFocus;
  13193. },
  13194. /**
  13195. * @ngdoc service
  13196. * @name editColumnBuilder
  13197. * @methodOf ui.grid.edit.service:uiGridEditService
  13198. * @description columnBuilder function that adds edit properties to grid column
  13199. * @returns {promise} promise that will load any needed templates when resolved
  13200. */
  13201. editColumnBuilder: function (colDef, col, gridOptions) {
  13202. var promises = [];
  13203. /**
  13204. * @ngdoc object
  13205. * @name ui.grid.edit.api:ColumnDef
  13206. *
  13207. * @description Column Definition for edit feature, these are available to be
  13208. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  13209. */
  13210. /**
  13211. * @ngdoc object
  13212. * @name enableCellEdit
  13213. * @propertyOf ui.grid.edit.api:ColumnDef
  13214. * @description enable editing on column
  13215. */
  13216. colDef.enableCellEdit = colDef.enableCellEdit === undefined ? (gridOptions.enableCellEdit === undefined ?
  13217. (colDef.type !== 'object') : gridOptions.enableCellEdit) : colDef.enableCellEdit;
  13218. /**
  13219. * @ngdoc object
  13220. * @name cellEditableCondition
  13221. * @propertyOf ui.grid.edit.api:ColumnDef
  13222. * @description If specified, either a value or function evaluated before editing cell. If falsy, then editing of cell is not allowed.
  13223. * @example
  13224. * <pre>
  13225. * function($scope){
  13226. * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed
  13227. * return true;
  13228. * }
  13229. * </pre>
  13230. */
  13231. colDef.cellEditableCondition = colDef.cellEditableCondition === undefined ? gridOptions.cellEditableCondition : colDef.cellEditableCondition;
  13232. /**
  13233. * @ngdoc object
  13234. * @name editableCellTemplate
  13235. * @propertyOf ui.grid.edit.api:ColumnDef
  13236. * @description cell template to be used when editing this column. Can be Url or text template
  13237. * <br/>Defaults to gridOptions.editableCellTemplate
  13238. */
  13239. if (colDef.enableCellEdit) {
  13240. colDef.editableCellTemplate = colDef.editableCellTemplate || gridOptions.editableCellTemplate || 'ui-grid/cellEditor';
  13241. promises.push(gridUtil.getTemplate(colDef.editableCellTemplate)
  13242. .then(
  13243. function (template) {
  13244. col.editableCellTemplate = template;
  13245. },
  13246. function (res) {
  13247. // Todo handle response error here?
  13248. throw new Error("Couldn't fetch/use colDef.editableCellTemplate '" + colDef.editableCellTemplate + "'");
  13249. }));
  13250. }
  13251. /**
  13252. * @ngdoc object
  13253. * @name enableCellEditOnFocus
  13254. * @propertyOf ui.grid.edit.api:ColumnDef
  13255. * @requires ui.grid.cellNav
  13256. * @description If true, then editor is invoked as soon as cell receives focus. Default false.
  13257. * <br>_requires both the cellNav feature and the edit feature to be enabled_
  13258. */
  13259. //enableCellEditOnFocus can only be used if cellnav module is used
  13260. colDef.enableCellEditOnFocus = colDef.enableCellEditOnFocus === undefined ? gridOptions.enableCellEditOnFocus : colDef.enableCellEditOnFocus;
  13261. /**
  13262. * @ngdoc string
  13263. * @name editModelField
  13264. * @propertyOf ui.grid.edit.api:ColumnDef
  13265. * @description a bindable string value that is used when binding to edit controls instead of colDef.field
  13266. * <br/> example: You have a complex property on and object like state:{abbrev:'MS',name:'Mississippi'}. The
  13267. * grid should display state.name in the cell and sort/filter based on the state.name property but the editor
  13268. * requires the full state object.
  13269. * <br/>colDef.field = 'state.name'
  13270. * <br/>colDef.editModelField = 'state'
  13271. */
  13272. //colDef.editModelField
  13273. return $q.all(promises);
  13274. },
  13275. /**
  13276. * @ngdoc service
  13277. * @name isStartEditKey
  13278. * @methodOf ui.grid.edit.service:uiGridEditService
  13279. * @description Determines if a keypress should start editing. Decorate this service to override with your
  13280. * own key events. See service decorator in angular docs.
  13281. * @param {Event} evt keydown event
  13282. * @returns {boolean} true if an edit should start
  13283. */
  13284. isStartEditKey: function (evt) {
  13285. if (evt.metaKey ||
  13286. evt.keyCode === uiGridConstants.keymap.ESC ||
  13287. evt.keyCode === uiGridConstants.keymap.SHIFT ||
  13288. evt.keyCode === uiGridConstants.keymap.CTRL ||
  13289. evt.keyCode === uiGridConstants.keymap.ALT ||
  13290. evt.keyCode === uiGridConstants.keymap.WIN ||
  13291. evt.keyCode === uiGridConstants.keymap.CAPSLOCK ||
  13292. evt.keyCode === uiGridConstants.keymap.LEFT ||
  13293. (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey) ||
  13294. evt.keyCode === uiGridConstants.keymap.RIGHT ||
  13295. evt.keyCode === uiGridConstants.keymap.TAB ||
  13296. evt.keyCode === uiGridConstants.keymap.UP ||
  13297. (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) ||
  13298. evt.keyCode === uiGridConstants.keymap.DOWN ||
  13299. evt.keyCode === uiGridConstants.keymap.ENTER) {
  13300. return false;
  13301. }
  13302. return true;
  13303. }
  13304. };
  13305. return service;
  13306. }]);
  13307. /**
  13308. * @ngdoc directive
  13309. * @name ui.grid.edit.directive:uiGridEdit
  13310. * @element div
  13311. * @restrict A
  13312. *
  13313. * @description Adds editing features to the ui-grid directive.
  13314. *
  13315. * @example
  13316. <example module="app">
  13317. <file name="app.js">
  13318. var app = angular.module('app', ['ui.grid', 'ui.grid.edit']);
  13319. app.controller('MainCtrl', ['$scope', function ($scope) {
  13320. $scope.data = [
  13321. { name: 'Bob', title: 'CEO' },
  13322. { name: 'Frank', title: 'Lowly Developer' }
  13323. ];
  13324. $scope.columnDefs = [
  13325. {name: 'name', enableCellEdit: true},
  13326. {name: 'title', enableCellEdit: true}
  13327. ];
  13328. }]);
  13329. </file>
  13330. <file name="index.html">
  13331. <div ng-controller="MainCtrl">
  13332. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-edit></div>
  13333. </div>
  13334. </file>
  13335. </example>
  13336. */
  13337. module.directive('uiGridEdit', ['gridUtil', 'uiGridEditService', function (gridUtil, uiGridEditService) {
  13338. return {
  13339. replace: true,
  13340. priority: 0,
  13341. require: '^uiGrid',
  13342. scope: false,
  13343. compile: function () {
  13344. return {
  13345. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  13346. uiGridEditService.initializeGrid(uiGridCtrl.grid);
  13347. },
  13348. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  13349. }
  13350. };
  13351. }
  13352. };
  13353. }]);
  13354. /**
  13355. * @ngdoc directive
  13356. * @name ui.grid.edit.directive:uiGridRenderContainer
  13357. * @element div
  13358. * @restrict A
  13359. *
  13360. * @description Adds keydown listeners to renderContainer element so we can capture when to begin edits
  13361. *
  13362. */
  13363. module.directive('uiGridViewport', [ 'uiGridEditConstants',
  13364. function ( uiGridEditConstants) {
  13365. return {
  13366. replace: true,
  13367. priority: -99998, //run before cellNav
  13368. require: ['^uiGrid', '^uiGridRenderContainer'],
  13369. scope: false,
  13370. compile: function () {
  13371. return {
  13372. post: function ($scope, $elm, $attrs, controllers) {
  13373. var uiGridCtrl = controllers[0];
  13374. // Skip attaching if edit and cellNav is not enabled
  13375. if (!uiGridCtrl.grid.api.edit || !uiGridCtrl.grid.api.cellNav) { return; }
  13376. var containerId = controllers[1].containerId;
  13377. //no need to process for other containers
  13378. if (containerId !== 'body') {
  13379. return;
  13380. }
  13381. //refocus on the grid
  13382. $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () {
  13383. uiGridCtrl.focus();
  13384. });
  13385. $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () {
  13386. uiGridCtrl.focus();
  13387. });
  13388. }
  13389. };
  13390. }
  13391. };
  13392. }]);
  13393. /**
  13394. * @ngdoc directive
  13395. * @name ui.grid.edit.directive:uiGridCell
  13396. * @element div
  13397. * @restrict A
  13398. *
  13399. * @description Stacks on top of ui.grid.uiGridCell to provide in-line editing capabilities to the cell
  13400. * Editing Actions.
  13401. *
  13402. * Binds edit start events to the uiGridCell element. When the events fire, the gridCell element is appended
  13403. * with the columnDef.editableCellTemplate element ('cellEditor.html' by default).
  13404. *
  13405. * The editableCellTemplate should respond to uiGridEditConstants.events.BEGIN\_CELL\_EDIT angular event
  13406. * and do the initial steps needed to edit the cell (setfocus on input element, etc).
  13407. *
  13408. * When the editableCellTemplate recognizes that the editing is ended (blur event, Enter key, etc.)
  13409. * it should emit the uiGridEditConstants.events.END\_CELL\_EDIT event.
  13410. *
  13411. * If editableCellTemplate recognizes that the editing has been cancelled (esc key)
  13412. * it should emit the uiGridEditConstants.events.CANCEL\_CELL\_EDIT event. The original value
  13413. * will be set back on the model by the uiGridCell directive.
  13414. *
  13415. * Events that invoke editing:
  13416. * - dblclick
  13417. * - F2 keydown (when using cell selection)
  13418. *
  13419. * Events that end editing:
  13420. * - Dependent on the specific editableCellTemplate
  13421. * - Standards should be blur and enter keydown
  13422. *
  13423. * Events that cancel editing:
  13424. * - Dependent on the specific editableCellTemplate
  13425. * - Standards should be Esc keydown
  13426. *
  13427. * Grid Events that end editing:
  13428. * - uiGridConstants.events.GRID_SCROLL
  13429. *
  13430. */
  13431. /**
  13432. * @ngdoc object
  13433. * @name ui.grid.edit.api:GridRow
  13434. *
  13435. * @description GridRow options for edit feature, these are available to be
  13436. * set internally only, by other features
  13437. */
  13438. /**
  13439. * @ngdoc object
  13440. * @name enableCellEdit
  13441. * @propertyOf ui.grid.edit.api:GridRow
  13442. * @description enable editing on row, grouping for example might disable editing on group header rows
  13443. */
  13444. module.directive('uiGridCell',
  13445. ['$compile', '$injector', '$timeout', 'uiGridConstants', 'uiGridEditConstants', 'gridUtil', '$parse', 'uiGridEditService', '$rootScope',
  13446. function ($compile, $injector, $timeout, uiGridConstants, uiGridEditConstants, gridUtil, $parse, uiGridEditService, $rootScope) {
  13447. var touchstartTimeout = 500;
  13448. if ($injector.has('uiGridCellNavService')) {
  13449. var uiGridCellNavService = $injector.get('uiGridCellNavService');
  13450. }
  13451. return {
  13452. priority: -100, // run after default uiGridCell directive
  13453. restrict: 'A',
  13454. scope: false,
  13455. require: '?^uiGrid',
  13456. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  13457. var html;
  13458. var origCellValue;
  13459. var inEdit = false;
  13460. var cellModel;
  13461. var cancelTouchstartTimeout;
  13462. var editCellScope;
  13463. if (!$scope.col.colDef.enableCellEdit) {
  13464. return;
  13465. }
  13466. var cellNavNavigateDereg = function() {};
  13467. var viewPortKeyDownDereg = function() {};
  13468. var setEditable = function() {
  13469. if ($scope.col.colDef.enableCellEdit && $scope.row.enableCellEdit !== false) {
  13470. if (!$scope.beginEditEventsWired) { //prevent multiple attachments
  13471. registerBeginEditEvents();
  13472. }
  13473. } else {
  13474. if ($scope.beginEditEventsWired) {
  13475. cancelBeginEditEvents();
  13476. }
  13477. }
  13478. };
  13479. setEditable();
  13480. var rowWatchDereg = $scope.$watch('row', function (n, o) {
  13481. if (n !== o) {
  13482. setEditable();
  13483. }
  13484. });
  13485. $scope.$on( '$destroy', rowWatchDereg );
  13486. function registerBeginEditEvents() {
  13487. $elm.on('dblclick', beginEdit);
  13488. // Add touchstart handling. If the users starts a touch and it doesn't end after X milliseconds, then start the edit
  13489. $elm.on('touchstart', touchStart);
  13490. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13491. viewPortKeyDownDereg = uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function (evt, rowCol) {
  13492. if (rowCol === null) {
  13493. return;
  13494. }
  13495. if (rowCol.row === $scope.row && rowCol.col === $scope.col && !$scope.col.colDef.enableCellEditOnFocus) {
  13496. //important to do this before scrollToIfNecessary
  13497. beginEditKeyDown(evt);
  13498. }
  13499. });
  13500. cellNavNavigateDereg = uiGridCtrl.grid.api.cellNav.on.navigate($scope, function (newRowCol, oldRowCol) {
  13501. if ($scope.col.colDef.enableCellEditOnFocus) {
  13502. // Don't begin edit if the cell hasn't changed
  13503. if ((!oldRowCol || newRowCol.row !== oldRowCol.row || newRowCol.col !== oldRowCol.col) &&
  13504. newRowCol.row === $scope.row && newRowCol.col === $scope.col) {
  13505. $timeout(function () {
  13506. beginEdit();
  13507. });
  13508. }
  13509. }
  13510. });
  13511. }
  13512. $scope.beginEditEventsWired = true;
  13513. }
  13514. function touchStart(event) {
  13515. // jQuery masks events
  13516. if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) {
  13517. event = event.originalEvent;
  13518. }
  13519. // Bind touchend handler
  13520. $elm.on('touchend', touchEnd);
  13521. // Start a timeout
  13522. cancelTouchstartTimeout = $timeout(function() { }, touchstartTimeout);
  13523. // Timeout's done! Start the edit
  13524. cancelTouchstartTimeout.then(function () {
  13525. // Use setTimeout to start the edit because beginEdit expects to be outside of $digest
  13526. setTimeout(beginEdit, 0);
  13527. // Undbind the touchend handler, we don't need it anymore
  13528. $elm.off('touchend', touchEnd);
  13529. });
  13530. }
  13531. // Cancel any touchstart timeout
  13532. function touchEnd(event) {
  13533. $timeout.cancel(cancelTouchstartTimeout);
  13534. $elm.off('touchend', touchEnd);
  13535. }
  13536. function cancelBeginEditEvents() {
  13537. $elm.off('dblclick', beginEdit);
  13538. $elm.off('keydown', beginEditKeyDown);
  13539. $elm.off('touchstart', touchStart);
  13540. cellNavNavigateDereg();
  13541. viewPortKeyDownDereg();
  13542. $scope.beginEditEventsWired = false;
  13543. }
  13544. function beginEditKeyDown(evt) {
  13545. if (uiGridEditService.isStartEditKey(evt)) {
  13546. beginEdit(evt);
  13547. }
  13548. }
  13549. function shouldEdit(col, row) {
  13550. return !row.isSaving &&
  13551. ( angular.isFunction(col.colDef.cellEditableCondition) ?
  13552. col.colDef.cellEditableCondition($scope) :
  13553. col.colDef.cellEditableCondition );
  13554. }
  13555. function beginEdit(triggerEvent) {
  13556. //we need to scroll the cell into focus before invoking the editor
  13557. $scope.grid.api.core.scrollToIfNecessary($scope.row, $scope.col)
  13558. .then(function () {
  13559. beginEditAfterScroll(triggerEvent);
  13560. });
  13561. }
  13562. /**
  13563. * @ngdoc property
  13564. * @name editDropdownOptionsArray
  13565. * @propertyOf ui.grid.edit.api:ColumnDef
  13566. * @description an array of values in the format
  13567. * [ {id: xxx, value: xxx} ], which is populated
  13568. * into the edit dropdown
  13569. *
  13570. */
  13571. /**
  13572. * @ngdoc property
  13573. * @name editDropdownIdLabel
  13574. * @propertyOf ui.grid.edit.api:ColumnDef
  13575. * @description the label for the "id" field
  13576. * in the editDropdownOptionsArray. Defaults
  13577. * to 'id'
  13578. * @example
  13579. * <pre>
  13580. * $scope.gridOptions = {
  13581. * columnDefs: [
  13582. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  13583. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  13584. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  13585. * ],
  13586. * </pre>
  13587. *
  13588. */
  13589. /**
  13590. * @ngdoc property
  13591. * @name editDropdownRowEntityOptionsArrayPath
  13592. * @propertyOf ui.grid.edit.api:ColumnDef
  13593. * @description a path to a property on row.entity containing an
  13594. * array of values in the format
  13595. * [ {id: xxx, value: xxx} ], which will be used to populate
  13596. * the edit dropdown. This can be used when the dropdown values are dependent on
  13597. * the backing row entity.
  13598. * If this property is set then editDropdownOptionsArray will be ignored.
  13599. * @example
  13600. * <pre>
  13601. * $scope.gridOptions = {
  13602. * columnDefs: [
  13603. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  13604. * editDropdownRowEntityOptionsArrayPath: 'foo.bars[0].baz',
  13605. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  13606. * ],
  13607. * </pre>
  13608. *
  13609. */
  13610. /**
  13611. * @ngdoc property
  13612. * @name editDropdownValueLabel
  13613. * @propertyOf ui.grid.edit.api:ColumnDef
  13614. * @description the label for the "value" field
  13615. * in the editDropdownOptionsArray. Defaults
  13616. * to 'value'
  13617. * @example
  13618. * <pre>
  13619. * $scope.gridOptions = {
  13620. * columnDefs: [
  13621. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  13622. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  13623. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  13624. * ],
  13625. * </pre>
  13626. *
  13627. */
  13628. /**
  13629. * @ngdoc property
  13630. * @name editDropdownFilter
  13631. * @propertyOf ui.grid.edit.api:ColumnDef
  13632. * @description A filter that you would like to apply to the values in the options list
  13633. * of the dropdown. For example if you were using angular-translate you might set this
  13634. * to `'translate'`
  13635. * @example
  13636. * <pre>
  13637. * $scope.gridOptions = {
  13638. * columnDefs: [
  13639. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  13640. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  13641. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status', editDropdownFilter: 'translate' }
  13642. * ],
  13643. * </pre>
  13644. *
  13645. */
  13646. function beginEditAfterScroll(triggerEvent) {
  13647. // If we are already editing, then just skip this so we don't try editing twice...
  13648. if (inEdit) {
  13649. return;
  13650. }
  13651. if (!shouldEdit($scope.col, $scope.row)) {
  13652. return;
  13653. }
  13654. cellModel = $parse($scope.row.getQualifiedColField($scope.col));
  13655. //get original value from the cell
  13656. origCellValue = cellModel($scope);
  13657. html = $scope.col.editableCellTemplate;
  13658. if ($scope.col.colDef.editModelField) {
  13659. html = html.replace(uiGridConstants.MODEL_COL_FIELD, gridUtil.preEval('row.entity.' + $scope.col.colDef.editModelField));
  13660. }
  13661. else {
  13662. html = html.replace(uiGridConstants.MODEL_COL_FIELD, $scope.row.getQualifiedColField($scope.col));
  13663. }
  13664. html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
  13665. var optionFilter = $scope.col.colDef.editDropdownFilter ? '|' + $scope.col.colDef.editDropdownFilter : '';
  13666. html = html.replace(uiGridConstants.CUSTOM_FILTERS, optionFilter);
  13667. var inputType = 'text';
  13668. switch ($scope.col.colDef.type){
  13669. case 'boolean':
  13670. inputType = 'checkbox';
  13671. break;
  13672. case 'number':
  13673. inputType = 'number';
  13674. break;
  13675. case 'date':
  13676. inputType = 'date';
  13677. break;
  13678. }
  13679. html = html.replace('INPUT_TYPE', inputType);
  13680. var editDropdownRowEntityOptionsArrayPath = $scope.col.colDef.editDropdownRowEntityOptionsArrayPath;
  13681. if (editDropdownRowEntityOptionsArrayPath) {
  13682. $scope.editDropdownOptionsArray = resolveObjectFromPath($scope.row.entity, editDropdownRowEntityOptionsArrayPath);
  13683. }
  13684. else {
  13685. $scope.editDropdownOptionsArray = $scope.col.colDef.editDropdownOptionsArray;
  13686. }
  13687. $scope.editDropdownIdLabel = $scope.col.colDef.editDropdownIdLabel ? $scope.col.colDef.editDropdownIdLabel : 'id';
  13688. $scope.editDropdownValueLabel = $scope.col.colDef.editDropdownValueLabel ? $scope.col.colDef.editDropdownValueLabel : 'value';
  13689. var cellElement;
  13690. var createEditor = function(){
  13691. inEdit = true;
  13692. cancelBeginEditEvents();
  13693. var cellElement = angular.element(html);
  13694. $elm.append(cellElement);
  13695. editCellScope = $scope.$new();
  13696. $compile(cellElement)(editCellScope);
  13697. var gridCellContentsEl = angular.element($elm.children()[0]);
  13698. gridCellContentsEl.addClass('ui-grid-cell-contents-hidden');
  13699. };
  13700. if (!$rootScope.$$phase) {
  13701. $scope.$apply(createEditor);
  13702. } else {
  13703. createEditor();
  13704. }
  13705. //stop editing when grid is scrolled
  13706. var deregOnGridScroll = $scope.col.grid.api.core.on.scrollBegin($scope, function () {
  13707. endEdit();
  13708. $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue);
  13709. deregOnGridScroll();
  13710. deregOnEndCellEdit();
  13711. deregOnCancelCellEdit();
  13712. });
  13713. //end editing
  13714. var deregOnEndCellEdit = $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () {
  13715. endEdit();
  13716. $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue);
  13717. deregOnEndCellEdit();
  13718. deregOnGridScroll();
  13719. deregOnCancelCellEdit();
  13720. });
  13721. //cancel editing
  13722. var deregOnCancelCellEdit = $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () {
  13723. cancelEdit();
  13724. deregOnCancelCellEdit();
  13725. deregOnGridScroll();
  13726. deregOnEndCellEdit();
  13727. });
  13728. $scope.$broadcast(uiGridEditConstants.events.BEGIN_CELL_EDIT, triggerEvent);
  13729. $timeout(function () {
  13730. //execute in a timeout to give any complex editor templates a cycle to completely render
  13731. $scope.grid.api.edit.raise.beginCellEdit($scope.row.entity, $scope.col.colDef, triggerEvent);
  13732. });
  13733. }
  13734. function endEdit() {
  13735. $scope.grid.disableScrolling = false;
  13736. if (!inEdit) {
  13737. return;
  13738. }
  13739. //sometimes the events can't keep up with the keyboard and grid focus is lost, so always focus
  13740. //back to grid here. The focus call needs to be before the $destroy and removal of the control,
  13741. //otherwise ng-model-options of UpdateOn: 'blur' will not work.
  13742. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13743. uiGridCtrl.focus();
  13744. }
  13745. var gridCellContentsEl = angular.element($elm.children()[0]);
  13746. //remove edit element
  13747. editCellScope.$destroy();
  13748. angular.element($elm.children()[1]).remove();
  13749. gridCellContentsEl.removeClass('ui-grid-cell-contents-hidden');
  13750. inEdit = false;
  13751. registerBeginEditEvents();
  13752. $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.EDIT );
  13753. }
  13754. function cancelEdit() {
  13755. $scope.grid.disableScrolling = false;
  13756. if (!inEdit) {
  13757. return;
  13758. }
  13759. cellModel.assign($scope, origCellValue);
  13760. $scope.$apply();
  13761. $scope.grid.api.edit.raise.cancelCellEdit($scope.row.entity, $scope.col.colDef);
  13762. endEdit();
  13763. }
  13764. // resolves a string path against the given object
  13765. // shamelessly borrowed from
  13766. // http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key
  13767. function resolveObjectFromPath(object, path) {
  13768. path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
  13769. path = path.replace(/^\./, ''); // strip a leading dot
  13770. var a = path.split('.');
  13771. while (a.length) {
  13772. var n = a.shift();
  13773. if (n in object) {
  13774. object = object[n];
  13775. } else {
  13776. return;
  13777. }
  13778. }
  13779. return object;
  13780. }
  13781. }
  13782. };
  13783. }]);
  13784. /**
  13785. * @ngdoc directive
  13786. * @name ui.grid.edit.directive:uiGridEditor
  13787. * @element div
  13788. * @restrict A
  13789. *
  13790. * @description input editor directive for editable fields.
  13791. * Provides EndEdit and CancelEdit events
  13792. *
  13793. * Events that end editing:
  13794. * blur and enter keydown
  13795. *
  13796. * Events that cancel editing:
  13797. * - Esc keydown
  13798. *
  13799. */
  13800. module.directive('uiGridEditor',
  13801. ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', 'uiGridEditService',
  13802. function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout, uiGridEditService) {
  13803. return {
  13804. scope: true,
  13805. require: ['?^uiGrid', '?^uiGridRenderContainer', 'ngModel'],
  13806. compile: function () {
  13807. return {
  13808. pre: function ($scope, $elm, $attrs) {
  13809. },
  13810. post: function ($scope, $elm, $attrs, controllers) {
  13811. var uiGridCtrl, renderContainerCtrl, ngModel;
  13812. if (controllers[0]) { uiGridCtrl = controllers[0]; }
  13813. if (controllers[1]) { renderContainerCtrl = controllers[1]; }
  13814. if (controllers[2]) { ngModel = controllers[2]; }
  13815. //set focus at start of edit
  13816. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function (evt,triggerEvent) {
  13817. $timeout(function () {
  13818. $elm[0].focus();
  13819. //only select text if it is not being replaced below in the cellNav viewPortKeyPress
  13820. if ($scope.col.colDef.enableCellEditOnFocus || !(uiGridCtrl && uiGridCtrl.grid.api.cellNav)) {
  13821. $elm[0].select();
  13822. }
  13823. else {
  13824. //some browsers (Chrome) stupidly, imo, support the w3 standard that number, email, ...
  13825. //fields should not allow setSelectionRange. We ignore the error for those browsers
  13826. //https://www.w3.org/Bugs/Public/show_bug.cgi?id=24796
  13827. try {
  13828. $elm[0].setSelectionRange($elm[0].value.length, $elm[0].value.length);
  13829. }
  13830. catch (ex) {
  13831. //ignore
  13832. }
  13833. }
  13834. });
  13835. //set the keystroke that started the edit event
  13836. //we must do this because the BeginEdit is done in a different event loop than the intitial
  13837. //keydown event
  13838. //fire this event for the keypress that is received
  13839. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13840. var viewPortKeyDownUnregister = uiGridCtrl.grid.api.cellNav.on.viewPortKeyPress($scope, function (evt, rowCol) {
  13841. if (uiGridEditService.isStartEditKey(evt)) {
  13842. ngModel.$setViewValue(String.fromCharCode(evt.keyCode), evt);
  13843. ngModel.$render();
  13844. }
  13845. viewPortKeyDownUnregister();
  13846. });
  13847. }
  13848. $elm.on('blur', function (evt) {
  13849. $scope.stopEdit(evt);
  13850. });
  13851. });
  13852. $scope.deepEdit = false;
  13853. $scope.stopEdit = function (evt) {
  13854. if ($scope.inputForm && !$scope.inputForm.$valid) {
  13855. evt.stopPropagation();
  13856. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  13857. }
  13858. else {
  13859. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  13860. }
  13861. $scope.deepEdit = false;
  13862. };
  13863. $elm.on('click', function (evt) {
  13864. if ($elm[0].type !== 'checkbox') {
  13865. $scope.deepEdit = true;
  13866. $timeout(function () {
  13867. $scope.grid.disableScrolling = true;
  13868. });
  13869. }
  13870. });
  13871. $elm.on('keydown', function (evt) {
  13872. switch (evt.keyCode) {
  13873. case uiGridConstants.keymap.ESC:
  13874. evt.stopPropagation();
  13875. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  13876. break;
  13877. }
  13878. if ($scope.deepEdit &&
  13879. (evt.keyCode === uiGridConstants.keymap.LEFT ||
  13880. evt.keyCode === uiGridConstants.keymap.RIGHT ||
  13881. evt.keyCode === uiGridConstants.keymap.UP ||
  13882. evt.keyCode === uiGridConstants.keymap.DOWN)) {
  13883. evt.stopPropagation();
  13884. }
  13885. // Pass the keydown event off to the cellNav service, if it exists
  13886. else if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13887. evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
  13888. if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
  13889. $scope.stopEdit(evt);
  13890. }
  13891. }
  13892. else {
  13893. //handle enter and tab for editing not using cellNav
  13894. switch (evt.keyCode) {
  13895. case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
  13896. case uiGridConstants.keymap.TAB:
  13897. evt.stopPropagation();
  13898. evt.preventDefault();
  13899. $scope.stopEdit(evt);
  13900. break;
  13901. }
  13902. }
  13903. return true;
  13904. });
  13905. }
  13906. };
  13907. }
  13908. };
  13909. }]);
  13910. /**
  13911. * @ngdoc directive
  13912. * @name ui.grid.edit.directive:input
  13913. * @element input
  13914. * @restrict E
  13915. *
  13916. * @description directive to provide binding between input[date] value and ng-model for angular 1.2
  13917. * It is similar to input[date] directive of angular 1.3
  13918. *
  13919. * Supported date format for input is 'yyyy-MM-dd'
  13920. * The directive will set the $valid property of input element and the enclosing form to false if
  13921. * model is invalid date or value of input is entered wrong.
  13922. *
  13923. */
  13924. module.directive('uiGridEditor', ['$filter', function ($filter) {
  13925. function parseDateString(dateString) {
  13926. if (typeof(dateString) === 'undefined' || dateString === '') {
  13927. return null;
  13928. }
  13929. var parts = dateString.split('-');
  13930. if (parts.length !== 3) {
  13931. return null;
  13932. }
  13933. var year = parseInt(parts[0], 10);
  13934. var month = parseInt(parts[1], 10);
  13935. var day = parseInt(parts[2], 10);
  13936. if (month < 1 || year < 1 || day < 1) {
  13937. return null;
  13938. }
  13939. return new Date(year, (month - 1), day);
  13940. }
  13941. return {
  13942. priority: -100, // run after default uiGridEditor directive
  13943. require: '?ngModel',
  13944. link: function (scope, element, attrs, ngModel) {
  13945. if (angular.version.minor === 2 && attrs.type && attrs.type === 'date' && ngModel) {
  13946. ngModel.$formatters.push(function (modelValue) {
  13947. ngModel.$setValidity(null,(!modelValue || !isNaN(modelValue.getTime())));
  13948. return $filter('date')(modelValue, 'yyyy-MM-dd');
  13949. });
  13950. ngModel.$parsers.push(function (viewValue) {
  13951. if (viewValue && viewValue.length > 0) {
  13952. var dateValue = parseDateString(viewValue);
  13953. ngModel.$setValidity(null, (dateValue && !isNaN(dateValue.getTime())));
  13954. return dateValue;
  13955. }
  13956. else {
  13957. ngModel.$setValidity(null, true);
  13958. return null;
  13959. }
  13960. });
  13961. }
  13962. }
  13963. };
  13964. }]);
  13965. /**
  13966. * @ngdoc directive
  13967. * @name ui.grid.edit.directive:uiGridEditDropdown
  13968. * @element div
  13969. * @restrict A
  13970. *
  13971. * @description dropdown editor for editable fields.
  13972. * Provides EndEdit and CancelEdit events
  13973. *
  13974. * Events that end editing:
  13975. * blur and enter keydown, and any left/right nav
  13976. *
  13977. * Events that cancel editing:
  13978. * - Esc keydown
  13979. *
  13980. */
  13981. module.directive('uiGridEditDropdown',
  13982. ['uiGridConstants', 'uiGridEditConstants',
  13983. function (uiGridConstants, uiGridEditConstants) {
  13984. return {
  13985. require: ['?^uiGrid', '?^uiGridRenderContainer'],
  13986. scope: true,
  13987. compile: function () {
  13988. return {
  13989. pre: function ($scope, $elm, $attrs) {
  13990. },
  13991. post: function ($scope, $elm, $attrs, controllers) {
  13992. var uiGridCtrl = controllers[0];
  13993. var renderContainerCtrl = controllers[1];
  13994. //set focus at start of edit
  13995. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
  13996. $elm[0].focus();
  13997. $elm[0].style.width = ($elm[0].parentElement.offsetWidth - 1) + 'px';
  13998. $elm.on('blur', function (evt) {
  13999. $scope.stopEdit(evt);
  14000. });
  14001. });
  14002. $scope.stopEdit = function (evt) {
  14003. // no need to validate a dropdown - invalid values shouldn't be
  14004. // available in the list
  14005. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  14006. };
  14007. $elm.on('keydown', function (evt) {
  14008. switch (evt.keyCode) {
  14009. case uiGridConstants.keymap.ESC:
  14010. evt.stopPropagation();
  14011. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  14012. break;
  14013. }
  14014. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  14015. evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
  14016. if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
  14017. $scope.stopEdit(evt);
  14018. }
  14019. }
  14020. else {
  14021. //handle enter and tab for editing not using cellNav
  14022. switch (evt.keyCode) {
  14023. case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
  14024. case uiGridConstants.keymap.TAB:
  14025. evt.stopPropagation();
  14026. evt.preventDefault();
  14027. $scope.stopEdit(evt);
  14028. break;
  14029. }
  14030. }
  14031. return true;
  14032. });
  14033. }
  14034. };
  14035. }
  14036. };
  14037. }]);
  14038. /**
  14039. * @ngdoc directive
  14040. * @name ui.grid.edit.directive:uiGridEditFileChooser
  14041. * @element div
  14042. * @restrict A
  14043. *
  14044. * @description input editor directive for editable fields.
  14045. * Provides EndEdit and CancelEdit events
  14046. *
  14047. * Events that end editing:
  14048. * blur and enter keydown
  14049. *
  14050. * Events that cancel editing:
  14051. * - Esc keydown
  14052. *
  14053. */
  14054. module.directive('uiGridEditFileChooser',
  14055. ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout',
  14056. function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout) {
  14057. return {
  14058. scope: true,
  14059. require: ['?^uiGrid', '?^uiGridRenderContainer'],
  14060. compile: function () {
  14061. return {
  14062. pre: function ($scope, $elm, $attrs) {
  14063. },
  14064. post: function ($scope, $elm, $attrs, controllers) {
  14065. var uiGridCtrl, renderContainerCtrl;
  14066. if (controllers[0]) { uiGridCtrl = controllers[0]; }
  14067. if (controllers[1]) { renderContainerCtrl = controllers[1]; }
  14068. var grid = uiGridCtrl.grid;
  14069. var handleFileSelect = function( event ){
  14070. var target = event.srcElement || event.target;
  14071. if (target && target.files && target.files.length > 0) {
  14072. /**
  14073. * @ngdoc property
  14074. * @name editFileChooserCallback
  14075. * @propertyOf ui.grid.edit.api:ColumnDef
  14076. * @description A function that should be called when any files have been chosen
  14077. * by the user. You should use this to process the files appropriately for your
  14078. * application.
  14079. *
  14080. * It passes the gridCol, the gridRow (from which you can get gridRow.entity),
  14081. * and the files. The files are in the format as returned from the file chooser,
  14082. * an array of files, with each having useful information such as:
  14083. * - `files[0].lastModifiedDate`
  14084. * - `files[0].name`
  14085. * - `files[0].size` (appears to be in bytes)
  14086. * - `files[0].type` (MIME type by the looks)
  14087. *
  14088. * Typically you would do something with these files - most commonly you would
  14089. * use the filename or read the file itself in. The example function does both.
  14090. *
  14091. * @example
  14092. * <pre>
  14093. * editFileChooserCallBack: function(gridRow, gridCol, files ){
  14094. * // ignore all but the first file, it can only choose one anyway
  14095. * // set the filename into this column
  14096. * gridRow.entity.filename = file[0].name;
  14097. *
  14098. * // read the file and set it into a hidden column, which we may do stuff with later
  14099. * var setFile = function(fileContent){
  14100. * gridRow.entity.file = fileContent.currentTarget.result;
  14101. * };
  14102. * var reader = new FileReader();
  14103. * reader.onload = setFile;
  14104. * reader.readAsText( files[0] );
  14105. * }
  14106. * </pre>
  14107. */
  14108. if ( typeof($scope.col.colDef.editFileChooserCallback) === 'function' ) {
  14109. $scope.col.colDef.editFileChooserCallback($scope.row, $scope.col, target.files);
  14110. } else {
  14111. gridUtil.logError('You need to set colDef.editFileChooserCallback to use the file chooser');
  14112. }
  14113. target.form.reset();
  14114. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  14115. } else {
  14116. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  14117. }
  14118. };
  14119. $elm[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google
  14120. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
  14121. $elm[0].focus();
  14122. $elm[0].select();
  14123. $elm.on('blur', function (evt) {
  14124. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  14125. });
  14126. });
  14127. }
  14128. };
  14129. }
  14130. };
  14131. }]);
  14132. })();
  14133. (function () {
  14134. 'use strict';
  14135. /**
  14136. * @ngdoc overview
  14137. * @name ui.grid.expandable
  14138. * @description
  14139. *
  14140. * # ui.grid.expandable
  14141. *
  14142. * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div>
  14143. *
  14144. * This module provides the ability to create subgrids with the ability to expand a row
  14145. * to show the subgrid.
  14146. *
  14147. * <div doc-module-components="ui.grid.expandable"></div>
  14148. */
  14149. var module = angular.module('ui.grid.expandable', ['ui.grid']);
  14150. /**
  14151. * @ngdoc service
  14152. * @name ui.grid.expandable.service:uiGridExpandableService
  14153. *
  14154. * @description Services for the expandable grid
  14155. */
  14156. module.service('uiGridExpandableService', ['gridUtil', '$compile', function (gridUtil, $compile) {
  14157. var service = {
  14158. initializeGrid: function (grid) {
  14159. grid.expandable = {};
  14160. grid.expandable.expandedAll = false;
  14161. /**
  14162. * @ngdoc object
  14163. * @name enableExpandable
  14164. * @propertyOf ui.grid.expandable.api:GridOptions
  14165. * @description Whether or not to use expandable feature, allows you to turn off expandable on specific grids
  14166. * within your application, or in specific modes on _this_ grid. Defaults to true.
  14167. * @example
  14168. * <pre>
  14169. * $scope.gridOptions = {
  14170. * enableExpandable: false
  14171. * }
  14172. * </pre>
  14173. */
  14174. grid.options.enableExpandable = grid.options.enableExpandable !== false;
  14175. /**
  14176. * @ngdoc object
  14177. * @name expandableRowHeight
  14178. * @propertyOf ui.grid.expandable.api:GridOptions
  14179. * @description Height in pixels of the expanded subgrid. Defaults to
  14180. * 150
  14181. * @example
  14182. * <pre>
  14183. * $scope.gridOptions = {
  14184. * expandableRowHeight: 150
  14185. * }
  14186. * </pre>
  14187. */
  14188. grid.options.expandableRowHeight = grid.options.expandableRowHeight || 150;
  14189. /**
  14190. * @ngdoc object
  14191. * @name
  14192. * @propertyOf ui.grid.expandable.api:GridOptions
  14193. * @description Width in pixels of the expandable column. Defaults to 40
  14194. * @example
  14195. * <pre>
  14196. * $scope.gridOptions = {
  14197. * expandableRowHeaderWidth: 40
  14198. * }
  14199. * </pre>
  14200. */
  14201. grid.options.expandableRowHeaderWidth = grid.options.expandableRowHeaderWidth || 40;
  14202. /**
  14203. * @ngdoc object
  14204. * @name expandableRowTemplate
  14205. * @propertyOf ui.grid.expandable.api:GridOptions
  14206. * @description Mandatory. The template for your expanded row
  14207. * @example
  14208. * <pre>
  14209. * $scope.gridOptions = {
  14210. * expandableRowTemplate: 'expandableRowTemplate.html'
  14211. * }
  14212. * </pre>
  14213. */
  14214. if ( grid.options.enableExpandable && !grid.options.expandableRowTemplate ){
  14215. gridUtil.logError( 'You have not set the expandableRowTemplate, disabling expandable module' );
  14216. grid.options.enableExpandable = false;
  14217. }
  14218. /**
  14219. * @ngdoc object
  14220. * @name ui.grid.expandable.api:PublicApi
  14221. *
  14222. * @description Public Api for expandable feature
  14223. */
  14224. /**
  14225. * @ngdoc object
  14226. * @name ui.grid.expandable.api:GridOptions
  14227. *
  14228. * @description Options for configuring the expandable feature, these are available to be
  14229. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  14230. */
  14231. var publicApi = {
  14232. events: {
  14233. expandable: {
  14234. /**
  14235. * @ngdoc event
  14236. * @name rowExpandedStateChanged
  14237. * @eventOf ui.grid.expandable.api:PublicApi
  14238. * @description raised when cell editing is complete
  14239. * <pre>
  14240. * gridApi.expandable.on.rowExpandedStateChanged(scope,function(row){})
  14241. * </pre>
  14242. * @param {GridRow} row the row that was expanded
  14243. */
  14244. rowExpandedStateChanged: function (scope, row) {
  14245. }
  14246. }
  14247. },
  14248. methods: {
  14249. expandable: {
  14250. /**
  14251. * @ngdoc method
  14252. * @name toggleRowExpansion
  14253. * @methodOf ui.grid.expandable.api:PublicApi
  14254. * @description Toggle a specific row
  14255. * <pre>
  14256. * gridApi.expandable.toggleRowExpansion(rowEntity);
  14257. * </pre>
  14258. * @param {object} rowEntity the data entity for the row you want to expand
  14259. */
  14260. toggleRowExpansion: function (rowEntity) {
  14261. var row = grid.getRow(rowEntity);
  14262. if (row !== null) {
  14263. service.toggleRowExpansion(grid, row);
  14264. }
  14265. },
  14266. /**
  14267. * @ngdoc method
  14268. * @name expandAllRows
  14269. * @methodOf ui.grid.expandable.api:PublicApi
  14270. * @description Expand all subgrids.
  14271. * <pre>
  14272. * gridApi.expandable.expandAllRows();
  14273. * </pre>
  14274. */
  14275. expandAllRows: function() {
  14276. service.expandAllRows(grid);
  14277. },
  14278. /**
  14279. * @ngdoc method
  14280. * @name collapseAllRows
  14281. * @methodOf ui.grid.expandable.api:PublicApi
  14282. * @description Collapse all subgrids.
  14283. * <pre>
  14284. * gridApi.expandable.collapseAllRows();
  14285. * </pre>
  14286. */
  14287. collapseAllRows: function() {
  14288. service.collapseAllRows(grid);
  14289. },
  14290. /**
  14291. * @ngdoc method
  14292. * @name toggleAllRows
  14293. * @methodOf ui.grid.expandable.api:PublicApi
  14294. * @description Toggle all subgrids.
  14295. * <pre>
  14296. * gridApi.expandable.toggleAllRows();
  14297. * </pre>
  14298. */
  14299. toggleAllRows: function() {
  14300. service.toggleAllRows(grid);
  14301. }
  14302. }
  14303. }
  14304. };
  14305. grid.api.registerEventsFromObject(publicApi.events);
  14306. grid.api.registerMethodsFromObject(publicApi.methods);
  14307. },
  14308. toggleRowExpansion: function (grid, row) {
  14309. row.isExpanded = !row.isExpanded;
  14310. if (row.isExpanded) {
  14311. row.height = row.grid.options.rowHeight + grid.options.expandableRowHeight;
  14312. }
  14313. else {
  14314. row.height = row.grid.options.rowHeight;
  14315. grid.expandable.expandedAll = false;
  14316. }
  14317. grid.api.expandable.raise.rowExpandedStateChanged(row);
  14318. },
  14319. expandAllRows: function(grid, $scope) {
  14320. grid.renderContainers.body.visibleRowCache.forEach( function(row) {
  14321. if (!row.isExpanded) {
  14322. service.toggleRowExpansion(grid, row);
  14323. }
  14324. });
  14325. grid.expandable.expandedAll = true;
  14326. grid.queueGridRefresh();
  14327. },
  14328. collapseAllRows: function(grid) {
  14329. grid.renderContainers.body.visibleRowCache.forEach( function(row) {
  14330. if (row.isExpanded) {
  14331. service.toggleRowExpansion(grid, row);
  14332. }
  14333. });
  14334. grid.expandable.expandedAll = false;
  14335. grid.queueGridRefresh();
  14336. },
  14337. toggleAllRows: function(grid) {
  14338. if (grid.expandable.expandedAll) {
  14339. service.collapseAllRows(grid);
  14340. }
  14341. else {
  14342. service.expandAllRows(grid);
  14343. }
  14344. }
  14345. };
  14346. return service;
  14347. }]);
  14348. /**
  14349. * @ngdoc object
  14350. * @name enableExpandableRowHeader
  14351. * @propertyOf ui.grid.expandable.api:GridOptions
  14352. * @description Show a rowHeader to provide the expandable buttons. If set to false then implies
  14353. * you're going to use a custom method for expanding and collapsing the subgrids. Defaults to true.
  14354. * @example
  14355. * <pre>
  14356. * $scope.gridOptions = {
  14357. * enableExpandableRowHeader: false
  14358. * }
  14359. * </pre>
  14360. */
  14361. module.directive('uiGridExpandable', ['uiGridExpandableService', '$templateCache',
  14362. function (uiGridExpandableService, $templateCache) {
  14363. return {
  14364. replace: true,
  14365. priority: 0,
  14366. require: '^uiGrid',
  14367. scope: false,
  14368. compile: function () {
  14369. return {
  14370. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  14371. if ( uiGridCtrl.grid.options.enableExpandableRowHeader !== false ) {
  14372. var expandableRowHeaderColDef = {
  14373. name: 'expandableButtons',
  14374. displayName: '',
  14375. exporterSuppressExport: true,
  14376. enableColumnResizing: false,
  14377. enableColumnMenu: false,
  14378. width: uiGridCtrl.grid.options.expandableRowHeaderWidth || 40
  14379. };
  14380. expandableRowHeaderColDef.cellTemplate = $templateCache.get('ui-grid/expandableRowHeader');
  14381. expandableRowHeaderColDef.headerCellTemplate = $templateCache.get('ui-grid/expandableTopRowHeader');
  14382. uiGridCtrl.grid.addRowHeaderColumn(expandableRowHeaderColDef);
  14383. }
  14384. uiGridExpandableService.initializeGrid(uiGridCtrl.grid);
  14385. },
  14386. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  14387. }
  14388. };
  14389. }
  14390. };
  14391. }]);
  14392. /**
  14393. * @ngdoc directive
  14394. * @name ui.grid.expandable.directive:uiGrid
  14395. * @description stacks on the uiGrid directive to register child grid with parent row when child is created
  14396. */
  14397. module.directive('uiGrid', ['uiGridExpandableService', '$templateCache',
  14398. function (uiGridExpandableService, $templateCache) {
  14399. return {
  14400. replace: true,
  14401. priority: 599,
  14402. require: '^uiGrid',
  14403. scope: false,
  14404. compile: function () {
  14405. return {
  14406. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  14407. uiGridCtrl.grid.api.core.on.renderingComplete($scope, function() {
  14408. //if a parent grid row is on the scope, then add the parentRow property to this childGrid
  14409. if ($scope.row && $scope.row.grid && $scope.row.grid.options && $scope.row.grid.options.enableExpandable) {
  14410. /**
  14411. * @ngdoc directive
  14412. * @name ui.grid.expandable.class:Grid
  14413. * @description Additional Grid properties added by expandable module
  14414. */
  14415. /**
  14416. * @ngdoc object
  14417. * @name parentRow
  14418. * @propertyOf ui.grid.expandable.class:Grid
  14419. * @description reference to the expanded parent row that owns this grid
  14420. */
  14421. uiGridCtrl.grid.parentRow = $scope.row;
  14422. //todo: adjust height on parent row when child grid height changes. we need some sort of gridHeightChanged event
  14423. // uiGridCtrl.grid.core.on.canvasHeightChanged($scope, function(oldHeight, newHeight) {
  14424. // uiGridCtrl.grid.parentRow = newHeight;
  14425. // });
  14426. }
  14427. });
  14428. },
  14429. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  14430. }
  14431. };
  14432. }
  14433. };
  14434. }]);
  14435. /**
  14436. * @ngdoc directive
  14437. * @name ui.grid.expandable.directive:uiGridExpandableRow
  14438. * @description directive to render the expandable row template
  14439. */
  14440. module.directive('uiGridExpandableRow',
  14441. ['uiGridExpandableService', '$timeout', '$compile', 'uiGridConstants','gridUtil','$interval', '$log',
  14442. function (uiGridExpandableService, $timeout, $compile, uiGridConstants, gridUtil, $interval, $log) {
  14443. return {
  14444. replace: false,
  14445. priority: 0,
  14446. scope: false,
  14447. compile: function () {
  14448. return {
  14449. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  14450. gridUtil.getTemplate($scope.grid.options.expandableRowTemplate).then(
  14451. function (template) {
  14452. if ($scope.grid.options.expandableRowScope) {
  14453. var expandableRowScope = $scope.grid.options.expandableRowScope;
  14454. for (var property in expandableRowScope) {
  14455. if (expandableRowScope.hasOwnProperty(property)) {
  14456. $scope[property] = expandableRowScope[property];
  14457. }
  14458. }
  14459. }
  14460. var expandedRowElement = $compile(template)($scope);
  14461. $elm.append(expandedRowElement);
  14462. $scope.row.expandedRendered = true;
  14463. });
  14464. },
  14465. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  14466. $scope.$on('$destroy', function() {
  14467. $scope.row.expandedRendered = false;
  14468. });
  14469. }
  14470. };
  14471. }
  14472. };
  14473. }]);
  14474. /**
  14475. * @ngdoc directive
  14476. * @name ui.grid.expandable.directive:uiGridRow
  14477. * @description stacks on the uiGridRow directive to add support for expandable rows
  14478. */
  14479. module.directive('uiGridRow',
  14480. ['$compile', 'gridUtil', '$templateCache',
  14481. function ($compile, gridUtil, $templateCache) {
  14482. return {
  14483. priority: -200,
  14484. scope: false,
  14485. compile: function ($elm, $attrs) {
  14486. return {
  14487. pre: function ($scope, $elm, $attrs, controllers) {
  14488. $scope.expandableRow = {};
  14489. $scope.expandableRow.shouldRenderExpand = function () {
  14490. var ret = $scope.colContainer.name === 'body' && $scope.grid.options.enableExpandable !== false && $scope.row.isExpanded && (!$scope.grid.isScrollingVertically || $scope.row.expandedRendered);
  14491. return ret;
  14492. };
  14493. $scope.expandableRow.shouldRenderFiller = function () {
  14494. var ret = $scope.row.isExpanded && ( $scope.colContainer.name !== 'body' || ($scope.grid.isScrollingVertically && !$scope.row.expandedRendered));
  14495. return ret;
  14496. };
  14497. /*
  14498. * Commented out @PaulL1. This has no purpose that I can see, and causes #2964. If this code needs to be reinstated for some
  14499. * reason it needs to use drawnWidth, not width, and needs to check column visibility. It should really use render container
  14500. * visible column cache also instead of checking column.renderContainer.
  14501. function updateRowContainerWidth() {
  14502. var grid = $scope.grid;
  14503. var colWidth = 0;
  14504. grid.columns.forEach( function (column) {
  14505. if (column.renderContainer === 'left') {
  14506. colWidth += column.width;
  14507. }
  14508. });
  14509. colWidth = Math.floor(colWidth);
  14510. return '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.colContainer.name + ', .grid' + grid.id +
  14511. ' .ui-grid-pinned-container-' + $scope.colContainer.name + ' .ui-grid-render-container-' + $scope.colContainer.name +
  14512. ' .ui-grid-viewport .ui-grid-canvas .ui-grid-row { width: ' + colWidth + 'px; }';
  14513. }
  14514. if ($scope.colContainer.name === 'left') {
  14515. $scope.grid.registerStyleComputation({
  14516. priority: 15,
  14517. func: updateRowContainerWidth
  14518. });
  14519. }*/
  14520. },
  14521. post: function ($scope, $elm, $attrs, controllers) {
  14522. }
  14523. };
  14524. }
  14525. };
  14526. }]);
  14527. /**
  14528. * @ngdoc directive
  14529. * @name ui.grid.expandable.directive:uiGridViewport
  14530. * @description stacks on the uiGridViewport directive to append the expandable row html elements to the
  14531. * default gridRow template
  14532. */
  14533. module.directive('uiGridViewport',
  14534. ['$compile', 'gridUtil', '$templateCache',
  14535. function ($compile, gridUtil, $templateCache) {
  14536. return {
  14537. priority: -200,
  14538. scope: false,
  14539. compile: function ($elm, $attrs) {
  14540. var rowRepeatDiv = angular.element($elm.children().children()[0]);
  14541. var expandedRowFillerElement = $templateCache.get('ui-grid/expandableScrollFiller');
  14542. var expandedRowElement = $templateCache.get('ui-grid/expandableRow');
  14543. rowRepeatDiv.append(expandedRowElement);
  14544. rowRepeatDiv.append(expandedRowFillerElement);
  14545. return {
  14546. pre: function ($scope, $elm, $attrs, controllers) {
  14547. },
  14548. post: function ($scope, $elm, $attrs, controllers) {
  14549. }
  14550. };
  14551. }
  14552. };
  14553. }]);
  14554. })();
  14555. /* global console */
  14556. (function () {
  14557. 'use strict';
  14558. /**
  14559. * @ngdoc overview
  14560. * @name ui.grid.exporter
  14561. * @description
  14562. *
  14563. * # ui.grid.exporter
  14564. *
  14565. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  14566. *
  14567. * This module provides the ability to exporter data from the grid.
  14568. *
  14569. * Data can be exported in a range of formats, and all data, visible
  14570. * data, or selected rows can be exported, with all columns or visible
  14571. * columns.
  14572. *
  14573. * No UI is provided, the caller should provide their own UI/buttons
  14574. * as appropriate, or enable the gridMenu
  14575. *
  14576. * <br/>
  14577. * <br/>
  14578. *
  14579. * <div doc-module-components="ui.grid.exporter"></div>
  14580. */
  14581. var module = angular.module('ui.grid.exporter', ['ui.grid']);
  14582. /**
  14583. * @ngdoc object
  14584. * @name ui.grid.exporter.constant:uiGridExporterConstants
  14585. *
  14586. * @description constants available in exporter module
  14587. */
  14588. /**
  14589. * @ngdoc property
  14590. * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
  14591. * @name ALL
  14592. * @description export all data, including data not visible. Can
  14593. * be set for either rowTypes or colTypes
  14594. */
  14595. /**
  14596. * @ngdoc property
  14597. * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
  14598. * @name VISIBLE
  14599. * @description export only visible data, including data not visible. Can
  14600. * be set for either rowTypes or colTypes
  14601. */
  14602. /**
  14603. * @ngdoc property
  14604. * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
  14605. * @name SELECTED
  14606. * @description export all data, including data not visible. Can
  14607. * be set only for rowTypes, selection of only some columns is
  14608. * not supported
  14609. */
  14610. module.constant('uiGridExporterConstants', {
  14611. featureName: 'exporter',
  14612. ALL: 'all',
  14613. VISIBLE: 'visible',
  14614. SELECTED: 'selected',
  14615. CSV_CONTENT: 'CSV_CONTENT',
  14616. BUTTON_LABEL: 'BUTTON_LABEL',
  14617. FILE_NAME: 'FILE_NAME'
  14618. });
  14619. /**
  14620. * @ngdoc service
  14621. * @name ui.grid.exporter.service:uiGridExporterService
  14622. *
  14623. * @description Services for exporter feature
  14624. */
  14625. module.service('uiGridExporterService', ['$q', 'uiGridExporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService',
  14626. function ($q, uiGridExporterConstants, gridUtil, $compile, $interval, i18nService) {
  14627. var service = {
  14628. delay: 100,
  14629. initializeGrid: function (grid) {
  14630. //add feature namespace and any properties to grid for needed state
  14631. grid.exporter = {};
  14632. this.defaultGridOptions(grid.options);
  14633. /**
  14634. * @ngdoc object
  14635. * @name ui.grid.exporter.api:PublicApi
  14636. *
  14637. * @description Public Api for exporter feature
  14638. */
  14639. var publicApi = {
  14640. events: {
  14641. exporter: {
  14642. }
  14643. },
  14644. methods: {
  14645. exporter: {
  14646. /**
  14647. * @ngdoc function
  14648. * @name csvExport
  14649. * @methodOf ui.grid.exporter.api:PublicApi
  14650. * @description Exports rows from the grid in csv format,
  14651. * the data exported is selected based on the provided options
  14652. * @param {string} rowTypes which rows to export, valid values are
  14653. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  14654. * uiGridExporterConstants.SELECTED
  14655. * @param {string} colTypes which columns to export, valid values are
  14656. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE
  14657. */
  14658. csvExport: function (rowTypes, colTypes) {
  14659. service.csvExport(grid, rowTypes, colTypes);
  14660. },
  14661. /**
  14662. * @ngdoc function
  14663. * @name pdfExport
  14664. * @methodOf ui.grid.exporter.api:PublicApi
  14665. * @description Exports rows from the grid in pdf format,
  14666. * the data exported is selected based on the provided options
  14667. * Note that this function has a dependency on pdfMake, all
  14668. * going well this has been installed for you.
  14669. * The resulting pdf opens in a new browser window.
  14670. * @param {string} rowTypes which rows to export, valid values are
  14671. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  14672. * uiGridExporterConstants.SELECTED
  14673. * @param {string} colTypes which columns to export, valid values are
  14674. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE
  14675. */
  14676. pdfExport: function (rowTypes, colTypes) {
  14677. service.pdfExport(grid, rowTypes, colTypes);
  14678. }
  14679. }
  14680. }
  14681. };
  14682. grid.api.registerEventsFromObject(publicApi.events);
  14683. grid.api.registerMethodsFromObject(publicApi.methods);
  14684. if (grid.api.core.addToGridMenu){
  14685. service.addToMenu( grid );
  14686. } else {
  14687. // order of registration is not guaranteed, register in a little while
  14688. $interval( function() {
  14689. if (grid.api.core.addToGridMenu){
  14690. service.addToMenu( grid );
  14691. }
  14692. }, this.delay, 1);
  14693. }
  14694. },
  14695. defaultGridOptions: function (gridOptions) {
  14696. //default option to true unless it was explicitly set to false
  14697. /**
  14698. * @ngdoc object
  14699. * @name ui.grid.exporter.api:GridOptions
  14700. *
  14701. * @description GridOptions for exporter feature, these are available to be
  14702. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  14703. */
  14704. /**
  14705. * @ngdoc object
  14706. * @name ui.grid.exporter.api:ColumnDef
  14707. * @description ColumnDef settings for exporter
  14708. */
  14709. /**
  14710. * @ngdoc object
  14711. * @name exporterSuppressMenu
  14712. * @propertyOf ui.grid.exporter.api:GridOptions
  14713. * @description Don't show the export menu button, implying the user
  14714. * will roll their own UI for calling the exporter
  14715. * <br/>Defaults to false
  14716. */
  14717. gridOptions.exporterSuppressMenu = gridOptions.exporterSuppressMenu === true;
  14718. /**
  14719. * @ngdoc object
  14720. * @name exporterMenuLabel
  14721. * @propertyOf ui.grid.exporter.api:GridOptions
  14722. * @description The text to show on the exporter menu button
  14723. * link
  14724. * <br/>Defaults to 'Export'
  14725. */
  14726. gridOptions.exporterMenuLabel = gridOptions.exporterMenuLabel ? gridOptions.exporterMenuLabel : 'Export';
  14727. /**
  14728. * @ngdoc object
  14729. * @name exporterSuppressColumns
  14730. * @propertyOf ui.grid.exporter.api:GridOptions
  14731. * @description Columns that should not be exported. The selectionRowHeader is already automatically
  14732. * suppressed, but if you had a button column or some other "system" column that shouldn't be shown in the
  14733. * output then add it in this list. You should provide an array of column names.
  14734. * <br/>Defaults to: []
  14735. * <pre>
  14736. * gridOptions.exporterSuppressColumns = [ 'buttons' ];
  14737. * </pre>
  14738. */
  14739. gridOptions.exporterSuppressColumns = gridOptions.exporterSuppressColumns ? gridOptions.exporterSuppressColumns : [];
  14740. /**
  14741. * @ngdoc object
  14742. * @name exporterCsvColumnSeparator
  14743. * @propertyOf ui.grid.exporter.api:GridOptions
  14744. * @description The character to use as column separator
  14745. * link
  14746. * <br/>Defaults to ','
  14747. */
  14748. gridOptions.exporterCsvColumnSeparator = gridOptions.exporterCsvColumnSeparator ? gridOptions.exporterCsvColumnSeparator : ',';
  14749. /**
  14750. * @ngdoc object
  14751. * @name exporterCsvFilename
  14752. * @propertyOf ui.grid.exporter.api:GridOptions
  14753. * @description The default filename to use when saving the downloaded csv.
  14754. * This will only work in some browsers.
  14755. * <br/>Defaults to 'download.csv'
  14756. */
  14757. gridOptions.exporterCsvFilename = gridOptions.exporterCsvFilename ? gridOptions.exporterCsvFilename : 'download.csv';
  14758. /**
  14759. * @ngdoc object
  14760. * @name exporterPdfFilename
  14761. * @propertyOf ui.grid.exporter.api:GridOptions
  14762. * @description The default filename to use when saving the downloaded pdf, only used in IE (other browsers open pdfs in a new window)
  14763. * <br/>Defaults to 'download.pdf'
  14764. */
  14765. gridOptions.exporterPdfFilename = gridOptions.exporterPdfFilename ? gridOptions.exporterPdfFilename : 'download.pdf';
  14766. /**
  14767. * @ngdoc object
  14768. * @name exporterOlderExcelCompatibility
  14769. * @propertyOf ui.grid.exporter.api:GridOptions
  14770. * @description Some versions of excel don't like the utf-16 BOM on the front, and it comes
  14771. * through as  in the first column header. Setting this option to false will suppress this, at the
  14772. * expense of proper utf-16 handling in applications that do recognise the BOM
  14773. * <br/>Defaults to false
  14774. */
  14775. gridOptions.exporterOlderExcelCompatibility = gridOptions.exporterOlderExcelCompatibility === true;
  14776. /**
  14777. * @ngdoc object
  14778. * @name exporterPdfDefaultStyle
  14779. * @propertyOf ui.grid.exporter.api:GridOptions
  14780. * @description The default style in pdfMake format
  14781. * <br/>Defaults to:
  14782. * <pre>
  14783. * {
  14784. * fontSize: 11
  14785. * }
  14786. * </pre>
  14787. */
  14788. gridOptions.exporterPdfDefaultStyle = gridOptions.exporterPdfDefaultStyle ? gridOptions.exporterPdfDefaultStyle : { fontSize: 11 };
  14789. /**
  14790. * @ngdoc object
  14791. * @name exporterPdfTableStyle
  14792. * @propertyOf ui.grid.exporter.api:GridOptions
  14793. * @description The table style in pdfMake format
  14794. * <br/>Defaults to:
  14795. * <pre>
  14796. * {
  14797. * margin: [0, 5, 0, 15]
  14798. * }
  14799. * </pre>
  14800. */
  14801. gridOptions.exporterPdfTableStyle = gridOptions.exporterPdfTableStyle ? gridOptions.exporterPdfTableStyle : { margin: [0, 5, 0, 15] };
  14802. /**
  14803. * @ngdoc object
  14804. * @name exporterPdfTableHeaderStyle
  14805. * @propertyOf ui.grid.exporter.api:GridOptions
  14806. * @description The tableHeader style in pdfMake format
  14807. * <br/>Defaults to:
  14808. * <pre>
  14809. * {
  14810. * bold: true,
  14811. * fontSize: 12,
  14812. * color: 'black'
  14813. * }
  14814. * </pre>
  14815. */
  14816. gridOptions.exporterPdfTableHeaderStyle = gridOptions.exporterPdfTableHeaderStyle ? gridOptions.exporterPdfTableHeaderStyle : { bold: true, fontSize: 12, color: 'black' };
  14817. /**
  14818. * @ngdoc object
  14819. * @name exporterPdfHeader
  14820. * @propertyOf ui.grid.exporter.api:GridOptions
  14821. * @description The header section for pdf exports. Can be
  14822. * simple text:
  14823. * <pre>
  14824. * gridOptions.exporterPdfHeader = 'My Header';
  14825. * </pre>
  14826. * Can be a more complex object in pdfMake format:
  14827. * <pre>
  14828. * gridOptions.exporterPdfHeader = {
  14829. * columns: [
  14830. * 'Left part',
  14831. * { text: 'Right part', alignment: 'right' }
  14832. * ]
  14833. * };
  14834. * </pre>
  14835. * Or can be a function, allowing page numbers and the like
  14836. * <pre>
  14837. * gridOptions.exporterPdfHeader: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; };
  14838. * </pre>
  14839. */
  14840. gridOptions.exporterPdfHeader = gridOptions.exporterPdfHeader ? gridOptions.exporterPdfHeader : null;
  14841. /**
  14842. * @ngdoc object
  14843. * @name exporterPdfFooter
  14844. * @propertyOf ui.grid.exporter.api:GridOptions
  14845. * @description The header section for pdf exports. Can be
  14846. * simple text:
  14847. * <pre>
  14848. * gridOptions.exporterPdfFooter = 'My Footer';
  14849. * </pre>
  14850. * Can be a more complex object in pdfMake format:
  14851. * <pre>
  14852. * gridOptions.exporterPdfFooter = {
  14853. * columns: [
  14854. * 'Left part',
  14855. * { text: 'Right part', alignment: 'right' }
  14856. * ]
  14857. * };
  14858. * </pre>
  14859. * Or can be a function, allowing page numbers and the like
  14860. * <pre>
  14861. * gridOptions.exporterPdfFooter: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; };
  14862. * </pre>
  14863. */
  14864. gridOptions.exporterPdfFooter = gridOptions.exporterPdfFooter ? gridOptions.exporterPdfFooter : null;
  14865. /**
  14866. * @ngdoc object
  14867. * @name exporterPdfOrientation
  14868. * @propertyOf ui.grid.exporter.api:GridOptions
  14869. * @description The orientation, should be a valid pdfMake value,
  14870. * 'landscape' or 'portrait'
  14871. * <br/>Defaults to landscape
  14872. */
  14873. gridOptions.exporterPdfOrientation = gridOptions.exporterPdfOrientation ? gridOptions.exporterPdfOrientation : 'landscape';
  14874. /**
  14875. * @ngdoc object
  14876. * @name exporterPdfPageSize
  14877. * @propertyOf ui.grid.exporter.api:GridOptions
  14878. * @description The orientation, should be a valid pdfMake
  14879. * paper size, usually 'A4' or 'LETTER'
  14880. * {@link https://github.com/bpampuch/pdfmake/blob/master/src/standardPageSizes.js pdfMake page sizes}
  14881. * <br/>Defaults to A4
  14882. */
  14883. gridOptions.exporterPdfPageSize = gridOptions.exporterPdfPageSize ? gridOptions.exporterPdfPageSize : 'A4';
  14884. /**
  14885. * @ngdoc object
  14886. * @name exporterPdfMaxGridWidth
  14887. * @propertyOf ui.grid.exporter.api:GridOptions
  14888. * @description The maxium grid width - the current grid width
  14889. * will be scaled to match this, with any fixed width columns
  14890. * being adjusted accordingly.
  14891. * <br/>Defaults to 720 (for A4 landscape), use 670 for LETTER
  14892. */
  14893. gridOptions.exporterPdfMaxGridWidth = gridOptions.exporterPdfMaxGridWidth ? gridOptions.exporterPdfMaxGridWidth : 720;
  14894. /**
  14895. * @ngdoc object
  14896. * @name exporterPdfTableLayout
  14897. * @propertyOf ui.grid.exporter.api:GridOptions
  14898. * @description A tableLayout in pdfMake format,
  14899. * controls gridlines and the like. We use the default
  14900. * layout usually.
  14901. * <br/>Defaults to null, which means no layout
  14902. */
  14903. /**
  14904. * @ngdoc object
  14905. * @name exporterMenuAllData
  14906. * @porpertyOf ui.grid.exporter.api:GridOptions
  14907. * @description Add export all data as cvs/pdf menu items to the ui-grid grid menu, if it's present. Defaults to true.
  14908. */
  14909. gridOptions.exporterMenuAllData = gridOptions.exporterMenuAllData !== undefined ? gridOptions.exporterMenuAllData : true;
  14910. /**
  14911. * @ngdoc object
  14912. * @name exporterMenuCsv
  14913. * @propertyOf ui.grid.exporter.api:GridOptions
  14914. * @description Add csv export menu items to the ui-grid grid menu, if it's present. Defaults to true.
  14915. */
  14916. gridOptions.exporterMenuCsv = gridOptions.exporterMenuCsv !== undefined ? gridOptions.exporterMenuCsv : true;
  14917. /**
  14918. * @ngdoc object
  14919. * @name exporterMenuPdf
  14920. * @propertyOf ui.grid.exporter.api:GridOptions
  14921. * @description Add pdf export menu items to the ui-grid grid menu, if it's present. Defaults to true.
  14922. */
  14923. gridOptions.exporterMenuPdf = gridOptions.exporterMenuPdf !== undefined ? gridOptions.exporterMenuPdf : true;
  14924. /**
  14925. * @ngdoc object
  14926. * @name exporterPdfCustomFormatter
  14927. * @propertyOf ui.grid.exporter.api:GridOptions
  14928. * @description A custom callback routine that changes the pdf document, adding any
  14929. * custom styling or content that is supported by pdfMake. Takes in the complete docDefinition, and
  14930. * must return an updated docDefinition ready for pdfMake.
  14931. * @example
  14932. * In this example we add a style to the style array, so that we can use it in our
  14933. * footer definition.
  14934. * <pre>
  14935. * gridOptions.exporterPdfCustomFormatter = function ( docDefinition ) {
  14936. * docDefinition.styles.footerStyle = { bold: true, fontSize: 10 };
  14937. * return docDefinition;
  14938. * }
  14939. *
  14940. * gridOptions.exporterPdfFooter = { text: 'My footer', style: 'footerStyle' }
  14941. * </pre>
  14942. */
  14943. gridOptions.exporterPdfCustomFormatter = ( gridOptions.exporterPdfCustomFormatter && typeof( gridOptions.exporterPdfCustomFormatter ) === 'function' ) ? gridOptions.exporterPdfCustomFormatter : function ( docDef ) { return docDef; };
  14944. /**
  14945. * @ngdoc object
  14946. * @name exporterHeaderFilterUseName
  14947. * @propertyOf ui.grid.exporter.api:GridOptions
  14948. * @description Defaults to false, which leads to `displayName` being passed into the headerFilter.
  14949. * If set to true, then will pass `name` instead.
  14950. *
  14951. *
  14952. * @example
  14953. * <pre>
  14954. * gridOptions.exporterHeaderFilterUseName = true;
  14955. * </pre>
  14956. */
  14957. gridOptions.exporterHeaderFilterUseName = gridOptions.exporterHeaderFilterUseName === true;
  14958. /**
  14959. * @ngdoc object
  14960. * @name exporterHeaderFilter
  14961. * @propertyOf ui.grid.exporter.api:GridOptions
  14962. * @description A function to apply to the header displayNames before exporting. Useful for internationalisation,
  14963. * for example if you were using angular-translate you'd set this to `$translate.instant`. Note that this
  14964. * call must be synchronous, it cannot be a call that returns a promise.
  14965. *
  14966. * Behaviour can be changed to pass in `name` instead of `displayName` through use of `exporterHeaderFilterUseName: true`.
  14967. *
  14968. * @example
  14969. * <pre>
  14970. * gridOptions.exporterHeaderFilter = function( displayName ){ return 'col: ' + name; };
  14971. * </pre>
  14972. * OR
  14973. * <pre>
  14974. * gridOptions.exporterHeaderFilter = $translate.instant;
  14975. * </pre>
  14976. */
  14977. /**
  14978. * @ngdoc function
  14979. * @name exporterFieldCallback
  14980. * @propertyOf ui.grid.exporter.api:GridOptions
  14981. * @description A function to call for each field before exporting it. Allows
  14982. * massaging of raw data into a display format, for example if you have applied
  14983. * filters to convert codes into decodes, or you require
  14984. * a specific date format in the exported content.
  14985. *
  14986. * The method is called once for each field exported, and provides the grid, the
  14987. * gridCol and the GridRow for you to use as context in massaging the data.
  14988. *
  14989. * @param {Grid} grid provides the grid in case you have need of it
  14990. * @param {GridRow} row the row from which the data comes
  14991. * @param {GridCol} col the column from which the data comes
  14992. * @param {object} value the value for your massaging
  14993. * @returns {object} you must return the massaged value ready for exporting
  14994. *
  14995. * @example
  14996. * <pre>
  14997. * gridOptions.exporterFieldCallback = function ( grid, row, col, value ){
  14998. * if ( col.name === 'status' ){
  14999. * value = decodeStatus( value );
  15000. * }
  15001. * return value;
  15002. * }
  15003. * </pre>
  15004. */
  15005. gridOptions.exporterFieldCallback = gridOptions.exporterFieldCallback ? gridOptions.exporterFieldCallback : function( grid, row, col, value ) { return value; };
  15006. /**
  15007. * @ngdoc function
  15008. * @name exporterAllDataFn
  15009. * @propertyOf ui.grid.exporter.api:GridOptions
  15010. * @description This promise is needed when exporting all rows,
  15011. * and the data need to be provided by server side. Default is null.
  15012. * @returns {Promise} a promise to load all data from server
  15013. *
  15014. * @example
  15015. * <pre>
  15016. * gridOptions.exporterAllDataFn = function () {
  15017. * return $http.get('/data/100.json')
  15018. * }
  15019. * </pre>
  15020. */
  15021. gridOptions.exporterAllDataFn = gridOptions.exporterAllDataFn ? gridOptions.exporterAllDataFn : null;
  15022. /**
  15023. * @ngdoc function
  15024. * @name exporterAllDataPromise
  15025. * @propertyOf ui.grid.exporter.api:GridOptions
  15026. * @description DEPRECATED - exporterAllDataFn used to be
  15027. * called this, but it wasn't a promise, it was a function that returned
  15028. * a promise. Deprecated, but supported for backward compatibility, use
  15029. * exporterAllDataFn instead.
  15030. * @returns {Promise} a promise to load all data from server
  15031. *
  15032. * @example
  15033. * <pre>
  15034. * gridOptions.exporterAllDataFn = function () {
  15035. * return $http.get('/data/100.json')
  15036. * }
  15037. * </pre>
  15038. */
  15039. if ( gridOptions.exporterAllDataFn == null && gridOptions.exporterAllDataPromise ) {
  15040. gridOptions.exporterAllDataFn = gridOptions.exporterAllDataPromise;
  15041. }
  15042. },
  15043. /**
  15044. * @ngdoc function
  15045. * @name addToMenu
  15046. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15047. * @description Adds export items to the grid menu,
  15048. * allowing the user to select export options
  15049. * @param {Grid} grid the grid from which data should be exported
  15050. */
  15051. addToMenu: function ( grid ) {
  15052. grid.api.core.addToGridMenu( grid, [
  15053. {
  15054. title: i18nService.getSafeText('gridMenu.exporterAllAsCsv'),
  15055. action: function ($event) {
  15056. this.grid.api.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL );
  15057. },
  15058. shown: function() {
  15059. return this.grid.options.exporterMenuCsv && this.grid.options.exporterMenuAllData;
  15060. },
  15061. order: 200
  15062. },
  15063. {
  15064. title: i18nService.getSafeText('gridMenu.exporterVisibleAsCsv'),
  15065. action: function ($event) {
  15066. this.grid.api.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE );
  15067. },
  15068. shown: function() {
  15069. return this.grid.options.exporterMenuCsv;
  15070. },
  15071. order: 201
  15072. },
  15073. {
  15074. title: i18nService.getSafeText('gridMenu.exporterSelectedAsCsv'),
  15075. action: function ($event) {
  15076. this.grid.api.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE );
  15077. },
  15078. shown: function() {
  15079. return this.grid.options.exporterMenuCsv &&
  15080. ( this.grid.api.selection && this.grid.api.selection.getSelectedRows().length > 0 );
  15081. },
  15082. order: 202
  15083. },
  15084. {
  15085. title: i18nService.getSafeText('gridMenu.exporterAllAsPdf'),
  15086. action: function ($event) {
  15087. this.grid.api.exporter.pdfExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL );
  15088. },
  15089. shown: function() {
  15090. return this.grid.options.exporterMenuPdf && this.grid.options.exporterMenuAllData;
  15091. },
  15092. order: 203
  15093. },
  15094. {
  15095. title: i18nService.getSafeText('gridMenu.exporterVisibleAsPdf'),
  15096. action: function ($event) {
  15097. this.grid.api.exporter.pdfExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE );
  15098. },
  15099. shown: function() {
  15100. return this.grid.options.exporterMenuPdf;
  15101. },
  15102. order: 204
  15103. },
  15104. {
  15105. title: i18nService.getSafeText('gridMenu.exporterSelectedAsPdf'),
  15106. action: function ($event) {
  15107. this.grid.api.exporter.pdfExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE );
  15108. },
  15109. shown: function() {
  15110. return this.grid.options.exporterMenuPdf &&
  15111. ( this.grid.api.selection && this.grid.api.selection.getSelectedRows().length > 0 );
  15112. },
  15113. order: 205
  15114. }
  15115. ]);
  15116. },
  15117. /**
  15118. * @ngdoc function
  15119. * @name csvExport
  15120. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15121. * @description Exports rows from the grid in csv format,
  15122. * the data exported is selected based on the provided options
  15123. * @param {Grid} grid the grid from which data should be exported
  15124. * @param {string} rowTypes which rows to export, valid values are
  15125. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15126. * uiGridExporterConstants.SELECTED
  15127. * @param {string} colTypes which columns to export, valid values are
  15128. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15129. * uiGridExporterConstants.SELECTED
  15130. */
  15131. csvExport: function (grid, rowTypes, colTypes) {
  15132. var self = this;
  15133. this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function() {
  15134. var exportColumnHeaders = self.getColumnHeaders(grid, colTypes);
  15135. var exportData = self.getData(grid, rowTypes, colTypes);
  15136. var csvContent = self.formatAsCsv(exportColumnHeaders, exportData, grid.options.exporterCsvColumnSeparator);
  15137. self.downloadFile (grid.options.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
  15138. });
  15139. },
  15140. /**
  15141. * @ngdoc function
  15142. * @name loadAllDataIfNeeded
  15143. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15144. * @description When using server side pagination, use exporterAllDataFn to
  15145. * load all data before continuing processing.
  15146. * When using client side pagination, return a resolved promise so processing
  15147. * continues immediately
  15148. * @param {Grid} grid the grid from which data should be exported
  15149. * @param {string} rowTypes which rows to export, valid values are
  15150. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15151. * uiGridExporterConstants.SELECTED
  15152. * @param {string} colTypes which columns to export, valid values are
  15153. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15154. * uiGridExporterConstants.SELECTED
  15155. */
  15156. loadAllDataIfNeeded: function (grid, rowTypes, colTypes) {
  15157. if ( rowTypes === uiGridExporterConstants.ALL && grid.rows.length !== grid.options.totalItems && grid.options.exporterAllDataFn) {
  15158. return grid.options.exporterAllDataFn()
  15159. .then(function() {
  15160. grid.modifyRows(grid.options.data);
  15161. });
  15162. } else {
  15163. var deferred = $q.defer();
  15164. deferred.resolve();
  15165. return deferred.promise;
  15166. }
  15167. },
  15168. /**
  15169. * @ngdoc property
  15170. * @propertyOf ui.grid.exporter.api:ColumnDef
  15171. * @name exporterSuppressExport
  15172. * @description Suppresses export for this column. Used by selection and expandable.
  15173. */
  15174. /**
  15175. * @ngdoc function
  15176. * @name getColumnHeaders
  15177. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15178. * @description Gets the column headers from the grid to use
  15179. * as a title row for the exported file, all headers have
  15180. * headerCellFilters applied as appropriate.
  15181. *
  15182. * Column headers are an array of objects, each object has
  15183. * name, displayName, width and align attributes. Only name is
  15184. * used for csv, all attributes are used for pdf.
  15185. *
  15186. * @param {Grid} grid the grid from which data should be exported
  15187. * @param {string} colTypes which columns to export, valid values are
  15188. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15189. * uiGridExporterConstants.SELECTED
  15190. */
  15191. getColumnHeaders: function (grid, colTypes) {
  15192. var headers = [];
  15193. var columns;
  15194. if ( colTypes === uiGridExporterConstants.ALL ){
  15195. columns = grid.columns;
  15196. } else {
  15197. var leftColumns = grid.renderContainers.left ? grid.renderContainers.left.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
  15198. var bodyColumns = grid.renderContainers.body ? grid.renderContainers.body.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
  15199. var rightColumns = grid.renderContainers.right ? grid.renderContainers.right.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
  15200. columns = leftColumns.concat(bodyColumns,rightColumns);
  15201. }
  15202. columns.forEach( function( gridCol, index ) {
  15203. if ( gridCol.colDef.exporterSuppressExport !== true &&
  15204. grid.options.exporterSuppressColumns.indexOf( gridCol.name ) === -1 ){
  15205. headers.push({
  15206. name: gridCol.field,
  15207. displayName: grid.options.exporterHeaderFilter ? ( grid.options.exporterHeaderFilterUseName ? grid.options.exporterHeaderFilter(gridCol.name) : grid.options.exporterHeaderFilter(gridCol.displayName) ) : gridCol.displayName,
  15208. width: gridCol.drawnWidth ? gridCol.drawnWidth : gridCol.width,
  15209. align: gridCol.colDef.type === 'number' ? 'right' : 'left'
  15210. });
  15211. }
  15212. });
  15213. return headers;
  15214. },
  15215. /**
  15216. * @ngdoc property
  15217. * @propertyOf ui.grid.exporter.api:ColumnDef
  15218. * @name exporterPdfAlign
  15219. * @description the alignment you'd like for this specific column when
  15220. * exported into a pdf. Can be 'left', 'right', 'center' or any other
  15221. * valid pdfMake alignment option.
  15222. */
  15223. /**
  15224. * @ngdoc object
  15225. * @name ui.grid.exporter.api:GridRow
  15226. * @description GridRow settings for exporter
  15227. */
  15228. /**
  15229. * @ngdoc object
  15230. * @name exporterEnableExporting
  15231. * @propertyOf ui.grid.exporter.api:GridRow
  15232. * @description If set to false, then don't export this row, notwithstanding visible or
  15233. * other settings
  15234. * <br/>Defaults to true
  15235. */
  15236. /**
  15237. * @ngdoc function
  15238. * @name getData
  15239. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15240. * @description Gets data from the grid based on the provided options,
  15241. * all cells have cellFilters applied as appropriate. Any rows marked
  15242. * `exporterEnableExporting: false` will not be exported
  15243. * @param {Grid} grid the grid from which data should be exported
  15244. * @param {string} rowTypes which rows to export, valid values are
  15245. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15246. * uiGridExporterConstants.SELECTED
  15247. * @param {string} colTypes which columns to export, valid values are
  15248. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15249. * uiGridExporterConstants.SELECTED
  15250. */
  15251. getData: function (grid, rowTypes, colTypes) {
  15252. var data = [];
  15253. var rows;
  15254. var columns;
  15255. switch ( rowTypes ) {
  15256. case uiGridExporterConstants.ALL:
  15257. rows = grid.rows;
  15258. break;
  15259. case uiGridExporterConstants.VISIBLE:
  15260. rows = grid.getVisibleRows();
  15261. break;
  15262. case uiGridExporterConstants.SELECTED:
  15263. if ( grid.api.selection ){
  15264. rows = grid.api.selection.getSelectedGridRows();
  15265. } else {
  15266. gridUtil.logError('selection feature must be enabled to allow selected rows to be exported');
  15267. }
  15268. break;
  15269. }
  15270. if ( colTypes === uiGridExporterConstants.ALL ){
  15271. columns = grid.columns;
  15272. } else {
  15273. var leftColumns = grid.renderContainers.left ? grid.renderContainers.left.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
  15274. var bodyColumns = grid.renderContainers.body ? grid.renderContainers.body.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
  15275. var rightColumns = grid.renderContainers.right ? grid.renderContainers.right.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
  15276. columns = leftColumns.concat(bodyColumns,rightColumns);
  15277. }
  15278. rows.forEach( function( row, index ) {
  15279. if (row.exporterEnableExporting !== false) {
  15280. var extractedRow = [];
  15281. columns.forEach( function( gridCol, index ) {
  15282. if ( (gridCol.visible || colTypes === uiGridExporterConstants.ALL ) &&
  15283. gridCol.colDef.exporterSuppressExport !== true &&
  15284. grid.options.exporterSuppressColumns.indexOf( gridCol.name ) === -1 ){
  15285. var extractedField = { value: grid.options.exporterFieldCallback( grid, row, gridCol, grid.getCellValue( row, gridCol ) ) };
  15286. if ( gridCol.colDef.exporterPdfAlign ) {
  15287. extractedField.alignment = gridCol.colDef.exporterPdfAlign;
  15288. }
  15289. extractedRow.push(extractedField);
  15290. }
  15291. });
  15292. data.push(extractedRow);
  15293. }
  15294. });
  15295. return data;
  15296. },
  15297. /**
  15298. * @ngdoc function
  15299. * @name formatAsCSV
  15300. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15301. * @description Formats the column headers and data as a CSV,
  15302. * and sends that data to the user
  15303. * @param {array} exportColumnHeaders an array of column headers,
  15304. * where each header is an object with name, width and maybe alignment
  15305. * @param {array} exportData an array of rows, where each row is
  15306. * an array of column data
  15307. * @returns {string} csv the formatted csv as a string
  15308. */
  15309. formatAsCsv: function (exportColumnHeaders, exportData, separator) {
  15310. var self = this;
  15311. var bareHeaders = exportColumnHeaders.map(function(header){return { value: header.displayName };});
  15312. var csv = self.formatRowAsCsv(this, separator)(bareHeaders) + '\n';
  15313. csv += exportData.map(this.formatRowAsCsv(this, separator)).join('\n');
  15314. return csv;
  15315. },
  15316. /**
  15317. * @ngdoc function
  15318. * @name formatRowAsCsv
  15319. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15320. * @description Renders a single field as a csv field, including
  15321. * quotes around the value
  15322. * @param {exporterService} exporter pass in exporter
  15323. * @param {array} row the row to be turned into a csv string
  15324. * @returns {string} a csv-ified version of the row
  15325. */
  15326. formatRowAsCsv: function (exporter, separator) {
  15327. return function (row) {
  15328. return row.map(exporter.formatFieldAsCsv).join(separator);
  15329. };
  15330. },
  15331. /**
  15332. * @ngdoc function
  15333. * @name formatFieldAsCsv
  15334. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15335. * @description Renders a single field as a csv field, including
  15336. * quotes around the value
  15337. * @param {field} field the field to be turned into a csv string,
  15338. * may be of any type
  15339. * @returns {string} a csv-ified version of the field
  15340. */
  15341. formatFieldAsCsv: function (field) {
  15342. if (field.value == null) { // we want to catch anything null-ish, hence just == not ===
  15343. return '';
  15344. }
  15345. if (typeof(field.value) === 'number') {
  15346. return field.value;
  15347. }
  15348. if (typeof(field.value) === 'boolean') {
  15349. return (field.value ? 'TRUE' : 'FALSE') ;
  15350. }
  15351. if (typeof(field.value) === 'string') {
  15352. return '"' + field.value.replace(/"/g,'""') + '"';
  15353. }
  15354. return JSON.stringify(field.value);
  15355. },
  15356. /**
  15357. * @ngdoc function
  15358. * @name isIE
  15359. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15360. * @description Checks whether current browser is IE and returns it's version if it is
  15361. */
  15362. isIE: function () {
  15363. var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/);
  15364. return match ? parseInt(match[1]) : false;
  15365. },
  15366. /**
  15367. * @ngdoc function
  15368. * @name downloadFile
  15369. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15370. * @description Triggers download of a csv file. Logic provided
  15371. * by @cssensei (from his colleagues at https://github.com/ifeelgoods) in issue #2391
  15372. * @param {string} fileName the filename we'd like our file to be
  15373. * given
  15374. * @param {string} csvContent the csv content that we'd like to
  15375. * download as a file
  15376. * @param {boolean} exporterOlderExcelCompatibility whether or not we put a utf-16 BOM on the from (\uFEFF)
  15377. */
  15378. downloadFile: function (fileName, csvContent, exporterOlderExcelCompatibility) {
  15379. var D = document;
  15380. var a = D.createElement('a');
  15381. var strMimeType = 'application/octet-stream;charset=utf-8';
  15382. var rawFile;
  15383. var ieVersion;
  15384. ieVersion = this.isIE();
  15385. if (ieVersion && ieVersion < 10) {
  15386. var frame = D.createElement('iframe');
  15387. document.body.appendChild(frame);
  15388. frame.contentWindow.document.open("text/html", "replace");
  15389. frame.contentWindow.document.write('sep=,\r\n' + csvContent);
  15390. frame.contentWindow.document.close();
  15391. frame.contentWindow.focus();
  15392. frame.contentWindow.document.execCommand('SaveAs', true, fileName);
  15393. document.body.removeChild(frame);
  15394. return true;
  15395. }
  15396. // IE10+
  15397. if (navigator.msSaveBlob) {
  15398. return navigator.msSaveOrOpenBlob(
  15399. new Blob(
  15400. [exporterOlderExcelCompatibility ? "\uFEFF" : '', csvContent],
  15401. { type: strMimeType } ),
  15402. fileName
  15403. );
  15404. }
  15405. //html5 A[download]
  15406. if ('download' in a) {
  15407. var blob = new Blob(
  15408. [exporterOlderExcelCompatibility ? "\uFEFF" : '', csvContent],
  15409. { type: strMimeType }
  15410. );
  15411. rawFile = URL.createObjectURL(blob);
  15412. a.setAttribute('download', fileName);
  15413. } else {
  15414. rawFile = 'data:' + strMimeType + ',' + encodeURIComponent(csvContent);
  15415. a.setAttribute('target', '_blank');
  15416. }
  15417. a.href = rawFile;
  15418. a.setAttribute('style', 'display:none;');
  15419. D.body.appendChild(a);
  15420. setTimeout(function() {
  15421. if (a.click) {
  15422. a.click();
  15423. // Workaround for Safari 5
  15424. } else if (document.createEvent) {
  15425. var eventObj = document.createEvent('MouseEvents');
  15426. eventObj.initEvent('click', true, true);
  15427. a.dispatchEvent(eventObj);
  15428. }
  15429. D.body.removeChild(a);
  15430. }, this.delay);
  15431. },
  15432. /**
  15433. * @ngdoc function
  15434. * @name pdfExport
  15435. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15436. * @description Exports rows from the grid in pdf format,
  15437. * the data exported is selected based on the provided options.
  15438. * Note that this function has a dependency on pdfMake, which must
  15439. * be installed. The resulting pdf opens in a new
  15440. * browser window.
  15441. * @param {Grid} grid the grid from which data should be exported
  15442. * @param {string} rowTypes which rows to export, valid values are
  15443. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15444. * uiGridExporterConstants.SELECTED
  15445. * @param {string} colTypes which columns to export, valid values are
  15446. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15447. * uiGridExporterConstants.SELECTED
  15448. */
  15449. pdfExport: function (grid, rowTypes, colTypes) {
  15450. var self = this;
  15451. this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function () {
  15452. var exportColumnHeaders = self.getColumnHeaders(grid, colTypes);
  15453. var exportData = self.getData(grid, rowTypes, colTypes);
  15454. var docDefinition = self.prepareAsPdf(grid, exportColumnHeaders, exportData);
  15455. if (self.isIE()) {
  15456. self.downloadPDF(grid.options.exporterPdfFilename, docDefinition);
  15457. } else {
  15458. pdfMake.createPdf(docDefinition).open();
  15459. }
  15460. });
  15461. },
  15462. /**
  15463. * @ngdoc function
  15464. * @name downloadPdf
  15465. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15466. * @description Generates and retrieves the pdf as a blob, then downloads
  15467. * it as a file. Only used in IE, in all other browsers we use the native
  15468. * pdfMake.open function to just open the PDF
  15469. * @param {string} fileName the filename to give to the pdf, can be set
  15470. * through exporterPdfFilename
  15471. * @param {object} docDefinition a pdf docDefinition that we can generate
  15472. * and get a blob from
  15473. */
  15474. downloadPDF: function (fileName, docDefinition) {
  15475. var D = document;
  15476. var a = D.createElement('a');
  15477. var strMimeType = 'application/octet-stream;charset=utf-8';
  15478. var rawFile;
  15479. var ieVersion;
  15480. ieVersion = this.isIE();
  15481. var doc = pdfMake.createPdf(docDefinition);
  15482. var blob;
  15483. doc.getBuffer( function (buffer) {
  15484. blob = new Blob([buffer]);
  15485. if (ieVersion && ieVersion < 10) {
  15486. var frame = D.createElement('iframe');
  15487. document.body.appendChild(frame);
  15488. frame.contentWindow.document.open("text/html", "replace");
  15489. frame.contentWindow.document.write(blob);
  15490. frame.contentWindow.document.close();
  15491. frame.contentWindow.focus();
  15492. frame.contentWindow.document.execCommand('SaveAs', true, fileName);
  15493. document.body.removeChild(frame);
  15494. return true;
  15495. }
  15496. // IE10+
  15497. if (navigator.msSaveBlob) {
  15498. return navigator.msSaveBlob(
  15499. blob, fileName
  15500. );
  15501. }
  15502. });
  15503. },
  15504. /**
  15505. * @ngdoc function
  15506. * @name renderAsPdf
  15507. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15508. * @description Renders the data into a pdf, and opens that pdf.
  15509. *
  15510. * @param {Grid} grid the grid from which data should be exported
  15511. * @param {array} exportColumnHeaders an array of column headers,
  15512. * where each header is an object with name, width and maybe alignment
  15513. * @param {array} exportData an array of rows, where each row is
  15514. * an array of column data
  15515. * @returns {object} a pdfMake format document definition, ready
  15516. * for generation
  15517. */
  15518. prepareAsPdf: function(grid, exportColumnHeaders, exportData) {
  15519. var headerWidths = this.calculatePdfHeaderWidths( grid, exportColumnHeaders );
  15520. var headerColumns = exportColumnHeaders.map( function( header ) {
  15521. return { text: header.displayName, style: 'tableHeader' };
  15522. });
  15523. var stringData = exportData.map(this.formatRowAsPdf(this));
  15524. var allData = [headerColumns].concat(stringData);
  15525. var docDefinition = {
  15526. pageOrientation: grid.options.exporterPdfOrientation,
  15527. pageSize: grid.options.exporterPdfPageSize,
  15528. content: [{
  15529. style: 'tableStyle',
  15530. table: {
  15531. headerRows: 1,
  15532. widths: headerWidths,
  15533. body: allData
  15534. }
  15535. }],
  15536. styles: {
  15537. tableStyle: grid.options.exporterPdfTableStyle,
  15538. tableHeader: grid.options.exporterPdfTableHeaderStyle
  15539. },
  15540. defaultStyle: grid.options.exporterPdfDefaultStyle
  15541. };
  15542. if ( grid.options.exporterPdfLayout ){
  15543. docDefinition.layout = grid.options.exporterPdfLayout;
  15544. }
  15545. if ( grid.options.exporterPdfHeader ){
  15546. docDefinition.header = grid.options.exporterPdfHeader;
  15547. }
  15548. if ( grid.options.exporterPdfFooter ){
  15549. docDefinition.footer = grid.options.exporterPdfFooter;
  15550. }
  15551. if ( grid.options.exporterPdfCustomFormatter ){
  15552. docDefinition = grid.options.exporterPdfCustomFormatter( docDefinition );
  15553. }
  15554. return docDefinition;
  15555. },
  15556. /**
  15557. * @ngdoc function
  15558. * @name calculatePdfHeaderWidths
  15559. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15560. * @description Determines the column widths base on the
  15561. * widths we got from the grid. If the column is drawn
  15562. * then we have a drawnWidth. If the column is not visible
  15563. * then we have '*', 'x%' or a width. When columns are
  15564. * not visible they don't contribute to the overall gridWidth,
  15565. * so we need to adjust to allow for extra columns
  15566. *
  15567. * Our basic heuristic is to take the current gridWidth, plus
  15568. * numeric columns and call this the base gridwidth.
  15569. *
  15570. * To that we add 100 for any '*' column, and x% of the base gridWidth
  15571. * for any column that is a %
  15572. *
  15573. * @param {Grid} grid the grid from which data should be exported
  15574. * @param {array} exportHeaders array of header information
  15575. * @returns {object} an array of header widths
  15576. */
  15577. calculatePdfHeaderWidths: function ( grid, exportHeaders ) {
  15578. var baseGridWidth = 0;
  15579. exportHeaders.forEach( function(value){
  15580. if (typeof(value.width) === 'number'){
  15581. baseGridWidth += value.width;
  15582. }
  15583. });
  15584. var extraColumns = 0;
  15585. exportHeaders.forEach( function(value){
  15586. if (value.width === '*'){
  15587. extraColumns += 100;
  15588. }
  15589. if (typeof(value.width) === 'string' && value.width.match(/(\d)*%/)) {
  15590. var percent = parseInt(value.width.match(/(\d)*%/)[0]);
  15591. value.width = baseGridWidth * percent / 100;
  15592. extraColumns += value.width;
  15593. }
  15594. });
  15595. var gridWidth = baseGridWidth + extraColumns;
  15596. return exportHeaders.map(function( header ) {
  15597. return header.width === '*' ? header.width : header.width * grid.options.exporterPdfMaxGridWidth / gridWidth;
  15598. });
  15599. },
  15600. /**
  15601. * @ngdoc function
  15602. * @name formatRowAsPdf
  15603. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15604. * @description Renders a row in a format consumable by PDF,
  15605. * mainly meaning casting everything to a string
  15606. * @param {exporterService} exporter pass in exporter
  15607. * @param {array} row the row to be turned into a csv string
  15608. * @returns {string} a csv-ified version of the row
  15609. */
  15610. formatRowAsPdf: function ( exporter ) {
  15611. return function( row ) {
  15612. return row.map(exporter.formatFieldAsPdfString);
  15613. };
  15614. },
  15615. /**
  15616. * @ngdoc function
  15617. * @name formatFieldAsCsv
  15618. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15619. * @description Renders a single field as a pdf-able field, which
  15620. * is different from a csv field only in that strings don't have quotes
  15621. * around them
  15622. * @param {field} field the field to be turned into a pdf string,
  15623. * may be of any type
  15624. * @returns {string} a string-ified version of the field
  15625. */
  15626. formatFieldAsPdfString: function (field) {
  15627. var returnVal;
  15628. if (field.value == null) { // we want to catch anything null-ish, hence just == not ===
  15629. returnVal = '';
  15630. } else if (typeof(field.value) === 'number') {
  15631. returnVal = field.value.toString();
  15632. } else if (typeof(field.value) === 'boolean') {
  15633. returnVal = (field.value ? 'TRUE' : 'FALSE') ;
  15634. } else if (typeof(field.value) === 'string') {
  15635. returnVal = field.value.replace(/"/g,'""');
  15636. } else {
  15637. returnVal = JSON.stringify(field.value).replace(/^"/,'').replace(/"$/,'');
  15638. }
  15639. if (field.alignment && typeof(field.alignment) === 'string' ){
  15640. returnVal = { text: returnVal, alignment: field.alignment };
  15641. }
  15642. return returnVal;
  15643. }
  15644. };
  15645. return service;
  15646. }
  15647. ]);
  15648. /**
  15649. * @ngdoc directive
  15650. * @name ui.grid.exporter.directive:uiGridExporter
  15651. * @element div
  15652. * @restrict A
  15653. *
  15654. * @description Adds exporter features to grid
  15655. *
  15656. * @example
  15657. <example module="app">
  15658. <file name="app.js">
  15659. var app = angular.module('app', ['ui.grid', 'ui.grid.exporter']);
  15660. app.controller('MainCtrl', ['$scope', function ($scope) {
  15661. $scope.data = [
  15662. { name: 'Bob', title: 'CEO' },
  15663. { name: 'Frank', title: 'Lowly Developer' }
  15664. ];
  15665. $scope.gridOptions = {
  15666. enableGridMenu: true,
  15667. exporterMenuCsv: false,
  15668. columnDefs: [
  15669. {name: 'name', enableCellEdit: true},
  15670. {name: 'title', enableCellEdit: true}
  15671. ],
  15672. data: $scope.data
  15673. };
  15674. }]);
  15675. </file>
  15676. <file name="index.html">
  15677. <div ng-controller="MainCtrl">
  15678. <div ui-grid="gridOptions" ui-grid-exporter></div>
  15679. </div>
  15680. </file>
  15681. </example>
  15682. */
  15683. module.directive('uiGridExporter', ['uiGridExporterConstants', 'uiGridExporterService', 'gridUtil', '$compile',
  15684. function (uiGridExporterConstants, uiGridExporterService, gridUtil, $compile) {
  15685. return {
  15686. replace: true,
  15687. priority: 0,
  15688. require: '^uiGrid',
  15689. scope: false,
  15690. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  15691. uiGridExporterService.initializeGrid(uiGridCtrl.grid);
  15692. uiGridCtrl.grid.exporter.$scope = $scope;
  15693. }
  15694. };
  15695. }
  15696. ]);
  15697. })();
  15698. (function () {
  15699. 'use strict';
  15700. /**
  15701. * @ngdoc overview
  15702. * @name ui.grid.grouping
  15703. * @description
  15704. *
  15705. * # ui.grid.grouping
  15706. *
  15707. * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div>
  15708. *
  15709. * This module provides grouping of rows based on the data in them, similar
  15710. * in concept to excel grouping. You can group multiple columns, resulting in
  15711. * nested grouping.
  15712. *
  15713. * In concept this feature is similar to sorting + grid footer/aggregation, it
  15714. * sorts the data based on the grouped columns, then creates group rows that
  15715. * reflect a break in the data. Each of those group rows can have aggregations for
  15716. * the data within that group.
  15717. *
  15718. * This feature leverages treeBase to provide the tree functionality itself,
  15719. * the key thing this feature does therefore is to set treeLevels on the rows
  15720. * and insert the group headers.
  15721. *
  15722. * Design information:
  15723. * -------------------
  15724. *
  15725. * Each column will get new menu items - group by, and aggregate by. Group by
  15726. * will cause this column to be sorted (if not already), and will move this column
  15727. * to the front of the sorted columns (i.e. grouped columns take precedence over
  15728. * sorted columns). It will respect the sort order already set if there is one,
  15729. * and it will allow the sorting logic to change that sort order, it just forces
  15730. * the column to the front of the sorting. You can group by multiple columns, the
  15731. * logic will add this column to the sorting after any already grouped columns.
  15732. *
  15733. * Once a grouping is defined, grouping logic is added to the rowsProcessors. This
  15734. * will process the rows, identifying a break in the data value, and inserting a grouping row.
  15735. * Grouping rows have specific attributes on them:
  15736. *
  15737. * - internalRow = true: tells us that this isn't a real row, so we can ignore it
  15738. * from any processing that it looking at core data rows. This is used by the core
  15739. * logic (or will be one day), as it's not grouping specific
  15740. * - groupHeader = true: tells us this is a groupHeader. This is used by the grouping logic
  15741. * to know if this is a groupHeader row or not
  15742. *
  15743. * Since the logic is baked into the rowsProcessors, it should get triggered whenever
  15744. * row order or filtering or anything like that is changed. In order to avoid the row instantiation
  15745. * time, and to preserve state across invocations, we hold a cache of the rows that we created
  15746. * last time, and we use them again this time if we can.
  15747. *
  15748. * By default rows are collapsed, which means all data rows have their visible property
  15749. * set to false, and only level 0 group rows are set to visible.
  15750. *
  15751. * <br/>
  15752. * <br/>
  15753. *
  15754. * <div doc-module-components="ui.grid.grouping"></div>
  15755. */
  15756. var module = angular.module('ui.grid.grouping', ['ui.grid', 'ui.grid.treeBase']);
  15757. /**
  15758. * @ngdoc object
  15759. * @name ui.grid.grouping.constant:uiGridGroupingConstants
  15760. *
  15761. * @description constants available in grouping module, this includes
  15762. * all the constants declared in the treeBase module (these are manually copied
  15763. * as there isn't an easy way to include constants in another constants file, and
  15764. * we don't want to make users include treeBase)
  15765. *
  15766. */
  15767. module.constant('uiGridGroupingConstants', {
  15768. featureName: "grouping",
  15769. rowHeaderColName: 'treeBaseRowHeaderCol',
  15770. EXPANDED: 'expanded',
  15771. COLLAPSED: 'collapsed',
  15772. aggregation: {
  15773. COUNT: 'count',
  15774. SUM: 'sum',
  15775. MAX: 'max',
  15776. MIN: 'min',
  15777. AVG: 'avg'
  15778. }
  15779. });
  15780. /**
  15781. * @ngdoc service
  15782. * @name ui.grid.grouping.service:uiGridGroupingService
  15783. *
  15784. * @description Services for grouping features
  15785. */
  15786. module.service('uiGridGroupingService', ['$q', 'uiGridGroupingConstants', 'gridUtil', 'rowSorter', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'uiGridTreeBaseService',
  15787. function ($q, uiGridGroupingConstants, gridUtil, rowSorter, GridRow, gridClassFactory, i18nService, uiGridConstants, uiGridTreeBaseService) {
  15788. var service = {
  15789. initializeGrid: function (grid, $scope) {
  15790. uiGridTreeBaseService.initializeGrid( grid, $scope );
  15791. //add feature namespace and any properties to grid for needed
  15792. /**
  15793. * @ngdoc object
  15794. * @name ui.grid.grouping.grid:grouping
  15795. *
  15796. * @description Grid properties and functions added for grouping
  15797. */
  15798. grid.grouping = {};
  15799. /**
  15800. * @ngdoc property
  15801. * @propertyOf ui.grid.grouping.grid:grouping
  15802. * @name groupHeaderCache
  15803. *
  15804. * @description Cache that holds the group header rows we created last time, we'll
  15805. * reuse these next time, not least because they hold our expanded states.
  15806. *
  15807. * We need to take care with these that they don't become a memory leak, we
  15808. * create a new cache each time using the values from the old cache. This works
  15809. * so long as we're creating group rows for invisible rows as well.
  15810. *
  15811. * The cache is a nested hash, indexed on the value we grouped by. So if we
  15812. * grouped by gender then age, we'd maybe have something like:
  15813. * ```
  15814. * {
  15815. * male: {
  15816. * row: <pointer to the old row>,
  15817. * children: {
  15818. * 22: { row: <pointer to the old row> },
  15819. * 31: { row: <pointer to the old row> }
  15820. * },
  15821. * female: {
  15822. * row: <pointer to the old row>,
  15823. * children: {
  15824. * 28: { row: <pointer to the old row> },
  15825. * 55: { row: <pointer to the old row> }
  15826. * }
  15827. * }
  15828. * ```
  15829. *
  15830. * We create new rows for any missing rows, this means that they come in as collapsed.
  15831. *
  15832. */
  15833. grid.grouping.groupHeaderCache = {};
  15834. service.defaultGridOptions(grid.options);
  15835. grid.registerRowsProcessor(service.groupRows, 400);
  15836. grid.registerColumnBuilder( service.groupingColumnBuilder);
  15837. grid.registerColumnsProcessor(service.groupingColumnProcessor, 400);
  15838. /**
  15839. * @ngdoc object
  15840. * @name ui.grid.grouping.api:PublicApi
  15841. *
  15842. * @description Public Api for grouping feature
  15843. */
  15844. var publicApi = {
  15845. events: {
  15846. grouping: {
  15847. /**
  15848. * @ngdoc event
  15849. * @eventOf ui.grid.grouping.api:PublicApi
  15850. * @name aggregationChanged
  15851. * @description raised whenever aggregation is changed, added or removed from a column
  15852. *
  15853. * <pre>
  15854. * gridApi.grouping.on.aggregationChanged(scope,function(col){})
  15855. * </pre>
  15856. * @param {gridCol} col the column which on which aggregation changed. The aggregation
  15857. * type is available as `col.treeAggregation.type`
  15858. */
  15859. aggregationChanged: {},
  15860. /**
  15861. * @ngdoc event
  15862. * @eventOf ui.grid.grouping.api:PublicApi
  15863. * @name groupingChanged
  15864. * @description raised whenever the grouped columns changes
  15865. *
  15866. * <pre>
  15867. * gridApi.grouping.on.groupingChanged(scope,function(col){})
  15868. * </pre>
  15869. * @param {gridCol} col the column which on which grouping changed. The new grouping is
  15870. * available as `col.grouping`
  15871. */
  15872. groupingChanged: {}
  15873. }
  15874. },
  15875. methods: {
  15876. grouping: {
  15877. /**
  15878. * @ngdoc function
  15879. * @name getGrouping
  15880. * @methodOf ui.grid.grouping.api:PublicApi
  15881. * @description Get the grouping configuration for this grid,
  15882. * used by the saveState feature. Adds expandedState to the information
  15883. * provided by the internal getGrouping, and removes any aggregations that have a source
  15884. * of grouping (i.e. will be automatically reapplied when we regroup the column)
  15885. * Returned grouping is an object
  15886. * `{ grouping: groupArray, treeAggregations: aggregateArray, expandedState: hash }`
  15887. * where grouping contains an array of objects:
  15888. * `{ field: column.field, colName: column.name, groupPriority: column.grouping.groupPriority }`
  15889. * and aggregations contains an array of objects:
  15890. * `{ field: column.field, colName: column.name, aggregation: column.grouping.aggregation }`
  15891. * and expandedState is a hash of the currently expanded nodes
  15892. *
  15893. * The groupArray will be sorted by groupPriority.
  15894. *
  15895. * @param {boolean} getExpanded whether or not to return the expanded state
  15896. * @returns {object} grouping configuration
  15897. */
  15898. getGrouping: function ( getExpanded ) {
  15899. var grouping = service.getGrouping(grid);
  15900. grouping.grouping.forEach( function( group ) {
  15901. group.colName = group.col.name;
  15902. delete group.col;
  15903. });
  15904. grouping.aggregations.forEach( function( aggregation ) {
  15905. aggregation.colName = aggregation.col.name;
  15906. delete aggregation.col;
  15907. });
  15908. grouping.aggregations = grouping.aggregations.filter( function( aggregation ){
  15909. return !aggregation.aggregation.source || aggregation.aggregation.source !== 'grouping';
  15910. });
  15911. if ( getExpanded ){
  15912. grouping.rowExpandedStates = service.getRowExpandedStates( grid.grouping.groupingHeaderCache );
  15913. }
  15914. return grouping;
  15915. },
  15916. /**
  15917. * @ngdoc function
  15918. * @name setGrouping
  15919. * @methodOf ui.grid.grouping.api:PublicApi
  15920. * @description Set the grouping configuration for this grid,
  15921. * used by the saveState feature, but can also be used by any
  15922. * user to specify a combined grouping and aggregation configuration
  15923. * @param {object} config the config you want to apply, in the format
  15924. * provided out by getGrouping
  15925. */
  15926. setGrouping: function ( config ) {
  15927. service.setGrouping(grid, config);
  15928. },
  15929. /**
  15930. * @ngdoc function
  15931. * @name groupColumn
  15932. * @methodOf ui.grid.grouping.api:PublicApi
  15933. * @description Adds this column to the existing grouping, at the end of the priority order.
  15934. * If the column doesn't have a sort, adds one, by default ASC
  15935. *
  15936. * This column will move to the left of any non-group columns, the
  15937. * move is handled in a columnProcessor, so gets called as part of refresh
  15938. *
  15939. * @param {string} columnName the name of the column we want to group
  15940. */
  15941. groupColumn: function( columnName ) {
  15942. var column = grid.getColumn(columnName);
  15943. service.groupColumn(grid, column);
  15944. },
  15945. /**
  15946. * @ngdoc function
  15947. * @name ungroupColumn
  15948. * @methodOf ui.grid.grouping.api:PublicApi
  15949. * @description Removes the groupPriority from this column. If the
  15950. * column was previously aggregated the aggregation will come back.
  15951. * The sort will remain.
  15952. *
  15953. * This column will move to the right of any other group columns, the
  15954. * move is handled in a columnProcessor, so gets called as part of refresh
  15955. *
  15956. * @param {string} columnName the name of the column we want to ungroup
  15957. */
  15958. ungroupColumn: function( columnName ) {
  15959. var column = grid.getColumn(columnName);
  15960. service.ungroupColumn(grid, column);
  15961. },
  15962. /**
  15963. * @ngdoc function
  15964. * @name clearGrouping
  15965. * @methodOf ui.grid.grouping.api:PublicApi
  15966. * @description Clear any grouped columns and any aggregations. Doesn't remove sorting,
  15967. * as we don't know whether that sorting was added by grouping or was there beforehand
  15968. *
  15969. */
  15970. clearGrouping: function() {
  15971. service.clearGrouping(grid);
  15972. },
  15973. /**
  15974. * @ngdoc function
  15975. * @name aggregateColumn
  15976. * @methodOf ui.grid.grouping.api:PublicApi
  15977. * @description Sets the aggregation type on a column, if the
  15978. * column is currently grouped then it removes the grouping first.
  15979. * If the aggregationDef is null then will result in the aggregation
  15980. * being removed
  15981. *
  15982. * @param {string} columnName the column we want to aggregate
  15983. * @param {string} or {function} aggregationDef one of the recognised types
  15984. * from uiGridGroupingConstants or a custom aggregation function.
  15985. * @param {string} aggregationLabel (optional) The label to use for this aggregation.
  15986. */
  15987. aggregateColumn: function( columnName, aggregationDef, aggregationLabel){
  15988. var column = grid.getColumn(columnName);
  15989. service.aggregateColumn( grid, column, aggregationDef, aggregationLabel);
  15990. }
  15991. }
  15992. }
  15993. };
  15994. grid.api.registerEventsFromObject(publicApi.events);
  15995. grid.api.registerMethodsFromObject(publicApi.methods);
  15996. grid.api.core.on.sortChanged( $scope, service.tidyPriorities);
  15997. },
  15998. defaultGridOptions: function (gridOptions) {
  15999. //default option to true unless it was explicitly set to false
  16000. /**
  16001. * @ngdoc object
  16002. * @name ui.grid.grouping.api:GridOptions
  16003. *
  16004. * @description GridOptions for grouping feature, these are available to be
  16005. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  16006. */
  16007. /**
  16008. * @ngdoc object
  16009. * @name enableGrouping
  16010. * @propertyOf ui.grid.grouping.api:GridOptions
  16011. * @description Enable row grouping for entire grid.
  16012. * <br/>Defaults to true
  16013. */
  16014. gridOptions.enableGrouping = gridOptions.enableGrouping !== false;
  16015. /**
  16016. * @ngdoc object
  16017. * @name groupingShowCounts
  16018. * @propertyOf ui.grid.grouping.api:GridOptions
  16019. * @description shows counts on the groupHeader rows. Not that if you are using a cellFilter or a
  16020. * sortingAlgorithm which relies on a specific format or data type, showing counts may cause that
  16021. * to break, since the group header rows will always be a string with groupingShowCounts enabled.
  16022. * <br/>Defaults to true except on columns of type 'date'
  16023. */
  16024. gridOptions.groupingShowCounts = gridOptions.groupingShowCounts !== false;
  16025. /**
  16026. * @ngdoc object
  16027. * @name groupingNullLabel
  16028. * @propertyOf ui.grid.grouping.api:GridOptions
  16029. * @description The string to use for the grouping header row label on rows which contain a null or undefined value in the grouped column.
  16030. * <br/>Defaults to "Null"
  16031. */
  16032. gridOptions.groupingNullLabel = typeof(gridOptions.groupingNullLabel) === 'undefined' ? 'Null' : gridOptions.groupingNullLabel;
  16033. /**
  16034. * @ngdoc object
  16035. * @name enableGroupHeaderSelection
  16036. * @propertyOf ui.grid.grouping.api:GridOptions
  16037. * @description Allows group header rows to be selected.
  16038. * <br/>Defaults to false
  16039. */
  16040. gridOptions.enableGroupHeaderSelection = gridOptions.enableGroupHeaderSelection === true;
  16041. },
  16042. /**
  16043. * @ngdoc function
  16044. * @name groupingColumnBuilder
  16045. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16046. * @description Sets the grouping defaults based on the columnDefs
  16047. *
  16048. * @param {object} colDef columnDef we're basing on
  16049. * @param {GridCol} col the column we're to update
  16050. * @param {object} gridOptions the options we should use
  16051. * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved
  16052. */
  16053. groupingColumnBuilder: function (colDef, col, gridOptions) {
  16054. /**
  16055. * @ngdoc object
  16056. * @name ui.grid.grouping.api:ColumnDef
  16057. *
  16058. * @description ColumnDef for grouping feature, these are available to be
  16059. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  16060. */
  16061. /**
  16062. * @ngdoc object
  16063. * @name enableGrouping
  16064. * @propertyOf ui.grid.grouping.api:ColumnDef
  16065. * @description Enable grouping on this column
  16066. * <br/>Defaults to true.
  16067. */
  16068. if (colDef.enableGrouping === false){
  16069. return;
  16070. }
  16071. /**
  16072. * @ngdoc object
  16073. * @name grouping
  16074. * @propertyOf ui.grid.grouping.api:ColumnDef
  16075. * @description Set the grouping for a column. Format is:
  16076. * ```
  16077. * {
  16078. * groupPriority: <number, starts at 0, if less than 0 or undefined then we're aggregating in this column>
  16079. * }
  16080. * ```
  16081. *
  16082. * **Note that aggregation used to be included in grouping, but is now separately set on the column via treeAggregation
  16083. * setting in treeBase**
  16084. *
  16085. * We group in the priority order given, this will also put these columns to the high order of the sort irrespective
  16086. * of the sort priority given them. If there is no sort defined then we sort ascending, if there is a sort defined then
  16087. * we use that sort.
  16088. *
  16089. * If the groupPriority is undefined or less than 0, then we expect to be aggregating, and we look at the
  16090. * aggregation types to determine what sort of aggregation we can do. Values are in the constants file, but
  16091. * include SUM, COUNT, MAX, MIN
  16092. *
  16093. * groupPriorities should generally be sequential, if they're not then the next time getGrouping is called
  16094. * we'll renumber them to be sequential.
  16095. * <br/>Defaults to undefined.
  16096. */
  16097. if ( typeof(col.grouping) === 'undefined' && typeof(colDef.grouping) !== 'undefined') {
  16098. col.grouping = angular.copy(colDef.grouping);
  16099. if ( typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority > -1 ){
  16100. col.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn;
  16101. col.treeAggregationFinalizerFn = service.groupedFinalizerFn;
  16102. }
  16103. } else if (typeof(col.grouping) === 'undefined'){
  16104. col.grouping = {};
  16105. }
  16106. if (typeof(col.grouping) !== 'undefined' && typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority >= 0){
  16107. col.suppressRemoveSort = true;
  16108. }
  16109. var groupColumn = {
  16110. name: 'ui.grid.grouping.group',
  16111. title: i18nService.get().grouping.group,
  16112. icon: 'ui-grid-icon-indent-right',
  16113. shown: function () {
  16114. return typeof(this.context.col.grouping) === 'undefined' ||
  16115. typeof(this.context.col.grouping.groupPriority) === 'undefined' ||
  16116. this.context.col.grouping.groupPriority < 0;
  16117. },
  16118. action: function () {
  16119. service.groupColumn( this.context.col.grid, this.context.col );
  16120. }
  16121. };
  16122. var ungroupColumn = {
  16123. name: 'ui.grid.grouping.ungroup',
  16124. title: i18nService.get().grouping.ungroup,
  16125. icon: 'ui-grid-icon-indent-left',
  16126. shown: function () {
  16127. return typeof(this.context.col.grouping) !== 'undefined' &&
  16128. typeof(this.context.col.grouping.groupPriority) !== 'undefined' &&
  16129. this.context.col.grouping.groupPriority >= 0;
  16130. },
  16131. action: function () {
  16132. service.ungroupColumn( this.context.col.grid, this.context.col );
  16133. }
  16134. };
  16135. var aggregateRemove = {
  16136. name: 'ui.grid.grouping.aggregateRemove',
  16137. title: i18nService.get().grouping.aggregate_remove,
  16138. shown: function () {
  16139. return typeof(this.context.col.treeAggregationFn) !== 'undefined';
  16140. },
  16141. action: function () {
  16142. service.aggregateColumn( this.context.col.grid, this.context.col, null);
  16143. }
  16144. };
  16145. // generic adder for the aggregation menus, which follow a pattern
  16146. var addAggregationMenu = function(type, title){
  16147. title = title || i18nService.get().grouping['aggregate_' + type] || type;
  16148. var menuItem = {
  16149. name: 'ui.grid.grouping.aggregate' + type,
  16150. title: title,
  16151. shown: function () {
  16152. return typeof(this.context.col.treeAggregation) === 'undefined' ||
  16153. typeof(this.context.col.treeAggregation.type) === 'undefined' ||
  16154. this.context.col.treeAggregation.type !== type;
  16155. },
  16156. action: function () {
  16157. service.aggregateColumn( this.context.col.grid, this.context.col, type);
  16158. }
  16159. };
  16160. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregate' + type)) {
  16161. col.menuItems.push(menuItem);
  16162. }
  16163. };
  16164. /**
  16165. * @ngdoc object
  16166. * @name groupingShowGroupingMenu
  16167. * @propertyOf ui.grid.grouping.api:ColumnDef
  16168. * @description Show the grouping (group and ungroup items) menu on this column
  16169. * <br/>Defaults to true.
  16170. */
  16171. if ( col.colDef.groupingShowGroupingMenu !== false ){
  16172. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.group')) {
  16173. col.menuItems.push(groupColumn);
  16174. }
  16175. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.ungroup')) {
  16176. col.menuItems.push(ungroupColumn);
  16177. }
  16178. }
  16179. /**
  16180. * @ngdoc object
  16181. * @name groupingShowAggregationMenu
  16182. * @propertyOf ui.grid.grouping.api:ColumnDef
  16183. * @description Show the aggregation menu on this column
  16184. * <br/>Defaults to true.
  16185. */
  16186. if ( col.colDef.groupingShowAggregationMenu !== false ){
  16187. angular.forEach(uiGridTreeBaseService.nativeAggregations(), function(aggregationDef, name){
  16188. addAggregationMenu(name);
  16189. });
  16190. angular.forEach(gridOptions.treeCustomAggregations, function(aggregationDef, name){
  16191. addAggregationMenu(name, aggregationDef.menuTitle);
  16192. });
  16193. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregateRemove')) {
  16194. col.menuItems.push(aggregateRemove);
  16195. }
  16196. }
  16197. },
  16198. /**
  16199. * @ngdoc function
  16200. * @name groupingColumnProcessor
  16201. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16202. * @description Moves the columns around based on which are grouped
  16203. *
  16204. * @param {array} columns the columns to consider rendering
  16205. * @param {array} rows the grid rows, which we don't use but are passed to us
  16206. * @returns {array} updated columns array
  16207. */
  16208. groupingColumnProcessor: function( columns, rows ) {
  16209. var grid = this;
  16210. columns = service.moveGroupColumns(this, columns, rows);
  16211. return columns;
  16212. },
  16213. /**
  16214. * @ngdoc function
  16215. * @name groupedFinalizerFn
  16216. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16217. * @description Used on group columns to display the rendered value and optionally
  16218. * display the count of rows.
  16219. *
  16220. * @param {aggregation} the aggregation entity for a grouped column
  16221. */
  16222. groupedFinalizerFn: function( aggregation ){
  16223. var col = this;
  16224. if ( typeof(aggregation.groupVal) !== 'undefined') {
  16225. aggregation.rendered = aggregation.groupVal;
  16226. if ( col.grid.options.groupingShowCounts && col.colDef.type !== 'date' ){
  16227. aggregation.rendered += (' (' + aggregation.value + ')');
  16228. }
  16229. } else {
  16230. aggregation.rendered = null;
  16231. }
  16232. },
  16233. /**
  16234. * @ngdoc function
  16235. * @name moveGroupColumns
  16236. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16237. * @description Moves the column order so that the grouped columns are lined up
  16238. * to the left (well, unless you're RTL, then it's the right). By doing this in
  16239. * the columnsProcessor, we make it transient - when the column is ungrouped it'll
  16240. * go back to where it was.
  16241. *
  16242. * Does nothing if the option `moveGroupColumns` is set to false.
  16243. *
  16244. * @param {Grid} grid grid object
  16245. * @param {array} columns the columns that we should process/move
  16246. * @param {array} rows the grid rows
  16247. * @returns {array} updated columns
  16248. */
  16249. moveGroupColumns: function( grid, columns, rows ){
  16250. if ( grid.options.moveGroupColumns === false){
  16251. return columns;
  16252. }
  16253. columns.forEach( function(column, index){
  16254. // position used to make stable sort in moveGroupColumns
  16255. column.groupingPosition = index;
  16256. });
  16257. columns.sort(function(a, b){
  16258. var a_group, b_group;
  16259. if (a.isRowHeader){
  16260. a_group = -1000;
  16261. }
  16262. else if ( typeof(a.grouping) === 'undefined' || typeof(a.grouping.groupPriority) === 'undefined' || a.grouping.groupPriority < 0){
  16263. a_group = null;
  16264. } else {
  16265. a_group = a.grouping.groupPriority;
  16266. }
  16267. if (b.isRowHeader){
  16268. b_group = -1000;
  16269. }
  16270. else if ( typeof(b.grouping) === 'undefined' || typeof(b.grouping.groupPriority) === 'undefined' || b.grouping.groupPriority < 0){
  16271. b_group = null;
  16272. } else {
  16273. b_group = b.grouping.groupPriority;
  16274. }
  16275. // groups get sorted to the top
  16276. if ( a_group !== null && b_group === null) { return -1; }
  16277. if ( b_group !== null && a_group === null) { return 1; }
  16278. if ( a_group !== null && b_group !== null) {return a_group - b_group; }
  16279. return a.groupingPosition - b.groupingPosition;
  16280. });
  16281. columns.forEach( function(column, index) {
  16282. delete column.groupingPosition;
  16283. });
  16284. return columns;
  16285. },
  16286. /**
  16287. * @ngdoc function
  16288. * @name groupColumn
  16289. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16290. * @description Adds this column to the existing grouping, at the end of the priority order.
  16291. * If the column doesn't have a sort, adds one, by default ASC
  16292. *
  16293. * This column will move to the left of any non-group columns, the
  16294. * move is handled in a columnProcessor, so gets called as part of refresh
  16295. *
  16296. * @param {Grid} grid grid object
  16297. * @param {GridCol} column the column we want to group
  16298. */
  16299. groupColumn: function( grid, column){
  16300. if ( typeof(column.grouping) === 'undefined' ){
  16301. column.grouping = {};
  16302. }
  16303. // set the group priority to the next number in the hierarchy
  16304. var existingGrouping = service.getGrouping( grid );
  16305. column.grouping.groupPriority = existingGrouping.grouping.length;
  16306. // add sort if not present
  16307. if ( !column.sort ){
  16308. column.sort = { direction: uiGridConstants.ASC };
  16309. } else if ( typeof(column.sort.direction) === 'undefined' || column.sort.direction === null ){
  16310. column.sort.direction = uiGridConstants.ASC;
  16311. }
  16312. column.treeAggregation = { type: uiGridGroupingConstants.aggregation.COUNT, source: 'grouping' };
  16313. column.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn;
  16314. column.treeAggregationFinalizerFn = service.groupedFinalizerFn;
  16315. grid.api.grouping.raise.groupingChanged(column);
  16316. // This indirectly calls service.tidyPriorities( grid );
  16317. grid.api.core.raise.sortChanged(grid, grid.getColumnSorting());
  16318. grid.queueGridRefresh();
  16319. },
  16320. /**
  16321. * @ngdoc function
  16322. * @name ungroupColumn
  16323. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16324. * @description Removes the groupPriority from this column. If the
  16325. * column was previously aggregated the aggregation will come back.
  16326. * The sort will remain.
  16327. *
  16328. * This column will move to the right of any other group columns, the
  16329. * move is handled in a columnProcessor, so gets called as part of refresh
  16330. *
  16331. * @param {Grid} grid grid object
  16332. * @param {GridCol} column the column we want to ungroup
  16333. */
  16334. ungroupColumn: function( grid, column){
  16335. if ( typeof(column.grouping) === 'undefined' ){
  16336. return;
  16337. }
  16338. delete column.grouping.groupPriority;
  16339. delete column.treeAggregation;
  16340. delete column.customTreeAggregationFinalizer;
  16341. service.tidyPriorities( grid );
  16342. grid.api.grouping.raise.groupingChanged(column);
  16343. grid.queueGridRefresh();
  16344. },
  16345. /**
  16346. * @ngdoc function
  16347. * @name aggregateColumn
  16348. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16349. * @description Sets the aggregation type on a column, if the
  16350. * column is currently grouped then it removes the grouping first.
  16351. *
  16352. * @param {Grid} grid grid object
  16353. * @param {GridCol} column the column we want to aggregate
  16354. * @param {string} one of the recognised types from uiGridGroupingConstants or one of the custom aggregations from gridOptions
  16355. */
  16356. aggregateColumn: function( grid, column, aggregationType){
  16357. if (typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){
  16358. service.ungroupColumn( grid, column );
  16359. }
  16360. var aggregationDef = {};
  16361. if ( typeof(grid.options.treeCustomAggregations[aggregationType]) !== 'undefined' ){
  16362. aggregationDef = grid.options.treeCustomAggregations[aggregationType];
  16363. } else if ( typeof(uiGridTreeBaseService.nativeAggregations()[aggregationType]) !== 'undefined' ){
  16364. aggregationDef = uiGridTreeBaseService.nativeAggregations()[aggregationType];
  16365. }
  16366. column.treeAggregation = { type: aggregationType, label: i18nService.get().aggregation[aggregationDef.label] || aggregationDef.label };
  16367. column.treeAggregationFn = aggregationDef.aggregationFn;
  16368. column.treeAggregationFinalizerFn = aggregationDef.finalizerFn;
  16369. grid.api.grouping.raise.aggregationChanged(column);
  16370. grid.queueGridRefresh();
  16371. },
  16372. /**
  16373. * @ngdoc function
  16374. * @name setGrouping
  16375. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16376. * @description Set the grouping based on a config object, used by the save state feature
  16377. * (more specifically, by the restore function in that feature )
  16378. *
  16379. * @param {Grid} grid grid object
  16380. * @param {object} config the config we want to set, same format as that returned by getGrouping
  16381. */
  16382. setGrouping: function ( grid, config ){
  16383. if ( typeof(config) === 'undefined' ){
  16384. return;
  16385. }
  16386. // first remove any existing grouping
  16387. service.clearGrouping(grid);
  16388. if ( config.grouping && config.grouping.length && config.grouping.length > 0 ){
  16389. config.grouping.forEach( function( group ) {
  16390. var col = grid.getColumn(group.colName);
  16391. if ( col ) {
  16392. service.groupColumn( grid, col );
  16393. }
  16394. });
  16395. }
  16396. if ( config.aggregations && config.aggregations.length ){
  16397. config.aggregations.forEach( function( aggregation ) {
  16398. var col = grid.getColumn(aggregation.colName);
  16399. if ( col ) {
  16400. service.aggregateColumn( grid, col, aggregation.aggregation.type );
  16401. }
  16402. });
  16403. }
  16404. if ( config.rowExpandedStates ){
  16405. service.applyRowExpandedStates( grid.grouping.groupingHeaderCache, config.rowExpandedStates );
  16406. }
  16407. },
  16408. /**
  16409. * @ngdoc function
  16410. * @name clearGrouping
  16411. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16412. * @description Clear any grouped columns and any aggregations. Doesn't remove sorting,
  16413. * as we don't know whether that sorting was added by grouping or was there beforehand
  16414. *
  16415. * @param {Grid} grid grid object
  16416. */
  16417. clearGrouping: function( grid ) {
  16418. var currentGrouping = service.getGrouping(grid);
  16419. if ( currentGrouping.grouping.length > 0 ){
  16420. currentGrouping.grouping.forEach( function( group ) {
  16421. if (!group.col){
  16422. // should have a group.colName if there's no col
  16423. group.col = grid.getColumn(group.colName);
  16424. }
  16425. service.ungroupColumn(grid, group.col);
  16426. });
  16427. }
  16428. if ( currentGrouping.aggregations.length > 0 ){
  16429. currentGrouping.aggregations.forEach( function( aggregation ){
  16430. if (!aggregation.col){
  16431. // should have a group.colName if there's no col
  16432. aggregation.col = grid.getColumn(aggregation.colName);
  16433. }
  16434. service.aggregateColumn(grid, aggregation.col, null);
  16435. });
  16436. }
  16437. },
  16438. /**
  16439. * @ngdoc function
  16440. * @name tidyPriorities
  16441. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16442. * @description Renumbers groupPriority and sortPriority such that
  16443. * groupPriority is contiguous, and sortPriority either matches
  16444. * groupPriority (for group columns), and otherwise is contiguous and
  16445. * higher than groupPriority.
  16446. *
  16447. * @param {Grid} grid grid object
  16448. */
  16449. tidyPriorities: function( grid ){
  16450. // if we're called from sortChanged, grid is in this, not passed as param, the param can be a column or undefined
  16451. if ( ( typeof(grid) === 'undefined' || typeof(grid.grid) !== 'undefined' ) && typeof(this.grid) !== 'undefined' ) {
  16452. grid = this.grid;
  16453. }
  16454. var groupArray = [];
  16455. var sortArray = [];
  16456. grid.columns.forEach( function(column, index){
  16457. if ( typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){
  16458. groupArray.push(column);
  16459. } else if ( typeof(column.sort) !== 'undefined' && typeof(column.sort.priority) !== 'undefined' && column.sort.priority >= 0){
  16460. sortArray.push(column);
  16461. }
  16462. });
  16463. groupArray.sort(function(a, b){ return a.grouping.groupPriority - b.grouping.groupPriority; });
  16464. groupArray.forEach( function(column, index){
  16465. column.grouping.groupPriority = index;
  16466. column.suppressRemoveSort = true;
  16467. if ( typeof(column.sort) === 'undefined'){
  16468. column.sort = {};
  16469. }
  16470. column.sort.priority = index;
  16471. });
  16472. var i = groupArray.length;
  16473. sortArray.sort(function(a, b){ return a.sort.priority - b.sort.priority; });
  16474. sortArray.forEach( function(column, index){
  16475. column.sort.priority = i;
  16476. column.suppressRemoveSort = column.colDef.suppressRemoveSort;
  16477. i++;
  16478. });
  16479. },
  16480. /**
  16481. * @ngdoc function
  16482. * @name groupRows
  16483. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16484. * @description The rowProcessor that creates the groupHeaders (i.e. does
  16485. * the actual grouping).
  16486. *
  16487. * Assumes it is always called after the sorting processor, guaranteed by the priority setting
  16488. *
  16489. * Processes all the rows in order, inserting a groupHeader row whenever there is a change
  16490. * in value of a grouped row, based on the sortAlgorithm used for the column. The group header row
  16491. * is looked up in the groupHeaderCache, and used from there if there is one. The entity is reset
  16492. * to {} if one is found.
  16493. *
  16494. * As it processes it maintains a `processingState` array. This records, for each level of grouping we're
  16495. * working with, the following information:
  16496. * ```
  16497. * {
  16498. * fieldName: name,
  16499. * col: col,
  16500. * initialised: boolean,
  16501. * currentValue: value,
  16502. * currentRow: gridRow,
  16503. * }
  16504. * ```
  16505. * We look for changes in the currentValue at any of the levels. Where we find a change we:
  16506. *
  16507. * - create a new groupHeader row in the array
  16508. *
  16509. * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor
  16510. * @returns {array} the updated rows, including our new group rows
  16511. */
  16512. groupRows: function( renderableRows ) {
  16513. if (renderableRows.length === 0){
  16514. return renderableRows;
  16515. }
  16516. var grid = this;
  16517. grid.grouping.oldGroupingHeaderCache = grid.grouping.groupingHeaderCache || {};
  16518. grid.grouping.groupingHeaderCache = {};
  16519. var processingState = service.initialiseProcessingState( grid );
  16520. // processes each of the fields we are grouping by, checks if the value has changed and inserts a groupHeader
  16521. // Broken out as shouldn't create functions in a loop.
  16522. var updateProcessingState = function( groupFieldState, stateIndex ) {
  16523. var fieldValue = grid.getCellValue(row, groupFieldState.col);
  16524. // look for change of value - and insert a header
  16525. if ( !groupFieldState.initialised || rowSorter.getSortFn(grid, groupFieldState.col, renderableRows)(fieldValue, groupFieldState.currentValue) !== 0 ){
  16526. service.insertGroupHeader( grid, renderableRows, i, processingState, stateIndex );
  16527. i++;
  16528. }
  16529. };
  16530. // use a for loop because it's tolerant of the array length changing whilst we go - we can
  16531. // manipulate the iterator when we insert groupHeader rows
  16532. for (var i = 0; i < renderableRows.length; i++ ){
  16533. var row = renderableRows[i];
  16534. if ( row.visible ){
  16535. processingState.forEach( updateProcessingState );
  16536. }
  16537. }
  16538. delete grid.grouping.oldGroupingHeaderCache;
  16539. return renderableRows;
  16540. },
  16541. /**
  16542. * @ngdoc function
  16543. * @name initialiseProcessingState
  16544. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16545. * @description Creates the processing state array that is used
  16546. * for groupRows.
  16547. *
  16548. * @param {Grid} grid grid object
  16549. * @returns {array} an array in the format described in the groupRows method,
  16550. * initialised with blank values
  16551. */
  16552. initialiseProcessingState: function( grid ){
  16553. var processingState = [];
  16554. var columnSettings = service.getGrouping( grid );
  16555. columnSettings.grouping.forEach( function( groupItem, index){
  16556. processingState.push({
  16557. fieldName: groupItem.field,
  16558. col: groupItem.col,
  16559. initialised: false,
  16560. currentValue: null,
  16561. currentRow: null
  16562. });
  16563. });
  16564. return processingState;
  16565. },
  16566. /**
  16567. * @ngdoc function
  16568. * @name getGrouping
  16569. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16570. * @description Get the grouping settings from the columns. As a side effect
  16571. * this always renumbers the grouping starting at 0
  16572. * @param {Grid} grid grid object
  16573. * @returns {array} an array of the group fields, in order of priority
  16574. */
  16575. getGrouping: function( grid ){
  16576. var groupArray = [];
  16577. var aggregateArray = [];
  16578. // get all the grouping
  16579. grid.columns.forEach( function(column, columnIndex){
  16580. if ( column.grouping ){
  16581. if ( typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){
  16582. groupArray.push({ field: column.field, col: column, groupPriority: column.grouping.groupPriority, grouping: column.grouping });
  16583. }
  16584. }
  16585. if ( column.treeAggregation && column.treeAggregation.type ){
  16586. aggregateArray.push({ field: column.field, col: column, aggregation: column.treeAggregation });
  16587. }
  16588. });
  16589. // sort grouping into priority order
  16590. groupArray.sort( function(a, b){
  16591. return a.groupPriority - b.groupPriority;
  16592. });
  16593. // renumber the priority in case it was somewhat messed up, then remove the grouping reference
  16594. groupArray.forEach( function( group, index) {
  16595. group.grouping.groupPriority = index;
  16596. group.groupPriority = index;
  16597. delete group.grouping;
  16598. });
  16599. return { grouping: groupArray, aggregations: aggregateArray };
  16600. },
  16601. /**
  16602. * @ngdoc function
  16603. * @name insertGroupHeader
  16604. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16605. * @description Create a group header row, and link it to the various configuration
  16606. * items that we use.
  16607. *
  16608. * Look for the row in the oldGroupingHeaderCache, write the row into the new groupingHeaderCache.
  16609. *
  16610. * @param {Grid} grid grid object
  16611. * @param {array} renderableRows the rows that we are processing
  16612. * @param {number} rowIndex the row we were up to processing
  16613. * @param {array} processingState the current processing state
  16614. * @param {number} stateIndex the processing state item that we were on when we triggered a new group header -
  16615. * i.e. the column that we want to create a header for
  16616. */
  16617. insertGroupHeader: function( grid, renderableRows, rowIndex, processingState, stateIndex ) {
  16618. // set the value that caused the end of a group into the header row and the processing state
  16619. var fieldName = processingState[stateIndex].fieldName;
  16620. var col = processingState[stateIndex].col;
  16621. var newValue = grid.getCellValue(renderableRows[rowIndex], col);
  16622. var newDisplayValue = newValue;
  16623. if ( typeof(newValue) === 'undefined' || newValue === null ) {
  16624. newDisplayValue = grid.options.groupingNullLabel;
  16625. }
  16626. var cacheItem = grid.grouping.oldGroupingHeaderCache;
  16627. for ( var i = 0; i < stateIndex; i++ ){
  16628. if ( cacheItem && cacheItem[processingState[i].currentValue] ){
  16629. cacheItem = cacheItem[processingState[i].currentValue].children;
  16630. }
  16631. }
  16632. var headerRow;
  16633. if ( cacheItem && cacheItem[newValue]){
  16634. headerRow = cacheItem[newValue].row;
  16635. headerRow.entity = {};
  16636. } else {
  16637. headerRow = new GridRow( {}, null, grid );
  16638. gridClassFactory.rowTemplateAssigner.call(grid, headerRow);
  16639. }
  16640. headerRow.entity['$$' + processingState[stateIndex].col.uid] = { groupVal: newDisplayValue };
  16641. headerRow.treeLevel = stateIndex;
  16642. headerRow.groupHeader = true;
  16643. headerRow.internalRow = true;
  16644. headerRow.enableCellEdit = false;
  16645. headerRow.enableSelection = grid.options.enableGroupHeaderSelection;
  16646. processingState[stateIndex].initialised = true;
  16647. processingState[stateIndex].currentValue = newValue;
  16648. processingState[stateIndex].currentRow = headerRow;
  16649. // set all processing states below this one to not be initialised - change of this state
  16650. // means all those need to start again
  16651. service.finaliseProcessingState( processingState, stateIndex + 1);
  16652. // insert our new header row
  16653. renderableRows.splice(rowIndex, 0, headerRow);
  16654. // add our new header row to the cache
  16655. cacheItem = grid.grouping.groupingHeaderCache;
  16656. for ( i = 0; i < stateIndex; i++ ){
  16657. cacheItem = cacheItem[processingState[i].currentValue].children;
  16658. }
  16659. cacheItem[newValue] = { row: headerRow, children: {} };
  16660. },
  16661. /**
  16662. * @ngdoc function
  16663. * @name finaliseProcessingState
  16664. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16665. * @description Set all processing states lower than the one that had a break in value to
  16666. * no longer be initialised. Render the counts into the entity ready for display.
  16667. *
  16668. * @param {Grid} grid grid object
  16669. * @param {array} processingState the current processing state
  16670. * @param {number} stateIndex the processing state item that we were on when we triggered a new group header, all
  16671. * processing states after this need to be finalised
  16672. */
  16673. finaliseProcessingState: function( processingState, stateIndex ){
  16674. for ( var i = stateIndex; i < processingState.length; i++){
  16675. processingState[i].initialised = false;
  16676. processingState[i].currentRow = null;
  16677. processingState[i].currentValue = null;
  16678. }
  16679. },
  16680. /**
  16681. * @ngdoc function
  16682. * @name getRowExpandedStates
  16683. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16684. * @description Extract the groupHeaderCache hash, pulling out only the states.
  16685. *
  16686. * The example below shows a grid that is grouped by gender then age
  16687. *
  16688. * <pre>
  16689. * {
  16690. * male: {
  16691. * state: 'expanded',
  16692. * children: {
  16693. * 22: { state: 'expanded' },
  16694. * 30: { state: 'collapsed' }
  16695. * }
  16696. * },
  16697. * female: {
  16698. * state: 'expanded',
  16699. * children: {
  16700. * 28: { state: 'expanded' },
  16701. * 55: { state: 'collapsed' }
  16702. * }
  16703. * }
  16704. * }
  16705. * </pre>
  16706. *
  16707. * @param {Grid} grid grid object
  16708. * @returns {hash} the expanded states as a hash
  16709. */
  16710. getRowExpandedStates: function(treeChildren){
  16711. if ( typeof(treeChildren) === 'undefined' ){
  16712. return {};
  16713. }
  16714. var newChildren = {};
  16715. angular.forEach( treeChildren, function( value, key ){
  16716. newChildren[key] = { state: value.row.treeNode.state };
  16717. if ( value.children ){
  16718. newChildren[key].children = service.getRowExpandedStates( value.children );
  16719. } else {
  16720. newChildren[key].children = {};
  16721. }
  16722. });
  16723. return newChildren;
  16724. },
  16725. /**
  16726. * @ngdoc function
  16727. * @name applyRowExpandedStates
  16728. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16729. * @description Take a hash in the format as created by getRowExpandedStates,
  16730. * and apply it to the grid.grouping.groupHeaderCache.
  16731. *
  16732. * Takes a treeSubset, and applies to a treeSubset - so can be called
  16733. * recursively.
  16734. *
  16735. * @param {object} currentNode can be grid.grouping.groupHeaderCache, or any of
  16736. * the children of that hash
  16737. * @returns {hash} expandedStates can be the full expanded states, or children
  16738. * of that expanded states (which hopefully matches the subset of the groupHeaderCache)
  16739. */
  16740. applyRowExpandedStates: function( currentNode, expandedStates ){
  16741. if ( typeof(expandedStates) === 'undefined' ){
  16742. return;
  16743. }
  16744. angular.forEach(expandedStates, function( value, key ) {
  16745. if ( currentNode[key] ){
  16746. currentNode[key].row.treeNode.state = value.state;
  16747. if (value.children && currentNode[key].children){
  16748. service.applyRowExpandedStates( currentNode[key].children, value.children );
  16749. }
  16750. }
  16751. });
  16752. }
  16753. };
  16754. return service;
  16755. }]);
  16756. /**
  16757. * @ngdoc directive
  16758. * @name ui.grid.grouping.directive:uiGridGrouping
  16759. * @element div
  16760. * @restrict A
  16761. *
  16762. * @description Adds grouping features to grid
  16763. *
  16764. * @example
  16765. <example module="app">
  16766. <file name="app.js">
  16767. var app = angular.module('app', ['ui.grid', 'ui.grid.grouping']);
  16768. app.controller('MainCtrl', ['$scope', function ($scope) {
  16769. $scope.data = [
  16770. { name: 'Bob', title: 'CEO' },
  16771. { name: 'Frank', title: 'Lowly Developer' }
  16772. ];
  16773. $scope.columnDefs = [
  16774. {name: 'name', enableCellEdit: true},
  16775. {name: 'title', enableCellEdit: true}
  16776. ];
  16777. $scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data };
  16778. }]);
  16779. </file>
  16780. <file name="index.html">
  16781. <div ng-controller="MainCtrl">
  16782. <div ui-grid="gridOptions" ui-grid-grouping></div>
  16783. </div>
  16784. </file>
  16785. </example>
  16786. */
  16787. module.directive('uiGridGrouping', ['uiGridGroupingConstants', 'uiGridGroupingService', '$templateCache',
  16788. function (uiGridGroupingConstants, uiGridGroupingService, $templateCache) {
  16789. return {
  16790. replace: true,
  16791. priority: 0,
  16792. require: '^uiGrid',
  16793. scope: false,
  16794. compile: function () {
  16795. return {
  16796. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  16797. if (uiGridCtrl.grid.options.enableGrouping !== false){
  16798. uiGridGroupingService.initializeGrid(uiGridCtrl.grid, $scope);
  16799. }
  16800. },
  16801. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  16802. }
  16803. };
  16804. }
  16805. };
  16806. }]);
  16807. })();
  16808. (function () {
  16809. 'use strict';
  16810. /**
  16811. * @ngdoc overview
  16812. * @name ui.grid.importer
  16813. * @description
  16814. *
  16815. * # ui.grid.importer
  16816. *
  16817. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  16818. *
  16819. * This module provides the ability to import data into the grid. It
  16820. * uses the column defs to work out which data belongs in which column,
  16821. * and creates entities from a configured class (typically a $resource).
  16822. *
  16823. * If the rowEdit feature is enabled, it also calls save on those newly
  16824. * created objects, and then displays any errors in the imported data.
  16825. *
  16826. * Currently the importer imports only CSV and json files, although provision has been
  16827. * made to process other file formats, and these can be added over time.
  16828. *
  16829. * For json files, the properties within each object in the json must match the column names
  16830. * (to put it another way, the importer doesn't process the json, it just copies the objects
  16831. * within the json into a new instance of the specified object type)
  16832. *
  16833. * For CSV import, the default column identification relies on each column in the
  16834. * header row matching a column.name or column.displayName. Optionally, a column identification
  16835. * callback can be used. This allows matching using other attributes, which is particularly
  16836. * useful if your application has internationalised column headings (i.e. the headings that
  16837. * the user sees don't match the column names).
  16838. *
  16839. * The importer makes use of the grid menu as the UI for requesting an
  16840. * import.
  16841. *
  16842. * <div ui-grid-importer></div>
  16843. */
  16844. var module = angular.module('ui.grid.importer', ['ui.grid']);
  16845. /**
  16846. * @ngdoc object
  16847. * @name ui.grid.importer.constant:uiGridImporterConstants
  16848. *
  16849. * @description constants available in importer module
  16850. */
  16851. module.constant('uiGridImporterConstants', {
  16852. featureName: 'importer'
  16853. });
  16854. /**
  16855. * @ngdoc service
  16856. * @name ui.grid.importer.service:uiGridImporterService
  16857. *
  16858. * @description Services for importer feature
  16859. */
  16860. module.service('uiGridImporterService', ['$q', 'uiGridConstants', 'uiGridImporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService', '$window',
  16861. function ($q, uiGridConstants, uiGridImporterConstants, gridUtil, $compile, $interval, i18nService, $window) {
  16862. var service = {
  16863. initializeGrid: function ($scope, grid) {
  16864. //add feature namespace and any properties to grid for needed state
  16865. grid.importer = {
  16866. $scope: $scope
  16867. };
  16868. this.defaultGridOptions(grid.options);
  16869. /**
  16870. * @ngdoc object
  16871. * @name ui.grid.importer.api:PublicApi
  16872. *
  16873. * @description Public Api for importer feature
  16874. */
  16875. var publicApi = {
  16876. events: {
  16877. importer: {
  16878. }
  16879. },
  16880. methods: {
  16881. importer: {
  16882. /**
  16883. * @ngdoc function
  16884. * @name importFile
  16885. * @methodOf ui.grid.importer.api:PublicApi
  16886. * @description Imports a file into the grid using the file object
  16887. * provided. Bypasses the grid menu
  16888. * @param {File} fileObject the file we want to import, as a javascript
  16889. * File object
  16890. */
  16891. importFile: function ( fileObject ) {
  16892. service.importThisFile( grid, fileObject );
  16893. }
  16894. }
  16895. }
  16896. };
  16897. grid.api.registerEventsFromObject(publicApi.events);
  16898. grid.api.registerMethodsFromObject(publicApi.methods);
  16899. if ( grid.options.enableImporter && grid.options.importerShowMenu ){
  16900. if ( grid.api.core.addToGridMenu ){
  16901. service.addToMenu( grid );
  16902. } else {
  16903. // order of registration is not guaranteed, register in a little while
  16904. $interval( function() {
  16905. if (grid.api.core.addToGridMenu){
  16906. service.addToMenu( grid );
  16907. }
  16908. }, 100, 1);
  16909. }
  16910. }
  16911. },
  16912. defaultGridOptions: function (gridOptions) {
  16913. //default option to true unless it was explicitly set to false
  16914. /**
  16915. * @ngdoc object
  16916. * @name ui.grid.importer.api:GridOptions
  16917. *
  16918. * @description GridOptions for importer feature, these are available to be
  16919. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  16920. */
  16921. /**
  16922. * @ngdoc property
  16923. * @propertyOf ui.grid.importer.api:GridOptions
  16924. * @name enableImporter
  16925. * @description Whether or not importer is enabled. Automatically set
  16926. * to false if the user's browser does not support the required fileApi.
  16927. * Otherwise defaults to true.
  16928. *
  16929. */
  16930. if (gridOptions.enableImporter || gridOptions.enableImporter === undefined) {
  16931. if ( !($window.hasOwnProperty('File') && $window.hasOwnProperty('FileReader') && $window.hasOwnProperty('FileList') && $window.hasOwnProperty('Blob')) ) {
  16932. gridUtil.logError('The File APIs are not fully supported in this browser, grid importer cannot be used.');
  16933. gridOptions.enableImporter = false;
  16934. } else {
  16935. gridOptions.enableImporter = true;
  16936. }
  16937. } else {
  16938. gridOptions.enableImporter = false;
  16939. }
  16940. /**
  16941. * @ngdoc method
  16942. * @name importerProcessHeaders
  16943. * @methodOf ui.grid.importer.api:GridOptions
  16944. * @description A callback function that will process headers using custom
  16945. * logic. Set this callback function if the headers that your user will provide in their
  16946. * import file don't necessarily match the grid header or field names. This might commonly
  16947. * occur where your application is internationalised, and therefore the field names
  16948. * that the user recognises are in a different language than the field names that
  16949. * ui-grid knows about.
  16950. *
  16951. * Defaults to the internal `processHeaders` method, which seeks to match using both
  16952. * displayName and column.name. Any non-matching columns are discarded.
  16953. *
  16954. * Your callback routine should respond by processing the header array, and returning an array
  16955. * of matching column names. A null value in any given position means "don't import this column"
  16956. *
  16957. * <pre>
  16958. * gridOptions.importerProcessHeaders: function( headerArray ) {
  16959. * var myHeaderColumns = [];
  16960. * var thisCol;
  16961. * headerArray.forEach( function( value, index ) {
  16962. * thisCol = mySpecialLookupFunction( value );
  16963. * myHeaderColumns.push( thisCol.name );
  16964. * });
  16965. *
  16966. * return myHeaderCols;
  16967. * })
  16968. * </pre>
  16969. * @param {Grid} grid the grid we're importing into
  16970. * @param {array} headerArray an array of the text from the first row of the csv file,
  16971. * which you need to match to column.names
  16972. * @returns {array} array of matching column names, in the same order as the headerArray
  16973. *
  16974. */
  16975. gridOptions.importerProcessHeaders = gridOptions.importerProcessHeaders || service.processHeaders;
  16976. /**
  16977. * @ngdoc method
  16978. * @name importerHeaderFilter
  16979. * @methodOf ui.grid.importer.api:GridOptions
  16980. * @description A callback function that will filter (usually translate) a single
  16981. * header. Used when you want to match the passed in column names to the column
  16982. * displayName after the header filter.
  16983. *
  16984. * Your callback routine needs to return the filtered header value.
  16985. * <pre>
  16986. * gridOptions.importerHeaderFilter: function( displayName ) {
  16987. * return $translate.instant( displayName );
  16988. * })
  16989. * </pre>
  16990. *
  16991. * or:
  16992. * <pre>
  16993. * gridOptions.importerHeaderFilter: $translate.instant
  16994. * </pre>
  16995. * @param {string} displayName the displayName that we'd like to translate
  16996. * @returns {string} the translated name
  16997. *
  16998. */
  16999. gridOptions.importerHeaderFilter = gridOptions.importerHeaderFilter || function( displayName ) { return displayName; };
  17000. /**
  17001. * @ngdoc method
  17002. * @name importerErrorCallback
  17003. * @methodOf ui.grid.importer.api:GridOptions
  17004. * @description A callback function that provides custom error handling, rather
  17005. * than the standard grid behaviour of an alert box and a console message. You
  17006. * might use this to internationalise the console log messages, or to write to a
  17007. * custom logging routine that returned errors to the server.
  17008. *
  17009. * <pre>
  17010. * gridOptions.importerErrorCallback: function( grid, errorKey, consoleMessage, context ) {
  17011. * myUserDisplayRoutine( errorKey );
  17012. * myLoggingRoutine( consoleMessage, context );
  17013. * })
  17014. * </pre>
  17015. * @param {Grid} grid the grid we're importing into, may be useful if you're positioning messages
  17016. * in some way
  17017. * @param {string} errorKey one of the i18n keys the importer can return - importer.noHeaders,
  17018. * importer.noObjects, importer.invalidCsv, importer.invalidJson, importer.jsonNotArray
  17019. * @param {string} consoleMessage the English console message that importer would have written
  17020. * @param {object} context the context data that importer would have appended to that console message,
  17021. * often the file content itself or the element that is in error
  17022. *
  17023. */
  17024. if ( !gridOptions.importerErrorCallback || typeof(gridOptions.importerErrorCallback) !== 'function' ){
  17025. delete gridOptions.importerErrorCallback;
  17026. }
  17027. /**
  17028. * @ngdoc method
  17029. * @name importerDataAddCallback
  17030. * @methodOf ui.grid.importer.api:GridOptions
  17031. * @description A mandatory callback function that adds data to the source data array. The grid
  17032. * generally doesn't add rows to the source data array, it is tidier to handle this through a user
  17033. * callback.
  17034. *
  17035. * <pre>
  17036. * gridOptions.importerDataAddCallback: function( grid, newObjects ) {
  17037. * $scope.myData = $scope.myData.concat( newObjects );
  17038. * })
  17039. * </pre>
  17040. * @param {Grid} grid the grid we're importing into, may be useful in some way
  17041. * @param {array} newObjects an array of new objects that you should add to your data
  17042. *
  17043. */
  17044. if ( gridOptions.enableImporter === true && !gridOptions.importerDataAddCallback ) {
  17045. gridUtil.logError("You have not set an importerDataAddCallback, importer is disabled");
  17046. gridOptions.enableImporter = false;
  17047. }
  17048. /**
  17049. * @ngdoc object
  17050. * @name importerNewObject
  17051. * @propertyOf ui.grid.importer.api:GridOptions
  17052. * @description An object on which we call `new` to create each new row before inserting it into
  17053. * the data array. Typically this would be a $resource entity, which means that if you're using
  17054. * the rowEdit feature, you can directly call save on this entity when the save event is triggered.
  17055. *
  17056. * Defaults to a vanilla javascript object
  17057. *
  17058. * @example
  17059. * <pre>
  17060. * gridOptions.importerNewObject = MyRes;
  17061. * </pre>
  17062. *
  17063. */
  17064. /**
  17065. * @ngdoc property
  17066. * @propertyOf ui.grid.importer.api:GridOptions
  17067. * @name importerShowMenu
  17068. * @description Whether or not to show an item in the grid menu. Defaults to true.
  17069. *
  17070. */
  17071. gridOptions.importerShowMenu = gridOptions.importerShowMenu !== false;
  17072. /**
  17073. * @ngdoc method
  17074. * @methodOf ui.grid.importer.api:GridOptions
  17075. * @name importerObjectCallback
  17076. * @description A callback that massages the data for each object. For example,
  17077. * you might have data stored as a code value, but display the decode. This callback
  17078. * can be used to change the decoded value back into a code. Defaults to doing nothing.
  17079. * @param {Grid} grid in case you need it
  17080. * @param {object} newObject the new object as importer has created it, modify it
  17081. * then return the modified version
  17082. * @returns {object} the modified object
  17083. * @example
  17084. * <pre>
  17085. * gridOptions.importerObjectCallback = function ( grid, newObject ) {
  17086. * switch newObject.status {
  17087. * case 'Active':
  17088. * newObject.status = 1;
  17089. * break;
  17090. * case 'Inactive':
  17091. * newObject.status = 2;
  17092. * break;
  17093. * }
  17094. * return newObject;
  17095. * };
  17096. * </pre>
  17097. */
  17098. gridOptions.importerObjectCallback = gridOptions.importerObjectCallback || function( grid, newObject ) { return newObject; };
  17099. },
  17100. /**
  17101. * @ngdoc function
  17102. * @name addToMenu
  17103. * @methodOf ui.grid.importer.service:uiGridImporterService
  17104. * @description Adds import menu item to the grid menu,
  17105. * allowing the user to request import of a file
  17106. * @param {Grid} grid the grid into which data should be imported
  17107. */
  17108. addToMenu: function ( grid ) {
  17109. grid.api.core.addToGridMenu( grid, [
  17110. {
  17111. title: i18nService.getSafeText('gridMenu.importerTitle'),
  17112. order: 150
  17113. },
  17114. {
  17115. templateUrl: 'ui-grid/importerMenuItemContainer',
  17116. action: function ($event) {
  17117. this.grid.api.importer.importAFile( grid );
  17118. },
  17119. order: 151
  17120. }
  17121. ]);
  17122. },
  17123. /**
  17124. * @ngdoc function
  17125. * @name importThisFile
  17126. * @methodOf ui.grid.importer.service:uiGridImporterService
  17127. * @description Imports the provided file into the grid using the file object
  17128. * provided. Bypasses the grid menu
  17129. * @param {Grid} grid the grid we're importing into
  17130. * @param {File} fileObject the file we want to import, as returned from the File
  17131. * javascript object
  17132. */
  17133. importThisFile: function ( grid, fileObject ) {
  17134. if (!fileObject){
  17135. gridUtil.logError( 'No file object provided to importThisFile, should be impossible, aborting');
  17136. return;
  17137. }
  17138. var reader = new FileReader();
  17139. switch ( fileObject.type ){
  17140. case 'application/json':
  17141. reader.onload = service.importJsonClosure( grid );
  17142. break;
  17143. default:
  17144. reader.onload = service.importCsvClosure( grid );
  17145. break;
  17146. }
  17147. reader.readAsText( fileObject );
  17148. },
  17149. /**
  17150. * @ngdoc function
  17151. * @name importJson
  17152. * @methodOf ui.grid.importer.service:uiGridImporterService
  17153. * @description Creates a function that imports a json file into the grid.
  17154. * The json data is imported into new objects of type `gridOptions.importerNewObject`,
  17155. * and if the rowEdit feature is enabled the rows are marked as dirty
  17156. * @param {Grid} grid the grid we want to import into
  17157. * @param {FileObject} importFile the file that we want to import, as
  17158. * a FileObject
  17159. */
  17160. importJsonClosure: function( grid ) {
  17161. return function( importFile ){
  17162. var newObjects = [];
  17163. var newObject;
  17164. var importArray = service.parseJson( grid, importFile );
  17165. if (importArray === null){
  17166. return;
  17167. }
  17168. importArray.forEach( function( value, index ) {
  17169. newObject = service.newObject( grid );
  17170. angular.extend( newObject, value );
  17171. newObject = grid.options.importerObjectCallback( grid, newObject );
  17172. newObjects.push( newObject );
  17173. });
  17174. service.addObjects( grid, newObjects );
  17175. };
  17176. },
  17177. /**
  17178. * @ngdoc function
  17179. * @name parseJson
  17180. * @methodOf ui.grid.importer.service:uiGridImporterService
  17181. * @description Parses a json file, returns the parsed data.
  17182. * Displays an error if file doesn't parse
  17183. * @param {Grid} grid the grid that we want to import into
  17184. * @param {FileObject} importFile the file that we want to import, as
  17185. * a FileObject
  17186. * @returns {array} array of objects from the imported json
  17187. */
  17188. parseJson: function( grid, importFile ){
  17189. var loadedObjects;
  17190. try {
  17191. loadedObjects = JSON.parse( importFile.target.result );
  17192. } catch (e) {
  17193. service.alertError( grid, 'importer.invalidJson', 'File could not be processed, is it valid json? Content was: ', importFile.target.result );
  17194. return;
  17195. }
  17196. if ( !Array.isArray( loadedObjects ) ){
  17197. service.alertError( grid, 'importer.jsonNotarray', 'Import failed, file is not an array, file was: ', importFile.target.result );
  17198. return [];
  17199. } else {
  17200. return loadedObjects;
  17201. }
  17202. },
  17203. /**
  17204. * @ngdoc function
  17205. * @name importCsvClosure
  17206. * @methodOf ui.grid.importer.service:uiGridImporterService
  17207. * @description Creates a function that imports a csv file into the grid
  17208. * (allowing it to be used in the reader.onload event)
  17209. * @param {Grid} grid the grid that we want to import into
  17210. * @param {FileObject} importFile the file that we want to import, as
  17211. * a file object
  17212. */
  17213. importCsvClosure: function( grid ) {
  17214. return function( importFile ){
  17215. var importArray = service.parseCsv( importFile );
  17216. if ( !importArray || importArray.length < 1 ){
  17217. service.alertError( grid, 'importer.invalidCsv', 'File could not be processed, is it valid csv? Content was: ', importFile.target.result );
  17218. return;
  17219. }
  17220. var newObjects = service.createCsvObjects( grid, importArray );
  17221. if ( !newObjects || newObjects.length === 0 ){
  17222. service.alertError( grid, 'importer.noObjects', 'Objects were not able to be derived, content was: ', importFile.target.result );
  17223. return;
  17224. }
  17225. service.addObjects( grid, newObjects );
  17226. };
  17227. },
  17228. /**
  17229. * @ngdoc function
  17230. * @name parseCsv
  17231. * @methodOf ui.grid.importer.service:uiGridImporterService
  17232. * @description Parses a csv file into an array of arrays, with the first
  17233. * array being the headers, and the remaining arrays being the data.
  17234. * The logic for this comes from https://github.com/thetalecrafter/excel.js/blob/master/src/csv.js,
  17235. * which is noted as being under the MIT license. The code is modified to pass the jscs yoda condition
  17236. * checker
  17237. * @param {FileObject} importFile the file that we want to import, as a
  17238. * file object
  17239. */
  17240. parseCsv: function( importFile ) {
  17241. var csv = importFile.target.result;
  17242. // use the CSV-JS library to parse
  17243. return CSV.parse(csv);
  17244. },
  17245. /**
  17246. * @ngdoc function
  17247. * @name createCsvObjects
  17248. * @methodOf ui.grid.importer.service:uiGridImporterService
  17249. * @description Converts an array of arrays (representing the csv file)
  17250. * into a set of objects. Uses the provided `gridOptions.importerNewObject`
  17251. * to create the objects, and maps the header row into the individual columns
  17252. * using either `gridOptions.importerProcessHeaders`, or by using a native method
  17253. * of matching to either the displayName, column name or column field of
  17254. * the columns in the column defs. The resulting objects will have attributes
  17255. * that are named based on the column.field or column.name, in that order.
  17256. * @param {Grid} grid the grid that we want to import into
  17257. * @param {Array} importArray the data that we want to import, as an array
  17258. */
  17259. createCsvObjects: function( grid, importArray ){
  17260. // pull off header row and turn into headers
  17261. var headerMapping = grid.options.importerProcessHeaders( grid, importArray.shift() );
  17262. if ( !headerMapping || headerMapping.length === 0 ){
  17263. service.alertError( grid, 'importer.noHeaders', 'Column names could not be derived, content was: ', importArray );
  17264. return [];
  17265. }
  17266. var newObjects = [];
  17267. var newObject;
  17268. importArray.forEach( function( row, index ) {
  17269. newObject = service.newObject( grid );
  17270. if ( row !== null ){
  17271. row.forEach( function( field, index ){
  17272. if ( headerMapping[index] !== null ){
  17273. newObject[ headerMapping[index] ] = field;
  17274. }
  17275. });
  17276. }
  17277. newObject = grid.options.importerObjectCallback( grid, newObject );
  17278. newObjects.push( newObject );
  17279. });
  17280. return newObjects;
  17281. },
  17282. /**
  17283. * @ngdoc function
  17284. * @name processHeaders
  17285. * @methodOf ui.grid.importer.service:uiGridImporterService
  17286. * @description Determines the columns that the header row from
  17287. * a csv (or other) file represents.
  17288. * @param {Grid} grid the grid we're importing into
  17289. * @param {array} headerRow the header row that we wish to match against
  17290. * the column definitions
  17291. * @returns {array} an array of the attribute names that should be used
  17292. * for that column, based on matching the headers or creating the headers
  17293. *
  17294. */
  17295. processHeaders: function( grid, headerRow ) {
  17296. var headers = [];
  17297. if ( !grid.options.columnDefs || grid.options.columnDefs.length === 0 ){
  17298. // we are going to create new columnDefs for all these columns, so just remove
  17299. // spaces from the names to create fields
  17300. headerRow.forEach( function( value, index ) {
  17301. headers.push( value.replace( /[^0-9a-zA-Z\-_]/g, '_' ) );
  17302. });
  17303. return headers;
  17304. } else {
  17305. var lookupHash = service.flattenColumnDefs( grid, grid.options.columnDefs );
  17306. headerRow.forEach( function( value, index ) {
  17307. if ( lookupHash[value] ) {
  17308. headers.push( lookupHash[value] );
  17309. } else if ( lookupHash[ value.toLowerCase() ] ) {
  17310. headers.push( lookupHash[ value.toLowerCase() ] );
  17311. } else {
  17312. headers.push( null );
  17313. }
  17314. });
  17315. return headers;
  17316. }
  17317. },
  17318. /**
  17319. * @name flattenColumnDefs
  17320. * @methodOf ui.grid.importer.service:uiGridImporterService
  17321. * @description Runs through the column defs and creates a hash of
  17322. * the displayName, name and field, and of each of those values forced to lower case,
  17323. * with each pointing to the field or name
  17324. * (whichever is present). Used to lookup column headers and decide what
  17325. * attribute name to give to the resulting field.
  17326. * @param {Grid} grid the grid we're importing into
  17327. * @param {array} columnDefs the columnDefs that we should flatten
  17328. * @returns {hash} the flattened version of the column def information, allowing
  17329. * us to look up a value by `flattenedHash[ headerValue ]`
  17330. */
  17331. flattenColumnDefs: function( grid, columnDefs ){
  17332. var flattenedHash = {};
  17333. columnDefs.forEach( function( columnDef, index) {
  17334. if ( columnDef.name ){
  17335. flattenedHash[ columnDef.name ] = columnDef.field || columnDef.name;
  17336. flattenedHash[ columnDef.name.toLowerCase() ] = columnDef.field || columnDef.name;
  17337. }
  17338. if ( columnDef.field ){
  17339. flattenedHash[ columnDef.field ] = columnDef.field || columnDef.name;
  17340. flattenedHash[ columnDef.field.toLowerCase() ] = columnDef.field || columnDef.name;
  17341. }
  17342. if ( columnDef.displayName ){
  17343. flattenedHash[ columnDef.displayName ] = columnDef.field || columnDef.name;
  17344. flattenedHash[ columnDef.displayName.toLowerCase() ] = columnDef.field || columnDef.name;
  17345. }
  17346. if ( columnDef.displayName && grid.options.importerHeaderFilter ){
  17347. flattenedHash[ grid.options.importerHeaderFilter(columnDef.displayName) ] = columnDef.field || columnDef.name;
  17348. flattenedHash[ grid.options.importerHeaderFilter(columnDef.displayName).toLowerCase() ] = columnDef.field || columnDef.name;
  17349. }
  17350. });
  17351. return flattenedHash;
  17352. },
  17353. /**
  17354. * @ngdoc function
  17355. * @name addObjects
  17356. * @methodOf ui.grid.importer.service:uiGridImporterService
  17357. * @description Inserts our new objects into the grid data, and
  17358. * sets the rows to dirty if the rowEdit feature is being used
  17359. *
  17360. * Does this by registering a watch on dataChanges, which essentially
  17361. * is waiting on the result of the grid data watch, and downstream processing.
  17362. *
  17363. * When the callback is called, it deregisters itself - we don't want to run
  17364. * again next time data is added.
  17365. *
  17366. * If we never get called, we deregister on destroy.
  17367. *
  17368. * @param {Grid} grid the grid we're importing into
  17369. * @param {array} newObjects the objects we want to insert into the grid data
  17370. * @returns {object} the new object
  17371. */
  17372. addObjects: function( grid, newObjects, $scope ){
  17373. if ( grid.api.rowEdit ){
  17374. var dataChangeDereg = grid.registerDataChangeCallback( function() {
  17375. grid.api.rowEdit.setRowsDirty( newObjects );
  17376. dataChangeDereg();
  17377. }, [uiGridConstants.dataChange.ROW] );
  17378. grid.importer.$scope.$on( '$destroy', dataChangeDereg );
  17379. }
  17380. grid.importer.$scope.$apply( grid.options.importerDataAddCallback( grid, newObjects ) );
  17381. },
  17382. /**
  17383. * @ngdoc function
  17384. * @name newObject
  17385. * @methodOf ui.grid.importer.service:uiGridImporterService
  17386. * @description Makes a new object based on `gridOptions.importerNewObject`,
  17387. * or based on an empty object if not present
  17388. * @param {Grid} grid the grid we're importing into
  17389. * @returns {object} the new object
  17390. */
  17391. newObject: function( grid ){
  17392. if ( typeof(grid.options) !== "undefined" && typeof(grid.options.importerNewObject) !== "undefined" ){
  17393. return new grid.options.importerNewObject();
  17394. } else {
  17395. return {};
  17396. }
  17397. },
  17398. /**
  17399. * @ngdoc function
  17400. * @name alertError
  17401. * @methodOf ui.grid.importer.service:uiGridImporterService
  17402. * @description Provides an internationalised user alert for the failure,
  17403. * and logs a console message including diagnostic content.
  17404. * Optionally, if the the `gridOptions.importerErrorCallback` routine
  17405. * is defined, then calls that instead, allowing user specified error routines
  17406. * @param {Grid} grid the grid we're importing into
  17407. * @param {array} headerRow the header row that we wish to match against
  17408. * the column definitions
  17409. */
  17410. alertError: function( grid, alertI18nToken, consoleMessage, context ){
  17411. if ( grid.options.importerErrorCallback ){
  17412. grid.options.importerErrorCallback( grid, alertI18nToken, consoleMessage, context );
  17413. } else {
  17414. $window.alert(i18nService.getSafeText( alertI18nToken ));
  17415. gridUtil.logError(consoleMessage + context );
  17416. }
  17417. }
  17418. };
  17419. return service;
  17420. }
  17421. ]);
  17422. /**
  17423. * @ngdoc directive
  17424. * @name ui.grid.importer.directive:uiGridImporter
  17425. * @element div
  17426. * @restrict A
  17427. *
  17428. * @description Adds importer features to grid
  17429. *
  17430. */
  17431. module.directive('uiGridImporter', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile',
  17432. function (uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) {
  17433. return {
  17434. replace: true,
  17435. priority: 0,
  17436. require: '^uiGrid',
  17437. scope: false,
  17438. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  17439. uiGridImporterService.initializeGrid($scope, uiGridCtrl.grid);
  17440. }
  17441. };
  17442. }
  17443. ]);
  17444. /**
  17445. * @ngdoc directive
  17446. * @name ui.grid.importer.directive:uiGridImporterMenuItem
  17447. * @element div
  17448. * @restrict A
  17449. *
  17450. * @description Handles the processing from the importer menu item - once a file is
  17451. * selected
  17452. *
  17453. */
  17454. module.directive('uiGridImporterMenuItem', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile',
  17455. function (uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) {
  17456. return {
  17457. replace: true,
  17458. priority: 0,
  17459. require: '^uiGrid',
  17460. scope: false,
  17461. templateUrl: 'ui-grid/importerMenuItem',
  17462. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  17463. var handleFileSelect = function( event ){
  17464. var target = event.srcElement || event.target;
  17465. if (target && target.files && target.files.length === 1) {
  17466. var fileObject = target.files[0];
  17467. uiGridImporterService.importThisFile( grid, fileObject );
  17468. target.form.reset();
  17469. }
  17470. };
  17471. var fileChooser = $elm[0].querySelectorAll('.ui-grid-importer-file-chooser');
  17472. var grid = uiGridCtrl.grid;
  17473. if ( fileChooser.length !== 1 ){
  17474. gridUtil.logError('Found > 1 or < 1 file choosers within the menu item, error, cannot continue');
  17475. } else {
  17476. fileChooser[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google
  17477. }
  17478. }
  17479. };
  17480. }
  17481. ]);
  17482. })();
  17483. (function() {
  17484. 'use strict';
  17485. /**
  17486. * @ngdoc overview
  17487. * @name ui.grid.infiniteScroll
  17488. *
  17489. * @description
  17490. *
  17491. * #ui.grid.infiniteScroll
  17492. *
  17493. * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div>
  17494. *
  17495. * This module provides infinite scroll functionality to ui-grid
  17496. *
  17497. */
  17498. var module = angular.module('ui.grid.infiniteScroll', ['ui.grid']);
  17499. /**
  17500. * @ngdoc service
  17501. * @name ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17502. *
  17503. * @description Service for infinite scroll features
  17504. */
  17505. module.service('uiGridInfiniteScrollService', ['gridUtil', '$compile', '$timeout', 'uiGridConstants', 'ScrollEvent', '$q', function (gridUtil, $compile, $timeout, uiGridConstants, ScrollEvent, $q) {
  17506. var service = {
  17507. /**
  17508. * @ngdoc function
  17509. * @name initializeGrid
  17510. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17511. * @description This method register events and methods into grid public API
  17512. */
  17513. initializeGrid: function(grid, $scope) {
  17514. service.defaultGridOptions(grid.options);
  17515. if (!grid.options.enableInfiniteScroll){
  17516. return;
  17517. }
  17518. grid.infiniteScroll = { dataLoading: false };
  17519. service.setScrollDirections( grid, grid.options.infiniteScrollUp, grid.options.infiniteScrollDown );
  17520. grid.api.core.on.scrollEnd($scope, service.handleScroll);
  17521. /**
  17522. * @ngdoc object
  17523. * @name ui.grid.infiniteScroll.api:PublicAPI
  17524. *
  17525. * @description Public API for infinite scroll feature
  17526. */
  17527. var publicApi = {
  17528. events: {
  17529. infiniteScroll: {
  17530. /**
  17531. * @ngdoc event
  17532. * @name needLoadMoreData
  17533. * @eventOf ui.grid.infiniteScroll.api:PublicAPI
  17534. * @description This event fires when scroll reaches bottom percentage of grid
  17535. * and needs to load data
  17536. */
  17537. needLoadMoreData: function ($scope, fn) {
  17538. },
  17539. /**
  17540. * @ngdoc event
  17541. * @name needLoadMoreDataTop
  17542. * @eventOf ui.grid.infiniteScroll.api:PublicAPI
  17543. * @description This event fires when scroll reaches top percentage of grid
  17544. * and needs to load data
  17545. */
  17546. needLoadMoreDataTop: function ($scope, fn) {
  17547. }
  17548. }
  17549. },
  17550. methods: {
  17551. infiniteScroll: {
  17552. /**
  17553. * @ngdoc function
  17554. * @name dataLoaded
  17555. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17556. * @description Call this function when you have loaded the additional data
  17557. * requested. You should set scrollUp and scrollDown to indicate
  17558. * whether there are still more pages in each direction.
  17559. *
  17560. * If you call dataLoaded without first calling `saveScrollPercentage` then we will
  17561. * scroll the user to the start of the newly loaded data, which usually gives a smooth scroll
  17562. * experience, but can give a jumpy experience with large `infiniteScrollRowsFromEnd` values, and
  17563. * on variable speed internet connections. Using `saveScrollPercentage` as demonstrated in the tutorial
  17564. * should give a smoother scrolling experience for users.
  17565. *
  17566. * See infinite_scroll tutorial for example of usage
  17567. * @param {boolean} scrollUp if set to false flags that there are no more pages upwards, so don't fire
  17568. * any more infinite scroll events upward
  17569. * @param {boolean} scrollDown if set to false flags that there are no more pages downwards, so don't
  17570. * fire any more infinite scroll events downward
  17571. * @returns {promise} a promise that is resolved when the grid scrolling is fully adjusted. If you're
  17572. * planning to remove pages, you should wait on this promise first, or you'll break the scroll positioning
  17573. */
  17574. dataLoaded: function( scrollUp, scrollDown ) {
  17575. service.setScrollDirections(grid, scrollUp, scrollDown);
  17576. var promise = service.adjustScroll(grid).then(function() {
  17577. grid.infiniteScroll.dataLoading = false;
  17578. });
  17579. return promise;
  17580. },
  17581. /**
  17582. * @ngdoc function
  17583. * @name resetScroll
  17584. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17585. * @description Call this function when you have taken some action that makes the current
  17586. * scroll position invalid. For example, if you're using external sorting and you've resorted
  17587. * then you might reset the scroll, or if you've otherwise substantially changed the data, perhaps
  17588. * you've reused an existing grid for a new data set
  17589. *
  17590. * You must tell us whether there is data upwards or downwards after the reset
  17591. *
  17592. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17593. * infinite scroll events upward
  17594. * @param {boolean} scrollDown flag that there are pages downwards, so
  17595. * fire infinite scroll events downward
  17596. * @returns {promise} promise that is resolved when the scroll reset is complete
  17597. */
  17598. resetScroll: function( scrollUp, scrollDown ) {
  17599. service.setScrollDirections( grid, scrollUp, scrollDown);
  17600. return service.adjustInfiniteScrollPosition(grid, 0);
  17601. },
  17602. /**
  17603. * @ngdoc function
  17604. * @name saveScrollPercentage
  17605. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17606. * @description Saves the scroll percentage and number of visible rows before you adjust the data,
  17607. * used if you're subsequently going to call `dataRemovedTop` or `dataRemovedBottom`
  17608. */
  17609. saveScrollPercentage: function() {
  17610. grid.infiniteScroll.prevScrollTop = grid.renderContainers.body.prevScrollTop;
  17611. grid.infiniteScroll.previousVisibleRows = grid.getVisibleRowCount();
  17612. },
  17613. /**
  17614. * @ngdoc function
  17615. * @name dataRemovedTop
  17616. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17617. * @description Adjusts the scroll position after you've removed data at the top
  17618. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17619. * infinite scroll events upward
  17620. * @param {boolean} scrollDown flag that there are pages downwards, so
  17621. * fire infinite scroll events downward
  17622. */
  17623. dataRemovedTop: function( scrollUp, scrollDown ) {
  17624. service.dataRemovedTop( grid, scrollUp, scrollDown );
  17625. },
  17626. /**
  17627. * @ngdoc function
  17628. * @name dataRemovedBottom
  17629. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17630. * @description Adjusts the scroll position after you've removed data at the bottom
  17631. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17632. * infinite scroll events upward
  17633. * @param {boolean} scrollDown flag that there are pages downwards, so
  17634. * fire infinite scroll events downward
  17635. */
  17636. dataRemovedBottom: function( scrollUp, scrollDown ) {
  17637. service.dataRemovedBottom( grid, scrollUp, scrollDown );
  17638. },
  17639. /**
  17640. * @ngdoc function
  17641. * @name setScrollDirections
  17642. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17643. * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined,
  17644. * and also sets the grid.suppressParentScroll
  17645. * @param {boolean} scrollUp whether there are pages available up - defaults to false
  17646. * @param {boolean} scrollDown whether there are pages available down - defaults to true
  17647. */
  17648. setScrollDirections: function ( scrollUp, scrollDown ) {
  17649. service.setScrollDirections( grid, scrollUp, scrollDown );
  17650. }
  17651. }
  17652. }
  17653. };
  17654. grid.api.registerEventsFromObject(publicApi.events);
  17655. grid.api.registerMethodsFromObject(publicApi.methods);
  17656. },
  17657. defaultGridOptions: function (gridOptions) {
  17658. //default option to true unless it was explicitly set to false
  17659. /**
  17660. * @ngdoc object
  17661. * @name ui.grid.infiniteScroll.api:GridOptions
  17662. *
  17663. * @description GridOptions for infinite scroll feature, these are available to be
  17664. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  17665. */
  17666. /**
  17667. * @ngdoc object
  17668. * @name enableInfiniteScroll
  17669. * @propertyOf ui.grid.infiniteScroll.api:GridOptions
  17670. * @description Enable infinite scrolling for this grid
  17671. * <br/>Defaults to true
  17672. */
  17673. gridOptions.enableInfiniteScroll = gridOptions.enableInfiniteScroll !== false;
  17674. /**
  17675. * @ngdoc property
  17676. * @name infiniteScrollRowsFromEnd
  17677. * @propertyOf ui.grid.class:GridOptions
  17678. * @description This setting controls how close to the end of the dataset a user gets before
  17679. * more data is requested by the infinite scroll, whether scrolling up or down. This allows you to
  17680. * 'prefetch' rows before the user actually runs out of scrolling.
  17681. *
  17682. * Note that if you set this value too high it may give jumpy scrolling behaviour, if you're getting
  17683. * this behaviour you could use the `saveScrollPercentageMethod` right before loading your data, and we'll
  17684. * preserve that scroll position
  17685. *
  17686. * <br> Defaults to 20
  17687. */
  17688. gridOptions.infiniteScrollRowsFromEnd = gridOptions.infiniteScrollRowsFromEnd || 20;
  17689. /**
  17690. * @ngdoc property
  17691. * @name infiniteScrollUp
  17692. * @propertyOf ui.grid.class:GridOptions
  17693. * @description Whether you allow infinite scroll up, implying that the first page of data
  17694. * you have displayed is in the middle of your data set. If set to true then we trigger the
  17695. * needMoreDataTop event when the user hits the top of the scrollbar.
  17696. * <br> Defaults to false
  17697. */
  17698. gridOptions.infiniteScrollUp = gridOptions.infiniteScrollUp === true;
  17699. /**
  17700. * @ngdoc property
  17701. * @name infiniteScrollDown
  17702. * @propertyOf ui.grid.class:GridOptions
  17703. * @description Whether you allow infinite scroll down, implying that the first page of data
  17704. * you have displayed is in the middle of your data set. If set to true then we trigger the
  17705. * needMoreData event when the user hits the bottom of the scrollbar.
  17706. * <br> Defaults to true
  17707. */
  17708. gridOptions.infiniteScrollDown = gridOptions.infiniteScrollDown !== false;
  17709. },
  17710. /**
  17711. * @ngdoc function
  17712. * @name setScrollDirections
  17713. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17714. * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined,
  17715. * and also sets the grid.suppressParentScroll
  17716. * @param {grid} grid the grid we're operating on
  17717. * @param {boolean} scrollUp whether there are pages available up - defaults to false
  17718. * @param {boolean} scrollDown whether there are pages available down - defaults to true
  17719. */
  17720. setScrollDirections: function ( grid, scrollUp, scrollDown ) {
  17721. grid.infiniteScroll.scrollUp = ( scrollUp === true );
  17722. grid.suppressParentScrollUp = ( scrollUp === true );
  17723. grid.infiniteScroll.scrollDown = ( scrollDown !== false);
  17724. grid.suppressParentScrollDown = ( scrollDown !== false);
  17725. },
  17726. /**
  17727. * @ngdoc function
  17728. * @name handleScroll
  17729. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17730. * @description Called whenever the grid scrolls, determines whether the scroll should
  17731. * trigger an infinite scroll request for more data
  17732. * @param {object} args the args from the event
  17733. */
  17734. handleScroll: function (args) {
  17735. // don't request data if already waiting for data, or if source is coming from ui.grid.adjustInfiniteScrollPosition() function
  17736. if ( args.grid.infiniteScroll && args.grid.infiniteScroll.dataLoading || args.source === 'ui.grid.adjustInfiniteScrollPosition' ){
  17737. return;
  17738. }
  17739. if (args.y) {
  17740. var percentage;
  17741. var targetPercentage = args.grid.options.infiniteScrollRowsFromEnd / args.grid.renderContainers.body.visibleRowCache.length;
  17742. if (args.grid.scrollDirection === uiGridConstants.scrollDirection.UP ) {
  17743. percentage = args.y.percentage;
  17744. if (percentage <= targetPercentage){
  17745. service.loadData(args.grid);
  17746. }
  17747. } else if (args.grid.scrollDirection === uiGridConstants.scrollDirection.DOWN) {
  17748. percentage = 1 - args.y.percentage;
  17749. if (percentage <= targetPercentage){
  17750. service.loadData(args.grid);
  17751. }
  17752. }
  17753. }
  17754. },
  17755. /**
  17756. * @ngdoc function
  17757. * @name loadData
  17758. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17759. * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection
  17760. * and whether there are more pages upwards or downwards. It also stores the number of rows that we had previously,
  17761. * and clears out any saved scroll position so that we know whether or not the user calls `saveScrollPercentage`
  17762. * @param {Grid} grid the grid we're working on
  17763. */
  17764. loadData: function (grid) {
  17765. // save number of currently visible rows to calculate new scroll position later - we know that we want
  17766. // to be at approximately the row we're currently at
  17767. grid.infiniteScroll.previousVisibleRows = grid.renderContainers.body.visibleRowCache.length;
  17768. grid.infiniteScroll.direction = grid.scrollDirection;
  17769. delete grid.infiniteScroll.prevScrollTop;
  17770. if (grid.scrollDirection === uiGridConstants.scrollDirection.UP && grid.infiniteScroll.scrollUp ) {
  17771. grid.infiniteScroll.dataLoading = true;
  17772. grid.api.infiniteScroll.raise.needLoadMoreDataTop();
  17773. } else if (grid.scrollDirection === uiGridConstants.scrollDirection.DOWN && grid.infiniteScroll.scrollDown ) {
  17774. grid.infiniteScroll.dataLoading = true;
  17775. grid.api.infiniteScroll.raise.needLoadMoreData();
  17776. }
  17777. },
  17778. /**
  17779. * @ngdoc function
  17780. * @name adjustScroll
  17781. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17782. * @description Once we are informed that data has been loaded, adjust the scroll position to account for that
  17783. * addition and to make things look clean.
  17784. *
  17785. * If we're scrolling up we scroll to the first row of the old data set -
  17786. * so we're assuming that you would have gotten to the top of the grid (from the 20% need more data trigger) by
  17787. * the time the data comes back. If we're scrolling down we scoll to the last row of the old data set - so we're
  17788. * assuming that you would have gotten to the bottom of the grid (from the 80% need more data trigger) by the time
  17789. * the data comes back.
  17790. *
  17791. * Neither of these are good assumptions, but making this a smoother experience really requires
  17792. * that trigger to not be a percentage, and to be much closer to the end of the data (say, 5 rows off the end). Even then
  17793. * it'd be better still to actually run into the end. But if the data takes a while to come back, they may have scrolled
  17794. * somewhere else in the mean-time, in which case they'll get a jump back to the new data. Anyway, this will do for
  17795. * now, until someone wants to do better.
  17796. * @param {Grid} grid the grid we're working on
  17797. * @returns {promise} a promise that is resolved when scrolling has finished
  17798. */
  17799. adjustScroll: function(grid){
  17800. var promise = $q.defer();
  17801. $timeout(function () {
  17802. var newPercentage, viewportHeight, rowHeight, newVisibleRows, oldTop, newTop;
  17803. viewportHeight = grid.getViewportHeight() + grid.headerHeight - grid.renderContainers.body.headerHeight - grid.scrollbarHeight;
  17804. rowHeight = grid.options.rowHeight;
  17805. if ( grid.infiniteScroll.direction === undefined ){
  17806. // called from initialize, tweak our scroll up a little
  17807. service.adjustInfiniteScrollPosition(grid, 0);
  17808. }
  17809. newVisibleRows = grid.getVisibleRowCount();
  17810. if ( grid.infiniteScroll.direction === uiGridConstants.scrollDirection.UP ){
  17811. oldTop = grid.infiniteScroll.prevScrollTop || 0;
  17812. newTop = oldTop + (newVisibleRows - grid.infiniteScroll.previousVisibleRows)*rowHeight;
  17813. service.adjustInfiniteScrollPosition(grid, newTop);
  17814. $timeout( function() {
  17815. promise.resolve();
  17816. });
  17817. }
  17818. if ( grid.infiniteScroll.direction === uiGridConstants.scrollDirection.DOWN ){
  17819. newTop = grid.infiniteScroll.prevScrollTop || (grid.infiniteScroll.previousVisibleRows*rowHeight - viewportHeight);
  17820. service.adjustInfiniteScrollPosition(grid, newTop);
  17821. $timeout( function() {
  17822. promise.resolve();
  17823. });
  17824. }
  17825. }, 0);
  17826. return promise.promise;
  17827. },
  17828. /**
  17829. * @ngdoc function
  17830. * @name adjustInfiniteScrollPosition
  17831. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17832. * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection
  17833. * @param {Grid} grid the grid we're working on
  17834. * @param {number} scrollTop the position through the grid that we want to scroll to
  17835. * @returns {promise} a promise that is resolved when the scrolling finishes
  17836. */
  17837. adjustInfiniteScrollPosition: function (grid, scrollTop) {
  17838. var scrollEvent = new ScrollEvent(grid, null, null, 'ui.grid.adjustInfiniteScrollPosition'),
  17839. visibleRows = grid.getVisibleRowCount(),
  17840. viewportHeight = grid.getViewportHeight() + grid.headerHeight - grid.renderContainers.body.headerHeight - grid.scrollbarHeight,
  17841. rowHeight = grid.options.rowHeight,
  17842. scrollHeight = visibleRows*rowHeight-viewportHeight;
  17843. //for infinite scroll, if there are pages upwards then never allow it to be at the zero position so the up button can be active
  17844. if (scrollTop === 0 && grid.infiniteScroll.scrollUp) {
  17845. // using pixels results in a relative scroll, hence we have to use percentage
  17846. scrollEvent.y = {percentage: 1/scrollHeight};
  17847. }
  17848. else {
  17849. scrollEvent.y = {percentage: scrollTop/scrollHeight};
  17850. }
  17851. grid.scrollContainers('', scrollEvent);
  17852. },
  17853. /**
  17854. * @ngdoc function
  17855. * @name dataRemovedTop
  17856. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17857. * @description Adjusts the scroll position after you've removed data at the top. You should
  17858. * have called `saveScrollPercentage` before you remove the data, and if you're doing this in
  17859. * response to a `needMoreData` you should wait until the promise from `loadData` has resolved
  17860. * before you start removing data
  17861. * @param {Grid} grid the grid we're working on
  17862. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17863. * infinite scroll events upward
  17864. * @param {boolean} scrollDown flag that there are pages downwards, so
  17865. * fire infinite scroll events downward
  17866. * @returns {promise} a promise that is resolved when the scrolling finishes
  17867. */
  17868. dataRemovedTop: function( grid, scrollUp, scrollDown ) {
  17869. var newVisibleRows, oldTop, newTop, rowHeight;
  17870. service.setScrollDirections( grid, scrollUp, scrollDown );
  17871. newVisibleRows = grid.renderContainers.body.visibleRowCache.length;
  17872. oldTop = grid.infiniteScroll.prevScrollTop;
  17873. rowHeight = grid.options.rowHeight;
  17874. // since we removed from the top, our new scroll row will be the old scroll row less the number
  17875. // of rows removed
  17876. newTop = oldTop - ( grid.infiniteScroll.previousVisibleRows - newVisibleRows )*rowHeight;
  17877. return service.adjustInfiniteScrollPosition( grid, newTop );
  17878. },
  17879. /**
  17880. * @ngdoc function
  17881. * @name dataRemovedBottom
  17882. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17883. * @description Adjusts the scroll position after you've removed data at the bottom. You should
  17884. * have called `saveScrollPercentage` before you remove the data, and if you're doing this in
  17885. * response to a `needMoreData` you should wait until the promise from `loadData` has resolved
  17886. * before you start removing data
  17887. * @param {Grid} grid the grid we're working on
  17888. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17889. * infinite scroll events upward
  17890. * @param {boolean} scrollDown flag that there are pages downwards, so
  17891. * fire infinite scroll events downward
  17892. */
  17893. dataRemovedBottom: function( grid, scrollUp, scrollDown ) {
  17894. var newTop;
  17895. service.setScrollDirections( grid, scrollUp, scrollDown );
  17896. newTop = grid.infiniteScroll.prevScrollTop;
  17897. return service.adjustInfiniteScrollPosition( grid, newTop );
  17898. }
  17899. };
  17900. return service;
  17901. }]);
  17902. /**
  17903. * @ngdoc directive
  17904. * @name ui.grid.infiniteScroll.directive:uiGridInfiniteScroll
  17905. * @element div
  17906. * @restrict A
  17907. *
  17908. * @description Adds infinite scroll features to grid
  17909. *
  17910. * @example
  17911. <example module="app">
  17912. <file name="app.js">
  17913. var app = angular.module('app', ['ui.grid', 'ui.grid.infiniteScroll']);
  17914. app.controller('MainCtrl', ['$scope', function ($scope) {
  17915. $scope.data = [
  17916. { name: 'Alex', car: 'Toyota' },
  17917. { name: 'Sam', car: 'Lexus' }
  17918. ];
  17919. $scope.columnDefs = [
  17920. {name: 'name'},
  17921. {name: 'car'}
  17922. ];
  17923. }]);
  17924. </file>
  17925. <file name="index.html">
  17926. <div ng-controller="MainCtrl">
  17927. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-infinite-scroll="20"></div>
  17928. </div>
  17929. </file>
  17930. </example>
  17931. */
  17932. module.directive('uiGridInfiniteScroll', ['uiGridInfiniteScrollService',
  17933. function (uiGridInfiniteScrollService) {
  17934. return {
  17935. priority: -200,
  17936. scope: false,
  17937. require: '^uiGrid',
  17938. compile: function($scope, $elm, $attr){
  17939. return {
  17940. pre: function($scope, $elm, $attr, uiGridCtrl) {
  17941. uiGridInfiniteScrollService.initializeGrid(uiGridCtrl.grid, $scope);
  17942. },
  17943. post: function($scope, $elm, $attr) {
  17944. }
  17945. };
  17946. }
  17947. };
  17948. }]);
  17949. })();
  17950. (function () {
  17951. 'use strict';
  17952. /**
  17953. * @ngdoc overview
  17954. * @name ui.grid.moveColumns
  17955. * @description
  17956. *
  17957. * # ui.grid.moveColumns
  17958. *
  17959. * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div>
  17960. *
  17961. * This module provides column moving capability to ui.grid. It enables to change the position of columns.
  17962. * <div doc-module-components="ui.grid.moveColumns"></div>
  17963. */
  17964. var module = angular.module('ui.grid.moveColumns', ['ui.grid']);
  17965. /**
  17966. * @ngdoc service
  17967. * @name ui.grid.moveColumns.service:uiGridMoveColumnService
  17968. * @description Service for column moving feature.
  17969. */
  17970. module.service('uiGridMoveColumnService', ['$q', '$timeout', '$log', 'ScrollEvent', 'uiGridConstants', 'gridUtil', function ($q, $timeout, $log, ScrollEvent, uiGridConstants, gridUtil) {
  17971. var service = {
  17972. initializeGrid: function (grid) {
  17973. var self = this;
  17974. this.registerPublicApi(grid);
  17975. this.defaultGridOptions(grid.options);
  17976. grid.moveColumns = {orderCache: []}; // Used to cache the order before columns are rebuilt
  17977. grid.registerColumnBuilder(self.movableColumnBuilder);
  17978. grid.registerDataChangeCallback(self.verifyColumnOrder, [uiGridConstants.dataChange.COLUMN]);
  17979. },
  17980. registerPublicApi: function (grid) {
  17981. var self = this;
  17982. /**
  17983. * @ngdoc object
  17984. * @name ui.grid.moveColumns.api:PublicApi
  17985. * @description Public Api for column moving feature.
  17986. */
  17987. var publicApi = {
  17988. events: {
  17989. /**
  17990. * @ngdoc event
  17991. * @name columnPositionChanged
  17992. * @eventOf ui.grid.moveColumns.api:PublicApi
  17993. * @description raised when column is moved
  17994. * <pre>
  17995. * gridApi.colMovable.on.columnPositionChanged(scope,function(colDef, originalPosition, newPosition){})
  17996. * </pre>
  17997. * @param {object} colDef the column that was moved
  17998. * @param {integer} originalPosition of the column
  17999. * @param {integer} finalPosition of the column
  18000. */
  18001. colMovable: {
  18002. columnPositionChanged: function (colDef, originalPosition, newPosition) {
  18003. }
  18004. }
  18005. },
  18006. methods: {
  18007. /**
  18008. * @ngdoc method
  18009. * @name moveColumn
  18010. * @methodOf ui.grid.moveColumns.api:PublicApi
  18011. * @description Method can be used to change column position.
  18012. * <pre>
  18013. * gridApi.colMovable.moveColumn(oldPosition, newPosition)
  18014. * </pre>
  18015. * @param {integer} originalPosition of the column
  18016. * @param {integer} finalPosition of the column
  18017. */
  18018. colMovable: {
  18019. moveColumn: function (originalPosition, finalPosition) {
  18020. var columns = grid.columns;
  18021. if (!angular.isNumber(originalPosition) || !angular.isNumber(finalPosition)) {
  18022. gridUtil.logError('MoveColumn: Please provide valid values for originalPosition and finalPosition');
  18023. return;
  18024. }
  18025. var nonMovableColumns = 0;
  18026. for (var i = 0; i < columns.length; i++) {
  18027. if ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true) {
  18028. nonMovableColumns++;
  18029. }
  18030. }
  18031. if (originalPosition >= (columns.length - nonMovableColumns) || finalPosition >= (columns.length - nonMovableColumns)) {
  18032. gridUtil.logError('MoveColumn: Invalid values for originalPosition, finalPosition');
  18033. return;
  18034. }
  18035. var findPositionForRenderIndex = function (index) {
  18036. var position = index;
  18037. for (var i = 0; i <= position; i++) {
  18038. if (angular.isDefined(columns[i]) && ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true)) {
  18039. position++;
  18040. }
  18041. }
  18042. return position;
  18043. };
  18044. self.redrawColumnAtPosition(grid, findPositionForRenderIndex(originalPosition), findPositionForRenderIndex(finalPosition));
  18045. }
  18046. }
  18047. }
  18048. };
  18049. grid.api.registerEventsFromObject(publicApi.events);
  18050. grid.api.registerMethodsFromObject(publicApi.methods);
  18051. },
  18052. defaultGridOptions: function (gridOptions) {
  18053. /**
  18054. * @ngdoc object
  18055. * @name ui.grid.moveColumns.api:GridOptions
  18056. *
  18057. * @description Options for configuring the move column feature, these are available to be
  18058. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  18059. */
  18060. /**
  18061. * @ngdoc object
  18062. * @name enableColumnMoving
  18063. * @propertyOf ui.grid.moveColumns.api:GridOptions
  18064. * @description If defined, sets the default value for the colMovable flag on each individual colDefs
  18065. * if their individual enableColumnMoving configuration is not defined. Defaults to true.
  18066. */
  18067. gridOptions.enableColumnMoving = gridOptions.enableColumnMoving !== false;
  18068. },
  18069. movableColumnBuilder: function (colDef, col, gridOptions) {
  18070. var promises = [];
  18071. /**
  18072. * @ngdoc object
  18073. * @name ui.grid.moveColumns.api:ColumnDef
  18074. *
  18075. * @description Column Definition for move column feature, these are available to be
  18076. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  18077. */
  18078. /**
  18079. * @ngdoc object
  18080. * @name enableColumnMoving
  18081. * @propertyOf ui.grid.moveColumns.api:ColumnDef
  18082. * @description Enable column moving for the column.
  18083. */
  18084. colDef.enableColumnMoving = colDef.enableColumnMoving === undefined ? gridOptions.enableColumnMoving
  18085. : colDef.enableColumnMoving;
  18086. return $q.all(promises);
  18087. },
  18088. /**
  18089. * @ngdoc method
  18090. * @name updateColumnCache
  18091. * @methodOf ui.grid.moveColumns
  18092. * @description Cache the current order of columns, so we can restore them after new columnDefs are defined
  18093. */
  18094. updateColumnCache: function(grid){
  18095. grid.moveColumns.orderCache = grid.getOnlyDataColumns();
  18096. },
  18097. /**
  18098. * @ngdoc method
  18099. * @name verifyColumnOrder
  18100. * @methodOf ui.grid.moveColumns
  18101. * @description dataChangeCallback which uses the cached column order to restore the column order
  18102. * when it is reset by altering the columnDefs array.
  18103. */
  18104. verifyColumnOrder: function(grid){
  18105. var headerRowOffset = grid.rowHeaderColumns.length;
  18106. var newIndex;
  18107. angular.forEach(grid.moveColumns.orderCache, function(cacheCol, cacheIndex){
  18108. newIndex = grid.columns.indexOf(cacheCol);
  18109. if ( newIndex !== -1 && newIndex - headerRowOffset !== cacheIndex ){
  18110. var column = grid.columns.splice(newIndex, 1)[0];
  18111. grid.columns.splice(cacheIndex + headerRowOffset, 0, column);
  18112. }
  18113. });
  18114. },
  18115. redrawColumnAtPosition: function (grid, originalPosition, newPosition) {
  18116. var columns = grid.columns;
  18117. var originalColumn = columns[originalPosition];
  18118. if (originalColumn.colDef.enableColumnMoving) {
  18119. if (originalPosition > newPosition) {
  18120. for (var i1 = originalPosition; i1 > newPosition; i1--) {
  18121. columns[i1] = columns[i1 - 1];
  18122. }
  18123. }
  18124. else if (newPosition > originalPosition) {
  18125. for (var i2 = originalPosition; i2 < newPosition; i2++) {
  18126. columns[i2] = columns[i2 + 1];
  18127. }
  18128. }
  18129. columns[newPosition] = originalColumn;
  18130. service.updateColumnCache(grid);
  18131. grid.queueGridRefresh();
  18132. $timeout(function () {
  18133. grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
  18134. grid.api.colMovable.raise.columnPositionChanged(originalColumn.colDef, originalPosition, newPosition);
  18135. });
  18136. }
  18137. }
  18138. };
  18139. return service;
  18140. }]);
  18141. /**
  18142. * @ngdoc directive
  18143. * @name ui.grid.moveColumns.directive:uiGridMoveColumns
  18144. * @element div
  18145. * @restrict A
  18146. * @description Adds column moving features to the ui-grid directive.
  18147. * @example
  18148. <example module="app">
  18149. <file name="app.js">
  18150. var app = angular.module('app', ['ui.grid', 'ui.grid.moveColumns']);
  18151. app.controller('MainCtrl', ['$scope', function ($scope) {
  18152. $scope.data = [
  18153. { name: 'Bob', title: 'CEO', age: 45 },
  18154. { name: 'Frank', title: 'Lowly Developer', age: 25 },
  18155. { name: 'Jenny', title: 'Highly Developer', age: 35 }
  18156. ];
  18157. $scope.columnDefs = [
  18158. {name: 'name'},
  18159. {name: 'title'},
  18160. {name: 'age'}
  18161. ];
  18162. }]);
  18163. </file>
  18164. <file name="main.css">
  18165. .grid {
  18166. width: 100%;
  18167. height: 150px;
  18168. }
  18169. </file>
  18170. <file name="index.html">
  18171. <div ng-controller="MainCtrl">
  18172. <div class="grid" ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-move-columns></div>
  18173. </div>
  18174. </file>
  18175. </example>
  18176. */
  18177. module.directive('uiGridMoveColumns', ['uiGridMoveColumnService', function (uiGridMoveColumnService) {
  18178. return {
  18179. replace: true,
  18180. priority: 0,
  18181. require: '^uiGrid',
  18182. scope: false,
  18183. compile: function () {
  18184. return {
  18185. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  18186. uiGridMoveColumnService.initializeGrid(uiGridCtrl.grid);
  18187. },
  18188. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  18189. }
  18190. };
  18191. }
  18192. };
  18193. }]);
  18194. /**
  18195. * @ngdoc directive
  18196. * @name ui.grid.moveColumns.directive:uiGridHeaderCell
  18197. * @element div
  18198. * @restrict A
  18199. *
  18200. * @description Stacks on top of ui.grid.uiGridHeaderCell to provide capability to be able to move it to reposition column.
  18201. *
  18202. * On receiving mouseDown event headerCell is cloned, now as the mouse moves the cloned header cell also moved in the grid.
  18203. * In case the moving cloned header cell reaches the left or right extreme of grid, grid scrolling is triggered (if horizontal scroll exists).
  18204. * On mouseUp event column is repositioned at position where mouse is released and cloned header cell is removed.
  18205. *
  18206. * Events that invoke cloning of header cell:
  18207. * - mousedown
  18208. *
  18209. * Events that invoke movement of cloned header cell:
  18210. * - mousemove
  18211. *
  18212. * Events that invoke repositioning of column:
  18213. * - mouseup
  18214. */
  18215. module.directive('uiGridHeaderCell', ['$q', 'gridUtil', 'uiGridMoveColumnService', '$document', '$log', 'uiGridConstants', 'ScrollEvent',
  18216. function ($q, gridUtil, uiGridMoveColumnService, $document, $log, uiGridConstants, ScrollEvent) {
  18217. return {
  18218. priority: -10,
  18219. require: '^uiGrid',
  18220. compile: function () {
  18221. return {
  18222. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  18223. if ($scope.col.colDef.enableColumnMoving) {
  18224. /*
  18225. * Our general approach to column move is that we listen to a touchstart or mousedown
  18226. * event over the column header. When we hear one, then we wait for a move of the same type
  18227. * - if we are a touchstart then we listen for a touchmove, if we are a mousedown we listen for
  18228. * a mousemove (i.e. a drag) before we decide that there's a move underway. If there's never a move,
  18229. * and we instead get a mouseup or a touchend, then we just drop out again and do nothing.
  18230. *
  18231. */
  18232. var $contentsElm = angular.element( $elm[0].querySelectorAll('.ui-grid-cell-contents') );
  18233. var gridLeft;
  18234. var previousMouseX;
  18235. var totalMouseMovement;
  18236. var rightMoveLimit;
  18237. var elmCloned = false;
  18238. var movingElm;
  18239. var reducedWidth;
  18240. var moveOccurred = false;
  18241. var downFn = function( event ){
  18242. //Setting some variables required for calculations.
  18243. gridLeft = $scope.grid.element[0].getBoundingClientRect().left;
  18244. if ( $scope.grid.hasLeftContainer() ){
  18245. gridLeft += $scope.grid.renderContainers.left.header[0].getBoundingClientRect().width;
  18246. }
  18247. previousMouseX = event.pageX;
  18248. totalMouseMovement = 0;
  18249. rightMoveLimit = gridLeft + $scope.grid.getViewportWidth();
  18250. if ( event.type === 'mousedown' ){
  18251. $document.on('mousemove', moveFn);
  18252. $document.on('mouseup', upFn);
  18253. } else if ( event.type === 'touchstart' ){
  18254. $document.on('touchmove', moveFn);
  18255. $document.on('touchend', upFn);
  18256. }
  18257. };
  18258. var moveFn = function( event ) {
  18259. var changeValue = event.pageX - previousMouseX;
  18260. if ( changeValue === 0 ){ return; }
  18261. //Disable text selection in Chrome during column move
  18262. document.onselectstart = function() { return false; };
  18263. moveOccurred = true;
  18264. if (!elmCloned) {
  18265. cloneElement();
  18266. }
  18267. else if (elmCloned) {
  18268. moveElement(changeValue);
  18269. previousMouseX = event.pageX;
  18270. }
  18271. };
  18272. var upFn = function( event ){
  18273. //Re-enable text selection after column move
  18274. document.onselectstart = null;
  18275. //Remove the cloned element on mouse up.
  18276. if (movingElm) {
  18277. movingElm.remove();
  18278. elmCloned = false;
  18279. }
  18280. offAllEvents();
  18281. onDownEvents();
  18282. if (!moveOccurred){
  18283. return;
  18284. }
  18285. var columns = $scope.grid.columns;
  18286. var columnIndex = 0;
  18287. for (var i = 0; i < columns.length; i++) {
  18288. if (columns[i].colDef.name !== $scope.col.colDef.name) {
  18289. columnIndex++;
  18290. }
  18291. else {
  18292. break;
  18293. }
  18294. }
  18295. //Case where column should be moved to a position on its left
  18296. if (totalMouseMovement < 0) {
  18297. var totalColumnsLeftWidth = 0;
  18298. for (var il = columnIndex - 1; il >= 0; il--) {
  18299. if (angular.isUndefined(columns[il].colDef.visible) || columns[il].colDef.visible === true) {
  18300. totalColumnsLeftWidth += columns[il].drawnWidth || columns[il].width || columns[il].colDef.width;
  18301. if (totalColumnsLeftWidth > Math.abs(totalMouseMovement)) {
  18302. uiGridMoveColumnService.redrawColumnAtPosition
  18303. ($scope.grid, columnIndex, il + 1);
  18304. break;
  18305. }
  18306. }
  18307. }
  18308. //Case where column should be moved to beginning of the grid.
  18309. if (totalColumnsLeftWidth < Math.abs(totalMouseMovement)) {
  18310. uiGridMoveColumnService.redrawColumnAtPosition
  18311. ($scope.grid, columnIndex, 0);
  18312. }
  18313. }
  18314. //Case where column should be moved to a position on its right
  18315. else if (totalMouseMovement > 0) {
  18316. var totalColumnsRightWidth = 0;
  18317. for (var ir = columnIndex + 1; ir < columns.length; ir++) {
  18318. if (angular.isUndefined(columns[ir].colDef.visible) || columns[ir].colDef.visible === true) {
  18319. totalColumnsRightWidth += columns[ir].drawnWidth || columns[ir].width || columns[ir].colDef.width;
  18320. if (totalColumnsRightWidth > totalMouseMovement) {
  18321. uiGridMoveColumnService.redrawColumnAtPosition
  18322. ($scope.grid, columnIndex, ir - 1);
  18323. break;
  18324. }
  18325. }
  18326. }
  18327. //Case where column should be moved to end of the grid.
  18328. if (totalColumnsRightWidth < totalMouseMovement) {
  18329. uiGridMoveColumnService.redrawColumnAtPosition
  18330. ($scope.grid, columnIndex, columns.length - 1);
  18331. }
  18332. }
  18333. };
  18334. var onDownEvents = function(){
  18335. $contentsElm.on('touchstart', downFn);
  18336. $contentsElm.on('mousedown', downFn);
  18337. };
  18338. var offAllEvents = function() {
  18339. $contentsElm.off('touchstart', downFn);
  18340. $contentsElm.off('mousedown', downFn);
  18341. $document.off('mousemove', moveFn);
  18342. $document.off('touchmove', moveFn);
  18343. $document.off('mouseup', upFn);
  18344. $document.off('touchend', upFn);
  18345. };
  18346. onDownEvents();
  18347. var cloneElement = function () {
  18348. elmCloned = true;
  18349. //Cloning header cell and appending to current header cell.
  18350. movingElm = $elm.clone();
  18351. $elm.parent().append(movingElm);
  18352. //Left of cloned element should be aligned to original header cell.
  18353. movingElm.addClass('movingColumn');
  18354. var movingElementStyles = {};
  18355. var elmLeft;
  18356. if (gridUtil.detectBrowser() === 'safari') {
  18357. //Correction for Safari getBoundingClientRect,
  18358. //which does not correctly compute when there is an horizontal scroll
  18359. elmLeft = $elm[0].offsetLeft + $elm[0].offsetWidth - $elm[0].getBoundingClientRect().width;
  18360. }
  18361. else {
  18362. elmLeft = $elm[0].getBoundingClientRect().left;
  18363. }
  18364. movingElementStyles.left = (elmLeft - gridLeft) + 'px';
  18365. var gridRight = $scope.grid.element[0].getBoundingClientRect().right;
  18366. var elmRight = $elm[0].getBoundingClientRect().right;
  18367. if (elmRight > gridRight) {
  18368. reducedWidth = $scope.col.drawnWidth + (gridRight - elmRight);
  18369. movingElementStyles.width = reducedWidth + 'px';
  18370. }
  18371. movingElm.css(movingElementStyles);
  18372. };
  18373. var moveElement = function (changeValue) {
  18374. //Calculate total column width
  18375. var columns = $scope.grid.columns;
  18376. var totalColumnWidth = 0;
  18377. for (var i = 0; i < columns.length; i++) {
  18378. if (angular.isUndefined(columns[i].colDef.visible) || columns[i].colDef.visible === true) {
  18379. totalColumnWidth += columns[i].drawnWidth || columns[i].width || columns[i].colDef.width;
  18380. }
  18381. }
  18382. //Calculate new position of left of column
  18383. var currentElmLeft = movingElm[0].getBoundingClientRect().left - 1;
  18384. var currentElmRight = movingElm[0].getBoundingClientRect().right;
  18385. var newElementLeft;
  18386. newElementLeft = currentElmLeft - gridLeft + changeValue;
  18387. newElementLeft = newElementLeft < rightMoveLimit ? newElementLeft : rightMoveLimit;
  18388. //Update css of moving column to adjust to new left value or fire scroll in case column has reached edge of grid
  18389. if ((currentElmLeft >= gridLeft || changeValue > 0) && (currentElmRight <= rightMoveLimit || changeValue < 0)) {
  18390. movingElm.css({visibility: 'visible', 'left': newElementLeft + 'px'});
  18391. }
  18392. else if (totalColumnWidth > Math.ceil(uiGridCtrl.grid.gridWidth)) {
  18393. changeValue *= 8;
  18394. var scrollEvent = new ScrollEvent($scope.col.grid, null, null, 'uiGridHeaderCell.moveElement');
  18395. scrollEvent.x = {pixels: changeValue};
  18396. scrollEvent.grid.scrollContainers('',scrollEvent);
  18397. }
  18398. //Calculate total width of columns on the left of the moving column and the mouse movement
  18399. var totalColumnsLeftWidth = 0;
  18400. for (var il = 0; il < columns.length; il++) {
  18401. if (angular.isUndefined(columns[il].colDef.visible) || columns[il].colDef.visible === true) {
  18402. if (columns[il].colDef.name !== $scope.col.colDef.name) {
  18403. totalColumnsLeftWidth += columns[il].drawnWidth || columns[il].width || columns[il].colDef.width;
  18404. }
  18405. else {
  18406. break;
  18407. }
  18408. }
  18409. }
  18410. if ($scope.newScrollLeft === undefined) {
  18411. totalMouseMovement += changeValue;
  18412. }
  18413. else {
  18414. totalMouseMovement = $scope.newScrollLeft + newElementLeft - totalColumnsLeftWidth;
  18415. }
  18416. //Increase width of moving column, in case the rightmost column was moved and its width was
  18417. //decreased because of overflow
  18418. if (reducedWidth < $scope.col.drawnWidth) {
  18419. reducedWidth += Math.abs(changeValue);
  18420. movingElm.css({'width': reducedWidth + 'px'});
  18421. }
  18422. };
  18423. }
  18424. }
  18425. };
  18426. }
  18427. };
  18428. }]);
  18429. })();
  18430. (function() {
  18431. 'use strict';
  18432. /**
  18433. * @ngdoc overview
  18434. * @name ui.grid.pagination
  18435. *
  18436. * @description
  18437. *
  18438. * # ui.grid.pagination
  18439. *
  18440. * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div>
  18441. *
  18442. * This module provides pagination support to ui-grid
  18443. */
  18444. var module = angular.module('ui.grid.pagination', ['ng', 'ui.grid']);
  18445. /**
  18446. * @ngdoc service
  18447. * @name ui.grid.pagination.service:uiGridPaginationService
  18448. *
  18449. * @description Service for the pagination feature
  18450. */
  18451. module.service('uiGridPaginationService', ['gridUtil','$rootScope',
  18452. function (gridUtil,$rootScope) {
  18453. var service = {
  18454. /**
  18455. * @ngdoc method
  18456. * @name initializeGrid
  18457. * @methodOf ui.grid.pagination.service:uiGridPaginationService
  18458. * @description Attaches the service to a certain grid
  18459. * @param {Grid} grid The grid we want to work with
  18460. */
  18461. initializeGrid: function (grid) {
  18462. service.defaultGridOptions(grid.options);
  18463. /**
  18464. * @ngdoc object
  18465. * @name ui.grid.pagination.api:PublicAPI
  18466. *
  18467. * @description Public API for the pagination feature
  18468. */
  18469. var publicApi = {
  18470. events: {
  18471. pagination: {
  18472. /**
  18473. * @ngdoc event
  18474. * @name paginationChanged
  18475. * @eventOf ui.grid.pagination.api:PublicAPI
  18476. * @description This event fires when the pageSize or currentPage changes
  18477. * @param {int} currentPage requested page number
  18478. * @param {int} pageSize requested page size
  18479. */
  18480. paginationChanged: function (currentPage, pageSize) { }
  18481. }
  18482. },
  18483. methods: {
  18484. pagination: {
  18485. /**
  18486. * @ngdoc method
  18487. * @name getPage
  18488. * @methodOf ui.grid.pagination.api:PublicAPI
  18489. * @description Returns the number of the current page
  18490. */
  18491. getPage: function () {
  18492. return grid.options.enablePagination ? grid.options.paginationCurrentPage : null;
  18493. },
  18494. /**
  18495. * @ngdoc method
  18496. * @name getTotalPages
  18497. * @methodOf ui.grid.pagination.api:PublicAPI
  18498. * @description Returns the total number of pages
  18499. */
  18500. getTotalPages: function () {
  18501. if (!grid.options.enablePagination) {
  18502. return null;
  18503. }
  18504. return (grid.options.totalItems === 0) ? 1 : Math.ceil(grid.options.totalItems / grid.options.paginationPageSize);
  18505. },
  18506. /**
  18507. * @ngdoc method
  18508. * @name nextPage
  18509. * @methodOf ui.grid.pagination.api:PublicAPI
  18510. * @description Moves to the next page, if possible
  18511. */
  18512. nextPage: function () {
  18513. if (!grid.options.enablePagination) {
  18514. return;
  18515. }
  18516. if (grid.options.totalItems > 0) {
  18517. grid.options.paginationCurrentPage = Math.min(
  18518. grid.options.paginationCurrentPage + 1,
  18519. publicApi.methods.pagination.getTotalPages()
  18520. );
  18521. } else {
  18522. grid.options.paginationCurrentPage++;
  18523. }
  18524. },
  18525. /**
  18526. * @ngdoc method
  18527. * @name previousPage
  18528. * @methodOf ui.grid.pagination.api:PublicAPI
  18529. * @description Moves to the previous page, if we're not on the first page
  18530. */
  18531. previousPage: function () {
  18532. if (!grid.options.enablePagination) {
  18533. return;
  18534. }
  18535. grid.options.paginationCurrentPage = Math.max(grid.options.paginationCurrentPage - 1, 1);
  18536. },
  18537. /**
  18538. * @ngdoc method
  18539. * @name seek
  18540. * @methodOf ui.grid.pagination.api:PublicAPI
  18541. * @description Moves to the requested page
  18542. * @param {int} page The number of the page that should be displayed
  18543. */
  18544. seek: function (page) {
  18545. if (!grid.options.enablePagination) {
  18546. return;
  18547. }
  18548. if (!angular.isNumber(page) || page < 1) {
  18549. throw 'Invalid page number: ' + page;
  18550. }
  18551. grid.options.paginationCurrentPage = Math.min(page, publicApi.methods.pagination.getTotalPages());
  18552. }
  18553. }
  18554. }
  18555. };
  18556. grid.api.registerEventsFromObject(publicApi.events);
  18557. grid.api.registerMethodsFromObject(publicApi.methods);
  18558. var processPagination = function( renderableRows ){
  18559. if (grid.options.useExternalPagination || !grid.options.enablePagination) {
  18560. return renderableRows;
  18561. }
  18562. //client side pagination
  18563. var pageSize = parseInt(grid.options.paginationPageSize, 10);
  18564. var currentPage = parseInt(grid.options.paginationCurrentPage, 10);
  18565. var visibleRows = renderableRows.filter(function (row) { return row.visible; });
  18566. grid.options.totalItems = visibleRows.length;
  18567. var firstRow = (currentPage - 1) * pageSize;
  18568. if (firstRow > visibleRows.length) {
  18569. currentPage = grid.options.paginationCurrentPage = 1;
  18570. firstRow = (currentPage - 1) * pageSize;
  18571. }
  18572. return visibleRows.slice(firstRow, firstRow + pageSize);
  18573. };
  18574. grid.registerRowsProcessor(processPagination, 900 );
  18575. },
  18576. defaultGridOptions: function (gridOptions) {
  18577. /**
  18578. * @ngdoc object
  18579. * @name ui.grid.pagination.api:GridOptions
  18580. *
  18581. * @description GridOptions for the pagination feature, these are available to be
  18582. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  18583. */
  18584. /**
  18585. * @ngdoc property
  18586. * @name enablePagination
  18587. * @propertyOf ui.grid.pagination.api:GridOptions
  18588. * @description Enables pagination, defaults to true
  18589. */
  18590. gridOptions.enablePagination = gridOptions.enablePagination !== false;
  18591. /**
  18592. * @ngdoc property
  18593. * @name enablePaginationControls
  18594. * @propertyOf ui.grid.pagination.api:GridOptions
  18595. * @description Enables the paginator at the bottom of the grid. Turn this off, if you want to implement your
  18596. * own controls outside the grid.
  18597. */
  18598. gridOptions.enablePaginationControls = gridOptions.enablePaginationControls !== false;
  18599. /**
  18600. * @ngdoc property
  18601. * @name useExternalPagination
  18602. * @propertyOf ui.grid.pagination.api:GridOptions
  18603. * @description Disables client side pagination. When true, handle the paginationChanged event and set data
  18604. * and totalItems, defaults to `false`
  18605. */
  18606. gridOptions.useExternalPagination = gridOptions.useExternalPagination === true;
  18607. /**
  18608. * @ngdoc property
  18609. * @name totalItems
  18610. * @propertyOf ui.grid.pagination.api:GridOptions
  18611. * @description Total number of items, set automatically when client side pagination, needs set by user
  18612. * for server side pagination
  18613. */
  18614. if (gridUtil.isNullOrUndefined(gridOptions.totalItems)) {
  18615. gridOptions.totalItems = 0;
  18616. }
  18617. /**
  18618. * @ngdoc property
  18619. * @name paginationPageSizes
  18620. * @propertyOf ui.grid.pagination.api:GridOptions
  18621. * @description Array of page sizes, defaults to `[250, 500, 1000]`
  18622. */
  18623. if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSizes)) {
  18624. gridOptions.paginationPageSizes = [10, 20, 50,100];
  18625. }
  18626. /**
  18627. * @ngdoc property
  18628. * @name paginationPageSize
  18629. * @propertyOf ui.grid.pagination.api:GridOptions
  18630. * @description Page size, defaults to the first item in paginationPageSizes, or 0 if paginationPageSizes is empty
  18631. */
  18632. if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSize)) {
  18633. if (gridOptions.paginationPageSizes.length > 0) {
  18634. gridOptions.paginationPageSize = gridOptions.paginationPageSizes[0];
  18635. } else {
  18636. gridOptions.paginationPageSize = 0;
  18637. }
  18638. }
  18639. /**
  18640. * @ngdoc property
  18641. * @name paginationCurrentPage
  18642. * @propertyOf ui.grid.pagination.api:GridOptions
  18643. * @description Current page number, defaults to 1
  18644. */
  18645. gridOptions.refresh=function(){
  18646. gridOptions.paginationCurrentPage =1;
  18647. }
  18648. if (gridUtil.isNullOrUndefined(gridOptions.paginationCurrentPage)) {
  18649. if($rootScope.cmdbs=='incident'||$rootScope.cmdbs=='problem'||$rootScope.cmdbs=='release'||$rootScope.cmdbs=='change'||$rootScope.cmdbs=='cmdb'||$rootScope.cmdbs=='scheduling'||$rootScope.cmdbs=='user'||$rootScope.cmdbs=='nav'||$rootScope.cmdbs=='role'){
  18650. gridOptions.paginationCurrentPage = $rootScope.idx;
  18651. $rootScope.cmdbs=''
  18652. }
  18653. // $rootScope.cmdbs=''
  18654. else{gridOptions.paginationCurrentPage =1;}
  18655. }
  18656. /**
  18657. * @ngdoc property
  18658. * @name paginationTemplate
  18659. * @propertyOf ui.grid.pagination.api:GridOptions
  18660. * @description A custom template for the pager, defaults to `ui-grid/pagination`
  18661. */
  18662. if (gridUtil.isNullOrUndefined(gridOptions.paginationTemplate)) {
  18663. gridOptions.paginationTemplate = 'ui-grid/pagination';
  18664. }
  18665. },
  18666. /**
  18667. * @ngdoc method
  18668. * @methodOf ui.grid.pagination.service:uiGridPaginationService
  18669. * @name uiGridPaginationService
  18670. * @description Raises paginationChanged and calls refresh for client side pagination
  18671. * @param {Grid} grid the grid for which the pagination changed
  18672. * @param {int} currentPage requested page number
  18673. * @param {int} pageSize requested page size
  18674. */
  18675. onPaginationChanged: function (grid, currentPage, pageSize) {
  18676. grid.api.pagination.raise.paginationChanged(currentPage, pageSize);
  18677. if (!grid.options.useExternalPagination) {
  18678. grid.queueGridRefresh(); //client side pagination
  18679. }
  18680. }
  18681. };
  18682. return service;
  18683. }
  18684. ]);
  18685. /**
  18686. * @ngdoc directive
  18687. * @name ui.grid.pagination.directive:uiGridPagination
  18688. * @element div
  18689. * @restrict A
  18690. *
  18691. * @description Adds pagination features to grid
  18692. * @example
  18693. <example module="app">
  18694. <file name="app.js">
  18695. var app = angular.module('app', ['ui.grid', 'ui.grid.pagination']);
  18696. app.controller('MainCtrl', ['$scope', function ($scope) {
  18697. $scope.data = [
  18698. { name: 'Alex', car: 'Toyota' },
  18699. { name: 'Sam', car: 'Lexus' },
  18700. { name: 'Joe', car: 'Dodge' },
  18701. { name: 'Bob', car: 'Buick' },
  18702. { name: 'Cindy', car: 'Ford' },
  18703. { name: 'Brian', car: 'Audi' },
  18704. { name: 'Malcom', car: 'Mercedes Benz' },
  18705. { name: 'Dave', car: 'Ford' },
  18706. { name: 'Stacey', car: 'Audi' },
  18707. { name: 'Amy', car: 'Acura' },
  18708. { name: 'Scott', car: 'Toyota' },
  18709. { name: 'Ryan', car: 'BMW' },
  18710. ];
  18711. $scope.gridOptions = {
  18712. data: 'data',
  18713. paginationPageSizes: [5, 10, 25],
  18714. paginationPageSize: 5,
  18715. columnDefs: [
  18716. {name: 'name'},
  18717. {name: 'car'}
  18718. ]
  18719. }
  18720. }]);
  18721. </file>
  18722. <file name="index.html">
  18723. <div ng-controller="MainCtrl">
  18724. <div ui-grid="gridOptions" ui-grid-pagination></div>
  18725. </div>
  18726. </file>
  18727. </example>
  18728. */
  18729. module.directive('uiGridPagination', ['gridUtil', 'uiGridPaginationService',
  18730. function (gridUtil, uiGridPaginationService) {
  18731. return {
  18732. priority: -200,
  18733. scope: false,
  18734. require: 'uiGrid',
  18735. link: {
  18736. pre: function ($scope, $elm, $attr, uiGridCtrl) {
  18737. uiGridPaginationService.initializeGrid(uiGridCtrl.grid);
  18738. gridUtil.getTemplate(uiGridCtrl.grid.options.paginationTemplate)
  18739. .then(function (contents) {
  18740. var template = angular.element(contents);
  18741. $elm.append(template);
  18742. uiGridCtrl.innerCompile(template);
  18743. });
  18744. }
  18745. }
  18746. };
  18747. }
  18748. ]);
  18749. /**
  18750. * @ngdoc directive
  18751. * @name ui.grid.pagination.directive:uiGridPager
  18752. * @element div
  18753. *
  18754. * @description Panel for handling pagination
  18755. */
  18756. module.directive('uiGridPager', ['uiGridPaginationService', 'uiGridConstants', 'gridUtil', 'i18nService',
  18757. function (uiGridPaginationService, uiGridConstants, gridUtil, i18nService) {
  18758. return {
  18759. priority: -200,
  18760. scope: true,
  18761. require: '^uiGrid',
  18762. link: function ($scope, $elm, $attr, uiGridCtrl) {
  18763. var defaultFocusElementSelector = '.ui-grid-pager-control-input';
  18764. $scope.aria = i18nService.getSafeText('pagination.aria'); //Returns an object with all of the aria labels
  18765. $scope.paginationApi = uiGridCtrl.grid.api.pagination;
  18766. $scope.sizesLabel = i18nService.getSafeText('pagination.sizes');
  18767. $scope.totalItemsLabel = i18nService.getSafeText('pagination.totalItems');
  18768. $scope.paginationOf = i18nService.getSafeText('pagination.of');
  18769. $scope.paginationThrough = i18nService.getSafeText('pagination.through');
  18770. var options = uiGridCtrl.grid.options;
  18771. uiGridCtrl.grid.renderContainers.body.registerViewportAdjuster(function (adjustment) {
  18772. adjustment.height = adjustment.height - gridUtil.elementHeight($elm);
  18773. return adjustment;
  18774. });
  18775. var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback(function (grid) {
  18776. if (!grid.options.useExternalPagination) {
  18777. grid.options.totalItems = grid.rows.length;
  18778. }
  18779. }, [uiGridConstants.dataChange.ROW]);
  18780. $scope.$on('$destroy', dataChangeDereg);
  18781. var setShowing = function () {
  18782. $scope.showingLow = ((options.paginationCurrentPage - 1) * options.paginationPageSize) + 1;
  18783. $scope.showingHigh = Math.min(options.paginationCurrentPage * options.paginationPageSize, options.totalItems);
  18784. };
  18785. var deregT = $scope.$watch('grid.options.totalItems + grid.options.paginationPageSize', setShowing);
  18786. var deregP = $scope.$watch('grid.options.paginationCurrentPage + grid.options.paginationPageSize', function (newValues, oldValues) {
  18787. if (newValues === oldValues || oldValues === undefined) {
  18788. return;
  18789. }
  18790. if (!angular.isNumber(options.paginationCurrentPage) || options.paginationCurrentPage < 1) {
  18791. options.paginationCurrentPage = 1;
  18792. return;
  18793. }
  18794. if (options.totalItems > 0 && options.paginationCurrentPage > $scope.paginationApi.getTotalPages()) {
  18795. options.paginationCurrentPage = $scope.paginationApi.getTotalPages();
  18796. return;
  18797. }
  18798. setShowing();
  18799. uiGridPaginationService.onPaginationChanged($scope.grid, options.paginationCurrentPage, options.paginationPageSize);
  18800. }
  18801. );
  18802. $scope.$on('$destroy', function() {
  18803. deregT();
  18804. deregP();
  18805. });
  18806. $scope.cantPageForward = function () {
  18807. if (options.totalItems > 0) {
  18808. return options.paginationCurrentPage >= $scope.paginationApi.getTotalPages();
  18809. } else {
  18810. return options.data.length > 1;
  18811. }
  18812. };
  18813. $scope.cantPageToLast = function () {
  18814. if (options.totalItems > 0) {
  18815. return $scope.cantPageForward();
  18816. } else {
  18817. return true;
  18818. }
  18819. };
  18820. $scope.cantPageBackward = function () {
  18821. return options.paginationCurrentPage <= 1;
  18822. };
  18823. var focusToInputIf = function(condition){
  18824. if (condition){
  18825. gridUtil.focus.bySelector($elm, defaultFocusElementSelector);
  18826. }
  18827. };
  18828. //Takes care of setting focus to the middle element when focus is lost
  18829. $scope.pageFirstPageClick = function () {
  18830. $scope.paginationApi.seek(1);
  18831. focusToInputIf($scope.cantPageBackward());
  18832. };
  18833. $scope.pagePreviousPageClick = function () {
  18834. $scope.paginationApi.previousPage();
  18835. focusToInputIf($scope.cantPageBackward());
  18836. };
  18837. $scope.pageNextPageClick = function () {
  18838. $scope.paginationApi.nextPage();
  18839. focusToInputIf($scope.cantPageForward());
  18840. };
  18841. $scope.pageLastPageClick = function () {
  18842. $scope.paginationApi.seek($scope.paginationApi.getTotalPages());
  18843. focusToInputIf($scope.cantPageToLast());
  18844. };
  18845. }
  18846. };
  18847. }
  18848. ]);
  18849. })();
  18850. (function () {
  18851. 'use strict';
  18852. /**
  18853. * @ngdoc overview
  18854. * @name ui.grid.pinning
  18855. * @description
  18856. *
  18857. * # ui.grid.pinning
  18858. *
  18859. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  18860. *
  18861. * This module provides column pinning to the end user via menu options in the column header
  18862. *
  18863. * <div doc-module-components="ui.grid.pinning"></div>
  18864. */
  18865. var module = angular.module('ui.grid.pinning', ['ui.grid']);
  18866. module.constant('uiGridPinningConstants', {
  18867. container: {
  18868. LEFT: 'left',
  18869. RIGHT: 'right',
  18870. NONE: ''
  18871. }
  18872. });
  18873. module.service('uiGridPinningService', ['gridUtil', 'GridRenderContainer', 'i18nService', 'uiGridPinningConstants', function (gridUtil, GridRenderContainer, i18nService, uiGridPinningConstants) {
  18874. var service = {
  18875. initializeGrid: function (grid) {
  18876. service.defaultGridOptions(grid.options);
  18877. // Register a column builder to add new menu items for pinning left and right
  18878. grid.registerColumnBuilder(service.pinningColumnBuilder);
  18879. /**
  18880. * @ngdoc object
  18881. * @name ui.grid.pinning.api:PublicApi
  18882. *
  18883. * @description Public Api for pinning feature
  18884. */
  18885. var publicApi = {
  18886. events: {
  18887. pinning: {
  18888. /**
  18889. * @ngdoc event
  18890. * @name columnPin
  18891. * @eventOf ui.grid.pinning.api:PublicApi
  18892. * @description raised when column pin state has changed
  18893. * <pre>
  18894. * gridApi.pinning.on.columnPinned(scope, function(colDef){})
  18895. * </pre>
  18896. * @param {object} colDef the column that was changed
  18897. * @param {string} container the render container the column is in ('left', 'right', '')
  18898. */
  18899. columnPinned: function(colDef, container) {
  18900. }
  18901. }
  18902. },
  18903. methods: {
  18904. pinning: {
  18905. /**
  18906. * @ngdoc function
  18907. * @name pinColumn
  18908. * @methodOf ui.grid.pinning.api:PublicApi
  18909. * @description pin column left, right, or none
  18910. * <pre>
  18911. * gridApi.pinning.pinColumn(col, uiGridPinningConstants.container.LEFT)
  18912. * </pre>
  18913. * @param {gridColumn} col the column being pinned
  18914. * @param {string} container one of the recognised types
  18915. * from uiGridPinningConstants
  18916. */
  18917. pinColumn: function(col, container) {
  18918. service.pinColumn(grid, col, container);
  18919. }
  18920. }
  18921. }
  18922. };
  18923. grid.api.registerEventsFromObject(publicApi.events);
  18924. grid.api.registerMethodsFromObject(publicApi.methods);
  18925. },
  18926. defaultGridOptions: function (gridOptions) {
  18927. //default option to true unless it was explicitly set to false
  18928. /**
  18929. * @ngdoc object
  18930. * @name ui.grid.pinning.api:GridOptions
  18931. *
  18932. * @description GridOptions for pinning feature, these are available to be
  18933. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  18934. */
  18935. /**
  18936. * @ngdoc object
  18937. * @name enablePinning
  18938. * @propertyOf ui.grid.pinning.api:GridOptions
  18939. * @description Enable pinning for the entire grid.
  18940. * <br/>Defaults to true
  18941. */
  18942. gridOptions.enablePinning = gridOptions.enablePinning !== false;
  18943. },
  18944. pinningColumnBuilder: function (colDef, col, gridOptions) {
  18945. //default to true unless gridOptions or colDef is explicitly false
  18946. /**
  18947. * @ngdoc object
  18948. * @name ui.grid.pinning.api:ColumnDef
  18949. *
  18950. * @description ColumnDef for pinning feature, these are available to be
  18951. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  18952. */
  18953. /**
  18954. * @ngdoc object
  18955. * @name enablePinning
  18956. * @propertyOf ui.grid.pinning.api:ColumnDef
  18957. * @description Enable pinning for the individual column.
  18958. * <br/>Defaults to true
  18959. */
  18960. colDef.enablePinning = colDef.enablePinning === undefined ? gridOptions.enablePinning : colDef.enablePinning;
  18961. /**
  18962. * @ngdoc object
  18963. * @name pinnedLeft
  18964. * @propertyOf ui.grid.pinning.api:ColumnDef
  18965. * @description Column is pinned left when grid is rendered
  18966. * <br/>Defaults to false
  18967. */
  18968. /**
  18969. * @ngdoc object
  18970. * @name pinnedRight
  18971. * @propertyOf ui.grid.pinning.api:ColumnDef
  18972. * @description Column is pinned right when grid is rendered
  18973. * <br/>Defaults to false
  18974. */
  18975. if (colDef.pinnedLeft) {
  18976. col.renderContainer = 'left';
  18977. col.grid.createLeftContainer();
  18978. }
  18979. else if (colDef.pinnedRight) {
  18980. col.renderContainer = 'right';
  18981. col.grid.createRightContainer();
  18982. }
  18983. if (!colDef.enablePinning) {
  18984. return;
  18985. }
  18986. var pinColumnLeftAction = {
  18987. name: 'ui.grid.pinning.pinLeft',
  18988. title: i18nService.get().pinning.pinLeft,
  18989. icon: 'ui-grid-icon-left-open',
  18990. shown: function () {
  18991. return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'left';
  18992. },
  18993. action: function () {
  18994. service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.LEFT);
  18995. }
  18996. };
  18997. var pinColumnRightAction = {
  18998. name: 'ui.grid.pinning.pinRight',
  18999. title: i18nService.get().pinning.pinRight,
  19000. icon: 'ui-grid-icon-right-open',
  19001. shown: function () {
  19002. return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'right';
  19003. },
  19004. action: function () {
  19005. service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.RIGHT);
  19006. }
  19007. };
  19008. var removePinAction = {
  19009. name: 'ui.grid.pinning.unpin',
  19010. title: i18nService.get().pinning.unpin,
  19011. icon: 'ui-grid-icon-cancel',
  19012. shown: function () {
  19013. return typeof(this.context.col.renderContainer) !== 'undefined' && this.context.col.renderContainer !== null && this.context.col.renderContainer !== 'body';
  19014. },
  19015. action: function () {
  19016. service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.UNPIN);
  19017. }
  19018. };
  19019. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinLeft')) {
  19020. col.menuItems.push(pinColumnLeftAction);
  19021. }
  19022. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinRight')) {
  19023. col.menuItems.push(pinColumnRightAction);
  19024. }
  19025. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.unpin')) {
  19026. col.menuItems.push(removePinAction);
  19027. }
  19028. },
  19029. pinColumn: function(grid, col, container) {
  19030. if (container === uiGridPinningConstants.container.NONE) {
  19031. col.renderContainer = null;
  19032. }
  19033. else {
  19034. col.renderContainer = container;
  19035. if (container === uiGridPinningConstants.container.LEFT) {
  19036. grid.createLeftContainer();
  19037. }
  19038. else if (container === uiGridPinningConstants.container.RIGHT) {
  19039. grid.createRightContainer();
  19040. }
  19041. }
  19042. grid.refresh()
  19043. .then(function() {
  19044. grid.api.pinning.raise.columnPinned( col.colDef, container );
  19045. });
  19046. }
  19047. };
  19048. return service;
  19049. }]);
  19050. module.directive('uiGridPinning', ['gridUtil', 'uiGridPinningService',
  19051. function (gridUtil, uiGridPinningService) {
  19052. return {
  19053. require: 'uiGrid',
  19054. scope: false,
  19055. compile: function () {
  19056. return {
  19057. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  19058. uiGridPinningService.initializeGrid(uiGridCtrl.grid);
  19059. },
  19060. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  19061. }
  19062. };
  19063. }
  19064. };
  19065. }]);
  19066. })();
  19067. (function(){
  19068. 'use strict';
  19069. /**
  19070. * @ngdoc overview
  19071. * @name ui.grid.resizeColumns
  19072. * @description
  19073. *
  19074. * # ui.grid.resizeColumns
  19075. *
  19076. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  19077. *
  19078. * This module allows columns to be resized.
  19079. */
  19080. var module = angular.module('ui.grid.resizeColumns', ['ui.grid']);
  19081. module.service('uiGridResizeColumnsService', ['gridUtil', '$q', '$timeout',
  19082. function (gridUtil, $q, $timeout) {
  19083. var service = {
  19084. defaultGridOptions: function(gridOptions){
  19085. //default option to true unless it was explicitly set to false
  19086. /**
  19087. * @ngdoc object
  19088. * @name ui.grid.resizeColumns.api:GridOptions
  19089. *
  19090. * @description GridOptions for resizeColumns feature, these are available to be
  19091. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  19092. */
  19093. /**
  19094. * @ngdoc object
  19095. * @name enableColumnResizing
  19096. * @propertyOf ui.grid.resizeColumns.api:GridOptions
  19097. * @description Enable column resizing on the entire grid
  19098. * <br/>Defaults to true
  19099. */
  19100. gridOptions.enableColumnResizing = gridOptions.enableColumnResizing !== false;
  19101. //legacy support
  19102. //use old name if it is explicitly false
  19103. if (gridOptions.enableColumnResize === false){
  19104. gridOptions.enableColumnResizing = false;
  19105. }
  19106. },
  19107. colResizerColumnBuilder: function (colDef, col, gridOptions) {
  19108. var promises = [];
  19109. /**
  19110. * @ngdoc object
  19111. * @name ui.grid.resizeColumns.api:ColumnDef
  19112. *
  19113. * @description ColumnDef for resizeColumns feature, these are available to be
  19114. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  19115. */
  19116. /**
  19117. * @ngdoc object
  19118. * @name enableColumnResizing
  19119. * @propertyOf ui.grid.resizeColumns.api:ColumnDef
  19120. * @description Enable column resizing on an individual column
  19121. * <br/>Defaults to GridOptions.enableColumnResizing
  19122. */
  19123. //default to true unless gridOptions or colDef is explicitly false
  19124. colDef.enableColumnResizing = colDef.enableColumnResizing === undefined ? gridOptions.enableColumnResizing : colDef.enableColumnResizing;
  19125. //legacy support of old option name
  19126. if (colDef.enableColumnResize === false){
  19127. colDef.enableColumnResizing = false;
  19128. }
  19129. return $q.all(promises);
  19130. },
  19131. registerPublicApi: function (grid) {
  19132. /**
  19133. * @ngdoc object
  19134. * @name ui.grid.resizeColumns.api:PublicApi
  19135. * @description Public Api for column resize feature.
  19136. */
  19137. var publicApi = {
  19138. events: {
  19139. /**
  19140. * @ngdoc event
  19141. * @name columnSizeChanged
  19142. * @eventOf ui.grid.resizeColumns.api:PublicApi
  19143. * @description raised when column is resized
  19144. * <pre>
  19145. * gridApi.colResizable.on.columnSizeChanged(scope,function(colDef, deltaChange){})
  19146. * </pre>
  19147. * @param {object} colDef the column that was resized
  19148. * @param {integer} delta of the column size change
  19149. */
  19150. colResizable: {
  19151. columnSizeChanged: function (colDef, deltaChange) {
  19152. }
  19153. }
  19154. }
  19155. };
  19156. grid.api.registerEventsFromObject(publicApi.events);
  19157. },
  19158. fireColumnSizeChanged: function (grid, colDef, deltaChange) {
  19159. $timeout(function () {
  19160. if ( grid.api.colResizable ){
  19161. grid.api.colResizable.raise.columnSizeChanged(colDef, deltaChange);
  19162. } else {
  19163. gridUtil.logError("The resizeable api is not registered, this may indicate that you've included the module but not added the 'ui-grid-resize-columns' directive to your grid definition. Cannot raise any events.");
  19164. }
  19165. });
  19166. },
  19167. // get either this column, or the column next to this column, to resize,
  19168. // returns the column we're going to resize
  19169. findTargetCol: function(col, position, rtlMultiplier){
  19170. var renderContainer = col.getRenderContainer();
  19171. if (position === 'left') {
  19172. // Get the column to the left of this one
  19173. var colIndex = renderContainer.visibleColumnCache.indexOf(col);
  19174. return renderContainer.visibleColumnCache[colIndex - 1 * rtlMultiplier];
  19175. } else {
  19176. return col;
  19177. }
  19178. }
  19179. };
  19180. return service;
  19181. }]);
  19182. /**
  19183. * @ngdoc directive
  19184. * @name ui.grid.resizeColumns.directive:uiGridResizeColumns
  19185. * @element div
  19186. * @restrict A
  19187. * @description
  19188. * Enables resizing for all columns on the grid. If, for some reason, you want to use the ui-grid-resize-columns directive, but not allow column resizing, you can explicitly set the
  19189. * option to false. This prevents resizing for the entire grid, regardless of individual columnDef options.
  19190. *
  19191. * @example
  19192. <doc:example module="app">
  19193. <doc:source>
  19194. <script>
  19195. var app = angular.module('app', ['ui.grid', 'ui.grid.resizeColumns']);
  19196. app.controller('MainCtrl', ['$scope', function ($scope) {
  19197. $scope.gridOpts = {
  19198. data: [
  19199. { "name": "Ethel Price", "gender": "female", "company": "Enersol" },
  19200. { "name": "Claudine Neal", "gender": "female", "company": "Sealoud" },
  19201. { "name": "Beryl Rice", "gender": "female", "company": "Velity" },
  19202. { "name": "Wilder Gonzales", "gender": "male", "company": "Geekko" }
  19203. ]
  19204. };
  19205. }]);
  19206. </script>
  19207. <div ng-controller="MainCtrl">
  19208. <div class="testGrid" ui-grid="gridOpts" ui-grid-resize-columns ></div>
  19209. </div>
  19210. </doc:source>
  19211. <doc:scenario>
  19212. </doc:scenario>
  19213. </doc:example>
  19214. */
  19215. module.directive('uiGridResizeColumns', ['gridUtil', 'uiGridResizeColumnsService', function (gridUtil, uiGridResizeColumnsService) {
  19216. return {
  19217. replace: true,
  19218. priority: 0,
  19219. require: '^uiGrid',
  19220. scope: false,
  19221. compile: function () {
  19222. return {
  19223. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  19224. uiGridResizeColumnsService.defaultGridOptions(uiGridCtrl.grid.options);
  19225. uiGridCtrl.grid.registerColumnBuilder( uiGridResizeColumnsService.colResizerColumnBuilder);
  19226. uiGridResizeColumnsService.registerPublicApi(uiGridCtrl.grid);
  19227. },
  19228. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  19229. }
  19230. };
  19231. }
  19232. };
  19233. }]);
  19234. // Extend the uiGridHeaderCell directive
  19235. module.directive('uiGridHeaderCell', ['gridUtil', '$templateCache', '$compile', '$q', 'uiGridResizeColumnsService', 'uiGridConstants', '$timeout', function (gridUtil, $templateCache, $compile, $q, uiGridResizeColumnsService, uiGridConstants, $timeout) {
  19236. return {
  19237. // Run after the original uiGridHeaderCell
  19238. priority: -10,
  19239. require: '^uiGrid',
  19240. // scope: false,
  19241. compile: function() {
  19242. return {
  19243. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  19244. var grid = uiGridCtrl.grid;
  19245. if (grid.options.enableColumnResizing) {
  19246. var columnResizerElm = $templateCache.get('ui-grid/columnResizer');
  19247. var rtlMultiplier = 1;
  19248. //when in RTL mode reverse the direction using the rtlMultiplier and change the position to left
  19249. if (grid.isRTL()) {
  19250. $scope.position = 'left';
  19251. rtlMultiplier = -1;
  19252. }
  19253. var displayResizers = function(){
  19254. // remove any existing resizers.
  19255. var resizers = $elm[0].getElementsByClassName('ui-grid-column-resizer');
  19256. for ( var i = 0; i < resizers.length; i++ ){
  19257. angular.element(resizers[i]).remove();
  19258. }
  19259. // get the target column for the left resizer
  19260. var otherCol = uiGridResizeColumnsService.findTargetCol($scope.col, 'left', rtlMultiplier);
  19261. var renderContainer = $scope.col.getRenderContainer();
  19262. // Don't append the left resizer if this is the first column or the column to the left of this one has resizing disabled
  19263. if (otherCol && renderContainer.visibleColumnCache.indexOf($scope.col) !== 0 && otherCol.colDef.enableColumnResizing !== false) {
  19264. var resizerLeft = angular.element(columnResizerElm).clone();
  19265. resizerLeft.attr('position', 'left');
  19266. $elm.prepend(resizerLeft);
  19267. $compile(resizerLeft)($scope);
  19268. }
  19269. // Don't append the right resizer if this column has resizing disabled
  19270. if ($scope.col.colDef.enableColumnResizing !== false) {
  19271. var resizerRight = angular.element(columnResizerElm).clone();
  19272. resizerRight.attr('position', 'right');
  19273. $elm.append(resizerRight);
  19274. $compile(resizerRight)($scope);
  19275. }
  19276. };
  19277. displayResizers();
  19278. var waitDisplay = function(){
  19279. $timeout(displayResizers);
  19280. };
  19281. var dataChangeDereg = grid.registerDataChangeCallback( waitDisplay, [uiGridConstants.dataChange.COLUMN] );
  19282. $scope.$on( '$destroy', dataChangeDereg );
  19283. }
  19284. }
  19285. };
  19286. }
  19287. };
  19288. }]);
  19289. /**
  19290. * @ngdoc directive
  19291. * @name ui.grid.resizeColumns.directive:uiGridColumnResizer
  19292. * @element div
  19293. * @restrict A
  19294. *
  19295. * @description
  19296. * Draggable handle that controls column resizing.
  19297. *
  19298. * @example
  19299. <doc:example module="app">
  19300. <doc:source>
  19301. <script>
  19302. var app = angular.module('app', ['ui.grid', 'ui.grid.resizeColumns']);
  19303. app.controller('MainCtrl', ['$scope', function ($scope) {
  19304. $scope.gridOpts = {
  19305. enableColumnResizing: true,
  19306. data: [
  19307. { "name": "Ethel Price", "gender": "female", "company": "Enersol" },
  19308. { "name": "Claudine Neal", "gender": "female", "company": "Sealoud" },
  19309. { "name": "Beryl Rice", "gender": "female", "company": "Velity" },
  19310. { "name": "Wilder Gonzales", "gender": "male", "company": "Geekko" }
  19311. ]
  19312. };
  19313. }]);
  19314. </script>
  19315. <div ng-controller="MainCtrl">
  19316. <div class="testGrid" ui-grid="gridOpts"></div>
  19317. </div>
  19318. </doc:source>
  19319. <doc:scenario>
  19320. // TODO: e2e specs?
  19321. // TODO: post-resize a horizontal scroll event should be fired
  19322. </doc:scenario>
  19323. </doc:example>
  19324. */
  19325. module.directive('uiGridColumnResizer', ['$document', 'gridUtil', 'uiGridConstants', 'uiGridResizeColumnsService', function ($document, gridUtil, uiGridConstants, uiGridResizeColumnsService) {
  19326. var resizeOverlay = angular.element('<div class="ui-grid-resize-overlay"></div>');
  19327. var resizer = {
  19328. priority: 0,
  19329. scope: {
  19330. col: '=',
  19331. position: '@',
  19332. renderIndex: '='
  19333. },
  19334. require: '?^uiGrid',
  19335. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  19336. var startX = 0,
  19337. x = 0,
  19338. gridLeft = 0,
  19339. rtlMultiplier = 1;
  19340. //when in RTL mode reverse the direction using the rtlMultiplier and change the position to left
  19341. if (uiGridCtrl.grid.isRTL()) {
  19342. $scope.position = 'left';
  19343. rtlMultiplier = -1;
  19344. }
  19345. if ($scope.position === 'left') {
  19346. $elm.addClass('left');
  19347. }
  19348. else if ($scope.position === 'right') {
  19349. $elm.addClass('right');
  19350. }
  19351. // Refresh the grid canvas
  19352. // takes an argument representing the diff along the X-axis that the resize had
  19353. function refreshCanvas(xDiff) {
  19354. // Then refresh the grid canvas, rebuilding the styles so that the scrollbar updates its size
  19355. uiGridCtrl.grid.refreshCanvas(true).then( function() {
  19356. uiGridCtrl.grid.queueGridRefresh();
  19357. });
  19358. }
  19359. // Check that the requested width isn't wider than the maxWidth, or narrower than the minWidth
  19360. // Returns the new recommended with, after constraints applied
  19361. function constrainWidth(col, width){
  19362. var newWidth = width;
  19363. // If the new width would be less than the column's allowably minimum width, don't allow it
  19364. if (col.minWidth && newWidth < col.minWidth) {
  19365. newWidth = col.minWidth;
  19366. }
  19367. else if (col.maxWidth && newWidth > col.maxWidth) {
  19368. newWidth = col.maxWidth;
  19369. }
  19370. return newWidth;
  19371. }
  19372. /*
  19373. * Our approach to event handling aims to deal with both touch devices and mouse devices
  19374. * We register down handlers on both touch and mouse. When a touchstart or mousedown event
  19375. * occurs, we register the corresponding touchmove/touchend, or mousemove/mouseend events.
  19376. *
  19377. * This way we can listen for both without worrying about the fact many touch devices also emulate
  19378. * mouse events - basically whichever one we hear first is what we'll go with.
  19379. */
  19380. function moveFunction(event, args) {
  19381. if (event.originalEvent) { event = event.originalEvent; }
  19382. event.preventDefault();
  19383. x = (event.targetTouches ? event.targetTouches[0] : event).clientX - gridLeft;
  19384. if (x < 0) { x = 0; }
  19385. else if (x > uiGridCtrl.grid.gridWidth) { x = uiGridCtrl.grid.gridWidth; }
  19386. var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier);
  19387. // Don't resize if it's disabled on this column
  19388. if (col.colDef.enableColumnResizing === false) {
  19389. return;
  19390. }
  19391. if (!uiGridCtrl.grid.element.hasClass('column-resizing')) {
  19392. uiGridCtrl.grid.element.addClass('column-resizing');
  19393. }
  19394. // Get the diff along the X axis
  19395. var xDiff = x - startX;
  19396. // Get the width that this mouse would give the column
  19397. var newWidth = parseInt(col.drawnWidth + xDiff * rtlMultiplier, 10);
  19398. // check we're not outside the allowable bounds for this column
  19399. x = x + ( constrainWidth(col, newWidth) - newWidth ) * rtlMultiplier;
  19400. resizeOverlay.css({ left: x + 'px' });
  19401. uiGridCtrl.fireEvent(uiGridConstants.events.ITEM_DRAGGING);
  19402. }
  19403. function upFunction(event, args) {
  19404. if (event.originalEvent) { event = event.originalEvent; }
  19405. event.preventDefault();
  19406. uiGridCtrl.grid.element.removeClass('column-resizing');
  19407. resizeOverlay.remove();
  19408. // Resize the column
  19409. x = (event.changedTouches ? event.changedTouches[0] : event).clientX - gridLeft;
  19410. var xDiff = x - startX;
  19411. if (xDiff === 0) {
  19412. // no movement, so just reset event handlers, including turning back on both
  19413. // down events - we turned one off when this event started
  19414. offAllEvents();
  19415. onDownEvents();
  19416. return;
  19417. }
  19418. var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier);
  19419. // Don't resize if it's disabled on this column
  19420. if (col.colDef.enableColumnResizing === false) {
  19421. return;
  19422. }
  19423. // Get the new width
  19424. var newWidth = parseInt(col.drawnWidth + xDiff * rtlMultiplier, 10);
  19425. // check we're not outside the allowable bounds for this column
  19426. col.width = constrainWidth(col, newWidth);
  19427. col.hasCustomWidth = true;
  19428. refreshCanvas(xDiff);
  19429. uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff);
  19430. // stop listening of up and move events - wait for next down
  19431. // reset the down events - we will have turned one off when this event started
  19432. offAllEvents();
  19433. onDownEvents();
  19434. }
  19435. var downFunction = function(event, args) {
  19436. if (event.originalEvent) { event = event.originalEvent; }
  19437. event.stopPropagation();
  19438. // Get the left offset of the grid
  19439. // gridLeft = uiGridCtrl.grid.element[0].offsetLeft;
  19440. gridLeft = uiGridCtrl.grid.element[0].getBoundingClientRect().left;
  19441. // Get the starting X position, which is the X coordinate of the click minus the grid's offset
  19442. startX = (event.targetTouches ? event.targetTouches[0] : event).clientX - gridLeft;
  19443. // Append the resizer overlay
  19444. uiGridCtrl.grid.element.append(resizeOverlay);
  19445. // Place the resizer overlay at the start position
  19446. resizeOverlay.css({ left: startX });
  19447. // Add handlers for move and up events - if we were mousedown then we listen for mousemove and mouseup, if
  19448. // we were touchdown then we listen for touchmove and touchup. Also remove the handler for the equivalent
  19449. // down event - so if we're touchdown, then remove the mousedown handler until this event is over, if we're
  19450. // mousedown then remove the touchdown handler until this event is over, this avoids processing duplicate events
  19451. if ( event.type === 'touchstart' ){
  19452. $document.on('touchend', upFunction);
  19453. $document.on('touchmove', moveFunction);
  19454. $elm.off('mousedown', downFunction);
  19455. } else {
  19456. $document.on('mouseup', upFunction);
  19457. $document.on('mousemove', moveFunction);
  19458. $elm.off('touchstart', downFunction);
  19459. }
  19460. };
  19461. var onDownEvents = function() {
  19462. $elm.on('mousedown', downFunction);
  19463. $elm.on('touchstart', downFunction);
  19464. };
  19465. var offAllEvents = function() {
  19466. $document.off('mouseup', upFunction);
  19467. $document.off('touchend', upFunction);
  19468. $document.off('mousemove', moveFunction);
  19469. $document.off('touchmove', moveFunction);
  19470. $elm.off('mousedown', downFunction);
  19471. $elm.off('touchstart', downFunction);
  19472. };
  19473. onDownEvents();
  19474. // On doubleclick, resize to fit all rendered cells
  19475. var dblClickFn = function(event, args){
  19476. event.stopPropagation();
  19477. var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier);
  19478. // Don't resize if it's disabled on this column
  19479. if (col.colDef.enableColumnResizing === false) {
  19480. return;
  19481. }
  19482. // Go through the rendered rows and find out the max size for the data in this column
  19483. var maxWidth = 0;
  19484. var xDiff = 0;
  19485. // Get the parent render container element
  19486. var renderContainerElm = gridUtil.closestElm($elm, '.ui-grid-render-container');
  19487. // Get the cell contents so we measure correctly. For the header cell we have to account for the sort icon and the menu buttons, if present
  19488. var cells = renderContainerElm.querySelectorAll('.' + uiGridConstants.COL_CLASS_PREFIX + col.uid + ' .ui-grid-cell-contents');
  19489. Array.prototype.forEach.call(cells, function (cell) {
  19490. // Get the cell width
  19491. // gridUtil.logDebug('width', gridUtil.elementWidth(cell));
  19492. // Account for the menu button if it exists
  19493. var menuButton;
  19494. if (angular.element(cell).parent().hasClass('ui-grid-header-cell')) {
  19495. menuButton = angular.element(cell).parent()[0].querySelectorAll('.ui-grid-column-menu-button');
  19496. }
  19497. gridUtil.fakeElement(cell, {}, function(newElm) {
  19498. // Make the element float since it's a div and can expand to fill its container
  19499. var e = angular.element(newElm);
  19500. e.attr('style', 'float: left');
  19501. var width = gridUtil.elementWidth(e);
  19502. if (menuButton) {
  19503. var menuButtonWidth = gridUtil.elementWidth(menuButton);
  19504. width = width + menuButtonWidth;
  19505. }
  19506. if (width > maxWidth) {
  19507. maxWidth = width;
  19508. xDiff = maxWidth - width;
  19509. }
  19510. });
  19511. });
  19512. // check we're not outside the allowable bounds for this column
  19513. col.width = constrainWidth(col, maxWidth);
  19514. col.hasCustomWidth = true;
  19515. refreshCanvas(xDiff);
  19516. uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff); };
  19517. $elm.on('dblclick', dblClickFn);
  19518. $elm.on('$destroy', function() {
  19519. $elm.off('dblclick', dblClickFn);
  19520. offAllEvents();
  19521. });
  19522. }
  19523. };
  19524. return resizer;
  19525. }]);
  19526. })();
  19527. (function () {
  19528. 'use strict';
  19529. /**
  19530. * @ngdoc overview
  19531. * @name ui.grid.rowEdit
  19532. * @description
  19533. *
  19534. * # ui.grid.rowEdit
  19535. *
  19536. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  19537. *
  19538. * This module extends the edit feature to provide tracking and saving of rows
  19539. * of data. The tutorial provides more information on how this feature is best
  19540. * used {@link tutorial/205_row_editable here}.
  19541. * <br/>
  19542. * This feature depends on usage of the ui-grid-edit feature, and also benefits
  19543. * from use of ui-grid-cellNav to provide the full spreadsheet-like editing
  19544. * experience
  19545. *
  19546. */
  19547. var module = angular.module('ui.grid.rowEdit', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav']);
  19548. /**
  19549. * @ngdoc object
  19550. * @name ui.grid.rowEdit.constant:uiGridRowEditConstants
  19551. *
  19552. * @description constants available in row edit module
  19553. */
  19554. module.constant('uiGridRowEditConstants', {
  19555. });
  19556. /**
  19557. * @ngdoc service
  19558. * @name ui.grid.rowEdit.service:uiGridRowEditService
  19559. *
  19560. * @description Services for row editing features
  19561. */
  19562. module.service('uiGridRowEditService', ['$interval', '$q', 'uiGridConstants', 'uiGridRowEditConstants', 'gridUtil',
  19563. function ($interval, $q, uiGridConstants, uiGridRowEditConstants, gridUtil) {
  19564. var service = {
  19565. initializeGrid: function (scope, grid) {
  19566. /**
  19567. * @ngdoc object
  19568. * @name ui.grid.rowEdit.api:PublicApi
  19569. *
  19570. * @description Public Api for rowEdit feature
  19571. */
  19572. grid.rowEdit = {};
  19573. var publicApi = {
  19574. events: {
  19575. rowEdit: {
  19576. /**
  19577. * @ngdoc event
  19578. * @eventOf ui.grid.rowEdit.api:PublicApi
  19579. * @name saveRow
  19580. * @description raised when a row is ready for saving. Once your
  19581. * row has saved you may need to use angular.extend to update the
  19582. * data entity with any changed data from your save (for example,
  19583. * lock version information if you're using optimistic locking,
  19584. * or last update time/user information).
  19585. *
  19586. * Your method should call setSavePromise somewhere in the body before
  19587. * returning control. The feature will then wait, with the gridRow greyed out
  19588. * whilst this promise is being resolved.
  19589. *
  19590. * <pre>
  19591. * gridApi.rowEdit.on.saveRow(scope,function(rowEntity){})
  19592. * </pre>
  19593. * and somewhere within the event handler:
  19594. * <pre>
  19595. * gridApi.rowEdit.setSavePromise( rowEntity, savePromise)
  19596. * </pre>
  19597. * @param {object} rowEntity the options.data element that was edited
  19598. * @returns {promise} Your saveRow method should return a promise, the
  19599. * promise should either be resolved (implying successful save), or
  19600. * rejected (implying an error).
  19601. */
  19602. saveRow: function (rowEntity) {
  19603. }
  19604. }
  19605. },
  19606. methods: {
  19607. rowEdit: {
  19608. /**
  19609. * @ngdoc method
  19610. * @methodOf ui.grid.rowEdit.api:PublicApi
  19611. * @name setSavePromise
  19612. * @description Sets the promise associated with the row save, mandatory that
  19613. * the saveRow event handler calls this method somewhere before returning.
  19614. * <pre>
  19615. * gridApi.rowEdit.setSavePromise(rowEntity, savePromise)
  19616. * </pre>
  19617. * @param {object} rowEntity a data row from the grid for which a save has
  19618. * been initiated
  19619. * @param {promise} savePromise the promise that will be resolved when the
  19620. * save is successful, or rejected if the save fails
  19621. *
  19622. */
  19623. setSavePromise: function ( rowEntity, savePromise) {
  19624. service.setSavePromise(grid, rowEntity, savePromise);
  19625. },
  19626. /**
  19627. * @ngdoc method
  19628. * @methodOf ui.grid.rowEdit.api:PublicApi
  19629. * @name getDirtyRows
  19630. * @description Returns all currently dirty rows
  19631. * <pre>
  19632. * gridApi.rowEdit.getDirtyRows(grid)
  19633. * </pre>
  19634. * @returns {array} An array of gridRows that are currently dirty
  19635. *
  19636. */
  19637. getDirtyRows: function () {
  19638. return grid.rowEdit.dirtyRows ? grid.rowEdit.dirtyRows : [];
  19639. },
  19640. /**
  19641. * @ngdoc method
  19642. * @methodOf ui.grid.rowEdit.api:PublicApi
  19643. * @name getErrorRows
  19644. * @description Returns all currently errored rows
  19645. * <pre>
  19646. * gridApi.rowEdit.getErrorRows(grid)
  19647. * </pre>
  19648. * @returns {array} An array of gridRows that are currently in error
  19649. *
  19650. */
  19651. getErrorRows: function () {
  19652. return grid.rowEdit.errorRows ? grid.rowEdit.errorRows : [];
  19653. },
  19654. /**
  19655. * @ngdoc method
  19656. * @methodOf ui.grid.rowEdit.api:PublicApi
  19657. * @name flushDirtyRows
  19658. * @description Triggers a save event for all currently dirty rows, could
  19659. * be used where user presses a save button or navigates away from the page
  19660. * <pre>
  19661. * gridApi.rowEdit.flushDirtyRows(grid)
  19662. * </pre>
  19663. * @returns {promise} a promise that represents the aggregate of all
  19664. * of the individual save promises - i.e. it will be resolved when all
  19665. * the individual save promises have been resolved.
  19666. *
  19667. */
  19668. flushDirtyRows: function () {
  19669. return service.flushDirtyRows(grid);
  19670. },
  19671. /**
  19672. * @ngdoc method
  19673. * @methodOf ui.grid.rowEdit.api:PublicApi
  19674. * @name setRowsDirty
  19675. * @description Sets each of the rows passed in dataRows
  19676. * to be dirty. note that if you have only just inserted the
  19677. * rows into your data you will need to wait for a $digest cycle
  19678. * before the gridRows are present - so often you would wrap this
  19679. * call in a $interval or $timeout
  19680. * <pre>
  19681. * $interval( function() {
  19682. * gridApi.rowEdit.setRowsDirty(myDataRows);
  19683. * }, 0, 1);
  19684. * </pre>
  19685. * @param {array} dataRows the data entities for which the gridRows
  19686. * should be set dirty.
  19687. *
  19688. */
  19689. setRowsDirty: function ( dataRows) {
  19690. service.setRowsDirty(grid, dataRows);
  19691. },
  19692. /**
  19693. * @ngdoc method
  19694. * @methodOf ui.grid.rowEdit.api:PublicApi
  19695. * @name setRowsClean
  19696. * @description Sets each of the rows passed in dataRows
  19697. * to be clean, removing them from the dirty cache and the error cache,
  19698. * and clearing the error flag and the dirty flag
  19699. * <pre>
  19700. * var gridRows = $scope.gridApi.rowEdit.getDirtyRows();
  19701. * var dataRows = gridRows.map( function( gridRow ) { return gridRow.entity; });
  19702. * $scope.gridApi.rowEdit.setRowsClean( dataRows );
  19703. * </pre>
  19704. * @param {array} dataRows the data entities for which the gridRows
  19705. * should be set clean.
  19706. *
  19707. */
  19708. setRowsClean: function ( dataRows) {
  19709. service.setRowsClean(grid, dataRows);
  19710. }
  19711. }
  19712. }
  19713. };
  19714. grid.api.registerEventsFromObject(publicApi.events);
  19715. grid.api.registerMethodsFromObject(publicApi.methods);
  19716. grid.api.core.on.renderingComplete( scope, function ( gridApi ) {
  19717. grid.api.edit.on.afterCellEdit( scope, service.endEditCell );
  19718. grid.api.edit.on.beginCellEdit( scope, service.beginEditCell );
  19719. grid.api.edit.on.cancelCellEdit( scope, service.cancelEditCell );
  19720. if ( grid.api.cellNav ) {
  19721. grid.api.cellNav.on.navigate( scope, service.navigate );
  19722. }
  19723. });
  19724. },
  19725. defaultGridOptions: function (gridOptions) {
  19726. /**
  19727. * @ngdoc object
  19728. * @name ui.grid.rowEdit.api:GridOptions
  19729. *
  19730. * @description Options for configuring the rowEdit feature, these are available to be
  19731. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  19732. */
  19733. },
  19734. /**
  19735. * @ngdoc method
  19736. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19737. * @name saveRow
  19738. * @description Returns a function that saves the specified row from the grid,
  19739. * and returns a promise
  19740. * @param {object} grid the grid for which dirty rows should be flushed
  19741. * @param {GridRow} gridRow the row that should be saved
  19742. * @returns {function} the saveRow function returns a function. That function
  19743. * in turn, when called, returns a promise relating to the save callback
  19744. */
  19745. saveRow: function ( grid, gridRow ) {
  19746. var self = this;
  19747. return function() {
  19748. gridRow.isSaving = true;
  19749. if ( gridRow.rowEditSavePromise ){
  19750. // don't save the row again if it's already saving - that causes stale object exceptions
  19751. return gridRow.rowEditSavePromise;
  19752. }
  19753. var promise = grid.api.rowEdit.raise.saveRow( gridRow.entity );
  19754. if ( gridRow.rowEditSavePromise ){
  19755. gridRow.rowEditSavePromise.then( self.processSuccessPromise( grid, gridRow ), self.processErrorPromise( grid, gridRow ));
  19756. } else {
  19757. gridUtil.logError( 'A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise' );
  19758. }
  19759. return promise;
  19760. };
  19761. },
  19762. /**
  19763. * @ngdoc method
  19764. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19765. * @name setSavePromise
  19766. * @description Sets the promise associated with the row save, mandatory that
  19767. * the saveRow event handler calls this method somewhere before returning.
  19768. * <pre>
  19769. * gridApi.rowEdit.setSavePromise(grid, rowEntity)
  19770. * </pre>
  19771. * @param {object} grid the grid for which dirty rows should be returned
  19772. * @param {object} rowEntity a data row from the grid for which a save has
  19773. * been initiated
  19774. * @param {promise} savePromise the promise that will be resolved when the
  19775. * save is successful, or rejected if the save fails
  19776. *
  19777. */
  19778. setSavePromise: function (grid, rowEntity, savePromise) {
  19779. var gridRow = grid.getRow( rowEntity );
  19780. gridRow.rowEditSavePromise = savePromise;
  19781. },
  19782. /**
  19783. * @ngdoc method
  19784. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19785. * @name processSuccessPromise
  19786. * @description Returns a function that processes the successful
  19787. * resolution of a save promise
  19788. * @param {object} grid the grid for which the promise should be processed
  19789. * @param {GridRow} gridRow the row that has been saved
  19790. * @returns {function} the success handling function
  19791. */
  19792. processSuccessPromise: function ( grid, gridRow ) {
  19793. var self = this;
  19794. return function() {
  19795. delete gridRow.isSaving;
  19796. delete gridRow.isDirty;
  19797. delete gridRow.isError;
  19798. delete gridRow.rowEditSaveTimer;
  19799. delete gridRow.rowEditSavePromise;
  19800. self.removeRow( grid.rowEdit.errorRows, gridRow );
  19801. self.removeRow( grid.rowEdit.dirtyRows, gridRow );
  19802. };
  19803. },
  19804. /**
  19805. * @ngdoc method
  19806. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19807. * @name processErrorPromise
  19808. * @description Returns a function that processes the failed
  19809. * resolution of a save promise
  19810. * @param {object} grid the grid for which the promise should be processed
  19811. * @param {GridRow} gridRow the row that is now in error
  19812. * @returns {function} the error handling function
  19813. */
  19814. processErrorPromise: function ( grid, gridRow ) {
  19815. return function() {
  19816. delete gridRow.isSaving;
  19817. delete gridRow.rowEditSaveTimer;
  19818. delete gridRow.rowEditSavePromise;
  19819. gridRow.isError = true;
  19820. if (!grid.rowEdit.errorRows){
  19821. grid.rowEdit.errorRows = [];
  19822. }
  19823. if (!service.isRowPresent( grid.rowEdit.errorRows, gridRow ) ){
  19824. grid.rowEdit.errorRows.push( gridRow );
  19825. }
  19826. };
  19827. },
  19828. /**
  19829. * @ngdoc method
  19830. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19831. * @name removeRow
  19832. * @description Removes a row from a cache of rows - either
  19833. * grid.rowEdit.errorRows or grid.rowEdit.dirtyRows. If the row
  19834. * is not present silently does nothing.
  19835. * @param {array} rowArray the array from which to remove the row
  19836. * @param {GridRow} gridRow the row that should be removed
  19837. */
  19838. removeRow: function( rowArray, removeGridRow ){
  19839. if (typeof(rowArray) === 'undefined' || rowArray === null){
  19840. return;
  19841. }
  19842. rowArray.forEach( function( gridRow, index ){
  19843. if ( gridRow.uid === removeGridRow.uid ){
  19844. rowArray.splice( index, 1);
  19845. }
  19846. });
  19847. },
  19848. /**
  19849. * @ngdoc method
  19850. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19851. * @name isRowPresent
  19852. * @description Checks whether a row is already present
  19853. * in the given array
  19854. * @param {array} rowArray the array in which to look for the row
  19855. * @param {GridRow} gridRow the row that should be looked for
  19856. */
  19857. isRowPresent: function( rowArray, removeGridRow ){
  19858. var present = false;
  19859. rowArray.forEach( function( gridRow, index ){
  19860. if ( gridRow.uid === removeGridRow.uid ){
  19861. present = true;
  19862. }
  19863. });
  19864. return present;
  19865. },
  19866. /**
  19867. * @ngdoc method
  19868. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19869. * @name flushDirtyRows
  19870. * @description Triggers a save event for all currently dirty rows, could
  19871. * be used where user presses a save button or navigates away from the page
  19872. * <pre>
  19873. * gridApi.rowEdit.flushDirtyRows(grid)
  19874. * </pre>
  19875. * @param {object} grid the grid for which dirty rows should be flushed
  19876. * @returns {promise} a promise that represents the aggregate of all
  19877. * of the individual save promises - i.e. it will be resolved when all
  19878. * the individual save promises have been resolved.
  19879. *
  19880. */
  19881. flushDirtyRows: function(grid){
  19882. var promises = [];
  19883. grid.api.rowEdit.getDirtyRows().forEach( function( gridRow ){
  19884. service.saveRow( grid, gridRow )();
  19885. promises.push( gridRow.rowEditSavePromise );
  19886. });
  19887. return $q.all( promises );
  19888. },
  19889. /**
  19890. * @ngdoc method
  19891. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19892. * @name endEditCell
  19893. * @description Receives an afterCellEdit event from the edit function,
  19894. * and sets flags as appropriate. Only the rowEntity parameter
  19895. * is processed, although other params are available. Grid
  19896. * is automatically provided by the gridApi.
  19897. * @param {object} rowEntity the data entity for which the cell
  19898. * was edited
  19899. */
  19900. endEditCell: function( rowEntity, colDef, newValue, previousValue ){
  19901. var grid = this.grid;
  19902. var gridRow = grid.getRow( rowEntity );
  19903. if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, dirty flag cannot be set' ); return; }
  19904. if ( newValue !== previousValue || gridRow.isDirty ){
  19905. if ( !grid.rowEdit.dirtyRows ){
  19906. grid.rowEdit.dirtyRows = [];
  19907. }
  19908. if ( !gridRow.isDirty ){
  19909. gridRow.isDirty = true;
  19910. grid.rowEdit.dirtyRows.push( gridRow );
  19911. }
  19912. delete gridRow.isError;
  19913. service.considerSetTimer( grid, gridRow );
  19914. }
  19915. },
  19916. /**
  19917. * @ngdoc method
  19918. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19919. * @name beginEditCell
  19920. * @description Receives a beginCellEdit event from the edit function,
  19921. * and cancels any rowEditSaveTimers if present, as the user is still editing
  19922. * this row. Only the rowEntity parameter
  19923. * is processed, although other params are available. Grid
  19924. * is automatically provided by the gridApi.
  19925. * @param {object} rowEntity the data entity for which the cell
  19926. * editing has commenced
  19927. */
  19928. beginEditCell: function( rowEntity, colDef ){
  19929. var grid = this.grid;
  19930. var gridRow = grid.getRow( rowEntity );
  19931. if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be cancelled' ); return; }
  19932. service.cancelTimer( grid, gridRow );
  19933. },
  19934. /**
  19935. * @ngdoc method
  19936. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19937. * @name cancelEditCell
  19938. * @description Receives a cancelCellEdit event from the edit function,
  19939. * and if the row was already dirty, restarts the save timer. If the row
  19940. * was not already dirty, then it's not dirty now either and does nothing.
  19941. *
  19942. * Only the rowEntity parameter
  19943. * is processed, although other params are available. Grid
  19944. * is automatically provided by the gridApi.
  19945. *
  19946. * @param {object} rowEntity the data entity for which the cell
  19947. * editing was cancelled
  19948. */
  19949. cancelEditCell: function( rowEntity, colDef ){
  19950. var grid = this.grid;
  19951. var gridRow = grid.getRow( rowEntity );
  19952. if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be set' ); return; }
  19953. service.considerSetTimer( grid, gridRow );
  19954. },
  19955. /**
  19956. * @ngdoc method
  19957. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19958. * @name navigate
  19959. * @description cellNav tells us that the selected cell has changed. If
  19960. * the new row had a timer running, then stop it similar to in a beginCellEdit
  19961. * call. If the old row is dirty and not the same as the new row, then
  19962. * start a timer on it.
  19963. * @param {object} newRowCol the row and column that were selected
  19964. * @param {object} oldRowCol the row and column that was left
  19965. *
  19966. */
  19967. navigate: function( newRowCol, oldRowCol ){
  19968. var grid = this.grid;
  19969. if ( newRowCol.row.rowEditSaveTimer ){
  19970. service.cancelTimer( grid, newRowCol.row );
  19971. }
  19972. if ( oldRowCol && oldRowCol.row && oldRowCol.row !== newRowCol.row ){
  19973. service.considerSetTimer( grid, oldRowCol.row );
  19974. }
  19975. },
  19976. /**
  19977. * @ngdoc property
  19978. * @propertyOf ui.grid.rowEdit.api:GridOptions
  19979. * @name rowEditWaitInterval
  19980. * @description How long the grid should wait for another change on this row
  19981. * before triggering a save (in milliseconds). If set to -1, then saves are
  19982. * never triggered by timer (implying that the user will call flushDirtyRows()
  19983. * manually)
  19984. *
  19985. * @example
  19986. * Setting the wait interval to 4 seconds
  19987. * <pre>
  19988. * $scope.gridOptions = { rowEditWaitInterval: 4000 }
  19989. * </pre>
  19990. *
  19991. */
  19992. /**
  19993. * @ngdoc method
  19994. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19995. * @name considerSetTimer
  19996. * @description Consider setting a timer on this row (if it is dirty). if there is a timer running
  19997. * on the row and the row isn't currently saving, cancel it, using cancelTimer, then if the row is
  19998. * dirty and not currently saving then set a new timer
  19999. * @param {object} grid the grid for which we are processing
  20000. * @param {GridRow} gridRow the row for which the timer should be adjusted
  20001. *
  20002. */
  20003. considerSetTimer: function( grid, gridRow ){
  20004. service.cancelTimer( grid, gridRow );
  20005. if ( gridRow.isDirty && !gridRow.isSaving ){
  20006. if ( grid.options.rowEditWaitInterval !== -1 ){
  20007. var waitTime = grid.options.rowEditWaitInterval ? grid.options.rowEditWaitInterval : 2000;
  20008. gridRow.rowEditSaveTimer = $interval( service.saveRow( grid, gridRow ), waitTime, 1);
  20009. }
  20010. }
  20011. },
  20012. /**
  20013. * @ngdoc method
  20014. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  20015. * @name cancelTimer
  20016. * @description cancel the $interval for any timer running on this row
  20017. * then delete the timer itself
  20018. * @param {object} grid the grid for which we are processing
  20019. * @param {GridRow} gridRow the row for which the timer should be adjusted
  20020. *
  20021. */
  20022. cancelTimer: function( grid, gridRow ){
  20023. if ( gridRow.rowEditSaveTimer && !gridRow.isSaving ){
  20024. $interval.cancel(gridRow.rowEditSaveTimer);
  20025. delete gridRow.rowEditSaveTimer;
  20026. }
  20027. },
  20028. /**
  20029. * @ngdoc method
  20030. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  20031. * @name setRowsDirty
  20032. * @description Sets each of the rows passed in dataRows
  20033. * to be dirty. note that if you have only just inserted the
  20034. * rows into your data you will need to wait for a $digest cycle
  20035. * before the gridRows are present - so often you would wrap this
  20036. * call in a $interval or $timeout
  20037. * <pre>
  20038. * $interval( function() {
  20039. * gridApi.rowEdit.setRowsDirty( myDataRows);
  20040. * }, 0, 1);
  20041. * </pre>
  20042. * @param {object} grid the grid for which rows should be set dirty
  20043. * @param {array} dataRows the data entities for which the gridRows
  20044. * should be set dirty.
  20045. *
  20046. */
  20047. setRowsDirty: function( grid, myDataRows ) {
  20048. var gridRow;
  20049. myDataRows.forEach( function( value, index ){
  20050. gridRow = grid.getRow( value );
  20051. if ( gridRow ){
  20052. if ( !grid.rowEdit.dirtyRows ){
  20053. grid.rowEdit.dirtyRows = [];
  20054. }
  20055. if ( !gridRow.isDirty ){
  20056. gridRow.isDirty = true;
  20057. grid.rowEdit.dirtyRows.push( gridRow );
  20058. }
  20059. delete gridRow.isError;
  20060. service.considerSetTimer( grid, gridRow );
  20061. } else {
  20062. gridUtil.logError( "requested row not found in rowEdit.setRowsDirty, row was: " + value );
  20063. }
  20064. });
  20065. },
  20066. /**
  20067. * @ngdoc method
  20068. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  20069. * @name setRowsClean
  20070. * @description Sets each of the rows passed in dataRows
  20071. * to be clean, clearing the dirty flag and the error flag, and removing
  20072. * the rows from the dirty and error caches.
  20073. * @param {object} grid the grid for which rows should be set clean
  20074. * @param {array} dataRows the data entities for which the gridRows
  20075. * should be set clean.
  20076. *
  20077. */
  20078. setRowsClean: function( grid, myDataRows ) {
  20079. var gridRow;
  20080. myDataRows.forEach( function( value, index ){
  20081. gridRow = grid.getRow( value );
  20082. if ( gridRow ){
  20083. delete gridRow.isDirty;
  20084. service.removeRow( grid.rowEdit.dirtyRows, gridRow );
  20085. service.cancelTimer( grid, gridRow );
  20086. delete gridRow.isError;
  20087. service.removeRow( grid.rowEdit.errorRows, gridRow );
  20088. } else {
  20089. gridUtil.logError( "requested row not found in rowEdit.setRowsClean, row was: " + value );
  20090. }
  20091. });
  20092. }
  20093. };
  20094. return service;
  20095. }]);
  20096. /**
  20097. * @ngdoc directive
  20098. * @name ui.grid.rowEdit.directive:uiGridEdit
  20099. * @element div
  20100. * @restrict A
  20101. *
  20102. * @description Adds row editing features to the ui-grid-edit directive.
  20103. *
  20104. */
  20105. module.directive('uiGridRowEdit', ['gridUtil', 'uiGridRowEditService', 'uiGridEditConstants',
  20106. function (gridUtil, uiGridRowEditService, uiGridEditConstants) {
  20107. return {
  20108. replace: true,
  20109. priority: 0,
  20110. require: '^uiGrid',
  20111. scope: false,
  20112. compile: function () {
  20113. return {
  20114. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  20115. uiGridRowEditService.initializeGrid($scope, uiGridCtrl.grid);
  20116. },
  20117. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  20118. }
  20119. };
  20120. }
  20121. };
  20122. }]);
  20123. /**
  20124. * @ngdoc directive
  20125. * @name ui.grid.rowEdit.directive:uiGridViewport
  20126. * @element div
  20127. *
  20128. * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used
  20129. * for the grid row to allow coloring of saving and error rows
  20130. */
  20131. module.directive('uiGridViewport',
  20132. ['$compile', 'uiGridConstants', 'gridUtil', '$parse',
  20133. function ($compile, uiGridConstants, gridUtil, $parse) {
  20134. return {
  20135. priority: -200, // run after default directive
  20136. scope: false,
  20137. compile: function ($elm, $attrs) {
  20138. var rowRepeatDiv = angular.element($elm.children().children()[0]);
  20139. var existingNgClass = rowRepeatDiv.attr("ng-class");
  20140. var newNgClass = '';
  20141. if ( existingNgClass ) {
  20142. newNgClass = existingNgClass.slice(0, -1) + ", 'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}";
  20143. } else {
  20144. newNgClass = "{'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}";
  20145. }
  20146. rowRepeatDiv.attr("ng-class", newNgClass);
  20147. return {
  20148. pre: function ($scope, $elm, $attrs, controllers) {
  20149. },
  20150. post: function ($scope, $elm, $attrs, controllers) {
  20151. }
  20152. };
  20153. }
  20154. };
  20155. }]);
  20156. })();
  20157. (function () {
  20158. 'use strict';
  20159. /**
  20160. * @ngdoc overview
  20161. * @name ui.grid.saveState
  20162. * @description
  20163. *
  20164. * # ui.grid.saveState
  20165. *
  20166. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  20167. *
  20168. * This module provides the ability to save the grid state, and restore
  20169. * it when the user returns to the page.
  20170. *
  20171. * No UI is provided, the caller should provide their own UI/buttons
  20172. * as appropriate. Usually the navigate events would be used to save
  20173. * the grid state and restore it.
  20174. *
  20175. * <br/>
  20176. * <br/>
  20177. *
  20178. * <div doc-module-components="ui.grid.save-state"></div>
  20179. */
  20180. var module = angular.module('ui.grid.saveState', ['ui.grid', 'ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.grouping', 'ui.grid.pinning', 'ui.grid.treeView']);
  20181. /**
  20182. * @ngdoc object
  20183. * @name ui.grid.saveState.constant:uiGridSaveStateConstants
  20184. *
  20185. * @description constants available in save state module
  20186. */
  20187. module.constant('uiGridSaveStateConstants', {
  20188. featureName: 'saveState'
  20189. });
  20190. /**
  20191. * @ngdoc service
  20192. * @name ui.grid.saveState.service:uiGridSaveStateService
  20193. *
  20194. * @description Services for saveState feature
  20195. */
  20196. module.service('uiGridSaveStateService', ['$q', 'uiGridSaveStateConstants', 'gridUtil', '$compile', '$interval', 'uiGridConstants',
  20197. function ($q, uiGridSaveStateConstants, gridUtil, $compile, $interval, uiGridConstants ) {
  20198. var service = {
  20199. initializeGrid: function (grid) {
  20200. //add feature namespace and any properties to grid for needed state
  20201. grid.saveState = {};
  20202. this.defaultGridOptions(grid.options);
  20203. /**
  20204. * @ngdoc object
  20205. * @name ui.grid.saveState.api:PublicApi
  20206. *
  20207. * @description Public Api for saveState feature
  20208. */
  20209. var publicApi = {
  20210. events: {
  20211. saveState: {
  20212. }
  20213. },
  20214. methods: {
  20215. saveState: {
  20216. /**
  20217. * @ngdoc function
  20218. * @name save
  20219. * @methodOf ui.grid.saveState.api:PublicApi
  20220. * @description Packages the current state of the grid into
  20221. * an object, and provides it to the user for saving
  20222. * @returns {object} the state as a javascript object that can be saved
  20223. */
  20224. save: function () {
  20225. return service.save(grid);
  20226. },
  20227. /**
  20228. * @ngdoc function
  20229. * @name restore
  20230. * @methodOf ui.grid.saveState.api:PublicApi
  20231. * @description Restores the provided state into the grid
  20232. * @param {scope} $scope a scope that we can broadcast on
  20233. * @param {object} state the state that should be restored into the grid
  20234. */
  20235. restore: function ( $scope, state) {
  20236. service.restore(grid, $scope, state);
  20237. }
  20238. }
  20239. }
  20240. };
  20241. grid.api.registerEventsFromObject(publicApi.events);
  20242. grid.api.registerMethodsFromObject(publicApi.methods);
  20243. },
  20244. defaultGridOptions: function (gridOptions) {
  20245. //default option to true unless it was explicitly set to false
  20246. /**
  20247. * @ngdoc object
  20248. * @name ui.grid.saveState.api:GridOptions
  20249. *
  20250. * @description GridOptions for saveState feature, these are available to be
  20251. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  20252. */
  20253. /**
  20254. * @ngdoc object
  20255. * @name saveWidths
  20256. * @propertyOf ui.grid.saveState.api:GridOptions
  20257. * @description Save the current column widths. Note that unless
  20258. * you've provided the user with some way to resize their columns (say
  20259. * the resize columns feature), then this makes little sense.
  20260. * <br/>Defaults to true
  20261. */
  20262. gridOptions.saveWidths = gridOptions.saveWidths !== false;
  20263. /**
  20264. * @ngdoc object
  20265. * @name saveOrder
  20266. * @propertyOf ui.grid.saveState.api:GridOptions
  20267. * @description Restore the current column order. Note that unless
  20268. * you've provided the user with some way to reorder their columns (for
  20269. * example the move columns feature), this makes little sense.
  20270. * <br/>Defaults to true
  20271. */
  20272. gridOptions.saveOrder = gridOptions.saveOrder !== false;
  20273. /**
  20274. * @ngdoc object
  20275. * @name saveScroll
  20276. * @propertyOf ui.grid.saveState.api:GridOptions
  20277. * @description Save the current scroll position. Note that this
  20278. * is saved as the percentage of the grid scrolled - so if your
  20279. * user returns to a grid with a significantly different number of
  20280. * rows (perhaps some data has been deleted) then the scroll won't
  20281. * actually show the same rows as before. If you want to scroll to
  20282. * a specific row then you should instead use the saveFocus option, which
  20283. * is the default.
  20284. *
  20285. * Note that this element will only be saved if the cellNav feature is
  20286. * enabled
  20287. * <br/>Defaults to false
  20288. */
  20289. gridOptions.saveScroll = gridOptions.saveScroll === true;
  20290. /**
  20291. * @ngdoc object
  20292. * @name saveFocus
  20293. * @propertyOf ui.grid.saveState.api:GridOptions
  20294. * @description Save the current focused cell. On returning
  20295. * to this focused cell we'll also scroll. This option is
  20296. * preferred to the saveScroll option, so is set to true by
  20297. * default. If saveScroll is set to true then this option will
  20298. * be disabled.
  20299. *
  20300. * By default this option saves the current row number and column
  20301. * number, and returns to that row and column. However, if you define
  20302. * a saveRowIdentity function, then it will return you to the currently
  20303. * selected column within that row (in a business sense - so if some
  20304. * rows have been deleted, it will still find the same data, presuming it
  20305. * still exists in the list. If it isn't in the list then it will instead
  20306. * return to the same row number - i.e. scroll percentage)
  20307. *
  20308. * Note that this option will do nothing if the cellNav
  20309. * feature is not enabled.
  20310. *
  20311. * <br/>Defaults to true (unless saveScroll is true)
  20312. */
  20313. gridOptions.saveFocus = gridOptions.saveScroll !== true && gridOptions.saveFocus !== false;
  20314. /**
  20315. * @ngdoc object
  20316. * @name saveRowIdentity
  20317. * @propertyOf ui.grid.saveState.api:GridOptions
  20318. * @description A function that can be called, passing in a rowEntity,
  20319. * and that will return a unique id for that row. This might simply
  20320. * return the `id` field from that row (if you have one), or it might
  20321. * concatenate some fields within the row to make a unique value.
  20322. *
  20323. * This value will be used to find the same row again and set the focus
  20324. * to it, if it exists when we return.
  20325. *
  20326. * <br/>Defaults to undefined
  20327. */
  20328. /**
  20329. * @ngdoc object
  20330. * @name saveVisible
  20331. * @propertyOf ui.grid.saveState.api:GridOptions
  20332. * @description Save whether or not columns are visible.
  20333. *
  20334. * <br/>Defaults to true
  20335. */
  20336. gridOptions.saveVisible = gridOptions.saveVisible !== false;
  20337. /**
  20338. * @ngdoc object
  20339. * @name saveSort
  20340. * @propertyOf ui.grid.saveState.api:GridOptions
  20341. * @description Save the current sort state for each column
  20342. *
  20343. * <br/>Defaults to true
  20344. */
  20345. gridOptions.saveSort = gridOptions.saveSort !== false;
  20346. /**
  20347. * @ngdoc object
  20348. * @name saveFilter
  20349. * @propertyOf ui.grid.saveState.api:GridOptions
  20350. * @description Save the current filter state for each column
  20351. *
  20352. * <br/>Defaults to true
  20353. */
  20354. gridOptions.saveFilter = gridOptions.saveFilter !== false;
  20355. /**
  20356. * @ngdoc object
  20357. * @name saveSelection
  20358. * @propertyOf ui.grid.saveState.api:GridOptions
  20359. * @description Save the currently selected rows. If the `saveRowIdentity` callback
  20360. * is defined, then it will save the id of the row and select that. If not, then
  20361. * it will attempt to select the rows by row number, which will give the wrong results
  20362. * if the data set has changed in the mean-time.
  20363. *
  20364. * Note that this option only does anything
  20365. * if the selection feature is enabled.
  20366. *
  20367. * <br/>Defaults to true
  20368. */
  20369. gridOptions.saveSelection = gridOptions.saveSelection !== false;
  20370. /**
  20371. * @ngdoc object
  20372. * @name saveGrouping
  20373. * @propertyOf ui.grid.saveState.api:GridOptions
  20374. * @description Save the grouping configuration. If set to true and the
  20375. * grouping feature is not enabled then does nothing.
  20376. *
  20377. * <br/>Defaults to true
  20378. */
  20379. gridOptions.saveGrouping = gridOptions.saveGrouping !== false;
  20380. /**
  20381. * @ngdoc object
  20382. * @name saveGroupingExpandedStates
  20383. * @propertyOf ui.grid.saveState.api:GridOptions
  20384. * @description Save the grouping row expanded states. If set to true and the
  20385. * grouping feature is not enabled then does nothing.
  20386. *
  20387. * This can be quite a bit of data, in many cases you wouldn't want to save this
  20388. * information.
  20389. *
  20390. * <br/>Defaults to false
  20391. */
  20392. gridOptions.saveGroupingExpandedStates = gridOptions.saveGroupingExpandedStates === true;
  20393. /**
  20394. * @ngdoc object
  20395. * @name savePinning
  20396. * @propertyOf ui.grid.saveState.api:GridOptions
  20397. * @description Save pinning state for columns.
  20398. *
  20399. * <br/>Defaults to true
  20400. */
  20401. gridOptions.savePinning = gridOptions.savePinning !== false;
  20402. /**
  20403. * @ngdoc object
  20404. * @name saveTreeView
  20405. * @propertyOf ui.grid.saveState.api:GridOptions
  20406. * @description Save the treeView configuration. If set to true and the
  20407. * treeView feature is not enabled then does nothing.
  20408. *
  20409. * <br/>Defaults to true
  20410. */
  20411. gridOptions.saveTreeView = gridOptions.saveTreeView !== false;
  20412. },
  20413. /**
  20414. * @ngdoc function
  20415. * @name save
  20416. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20417. * @description Saves the current grid state into an object, and
  20418. * passes that object back to the caller
  20419. * @param {Grid} grid the grid whose state we'd like to save
  20420. * @returns {object} the state ready to be saved
  20421. */
  20422. save: function (grid) {
  20423. var savedState = {};
  20424. savedState.columns = service.saveColumns( grid );
  20425. savedState.scrollFocus = service.saveScrollFocus( grid );
  20426. savedState.selection = service.saveSelection( grid );
  20427. savedState.grouping = service.saveGrouping( grid );
  20428. savedState.treeView = service.saveTreeView( grid );
  20429. return savedState;
  20430. },
  20431. /**
  20432. * @ngdoc function
  20433. * @name restore
  20434. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20435. * @description Applies the provided state to the grid
  20436. *
  20437. * @param {Grid} grid the grid whose state we'd like to restore
  20438. * @param {scope} $scope a scope that we can broadcast on
  20439. * @param {object} state the state we'd like to restore
  20440. */
  20441. restore: function( grid, $scope, state ){
  20442. if ( state.columns ) {
  20443. service.restoreColumns( grid, state.columns );
  20444. }
  20445. if ( state.scrollFocus ){
  20446. service.restoreScrollFocus( grid, $scope, state.scrollFocus );
  20447. }
  20448. if ( state.selection ){
  20449. service.restoreSelection( grid, state.selection );
  20450. }
  20451. if ( state.grouping ){
  20452. service.restoreGrouping( grid, state.grouping );
  20453. }
  20454. if ( state.treeView ){
  20455. service.restoreTreeView( grid, state.treeView );
  20456. }
  20457. grid.refresh();
  20458. },
  20459. /**
  20460. * @ngdoc function
  20461. * @name saveColumns
  20462. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20463. * @description Saves the column setup, including sort, filters, ordering,
  20464. * pinning and column widths.
  20465. *
  20466. * Works through the current columns, storing them in order. Stores the
  20467. * column name, then the visible flag, width, sort and filters for each column.
  20468. *
  20469. * @param {Grid} grid the grid whose state we'd like to save
  20470. * @returns {array} the columns state ready to be saved
  20471. */
  20472. saveColumns: function( grid ) {
  20473. var columns = [];
  20474. grid.getOnlyDataColumns().forEach( function( column ) {
  20475. var savedColumn = {};
  20476. savedColumn.name = column.name;
  20477. if ( grid.options.saveVisible ){
  20478. savedColumn.visible = column.visible;
  20479. }
  20480. if ( grid.options.saveWidths ){
  20481. savedColumn.width = column.width;
  20482. }
  20483. // these two must be copied, not just pointed too - otherwise our saved state is pointing to the same object as current state
  20484. if ( grid.options.saveSort ){
  20485. savedColumn.sort = angular.copy( column.sort );
  20486. }
  20487. if ( grid.options.saveFilter ){
  20488. savedColumn.filters = [];
  20489. column.filters.forEach( function( filter ){
  20490. var copiedFilter = {};
  20491. angular.forEach( filter, function( value, key) {
  20492. if ( key !== 'condition' && key !== '$$hashKey' && key !== 'placeholder'){
  20493. copiedFilter[key] = value;
  20494. }
  20495. });
  20496. savedColumn.filters.push(copiedFilter);
  20497. });
  20498. }
  20499. if ( !!grid.api.pinning && grid.options.savePinning ){
  20500. savedColumn.pinned = column.renderContainer ? column.renderContainer : '';
  20501. }
  20502. columns.push( savedColumn );
  20503. });
  20504. return columns;
  20505. },
  20506. /**
  20507. * @ngdoc function
  20508. * @name saveScrollFocus
  20509. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20510. * @description Saves the currently scroll or focus.
  20511. *
  20512. * If cellNav isn't present then does nothing - we can't return
  20513. * to the scroll position without cellNav anyway.
  20514. *
  20515. * If the cellNav module is present, and saveFocus is true, then
  20516. * it saves the currently focused cell. If rowIdentity is present
  20517. * then saves using rowIdentity, otherwise saves visibleRowNum.
  20518. *
  20519. * If the cellNav module is not present, and saveScroll is true, then
  20520. * it approximates the current scroll row and column, and saves that.
  20521. *
  20522. * @param {Grid} grid the grid whose state we'd like to save
  20523. * @returns {object} the selection state ready to be saved
  20524. */
  20525. saveScrollFocus: function( grid ){
  20526. if ( !grid.api.cellNav ){
  20527. return {};
  20528. }
  20529. var scrollFocus = {};
  20530. if ( grid.options.saveFocus ){
  20531. scrollFocus.focus = true;
  20532. var rowCol = grid.api.cellNav.getFocusedCell();
  20533. if ( rowCol !== null ) {
  20534. if ( rowCol.col !== null ){
  20535. scrollFocus.colName = rowCol.col.colDef.name;
  20536. }
  20537. if ( rowCol.row !== null ){
  20538. scrollFocus.rowVal = service.getRowVal( grid, rowCol.row );
  20539. }
  20540. }
  20541. }
  20542. if ( grid.options.saveScroll || grid.options.saveFocus && !scrollFocus.colName && !scrollFocus.rowVal ) {
  20543. scrollFocus.focus = false;
  20544. if ( grid.renderContainers.body.prevRowScrollIndex ){
  20545. scrollFocus.rowVal = service.getRowVal( grid, grid.renderContainers.body.visibleRowCache[ grid.renderContainers.body.prevRowScrollIndex ]);
  20546. }
  20547. if ( grid.renderContainers.body.prevColScrollIndex ){
  20548. scrollFocus.colName = grid.renderContainers.body.visibleColumnCache[ grid.renderContainers.body.prevColScrollIndex ].name;
  20549. }
  20550. }
  20551. return scrollFocus;
  20552. },
  20553. /**
  20554. * @ngdoc function
  20555. * @name saveSelection
  20556. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20557. * @description Saves the currently selected rows, if the selection feature is enabled
  20558. * @param {Grid} grid the grid whose state we'd like to save
  20559. * @returns {array} the selection state ready to be saved
  20560. */
  20561. saveSelection: function( grid ){
  20562. if ( !grid.api.selection || !grid.options.saveSelection ){
  20563. return [];
  20564. }
  20565. var selection = grid.api.selection.getSelectedGridRows().map( function( gridRow ) {
  20566. return service.getRowVal( grid, gridRow );
  20567. });
  20568. return selection;
  20569. },
  20570. /**
  20571. * @ngdoc function
  20572. * @name saveGrouping
  20573. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20574. * @description Saves the grouping state, if the grouping feature is enabled
  20575. * @param {Grid} grid the grid whose state we'd like to save
  20576. * @returns {object} the grouping state ready to be saved
  20577. */
  20578. saveGrouping: function( grid ){
  20579. if ( !grid.api.grouping || !grid.options.saveGrouping ){
  20580. return {};
  20581. }
  20582. return grid.api.grouping.getGrouping( grid.options.saveGroupingExpandedStates );
  20583. },
  20584. /**
  20585. * @ngdoc function
  20586. * @name saveTreeView
  20587. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20588. * @description Saves the tree view state, if the tree feature is enabled
  20589. * @param {Grid} grid the grid whose state we'd like to save
  20590. * @returns {object} the tree view state ready to be saved
  20591. */
  20592. saveTreeView: function( grid ){
  20593. if ( !grid.api.treeView || !grid.options.saveTreeView ){
  20594. return {};
  20595. }
  20596. return grid.api.treeView.getTreeView();
  20597. },
  20598. /**
  20599. * @ngdoc function
  20600. * @name getRowVal
  20601. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20602. * @description Helper function that gets either the rowNum or
  20603. * the saveRowIdentity, given a gridRow
  20604. * @param {Grid} grid the grid the row is in
  20605. * @param {GridRow} gridRow the row we want the rowNum for
  20606. * @returns {object} an object containing { identity: true/false, row: rowNumber/rowIdentity }
  20607. *
  20608. */
  20609. getRowVal: function( grid, gridRow ){
  20610. if ( !gridRow ) {
  20611. return null;
  20612. }
  20613. var rowVal = {};
  20614. if ( grid.options.saveRowIdentity ){
  20615. rowVal.identity = true;
  20616. rowVal.row = grid.options.saveRowIdentity( gridRow.entity );
  20617. } else {
  20618. rowVal.identity = false;
  20619. rowVal.row = grid.renderContainers.body.visibleRowCache.indexOf( gridRow );
  20620. }
  20621. return rowVal;
  20622. },
  20623. /**
  20624. * @ngdoc function
  20625. * @name restoreColumns
  20626. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20627. * @description Restores the columns, including order, visible, width,
  20628. * pinning, sort and filters.
  20629. *
  20630. * @param {Grid} grid the grid whose state we'd like to restore
  20631. * @param {object} columnsState the list of columns we had before, with their state
  20632. */
  20633. restoreColumns: function( grid, columnsState ){
  20634. var isSortChanged = false;
  20635. columnsState.forEach( function( columnState, index ) {
  20636. var currentCol = grid.getColumn( columnState.name );
  20637. if ( currentCol && !grid.isRowHeaderColumn(currentCol) ){
  20638. if ( grid.options.saveVisible &&
  20639. ( currentCol.visible !== columnState.visible ||
  20640. currentCol.colDef.visible !== columnState.visible ) ){
  20641. currentCol.visible = columnState.visible;
  20642. currentCol.colDef.visible = columnState.visible;
  20643. grid.api.core.raise.columnVisibilityChanged(currentCol);
  20644. }
  20645. if ( grid.options.saveWidths ){
  20646. currentCol.width = columnState.width;
  20647. }
  20648. if ( grid.options.saveSort &&
  20649. !angular.equals(currentCol.sort, columnState.sort) &&
  20650. !( currentCol.sort === undefined && angular.isEmpty(columnState.sort) ) ){
  20651. currentCol.sort = angular.copy( columnState.sort );
  20652. isSortChanged = true;
  20653. }
  20654. if ( grid.options.saveFilter &&
  20655. !angular.equals(currentCol.filters, columnState.filters ) ){
  20656. columnState.filters.forEach( function( filter, index ){
  20657. angular.extend( currentCol.filters[index], filter );
  20658. if ( typeof(filter.term) === 'undefined' || filter.term === null ){
  20659. delete currentCol.filters[index].term;
  20660. }
  20661. });
  20662. grid.api.core.raise.filterChanged();
  20663. }
  20664. if ( !!grid.api.pinning && grid.options.savePinning && currentCol.renderContainer !== columnState.pinned ){
  20665. grid.api.pinning.pinColumn(currentCol, columnState.pinned);
  20666. }
  20667. var currentIndex = grid.getOnlyDataColumns().indexOf( currentCol );
  20668. if (currentIndex !== -1) {
  20669. if (grid.options.saveOrder && currentIndex !== index) {
  20670. var column = grid.columns.splice(currentIndex + grid.rowHeaderColumns.length, 1)[0];
  20671. grid.columns.splice(index + grid.rowHeaderColumns.length, 0, column);
  20672. }
  20673. }
  20674. }
  20675. });
  20676. if ( isSortChanged ) {
  20677. grid.api.core.raise.sortChanged( grid, grid.getColumnSorting() );
  20678. }
  20679. },
  20680. /**
  20681. * @ngdoc function
  20682. * @name restoreScrollFocus
  20683. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20684. * @description Scrolls to the position that was saved. If focus is true, then
  20685. * sets focus to the specified row/col. If focus is false, then scrolls to the
  20686. * specified row/col.
  20687. *
  20688. * @param {Grid} grid the grid whose state we'd like to restore
  20689. * @param {scope} $scope a scope that we can broadcast on
  20690. * @param {object} scrollFocusState the scroll/focus state ready to be restored
  20691. */
  20692. restoreScrollFocus: function( grid, $scope, scrollFocusState ){
  20693. if ( !grid.api.cellNav ){
  20694. return;
  20695. }
  20696. var colDef, row;
  20697. if ( scrollFocusState.colName ){
  20698. var colDefs = grid.options.columnDefs.filter( function( colDef ) { return colDef.name === scrollFocusState.colName; });
  20699. if ( colDefs.length > 0 ){
  20700. colDef = colDefs[0];
  20701. }
  20702. }
  20703. if ( scrollFocusState.rowVal && scrollFocusState.rowVal.row ){
  20704. if ( scrollFocusState.rowVal.identity ){
  20705. row = service.findRowByIdentity( grid, scrollFocusState.rowVal );
  20706. } else {
  20707. row = grid.renderContainers.body.visibleRowCache[ scrollFocusState.rowVal.row ];
  20708. }
  20709. }
  20710. var entity = row && row.entity ? row.entity : null ;
  20711. if ( colDef || entity ) {
  20712. if (scrollFocusState.focus ){
  20713. grid.api.cellNav.scrollToFocus( entity, colDef );
  20714. } else {
  20715. grid.scrollTo( entity, colDef );
  20716. }
  20717. }
  20718. },
  20719. /**
  20720. * @ngdoc function
  20721. * @name restoreSelection
  20722. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20723. * @description Selects the rows that are provided in the selection
  20724. * state. If you are using `saveRowIdentity` and more than one row matches the identity
  20725. * function then only the first is selected.
  20726. * @param {Grid} grid the grid whose state we'd like to restore
  20727. * @param {object} selectionState the selection state ready to be restored
  20728. */
  20729. restoreSelection: function( grid, selectionState ){
  20730. if ( !grid.api.selection ){
  20731. return;
  20732. }
  20733. grid.api.selection.clearSelectedRows();
  20734. selectionState.forEach( function( rowVal ) {
  20735. if ( rowVal.identity ){
  20736. var foundRow = service.findRowByIdentity( grid, rowVal );
  20737. if ( foundRow ){
  20738. grid.api.selection.selectRow( foundRow.entity );
  20739. }
  20740. } else {
  20741. grid.api.selection.selectRowByVisibleIndex( rowVal.row );
  20742. }
  20743. });
  20744. },
  20745. /**
  20746. * @ngdoc function
  20747. * @name restoreGrouping
  20748. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20749. * @description Restores the grouping configuration, if the grouping feature
  20750. * is enabled.
  20751. * @param {Grid} grid the grid whose state we'd like to restore
  20752. * @param {object} groupingState the grouping state ready to be restored
  20753. */
  20754. restoreGrouping: function( grid, groupingState ){
  20755. if ( !grid.api.grouping || typeof(groupingState) === 'undefined' || groupingState === null || angular.equals(groupingState, {}) ){
  20756. return;
  20757. }
  20758. grid.api.grouping.setGrouping( groupingState );
  20759. },
  20760. /**
  20761. * @ngdoc function
  20762. * @name restoreTreeView
  20763. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20764. * @description Restores the tree view configuration, if the tree view feature
  20765. * is enabled.
  20766. * @param {Grid} grid the grid whose state we'd like to restore
  20767. * @param {object} treeViewState the tree view state ready to be restored
  20768. */
  20769. restoreTreeView: function( grid, treeViewState ){
  20770. if ( !grid.api.treeView || typeof(treeViewState) === 'undefined' || treeViewState === null || angular.equals(treeViewState, {}) ){
  20771. return;
  20772. }
  20773. grid.api.treeView.setTreeView( treeViewState );
  20774. },
  20775. /**
  20776. * @ngdoc function
  20777. * @name findRowByIdentity
  20778. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20779. * @description Finds a row given it's identity value, returns the first found row
  20780. * if any are found, otherwise returns null if no rows are found.
  20781. * @param {Grid} grid the grid whose state we'd like to restore
  20782. * @param {object} rowVal the row we'd like to find
  20783. * @returns {gridRow} the found row, or null if none found
  20784. */
  20785. findRowByIdentity: function( grid, rowVal ){
  20786. if ( !grid.options.saveRowIdentity ){
  20787. return null;
  20788. }
  20789. var filteredRows = grid.rows.filter( function( gridRow ) {
  20790. if ( grid.options.saveRowIdentity( gridRow.entity ) === rowVal.row ){
  20791. return true;
  20792. } else {
  20793. return false;
  20794. }
  20795. });
  20796. if ( filteredRows.length > 0 ){
  20797. return filteredRows[0];
  20798. } else {
  20799. return null;
  20800. }
  20801. }
  20802. };
  20803. return service;
  20804. }
  20805. ]);
  20806. /**
  20807. * @ngdoc directive
  20808. * @name ui.grid.saveState.directive:uiGridSaveState
  20809. * @element div
  20810. * @restrict A
  20811. *
  20812. * @description Adds saveState features to grid
  20813. *
  20814. * @example
  20815. <example module="app">
  20816. <file name="app.js">
  20817. var app = angular.module('app', ['ui.grid', 'ui.grid.saveState']);
  20818. app.controller('MainCtrl', ['$scope', function ($scope) {
  20819. $scope.data = [
  20820. { name: 'Bob', title: 'CEO' },
  20821. { name: 'Frank', title: 'Lowly Developer' }
  20822. ];
  20823. $scope.gridOptions = {
  20824. columnDefs: [
  20825. {name: 'name'},
  20826. {name: 'title', enableCellEdit: true}
  20827. ],
  20828. data: $scope.data
  20829. };
  20830. }]);
  20831. </file>
  20832. <file name="index.html">
  20833. <div ng-controller="MainCtrl">
  20834. <div ui-grid="gridOptions" ui-grid-save-state></div>
  20835. </div>
  20836. </file>
  20837. </example>
  20838. */
  20839. module.directive('uiGridSaveState', ['uiGridSaveStateConstants', 'uiGridSaveStateService', 'gridUtil', '$compile',
  20840. function (uiGridSaveStateConstants, uiGridSaveStateService, gridUtil, $compile) {
  20841. return {
  20842. replace: true,
  20843. priority: 0,
  20844. require: '^uiGrid',
  20845. scope: false,
  20846. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  20847. uiGridSaveStateService.initializeGrid(uiGridCtrl.grid);
  20848. }
  20849. };
  20850. }
  20851. ]);
  20852. })();
  20853. (function () {
  20854. 'use strict';
  20855. /**
  20856. * @ngdoc overview
  20857. * @name ui.grid.selection
  20858. * @description
  20859. *
  20860. * # ui.grid.selection
  20861. * This module provides row selection
  20862. *
  20863. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  20864. *
  20865. * <div doc-module-components="ui.grid.selection"></div>
  20866. */
  20867. var module = angular.module('ui.grid.selection', ['ui.grid']);
  20868. /**
  20869. * @ngdoc object
  20870. * @name ui.grid.selection.constant:uiGridSelectionConstants
  20871. *
  20872. * @description constants available in selection module
  20873. */
  20874. module.constant('uiGridSelectionConstants', {
  20875. featureName: "selection",
  20876. selectionRowHeaderColName: 'selectionRowHeaderCol'
  20877. });
  20878. //add methods to GridRow
  20879. angular.module('ui.grid').config(['$provide', function($provide) {
  20880. $provide.decorator('GridRow', ['$delegate', function($delegate) {
  20881. /**
  20882. * @ngdoc object
  20883. * @name ui.grid.selection.api:GridRow
  20884. *
  20885. * @description GridRow prototype functions added for selection
  20886. */
  20887. /**
  20888. * @ngdoc object
  20889. * @name enableSelection
  20890. * @propertyOf ui.grid.selection.api:GridRow
  20891. * @description Enable row selection for this row, only settable by internal code.
  20892. *
  20893. * The grouping feature, for example, might set group header rows to not be selectable.
  20894. * <br/>Defaults to true
  20895. */
  20896. /**
  20897. * @ngdoc object
  20898. * @name isSelected
  20899. * @propertyOf ui.grid.selection.api:GridRow
  20900. * @description Selected state of row. Should be readonly. Make any changes to selected state using setSelected().
  20901. * <br/>Defaults to false
  20902. */
  20903. /**
  20904. * @ngdoc function
  20905. * @name setSelected
  20906. * @methodOf ui.grid.selection.api:GridRow
  20907. * @description Sets the isSelected property and updates the selectedCount
  20908. * Changes to isSelected state should only be made via this function
  20909. * @param {bool} selected value to set
  20910. */
  20911. $delegate.prototype.setSelected = function(selected) {
  20912. this.isSelected = selected;
  20913. if (selected) {
  20914. this.grid.selection.selectedCount++;
  20915. }
  20916. else {
  20917. this.grid.selection.selectedCount--;
  20918. }
  20919. };
  20920. return $delegate;
  20921. }]);
  20922. }]);
  20923. /**
  20924. * @ngdoc service
  20925. * @name ui.grid.selection.service:uiGridSelectionService
  20926. *
  20927. * @description Services for selection features
  20928. */
  20929. module.service('uiGridSelectionService', ['$q', '$templateCache', 'uiGridSelectionConstants', 'gridUtil',
  20930. function ($q, $templateCache, uiGridSelectionConstants, gridUtil) {
  20931. var service = {
  20932. initializeGrid: function (grid) {
  20933. //add feature namespace and any properties to grid for needed
  20934. /**
  20935. * @ngdoc object
  20936. * @name ui.grid.selection.grid:selection
  20937. *
  20938. * @description Grid properties and functions added for selection
  20939. */
  20940. grid.selection = {};
  20941. grid.selection.lastSelectedRow = null;
  20942. grid.selection.selectAll = false;
  20943. /**
  20944. * @ngdoc object
  20945. * @name selectedCount
  20946. * @propertyOf ui.grid.selection.grid:selection
  20947. * @description Current count of selected rows
  20948. * @example
  20949. * var count = grid.selection.selectedCount
  20950. */
  20951. grid.selection.selectedCount = 0;
  20952. service.defaultGridOptions(grid.options);
  20953. /**
  20954. * @ngdoc object
  20955. * @name ui.grid.selection.api:PublicApi
  20956. *
  20957. * @description Public Api for selection feature
  20958. */
  20959. var publicApi = {
  20960. events: {
  20961. selection: {
  20962. /**
  20963. * @ngdoc event
  20964. * @name rowSelectionChanged
  20965. * @eventOf ui.grid.selection.api:PublicApi
  20966. * @description is raised after the row.isSelected state is changed
  20967. * @param {GridRow} row the row that was selected/deselected
  20968. * @param {Event} event object if raised from an event
  20969. */
  20970. rowSelectionChanged: function (scope, row, evt) {
  20971. },
  20972. /**
  20973. * @ngdoc event
  20974. * @name rowSelectionChangedBatch
  20975. * @eventOf ui.grid.selection.api:PublicApi
  20976. * @description is raised after the row.isSelected state is changed
  20977. * in bulk, if the `enableSelectionBatchEvent` option is set to true
  20978. * (which it is by default). This allows more efficient processing
  20979. * of bulk events.
  20980. * @param {array} rows the rows that were selected/deselected
  20981. * @param {Event} event object if raised from an event
  20982. */
  20983. rowSelectionChangedBatch: function (scope, rows, evt) {
  20984. }
  20985. }
  20986. },
  20987. methods: {
  20988. selection: {
  20989. /**
  20990. * @ngdoc function
  20991. * @name toggleRowSelection
  20992. * @methodOf ui.grid.selection.api:PublicApi
  20993. * @description Toggles data row as selected or unselected
  20994. * @param {object} rowEntity gridOptions.data[] array instance
  20995. * @param {Event} event object if raised from an event
  20996. */
  20997. toggleRowSelection: function (rowEntity, evt) {
  20998. var row = grid.getRow(rowEntity);
  20999. if (row !== null) {
  21000. service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
  21001. }
  21002. },
  21003. /**
  21004. * @ngdoc function
  21005. * @name selectRow
  21006. * @methodOf ui.grid.selection.api:PublicApi
  21007. * @description Select the data row
  21008. * @param {object} rowEntity gridOptions.data[] array instance
  21009. * @param {Event} event object if raised from an event
  21010. */
  21011. selectRow: function (rowEntity, evt) {
  21012. var row = grid.getRow(rowEntity);
  21013. if (row !== null && !row.isSelected) {
  21014. service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
  21015. }
  21016. },
  21017. /**
  21018. * @ngdoc function
  21019. * @name selectRowByVisibleIndex
  21020. * @methodOf ui.grid.selection.api:PublicApi
  21021. * @description Select the specified row by visible index (i.e. if you
  21022. * specify row 0 you'll get the first visible row selected). In this context
  21023. * visible means of those rows that are theoretically visible (i.e. not filtered),
  21024. * rather than rows currently rendered on the screen.
  21025. * @param {number} index index within the rowsVisible array
  21026. * @param {Event} event object if raised from an event
  21027. */
  21028. selectRowByVisibleIndex: function ( rowNum, evt ) {
  21029. var row = grid.renderContainers.body.visibleRowCache[rowNum];
  21030. if (row !== null && typeof(row) !== 'undefined' && !row.isSelected) {
  21031. service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
  21032. }
  21033. },
  21034. /**
  21035. * @ngdoc function
  21036. * @name unSelectRow
  21037. * @methodOf ui.grid.selection.api:PublicApi
  21038. * @description UnSelect the data row
  21039. * @param {object} rowEntity gridOptions.data[] array instance
  21040. * @param {Event} event object if raised from an event
  21041. */
  21042. unSelectRow: function (rowEntity, evt) {
  21043. var row = grid.getRow(rowEntity);
  21044. if (row !== null && row.isSelected) {
  21045. service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
  21046. }
  21047. },
  21048. /**
  21049. * @ngdoc function
  21050. * @name selectAllRows
  21051. * @methodOf ui.grid.selection.api:PublicApi
  21052. * @description Selects all rows. Does nothing if multiSelect = false
  21053. * @param {Event} event object if raised from an event
  21054. */
  21055. selectAllRows: function (evt) {
  21056. if (grid.options.multiSelect === false) {
  21057. return;
  21058. }
  21059. var changedRows = [];
  21060. grid.rows.forEach(function (row) {
  21061. if ( !row.isSelected && row.enableSelection !== false ){
  21062. row.setSelected(true);
  21063. service.decideRaiseSelectionEvent( grid, row, changedRows, evt );
  21064. }
  21065. });
  21066. service.decideRaiseSelectionBatchEvent( grid, changedRows, evt );
  21067. grid.selection.selectAll = true;
  21068. },
  21069. /**
  21070. * @ngdoc function
  21071. * @name selectAllVisibleRows
  21072. * @methodOf ui.grid.selection.api:PublicApi
  21073. * @description Selects all visible rows. Does nothing if multiSelect = false
  21074. * @param {Event} event object if raised from an event
  21075. */
  21076. selectAllVisibleRows: function (evt) {
  21077. if (grid.options.multiSelect === false) {
  21078. return;
  21079. }
  21080. var changedRows = [];
  21081. grid.rows.forEach(function (row) {
  21082. if (row.visible) {
  21083. if (!row.isSelected && row.enableSelection !== false){
  21084. row.setSelected(true);
  21085. service.decideRaiseSelectionEvent( grid, row, changedRows, evt );
  21086. }
  21087. } else {
  21088. if (row.isSelected){
  21089. row.setSelected(false);
  21090. service.decideRaiseSelectionEvent( grid, row, changedRows, evt );
  21091. }
  21092. }
  21093. });
  21094. service.decideRaiseSelectionBatchEvent( grid, changedRows, evt );
  21095. grid.selection.selectAll = true;
  21096. },
  21097. /**
  21098. * @ngdoc function
  21099. * @name clearSelectedRows
  21100. * @methodOf ui.grid.selection.api:PublicApi
  21101. * @description Unselects all rows
  21102. * @param {Event} event object if raised from an event
  21103. */
  21104. clearSelectedRows: function (evt) {
  21105. service.clearSelectedRows(grid, evt);
  21106. },
  21107. /**
  21108. * @ngdoc function
  21109. * @name getSelectedRows
  21110. * @methodOf ui.grid.selection.api:PublicApi
  21111. * @description returns all selectedRow's entity references
  21112. */
  21113. getSelectedRows: function () {
  21114. return service.getSelectedRows(grid).map(function (gridRow) {
  21115. return gridRow.entity;
  21116. });
  21117. },
  21118. /**
  21119. * @ngdoc function
  21120. * @name getSelectedGridRows
  21121. * @methodOf ui.grid.selection.api:PublicApi
  21122. * @description returns all selectedRow's as gridRows
  21123. */
  21124. getSelectedGridRows: function () {
  21125. return service.getSelectedRows(grid);
  21126. },
  21127. /**
  21128. * @ngdoc function
  21129. * @name setMultiSelect
  21130. * @methodOf ui.grid.selection.api:PublicApi
  21131. * @description Sets the current gridOption.multiSelect to true or false
  21132. * @param {bool} multiSelect true to allow multiple rows
  21133. */
  21134. setMultiSelect: function (multiSelect) {
  21135. grid.options.multiSelect = multiSelect;
  21136. },
  21137. /**
  21138. * @ngdoc function
  21139. * @name setModifierKeysToMultiSelect
  21140. * @methodOf ui.grid.selection.api:PublicApi
  21141. * @description Sets the current gridOption.modifierKeysToMultiSelect to true or false
  21142. * @param {bool} modifierKeysToMultiSelect true to only allow multiple rows when using ctrlKey or shiftKey is used
  21143. */
  21144. setModifierKeysToMultiSelect: function (modifierKeysToMultiSelect) {
  21145. grid.options.modifierKeysToMultiSelect = modifierKeysToMultiSelect;
  21146. },
  21147. /**
  21148. * @ngdoc function
  21149. * @name getSelectAllState
  21150. * @methodOf ui.grid.selection.api:PublicApi
  21151. * @description Returns whether or not the selectAll checkbox is currently ticked. The
  21152. * grid doesn't automatically select rows when you add extra data - so when you add data
  21153. * you need to explicitly check whether the selectAll is set, and then call setVisible rows
  21154. * if it is
  21155. */
  21156. getSelectAllState: function () {
  21157. return grid.selection.selectAll;
  21158. }
  21159. }
  21160. }
  21161. };
  21162. grid.api.registerEventsFromObject(publicApi.events);
  21163. grid.api.registerMethodsFromObject(publicApi.methods);
  21164. },
  21165. defaultGridOptions: function (gridOptions) {
  21166. //default option to true unless it was explicitly set to false
  21167. /**
  21168. * @ngdoc object
  21169. * @name ui.grid.selection.api:GridOptions
  21170. *
  21171. * @description GridOptions for selection feature, these are available to be
  21172. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  21173. */
  21174. /**
  21175. * @ngdoc object
  21176. * @name enableRowSelection
  21177. * @propertyOf ui.grid.selection.api:GridOptions
  21178. * @description Enable row selection for entire grid.
  21179. * <br/>Defaults to true
  21180. */
  21181. gridOptions.enableRowSelection = gridOptions.enableRowSelection !== false;
  21182. /**
  21183. * @ngdoc object
  21184. * @name multiSelect
  21185. * @propertyOf ui.grid.selection.api:GridOptions
  21186. * @description Enable multiple row selection for entire grid
  21187. * <br/>Defaults to true
  21188. */
  21189. gridOptions.multiSelect = gridOptions.multiSelect !== false;
  21190. /**
  21191. * @ngdoc object
  21192. * @name noUnselect
  21193. * @propertyOf ui.grid.selection.api:GridOptions
  21194. * @description Prevent a row from being unselected. Works in conjunction
  21195. * with `multiselect = false` and `gridApi.selection.selectRow()` to allow
  21196. * you to create a single selection only grid - a row is always selected, you
  21197. * can only select different rows, you can't unselect the row.
  21198. * <br/>Defaults to false
  21199. */
  21200. gridOptions.noUnselect = gridOptions.noUnselect === true;
  21201. /**
  21202. * @ngdoc object
  21203. * @name modifierKeysToMultiSelect
  21204. * @propertyOf ui.grid.selection.api:GridOptions
  21205. * @description Enable multiple row selection only when using the ctrlKey or shiftKey. Requires multiSelect to be true.
  21206. * <br/>Defaults to false
  21207. */
  21208. gridOptions.modifierKeysToMultiSelect = gridOptions.modifierKeysToMultiSelect === true;
  21209. /**
  21210. * @ngdoc object
  21211. * @name enableRowHeaderSelection
  21212. * @propertyOf ui.grid.selection.api:GridOptions
  21213. * @description Enable a row header to be used for selection
  21214. * <br/>Defaults to true
  21215. */
  21216. gridOptions.enableRowHeaderSelection = gridOptions.enableRowHeaderSelection !== false;
  21217. /**
  21218. * @ngdoc object
  21219. * @name enableFullRowSelection
  21220. * @propertyOf ui.grid.selection.api:GridOptions
  21221. * @description Enable selection by clicking anywhere on the row. Defaults to
  21222. * false if `enableRowHeaderSelection` is true, otherwise defaults to false.
  21223. */
  21224. if ( typeof(gridOptions.enableFullRowSelection) === 'undefined' ){
  21225. gridOptions.enableFullRowSelection = !gridOptions.enableRowHeaderSelection;
  21226. }
  21227. /**
  21228. * @ngdoc object
  21229. * @name enableSelectAll
  21230. * @propertyOf ui.grid.selection.api:GridOptions
  21231. * @description Enable the select all checkbox at the top of the selectionRowHeader
  21232. * <br/>Defaults to true
  21233. */
  21234. gridOptions.enableSelectAll = gridOptions.enableSelectAll !== false;
  21235. /**
  21236. * @ngdoc object
  21237. * @name enableSelectionBatchEvent
  21238. * @propertyOf ui.grid.selection.api:GridOptions
  21239. * @description If selected rows are changed in bulk, either via the API or
  21240. * via the selectAll checkbox, then a separate event is fired. Setting this
  21241. * option to false will cause the rowSelectionChanged event to be called multiple times
  21242. * instead
  21243. * <br/>Defaults to true
  21244. */
  21245. gridOptions.enableSelectionBatchEvent = gridOptions.enableSelectionBatchEvent !== false;
  21246. /**
  21247. * @ngdoc object
  21248. * @name selectionRowHeaderWidth
  21249. * @propertyOf ui.grid.selection.api:GridOptions
  21250. * @description can be used to set a custom width for the row header selection column
  21251. * <br/>Defaults to 30px
  21252. */
  21253. gridOptions.selectionRowHeaderWidth = angular.isDefined(gridOptions.selectionRowHeaderWidth) ? gridOptions.selectionRowHeaderWidth : 30;
  21254. /**
  21255. * @ngdoc object
  21256. * @name enableFooterTotalSelected
  21257. * @propertyOf ui.grid.selection.api:GridOptions
  21258. * @description Shows the total number of selected items in footer if true.
  21259. * <br/>Defaults to true.
  21260. * <br/>GridOptions.showGridFooter must also be set to true.
  21261. */
  21262. gridOptions.enableFooterTotalSelected = gridOptions.enableFooterTotalSelected !== false;
  21263. /**
  21264. * @ngdoc object
  21265. * @name isRowSelectable
  21266. * @propertyOf ui.grid.selection.api:GridOptions
  21267. * @description Makes it possible to specify a method that evaluates for each row and sets its "enableSelection" property.
  21268. */
  21269. gridOptions.isRowSelectable = angular.isDefined(gridOptions.isRowSelectable) ? gridOptions.isRowSelectable : angular.noop;
  21270. },
  21271. /**
  21272. * @ngdoc function
  21273. * @name toggleRowSelection
  21274. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21275. * @description Toggles row as selected or unselected
  21276. * @param {Grid} grid grid object
  21277. * @param {GridRow} row row to select or deselect
  21278. * @param {Event} event object if resulting from event
  21279. * @param {bool} multiSelect if false, only one row at time can be selected
  21280. * @param {bool} noUnselect if true then rows cannot be unselected
  21281. */
  21282. toggleRowSelection: function (grid, row, evt, multiSelect, noUnselect) {
  21283. var selected = row.isSelected;
  21284. if ( row.enableSelection === false && !selected ){
  21285. return;
  21286. }
  21287. if (!multiSelect && !selected) {
  21288. service.clearSelectedRows(grid, evt);
  21289. } else if (!multiSelect && selected) {
  21290. var selectedRows = service.getSelectedRows(grid);
  21291. if (selectedRows.length > 1) {
  21292. selected = false; // Enable reselect of the row
  21293. service.clearSelectedRows(grid, evt);
  21294. }
  21295. }
  21296. if (selected && noUnselect){
  21297. // don't deselect the row
  21298. } else {
  21299. row.setSelected(!selected);
  21300. if (row.isSelected === true) {
  21301. grid.selection.lastSelectedRow = row;
  21302. } else {
  21303. grid.selection.selectAll = false;
  21304. }
  21305. grid.api.selection.raise.rowSelectionChanged(row, evt);
  21306. }
  21307. },
  21308. /**
  21309. * @ngdoc function
  21310. * @name shiftSelect
  21311. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21312. * @description selects a group of rows from the last selected row using the shift key
  21313. * @param {Grid} grid grid object
  21314. * @param {GridRow} clicked row
  21315. * @param {Event} event object if raised from an event
  21316. * @param {bool} multiSelect if false, does nothing this is for multiSelect only
  21317. */
  21318. shiftSelect: function (grid, row, evt, multiSelect) {
  21319. if (!multiSelect) {
  21320. return;
  21321. }
  21322. var selectedRows = service.getSelectedRows(grid);
  21323. var fromRow = selectedRows.length > 0 ? grid.renderContainers.body.visibleRowCache.indexOf(grid.selection.lastSelectedRow) : 0;
  21324. var toRow = grid.renderContainers.body.visibleRowCache.indexOf(row);
  21325. //reverse select direction
  21326. if (fromRow > toRow) {
  21327. var tmp = fromRow;
  21328. fromRow = toRow;
  21329. toRow = tmp;
  21330. }
  21331. var changedRows = [];
  21332. for (var i = fromRow; i <= toRow; i++) {
  21333. var rowToSelect = grid.renderContainers.body.visibleRowCache[i];
  21334. if (rowToSelect) {
  21335. if ( !rowToSelect.isSelected && rowToSelect.enableSelection !== false ){
  21336. rowToSelect.setSelected(true);
  21337. grid.selection.lastSelectedRow = rowToSelect;
  21338. service.decideRaiseSelectionEvent( grid, rowToSelect, changedRows, evt );
  21339. }
  21340. }
  21341. }
  21342. service.decideRaiseSelectionBatchEvent( grid, changedRows, evt );
  21343. },
  21344. /**
  21345. * @ngdoc function
  21346. * @name getSelectedRows
  21347. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21348. * @description Returns all the selected rows
  21349. * @param {Grid} grid grid object
  21350. */
  21351. getSelectedRows: function (grid) {
  21352. return grid.rows.filter(function (row) {
  21353. return row.isSelected;
  21354. });
  21355. },
  21356. /**
  21357. * @ngdoc function
  21358. * @name clearSelectedRows
  21359. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21360. * @description Clears all selected rows
  21361. * @param {Grid} grid grid object
  21362. * @param {Event} event object if raised from an event
  21363. */
  21364. clearSelectedRows: function (grid, evt) {
  21365. var changedRows = [];
  21366. service.getSelectedRows(grid).forEach(function (row) {
  21367. if ( row.isSelected ){
  21368. row.setSelected(false);
  21369. service.decideRaiseSelectionEvent( grid, row, changedRows, evt );
  21370. }
  21371. });
  21372. service.decideRaiseSelectionBatchEvent( grid, changedRows, evt );
  21373. grid.selection.selectAll = false;
  21374. },
  21375. /**
  21376. * @ngdoc function
  21377. * @name decideRaiseSelectionEvent
  21378. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21379. * @description Decides whether to raise a single event or a batch event
  21380. * @param {Grid} grid grid object
  21381. * @param {GridRow} row row that has changed
  21382. * @param {array} changedRows an array to which we can append the changed
  21383. * @param {Event} event object if raised from an event
  21384. * row if we're doing batch events
  21385. */
  21386. decideRaiseSelectionEvent: function( grid, row, changedRows, evt ){
  21387. if ( !grid.options.enableSelectionBatchEvent ){
  21388. grid.api.selection.raise.rowSelectionChanged(row, evt);
  21389. } else {
  21390. changedRows.push(row);
  21391. }
  21392. },
  21393. /**
  21394. * @ngdoc function
  21395. * @name raiseSelectionEvent
  21396. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21397. * @description Decides whether we need to raise a batch event, and
  21398. * raises it if we do.
  21399. * @param {Grid} grid grid object
  21400. * @param {array} changedRows an array of changed rows, only populated
  21401. * @param {Event} event object if raised from an event
  21402. * if we're doing batch events
  21403. */
  21404. decideRaiseSelectionBatchEvent: function( grid, changedRows, evt ){
  21405. if ( changedRows.length > 0 ){
  21406. grid.api.selection.raise.rowSelectionChangedBatch(changedRows, evt);
  21407. }
  21408. }
  21409. };
  21410. return service;
  21411. }]);
  21412. /**
  21413. * @ngdoc directive
  21414. * @name ui.grid.selection.directive:uiGridSelection
  21415. * @element div
  21416. * @restrict A
  21417. *
  21418. * @description Adds selection features to grid
  21419. *
  21420. * @example
  21421. <example module="app">
  21422. <file name="app.js">
  21423. var app = angular.module('app', ['ui.grid', 'ui.grid.selection']);
  21424. app.controller('MainCtrl', ['$scope', function ($scope) {
  21425. $scope.data = [
  21426. { name: 'Bob', title: 'CEO' },
  21427. { name: 'Frank', title: 'Lowly Developer' }
  21428. ];
  21429. $scope.columnDefs = [
  21430. {name: 'name', enableCellEdit: true},
  21431. {name: 'title', enableCellEdit: true}
  21432. ];
  21433. }]);
  21434. </file>
  21435. <file name="index.html">
  21436. <div ng-controller="MainCtrl">
  21437. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-selection></div>
  21438. </div>
  21439. </file>
  21440. </example>
  21441. */
  21442. module.directive('uiGridSelection', ['uiGridSelectionConstants', 'uiGridSelectionService', '$templateCache', 'uiGridConstants',
  21443. function (uiGridSelectionConstants, uiGridSelectionService, $templateCache, uiGridConstants) {
  21444. return {
  21445. replace: true,
  21446. priority: 0,
  21447. require: '^uiGrid',
  21448. scope: false,
  21449. compile: function () {
  21450. return {
  21451. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  21452. uiGridSelectionService.initializeGrid(uiGridCtrl.grid);
  21453. if (uiGridCtrl.grid.options.enableRowHeaderSelection) {
  21454. var selectionRowHeaderDef = {
  21455. name: uiGridSelectionConstants.selectionRowHeaderColName,
  21456. displayName: '',
  21457. width: uiGridCtrl.grid.options.selectionRowHeaderWidth,
  21458. minWidth: 10,
  21459. cellTemplate: 'ui-grid/selectionRowHeader',
  21460. headerCellTemplate: 'ui-grid/selectionHeaderCell',
  21461. enableColumnResizing: false,
  21462. enableColumnMenu: false,
  21463. exporterSuppressExport: true,
  21464. allowCellFocus: true
  21465. };
  21466. uiGridCtrl.grid.addRowHeaderColumn(selectionRowHeaderDef);
  21467. }
  21468. var processorSet = false;
  21469. var processSelectableRows = function( rows ){
  21470. rows.forEach(function(row){
  21471. row.enableSelection = uiGridCtrl.grid.options.isRowSelectable(row);
  21472. });
  21473. return rows;
  21474. };
  21475. var updateOptions = function(){
  21476. if (uiGridCtrl.grid.options.isRowSelectable !== angular.noop && processorSet !== true) {
  21477. uiGridCtrl.grid.registerRowsProcessor(processSelectableRows, 500);
  21478. processorSet = true;
  21479. }
  21480. };
  21481. updateOptions();
  21482. var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback( updateOptions, [uiGridConstants.dataChange.OPTIONS] );
  21483. $scope.$on( '$destroy', dataChangeDereg);
  21484. },
  21485. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  21486. }
  21487. };
  21488. }
  21489. };
  21490. }]);
  21491. module.directive('uiGridSelectionRowHeaderButtons', ['$templateCache', 'uiGridSelectionService', 'gridUtil',
  21492. function ($templateCache, uiGridSelectionService, gridUtil) {
  21493. return {
  21494. replace: true,
  21495. restrict: 'E',
  21496. template: $templateCache.get('ui-grid/selectionRowHeaderButtons'),
  21497. scope: true,
  21498. require: '^uiGrid',
  21499. link: function($scope, $elm, $attrs, uiGridCtrl) {
  21500. var self = uiGridCtrl.grid;
  21501. $scope.selectButtonClick = selectButtonClick;
  21502. // On IE, prevent mousedowns on the select button from starting a selection.
  21503. // If this is not done and you shift+click on another row, the browser will select a big chunk of text
  21504. if (gridUtil.detectBrowser() === 'ie') {
  21505. $elm.on('mousedown', selectButtonMouseDown);
  21506. }
  21507. function selectButtonClick(row, evt) {
  21508. evt.stopPropagation();
  21509. if (evt.shiftKey) {
  21510. uiGridSelectionService.shiftSelect(self, row, evt, self.options.multiSelect);
  21511. }
  21512. else if (evt.ctrlKey || evt.metaKey) {
  21513. uiGridSelectionService.toggleRowSelection(self, row, evt, self.options.multiSelect, self.options.noUnselect);
  21514. }
  21515. else {
  21516. uiGridSelectionService.toggleRowSelection(self, row, evt, (self.options.multiSelect && !self.options.modifierKeysToMultiSelect), self.options.noUnselect);
  21517. }
  21518. }
  21519. function selectButtonMouseDown(evt) {
  21520. if (evt.ctrlKey || evt.shiftKey) {
  21521. evt.target.onselectstart = function () { return false; };
  21522. window.setTimeout(function () { evt.target.onselectstart = null; }, 0);
  21523. }
  21524. }
  21525. }
  21526. };
  21527. }]);
  21528. module.directive('uiGridSelectionSelectAllButtons', ['$templateCache', 'uiGridSelectionService',
  21529. function ($templateCache, uiGridSelectionService) {
  21530. return {
  21531. replace: true,
  21532. restrict: 'E',
  21533. template: $templateCache.get('ui-grid/selectionSelectAllButtons'),
  21534. scope: false,
  21535. link: function($scope, $elm, $attrs, uiGridCtrl) {
  21536. var self = $scope.col.grid;
  21537. $scope.headerButtonClick = function(row, evt) {
  21538. if ( self.selection.selectAll ){
  21539. uiGridSelectionService.clearSelectedRows(self, evt);
  21540. if ( self.options.noUnselect ){
  21541. self.api.selection.selectRowByVisibleIndex(0, evt);
  21542. }
  21543. self.selection.selectAll = false;
  21544. } else {
  21545. if ( self.options.multiSelect ){
  21546. self.api.selection.selectAllVisibleRows(evt);
  21547. self.selection.selectAll = true;
  21548. }
  21549. }
  21550. };
  21551. }
  21552. };
  21553. }]);
  21554. /**
  21555. * @ngdoc directive
  21556. * @name ui.grid.selection.directive:uiGridViewport
  21557. * @element div
  21558. *
  21559. * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used
  21560. * for the grid row
  21561. */
  21562. module.directive('uiGridViewport',
  21563. ['$compile', 'uiGridConstants', 'uiGridSelectionConstants', 'gridUtil', '$parse', 'uiGridSelectionService',
  21564. function ($compile, uiGridConstants, uiGridSelectionConstants, gridUtil, $parse, uiGridSelectionService) {
  21565. return {
  21566. priority: -200, // run after default directive
  21567. scope: false,
  21568. compile: function ($elm, $attrs) {
  21569. var rowRepeatDiv = angular.element($elm.children().children()[0]);
  21570. var existingNgClass = rowRepeatDiv.attr("ng-class");
  21571. var newNgClass = '';
  21572. if ( existingNgClass ) {
  21573. newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-row-selected': row.isSelected}";
  21574. } else {
  21575. newNgClass = "{'ui-grid-row-selected': row.isSelected}";
  21576. }
  21577. rowRepeatDiv.attr("ng-class", newNgClass);
  21578. return {
  21579. pre: function ($scope, $elm, $attrs, controllers) {
  21580. },
  21581. post: function ($scope, $elm, $attrs, controllers) {
  21582. }
  21583. };
  21584. }
  21585. };
  21586. }]);
  21587. /**
  21588. * @ngdoc directive
  21589. * @name ui.grid.selection.directive:uiGridCell
  21590. * @element div
  21591. * @restrict A
  21592. *
  21593. * @description Stacks on top of ui.grid.uiGridCell to provide selection feature
  21594. */
  21595. module.directive('uiGridCell',
  21596. ['$compile', 'uiGridConstants', 'uiGridSelectionConstants', 'gridUtil', '$parse', 'uiGridSelectionService', '$timeout',
  21597. function ($compile, uiGridConstants, uiGridSelectionConstants, gridUtil, $parse, uiGridSelectionService, $timeout) {
  21598. return {
  21599. priority: -200, // run after default uiGridCell directive
  21600. restrict: 'A',
  21601. require: '?^uiGrid',
  21602. scope: false,
  21603. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  21604. var touchStartTime = 0;
  21605. var touchTimeout = 300;
  21606. // Bind to keydown events in the render container
  21607. if (uiGridCtrl.grid.api.cellNav) {
  21608. uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function (evt, rowCol) {
  21609. if (rowCol === null ||
  21610. rowCol.row !== $scope.row ||
  21611. rowCol.col !== $scope.col) {
  21612. return;
  21613. }
  21614. if (evt.keyCode === 32 && $scope.col.colDef.name === "selectionRowHeaderCol") {
  21615. uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect);
  21616. $scope.$apply();
  21617. }
  21618. // uiGridCellNavService.scrollToIfNecessary(uiGridCtrl.grid, rowCol.row, rowCol.col);
  21619. });
  21620. }
  21621. //$elm.bind('keydown', function (evt) {
  21622. // if (evt.keyCode === 32 && $scope.col.colDef.name === "selectionRowHeaderCol") {
  21623. // uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect);
  21624. // $scope.$apply();
  21625. // }
  21626. //});
  21627. var selectCells = function(evt){
  21628. // if we get a click, then stop listening for touchend
  21629. $elm.off('touchend', touchEnd);
  21630. if (evt.shiftKey) {
  21631. uiGridSelectionService.shiftSelect($scope.grid, $scope.row, evt, $scope.grid.options.multiSelect);
  21632. }
  21633. else if (evt.ctrlKey || evt.metaKey) {
  21634. uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, $scope.grid.options.multiSelect, $scope.grid.options.noUnselect);
  21635. }
  21636. else {
  21637. uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect);
  21638. }
  21639. $scope.$apply();
  21640. // don't re-enable the touchend handler for a little while - some devices generate both, and it will
  21641. // take a little while to move your hand from the mouse to the screen if you have both modes of input
  21642. $timeout(function() {
  21643. $elm.on('touchend', touchEnd);
  21644. }, touchTimeout);
  21645. };
  21646. var touchStart = function(evt){
  21647. touchStartTime = (new Date()).getTime();
  21648. // if we get a touch event, then stop listening for click
  21649. $elm.off('click', selectCells);
  21650. };
  21651. var touchEnd = function(evt) {
  21652. var touchEndTime = (new Date()).getTime();
  21653. var touchTime = touchEndTime - touchStartTime;
  21654. if (touchTime < touchTimeout ) {
  21655. // short touch
  21656. selectCells(evt);
  21657. }
  21658. // don't re-enable the click handler for a little while - some devices generate both, and it will
  21659. // take a little while to move your hand from the screen to the mouse if you have both modes of input
  21660. $timeout(function() {
  21661. $elm.on('click', selectCells);
  21662. }, touchTimeout);
  21663. };
  21664. function registerRowSelectionEvents() {
  21665. if ($scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection) {
  21666. $elm.addClass('ui-grid-disable-selection');
  21667. $elm.on('touchstart', touchStart);
  21668. $elm.on('touchend', touchEnd);
  21669. $elm.on('click', selectCells);
  21670. $scope.registered = true;
  21671. }
  21672. }
  21673. function deregisterRowSelectionEvents() {
  21674. if ($scope.registered){
  21675. $elm.removeClass('ui-grid-disable-selection');
  21676. $elm.off('touchstart', touchStart);
  21677. $elm.off('touchend', touchEnd);
  21678. $elm.off('click', selectCells);
  21679. $scope.registered = false;
  21680. }
  21681. }
  21682. registerRowSelectionEvents();
  21683. // register a dataChange callback so that we can change the selection configuration dynamically
  21684. // if the user changes the options
  21685. var dataChangeDereg = $scope.grid.registerDataChangeCallback( function() {
  21686. if ( $scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection &&
  21687. !$scope.registered ){
  21688. registerRowSelectionEvents();
  21689. } else if ( ( !$scope.grid.options.enableRowSelection || !$scope.grid.options.enableFullRowSelection ) &&
  21690. $scope.registered ){
  21691. deregisterRowSelectionEvents();
  21692. }
  21693. }, [uiGridConstants.dataChange.OPTIONS] );
  21694. $elm.on( '$destroy', dataChangeDereg);
  21695. }
  21696. };
  21697. }]);
  21698. module.directive('uiGridGridFooter', ['$compile', 'uiGridConstants', 'gridUtil', function ($compile, uiGridConstants, gridUtil) {
  21699. return {
  21700. restrict: 'EA',
  21701. replace: true,
  21702. priority: -1000,
  21703. require: '^uiGrid',
  21704. scope: true,
  21705. compile: function ($elm, $attrs) {
  21706. return {
  21707. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  21708. if (!uiGridCtrl.grid.options.showGridFooter) {
  21709. return;
  21710. }
  21711. gridUtil.getTemplate('ui-grid/gridFooterSelectedItems')
  21712. .then(function (contents) {
  21713. var template = angular.element(contents);
  21714. var newElm = $compile(template)($scope);
  21715. angular.element($elm[0].getElementsByClassName('ui-grid-grid-footer')[0]).append(newElm);
  21716. });
  21717. },
  21718. post: function ($scope, $elm, $attrs, controllers) {
  21719. }
  21720. };
  21721. }
  21722. };
  21723. }]);
  21724. })();
  21725. (function () {
  21726. 'use strict';
  21727. /**
  21728. * @ngdoc overview
  21729. * @name ui.grid.treeBase
  21730. * @description
  21731. *
  21732. * # ui.grid.treeBase
  21733. *
  21734. * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div>
  21735. *
  21736. * This module provides base tree handling functions that are shared by other features, notably grouping
  21737. * and treeView. It provides a tree view of the data, with nodes in that
  21738. * tree and leaves.
  21739. *
  21740. * Design information:
  21741. * -------------------
  21742. *
  21743. * The raw data that is provided must come with a $$treeLevel on any non-leaf node. Grouping will create
  21744. * these on all the group header rows, treeView will expect these to be set in the raw data by the user.
  21745. * TreeBase will run a rowsProcessor that:
  21746. * - builds `treeBase.tree` out of the provided rows
  21747. * - permits a recursive sort of the tree
  21748. * - maintains the expand/collapse state of each node
  21749. * - provides the expand/collapse all button and the expand/collapse buttons
  21750. * - maintains the count of children for each node
  21751. *
  21752. * Each row is updated with a link to the tree node that represents it. Refer {@link ui.grid.treeBase.grid:treeBase.tree tree documentation}
  21753. * for information.
  21754. *
  21755. * TreeBase adds information to the rows
  21756. * - treeLevel: if present and > -1 tells us the level (level 0 is the top level)
  21757. * - treeNode: pointer to the node in the grid.treeBase.tree that refers
  21758. * to this row, allowing us to manipulate the state
  21759. *
  21760. * Since the logic is baked into the rowsProcessors, it should get triggered whenever
  21761. * row order or filtering or anything like that is changed. We recall the expanded state
  21762. * across invocations of the rowsProcessors by the reference to the treeNode on the individual
  21763. * rows. We rebuild the tree itself quite frequently, when we do this we use the saved treeNodes to
  21764. * get the state, but we overwrite the other data in that treeNode.
  21765. *
  21766. * By default rows are collapsed, which means all data rows have their visible property
  21767. * set to false, and only level 0 group rows are set to visible.
  21768. *
  21769. * We rely on the rowsProcessors to do the actual expanding and collapsing, so we set the flags we want into
  21770. * grid.treeBase.tree, then call refresh. This is because we can't easily change the visible
  21771. * row cache without calling the processors, and once we've built the logic into the rowProcessors we may as
  21772. * well use it all the time.
  21773. *
  21774. * Tree base provides sorting (on non-grouped columns).
  21775. *
  21776. * Sorting works in two passes. The standard sorting is performed for any columns that are important to building
  21777. * the tree (for example, any grouped columns). Then after the tree is built, a recursive tree sort is performed
  21778. * for the remaining sort columns (including the original sort) - these columns are sorted within each tree level
  21779. * (so all the level 1 nodes are sorted, then all the level 2 nodes within each level 1 node etc).
  21780. *
  21781. * To achieve this we make use of the `ignoreSort` property on the sort configuration. The parent feature (treeView or grouping)
  21782. * must provide a rowsProcessor that runs with very low priority (typically in the 60-65 range), and that sets
  21783. * the `ignoreSort`on any sort that it wants to run on the tree. TreeBase will clear the ignoreSort on all sorts - so it
  21784. * will turn on any sorts that haven't run. It will then call a recursive sort on the tree.
  21785. *
  21786. * Tree base provides treeAggregation. It checks the treeAggregation configuration on each column, and aggregates based on
  21787. * the logic provided as it builds the tree. Footer aggregation from the uiGrid core should not be used with treeBase aggregation,
  21788. * since it operates on all visible rows, as opposed to to leaf nodes only. Setting `showColumnFooter: true` will show the
  21789. * treeAggregations in the column footer. Aggregation information will be collected in the format:
  21790. *
  21791. * ```
  21792. * {
  21793. * type: 'count',
  21794. * value: 4,
  21795. * label: 'count: ',
  21796. * rendered: 'count: 4'
  21797. * }
  21798. * ```
  21799. *
  21800. * A callback is provided to format the value once it is finalised (aka a valueFilter).
  21801. *
  21802. * <br/>
  21803. * <br/>
  21804. *
  21805. * <div doc-module-components="ui.grid.treeBase"></div>
  21806. */
  21807. var module = angular.module('ui.grid.treeBase', ['ui.grid']);
  21808. /**
  21809. * @ngdoc object
  21810. * @name ui.grid.treeBase.constant:uiGridTreeBaseConstants
  21811. *
  21812. * @description constants available in treeBase module.
  21813. *
  21814. * These constants are manually copied into grouping and treeView,
  21815. * as I haven't found a way to simply include them, and it's not worth
  21816. * investing time in for something that changes very infrequently.
  21817. *
  21818. */
  21819. module.constant('uiGridTreeBaseConstants', {
  21820. featureName: "treeBase",
  21821. rowHeaderColName: 'treeBaseRowHeaderCol',
  21822. EXPANDED: 'expanded',
  21823. COLLAPSED: 'collapsed',
  21824. aggregation: {
  21825. COUNT: 'count',
  21826. SUM: 'sum',
  21827. MAX: 'max',
  21828. MIN: 'min',
  21829. AVG: 'avg'
  21830. }
  21831. });
  21832. /**
  21833. * @ngdoc service
  21834. * @name ui.grid.treeBase.service:uiGridTreeBaseService
  21835. *
  21836. * @description Services for treeBase feature
  21837. */
  21838. /**
  21839. * @ngdoc object
  21840. * @name ui.grid.treeBase.api:ColumnDef
  21841. *
  21842. * @description ColumnDef for tree feature, these are available to be
  21843. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  21844. */
  21845. module.service('uiGridTreeBaseService', ['$q', 'uiGridTreeBaseConstants', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'rowSorter',
  21846. function ($q, uiGridTreeBaseConstants, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants, rowSorter) {
  21847. var service = {
  21848. initializeGrid: function (grid, $scope) {
  21849. //add feature namespace and any properties to grid for needed
  21850. /**
  21851. * @ngdoc object
  21852. * @name ui.grid.treeBase.grid:treeBase
  21853. *
  21854. * @description Grid properties and functions added for treeBase
  21855. */
  21856. grid.treeBase = {};
  21857. /**
  21858. * @ngdoc property
  21859. * @propertyOf ui.grid.treeBase.grid:treeBase
  21860. * @name numberLevels
  21861. *
  21862. * @description Total number of tree levels currently used, calculated by the rowsProcessor by
  21863. * retaining the highest tree level it sees
  21864. */
  21865. grid.treeBase.numberLevels = 0;
  21866. /**
  21867. * @ngdoc property
  21868. * @propertyOf ui.grid.treeBase.grid:treeBase
  21869. * @name expandAll
  21870. *
  21871. * @description Whether or not the expandAll box is selected
  21872. */
  21873. grid.treeBase.expandAll = false;
  21874. /**
  21875. * @ngdoc property
  21876. * @propertyOf ui.grid.treeBase.grid:treeBase
  21877. * @name tree
  21878. *
  21879. * @description Tree represented as a nested array that holds the state of each node, along with a
  21880. * pointer to the row. The array order is material - we will display the children in the order
  21881. * they are stored in the array
  21882. *
  21883. * Each node stores:
  21884. *
  21885. * - the state of this node
  21886. * - an array of children of this node
  21887. * - a pointer to the parent of this node (reverse pointer, allowing us to walk up the tree)
  21888. * - the number of children of this node
  21889. * - aggregation information calculated from the nodes
  21890. *
  21891. * ```
  21892. * [{
  21893. * state: 'expanded',
  21894. * row: <reference to row>,
  21895. * parentRow: null,
  21896. * aggregations: [{
  21897. * type: 'count',
  21898. * col: <gridCol>,
  21899. * value: 2,
  21900. * label: 'count: ',
  21901. * rendered: 'count: 2'
  21902. * }],
  21903. * children: [
  21904. * {
  21905. * state: 'expanded',
  21906. * row: <reference to row>,
  21907. * parentRow: <reference to row>,
  21908. * aggregations: [{
  21909. * type: 'count',
  21910. * col: '<gridCol>,
  21911. * value: 4,
  21912. * label: 'count: ',
  21913. * rendered: 'count: 4'
  21914. * }],
  21915. * children: [
  21916. * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
  21917. * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> },
  21918. * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
  21919. * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }
  21920. * ]
  21921. * },
  21922. * {
  21923. * state: 'collapsed',
  21924. * row: <reference to row>,
  21925. * parentRow: <reference to row>,
  21926. * aggregations: [{
  21927. * type: 'count',
  21928. * col: <gridCol>,
  21929. * value: 3,
  21930. * label: 'count: ',
  21931. * rendered: 'count: 3'
  21932. * }],
  21933. * children: [
  21934. * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
  21935. * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> },
  21936. * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }
  21937. * ]
  21938. * }
  21939. * ]
  21940. * }, {<another level 0 node maybe>} ]
  21941. * ```
  21942. * Missing state values are false - meaning they aren't expanded.
  21943. *
  21944. * This is used because the rowProcessors run every time the grid is refreshed, so
  21945. * we'd lose the expanded state every time the grid was refreshed. This instead gives
  21946. * us a reliable lookup that persists across rowProcessors.
  21947. *
  21948. * This tree is rebuilt every time we run the rowsProcessors. Since each row holds a pointer
  21949. * to it's tree node we can persist expand/collapse state across calls to rowsProcessor, we discard
  21950. * all transient information on the tree (children, childCount) and recalculate it
  21951. *
  21952. */
  21953. grid.treeBase.tree = {};
  21954. service.defaultGridOptions(grid.options);
  21955. grid.registerRowsProcessor(service.treeRows, 410);
  21956. grid.registerColumnBuilder( service.treeBaseColumnBuilder );
  21957. service.createRowHeader( grid );
  21958. /**
  21959. * @ngdoc object
  21960. * @name ui.grid.treeBase.api:PublicApi
  21961. *
  21962. * @description Public Api for treeBase feature
  21963. */
  21964. var publicApi = {
  21965. events: {
  21966. treeBase: {
  21967. /**
  21968. * @ngdoc event
  21969. * @eventOf ui.grid.treeBase.api:PublicApi
  21970. * @name rowExpanded
  21971. * @description raised whenever a row is expanded. If you are dynamically
  21972. * rendering your tree you can listen to this event, and then retrieve
  21973. * the children of this row and load them into the grid data.
  21974. *
  21975. * When the data is loaded the grid will automatically refresh to show these new rows
  21976. *
  21977. * <pre>
  21978. * gridApi.treeBase.on.rowExpanded(scope,function(row){})
  21979. * </pre>
  21980. * @param {gridRow} row the row that was expanded. You can also
  21981. * retrieve the grid from this row with row.grid
  21982. */
  21983. rowExpanded: {},
  21984. /**
  21985. * @ngdoc event
  21986. * @eventOf ui.grid.treeBase.api:PublicApi
  21987. * @name rowCollapsed
  21988. * @description raised whenever a row is collapsed. Doesn't really have
  21989. * a purpose at the moment, included for symmetry
  21990. *
  21991. * <pre>
  21992. * gridApi.treeBase.on.rowCollapsed(scope,function(row){})
  21993. * </pre>
  21994. * @param {gridRow} row the row that was collapsed. You can also
  21995. * retrieve the grid from this row with row.grid
  21996. */
  21997. rowCollapsed: {}
  21998. }
  21999. },
  22000. methods: {
  22001. treeBase: {
  22002. /**
  22003. * @ngdoc function
  22004. * @name expandAllRows
  22005. * @methodOf ui.grid.treeBase.api:PublicApi
  22006. * @description Expands all tree rows
  22007. */
  22008. expandAllRows: function () {
  22009. service.expandAllRows(grid);
  22010. },
  22011. /**
  22012. * @ngdoc function
  22013. * @name collapseAllRows
  22014. * @methodOf ui.grid.treeBase.api:PublicApi
  22015. * @description collapse all tree rows
  22016. */
  22017. collapseAllRows: function () {
  22018. service.collapseAllRows(grid);
  22019. },
  22020. /**
  22021. * @ngdoc function
  22022. * @name toggleRowTreeState
  22023. * @methodOf ui.grid.treeBase.api:PublicApi
  22024. * @description call expand if the row is collapsed, collapse if it is expanded
  22025. * @param {gridRow} row the row you wish to toggle
  22026. */
  22027. toggleRowTreeState: function (row) {
  22028. service.toggleRowTreeState(grid, row);
  22029. },
  22030. /**
  22031. * @ngdoc function
  22032. * @name expandRow
  22033. * @methodOf ui.grid.treeBase.api:PublicApi
  22034. * @description expand the immediate children of the specified row
  22035. * @param {gridRow} row the row you wish to expand
  22036. */
  22037. expandRow: function (row) {
  22038. service.expandRow(grid, row);
  22039. },
  22040. /**
  22041. * @ngdoc function
  22042. * @name expandRowChildren
  22043. * @methodOf ui.grid.treeBase.api:PublicApi
  22044. * @description expand all children of the specified row
  22045. * @param {gridRow} row the row you wish to expand
  22046. */
  22047. expandRowChildren: function (row) {
  22048. service.expandRowChildren(grid, row);
  22049. },
  22050. /**
  22051. * @ngdoc function
  22052. * @name collapseRow
  22053. * @methodOf ui.grid.treeBase.api:PublicApi
  22054. * @description collapse the specified row. When
  22055. * you expand the row again, all grandchildren will retain their state
  22056. * @param {gridRow} row the row you wish to collapse
  22057. */
  22058. collapseRow: function ( row ) {
  22059. service.collapseRow(grid, row);
  22060. },
  22061. /**
  22062. * @ngdoc function
  22063. * @name collapseRowChildren
  22064. * @methodOf ui.grid.treeBase.api:PublicApi
  22065. * @description collapse all children of the specified row. When
  22066. * you expand the row again, all grandchildren will be collapsed
  22067. * @param {gridRow} row the row you wish to collapse children for
  22068. */
  22069. collapseRowChildren: function ( row ) {
  22070. service.collapseRowChildren(grid, row);
  22071. },
  22072. /**
  22073. * @ngdoc function
  22074. * @name getTreeState
  22075. * @methodOf ui.grid.treeBase.api:PublicApi
  22076. * @description Get the tree state for this grid,
  22077. * used by the saveState feature
  22078. * Returned treeState as an object
  22079. * `{ expandedState: { uid: 'expanded', uid: 'collapsed' } }`
  22080. * where expandedState is a hash of row uid and the current expanded state
  22081. *
  22082. * @returns {object} tree state
  22083. *
  22084. * TODO - this needs work - we need an identifier that persists across instantiations,
  22085. * not uid. This really means we need a row identity defined, but that won't work for
  22086. * grouping. Perhaps this needs to be moved up to treeView and grouping, rather than
  22087. * being in base.
  22088. */
  22089. getTreeExpandedState: function () {
  22090. return { expandedState: service.getTreeState(grid) };
  22091. },
  22092. /**
  22093. * @ngdoc function
  22094. * @name setTreeState
  22095. * @methodOf ui.grid.treeBase.api:PublicApi
  22096. * @description Set the expanded states of the tree
  22097. * @param {object} config the config you want to apply, in the format
  22098. * provided by getTreeState
  22099. */
  22100. setTreeState: function ( config ) {
  22101. service.setTreeState( grid, config );
  22102. },
  22103. /**
  22104. * @ngdoc function
  22105. * @name getRowChildren
  22106. * @methodOf ui.grid.treeBase.api:PublicApi
  22107. * @description Get the children of the specified row
  22108. * @param {GridRow} row the row you want the children of
  22109. * @returns {Array} array of children of this row, the children
  22110. * are all gridRows
  22111. */
  22112. getRowChildren: function ( row ){
  22113. return row.treeNode.children.map( function( childNode ){
  22114. return childNode.row;
  22115. });
  22116. }
  22117. }
  22118. }
  22119. };
  22120. grid.api.registerEventsFromObject(publicApi.events);
  22121. grid.api.registerMethodsFromObject(publicApi.methods);
  22122. },
  22123. defaultGridOptions: function (gridOptions) {
  22124. //default option to true unless it was explicitly set to false
  22125. /**
  22126. * @ngdoc object
  22127. * @name ui.grid.treeBase.api:GridOptions
  22128. *
  22129. * @description GridOptions for treeBase feature, these are available to be
  22130. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  22131. */
  22132. /**
  22133. * @ngdoc object
  22134. * @name treeRowHeaderBaseWidth
  22135. * @propertyOf ui.grid.treeBase.api:GridOptions
  22136. * @description Base width of the tree header, provides for a single level of tree. This
  22137. * is incremented by `treeIndent` for each extra level
  22138. * <br/>Defaults to 30
  22139. */
  22140. gridOptions.treeRowHeaderBaseWidth = gridOptions.treeRowHeaderBaseWidth || 30;
  22141. /**
  22142. * @ngdoc object
  22143. * @name treeIndent
  22144. * @propertyOf ui.grid.treeBase.api:GridOptions
  22145. * @description Number of pixels of indent for the icon at each tree level, wider indents are visually more pleasing,
  22146. * but will make the tree row header wider
  22147. * <br/>Defaults to 10
  22148. */
  22149. gridOptions.treeIndent = gridOptions.treeIndent || 10;
  22150. /**
  22151. * @ngdoc object
  22152. * @name showTreeRowHeader
  22153. * @propertyOf ui.grid.treeBase.api:GridOptions
  22154. * @description If set to false, don't create the row header. Youll need to programatically control the expand
  22155. * states
  22156. * <br/>Defaults to true
  22157. */
  22158. gridOptions.showTreeRowHeader = gridOptions.showTreeRowHeader !== false;
  22159. /**
  22160. * @ngdoc object
  22161. * @name showTreeExpandNoChildren
  22162. * @propertyOf ui.grid.treeBase.api:GridOptions
  22163. * @description If set to true, show the expand/collapse button even if there are no
  22164. * children of a node. You'd use this if you're planning to dynamically load the children
  22165. *
  22166. * <br/>Defaults to true, grouping overrides to false
  22167. */
  22168. gridOptions.showTreeExpandNoChildren = gridOptions.showTreeExpandNoChildren !== false;
  22169. /**
  22170. * @ngdoc object
  22171. * @name treeRowHeaderAlwaysVisible
  22172. * @propertyOf ui.grid.treeBase.api:GridOptions
  22173. * @description If set to true, row header even if there are no tree nodes
  22174. *
  22175. * <br/>Defaults to true
  22176. */
  22177. gridOptions.treeRowHeaderAlwaysVisible = gridOptions.treeRowHeaderAlwaysVisible !== false;
  22178. /**
  22179. * @ngdoc object
  22180. * @name treeCustomAggregations
  22181. * @propertyOf ui.grid.treeBase.api:GridOptions
  22182. * @description Define custom aggregation functions. The properties of this object will be
  22183. * aggregation types available for use on columnDef with {@link ui.grid.treeBase.api:ColumnDef treeAggregationType} or through the column menu.
  22184. * If a function defined here uses the same name as one of the native aggregations, this one will take precedence.
  22185. * The object format is:
  22186. *
  22187. * <pre>
  22188. * {
  22189. * aggregationName: {
  22190. * label: (optional) string,
  22191. * aggregationFn: function( aggregation, fieldValue, numValue, row ){...},
  22192. * finalizerFn: (optional) function( aggregation ){...}
  22193. * },
  22194. * mean: {
  22195. * label: 'mean',
  22196. * aggregationFn: function( aggregation, fieldValue, numValue ){
  22197. * aggregation.count = (aggregation.count || 1) + 1;
  22198. * aggregation.sum = (aggregation.sum || 0) + numValue;
  22199. * },
  22200. * finalizerFn: function( aggregation ){
  22201. * aggregation.value = aggregation.sum / aggregation.count
  22202. * }
  22203. * }
  22204. * }
  22205. * </pre>
  22206. *
  22207. * <br/>The `finalizerFn` may be used to manipulate the value before rendering, or to
  22208. * apply a custom rendered value. If `aggregation.rendered` is left undefined, the value will be
  22209. * rendered. Note that the native aggregation functions use an `finalizerFn` to concatenate
  22210. * the label and the value.
  22211. *
  22212. * <br/>Defaults to {}
  22213. */
  22214. gridOptions.treeCustomAggregations = gridOptions.treeCustomAggregations || {};
  22215. },
  22216. /**
  22217. * @ngdoc function
  22218. * @name treeBaseColumnBuilder
  22219. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22220. * @description Sets the tree defaults based on the columnDefs
  22221. *
  22222. * @param {object} colDef columnDef we're basing on
  22223. * @param {GridCol} col the column we're to update
  22224. * @param {object} gridOptions the options we should use
  22225. * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved
  22226. */
  22227. treeBaseColumnBuilder: function (colDef, col, gridOptions) {
  22228. /**
  22229. * @ngdoc object
  22230. * @name customTreeAggregationFn
  22231. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22232. * @description A custom function that aggregates rows into some form of
  22233. * total. Aggregations run row-by-row, the function needs to be capable of
  22234. * creating a running total.
  22235. *
  22236. * The function will be provided the aggregation item (in which you can store running
  22237. * totals), the row value that is to be aggregated, and that same row value converted to
  22238. * a number (most aggregations work on numbers)
  22239. * @example
  22240. * <pre>
  22241. * customTreeAggregationFn = function ( aggregation, fieldValue, numValue, row ){
  22242. * // calculates the average of the squares of the values
  22243. * if ( typeof(aggregation.count) === 'undefined' ){
  22244. * aggregation.count = 0;
  22245. * }
  22246. * aggregation.count++;
  22247. *
  22248. * if ( !isNaN(numValue) ){
  22249. * if ( typeof(aggregation.total) === 'undefined' ){
  22250. * aggregation.total = 0;
  22251. * }
  22252. * aggregation.total = aggregation.total + numValue * numValue;
  22253. * }
  22254. *
  22255. * aggregation.value = aggregation.total / aggregation.count;
  22256. * }
  22257. * </pre>
  22258. * <br/>Defaults to undefined. May be overwritten by treeAggregationType, the two options should not be used together.
  22259. */
  22260. if ( typeof(colDef.customTreeAggregationFn) !== 'undefined' ){
  22261. col.treeAggregationFn = colDef.customTreeAggregationFn;
  22262. }
  22263. /**
  22264. * @ngdoc object
  22265. * @name treeAggregationType
  22266. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22267. * @description Use one of the native or grid-level aggregation methods for calculating aggregations on this column.
  22268. * Native method are in the constants file and include: SUM, COUNT, MIN, MAX, AVG. This may also be the property the
  22269. * name of an aggregation function defined with {@link ui.grid.treeBase.api:GridOptions treeCustomAggregations}.
  22270. *
  22271. * <pre>
  22272. * treeAggregationType = uiGridTreeBaseConstants.aggregation.SUM,
  22273. * }
  22274. * </pre>
  22275. *
  22276. * If you are using aggregations you should either:
  22277. *
  22278. * - also use grouping, in which case the aggregations are displayed in the group header, OR
  22279. * - use treeView, in which case you can set `treeAggregationUpdateEntity: true` in the colDef, and
  22280. * treeBase will store the aggregation information in the entity, or you can set `treeAggregationUpdateEntity: false`
  22281. * in the colDef, and you need to manual retrieve the calculated aggregations from the row.treeNode.aggregations
  22282. *
  22283. * <br/>Takes precendence over a treeAggregationFn, the two options should not be used together.
  22284. * <br/>Defaults to undefined.
  22285. */
  22286. if ( typeof(colDef.treeAggregationType) !== 'undefined' ){
  22287. col.treeAggregation = { type: colDef.treeAggregationType };
  22288. if ( typeof(gridOptions.treeCustomAggregations[colDef.treeAggregationType]) !== 'undefined' ){
  22289. col.treeAggregationFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].aggregationFn;
  22290. col.treeAggregationFinalizerFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].finalizerFn;
  22291. col.treeAggregation.label = gridOptions.treeCustomAggregations[colDef.treeAggregationType].label;
  22292. } else if ( typeof(service.nativeAggregations()[colDef.treeAggregationType]) !== 'undefined' ){
  22293. col.treeAggregationFn = service.nativeAggregations()[colDef.treeAggregationType].aggregationFn;
  22294. col.treeAggregation.label = service.nativeAggregations()[colDef.treeAggregationType].label;
  22295. }
  22296. }
  22297. /**
  22298. * @ngdoc object
  22299. * @name treeAggregationLabel
  22300. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22301. * @description A custom label to use for this aggregation. If provided we don't use native i18n.
  22302. */
  22303. if ( typeof(colDef.treeAggregationLabel) !== 'undefined' ){
  22304. if (typeof(col.treeAggregation) === 'undefined' ){
  22305. col.treeAggregation = {};
  22306. }
  22307. col.treeAggregation.label = colDef.treeAggregationLabel;
  22308. }
  22309. /**
  22310. * @ngdoc object
  22311. * @name treeAggregationUpdateEntity
  22312. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22313. * @description Store calculated aggregations into the entity, allowing them
  22314. * to be displayed in the grid using a standard cellTemplate. This defaults to true,
  22315. * if you are using grouping then you shouldn't set it to false, as then the aggregations won't
  22316. * display.
  22317. *
  22318. * If you are using treeView in most cases you'll want to set this to true. This will result in
  22319. * getCellValue returning the aggregation rather than whatever was stored in the cell attribute on
  22320. * the entity. If you want to render the underlying entity value (and do something else with the aggregation)
  22321. * then you could use a custom cellTemplate to display `row.entity.myAttribute`, rather than using getCellValue.
  22322. *
  22323. * <br/>Defaults to true
  22324. *
  22325. * @example
  22326. * <pre>
  22327. * gridOptions.columns = [{
  22328. * name: 'myCol',
  22329. * treeAggregation: { type: uiGridTreeBaseConstants.aggregation.SUM },
  22330. * treeAggregationUpdateEntity: true
  22331. * cellTemplate: '<div>{{row.entity.myCol + " " + row.treeNode.aggregations[0].rendered}}</div>'
  22332. * }];
  22333. * </pre>
  22334. */
  22335. col.treeAggregationUpdateEntity = colDef.treeAggregationUpdateEntity !== false;
  22336. /**
  22337. * @ngdoc object
  22338. * @name customTreeAggregationFinalizerFn
  22339. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22340. * @description A custom function that populates aggregation.rendered, this is called when
  22341. * a particular aggregation has been fully calculated, and we want to render the value.
  22342. *
  22343. * With the native aggregation options we just concatenate `aggregation.label` and
  22344. * `aggregation.value`, but if you wanted to apply a filter or otherwise manipulate the label
  22345. * or the value, you can do so with this function. This function will be called after the
  22346. * the default `finalizerFn`.
  22347. *
  22348. * @example
  22349. * <pre>
  22350. * customTreeAggregationFinalizerFn = function ( aggregation ){
  22351. * aggregation.rendered = aggregation.label + aggregation.value / 100 + '%';
  22352. * }
  22353. * </pre>
  22354. * <br/>Defaults to undefined.
  22355. */
  22356. if ( typeof(col.customTreeAggregationFinalizerFn) === 'undefined' ){
  22357. col.customTreeAggregationFinalizerFn = colDef.customTreeAggregationFinalizerFn;
  22358. }
  22359. },
  22360. /**
  22361. * @ngdoc function
  22362. * @name createRowHeader
  22363. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22364. * @description Create the rowHeader. If treeRowHeaderAlwaysVisible then
  22365. * set it to visible, otherwise set it to invisible
  22366. *
  22367. * @param {Grid} grid grid object
  22368. */
  22369. createRowHeader: function( grid ){
  22370. var rowHeaderColumnDef = {
  22371. name: uiGridTreeBaseConstants.rowHeaderColName,
  22372. displayName: '',
  22373. width: grid.options.treeRowHeaderBaseWidth,
  22374. minWidth: 10,
  22375. cellTemplate: 'ui-grid/treeBaseRowHeader',
  22376. headerCellTemplate: 'ui-grid/treeBaseHeaderCell',
  22377. enableColumnResizing: false,
  22378. enableColumnMenu: false,
  22379. exporterSuppressExport: true,
  22380. allowCellFocus: true
  22381. };
  22382. rowHeaderColumnDef.visible = grid.options.treeRowHeaderAlwaysVisible;
  22383. grid.addRowHeaderColumn( rowHeaderColumnDef );
  22384. },
  22385. /**
  22386. * @ngdoc function
  22387. * @name expandAllRows
  22388. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22389. * @description Expands all nodes in the tree
  22390. *
  22391. * @param {Grid} grid grid object
  22392. */
  22393. expandAllRows: function (grid) {
  22394. grid.treeBase.tree.forEach( function( node ) {
  22395. service.setAllNodes( grid, node, uiGridTreeBaseConstants.EXPANDED);
  22396. });
  22397. grid.treeBase.expandAll = true;
  22398. grid.queueGridRefresh();
  22399. },
  22400. /**
  22401. * @ngdoc function
  22402. * @name collapseAllRows
  22403. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22404. * @description Collapses all nodes in the tree
  22405. *
  22406. * @param {Grid} grid grid object
  22407. */
  22408. collapseAllRows: function (grid) {
  22409. grid.treeBase.tree.forEach( function( node ) {
  22410. service.setAllNodes( grid, node, uiGridTreeBaseConstants.COLLAPSED);
  22411. });
  22412. grid.treeBase.expandAll = false;
  22413. grid.queueGridRefresh();
  22414. },
  22415. /**
  22416. * @ngdoc function
  22417. * @name setAllNodes
  22418. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22419. * @description Works through a subset of grid.treeBase.rowExpandedStates, setting
  22420. * all child nodes (and their descendents) of the provided node to the given state.
  22421. *
  22422. * Calls itself recursively on all nodes so as to achieve this.
  22423. *
  22424. * @param {Grid} grid the grid we're operating on (so we can raise events)
  22425. * @param {object} treeNode a node in the tree that we want to update
  22426. * @param {string} targetState the state we want to set it to
  22427. */
  22428. setAllNodes: function (grid, treeNode, targetState) {
  22429. if ( typeof(treeNode.state) !== 'undefined' && treeNode.state !== targetState ){
  22430. treeNode.state = targetState;
  22431. if ( targetState === uiGridTreeBaseConstants.EXPANDED ){
  22432. grid.api.treeBase.raise.rowExpanded(treeNode.row);
  22433. } else {
  22434. grid.api.treeBase.raise.rowCollapsed(treeNode.row);
  22435. }
  22436. }
  22437. // set all child nodes
  22438. if ( treeNode.children ){
  22439. treeNode.children.forEach(function( childNode ){
  22440. service.setAllNodes(grid, childNode, targetState);
  22441. });
  22442. }
  22443. },
  22444. /**
  22445. * @ngdoc function
  22446. * @name toggleRowTreeState
  22447. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22448. * @description Toggles the expand or collapse state of this grouped row, if
  22449. * it's a parent row
  22450. *
  22451. * @param {Grid} grid grid object
  22452. * @param {GridRow} row the row we want to toggle
  22453. */
  22454. toggleRowTreeState: function ( grid, row ){
  22455. if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
  22456. return;
  22457. }
  22458. if (row.treeNode.state === uiGridTreeBaseConstants.EXPANDED){
  22459. service.collapseRow(grid, row);
  22460. } else {
  22461. service.expandRow(grid, row);
  22462. }
  22463. grid.queueGridRefresh();
  22464. },
  22465. /**
  22466. * @ngdoc function
  22467. * @name expandRow
  22468. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22469. * @description Expands this specific row, showing only immediate children.
  22470. *
  22471. * @param {Grid} grid grid object
  22472. * @param {GridRow} row the row we want to expand
  22473. */
  22474. expandRow: function ( grid, row ){
  22475. if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
  22476. return;
  22477. }
  22478. if ( row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED ){
  22479. row.treeNode.state = uiGridTreeBaseConstants.EXPANDED;
  22480. grid.api.treeBase.raise.rowExpanded(row);
  22481. grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
  22482. grid.queueGridRefresh();
  22483. }
  22484. },
  22485. /**
  22486. * @ngdoc function
  22487. * @name expandRowChildren
  22488. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22489. * @description Expands this specific row, showing all children.
  22490. *
  22491. * @param {Grid} grid grid object
  22492. * @param {GridRow} row the row we want to expand
  22493. */
  22494. expandRowChildren: function ( grid, row ){
  22495. if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
  22496. return;
  22497. }
  22498. service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.EXPANDED);
  22499. grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
  22500. grid.queueGridRefresh();
  22501. },
  22502. /**
  22503. * @ngdoc function
  22504. * @name collapseRow
  22505. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22506. * @description Collapses this specific row
  22507. *
  22508. * @param {Grid} grid grid object
  22509. * @param {GridRow} row the row we want to collapse
  22510. */
  22511. collapseRow: function( grid, row ){
  22512. if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
  22513. return;
  22514. }
  22515. if ( row.treeNode.state !== uiGridTreeBaseConstants.COLLAPSED ){
  22516. row.treeNode.state = uiGridTreeBaseConstants.COLLAPSED;
  22517. grid.treeBase.expandAll = false;
  22518. grid.api.treeBase.raise.rowCollapsed(row);
  22519. grid.queueGridRefresh();
  22520. }
  22521. },
  22522. /**
  22523. * @ngdoc function
  22524. * @name collapseRowChildren
  22525. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22526. * @description Collapses this specific row and all children
  22527. *
  22528. * @param {Grid} grid grid object
  22529. * @param {GridRow} row the row we want to collapse
  22530. */
  22531. collapseRowChildren: function( grid, row ){
  22532. if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
  22533. return;
  22534. }
  22535. service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.COLLAPSED);
  22536. grid.treeBase.expandAll = false;
  22537. grid.queueGridRefresh();
  22538. },
  22539. /**
  22540. * @ngdoc function
  22541. * @name allExpanded
  22542. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22543. * @description Returns true if all rows are expanded, false
  22544. * if they're not. Walks the tree to determine this. Used
  22545. * to set the expandAll state.
  22546. *
  22547. * If the node has no children, then return true (it's immaterial
  22548. * whether it is expanded). If the node has children, then return
  22549. * false if this node is collapsed, or if any child node is not all expanded
  22550. *
  22551. * @param {object} tree the grid to check
  22552. * @returns {boolean} whether or not the tree is all expanded
  22553. */
  22554. allExpanded: function( tree ){
  22555. var allExpanded = true;
  22556. tree.forEach( function( node ){
  22557. if ( !service.allExpandedInternal( node ) ){
  22558. allExpanded = false;
  22559. }
  22560. });
  22561. return allExpanded;
  22562. },
  22563. allExpandedInternal: function( treeNode ){
  22564. if ( treeNode.children && treeNode.children.length > 0 ){
  22565. if ( treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){
  22566. return false;
  22567. }
  22568. var allExpanded = true;
  22569. treeNode.children.forEach( function( node ){
  22570. if ( !service.allExpandedInternal( node ) ){
  22571. allExpanded = false;
  22572. }
  22573. });
  22574. return allExpanded;
  22575. } else {
  22576. return true;
  22577. }
  22578. },
  22579. /**
  22580. * @ngdoc function
  22581. * @name treeRows
  22582. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22583. * @description The rowProcessor that adds the nodes to the tree, and sets the visible
  22584. * state of each row based on it's parent state
  22585. *
  22586. * Assumes it is always called after the sorting processor, and the grouping processor if there is one.
  22587. * Performs any tree sorts itself after having built the tree
  22588. *
  22589. * Processes all the rows in order, setting the group level based on the $$treeLevel in the associated
  22590. * entity, and setting the visible state based on the parent's state.
  22591. *
  22592. * Calculates the deepest level of tree whilst it goes, and updates that so that the header column can be correctly
  22593. * sized.
  22594. *
  22595. * Aggregates if necessary along the way.
  22596. *
  22597. * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor
  22598. * @returns {array} the updated rows
  22599. */
  22600. treeRows: function( renderableRows ) {
  22601. if (renderableRows.length === 0){
  22602. return renderableRows;
  22603. }
  22604. var grid = this;
  22605. var currentLevel = 0;
  22606. var currentState = uiGridTreeBaseConstants.EXPANDED;
  22607. var parents = [];
  22608. grid.treeBase.tree = service.createTree( grid, renderableRows );
  22609. service.updateRowHeaderWidth( grid );
  22610. service.sortTree( grid );
  22611. service.fixFilter( grid );
  22612. return service.renderTree( grid.treeBase.tree );
  22613. },
  22614. /**
  22615. * @ngdoc function
  22616. * @name createOrUpdateRowHeaderWidth
  22617. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22618. * @description Calculates the rowHeader width.
  22619. *
  22620. * If rowHeader is always present, updates the width.
  22621. *
  22622. * If rowHeader is only sometimes present (`treeRowHeaderAlwaysVisible: false`), determines whether there
  22623. * should be one, then creates or removes it as appropriate, with the created rowHeader having the
  22624. * right width.
  22625. *
  22626. * If there's never a rowHeader then never creates one: `showTreeRowHeader: false`
  22627. *
  22628. * @param {Grid} grid the grid we want to set the row header on
  22629. */
  22630. updateRowHeaderWidth: function( grid ){
  22631. var rowHeader = grid.getColumn(uiGridTreeBaseConstants.rowHeaderColName);
  22632. var newWidth = grid.options.treeRowHeaderBaseWidth + grid.options.treeIndent * Math.max(grid.treeBase.numberLevels - 1, 0);
  22633. if ( rowHeader && newWidth !== rowHeader.width ){
  22634. rowHeader.width = newWidth;
  22635. grid.queueRefresh();
  22636. }
  22637. var newVisibility = true;
  22638. if ( grid.options.showTreeRowHeader === false ){
  22639. newVisibility = false;
  22640. }
  22641. if ( grid.options.treeRowHeaderAlwaysVisible === false && grid.treeBase.numberLevels <= 0 ){
  22642. newVisibility = false;
  22643. }
  22644. if ( rowHeader.visible !== newVisibility ) {
  22645. rowHeader.visible = newVisibility;
  22646. rowHeader.colDef.visible = newVisibility;
  22647. grid.queueGridRefresh();
  22648. }
  22649. },
  22650. /**
  22651. * @ngdoc function
  22652. * @name renderTree
  22653. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22654. * @description Creates an array of rows based on the tree, exporting only
  22655. * the visible nodes and leaves
  22656. *
  22657. * @param {array} nodeList the list of nodes - can be grid.treeBase.tree, or can be node.children when
  22658. * we're calling recursively
  22659. * @returns {array} renderable rows
  22660. */
  22661. renderTree: function( nodeList ){
  22662. var renderableRows = [];
  22663. nodeList.forEach( function ( node ){
  22664. if ( node.row.visible ){
  22665. renderableRows.push( node.row );
  22666. }
  22667. if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){
  22668. renderableRows = renderableRows.concat( service.renderTree( node.children ) );
  22669. }
  22670. });
  22671. return renderableRows;
  22672. },
  22673. /**
  22674. * @ngdoc function
  22675. * @name createTree
  22676. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22677. * @description Creates a tree from the renderableRows
  22678. *
  22679. * @param {Grid} grid the grid
  22680. * @param {array} renderableRows the rows we want to create a tree from
  22681. * @returns {object} the tree we've build
  22682. */
  22683. createTree: function( grid, renderableRows ) {
  22684. var currentLevel = -1;
  22685. var parents = [];
  22686. var currentState;
  22687. grid.treeBase.tree = [];
  22688. grid.treeBase.numberLevels = 0;
  22689. var aggregations = service.getAggregations( grid );
  22690. var createNode = function( row ){
  22691. if ( typeof(row.entity.$$treeLevel) !== 'undefined' && row.treeLevel !== row.entity.$$treeLevel ){
  22692. row.treeLevel = row.entity.$$treeLevel;
  22693. }
  22694. if ( row.treeLevel <= currentLevel ){
  22695. // pop any levels that aren't parents of this level, formatting the aggregation at the same time
  22696. while ( row.treeLevel <= currentLevel ){
  22697. var lastParent = parents.pop();
  22698. service.finaliseAggregations( lastParent );
  22699. currentLevel--;
  22700. }
  22701. // reset our current state based on the new parent, set to expanded if this is a level 0 node
  22702. if ( parents.length > 0 ){
  22703. currentState = service.setCurrentState(parents);
  22704. } else {
  22705. currentState = uiGridTreeBaseConstants.EXPANDED;
  22706. }
  22707. }
  22708. // aggregate if this is a leaf node
  22709. if ( ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ) && row.visible ){
  22710. service.aggregate( grid, row, parents );
  22711. }
  22712. // add this node to the tree
  22713. service.addOrUseNode(grid, row, parents, aggregations);
  22714. if ( typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0 ){
  22715. parents.push(row);
  22716. currentLevel++;
  22717. currentState = service.setCurrentState(parents);
  22718. }
  22719. // update the tree number of levels, so we can set header width if we need to
  22720. if ( grid.treeBase.numberLevels < row.treeLevel + 1){
  22721. grid.treeBase.numberLevels = row.treeLevel + 1;
  22722. }
  22723. };
  22724. renderableRows.forEach( createNode );
  22725. // finalise remaining aggregations
  22726. while ( parents.length > 0 ){
  22727. var lastParent = parents.pop();
  22728. service.finaliseAggregations( lastParent );
  22729. }
  22730. return grid.treeBase.tree;
  22731. },
  22732. /**
  22733. * @ngdoc function
  22734. * @name addOrUseNode
  22735. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22736. * @description Creates a tree node for this row. If this row already has a treeNode
  22737. * recorded against it, preserves the state, but otherwise overwrites the data.
  22738. *
  22739. * @param {grid} grid the grid we're operating on
  22740. * @param {gridRow} row the row we want to set
  22741. * @param {array} parents an array of the parents this row should have
  22742. * @param {array} aggregationBase empty aggregation information
  22743. * @returns {undefined} updates the parents array, updates the row to have a treeNode, and updates the
  22744. * grid.treeBase.tree
  22745. */
  22746. addOrUseNode: function( grid, row, parents, aggregationBase ){
  22747. var newAggregations = [];
  22748. aggregationBase.forEach( function(aggregation){
  22749. newAggregations.push(service.buildAggregationObject(aggregation.col));
  22750. });
  22751. var newNode = { state: uiGridTreeBaseConstants.COLLAPSED, row: row, parentRow: null, aggregations: newAggregations, children: [] };
  22752. if ( row.treeNode ){
  22753. newNode.state = row.treeNode.state;
  22754. }
  22755. if ( parents.length > 0 ){
  22756. newNode.parentRow = parents[parents.length - 1];
  22757. }
  22758. row.treeNode = newNode;
  22759. if ( parents.length === 0 ){
  22760. grid.treeBase.tree.push( newNode );
  22761. } else {
  22762. parents[parents.length - 1].treeNode.children.push( newNode );
  22763. }
  22764. },
  22765. /**
  22766. * @ngdoc function
  22767. * @name setCurrentState
  22768. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22769. * @description Looks at the parents array to determine our current state.
  22770. * If any node in the hierarchy is collapsed, then return collapsed, otherwise return
  22771. * expanded.
  22772. *
  22773. * @param {array} parents an array of the parents this row should have
  22774. * @returns {string} the state we should be setting to any nodes we see
  22775. */
  22776. setCurrentState: function( parents ){
  22777. var currentState = uiGridTreeBaseConstants.EXPANDED;
  22778. parents.forEach( function(parent){
  22779. if ( parent.treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){
  22780. currentState = uiGridTreeBaseConstants.COLLAPSED;
  22781. }
  22782. });
  22783. return currentState;
  22784. },
  22785. /**
  22786. * @ngdoc function
  22787. * @name sortTree
  22788. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22789. * @description Performs a recursive sort on the tree nodes, sorting the
  22790. * children of each node and putting them back into the children array.
  22791. *
  22792. * Before doing this it turns back on all the sortIgnore - things that were previously
  22793. * ignored we process now. Since we're sorting within the nodes, presumably anything
  22794. * that was already sorted is how we derived the nodes, we can keep those sorts too.
  22795. *
  22796. * We only sort tree nodes that are expanded - no point in wasting effort sorting collapsed
  22797. * nodes
  22798. *
  22799. * @param {Grid} grid the grid to get the aggregation information from
  22800. * @returns {array} the aggregation information
  22801. */
  22802. sortTree: function( grid ){
  22803. grid.columns.forEach( function( column ) {
  22804. if ( column.sort && column.sort.ignoreSort ){
  22805. delete column.sort.ignoreSort;
  22806. }
  22807. });
  22808. grid.treeBase.tree = service.sortInternal( grid, grid.treeBase.tree );
  22809. },
  22810. sortInternal: function( grid, treeList ){
  22811. var rows = treeList.map( function( node ){
  22812. return node.row;
  22813. });
  22814. rows = rowSorter.sort( grid, rows, grid.columns );
  22815. var treeNodes = rows.map( function( row ){
  22816. return row.treeNode;
  22817. });
  22818. treeNodes.forEach( function( node ){
  22819. if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){
  22820. node.children = service.sortInternal( grid, node.children );
  22821. }
  22822. });
  22823. return treeNodes;
  22824. },
  22825. /**
  22826. * @ngdoc function
  22827. * @name fixFilter
  22828. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22829. * @description After filtering has run, we need to go back through the tree
  22830. * and make sure the parent rows are always visible if any of the child rows
  22831. * are visible (filtering may make a child visible, but the parent may not
  22832. * match the filter criteria)
  22833. *
  22834. * This has a risk of being computationally expensive, we do it by walking
  22835. * the tree and remembering whether there are any invisible nodes on the
  22836. * way down.
  22837. *
  22838. * @param {Grid} grid the grid to fix filters on
  22839. */
  22840. fixFilter: function( grid ){
  22841. var parentsVisible;
  22842. grid.treeBase.tree.forEach( function( node ){
  22843. if ( node.children && node.children.length > 0 ){
  22844. parentsVisible = node.row.visible;
  22845. service.fixFilterInternal( node.children, parentsVisible );
  22846. }
  22847. });
  22848. },
  22849. fixFilterInternal: function( nodes, parentsVisible) {
  22850. nodes.forEach( function( node ){
  22851. if ( node.row.visible && !parentsVisible ){
  22852. service.setParentsVisible( node );
  22853. parentsVisible = true;
  22854. }
  22855. if ( node.children && node.children.length > 0 ){
  22856. if ( service.fixFilterInternal( node.children, ( parentsVisible && node.row.visible ) ) ) {
  22857. parentsVisible = true;
  22858. }
  22859. }
  22860. });
  22861. return parentsVisible;
  22862. },
  22863. setParentsVisible: function( node ){
  22864. while ( node.parentRow ){
  22865. node.parentRow.visible = true;
  22866. node = node.parentRow.treeNode;
  22867. }
  22868. },
  22869. /**
  22870. * @ngdoc function
  22871. * @name buildAggregationObject
  22872. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22873. * @description Build the object which is stored on the column for holding meta-data about the aggregation.
  22874. * This method should only be called with columns which have an aggregation.
  22875. *
  22876. * @param {Column} the column which this object relates to
  22877. * @returns {object} {col: Column object, label: string, type: string (optional)}
  22878. */
  22879. buildAggregationObject: function( column ){
  22880. var newAggregation = { col: column };
  22881. if ( column.treeAggregation && column.treeAggregation.type ){
  22882. newAggregation.type = column.treeAggregation.type;
  22883. }
  22884. if ( column.treeAggregation && column.treeAggregation.label ){
  22885. newAggregation.label = column.treeAggregation.label;
  22886. }
  22887. return newAggregation;
  22888. },
  22889. /**
  22890. * @ngdoc function
  22891. * @name getAggregations
  22892. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22893. * @description Looks through the grid columns to find those with aggregations,
  22894. * and collates the aggregation information into an array, returns that array
  22895. *
  22896. * @param {Grid} grid the grid to get the aggregation information from
  22897. * @returns {array} the aggregation information
  22898. */
  22899. getAggregations: function( grid ){
  22900. var aggregateArray = [];
  22901. grid.columns.forEach( function(column){
  22902. if ( typeof(column.treeAggregationFn) !== 'undefined' ){
  22903. aggregateArray.push( service.buildAggregationObject(column) );
  22904. if ( grid.options.showColumnFooter && typeof(column.colDef.aggregationType) === 'undefined' && column.treeAggregation ){
  22905. // Add aggregation object for footer
  22906. column.treeFooterAggregation = service.buildAggregationObject(column);
  22907. column.aggregationType = service.treeFooterAggregationType;
  22908. }
  22909. }
  22910. });
  22911. return aggregateArray;
  22912. },
  22913. /**
  22914. * @ngdoc function
  22915. * @name aggregate
  22916. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22917. * @description Accumulate the data from this row onto the aggregations for each parent
  22918. *
  22919. * Iterate over the parents, then iterate over the aggregations for each of those parents,
  22920. * and perform the aggregation for each individual aggregation
  22921. *
  22922. * @param {Grid} grid grid object
  22923. * @param {GridRow} row the row we want to set grouping visibility on
  22924. * @param {array} parents the parents that we would want to aggregate onto
  22925. */
  22926. aggregate: function( grid, row, parents ){
  22927. if ( parents.length === 0 && row.treeNode && row.treeNode.aggregations ){
  22928. row.treeNode.aggregations.forEach(function(aggregation){
  22929. // Calculate aggregations for footer even if there are no grouped rows
  22930. if ( typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ) {
  22931. var fieldValue = grid.getCellValue(row, aggregation.col);
  22932. var numValue = Number(fieldValue);
  22933. aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row);
  22934. }
  22935. });
  22936. }
  22937. parents.forEach( function( parent, index ){
  22938. if ( parent.treeNode.aggregations ){
  22939. parent.treeNode.aggregations.forEach( function( aggregation ){
  22940. var fieldValue = grid.getCellValue(row, aggregation.col);
  22941. var numValue = Number(fieldValue);
  22942. aggregation.col.treeAggregationFn(aggregation, fieldValue, numValue, row);
  22943. if ( index === 0 && typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ){
  22944. aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row);
  22945. }
  22946. });
  22947. }
  22948. });
  22949. },
  22950. // Aggregation routines - no doco needed as self evident
  22951. nativeAggregations: function() {
  22952. var nativeAggregations = {
  22953. count: {
  22954. label: i18nService.get().aggregation.count,
  22955. menuTitle: i18nService.get().grouping.aggregate_count,
  22956. aggregationFn: function (aggregation, fieldValue, numValue) {
  22957. if (typeof(aggregation.value) === 'undefined') {
  22958. aggregation.value = 1;
  22959. } else {
  22960. aggregation.value++;
  22961. }
  22962. }
  22963. },
  22964. sum: {
  22965. label: i18nService.get().aggregation.sum,
  22966. menuTitle: i18nService.get().grouping.aggregate_sum,
  22967. aggregationFn: function( aggregation, fieldValue, numValue ) {
  22968. if (!isNaN(numValue)) {
  22969. if (typeof(aggregation.value) === 'undefined') {
  22970. aggregation.value = numValue;
  22971. } else {
  22972. aggregation.value += numValue;
  22973. }
  22974. }
  22975. }
  22976. },
  22977. min: {
  22978. label: i18nService.get().aggregation.min,
  22979. menuTitle: i18nService.get().grouping.aggregate_min,
  22980. aggregationFn: function( aggregation, fieldValue, numValue ) {
  22981. if (typeof(aggregation.value) === 'undefined') {
  22982. aggregation.value = fieldValue;
  22983. } else {
  22984. if (typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue < aggregation.value || aggregation.value === null)) {
  22985. aggregation.value = fieldValue;
  22986. }
  22987. }
  22988. }
  22989. },
  22990. max: {
  22991. label: i18nService.get().aggregation.max,
  22992. menuTitle: i18nService.get().grouping.aggregate_max,
  22993. aggregationFn: function( aggregation, fieldValue, numValue ){
  22994. if ( typeof(aggregation.value) === 'undefined' ){
  22995. aggregation.value = fieldValue;
  22996. } else {
  22997. if ( typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue > aggregation.value || aggregation.value === null)){
  22998. aggregation.value = fieldValue;
  22999. }
  23000. }
  23001. }
  23002. },
  23003. avg: {
  23004. label: i18nService.get().aggregation.avg,
  23005. menuTitle: i18nService.get().grouping.aggregate_avg,
  23006. aggregationFn: function( aggregation, fieldValue, numValue ){
  23007. if ( typeof(aggregation.count) === 'undefined' ){
  23008. aggregation.count = 1;
  23009. } else {
  23010. aggregation.count++;
  23011. }
  23012. if ( isNaN(numValue) ){
  23013. return;
  23014. }
  23015. if ( typeof(aggregation.value) === 'undefined' || typeof(aggregation.sum) === 'undefined' ){
  23016. aggregation.value = numValue;
  23017. aggregation.sum = numValue;
  23018. } else {
  23019. aggregation.sum += numValue;
  23020. aggregation.value = aggregation.sum / aggregation.count;
  23021. }
  23022. }
  23023. }
  23024. };
  23025. return nativeAggregations;
  23026. },
  23027. /**
  23028. * @ngdoc function
  23029. * @name finaliseAggregation
  23030. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  23031. * @description Helper function used to finalize aggregation nodes and footer cells
  23032. *
  23033. * @param {gridRow} row the parent we're finalising
  23034. * @param {aggregation} the aggregation object manipulated by the aggregationFn
  23035. */
  23036. finaliseAggregation: function(row, aggregation){
  23037. if ( aggregation.col.treeAggregationUpdateEntity && typeof(row) !== 'undefined' && typeof(row.entity[ '$$' + aggregation.col.uid ]) !== 'undefined' ){
  23038. angular.extend( aggregation, row.entity[ '$$' + aggregation.col.uid ]);
  23039. }
  23040. if ( typeof(aggregation.col.treeAggregationFinalizerFn) === 'function' ){
  23041. aggregation.col.treeAggregationFinalizerFn( aggregation );
  23042. }
  23043. if ( typeof(aggregation.col.customTreeAggregationFinalizerFn) === 'function' ){
  23044. aggregation.col.customTreeAggregationFinalizerFn( aggregation );
  23045. }
  23046. if ( typeof(aggregation.rendered) === 'undefined' ){
  23047. aggregation.rendered = aggregation.label ? aggregation.label + aggregation.value : aggregation.value;
  23048. }
  23049. },
  23050. /**
  23051. * @ngdoc function
  23052. * @name finaliseAggregations
  23053. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  23054. * @description Format the data from the aggregation into the rendered text
  23055. * e.g. if we had label: 'sum: ' and value: 25, we'd create 'sum: 25'.
  23056. *
  23057. * As part of this we call any formatting callback routines we've been provided.
  23058. *
  23059. * We write our aggregation out to the row.entity if treeAggregationUpdateEntity is
  23060. * set on the column - we don't overwrite any information that's already there, we append
  23061. * to it so that grouping can have set the groupVal beforehand without us overwriting it.
  23062. *
  23063. * We need to copy the data from the row.entity first before we finalise the aggregation,
  23064. * we need that information for the finaliserFn
  23065. *
  23066. * @param {gridRow} row the parent we're finalising
  23067. */
  23068. finaliseAggregations: function( row ){
  23069. if ( typeof(row.treeNode.aggregations) === 'undefined' ){
  23070. return;
  23071. }
  23072. row.treeNode.aggregations.forEach( function( aggregation ) {
  23073. service.finaliseAggregation(row, aggregation);
  23074. if ( aggregation.col.treeAggregationUpdateEntity ){
  23075. var aggregationCopy = {};
  23076. angular.forEach( aggregation, function( value, key ){
  23077. if ( aggregation.hasOwnProperty(key) && key !== 'col' ){
  23078. aggregationCopy[key] = value;
  23079. }
  23080. });
  23081. row.entity[ '$$' + aggregation.col.uid ] = aggregationCopy;
  23082. }
  23083. });
  23084. },
  23085. /**
  23086. * @ngdoc function
  23087. * @name treeFooterAggregationType
  23088. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  23089. * @description Uses the tree aggregation functions and finalizers to set the
  23090. * column footer aggregations.
  23091. *
  23092. * @param {rows} visible rows. not used, but accepted to match signature of GridColumn.aggregationType
  23093. * @param {gridColumn} the column we are finalizing
  23094. */
  23095. treeFooterAggregationType: function( rows, column ) {
  23096. service.finaliseAggregation(undefined, column.treeFooterAggregation);
  23097. if ( typeof(column.treeFooterAggregation.value) === 'undefined' || column.treeFooterAggregation.rendered === null ){
  23098. // The was apparently no aggregation performed (perhaps this is a grouped column
  23099. return '';
  23100. }
  23101. return column.treeFooterAggregation.rendered;
  23102. }
  23103. };
  23104. return service;
  23105. }]);
  23106. /**
  23107. * @ngdoc directive
  23108. * @name ui.grid.treeBase.directive:uiGridTreeRowHeaderButtons
  23109. * @element div
  23110. *
  23111. * @description Provides the expand/collapse button on rows
  23112. */
  23113. module.directive('uiGridTreeBaseRowHeaderButtons', ['$templateCache', 'uiGridTreeBaseService',
  23114. function ($templateCache, uiGridTreeBaseService) {
  23115. return {
  23116. replace: true,
  23117. restrict: 'E',
  23118. template: $templateCache.get('ui-grid/treeBaseRowHeaderButtons'),
  23119. scope: true,
  23120. require: '^uiGrid',
  23121. link: function($scope, $elm, $attrs, uiGridCtrl) {
  23122. var self = uiGridCtrl.grid;
  23123. $scope.treeButtonClick = function(row, evt) {
  23124. uiGridTreeBaseService.toggleRowTreeState(self, row, evt);
  23125. };
  23126. }
  23127. };
  23128. }]);
  23129. /**
  23130. * @ngdoc directive
  23131. * @name ui.grid.treeBase.directive:uiGridTreeBaseExpandAllButtons
  23132. * @element div
  23133. *
  23134. * @description Provides the expand/collapse all button
  23135. */
  23136. module.directive('uiGridTreeBaseExpandAllButtons', ['$templateCache', 'uiGridTreeBaseService',
  23137. function ($templateCache, uiGridTreeBaseService) {
  23138. return {
  23139. replace: true,
  23140. restrict: 'E',
  23141. template: $templateCache.get('ui-grid/treeBaseExpandAllButtons'),
  23142. scope: false,
  23143. link: function($scope, $elm, $attrs, uiGridCtrl) {
  23144. var self = $scope.col.grid;
  23145. $scope.headerButtonClick = function(row, evt) {
  23146. if ( self.treeBase.expandAll ){
  23147. uiGridTreeBaseService.collapseAllRows(self, evt);
  23148. } else {
  23149. uiGridTreeBaseService.expandAllRows(self, evt);
  23150. }
  23151. };
  23152. }
  23153. };
  23154. }]);
  23155. /**
  23156. * @ngdoc directive
  23157. * @name ui.grid.treeBase.directive:uiGridViewport
  23158. * @element div
  23159. *
  23160. * @description Stacks on top of ui.grid.uiGridViewport to set formatting on a tree header row
  23161. */
  23162. module.directive('uiGridViewport',
  23163. ['$compile', 'uiGridConstants', 'gridUtil', '$parse',
  23164. function ($compile, uiGridConstants, gridUtil, $parse) {
  23165. return {
  23166. priority: -200, // run after default directive
  23167. scope: false,
  23168. compile: function ($elm, $attrs) {
  23169. var rowRepeatDiv = angular.element($elm.children().children()[0]);
  23170. var existingNgClass = rowRepeatDiv.attr("ng-class");
  23171. var newNgClass = '';
  23172. if ( existingNgClass ) {
  23173. newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-tree-header-row': row.treeLevel > -1}";
  23174. } else {
  23175. newNgClass = "{'ui-grid-tree-header-row': row.treeLevel > -1}";
  23176. }
  23177. rowRepeatDiv.attr("ng-class", newNgClass);
  23178. return {
  23179. pre: function ($scope, $elm, $attrs, controllers) {
  23180. },
  23181. post: function ($scope, $elm, $attrs, controllers) {
  23182. }
  23183. };
  23184. }
  23185. };
  23186. }]);
  23187. })();
  23188. (function () {
  23189. 'use strict';
  23190. /**
  23191. * @ngdoc overview
  23192. * @name ui.grid.treeView
  23193. * @description
  23194. *
  23195. * # ui.grid.treeView
  23196. *
  23197. * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div>
  23198. *
  23199. * This module provides a tree view of the data that it is provided, with nodes in that
  23200. * tree and leaves. Unlike grouping, the tree is an inherent property of the data and must
  23201. * be provided with your data array.
  23202. *
  23203. * Design information:
  23204. * -------------------
  23205. *
  23206. * TreeView uses treeBase for the underlying functionality, and is a very thin wrapper around
  23207. * that logic. Most of the design information has now moved to treebase.
  23208. * <br/>
  23209. * <br/>
  23210. *
  23211. * <div doc-module-components="ui.grid.treeView"></div>
  23212. */
  23213. var module = angular.module('ui.grid.treeView', ['ui.grid', 'ui.grid.treeBase']);
  23214. /**
  23215. * @ngdoc object
  23216. * @name ui.grid.treeView.constant:uiGridTreeViewConstants
  23217. *
  23218. * @description constants available in treeView module, this includes
  23219. * all the constants declared in the treeBase module (these are manually copied
  23220. * as there isn't an easy way to include constants in another constants file, and
  23221. * we don't want to make users include treeBase)
  23222. *
  23223. */
  23224. module.constant('uiGridTreeViewConstants', {
  23225. featureName: "treeView",
  23226. rowHeaderColName: 'treeBaseRowHeaderCol',
  23227. EXPANDED: 'expanded',
  23228. COLLAPSED: 'collapsed',
  23229. aggregation: {
  23230. COUNT: 'count',
  23231. SUM: 'sum',
  23232. MAX: 'max',
  23233. MIN: 'min',
  23234. AVG: 'avg'
  23235. }
  23236. });
  23237. /**
  23238. * @ngdoc service
  23239. * @name ui.grid.treeView.service:uiGridTreeViewService
  23240. *
  23241. * @description Services for treeView features
  23242. */
  23243. module.service('uiGridTreeViewService', ['$q', 'uiGridTreeViewConstants', 'uiGridTreeBaseConstants', 'uiGridTreeBaseService', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants',
  23244. function ($q, uiGridTreeViewConstants, uiGridTreeBaseConstants, uiGridTreeBaseService, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants) {
  23245. var service = {
  23246. initializeGrid: function (grid, $scope) {
  23247. uiGridTreeBaseService.initializeGrid( grid, $scope );
  23248. /**
  23249. * @ngdoc object
  23250. * @name ui.grid.treeView.grid:treeView
  23251. *
  23252. * @description Grid properties and functions added for treeView
  23253. */
  23254. grid.treeView = {};
  23255. grid.registerRowsProcessor(service.adjustSorting, 60);
  23256. /**
  23257. * @ngdoc object
  23258. * @name ui.grid.treeView.api:PublicApi
  23259. *
  23260. * @description Public Api for treeView feature
  23261. */
  23262. var publicApi = {
  23263. events: {
  23264. treeView: {
  23265. }
  23266. },
  23267. methods: {
  23268. treeView: {
  23269. }
  23270. }
  23271. };
  23272. grid.api.registerEventsFromObject(publicApi.events);
  23273. grid.api.registerMethodsFromObject(publicApi.methods);
  23274. },
  23275. defaultGridOptions: function (gridOptions) {
  23276. //default option to true unless it was explicitly set to false
  23277. /**
  23278. * @ngdoc object
  23279. * @name ui.grid.treeView.api:GridOptions
  23280. *
  23281. * @description GridOptions for treeView feature, these are available to be
  23282. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  23283. *
  23284. * Many tree options are set on treeBase, make sure to look at that feature in
  23285. * conjunction with these options.
  23286. */
  23287. /**
  23288. * @ngdoc object
  23289. * @name enableTreeView
  23290. * @propertyOf ui.grid.treeView.api:GridOptions
  23291. * @description Enable row tree view for entire grid.
  23292. * <br/>Defaults to true
  23293. */
  23294. gridOptions.enableTreeView = gridOptions.enableTreeView !== false;
  23295. },
  23296. /**
  23297. * @ngdoc function
  23298. * @name adjustSorting
  23299. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  23300. * @description Trees cannot be sorted the same as flat lists of rows -
  23301. * trees are sorted recursively within each level - so the children of each
  23302. * node are sorted, but not the full set of rows.
  23303. *
  23304. * To achieve this, we suppress the normal sorting by setting ignoreSort on
  23305. * each of the sort columns. When the treeBase rowsProcessor runs it will then
  23306. * unignore these, and will perform a recursive sort against the tree that it builds.
  23307. *
  23308. * @param {array} renderableRows the rows that we need to pass on through
  23309. * @returns {array} renderableRows that we passed on through
  23310. */
  23311. adjustSorting: function( renderableRows ) {
  23312. var grid = this;
  23313. grid.columns.forEach( function( column ){
  23314. if ( column.sort ){
  23315. column.sort.ignoreSort = true;
  23316. }
  23317. });
  23318. return renderableRows;
  23319. }
  23320. };
  23321. return service;
  23322. }]);
  23323. /**
  23324. * @ngdoc directive
  23325. * @name ui.grid.treeView.directive:uiGridTreeView
  23326. * @element div
  23327. * @restrict A
  23328. *
  23329. * @description Adds treeView features to grid
  23330. *
  23331. * @example
  23332. <example module="app">
  23333. <file name="app.js">
  23334. var app = angular.module('app', ['ui.grid', 'ui.grid.treeView']);
  23335. app.controller('MainCtrl', ['$scope', function ($scope) {
  23336. $scope.data = [
  23337. { name: 'Bob', title: 'CEO' },
  23338. { name: 'Frank', title: 'Lowly Developer' }
  23339. ];
  23340. $scope.columnDefs = [
  23341. {name: 'name', enableCellEdit: true},
  23342. {name: 'title', enableCellEdit: true}
  23343. ];
  23344. $scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data };
  23345. }]);
  23346. </file>
  23347. <file name="index.html">
  23348. <div ng-controller="MainCtrl">
  23349. <div ui-grid="gridOptions" ui-grid-tree-view></div>
  23350. </div>
  23351. </file>
  23352. </example>
  23353. */
  23354. module.directive('uiGridTreeView', ['uiGridTreeViewConstants', 'uiGridTreeViewService', '$templateCache',
  23355. function (uiGridTreeViewConstants, uiGridTreeViewService, $templateCache) {
  23356. return {
  23357. replace: true,
  23358. priority: 0,
  23359. require: '^uiGrid',
  23360. scope: false,
  23361. compile: function () {
  23362. return {
  23363. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  23364. if (uiGridCtrl.grid.options.enableTreeView !== false){
  23365. uiGridTreeViewService.initializeGrid(uiGridCtrl.grid, $scope);
  23366. }
  23367. },
  23368. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  23369. }
  23370. };
  23371. }
  23372. };
  23373. }]);
  23374. })();
  23375. angular.module('ui.grid').run(['$templateCache', function($templateCache) {
  23376. 'use strict';
  23377. $templateCache.put('ui-grid/ui-grid-filter',
  23378. "<div class=\"ui-grid-filter-container\" ng-repeat=\"colFilter in col.filters\" ng-class=\"{'ui-grid-filter-cancel-button-hidden' : colFilter.disableCancelFilterButton === true }\"><div ng-if=\"colFilter.type !== 'select'\"><input type=\"text\" class=\"ui-grid-filter-input ui-grid-filter-input-{{$index}}\" ng-model=\"colFilter.term\" ng-attr-placeholder=\"{{colFilter.placeholder || ''}}\" aria-label=\"{{colFilter.ariaLabel || aria.defaultFilterLabel}}\"><div role=\"button\" class=\"ui-grid-filter-button\" ng-click=\"removeFilter(colFilter, $index)\" ng-if=\"!colFilter.disableCancelFilterButton\" ng-disabled=\"colFilter.term === undefined || colFilter.term === null || colFilter.term === ''\" ng-show=\"colFilter.term !== undefined && colFilter.term !== null && colFilter.term !== ''\"><i class=\"ui-grid-icon-cancel\" ui-grid-one-bind-aria-label=\"aria.removeFilter\">&nbsp;</i></div></div><div ng-if=\"colFilter.type === 'select'\"><select class=\"ui-grid-filter-select ui-grid-filter-input-{{$index}}\" ng-model=\"colFilter.term\" ng-attr-placeholder=\"{{colFilter.placeholder || aria.defaultFilterLabel}}\" aria-label=\"{{colFilter.ariaLabel || ''}}\" ng-options=\"option.value as option.label for option in colFilter.selectOptions\"><option value=\"\"></option></select><div role=\"button\" class=\"ui-grid-filter-button-select\" ng-click=\"removeFilter(colFilter, $index)\" ng-if=\"!colFilter.disableCancelFilterButton\" ng-disabled=\"colFilter.term === undefined || colFilter.term === null || colFilter.term === ''\" ng-show=\"colFilter.term !== undefined && colFilter.term != null\"><i class=\"ui-grid-icon-cancel\" ui-grid-one-bind-aria-label=\"aria.removeFilter\">&nbsp;</i></div></div></div>"
  23379. );
  23380. $templateCache.put('ui-grid/ui-grid-footer',
  23381. "<div class=\"ui-grid-footer-panel ui-grid-footer-aggregates-row\"><!-- tfooter --><div class=\"ui-grid-footer ui-grid-footer-viewport\"><div class=\"ui-grid-footer-canvas\"><div class=\"ui-grid-footer-cell-wrapper\" ng-style=\"colContainer.headerCellWrapperStyle()\"><div role=\"row\" class=\"ui-grid-footer-cell-row\"><div ui-grid-footer-cell role=\"gridcell\" ng-repeat=\"col in colContainer.renderedColumns track by col.uid\" col=\"col\" render-index=\"$index\" class=\"ui-grid-footer-cell ui-grid-clearfix\"></div></div></div></div></div></div>"
  23382. );
  23383. $templateCache.put('ui-grid/ui-grid-grid-footer',
  23384. "<div class=\"ui-grid-footer-info ui-grid-grid-footer\"><span>{{'search.totalItems' | t}} {{grid.options.totalItems}}</span> <span ng-if=\"grid.renderContainers.body.visibleRowCache.length !== grid.rows.length\" class=\"ngLabel\">({{\"search.showingItems\" | t}} {{grid.renderContainers.body.visibleRowCache.length}})</span></div>"
  23385. );
  23386. $templateCache.put('ui-grid/ui-grid-group-panel',
  23387. "<div class=\"ui-grid-group-panel\"><div ui-t=\"groupPanel.description\" class=\"description\" ng-show=\"groupings.length == 0\"></div><ul ng-show=\"groupings.length > 0\" class=\"ngGroupList\"><li class=\"ngGroupItem\" ng-repeat=\"group in configGroups\"><span class=\"ngGroupElement\"><span class=\"ngGroupName\">{{group.displayName}} <span ng-click=\"removeGroup($index)\" class=\"ngRemoveGroup\">x</span></span> <span ng-hide=\"$last\" class=\"ngGroupArrow\"></span></span></li></ul></div>"
  23388. );
  23389. $templateCache.put('ui-grid/ui-grid-header',
  23390. "<div role=\"rowgroup\" class=\"ui-grid-header\"><!-- theader --><div class=\"ui-grid-top-panel\"><div class=\"ui-grid-header-viewport\"><div class=\"ui-grid-header-canvas\"><div class=\"ui-grid-header-cell-wrapper\" ng-style=\"colContainer.headerCellWrapperStyle()\"><div role=\"row\" class=\"ui-grid-header-cell-row\"><div class=\"ui-grid-header-cell ui-grid-clearfix\" ng-repeat=\"col in colContainer.renderedColumns track by col.uid\" ui-grid-header-cell col=\"col\" render-index=\"$index\"></div></div></div></div></div></div></div>"
  23391. );
  23392. $templateCache.put('ui-grid/ui-grid-menu-button',
  23393. "<div class=\"ui-grid-menu-button\"><div role=\"button\" ui-grid-one-bind-id-grid=\"'grid-menu'\" class=\"ui-grid-icon-container\" ng-click=\"toggleMenu()\" aria-haspopup=\"true\"><i class=\"ui-grid-icon-menu\" ui-grid-one-bind-aria-label=\"i18n.aria.buttonLabel\">&nbsp;</i></div><div ui-grid-menu menu-items=\"menuItems\"></div></div>"
  23394. );
  23395. $templateCache.put('ui-grid/ui-grid-no-header',
  23396. "<div class=\"ui-grid-top-panel\"></div>"
  23397. );
  23398. $templateCache.put('ui-grid/ui-grid-row',
  23399. "<div ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>"
  23400. );
  23401. $templateCache.put('ui-grid/ui-grid',
  23402. "<div ui-i18n=\"zh-cn\" class=\"ui-grid\"><!-- TODO (c0bra): add \"scoped\" attr here, eventually? --><style ui-grid-style>.grid{{ grid.id }} {\n" +
  23403. " /* Styles for the grid */\n" +
  23404. " }\n" +
  23405. "\n" +
  23406. " .grid{{ grid.id }} .ui-grid-row, .grid{{ grid.id }} .ui-grid-cell, .grid{{ grid.id }} .ui-grid-cell .ui-grid-vertical-bar {\n" +
  23407. " height: {{ grid.options.rowHeight }}px;\n" +
  23408. " }\n" +
  23409. "\n" +
  23410. " .grid{{ grid.id }} .ui-grid-row:last-child .ui-grid-cell {\n" +
  23411. " border-bottom-width: {{ ((grid.getTotalRowHeight() < grid.getViewportHeight()) && '1') || '0' }}px;\n" +
  23412. " }\n" +
  23413. "\n" +
  23414. " {{ grid.verticalScrollbarStyles }}\n" +
  23415. " {{ grid.horizontalScrollbarStyles }}\n" +
  23416. "\n" +
  23417. " /*\n" +
  23418. " .ui-grid[dir=rtl] .ui-grid-viewport {\n" +
  23419. " padding-left: {{ grid.verticalScrollbarWidth }}px;\n" +
  23420. " }\n" +
  23421. " */\n" +
  23422. "\n" +
  23423. " {{ grid.customStyles }}</style><div class=\"ui-grid-contents-wrapper\"><div ui-grid-menu-button ng-if=\"grid.options.enableGridMenu\"></div><div ng-if=\"grid.hasLeftContainer()\" style=\"width: 0\" ui-grid-pinned-container=\"'left'\"></div><div ui-grid-render-container container-id=\"'body'\" col-container-name=\"'body'\" row-container-name=\"'body'\" bind-scroll-horizontal=\"true\" bind-scroll-vertical=\"true\" enable-horizontal-scrollbar=\"grid.options.enableHorizontalScrollbar\" enable-vertical-scrollbar=\"grid.options.enableVerticalScrollbar\"></div><div ng-if=\"grid.hasRightContainer()\" style=\"width: 0\" ui-grid-pinned-container=\"'right'\"></div><div ng-if=\"grid.options.showGridFooter\"></div><div ui-grid-column-menu ng-if=\"grid.options.enableColumnMenus\"></div><div ng-transclude></div></div></div>"
  23424. );
  23425. $templateCache.put('ui-grid/uiGridCell',
  23426. "<div class=\"ui-grid-cell-contents\" title=\"TOOLTIP\">{{COL_FIELD CUSTOM_FILTERS}}</div>"
  23427. );
  23428. $templateCache.put('ui-grid/uiGridColumnMenu',
  23429. "<div class=\"ui-grid-column-menu\"><div ui-grid-menu menu-items=\"menuItems\"><!-- <div class=\"ui-grid-column-menu\">\n" +
  23430. " <div class=\"inner\" ng-show=\"menuShown\">\n" +
  23431. " <ul>\n" +
  23432. " <div ng-show=\"grid.options.enableSorting\">\n" +
  23433. " <li ng-click=\"sortColumn($event, asc)\" ng-class=\"{ 'selected' : col.sort.direction == asc }\"><i class=\"ui-grid-icon-sort-alt-up\"></i> Sort Ascending</li>\n" +
  23434. " <li ng-click=\"sortColumn($event, desc)\" ng-class=\"{ 'selected' : col.sort.direction == desc }\"><i class=\"ui-grid-icon-sort-alt-down\"></i> Sort Descending</li>\n" +
  23435. " <li ng-show=\"col.sort.direction\" ng-click=\"unsortColumn()\"><i class=\"ui-grid-icon-cancel\"></i> Remove Sort</li>\n" +
  23436. " </div>\n" +
  23437. " </ul>\n" +
  23438. " </div>\n" +
  23439. " </div> --></div></div>"
  23440. );
  23441. $templateCache.put('ui-grid/uiGridFooterCell',
  23442. "<div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><div>{{ col.getAggregationText() + ( col.getAggregationValue() CUSTOM_FILTERS ) }}</div></div>"
  23443. );
  23444. $templateCache.put('ui-grid/uiGridHeaderCell',
  23445. "<div role=\"columnheader\" ng-class=\"{ 'sortable': sortable }\" ui-grid-one-bind-aria-labelledby-grid=\"col.uid + '-header-text ' + col.uid + '-sortdir-text'\" aria-sort=\"{{col.sort.direction == asc ? 'ascending' : ( col.sort.direction == desc ? 'descending' : (!col.sort.direction ? 'none' : 'other'))}}\"><div role=\"button\" tabindex=\"0\" class=\"ui-grid-cell-contents ui-grid-header-cell-primary-focus action\" col-index=\"renderIndex\" title=\"TOOLTIP\"><span ui-grid-one-bind-id-grid=\"col.uid + '-header-text'\">{{value}}{{ col.displayName CUSTOM_FILTERS }}</span> </div><div role=\"button\" tabindex=\"0\" ui-grid-one-bind-id-grid=\"col.uid + '-menu-button'\" class=\"ui-grid-column-menu-button\" ng-if=\"grid.options.enableColumnMenus && !col.isRowHeader && col.colDef.enableColumnMenu !== false\" ng-click=\"toggleMenu($event)\" ng-class=\"{'ui-grid-column-menu-button-last-col': isLastCol}\" ui-grid-one-bind-aria-label=\"i18n.headerCell.aria.columnMenuButtonLabel\" aria-haspopup=\"true\"></div><div ui-grid-filter></div><div ui-grid-menu menu-items=\"menuItems\"></div></div>"
  23446. );
  23447. $templateCache.put('ui-grid/uiGridMenu',
  23448. "<div class=\"ui-grid-menu\" ng-if=\"shown\"><div class=\"ui-grid-menu-mid\" ng-show=\"shownMid\"><div class=\"ui-grid-menu-inner\"><button type=\"button\" ng-focus=\"focus=true\" ng-blur=\"focus=false\" class=\"ui-grid-menu-close-button\" ng-class=\"{'ui-grid-sr-only': (!focus)}\"><i class=\"ui-grid-icon-cancel\" ui-grid-one-bind-aria-label=\"i18n.close\"></i></button><ul role=\"menu\" class=\"ui-grid-menu-items\"><li ng-repeat=\"item in menuItems\" role=\"menuitem\" ui-grid-menu-item ui-grid-one-bind-id=\"'menuitem-'+$index\" action=\"item.action\" name=\"item.title\" active=\"item.active\" icon=\"item.icon\" shown=\"item.shown\" context=\"item.context\" template-url=\"item.templateUrl\" leave-open=\"item.leaveOpen\" screen-reader-only=\"item.screenReaderOnly\"></li></ul></div></div></div>"
  23449. );
  23450. $templateCache.put('ui-grid/uiGridMenuItem',
  23451. "<button type=\"button\" class=\"ui-grid-menu-item\" ng-click=\"itemAction($event, title)\" ng-show=\"itemShown()\" ng-class=\"{ 'ui-grid-menu-item-active': active(), 'ui-grid-sr-only': (!focus && screenReaderOnly) }\" aria-pressed=\"{{active()}}\" tabindex=\"0\" ng-focus=\"focus=true\" ng-blur=\"focus=false\"><i ng-class=\"icon\" aria-hidden=\"true\">&nbsp;</i> {{ name }}</button>"
  23452. );
  23453. $templateCache.put('ui-grid/uiGridRenderContainer',
  23454. "<div role=\"grid\" ui-grid-one-bind-id-grid=\"'grid-container'\" class=\"ui-grid-render-container\" ng-style=\"{ 'margin-left': colContainer.getMargin('left') + 'px', 'margin-right': colContainer.getMargin('right') + 'px' }\"><!-- All of these dom elements are replaced in place --><div ui-grid-header></div><div ui-grid-viewport></div><div ng-if=\"colContainer.needsHScrollbarPlaceholder()\" class=\"ui-grid-scrollbar-placeholder\" ng-style=\"{height:colContainer.grid.scrollbarHeight + 'px'}\"></div><ui-grid-footer ng-if=\"grid.options.showColumnFooter\"></ui-grid-footer></div>"
  23455. );
  23456. $templateCache.put('ui-grid/uiGridViewport',
  23457. "<div role=\"rowgroup\" class=\"ui-grid-viewport\" ng-style=\"colContainer.getViewportStyle()\"><!-- tbody --><div class=\"ui-grid-canvas\"><div ng-dblclick=\"grid.appScope.onDblClick(row)\" ng-repeat=\"(rowRenderIndex, row) in rowContainer.renderedRows track by $index\" class=\"ui-grid-row\" ng-style=\"Viewport.rowStyle(rowRenderIndex)\"><div role=\"row\" ui-grid-row=\"row\" row-render-index=\"rowRenderIndex\"></div></div></div></div>"
  23458. );
  23459. $templateCache.put('ui-grid/cellEditor',
  23460. "<div><form name=\"inputForm\"><input type=\"INPUT_TYPE\" ng-class=\"'colt' + col.uid\" ui-grid-editor ng-model=\"MODEL_COL_FIELD\"></form></div>"
  23461. );
  23462. $templateCache.put('ui-grid/dropdownEditor',
  23463. "<div><form name=\"inputForm\"><select ng-class=\"'colt' + col.uid\" ui-grid-edit-dropdown ng-model=\"MODEL_COL_FIELD\" ng-options=\"field[editDropdownIdLabel] as field[editDropdownValueLabel] CUSTOM_FILTERS for field in editDropdownOptionsArray\"></select></form></div>"
  23464. );
  23465. $templateCache.put('ui-grid/fileChooserEditor',
  23466. "<div><form name=\"inputForm\"><input ng-class=\"'colt' + col.uid\" ui-grid-edit-file-chooser type=\"file\" id=\"files\" name=\"files[]\" ng-model=\"MODEL_COL_FIELD\"></form></div>"
  23467. );
  23468. $templateCache.put('ui-grid/expandableRow',
  23469. "<div ui-grid-expandable-row ng-if=\"expandableRow.shouldRenderExpand()\" class=\"expandableRow\" style=\"float:left; margin-top: 1px; margin-bottom: 1px\" ng-style=\"{width: (grid.renderContainers.body.getCanvasWidth()) + 'px', height: grid.options.expandableRowHeight + 'px'}\"></div>"
  23470. );
  23471. $templateCache.put('ui-grid/expandableRowHeader',
  23472. "<div class=\"ui-grid-row-header-cell ui-grid-expandable-buttons-cell\"><div class=\"ui-grid-cell-contents\"><i ng-class=\"{ 'ui-grid-icon-plus-squared' : !row.isExpanded, 'ui-grid-icon-minus-squared' : row.isExpanded }\" ng-click=\"grid.api.expandable.toggleRowExpansion(row.entity)\"></i></div></div>"
  23473. );
  23474. $templateCache.put('ui-grid/expandableScrollFiller',
  23475. "<div ng-if=\"expandableRow.shouldRenderFiller()\" ng-class=\"{scrollFiller:true, scrollFillerClass:(colContainer.name === 'body')}\" ng-style=\"{ width: (grid.getViewportWidth()) + 'px', height: grid.options.expandableRowHeight + 2 + 'px', 'margin-left': grid.options.rowHeader.rowHeaderWidth + 'px' }\"><i class=\"ui-grid-icon-spin5 ui-grid-animate-spin\" ng-style=\"{'margin-top': ( grid.options.expandableRowHeight/2 - 5) + 'px', 'margin-left' : ((grid.getViewportWidth() - grid.options.rowHeader.rowHeaderWidth)/2 - 5) + 'px'}\"></i></div>"
  23476. );
  23477. $templateCache.put('ui-grid/expandableTopRowHeader',
  23478. "<div class=\"ui-grid-row-header-cell ui-grid-expandable-buttons-cell\"><div class=\"ui-grid-cell-contents\"><i ng-class=\"{ 'ui-grid-icon-plus-squared' : !grid.expandable.expandedAll, 'ui-grid-icon-minus-squared' : grid.expandable.expandedAll }\" ng-click=\"grid.api.expandable.toggleAllRows()\"></i></div></div>"
  23479. );
  23480. $templateCache.put('ui-grid/csvLink',
  23481. "<span class=\"ui-grid-exporter-csv-link-span\"><a href=\"data:text/csv;charset=UTF-8,CSV_CONTENT\" download=\"FILE_NAME\">LINK_LABEL</a></span>"
  23482. );
  23483. $templateCache.put('ui-grid/importerMenuItem',
  23484. "<li class=\"ui-grid-menu-item\"><form><input class=\"ui-grid-importer-file-chooser\" type=\"file\" id=\"files\" name=\"files[]\"></form></li>"
  23485. );
  23486. $templateCache.put('ui-grid/importerMenuItemContainer',
  23487. "<div ui-grid-importer-menu-item></div>"
  23488. );
  23489. $templateCache.put('ui-grid/pagination',
  23490. "<div role=\"contentinfo\" class=\"ui-grid-pager-panel\" ui-grid-pager ng-show=\"grid.options.enablePaginationControls\"><div role=\"navigation\" class=\"ui-grid-pager-container\"><div role=\"menubar\" class=\"ui-grid-pager-control\"><button type=\"button\" role=\"menuitem\" class=\"ui-grid-pager-first\" ui-grid-one-bind-title=\"aria.pageToFirst\" ui-grid-one-bind-aria-label=\"aria.pageToFirst\" ng-click=\"pageFirstPageClick()\" ng-disabled=\"cantPageBackward()\"><div class=\"first-triangle\"><div class=\"first-bar\"></div></div></button> <button type=\"button\" role=\"menuitem\" class=\"ui-grid-pager-previous\" ui-grid-one-bind-title=\"aria.pageBack\" ui-grid-one-bind-aria-label=\"aria.pageBack\" ng-click=\"pagePreviousPageClick()\" ng-disabled=\"cantPageBackward()\"><div class=\"first-triangle prev-triangle\"></div></button> <input type=\"number\" ui-grid-one-bind-title=\"aria.pageSelected\" ui-grid-one-bind-aria-label=\"aria.pageSelected\" class=\"ui-grid-pager-control-input\" ng-model=\"grid.options.paginationCurrentPage\" min=\"1\" max=\"{{ paginationApi.getTotalPages() }}\" required> <span class=\"ui-grid-pager-max-pages-number\" ng-show=\"paginationApi.getTotalPages() > 0\"><abbr ui-grid-one-bind-title=\"paginationOf\">/</abbr> {{ paginationApi.getTotalPages() }}</span> <button type=\"button\" role=\"menuitem\" class=\"ui-grid-pager-next\" ui-grid-one-bind-title=\"aria.pageForward\" ui-grid-one-bind-aria-label=\"aria.pageForward\" ng-click=\"pageNextPageClick()\" ng-disabled=\"cantPageForward()\"><div class=\"last-triangle next-triangle\"></div></button> <button type=\"button\" role=\"menuitem\" class=\"ui-grid-pager-last\" ui-grid-one-bind-title=\"aria.pageToLast\" ui-grid-one-bind-aria-label=\"aria.pageToLast\" ng-click=\"pageLastPageClick()\" ng-disabled=\"cantPageToLast()\"><div class=\"last-triangle\"><div class=\"last-bar\"></div></div></button></div><div class=\" ui-grid-pager-container\" ng-if=\"grid.options.paginationPageSizes.length > 1\"><select ui-grid-one-bind-aria-labelledby-grid=\"'items-per-page-label'\" ng-model=\"grid.options.paginationPageSize\" ng-options=\"o as o for o in grid.options.paginationPageSizes\"></select><span ui-grid-one-bind-id-grid=\"'items-per-page-label'\" class=\"ui-grid-pager-row-count-label\">&nbsp;{{sizesLabel}}</span></div><span ng-if=\"grid.options.paginationPageSizes.length <= 1\" class=\"ui-grid-pager-row-count-label\">{{grid.options.paginationPageSize}}&nbsp;{{sizesLabel}}</span></div><div class=\"ui-grid-pager-count-container\"><div class=\"ui-grid-pager-count\"><span ng-show=\"grid.options.totalItems > 0\">{{showingLow}} <abbr ui-grid-one-bind-title=\"paginationThrough\">-</abbr> {{showingHigh}} {{paginationOf}} {{grid.rows.length}} {{totalItemsLabel}}</span>&nbsp&nbsp&nbsp&nbsp<span>{{'search.totalItems' | t}} {{grid.options.totalItems}}</span> <span ng-if=\"grid.renderContainers.body.visibleRowCache.length !== grid.rows.length\" class=\"ngLabel\">({{\"search.showingItems\" | t}} {{grid.renderContainers.body.visibleRowCache.length}})</span></div></div></div>"
  23491. );
  23492. $templateCache.put('ui-grid/columnResizer',
  23493. "<div ui-grid-column-resizer ng-if=\"grid.options.enableColumnResizing\" class=\"ui-grid-column-resizer\" col=\"col\" position=\"right\" render-index=\"renderIndex\" unselectable=\"on\"></div>"
  23494. );
  23495. $templateCache.put('ui-grid/gridFooterSelectedItems',
  23496. "<span ng-if=\"grid.selection.selectedCount !== 0 && grid.options.enableFooterTotalSelected\">({{\"search.selectedItems\" | t}} {{grid.selection.selectedCount}})</span>"
  23497. );
  23498. $templateCache.put('ui-grid/selectionHeaderCell',
  23499. "<div><!-- <div class=\"ui-grid-vertical-bar\">&nbsp;</div> --><div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><ui-grid-selection-select-all-buttons ng-if=\"grid.options.enableSelectAll\"></ui-grid-selection-select-all-buttons></div></div>"
  23500. );
  23501. $templateCache.put('ui-grid/selectionRowHeader',
  23502. "<div class=\"ui-grid-disable-selection\"><div class=\"ui-grid-cell-contents\"><ui-grid-selection-row-header-buttons></ui-grid-selection-row-header-buttons></div></div>"
  23503. );
  23504. $templateCache.put('ui-grid/selectionRowHeaderButtons',
  23505. "<div class=\"ui-grid-selection-row-header-buttons ui-grid-icon-ok\" ng-class=\"{'ui-grid-row-selected': row.isSelected}\" ng-click=\"selectButtonClick(row, $event)\">&nbsp;</div>"
  23506. );
  23507. $templateCache.put('ui-grid/selectionSelectAllButtons',
  23508. "<div class=\"ui-grid-selection-row-header-buttons ui-grid-icon-ok\" ng-class=\"{'ui-grid-all-selected': grid.selection.selectAll}\" ng-click=\"headerButtonClick($event)\"></div>"
  23509. );
  23510. $templateCache.put('ui-grid/treeBaseExpandAllButtons',
  23511. "<div class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-icon-minus-squared': grid.treeBase.numberLevels > 0 && grid.treeBase.expandAll, 'ui-grid-icon-plus-squared': grid.treeBase.numberLevels > 0 && !grid.treeBase.expandAll}\" ng-click=\"headerButtonClick($event)\"></div>"
  23512. );
  23513. $templateCache.put('ui-grid/treeBaseHeaderCell',
  23514. "<div><div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><ui-grid-tree-base-expand-all-buttons></ui-grid-tree-base-expand-all-buttons></div></div>"
  23515. );
  23516. $templateCache.put('ui-grid/treeBaseRowHeader',
  23517. "<div class=\"ui-grid-cell-contents\"><ui-grid-tree-base-row-header-buttons></ui-grid-tree-base-row-header-buttons></div>"
  23518. );
  23519. $templateCache.put('ui-grid/treeBaseRowHeaderButtons',
  23520. "<div class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-tree-base-header': row.treeLevel > -1 }\" ng-click=\"treeButtonClick(row, $event)\"><i ng-class=\"{'ui-grid-icon-minus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'expanded', 'ui-grid-icon-plus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'collapsed'}\" ng-style=\"{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}\"></i> {{GridRow}}</div>"
  23521. );
  23522. }]);