ui-grid-2.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717
  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. } else {
  148. var html = $scope.col.cellTemplate
  149. .replace(uiGridConstants.MODEL_COL_FIELD, 'row.entity.' + gridUtil.preEval($scope.col.field))
  150. .replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
  151. var cellElement = $compile(html)($scope);
  152. $elm.append(cellElement);
  153. }
  154. }
  155. },
  156. post: function($scope, $elm, $attrs, uiGridCtrl) {
  157. var initColClass = $scope.col.getColClass(false);
  158. $elm.addClass(initColClass);
  159. var classAdded;
  160. var updateClass = function(grid) {
  161. var contents = $elm;
  162. if (classAdded) {
  163. contents.removeClass(classAdded);
  164. classAdded = null;
  165. }
  166. if (angular.isFunction($scope.col.cellClass)) {
  167. classAdded = $scope.col.cellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex);
  168. } else {
  169. classAdded = $scope.col.cellClass;
  170. }
  171. contents.addClass(classAdded);
  172. };
  173. if ($scope.col.cellClass) {
  174. updateClass();
  175. }
  176. // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs
  177. var dataChangeDereg = $scope.grid.registerDataChangeCallback(updateClass, [uiGridConstants.dataChange.COLUMN, uiGridConstants.dataChange.EDIT]);
  178. // watch the col and row to see if they change - which would indicate that we've scrolled or sorted or otherwise
  179. // changed the row/col that this cell relates to, and we need to re-evaluate cell classes and maybe other things
  180. var cellChangeFunction = function(n, o) {
  181. if (n !== o) {
  182. if (classAdded || $scope.col.cellClass) {
  183. updateClass();
  184. }
  185. // See if the column's internal class has changed
  186. var newColClass = $scope.col.getColClass(false);
  187. if (newColClass !== initColClass) {
  188. $elm.removeClass(initColClass);
  189. $elm.addClass(newColClass);
  190. initColClass = newColClass;
  191. }
  192. }
  193. };
  194. // TODO(c0bra): Turn this into a deep array watch
  195. /* shouldn't be needed any more given track by col.name
  196. var colWatchDereg = $scope.$watch( 'col', cellChangeFunction );
  197. */
  198. var rowWatchDereg = $scope.$watch('row', cellChangeFunction);
  199. var deregisterFunction = function() {
  200. dataChangeDereg();
  201. // colWatchDereg();
  202. rowWatchDereg();
  203. };
  204. $scope.$on('$destroy', deregisterFunction);
  205. $elm.on('$destroy', deregisterFunction);
  206. }
  207. };
  208. }
  209. };
  210. return uiGridCell;
  211. }]);
  212. (function() {
  213. angular.module('ui.grid')
  214. .service('uiGridColumnMenuService', ['i18nService', 'uiGridConstants', 'gridUtil',
  215. function(i18nService, uiGridConstants, gridUtil) {
  216. /**
  217. * @ngdoc service
  218. * @name ui.grid.service:uiGridColumnMenuService
  219. *
  220. * @description Services for working with column menus, factored out
  221. * to make the code easier to understand
  222. */
  223. var service = {
  224. /**
  225. * @ngdoc method
  226. * @methodOf ui.grid.service:uiGridColumnMenuService
  227. * @name initialize
  228. * @description Sets defaults, puts a reference to the $scope on
  229. * the uiGridController
  230. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  231. * @param {controller} uiGridCtrl the uiGridController for the grid
  232. * we're on
  233. *
  234. */
  235. initialize: function($scope, uiGridCtrl) {
  236. $scope.grid = uiGridCtrl.grid;
  237. // Store a reference to this link/controller in the main uiGrid controller
  238. // to allow showMenu later
  239. uiGridCtrl.columnMenuScope = $scope;
  240. // Save whether we're shown or not so the columns can check
  241. $scope.menuShown = false;
  242. },
  243. /**
  244. * @ngdoc method
  245. * @methodOf ui.grid.service:uiGridColumnMenuService
  246. * @name setColMenuItemWatch
  247. * @description Setup a watch on $scope.col.menuItems, and update
  248. * menuItems based on this. $scope.col needs to be set by the column
  249. * before calling the menu.
  250. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  251. * @param {controller} uiGridCtrl the uiGridController for the grid
  252. * we're on
  253. *
  254. */
  255. setColMenuItemWatch: function($scope) {
  256. var deregFunction = $scope.$watch('col.menuItems', function(n, o) {
  257. if (typeof(n) !== 'undefined' && n && angular.isArray(n)) {
  258. n.forEach(function(item) {
  259. if (typeof(item.context) === 'undefined' || !item.context) {
  260. item.context = {};
  261. }
  262. item.context.col = $scope.col;
  263. });
  264. $scope.menuItems = $scope.defaultMenuItems.concat(n);
  265. } else {
  266. $scope.menuItems = $scope.defaultMenuItems;
  267. }
  268. });
  269. $scope.$on('$destroy', deregFunction);
  270. },
  271. /**
  272. * @ngdoc boolean
  273. * @name enableSorting
  274. * @propertyOf ui.grid.class:GridOptions.columnDef
  275. * @description (optional) True by default. When enabled, this setting adds sort
  276. * widgets to the column header, allowing sorting of the data in the individual column.
  277. */
  278. /**
  279. * @ngdoc method
  280. * @methodOf ui.grid.service:uiGridColumnMenuService
  281. * @name sortable
  282. * @description determines whether this column is sortable
  283. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  284. *
  285. */
  286. sortable: function($scope) {
  287. if ($scope.grid.options.enableSorting && typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.enableSorting) {
  288. return true;
  289. } else {
  290. return false;
  291. }
  292. },
  293. /**
  294. * @ngdoc method
  295. * @methodOf ui.grid.service:uiGridColumnMenuService
  296. * @name isActiveSort
  297. * @description determines whether the requested sort direction is current active, to
  298. * allow highlighting in the menu
  299. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  300. * @param {string} direction the direction that we'd have selected for us to be active
  301. *
  302. */
  303. isActiveSort: function($scope, direction) {
  304. return (typeof($scope.col) !== 'undefined' && typeof($scope.col.sort) !== 'undefined' &&
  305. typeof($scope.col.sort.direction) !== 'undefined' && $scope.col.sort.direction === direction);
  306. },
  307. /**
  308. * @ngdoc method
  309. * @methodOf ui.grid.service:uiGridColumnMenuService
  310. * @name suppressRemoveSort
  311. * @description determines whether we should suppress the removeSort option
  312. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  313. *
  314. */
  315. suppressRemoveSort: function($scope) {
  316. if ($scope.col && $scope.col.suppressRemoveSort) {
  317. return true;
  318. } else {
  319. return false;
  320. }
  321. },
  322. /**
  323. * @ngdoc boolean
  324. * @name enableHiding
  325. * @propertyOf ui.grid.class:GridOptions.columnDef
  326. * @description (optional) True by default. When set to false, this setting prevents a user from hiding the column
  327. * using the column menu or the grid menu.
  328. */
  329. /**
  330. * @ngdoc method
  331. * @methodOf ui.grid.service:uiGridColumnMenuService
  332. * @name hideable
  333. * @description determines whether a column can be hidden, by checking the enableHiding columnDef option
  334. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  335. *
  336. */
  337. hideable: function($scope) {
  338. if (typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.colDef && $scope.col.colDef.enableHiding === false) {
  339. return false;
  340. } else {
  341. return true;
  342. }
  343. },
  344. /**
  345. * @ngdoc method
  346. * @methodOf ui.grid.service:uiGridColumnMenuService
  347. * @name getDefaultMenuItems
  348. * @description returns the default menu items for a column menu
  349. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  350. *
  351. */
  352. getDefaultMenuItems: function($scope) {
  353. return [{
  354. title: i18nService.getSafeText('sort.ascending'),
  355. icon: 'ui-grid-icon-sort-alt-up',
  356. action: function($event) {
  357. $event.stopPropagation();
  358. $scope.sortColumn($event, uiGridConstants.ASC);
  359. },
  360. shown: function() {
  361. return service.sortable($scope);
  362. },
  363. active: function() {
  364. return service.isActiveSort($scope, uiGridConstants.ASC);
  365. }
  366. },
  367. {
  368. title: i18nService.getSafeText('sort.descending'),
  369. icon: 'ui-grid-icon-sort-alt-down',
  370. action: function($event) {
  371. $event.stopPropagation();
  372. $scope.sortColumn($event, uiGridConstants.DESC);
  373. },
  374. shown: function() {
  375. return service.sortable($scope);
  376. },
  377. active: function() {
  378. return service.isActiveSort($scope, uiGridConstants.DESC);
  379. }
  380. },
  381. {
  382. title: i18nService.getSafeText('sort.remove'),
  383. icon: 'ui-grid-icon-cancel',
  384. action: function($event) {
  385. $event.stopPropagation();
  386. $scope.unsortColumn();
  387. },
  388. shown: function() {
  389. return service.sortable($scope) &&
  390. typeof($scope.col) !== 'undefined' && (typeof($scope.col.sort) !== 'undefined' &&
  391. typeof($scope.col.sort.direction) !== 'undefined') && $scope.col.sort.direction !== null &&
  392. !service.suppressRemoveSort($scope);
  393. }
  394. },
  395. {
  396. title: i18nService.getSafeText('column.hide'),
  397. icon: 'ui-grid-icon-cancel',
  398. shown: function() {
  399. return service.hideable($scope);
  400. },
  401. action: function($event) {
  402. $event.stopPropagation();
  403. $scope.hideColumn();
  404. }
  405. },
  406. {
  407. title: i18nService.getSafeText('columnMenu.close'),
  408. screenReaderOnly: true,
  409. shown: function() {
  410. return true;
  411. },
  412. action: function($event) {
  413. $event.stopPropagation();
  414. }
  415. }
  416. ];
  417. },
  418. /**
  419. * @ngdoc method
  420. * @methodOf ui.grid.service:uiGridColumnMenuService
  421. * @name getColumnElementPosition
  422. * @description gets the position information needed to place the column
  423. * menu below the column header
  424. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  425. * @param {GridCol} column the column we want to position below
  426. * @param {element} $columnElement the column element we want to position below
  427. * @returns {hash} containing left, top, offset, height, width
  428. *
  429. */
  430. getColumnElementPosition: function($scope, column, $columnElement) {
  431. var positionData = {};
  432. positionData.left = $columnElement[0].offsetLeft;
  433. positionData.top = $columnElement[0].offsetTop;
  434. positionData.parentLeft = $columnElement[0].offsetParent.offsetLeft;
  435. // Get the grid scrollLeft
  436. positionData.offset = 0;
  437. if (column.grid.options.offsetLeft) {
  438. positionData.offset = column.grid.options.offsetLeft;
  439. }
  440. positionData.height = gridUtil.elementHeight($columnElement, true);
  441. positionData.width = gridUtil.elementWidth($columnElement, true);
  442. return positionData;
  443. },
  444. /**
  445. * @ngdoc method
  446. * @methodOf ui.grid.service:uiGridColumnMenuService
  447. * @name repositionMenu
  448. * @description Reposition the menu below the new column. If the menu has no child nodes
  449. * (i.e. it's not currently visible) then we guess it's width at 100, we'll be called again
  450. * later to fix it
  451. * @param {$scope} $scope the $scope from the uiGridColumnMenu
  452. * @param {GridCol} column the column we want to position below
  453. * @param {hash} positionData a hash containing left, top, offset, height, width
  454. * @param {element} $elm the column menu element that we want to reposition
  455. * @param {element} $columnElement the column element that we want to reposition underneath
  456. *
  457. */
  458. repositionMenu: function($scope, column, positionData, $elm, $columnElement) {
  459. var menu = $elm[0].querySelectorAll('.ui-grid-menu');
  460. var containerId = column.renderContainer ? column.renderContainer : 'body';
  461. var renderContainer = column.grid.renderContainers[containerId];
  462. // It's possible that the render container of the column we're attaching to is
  463. // offset from the grid (i.e. pinned containers), we need to get the difference in the offsetLeft
  464. // between the render container and the grid
  465. var renderContainerElm = gridUtil.closestElm($columnElement, '.ui-grid-render-container');
  466. var renderContainerOffset = renderContainerElm.getBoundingClientRect().left - $scope.grid.element[0].getBoundingClientRect().left;
  467. var containerScrollLeft = renderContainerElm.querySelectorAll('.ui-grid-viewport')[0].scrollLeft;
  468. // default value the last width for _this_ column, otherwise last width for _any_ column, otherwise default to 170
  469. var myWidth = column.lastMenuWidth ? column.lastMenuWidth : ($scope.lastMenuWidth ? $scope.lastMenuWidth : 170);
  470. var paddingRight = column.lastMenuPaddingRight ? column.lastMenuPaddingRight : ($scope.lastMenuPaddingRight ? $scope.lastMenuPaddingRight : 10);
  471. if (menu.length !== 0) {
  472. var mid = menu[0].querySelectorAll('.ui-grid-menu-mid');
  473. if (mid.length !== 0 && !angular.element(mid).hasClass('ng-hide')) {
  474. myWidth = gridUtil.elementWidth(menu, true);
  475. $scope.lastMenuWidth = myWidth;
  476. column.lastMenuWidth = myWidth;
  477. // TODO(c0bra): use padding-left/padding-right based on document direction (ltr/rtl), place menu on proper side
  478. // Get the column menu right padding
  479. paddingRight = parseInt(gridUtil.getStyles(angular.element(menu)[0])['paddingRight'], 10);
  480. $scope.lastMenuPaddingRight = paddingRight;
  481. column.lastMenuPaddingRight = paddingRight;
  482. }
  483. }
  484. var left = positionData.left + renderContainerOffset - containerScrollLeft + positionData.parentLeft + positionData.width - myWidth + paddingRight;
  485. if (left < positionData.offset) {
  486. left = positionData.offset;
  487. }
  488. $elm.css('left', left + 'px');
  489. $elm.css('top', (positionData.top + positionData.height) + 'px');
  490. }
  491. };
  492. return service;
  493. }
  494. ])
  495. .directive('uiGridColumnMenu', ['$timeout', 'gridUtil', 'uiGridConstants', 'uiGridColumnMenuService', '$document',
  496. function($timeout, gridUtil, uiGridConstants, uiGridColumnMenuService, $document) {
  497. /**
  498. * @ngdoc directive
  499. * @name ui.grid.directive:uiGridColumnMenu
  500. * @description Provides the column menu framework, leverages uiGridMenu underneath
  501. *
  502. */
  503. var uiGridColumnMenu = {
  504. priority: 0,
  505. scope: true,
  506. require: '^uiGrid',
  507. templateUrl: 'ui-grid/uiGridColumnMenu',
  508. replace: true,
  509. link: function($scope, $elm, $attrs, uiGridCtrl) {
  510. var self = this;
  511. uiGridColumnMenuService.initialize($scope, uiGridCtrl);
  512. $scope.defaultMenuItems = uiGridColumnMenuService.getDefaultMenuItems($scope);
  513. // Set the menu items for use with the column menu. The user can later add additional items via the watch
  514. $scope.menuItems = $scope.defaultMenuItems;
  515. uiGridColumnMenuService.setColMenuItemWatch($scope);
  516. /**
  517. * @ngdoc method
  518. * @methodOf ui.grid.directive:uiGridColumnMenu
  519. * @name showMenu
  520. * @description Shows the column menu. If the menu is already displayed it
  521. * calls the menu to ask it to hide (it will animate), then it repositions the menu
  522. * to the right place whilst hidden (it will make an assumption on menu width),
  523. * then it asks the menu to show (it will animate), then it repositions the menu again
  524. * once we can calculate it's size.
  525. * @param {GridCol} column the column we want to position below
  526. * @param {element} $columnElement the column element we want to position below
  527. */
  528. $scope.showMenu = function(column, $columnElement, event) {
  529. // Swap to this column
  530. $scope.col = column;
  531. // Get the position information for the column element
  532. var colElementPosition = uiGridColumnMenuService.getColumnElementPosition($scope, column, $columnElement);
  533. if ($scope.menuShown) {
  534. // we want to hide, then reposition, then show, but we want to wait for animations
  535. // we set a variable, and then rely on the menu-hidden event to call the reposition and show
  536. $scope.colElement = $columnElement;
  537. $scope.colElementPosition = colElementPosition;
  538. $scope.hideThenShow = true;
  539. $scope.$broadcast('hide-menu', { originalEvent: event });
  540. } else {
  541. self.shown = $scope.menuShown = true;
  542. uiGridColumnMenuService.repositionMenu($scope, column, colElementPosition, $elm, $columnElement);
  543. $scope.colElement = $columnElement;
  544. $scope.colElementPosition = colElementPosition;
  545. $scope.$broadcast('show-menu', { originalEvent: event });
  546. }
  547. };
  548. /**
  549. * @ngdoc method
  550. * @methodOf ui.grid.directive:uiGridColumnMenu
  551. * @name hideMenu
  552. * @description Hides the column menu.
  553. * @param {boolean} broadcastTrigger true if we were triggered by a broadcast
  554. * from the menu itself - in which case don't broadcast again as we'll get
  555. * an infinite loop
  556. */
  557. $scope.hideMenu = function(broadcastTrigger) {
  558. $scope.menuShown = false;
  559. if (!broadcastTrigger) {
  560. $scope.$broadcast('hide-menu');
  561. }
  562. };
  563. $scope.$on('menu-hidden', function() {
  564. if ($scope.hideThenShow) {
  565. delete $scope.hideThenShow;
  566. uiGridColumnMenuService.repositionMenu($scope, $scope.col, $scope.colElementPosition, $elm, $scope.colElement);
  567. $scope.$broadcast('show-menu');
  568. $scope.menuShown = true;
  569. } else {
  570. $scope.hideMenu(true);
  571. if ($scope.col) {
  572. //Focus on the menu button
  573. gridUtil.focus.bySelector($document, '.ui-grid-header-cell.' + $scope.col.getColClass() + ' .ui-grid-column-menu-button', $scope.col.grid, false);
  574. }
  575. }
  576. });
  577. $scope.$on('menu-shown', function() {
  578. $timeout(function() {
  579. uiGridColumnMenuService.repositionMenu($scope, $scope.col, $scope.colElementPosition, $elm, $scope.colElement);
  580. delete $scope.colElementPosition;
  581. delete $scope.columnElement;
  582. }, 200);
  583. });
  584. /* Column methods */
  585. $scope.sortColumn = function(event, dir) {
  586. event.stopPropagation();
  587. $scope.grid.sortColumn($scope.col, dir, true)
  588. .then(function() {
  589. $scope.grid.refresh();
  590. $scope.hideMenu();
  591. });
  592. };
  593. $scope.unsortColumn = function() {
  594. $scope.col.unsort();
  595. $scope.grid.refresh();
  596. $scope.hideMenu();
  597. };
  598. //Since we are hiding this column the default hide action will fail so we need to focus somewhere else.
  599. var setFocusOnHideColumn = function() {
  600. $timeout(function() {
  601. // Get the UID of the first
  602. var focusToGridMenu = function() {
  603. return gridUtil.focus.byId('grid-menu', $scope.grid);
  604. };
  605. var thisIndex;
  606. $scope.grid.columns.some(function(element, index) {
  607. if (angular.equals(element, $scope.col)) {
  608. thisIndex = index;
  609. return true;
  610. }
  611. });
  612. var previousVisibleCol;
  613. // Try and find the next lower or nearest column to focus on
  614. $scope.grid.columns.some(function(element, index) {
  615. if (!element.visible) {
  616. return false;
  617. } // This columns index is below the current column index
  618. else if (index < thisIndex) {
  619. previousVisibleCol = element;
  620. } // This elements index is above this column index and we haven't found one that is lower
  621. else if (index > thisIndex && !previousVisibleCol) {
  622. // This is the next best thing
  623. previousVisibleCol = element;
  624. // We've found one so use it.
  625. return true;
  626. } // We've reached an element with an index above this column and the previousVisibleCol variable has been set
  627. else if (index > thisIndex && previousVisibleCol) {
  628. // We are done.
  629. return true;
  630. }
  631. });
  632. // If found then focus on it
  633. if (previousVisibleCol) {
  634. var colClass = previousVisibleCol.getColClass();
  635. gridUtil.focus.bySelector($document, '.ui-grid-header-cell.' + colClass + ' .ui-grid-header-cell-primary-focus', true).then(angular.noop, function(reason) {
  636. if (reason !== 'canceled') { // If this is canceled then don't perform the action
  637. //The fallback action is to focus on the grid menu
  638. return focusToGridMenu();
  639. }
  640. });
  641. } else {
  642. // Fallback action to focus on the grid menu
  643. focusToGridMenu();
  644. }
  645. });
  646. };
  647. $scope.hideColumn = function() {
  648. $scope.col.colDef.visible = false;
  649. $scope.col.visible = false;
  650. $scope.grid.queueGridRefresh();
  651. $scope.hideMenu();
  652. $scope.grid.api.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
  653. $scope.grid.api.core.raise.columnVisibilityChanged($scope.col);
  654. // We are hiding so the default action of focusing on the button that opened this menu will fail.
  655. setFocusOnHideColumn();
  656. };
  657. },
  658. controller: ['$scope', function($scope) {
  659. var self = this;
  660. $scope.$watch('menuItems', function(n, o) {
  661. self.menuItems = n;
  662. });
  663. }]
  664. };
  665. return uiGridColumnMenu;
  666. }
  667. ]);
  668. })();
  669. (function() {
  670. 'use strict';
  671. angular.module('ui.grid').directive('uiGridFilter', ['$compile', '$templateCache', 'i18nService', 'gridUtil', function($compile, $templateCache, i18nService, gridUtil) {
  672. return {
  673. compile: function() {
  674. return {
  675. pre: function($scope, $elm, $attrs, controllers) {
  676. $scope.col.updateFilters = function(filterable) {
  677. $elm.children().remove();
  678. if (filterable) {
  679. var template = $scope.col.filterHeaderTemplate;
  680. $elm.append($compile(template)($scope));
  681. }
  682. };
  683. $scope.$on('$destroy', function() {
  684. delete $scope.col.updateFilters;
  685. });
  686. },
  687. post: function($scope, $elm, $attrs, controllers) {
  688. $scope.aria = i18nService.getSafeText('headerCell.aria');
  689. $scope.removeFilter = function(colFilter, index) {
  690. colFilter.term = null;
  691. //Set the focus to the filter input after the action disables the button
  692. gridUtil.focus.bySelector($elm, '.ui-grid-filter-input-' + index);
  693. };
  694. }
  695. };
  696. }
  697. };
  698. }]);
  699. })();
  700. (function() {
  701. 'use strict';
  702. angular.module('ui.grid').directive('uiGridFooterCell', ['$timeout', 'gridUtil', 'uiGridConstants', '$compile',
  703. function($timeout, gridUtil, uiGridConstants, $compile) {
  704. var uiGridFooterCell = {
  705. priority: 0,
  706. scope: {
  707. col: '=',
  708. row: '=',
  709. renderIndex: '='
  710. },
  711. replace: true,
  712. require: '^uiGrid',
  713. compile: function compile(tElement, tAttrs, transclude) {
  714. return {
  715. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  716. var cellFooter = $compile($scope.col.footerCellTemplate)($scope);
  717. $elm.append(cellFooter);
  718. },
  719. post: function($scope, $elm, $attrs, uiGridCtrl) {
  720. //$elm.addClass($scope.col.getColClass(false));
  721. $scope.grid = uiGridCtrl.grid;
  722. var initColClass = $scope.col.getColClass(false);
  723. $elm.addClass(initColClass);
  724. // apply any footerCellClass
  725. var classAdded;
  726. var updateClass = function(grid) {
  727. var contents = $elm;
  728. if (classAdded) {
  729. contents.removeClass(classAdded);
  730. classAdded = null;
  731. }
  732. if (angular.isFunction($scope.col.footerCellClass)) {
  733. classAdded = $scope.col.footerCellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex);
  734. } else {
  735. classAdded = $scope.col.footerCellClass;
  736. }
  737. contents.addClass(classAdded);
  738. };
  739. if ($scope.col.footerCellClass) {
  740. updateClass();
  741. }
  742. $scope.col.updateAggregationValue();
  743. // Watch for column changes so we can alter the col cell class properly
  744. /* shouldn't be needed any more, given track by col.name
  745. $scope.$watch('col', function (n, o) {
  746. if (n !== o) {
  747. // See if the column's internal class has changed
  748. var newColClass = $scope.col.getColClass(false);
  749. if (newColClass !== initColClass) {
  750. $elm.removeClass(initColClass);
  751. $elm.addClass(newColClass);
  752. initColClass = newColClass;
  753. }
  754. }
  755. });
  756. */
  757. // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs
  758. var dataChangeDereg = $scope.grid.registerDataChangeCallback(updateClass, [uiGridConstants.dataChange.COLUMN]);
  759. // listen for visible rows change and update aggregation values
  760. $scope.grid.api.core.on.rowsRendered($scope, $scope.col.updateAggregationValue);
  761. $scope.grid.api.core.on.rowsRendered($scope, updateClass);
  762. $scope.$on('$destroy', dataChangeDereg);
  763. }
  764. };
  765. }
  766. };
  767. return uiGridFooterCell;
  768. }
  769. ]);
  770. })();
  771. (function() {
  772. 'use strict';
  773. angular.module('ui.grid').directive('uiGridFooter', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function($templateCache, $compile, uiGridConstants, gridUtil, $timeout) {
  774. return {
  775. restrict: 'EA',
  776. replace: true,
  777. // priority: 1000,
  778. require: ['^uiGrid', '^uiGridRenderContainer'],
  779. scope: true,
  780. compile: function($elm, $attrs) {
  781. return {
  782. pre: function($scope, $elm, $attrs, controllers) {
  783. var uiGridCtrl = controllers[0];
  784. var containerCtrl = controllers[1];
  785. $scope.grid = uiGridCtrl.grid;
  786. $scope.colContainer = containerCtrl.colContainer;
  787. containerCtrl.footer = $elm;
  788. var footerTemplate = $scope.grid.options.footerTemplate;
  789. gridUtil.getTemplate(footerTemplate)
  790. .then(function(contents) {
  791. var template = angular.element(contents);
  792. var newElm = $compile(template)($scope);
  793. $elm.append(newElm);
  794. if (containerCtrl) {
  795. // Inject a reference to the footer viewport (if it exists) into the grid controller for use in the horizontal scroll handler below
  796. var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0];
  797. if (footerViewport) {
  798. containerCtrl.footerViewport = footerViewport;
  799. }
  800. }
  801. });
  802. },
  803. post: function($scope, $elm, $attrs, controllers) {
  804. var uiGridCtrl = controllers[0];
  805. var containerCtrl = controllers[1];
  806. // gridUtil.logDebug('ui-grid-footer link');
  807. var grid = uiGridCtrl.grid;
  808. // Don't animate footer cells
  809. gridUtil.disableAnimations($elm);
  810. containerCtrl.footer = $elm;
  811. var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0];
  812. if (footerViewport) {
  813. containerCtrl.footerViewport = footerViewport;
  814. }
  815. }
  816. };
  817. }
  818. };
  819. }]);
  820. })();
  821. (function() {
  822. 'use strict';
  823. angular.module('ui.grid').directive('uiGridGridFooter', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function($templateCache, $compile, uiGridConstants, gridUtil, $timeout) {
  824. return {
  825. restrict: 'EA',
  826. replace: true,
  827. // priority: 1000,
  828. require: '^uiGrid',
  829. scope: true,
  830. compile: function($elm, $attrs) {
  831. return {
  832. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  833. $scope.grid = uiGridCtrl.grid;
  834. var footerTemplate = $scope.grid.options.gridFooterTemplate;
  835. gridUtil.getTemplate(footerTemplate)
  836. .then(function(contents) {
  837. var template = angular.element(contents);
  838. var newElm = $compile(template)($scope);
  839. $elm.append(newElm);
  840. });
  841. },
  842. post: function($scope, $elm, $attrs, controllers) {
  843. }
  844. };
  845. }
  846. };
  847. }]);
  848. })();
  849. (function() {
  850. 'use strict';
  851. angular.module('ui.grid').directive('uiGridGroupPanel', ["$compile", "uiGridConstants", "gridUtil", function($compile, uiGridConstants, gridUtil) {
  852. var defaultTemplate = 'ui-grid/ui-grid-group-panel';
  853. return {
  854. restrict: 'EA',
  855. replace: true,
  856. require: '?^uiGrid',
  857. scope: false,
  858. compile: function($elm, $attrs) {
  859. return {
  860. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  861. var groupPanelTemplate = $scope.grid.options.groupPanelTemplate || defaultTemplate;
  862. gridUtil.getTemplate(groupPanelTemplate)
  863. .then(function(contents) {
  864. var template = angular.element(contents);
  865. var newElm = $compile(template)($scope);
  866. $elm.append(newElm);
  867. });
  868. },
  869. post: function($scope, $elm, $attrs, uiGridCtrl) {
  870. $elm.bind('$destroy', function() {
  871. // scrollUnbinder();
  872. });
  873. }
  874. };
  875. }
  876. };
  877. }]);
  878. })();
  879. (function() {
  880. 'use strict';
  881. angular.module('ui.grid').directive('uiGridHeaderCell', ['$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', 'ScrollEvent', 'i18nService', 'uiGridGridMenuService',
  882. function($compile, $timeout, $window, $document, gridUtil, uiGridConstants, ScrollEvent, i18nService, uiGridGridMenuService) {
  883. // Do stuff after mouse has been down this many ms on the header cell
  884. var mousedownTimeout = 500;
  885. var changeModeTimeout = 500; // length of time between a touch event and a mouse event being recognised again, and vice versa
  886. var uiGridHeaderCell = {
  887. priority: 0,
  888. scope: {
  889. col: '=',
  890. row: '=',
  891. renderIndex: '='
  892. },
  893. require: ['^uiGrid', '^uiGridRenderContainer'],
  894. replace: true,
  895. compile: function() {
  896. return {
  897. pre: function($scope, $elm, $attrs) {
  898. var cellHeader = $compile($scope.col.headerCellTemplate)($scope);
  899. $elm.append(cellHeader);
  900. },
  901. post: function($scope, $elm, $attrs, controllers) {
  902. var uiGridCtrl = controllers[0];
  903. var renderContainerCtrl = controllers[1];
  904. $scope.i18n = {
  905. headerCell: i18nService.getSafeText('headerCell'),
  906. sort: i18nService.getSafeText('sort')
  907. };
  908. $scope.getSortDirectionAriaLabel = function() {
  909. var col = $scope.col;
  910. //Trying to recreate this sort of thing but it was getting messy having it in the template.
  911. //Sort direction {{col.sort.direction == asc ? 'ascending' : ( col.sort.direction == desc ? 'descending':'none')}}. {{col.sort.priority ? {{columnPriorityText}} {{col.sort.priority}} : ''}
  912. var sortDirectionText = col.sort.direction === uiGridConstants.ASC ? $scope.i18n.sort.ascending : (col.sort.direction === uiGridConstants.DESC ? $scope.i18n.sort.descending : $scope.i18n.sort.none);
  913. var label = sortDirectionText;
  914. //Append the priority if it exists
  915. if (col.sort.priority) {
  916. label = label + '. ' + $scope.i18n.headerCell.priority + ' ' + col.sort.priority;
  917. }
  918. return label;
  919. };
  920. $scope.grid = uiGridCtrl.grid;
  921. $scope.renderContainer = uiGridCtrl.grid.renderContainers[renderContainerCtrl.containerId];
  922. var initColClass = $scope.col.getColClass(false);
  923. $elm.addClass(initColClass);
  924. // Hide the menu by default
  925. $scope.menuShown = false;
  926. // Put asc and desc sort directions in scope
  927. $scope.asc = uiGridConstants.ASC;
  928. $scope.desc = uiGridConstants.DESC;
  929. // Store a reference to menu element
  930. var $colMenu = angular.element($elm[0].querySelectorAll('.ui-grid-header-cell-menu'));
  931. var $contentsElm = angular.element($elm[0].querySelectorAll('.ui-grid-cell-contents'));
  932. // apply any headerCellClass
  933. var classAdded;
  934. var previousMouseX;
  935. // filter watchers
  936. var filterDeregisters = [];
  937. /*
  938. * Our basic approach here for event handlers is that we listen for a down event (mousedown or touchstart).
  939. * Once we have a down event, we need to work out whether we have a click, a drag, or a
  940. * hold. A click would sort the grid (if sortable). A drag would be used by moveable, so
  941. * we ignore it. A hold would open the menu.
  942. *
  943. * So, on down event, we put in place handlers for move and up events, and a timer. If the
  944. * timer expires before we see a move or up, then we have a long press and hence a column menu open.
  945. * If the up happens before the timer, then we have a click, and we sort if the column is sortable.
  946. * If a move happens before the timer, then we are doing column move, so we do nothing, the moveable feature
  947. * will handle it.
  948. *
  949. * To deal with touch enabled devices that also have mice, we only create our handlers when
  950. * we get the down event, and we create the corresponding handlers - if we're touchstart then
  951. * we get touchmove and touchend, if we're mousedown then we get mousemove and mouseup.
  952. *
  953. * We also suppress the click action whilst this is happening - otherwise after the mouseup there
  954. * will be a click event and that can cause the column menu to close
  955. *
  956. */
  957. $scope.downFn = function(event) {
  958. event.stopPropagation();
  959. if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) {
  960. event = event.originalEvent;
  961. }
  962. // Don't show the menu if it's not the left button
  963. if (event.button && event.button !== 0) {
  964. return;
  965. }
  966. previousMouseX = event.pageX;
  967. $scope.mousedownStartTime = (new Date()).getTime();
  968. $scope.mousedownTimeout = $timeout(function() {}, mousedownTimeout);
  969. $scope.mousedownTimeout.then(function() {
  970. if ($scope.colMenu) {
  971. uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm, event);
  972. }
  973. });
  974. uiGridCtrl.fireEvent(uiGridConstants.events.COLUMN_HEADER_CLICK, { event: event, columnName: $scope.col.colDef.name });
  975. $scope.offAllEvents();
  976. if (event.type === 'touchstart') {
  977. $document.on('touchend', $scope.upFn);
  978. $document.on('touchmove', $scope.moveFn);
  979. } else if (event.type === 'mousedown') {
  980. $document.on('mouseup', $scope.upFn);
  981. $document.on('mousemove', $scope.moveFn);
  982. }
  983. };
  984. $scope.upFn = function(event) {
  985. event.stopPropagation();
  986. $timeout.cancel($scope.mousedownTimeout);
  987. $scope.offAllEvents();
  988. $scope.onDownEvents(event.type);
  989. var mousedownEndTime = (new Date()).getTime();
  990. var mousedownTime = mousedownEndTime - $scope.mousedownStartTime;
  991. if (mousedownTime > mousedownTimeout) {
  992. // long click, handled above with mousedown
  993. } else {
  994. // short click
  995. if ($scope.sortable) {
  996. $scope.handleClick(event);
  997. }
  998. }
  999. };
  1000. $scope.moveFn = function(event) {
  1001. // Chrome is known to fire some bogus move events.
  1002. var changeValue = event.pageX - previousMouseX;
  1003. if (changeValue === 0) { return; }
  1004. // we're a move, so do nothing and leave for column move (if enabled) to take over
  1005. $timeout.cancel($scope.mousedownTimeout);
  1006. $scope.offAllEvents();
  1007. $scope.onDownEvents(event.type);
  1008. };
  1009. $scope.clickFn = function(event) {
  1010. event.stopPropagation();
  1011. $contentsElm.off('click', $scope.clickFn);
  1012. };
  1013. $scope.offAllEvents = function() {
  1014. $contentsElm.off('touchstart', $scope.downFn);
  1015. $contentsElm.off('mousedown', $scope.downFn);
  1016. $document.off('touchend', $scope.upFn);
  1017. $document.off('mouseup', $scope.upFn);
  1018. $document.off('touchmove', $scope.moveFn);
  1019. $document.off('mousemove', $scope.moveFn);
  1020. $contentsElm.off('click', $scope.clickFn);
  1021. };
  1022. $scope.onDownEvents = function(type) {
  1023. // If there is a previous event, then wait a while before
  1024. // activating the other mode - i.e. if the last event was a touch event then
  1025. // don't enable mouse events for a wee while (500ms or so)
  1026. // Avoids problems with devices that emulate mouse events when you have touch events
  1027. switch (type) {
  1028. case 'touchmove':
  1029. case 'touchend':
  1030. $contentsElm.on('click', $scope.clickFn);
  1031. $contentsElm.on('touchstart', $scope.downFn);
  1032. $timeout(function() {
  1033. $contentsElm.on('mousedown', $scope.downFn);
  1034. }, changeModeTimeout);
  1035. break;
  1036. case 'mousemove':
  1037. case 'mouseup':
  1038. $contentsElm.on('click', $scope.clickFn);
  1039. $contentsElm.on('mousedown', $scope.downFn);
  1040. $timeout(function() {
  1041. $contentsElm.on('touchstart', $scope.downFn);
  1042. }, changeModeTimeout);
  1043. break;
  1044. default:
  1045. $contentsElm.on('click', $scope.clickFn);
  1046. $contentsElm.on('touchstart', $scope.downFn);
  1047. $contentsElm.on('mousedown', $scope.downFn);
  1048. }
  1049. };
  1050. var updateHeaderOptions = function(grid) {
  1051. var contents = $elm;
  1052. if (classAdded) {
  1053. contents.removeClass(classAdded);
  1054. classAdded = null;
  1055. }
  1056. if (angular.isFunction($scope.col.headerCellClass)) {
  1057. classAdded = $scope.col.headerCellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex);
  1058. } else {
  1059. classAdded = $scope.col.headerCellClass;
  1060. }
  1061. contents.addClass(classAdded);
  1062. var rightMostContainer = $scope.grid.renderContainers['right'] ? $scope.grid.renderContainers['right'] : $scope.grid.renderContainers['body'];
  1063. $scope.isLastCol = ($scope.col === rightMostContainer.visibleColumnCache[rightMostContainer.visibleColumnCache.length - 1]);
  1064. // Figure out whether this column is sortable or not
  1065. if (uiGridCtrl.grid.options.enableSorting && $scope.col.enableSorting) {
  1066. $scope.sortable = true;
  1067. } else {
  1068. $scope.sortable = false;
  1069. }
  1070. // Figure out whether this column is filterable or not
  1071. var oldFilterable = $scope.filterable;
  1072. if (uiGridCtrl.grid.options.enableFiltering && $scope.col.enableFiltering) {
  1073. $scope.filterable = true;
  1074. } else {
  1075. $scope.filterable = false;
  1076. }
  1077. if (oldFilterable !== $scope.filterable) {
  1078. if (typeof($scope.col.updateFilters) !== 'undefined') {
  1079. $scope.col.updateFilters($scope.filterable);
  1080. }
  1081. // if column is filterable add a filter watcher
  1082. if ($scope.filterable) {
  1083. $scope.col.filters.forEach(function(filter, i) {
  1084. filterDeregisters.push($scope.$watch('col.filters[' + i + '].term', function(n, o) {
  1085. if (n !== o) {
  1086. uiGridCtrl.grid.api.core.raise.filterChanged();
  1087. uiGridCtrl.grid.api.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
  1088. uiGridCtrl.grid.queueGridRefresh();
  1089. }
  1090. }));
  1091. });
  1092. $scope.$on('$destroy', function() {
  1093. filterDeregisters.forEach(function(filterDeregister) {
  1094. filterDeregister();
  1095. });
  1096. });
  1097. } else {
  1098. filterDeregisters.forEach(function(filterDeregister) {
  1099. filterDeregister();
  1100. });
  1101. }
  1102. }
  1103. // figure out whether we support column menus
  1104. if ($scope.col.grid.options && $scope.col.grid.options.enableColumnMenus !== false &&
  1105. $scope.col.colDef && $scope.col.colDef.enableColumnMenu !== false) {
  1106. $scope.colMenu = true;
  1107. } else {
  1108. $scope.colMenu = false;
  1109. }
  1110. /**
  1111. * @ngdoc property
  1112. * @name enableColumnMenu
  1113. * @propertyOf ui.grid.class:GridOptions.columnDef
  1114. * @description if column menus are enabled, controls the column menus for this specific
  1115. * column (i.e. if gridOptions.enableColumnMenus, then you can control column menus
  1116. * using this option. If gridOptions.enableColumnMenus === false then you get no column
  1117. * menus irrespective of the value of this option ). Defaults to true.
  1118. *
  1119. */
  1120. /**
  1121. * @ngdoc property
  1122. * @name enableColumnMenus
  1123. * @propertyOf ui.grid.class:GridOptions.columnDef
  1124. * @description Override for column menus everywhere - if set to false then you get no
  1125. * column menus. Defaults to true.
  1126. *
  1127. */
  1128. $scope.offAllEvents();
  1129. if ($scope.sortable || $scope.colMenu) {
  1130. $scope.onDownEvents();
  1131. $scope.$on('$destroy', function() {
  1132. $scope.offAllEvents();
  1133. });
  1134. }
  1135. };
  1136. /*
  1137. $scope.$watch('col', function (n, o) {
  1138. if (n !== o) {
  1139. // See if the column's internal class has changed
  1140. var newColClass = $scope.col.getColClass(false);
  1141. if (newColClass !== initColClass) {
  1142. $elm.removeClass(initColClass);
  1143. $elm.addClass(newColClass);
  1144. initColClass = newColClass;
  1145. }
  1146. }
  1147. });
  1148. */
  1149. updateHeaderOptions();
  1150. // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs
  1151. var dataChangeDereg = $scope.grid.registerDataChangeCallback(updateHeaderOptions, [uiGridConstants.dataChange.COLUMN]);
  1152. $scope.$on('$destroy', dataChangeDereg);
  1153. $scope.handleClick = function(event) {
  1154. // If the shift key is being held down, add this column to the sort
  1155. var add = false;
  1156. if (event.shiftKey) {
  1157. add = true;
  1158. }
  1159. // Sort this column then rebuild the grid's rows
  1160. uiGridCtrl.grid.sortColumn($scope.col, add)
  1161. .then(function() {
  1162. if (uiGridCtrl.columnMenuScope) { uiGridCtrl.columnMenuScope.hideMenu(); }
  1163. uiGridCtrl.grid.refresh();
  1164. });
  1165. };
  1166. $scope.decrement = function() {
  1167. if ($scope.shown) {
  1168. $scope.$broadcast('hide-menu');
  1169. $scope.shown = false;
  1170. } else {
  1171. console.log($scope.menuItems)
  1172. $scope.menuItems = uiGridGridMenuService.getMenuItems($scope);
  1173. $scope.$broadcast('show-menu');
  1174. $scope.shown = true;
  1175. }
  1176. };
  1177. $scope.toggleMenu = function(event) {
  1178. event.stopPropagation();
  1179. // If the menu is already showing...
  1180. if (uiGridCtrl.columnMenuScope.menuShown) {
  1181. // ... and we're the column the menu is on...
  1182. if (uiGridCtrl.columnMenuScope.col === $scope.col) {
  1183. // ... hide it
  1184. uiGridCtrl.columnMenuScope.hideMenu();
  1185. }
  1186. // ... and we're NOT the column the menu is on
  1187. else {
  1188. // ... move the menu to our column
  1189. uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);
  1190. }
  1191. }
  1192. // If the menu is NOT showing
  1193. else {
  1194. // ... show it on our column
  1195. uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);
  1196. }
  1197. };
  1198. }
  1199. };
  1200. }
  1201. };
  1202. return uiGridHeaderCell;
  1203. }
  1204. ]);
  1205. })();
  1206. (function() {
  1207. 'use strict';
  1208. angular.module('ui.grid').directive('uiGridHeader', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', 'ScrollEvent',
  1209. function($templateCache, $compile, uiGridConstants, gridUtil, $timeout, ScrollEvent) {
  1210. var defaultTemplate = 'ui-grid/ui-grid-header';
  1211. var emptyTemplate = 'ui-grid/ui-grid-no-header';
  1212. return {
  1213. restrict: 'EA',
  1214. // templateUrl: 'ui-grid/ui-grid-header',
  1215. replace: true,
  1216. // priority: 1000,
  1217. require: ['^uiGrid', '^uiGridRenderContainer'],
  1218. scope: true,
  1219. compile: function($elm, $attrs) {
  1220. return {
  1221. pre: function($scope, $elm, $attrs, controllers) {
  1222. var uiGridCtrl = controllers[0];
  1223. var containerCtrl = controllers[1];
  1224. $scope.grid = uiGridCtrl.grid;
  1225. $scope.colContainer = containerCtrl.colContainer;
  1226. updateHeaderReferences();
  1227. var headerTemplate;
  1228. if (!$scope.grid.options.showHeader) {
  1229. headerTemplate = emptyTemplate;
  1230. } else {
  1231. headerTemplate = ($scope.grid.options.headerTemplate) ? $scope.grid.options.headerTemplate : defaultTemplate;
  1232. }
  1233. gridUtil.getTemplate(headerTemplate)
  1234. .then(function(contents) {
  1235. var template = angular.element(contents);
  1236. var newElm = $compile(template)($scope);
  1237. $elm.replaceWith(newElm);
  1238. // And update $elm to be the new element
  1239. $elm = newElm;
  1240. updateHeaderReferences();
  1241. if (containerCtrl) {
  1242. // Inject a reference to the header viewport (if it exists) into the grid controller for use in the horizontal scroll handler below
  1243. var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0];
  1244. if (headerViewport) {
  1245. containerCtrl.headerViewport = headerViewport;
  1246. angular.element(headerViewport).on('scroll', scrollHandler);
  1247. $scope.$on('$destroy', function() {
  1248. angular.element(headerViewport).off('scroll', scrollHandler);
  1249. });
  1250. }
  1251. }
  1252. $scope.grid.queueRefresh();
  1253. });
  1254. function updateHeaderReferences() {
  1255. containerCtrl.header = containerCtrl.colContainer.header = $elm;
  1256. var headerCanvases = $elm[0].getElementsByClassName('ui-grid-header-canvas');
  1257. if (headerCanvases.length > 0) {
  1258. containerCtrl.headerCanvas = containerCtrl.colContainer.headerCanvas = headerCanvases[0];
  1259. } else {
  1260. containerCtrl.headerCanvas = null;
  1261. }
  1262. }
  1263. function scrollHandler(evt) {
  1264. if (uiGridCtrl.grid.isScrollingHorizontally) {
  1265. return;
  1266. }
  1267. var newScrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.headerViewport, uiGridCtrl.grid);
  1268. var horizScrollPercentage = containerCtrl.colContainer.scrollHorizontal(newScrollLeft);
  1269. var scrollEvent = new ScrollEvent(uiGridCtrl.grid, null, containerCtrl.colContainer, ScrollEvent.Sources.ViewPortScroll);
  1270. scrollEvent.newScrollLeft = newScrollLeft;
  1271. if (horizScrollPercentage > -1) {
  1272. scrollEvent.x = { percentage: horizScrollPercentage };
  1273. }
  1274. uiGridCtrl.grid.scrollContainers(null, scrollEvent);
  1275. }
  1276. },
  1277. post: function($scope, $elm, $attrs, controllers) {
  1278. var uiGridCtrl = controllers[0];
  1279. var containerCtrl = controllers[1];
  1280. // gridUtil.logDebug('ui-grid-header link');
  1281. var grid = uiGridCtrl.grid;
  1282. // Don't animate header cells
  1283. gridUtil.disableAnimations($elm);
  1284. function updateColumnWidths() {
  1285. // this styleBuilder always runs after the renderContainer, so we can rely on the column widths
  1286. // already being populated correctly
  1287. var columnCache = containerCtrl.colContainer.visibleColumnCache;
  1288. // Build the CSS
  1289. // uiGridCtrl.grid.columns.forEach(function (column) {
  1290. var ret = '';
  1291. var canvasWidth = 0;
  1292. columnCache.forEach(function(column) {
  1293. ret = ret + column.getColClassDefinition();
  1294. canvasWidth += column.drawnWidth;
  1295. });
  1296. containerCtrl.colContainer.canvasWidth = canvasWidth;
  1297. // Return the styles back to buildStyles which pops them into the `customStyles` scope variable
  1298. return ret;
  1299. }
  1300. containerCtrl.header = $elm;
  1301. var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0];
  1302. if (headerViewport) {
  1303. containerCtrl.headerViewport = headerViewport;
  1304. }
  1305. //todo: remove this if by injecting gridCtrl into unit tests
  1306. if (uiGridCtrl) {
  1307. uiGridCtrl.grid.registerStyleComputation({
  1308. priority: 15,
  1309. func: updateColumnWidths
  1310. });
  1311. }
  1312. }
  1313. };
  1314. }
  1315. };
  1316. }
  1317. ]);
  1318. })();
  1319. (function() {
  1320. angular.module('ui.grid')
  1321. .service('uiGridGridMenuService', ['gridUtil', 'i18nService', 'uiGridConstants', function(gridUtil, i18nService, uiGridConstants) {
  1322. /**
  1323. * @ngdoc service
  1324. * @name ui.grid.gridMenuService
  1325. *
  1326. * @description Methods for working with the grid menu
  1327. */
  1328. var service = {
  1329. /**
  1330. * @ngdoc method
  1331. * @methodOf ui.grid.gridMenuService
  1332. * @name initialize
  1333. * @description Sets up the gridMenu. Most importantly, sets our
  1334. * scope onto the grid object as grid.gridMenuScope, allowing us
  1335. * to operate when passed only the grid. Second most importantly,
  1336. * we register the 'addToGridMenu' and 'removeFromGridMenu' methods
  1337. * on the core api.
  1338. * @param {$scope} $scope the scope of this gridMenu
  1339. * @param {Grid} grid the grid to which this gridMenu is associated
  1340. */
  1341. initialize: function($scope, grid) {
  1342. grid.gridMenuScope = $scope;
  1343. $scope.grid = grid;
  1344. $scope.registeredMenuItems = [];
  1345. // not certain this is needed, but would be bad to create a memory leak
  1346. $scope.$on('$destroy', function() {
  1347. if ($scope.grid && $scope.grid.gridMenuScope) {
  1348. $scope.grid.gridMenuScope = null;
  1349. }
  1350. if ($scope.grid) {
  1351. $scope.grid = null;
  1352. }
  1353. if ($scope.registeredMenuItems) {
  1354. $scope.registeredMenuItems = null;
  1355. }
  1356. });
  1357. $scope.registeredMenuItems = [];
  1358. /**
  1359. * @ngdoc function
  1360. * @name addToGridMenu
  1361. * @methodOf ui.grid.core.api:PublicApi
  1362. * @description add items to the grid menu. Used by features
  1363. * to add their menu items if they are enabled, can also be used by
  1364. * end users to add menu items. This method has the advantage of allowing
  1365. * remove again, which can simplify management of which items are included
  1366. * in the menu when. (Noting that in most cases the shown and active functions
  1367. * provide a better way to handle visibility of menu items)
  1368. * @param {Grid} grid the grid on which we are acting
  1369. * @param {array} items menu items in the format as described in the tutorial, with
  1370. * the added note that if you want to use remove you must also specify an `id` field,
  1371. * which is provided when you want to remove an item. The id should be unique.
  1372. *
  1373. */
  1374. grid.api.registerMethod('core', 'addToGridMenu', service.addToGridMenu);
  1375. /**
  1376. * @ngdoc function
  1377. * @name removeFromGridMenu
  1378. * @methodOf ui.grid.core.api:PublicApi
  1379. * @description Remove an item from the grid menu based on a provided id. Assumes
  1380. * that the id is unique, removes only the last instance of that id. Does nothing if
  1381. * the specified id is not found
  1382. * @param {Grid} grid the grid on which we are acting
  1383. * @param {string} id the id we'd like to remove from the menu
  1384. *
  1385. */
  1386. grid.api.registerMethod('core', 'removeFromGridMenu', service.removeFromGridMenu);
  1387. },
  1388. /**
  1389. * @ngdoc function
  1390. * @name addToGridMenu
  1391. * @propertyOf ui.grid.gridMenuService
  1392. * @description add items to the grid menu. Used by features
  1393. * to add their menu items if they are enabled, can also be used by
  1394. * end users to add menu items. This method has the advantage of allowing
  1395. * remove again, which can simplify management of which items are included
  1396. * in the menu when. (Noting that in most cases the shown and active functions
  1397. * provide a better way to handle visibility of menu items)
  1398. * @param {Grid} grid the grid on which we are acting
  1399. * @param {array} items menu items in the format as described in the tutorial, with
  1400. * the added note that if you want to use remove you must also specify an `id` field,
  1401. * which is provided when you want to remove an item. The id should be unique.
  1402. *
  1403. */
  1404. addToGridMenu: function(grid, menuItems) {
  1405. if (!angular.isArray(menuItems)) {
  1406. gridUtil.logError('addToGridMenu: menuItems must be an array, and is not, not adding any items');
  1407. } else {
  1408. if (grid.gridMenuScope) {
  1409. grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems ? grid.gridMenuScope.registeredMenuItems : [];
  1410. grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems.concat(menuItems);
  1411. } else {
  1412. gridUtil.logError('Asked to addToGridMenu, but gridMenuScope not present. Timing issue? Please log issue with ui-grid');
  1413. }
  1414. }
  1415. },
  1416. /**
  1417. * @ngdoc function
  1418. * @name removeFromGridMenu
  1419. * @methodOf ui.grid.gridMenuService
  1420. * @description Remove an item from the grid menu based on a provided id. Assumes
  1421. * that the id is unique, removes only the last instance of that id. Does nothing if
  1422. * the specified id is not found. If there is no gridMenuScope or registeredMenuItems
  1423. * then do nothing silently - the desired result is those menu items not be present and they
  1424. * aren't.
  1425. * @param {Grid} grid the grid on which we are acting
  1426. * @param {string} id the id we'd like to remove from the menu
  1427. *
  1428. */
  1429. removeFromGridMenu: function(grid, id) {
  1430. var foundIndex = -1;
  1431. if (grid && grid.gridMenuScope) {
  1432. grid.gridMenuScope.registeredMenuItems.forEach(function(value, index) {
  1433. if (value.id === id) {
  1434. if (foundIndex > -1) {
  1435. gridUtil.logError('removeFromGridMenu: found multiple items with the same id, removing only the last');
  1436. } else {
  1437. foundIndex = index;
  1438. }
  1439. }
  1440. });
  1441. }
  1442. if (foundIndex > -1) {
  1443. grid.gridMenuScope.registeredMenuItems.splice(foundIndex, 1);
  1444. }
  1445. },
  1446. /**
  1447. * @ngdoc array
  1448. * @name gridMenuCustomItems
  1449. * @propertyOf ui.grid.class:GridOptions
  1450. * @description (optional) An array of menu items that should be added to
  1451. * the gridMenu. Follow the format documented in the tutorial for column
  1452. * menu customisation. The context provided to the action function will
  1453. * include context.grid. An alternative if working with dynamic menus is to use the
  1454. * provided api - core.addToGridMenu and core.removeFromGridMenu, which handles
  1455. * some of the management of items for you.
  1456. *
  1457. */
  1458. /**
  1459. * @ngdoc boolean
  1460. * @name gridMenuShowHideColumns
  1461. * @propertyOf ui.grid.class:GridOptions
  1462. * @description true by default, whether the grid menu should allow hide/show
  1463. * of columns
  1464. *
  1465. */
  1466. /**
  1467. * @ngdoc method
  1468. * @methodOf ui.grid.gridMenuService
  1469. * @name getMenuItems
  1470. * @description Decides the menu items to show in the menu. This is a
  1471. * combination of:
  1472. *
  1473. * - the default menu items that are always included,
  1474. * - any menu items that have been provided through the addMenuItem api. These
  1475. * are typically added by features within the grid
  1476. * - any menu items included in grid.options.gridMenuCustomItems. These can be
  1477. * changed dynamically, as they're always recalculated whenever we show the
  1478. * menu
  1479. * @param {$scope} $scope the scope of this gridMenu, from which we can find all
  1480. * the information that we need
  1481. * @returns {array} an array of menu items that can be shown
  1482. */
  1483. getMenuItems: function($scope) {
  1484. var menuItems = [
  1485. // this is where we add any menu items we want to always include
  1486. ];
  1487. if ($scope.grid.options.gridMenuCustomItems) {
  1488. if (!angular.isArray($scope.grid.options.gridMenuCustomItems)) {
  1489. gridUtil.logError('gridOptions.gridMenuCustomItems must be an array, and is not');
  1490. } else {
  1491. menuItems = menuItems.concat($scope.grid.options.gridMenuCustomItems);
  1492. }
  1493. }
  1494. var clearFilters = [{
  1495. title: i18nService.getSafeText('gridMenu.clearAllFilters'),
  1496. action: function($event) {
  1497. $scope.grid.clearAllFilters(undefined, true, undefined);
  1498. },
  1499. shown: function() {
  1500. return $scope.grid.options.enableFiltering;
  1501. },
  1502. order: 100
  1503. }];
  1504. menuItems = menuItems.concat(clearFilters);
  1505. menuItems = menuItems.concat($scope.registeredMenuItems);
  1506. if ($scope.grid.options.gridMenuShowHideColumns !== false) {
  1507. menuItems = menuItems.concat(service.showHideColumns($scope));
  1508. }
  1509. menuItems.sort(function(a, b) {
  1510. return a.order - b.order;
  1511. });
  1512. return menuItems;
  1513. },
  1514. /**
  1515. * @ngdoc array
  1516. * @name gridMenuTitleFilter
  1517. * @propertyOf ui.grid.class:GridOptions
  1518. * @description (optional) A function that takes a title string
  1519. * (usually the col.displayName), and converts it into a display value. The function
  1520. * must return either a string or a promise.
  1521. *
  1522. * Used for internationalization of the grid menu column names - for angular-translate
  1523. * you can pass $translate as the function, for i18nService you can pass getSafeText as the
  1524. * function
  1525. * @example
  1526. * <pre>
  1527. * gridOptions = {
  1528. * gridMenuTitleFilter: $translate
  1529. * }
  1530. * </pre>
  1531. */
  1532. /**
  1533. * @ngdoc method
  1534. * @methodOf ui.grid.gridMenuService
  1535. * @name showHideColumns
  1536. * @description Adds two menu items for each of the columns in columnDefs. One
  1537. * menu item for hide, one menu item for show. Each is visible when appropriate
  1538. * (show when column is not visible, hide when column is visible). Each toggles
  1539. * the visible property on the columnDef using toggleColumnVisibility
  1540. * @param {$scope} $scope of a gridMenu, which contains a reference to the grid
  1541. */
  1542. showHideColumns: function($scope) {
  1543. var showHideColumns = [];
  1544. if (!$scope.grid.options.columnDefs || $scope.grid.options.columnDefs.length === 0 || $scope.grid.columns.length === 0) {
  1545. return showHideColumns;
  1546. }
  1547. // add header for columns
  1548. showHideColumns.push({
  1549. title: i18nService.getSafeText('gridMenu.columns'),
  1550. order: 300
  1551. });
  1552. $scope.grid.options.gridMenuTitleFilter = $scope.grid.options.gridMenuTitleFilter ? $scope.grid.options.gridMenuTitleFilter : function(title) { return title; };
  1553. $scope.grid.options.columnDefs.forEach(function(colDef, index) {
  1554. if (colDef.enableHiding !== false) {
  1555. // add hide menu item - shows an OK icon as we only show when column is already visible
  1556. var menuItem = {
  1557. icon: 'ui-grid-icon-ok',
  1558. action: function($event) {
  1559. $event.stopPropagation();
  1560. service.toggleColumnVisibility(this.context.gridCol);
  1561. },
  1562. shown: function() {
  1563. return this.context.gridCol.colDef.visible === true || this.context.gridCol.colDef.visible === undefined;
  1564. },
  1565. context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) },
  1566. leaveOpen: true,
  1567. order: 301 + index * 2
  1568. };
  1569. service.setMenuItemTitle(menuItem, colDef, $scope.grid);
  1570. showHideColumns.push(menuItem);
  1571. // add show menu item - shows no icon as we only show when column is invisible
  1572. menuItem = {
  1573. icon: 'ui-grid-icon-cancel',
  1574. action: function($event) {
  1575. $event.stopPropagation();
  1576. service.toggleColumnVisibility(this.context.gridCol);
  1577. },
  1578. shown: function() {
  1579. return !(this.context.gridCol.colDef.visible === true || this.context.gridCol.colDef.visible === undefined);
  1580. },
  1581. context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) },
  1582. leaveOpen: true,
  1583. order: 301 + index * 2 + 1
  1584. };
  1585. service.setMenuItemTitle(menuItem, colDef, $scope.grid);
  1586. showHideColumns.push(menuItem);
  1587. }
  1588. });
  1589. return showHideColumns;
  1590. },
  1591. /**
  1592. * @ngdoc method
  1593. * @methodOf ui.grid.gridMenuService
  1594. * @name setMenuItemTitle
  1595. * @description Handles the response from gridMenuTitleFilter, adding it directly to the menu
  1596. * item if it returns a string, otherwise waiting for the promise to resolve or reject then
  1597. * putting the result into the title
  1598. * @param {object} menuItem the menuItem we want to put the title on
  1599. * @param {object} colDef the colDef from which we can get displayName, name or field
  1600. * @param {Grid} grid the grid, from which we can get the options.gridMenuTitleFilter
  1601. *
  1602. */
  1603. setMenuItemTitle: function(menuItem, colDef, grid) {
  1604. var title = grid.options.gridMenuTitleFilter(colDef.displayName || gridUtil.readableColumnName(colDef.name) || colDef.field);
  1605. if (typeof(title) === 'string') {
  1606. menuItem.title = title;
  1607. } else if (title.then) {
  1608. // must be a promise
  1609. menuItem.title = "";
  1610. title.then(function(successValue) {
  1611. menuItem.title = successValue;
  1612. }, function(errorValue) {
  1613. menuItem.title = errorValue;
  1614. });
  1615. } else {
  1616. gridUtil.logError('Expected gridMenuTitleFilter to return a string or a promise, it has returned neither, bad config');
  1617. menuItem.title = 'badconfig';
  1618. }
  1619. },
  1620. /**
  1621. * @ngdoc method
  1622. * @methodOf ui.grid.gridMenuService
  1623. * @name toggleColumnVisibility
  1624. * @description Toggles the visibility of an individual column. Expects to be
  1625. * provided a context that has on it a gridColumn, which is the column that
  1626. * we'll operate upon. We change the visibility, and refresh the grid as appropriate
  1627. * @param {GridCol} gridCol the column that we want to toggle
  1628. *
  1629. */
  1630. toggleColumnVisibility: function(gridCol) {
  1631. gridCol.colDef.visible = !(gridCol.colDef.visible === true || gridCol.colDef.visible === undefined);
  1632. gridCol.grid.refresh();
  1633. gridCol.grid.api.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
  1634. gridCol.grid.api.core.raise.columnVisibilityChanged(gridCol);
  1635. }
  1636. };
  1637. return service;
  1638. }])
  1639. .directive('uiGridMenuButton', ['gridUtil', 'uiGridConstants', 'uiGridGridMenuService', 'i18nService',
  1640. function(gridUtil, uiGridConstants, uiGridGridMenuService, i18nService) {
  1641. return {
  1642. priority: 0,
  1643. scope: true,
  1644. require: ['^uiGrid'],
  1645. templateUrl: 'ui-grid/ui-grid-menu-button',
  1646. replace: true,
  1647. link: function($scope, $elm, $attrs, controllers) {
  1648. var uiGridCtrl = controllers[0];
  1649. // For the aria label
  1650. $scope.i18n = {
  1651. aria: i18nService.getSafeText('gridMenu.aria')
  1652. };
  1653. uiGridGridMenuService.initialize($scope, uiGridCtrl.grid);
  1654. $scope.shown = false;
  1655. // $scope.decrement = function () {
  1656. // if ( $scope.shown ){
  1657. // $scope.$broadcast('hide-menu');
  1658. // $scope.shown = false;
  1659. // } else {
  1660. // console.log($scope.menuItems)
  1661. // // $scope.menuItems = uiGridGridMenuService.getMenuItems( $scope );
  1662. // $scope.$broadcast('show-menu');
  1663. // $scope.shown = true;
  1664. // }
  1665. // };
  1666. $scope.toggleMenu = function() {
  1667. if ($scope.shown) {
  1668. $scope.$broadcast('hide-menu');
  1669. $scope.shown = false;
  1670. } else {
  1671. $scope.menuItems = uiGridGridMenuService.getMenuItems($scope);
  1672. $scope.$broadcast('show-menu');
  1673. $scope.shown = true;
  1674. }
  1675. };
  1676. $scope.$on('menu-hidden', function() {
  1677. $scope.shown = false;
  1678. gridUtil.focus.bySelector($elm, '.ui-grid-icon-container');
  1679. });
  1680. }
  1681. };
  1682. }
  1683. ]);
  1684. })();
  1685. (function() {
  1686. /**
  1687. * @ngdoc directive
  1688. * @name ui.grid.directive:uiGridMenu
  1689. * @element style
  1690. * @restrict A
  1691. *
  1692. * @description
  1693. * Allows us to interpolate expressions in `<style>` elements. Angular doesn't do this by default as it can/will/might? break in IE8.
  1694. *
  1695. * @example
  1696. <doc:example module="app">
  1697. <doc:source>
  1698. <script>
  1699. var app = angular.module('app', ['ui.grid']);
  1700. app.controller('MainCtrl', ['$scope', function ($scope) {
  1701. }]);
  1702. </script>
  1703. <div ng-controller="MainCtrl">
  1704. <div ui-grid-menu shown="true" ></div>
  1705. </div>
  1706. </doc:source>
  1707. <doc:scenario>
  1708. </doc:scenario>
  1709. </doc:example>
  1710. */
  1711. angular.module('ui.grid')
  1712. .directive('uiGridMenu', ['$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', 'i18nService',
  1713. function($compile, $timeout, $window, $document, gridUtil, uiGridConstants, i18nService) {
  1714. var uiGridMenu = {
  1715. priority: 0,
  1716. scope: {
  1717. // shown: '&',
  1718. menuItems: '=',
  1719. autoHide: '=?'
  1720. },
  1721. require: '?^uiGrid',
  1722. templateUrl: 'ui-grid/uiGridMenu',
  1723. replace: false,
  1724. link: function($scope, $elm, $attrs, uiGridCtrl) {
  1725. var self = this;
  1726. var menuMid;
  1727. var $animate;
  1728. $scope.i18n = {
  1729. close: i18nService.getSafeText('columnMenu.close')
  1730. };
  1731. // *** Show/Hide functions ******
  1732. self.showMenu = $scope.showMenu = function(event, args) {
  1733. if (!$scope.shown) {
  1734. /*
  1735. * In order to animate cleanly we remove the ng-if, wait a digest cycle, then
  1736. * animate the removal of the ng-hide. We can't successfully (so far as I can tell)
  1737. * animate removal of the ng-if, as the menu items aren't there yet. And we don't want
  1738. * to rely on ng-show only, as that leaves elements in the DOM that are needlessly evaluated
  1739. * on scroll events.
  1740. *
  1741. * Note when testing animation that animations don't run on the tutorials. When debugging it looks
  1742. * like they do, but angular has a default $animate provider that is just a stub, and that's what's
  1743. * being called. ALso don't be fooled by the fact that your browser has actually loaded the
  1744. * angular-translate.js, it's not using it. You need to test animations in an external application.
  1745. */
  1746. $scope.shown = true;
  1747. $timeout(function() {
  1748. $scope.shownMid = true;
  1749. $scope.$emit('menu-shown');
  1750. });
  1751. } else if (!$scope.shownMid) {
  1752. // we're probably doing a hide then show, so we don't need to wait for ng-if
  1753. $scope.shownMid = true;
  1754. $scope.$emit('menu-shown');
  1755. }
  1756. var docEventType = 'click';
  1757. if (args && args.originalEvent && args.originalEvent.type && args.originalEvent.type === 'touchstart') {
  1758. docEventType = args.originalEvent.type;
  1759. }
  1760. // Turn off an existing document click handler
  1761. angular.element(document).off('click touchstart', applyHideMenu);
  1762. // Turn on the document click handler, but in a timeout so it doesn't apply to THIS click if there is one
  1763. $timeout(function() {
  1764. angular.element(document).on(docEventType, applyHideMenu);
  1765. });
  1766. //automatically set the focus to the first button element in the now open menu.
  1767. gridUtil.focus.bySelector($elm, 'button[type=button]', true);
  1768. };
  1769. self.hideMenu = $scope.hideMenu = function(event, args) {
  1770. if ($scope.shown) {
  1771. /*
  1772. * In order to animate cleanly we animate the addition of ng-hide, then use a $timeout to
  1773. * set the ng-if (shown = false) after the animation runs. In theory we can cascade off the
  1774. * callback on the addClass method, but it is very unreliable with unit tests for no discernable reason.
  1775. *
  1776. * The user may have clicked on the menu again whilst
  1777. * we're waiting, so we check that the mid isn't shown before applying the ng-if.
  1778. */
  1779. $scope.shownMid = false;
  1780. $timeout(function() {
  1781. if (!$scope.shownMid) {
  1782. $scope.shown = false;
  1783. $scope.$emit('menu-hidden');
  1784. }
  1785. }, 200);
  1786. }
  1787. angular.element(document).off('click touchstart', applyHideMenu);
  1788. };
  1789. $scope.$on('hide-menu', function(event, args) {
  1790. $scope.hideMenu(event, args);
  1791. });
  1792. $scope.$on('show-menu', function(event, args) {
  1793. $scope.showMenu(event, args);
  1794. });
  1795. // *** Auto hide when click elsewhere ******
  1796. var applyHideMenu = function() {
  1797. if ($scope.shown) {
  1798. $scope.$apply(function() {
  1799. $scope.hideMenu();
  1800. });
  1801. }
  1802. };
  1803. if (typeof($scope.autoHide) === 'undefined' || $scope.autoHide === undefined) {
  1804. $scope.autoHide = true;
  1805. }
  1806. if ($scope.autoHide) {
  1807. angular.element($window).on('resize', applyHideMenu);
  1808. }
  1809. $scope.$on('$destroy', function() {
  1810. angular.element(document).off('click touchstart', applyHideMenu);
  1811. });
  1812. $scope.$on('$destroy', function() {
  1813. angular.element($window).off('resize', applyHideMenu);
  1814. });
  1815. if (uiGridCtrl) {
  1816. $scope.$on('$destroy', uiGridCtrl.grid.api.core.on.scrollBegin($scope, applyHideMenu));
  1817. }
  1818. $scope.$on('$destroy', $scope.$on(uiGridConstants.events.ITEM_DRAGGING, applyHideMenu));
  1819. },
  1820. controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
  1821. var self = this;
  1822. }]
  1823. };
  1824. return uiGridMenu;
  1825. }
  1826. ])
  1827. .directive('uiGridMenuItem', ['gridUtil', '$compile', 'i18nService', function(gridUtil, $compile, i18nService) {
  1828. var uiGridMenuItem = {
  1829. priority: 0,
  1830. scope: {
  1831. name: '=',
  1832. active: '=',
  1833. action: '=',
  1834. icon: '=',
  1835. shown: '=',
  1836. context: '=',
  1837. templateUrl: '=',
  1838. leaveOpen: '=',
  1839. screenReaderOnly: '='
  1840. },
  1841. require: ['?^uiGrid', '^uiGridMenu'],
  1842. templateUrl: 'ui-grid/uiGridMenuItem',
  1843. replace: false,
  1844. compile: function($elm, $attrs) {
  1845. return {
  1846. pre: function($scope, $elm, $attrs, controllers) {
  1847. var uiGridCtrl = controllers[0],
  1848. uiGridMenuCtrl = controllers[1];
  1849. if ($scope.templateUrl) {
  1850. gridUtil.getTemplate($scope.templateUrl)
  1851. .then(function(contents) {
  1852. var template = angular.element(contents);
  1853. var newElm = $compile(template)($scope);
  1854. $elm.replaceWith(newElm);
  1855. });
  1856. }
  1857. },
  1858. post: function($scope, $elm, $attrs, controllers) {
  1859. var uiGridCtrl = controllers[0],
  1860. uiGridMenuCtrl = controllers[1];
  1861. // TODO(c0bra): validate that shown and active are functions if they're defined. An exception is already thrown above this though
  1862. // if (typeof($scope.shown) !== 'undefined' && $scope.shown && typeof($scope.shown) !== 'function') {
  1863. // throw new TypeError("$scope.shown is defined but not a function");
  1864. // }
  1865. if (typeof($scope.shown) === 'undefined' || $scope.shown === null) {
  1866. $scope.shown = function() { return true; };
  1867. }
  1868. $scope.itemShown = function() {
  1869. var context = {};
  1870. if ($scope.context) {
  1871. context.context = $scope.context;
  1872. }
  1873. if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) {
  1874. context.grid = uiGridCtrl.grid;
  1875. }
  1876. return $scope.shown.call(context);
  1877. };
  1878. $scope.itemAction = function($event, title) {
  1879. gridUtil.logDebug('itemAction');
  1880. $event.stopPropagation();
  1881. if (typeof($scope.action) === 'function') {
  1882. var context = {};
  1883. if ($scope.context) {
  1884. context.context = $scope.context;
  1885. }
  1886. // Add the grid to the function call context if the uiGrid controller is present
  1887. if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) {
  1888. context.grid = uiGridCtrl.grid;
  1889. }
  1890. $scope.action.call(context, $event, title);
  1891. if (!$scope.leaveOpen) {
  1892. $scope.$emit('hide-menu');
  1893. } else {
  1894. /*
  1895. * XXX: Fix after column refactor
  1896. * Ideally the focus would remain on the item.
  1897. * However, since there are two menu items that have their 'show' property toggled instead. This is a quick fix.
  1898. */
  1899. gridUtil.focus.bySelector(angular.element(gridUtil.closestElm($elm, ".ui-grid-menu-items")), 'button[type=button]', true);
  1900. }
  1901. }
  1902. };
  1903. $scope.i18n = i18nService.get();
  1904. }
  1905. };
  1906. }
  1907. };
  1908. return uiGridMenuItem;
  1909. }]);
  1910. })();
  1911. (function() {
  1912. 'use strict';
  1913. /**
  1914. * @ngdoc overview
  1915. * @name ui.grid.directive:uiGridOneBind
  1916. * @summary A group of directives that provide a one time bind to a dom element.
  1917. * @description A group of directives that provide a one time bind to a dom element.
  1918. * As one time bindings are not supported in Angular 1.2.* this directive provdes this capability.
  1919. * This is done to reduce the number of watchers on the dom.
  1920. * <br/>
  1921. * <h2>Short Example ({@link ui.grid.directive:uiGridOneBindSrc ui-grid-one-bind-src})</h2>
  1922. * <pre>
  1923. <div ng-init="imageName = 'myImageDir.jpg'">
  1924. <img ui-grid-one-bind-src="imageName"></img>
  1925. </div>
  1926. </pre>
  1927. * Will become:
  1928. * <pre>
  1929. <div ng-init="imageName = 'myImageDir.jpg'">
  1930. <img ui-grid-one-bind-src="imageName" src="myImageDir.jpg"></img>
  1931. </div>
  1932. </pre>
  1933. </br>
  1934. <h2>Short Example ({@link ui.grid.directive:uiGridOneBindText ui-grid-one-bind-text})</h2>
  1935. * <pre>
  1936. <div ng-init="text='Add this text'" ui-grid-one-bind-text="text"></div>
  1937. </pre>
  1938. * Will become:
  1939. * <pre>
  1940. <div ng-init="text='Add this text'" ui-grid-one-bind-text="text">Add this text</div>
  1941. </pre>
  1942. </br>
  1943. * <b>Note:</b> This behavior is slightly different for the {@link ui.grid.directive:uiGridOneBindIdGrid uiGridOneBindIdGrid}
  1944. * and {@link ui.grid.directive:uiGridOneBindAriaLabelledbyGrid uiGridOneBindAriaLabelledbyGrid} directives.
  1945. *
  1946. */
  1947. //https://github.com/joshkurz/Black-Belt-AngularJS-Directives/blob/master/directives/Optimization/oneBind.js
  1948. var oneBinders = angular.module('ui.grid');
  1949. angular.forEach([
  1950. /**
  1951. * @ngdoc directive
  1952. * @name ui.grid.directive:uiGridOneBindSrc
  1953. * @memberof ui.grid.directive:uiGridOneBind
  1954. * @element img
  1955. * @restrict A
  1956. * @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>.
  1957. * @description One time binding for the src dom tag.
  1958. *
  1959. */
  1960. { tag: 'Src', method: 'attr' },
  1961. /**
  1962. * @ngdoc directive
  1963. * @name ui.grid.directive:uiGridOneBindText
  1964. * @element div
  1965. * @restrict A
  1966. * @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>.
  1967. * @description One time binding for the text dom tag.
  1968. */
  1969. { tag: 'Text', method: 'text' },
  1970. /**
  1971. * @ngdoc directive
  1972. * @name ui.grid.directive:uiGridOneBindHref
  1973. * @element div
  1974. * @restrict A
  1975. * @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>.
  1976. * @description One time binding for the href dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  1977. */
  1978. { tag: 'Href', method: 'attr' },
  1979. /**
  1980. * @ngdoc directive
  1981. * @name ui.grid.directive:uiGridOneBindClass
  1982. * @element div
  1983. * @restrict A
  1984. * @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>.
  1985. * @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.
  1986. * this is to prevent the watcher from being removed before the scope is initialized.
  1987. * @param {Array} uiGridOneBindClass An array of classes to bind to this element.
  1988. * @description One time binding for the class dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  1989. */
  1990. { tag: 'Class', method: 'addClass' },
  1991. /**
  1992. * @ngdoc directive
  1993. * @name ui.grid.directive:uiGridOneBindHtml
  1994. * @element div
  1995. * @restrict A
  1996. * @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>.
  1997. * @description One time binding for the html method on a dom element. For more information see {@link ui.grid.directive:uiGridOneBind}.
  1998. */
  1999. { tag: 'Html', method: 'html' },
  2000. /**
  2001. * @ngdoc directive
  2002. * @name ui.grid.directive:uiGridOneBindAlt
  2003. * @element div
  2004. * @restrict A
  2005. * @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>.
  2006. * @description One time binding for the alt dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2007. */
  2008. { tag: 'Alt', method: 'attr' },
  2009. /**
  2010. * @ngdoc directive
  2011. * @name ui.grid.directive:uiGridOneBindStyle
  2012. * @element div
  2013. * @restrict A
  2014. * @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>.
  2015. * @description One time binding for the style dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2016. */
  2017. { tag: 'Style', method: 'css' },
  2018. /**
  2019. * @ngdoc directive
  2020. * @name ui.grid.directive:uiGridOneBindValue
  2021. * @element div
  2022. * @restrict A
  2023. * @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>.
  2024. * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2025. */
  2026. { tag: 'Value', method: 'attr' },
  2027. /**
  2028. * @ngdoc directive
  2029. * @name ui.grid.directive:uiGridOneBindId
  2030. * @element div
  2031. * @restrict A
  2032. * @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>.
  2033. * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2034. */
  2035. { tag: 'Id', method: 'attr' },
  2036. /**
  2037. * @ngdoc directive
  2038. * @name ui.grid.directive:uiGridOneBindIdGrid
  2039. * @element div
  2040. * @restrict A
  2041. * @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>.
  2042. * @description One time binding for the id dom tag.
  2043. * <h1>Important Note!</h1>
  2044. * If the id tag passed as a parameter does <b>not</b> contain the grid id as a substring
  2045. * then the directive will search the scope and the parent controller (if it is a uiGridController) for the grid.id value.
  2046. * 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.
  2047. * This is done in order to ensure uniqueness of id tags across the grid.
  2048. * This is to prevent two grids in the same document having duplicate id tags.
  2049. */
  2050. { tag: 'Id', directiveName: 'IdGrid', method: 'attr', appendGridId: true },
  2051. /**
  2052. * @ngdoc directive
  2053. * @name ui.grid.directive:uiGridOneBindTitle
  2054. * @element div
  2055. * @restrict A
  2056. * @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>.
  2057. * @description One time binding for the title dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2058. */
  2059. { tag: 'Title', method: 'attr' },
  2060. /**
  2061. * @ngdoc directive
  2062. * @name ui.grid.directive:uiGridOneBindAriaLabel
  2063. * @element div
  2064. * @restrict A
  2065. * @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>.
  2066. * @description One time binding for the aria-label dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2067. *<br/>
  2068. * <pre>
  2069. <div ng-init="text='Add this text'" ui-grid-one-bind-aria-label="text"></div>
  2070. </pre>
  2071. * Will become:
  2072. * <pre>
  2073. <div ng-init="text='Add this text'" ui-grid-one-bind-aria-label="text" aria-label="Add this text"></div>
  2074. </pre>
  2075. */
  2076. { tag: 'Label', method: 'attr', aria: true },
  2077. /**
  2078. * @ngdoc directive
  2079. * @name ui.grid.directive:uiGridOneBindAriaLabelledby
  2080. * @element div
  2081. * @restrict A
  2082. * @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>.
  2083. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2084. *<br/>
  2085. * <pre>
  2086. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby="anId"></div>
  2087. </pre>
  2088. * Will become:
  2089. * <pre>
  2090. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby="anId" aria-labelledby="gridID32"></div>
  2091. </pre>
  2092. */
  2093. { tag: 'Labelledby', method: 'attr', aria: true },
  2094. /**
  2095. * @ngdoc directive
  2096. * @name ui.grid.directive:uiGridOneBindAriaLabelledbyGrid
  2097. * @element div
  2098. * @restrict A
  2099. * @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>.
  2100. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2101. * 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
  2102. * grid id to each one.
  2103. *<br/>
  2104. * <pre>
  2105. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby-grid="anId"></div>
  2106. </pre>
  2107. * Will become ([grid.id] will be replaced by the actual grid id):
  2108. * <pre>
  2109. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby-grid="anId" aria-labelledby-Grid="[grid.id]-gridID32"></div>
  2110. </pre>
  2111. */
  2112. { tag: 'Labelledby', directiveName: 'LabelledbyGrid', appendGridId: true, method: 'attr', aria: true },
  2113. /**
  2114. * @ngdoc directive
  2115. * @name ui.grid.directive:uiGridOneBindAriaDescribedby
  2116. * @element ANY
  2117. * @restrict A
  2118. * @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>.
  2119. * @description One time binding for the aria-describedby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2120. *<br/>
  2121. * <pre>
  2122. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby="anId"></div>
  2123. </pre>
  2124. * Will become:
  2125. * <pre>
  2126. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby="anId" aria-describedby="gridID32"></div>
  2127. </pre>
  2128. */
  2129. { tag: 'Describedby', method: 'attr', aria: true },
  2130. /**
  2131. * @ngdoc directive
  2132. * @name ui.grid.directive:uiGridOneBindAriaDescribedbyGrid
  2133. * @element ANY
  2134. * @restrict A
  2135. * @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>.
  2136. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
  2137. * 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
  2138. * grid id to each one.
  2139. *<br/>
  2140. * <pre>
  2141. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby-grid="anId"></div>
  2142. </pre>
  2143. * Will become ([grid.id] will be replaced by the actual grid id):
  2144. * <pre>
  2145. <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-describedby-grid="anId" aria-describedby="[grid.id]-gridID32"></div>
  2146. </pre>
  2147. */
  2148. { tag: 'Describedby', directiveName: 'DescribedbyGrid', appendGridId: true, method: 'attr', aria: true }
  2149. ],
  2150. function(v) {
  2151. var baseDirectiveName = 'uiGridOneBind';
  2152. //If it is an aria tag then append the aria label seperately
  2153. //This is done because the aria tags are formatted aria-* and the directive name can't have a '-' character in it.
  2154. //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.
  2155. var directiveName = (v.aria ? baseDirectiveName + 'Aria' : baseDirectiveName) + (v.directiveName ? v.directiveName : v.tag);
  2156. oneBinders.directive(directiveName, ['gridUtil', function(gridUtil) {
  2157. return {
  2158. restrict: 'A',
  2159. require: ['?uiGrid', '?^uiGrid'],
  2160. link: function(scope, iElement, iAttrs, controllers) {
  2161. /* Appends the grid id to the beginnig of the value. */
  2162. var appendGridId = function(val) {
  2163. var grid; //Get an instance of the grid if its available
  2164. //If its available in the scope then we don't need to try to find it elsewhere
  2165. if (scope.grid) {
  2166. grid = scope.grid;
  2167. }
  2168. //Another possible location to try to find the grid
  2169. else if (scope.col && scope.col.grid) {
  2170. grid = scope.col.grid;
  2171. }
  2172. //Last ditch effort: Search through the provided controllers.
  2173. else if (!controllers.some( //Go through the controllers till one has the element we need
  2174. function(controller) {
  2175. if (controller && controller.grid) {
  2176. grid = controller.grid;
  2177. return true; //We've found the grid
  2178. }
  2179. })) {
  2180. //We tried our best to find it for you
  2181. gridUtil.logError("[" + directiveName + "] A valid grid could not be found to bind id. Are you using this directive " +
  2182. "within the correct scope? Trying to generate id: [gridID]-" + val);
  2183. throw new Error("No valid grid could be found");
  2184. }
  2185. if (grid) {
  2186. var idRegex = new RegExp(grid.id.toString());
  2187. //If the grid id hasn't been appended already in the template declaration
  2188. if (!idRegex.test(val)) {
  2189. val = grid.id.toString() + '-' + val;
  2190. }
  2191. }
  2192. return val;
  2193. };
  2194. // The watch returns a function to remove itself.
  2195. var rmWatcher = scope.$watch(iAttrs[directiveName], function(newV) {
  2196. if (newV) {
  2197. //If we are trying to add an id element then we also apply the grid id if it isn't already there
  2198. if (v.appendGridId) {
  2199. var newIdString = null;
  2200. //Append the id to all of the new ids.
  2201. angular.forEach(newV.split(' '), function(s) {
  2202. newIdString = (newIdString ? (newIdString + ' ') : '') + appendGridId(s);
  2203. });
  2204. newV = newIdString;
  2205. }
  2206. // Append this newValue to the dom element.
  2207. switch (v.method) {
  2208. case 'attr': //The attr method takes two paraams the tag and the value
  2209. if (v.aria) {
  2210. //If it is an aria element then append the aria prefix
  2211. iElement[v.method]('aria-' + v.tag.toLowerCase(), newV);
  2212. } else {
  2213. iElement[v.method](v.tag.toLowerCase(), newV);
  2214. }
  2215. break;
  2216. case 'addClass':
  2217. //Pulled from https://github.com/Pasvaz/bindonce/blob/master/bindonce.js
  2218. if (angular.isObject(newV) && !angular.isArray(newV)) {
  2219. var results = [];
  2220. var nonNullFound = false; //We don't want to remove the binding unless the key is actually defined
  2221. angular.forEach(newV, function(value, index) {
  2222. if (value !== null && typeof(value) !== "undefined") {
  2223. nonNullFound = true; //A non null value for a key was found so the object must have been initialized
  2224. if (value) { results.push(index); }
  2225. }
  2226. });
  2227. //A non null value for a key wasn't found so assume that the scope values haven't been fully initialized
  2228. if (!nonNullFound) {
  2229. return; // If not initialized then the watcher should not be removed yet.
  2230. }
  2231. newV = results;
  2232. }
  2233. if (newV) {
  2234. iElement.addClass(angular.isArray(newV) ? newV.join(' ') : newV);
  2235. } else {
  2236. return;
  2237. }
  2238. break;
  2239. default:
  2240. iElement[v.method](newV);
  2241. break;
  2242. }
  2243. //Removes the watcher on itself after the bind
  2244. rmWatcher();
  2245. }
  2246. // True ensures that equality is determined using angular.equals instead of ===
  2247. }, true); //End rm watchers
  2248. } //End compile function
  2249. }; //End directive return
  2250. } // End directive function
  2251. ]); //End directive
  2252. }); // End angular foreach
  2253. })();
  2254. (function() {
  2255. 'use strict';
  2256. var module = angular.module('ui.grid');
  2257. module.directive('uiGridRenderContainer', ['$timeout', '$document', 'uiGridConstants', 'gridUtil', 'ScrollEvent',
  2258. function($timeout, $document, uiGridConstants, gridUtil, ScrollEvent) {
  2259. return {
  2260. replace: true,
  2261. transclude: true,
  2262. templateUrl: 'ui-grid/uiGridRenderContainer',
  2263. require: ['^uiGrid', 'uiGridRenderContainer'],
  2264. scope: {
  2265. containerId: '=',
  2266. rowContainerName: '=',
  2267. colContainerName: '=',
  2268. bindScrollHorizontal: '=',
  2269. bindScrollVertical: '=',
  2270. enableVerticalScrollbar: '=',
  2271. enableHorizontalScrollbar: '='
  2272. },
  2273. controller: 'uiGridRenderContainer as RenderContainer',
  2274. compile: function() {
  2275. return {
  2276. pre: function prelink($scope, $elm, $attrs, controllers) {
  2277. var uiGridCtrl = controllers[0];
  2278. var containerCtrl = controllers[1];
  2279. var grid = $scope.grid = uiGridCtrl.grid;
  2280. // Verify that the render container for this element exists
  2281. if (!$scope.rowContainerName) {
  2282. throw "No row render container name specified";
  2283. }
  2284. if (!$scope.colContainerName) {
  2285. throw "No column render container name specified";
  2286. }
  2287. if (!grid.renderContainers[$scope.rowContainerName]) {
  2288. throw "Row render container '" + $scope.rowContainerName + "' is not registered.";
  2289. }
  2290. if (!grid.renderContainers[$scope.colContainerName]) {
  2291. throw "Column render container '" + $scope.colContainerName + "' is not registered.";
  2292. }
  2293. var rowContainer = $scope.rowContainer = grid.renderContainers[$scope.rowContainerName];
  2294. var colContainer = $scope.colContainer = grid.renderContainers[$scope.colContainerName];
  2295. containerCtrl.containerId = $scope.containerId;
  2296. containerCtrl.rowContainer = rowContainer;
  2297. containerCtrl.colContainer = colContainer;
  2298. },
  2299. post: function postlink($scope, $elm, $attrs, controllers) {
  2300. var uiGridCtrl = controllers[0];
  2301. var containerCtrl = controllers[1];
  2302. var grid = uiGridCtrl.grid;
  2303. var rowContainer = containerCtrl.rowContainer;
  2304. var colContainer = containerCtrl.colContainer;
  2305. var scrollTop = null;
  2306. var scrollLeft = null;
  2307. var renderContainer = grid.renderContainers[$scope.containerId];
  2308. // Put the container name on this element as a class
  2309. $elm.addClass('ui-grid-render-container-' + $scope.containerId);
  2310. // Scroll the render container viewport when the mousewheel is used
  2311. gridUtil.on.mousewheel($elm, function(event) {
  2312. var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.RenderContainerMouseWheel);
  2313. if (event.deltaY !== 0) {
  2314. var scrollYAmount = event.deltaY * -1 * event.deltaFactor;
  2315. scrollTop = containerCtrl.viewport[0].scrollTop;
  2316. // Get the scroll percentage
  2317. scrollEvent.verticalScrollLength = rowContainer.getVerticalScrollLength();
  2318. var scrollYPercentage = (scrollTop + scrollYAmount) / scrollEvent.verticalScrollLength;
  2319. // If we should be scrolled 100%, make sure the scrollTop matches the maximum scroll length
  2320. // Viewports that have "overflow: hidden" don't let the mousewheel scroll all the way to the bottom without this check
  2321. if (scrollYPercentage >= 1 && scrollTop < scrollEvent.verticalScrollLength) {
  2322. containerCtrl.viewport[0].scrollTop = scrollEvent.verticalScrollLength;
  2323. }
  2324. // Keep scrollPercentage within the range 0-1.
  2325. if (scrollYPercentage < 0) { scrollYPercentage = 0; } else if (scrollYPercentage > 1) { scrollYPercentage = 1; }
  2326. scrollEvent.y = { percentage: scrollYPercentage, pixels: scrollYAmount };
  2327. }
  2328. if (event.deltaX !== 0) {
  2329. var scrollXAmount = event.deltaX * event.deltaFactor;
  2330. // Get the scroll percentage
  2331. scrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.viewport, grid);
  2332. scrollEvent.horizontalScrollLength = (colContainer.getCanvasWidth() - colContainer.getViewportWidth());
  2333. var scrollXPercentage = (scrollLeft + scrollXAmount) / scrollEvent.horizontalScrollLength;
  2334. // Keep scrollPercentage within the range 0-1.
  2335. if (scrollXPercentage < 0) { scrollXPercentage = 0; } else if (scrollXPercentage > 1) { scrollXPercentage = 1; }
  2336. scrollEvent.x = { percentage: scrollXPercentage, pixels: scrollXAmount };
  2337. }
  2338. // Let the parent container scroll if the grid is already at the top/bottom
  2339. if ((event.deltaY !== 0 && (scrollEvent.atTop(scrollTop) || scrollEvent.atBottom(scrollTop))) ||
  2340. (event.deltaX !== 0 && (scrollEvent.atLeft(scrollLeft) || scrollEvent.atRight(scrollLeft)))) {
  2341. //parent controller scrolls
  2342. } else {
  2343. event.preventDefault();
  2344. event.stopPropagation();
  2345. scrollEvent.fireThrottledScrollingEvent('', scrollEvent);
  2346. }
  2347. });
  2348. $elm.bind('$destroy', function() {
  2349. $elm.unbind('keydown');
  2350. ['touchstart', 'touchmove', 'touchend', 'keydown', 'wheel', 'mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'].forEach(function(eventName) {
  2351. $elm.unbind(eventName);
  2352. });
  2353. });
  2354. // TODO(c0bra): Handle resizing the inner canvas based on the number of elements
  2355. function update() {
  2356. var ret = '';
  2357. var canvasWidth = colContainer.canvasWidth;
  2358. var viewportWidth = colContainer.getViewportWidth();
  2359. var canvasHeight = rowContainer.getCanvasHeight();
  2360. //add additional height for scrollbar on left and right container
  2361. //if ($scope.containerId !== 'body') {
  2362. // canvasHeight -= grid.scrollbarHeight;
  2363. //}
  2364. var viewportHeight = rowContainer.getViewportHeight();
  2365. //shorten the height to make room for a scrollbar placeholder
  2366. if (colContainer.needsHScrollbarPlaceholder()) {
  2367. viewportHeight -= grid.scrollbarHeight;
  2368. }
  2369. var headerViewportWidth,
  2370. footerViewportWidth;
  2371. headerViewportWidth = footerViewportWidth = colContainer.getHeaderViewportWidth();
  2372. // Set canvas dimensions
  2373. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-canvas { width: ' + canvasWidth + 'px; height: ' + canvasHeight + 'px; }';
  2374. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }';
  2375. if (renderContainer.explicitHeaderCanvasHeight) {
  2376. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: ' + renderContainer.explicitHeaderCanvasHeight + 'px; }';
  2377. } else {
  2378. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: inherit; }';
  2379. }
  2380. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-viewport { width: ' + viewportWidth + 'px; height: ' + viewportHeight + 'px; }';
  2381. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-viewport { width: ' + headerViewportWidth + 'px; }';
  2382. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-footer-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }';
  2383. ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-footer-viewport { width: ' + footerViewportWidth + 'px; }';
  2384. return ret;
  2385. }
  2386. uiGridCtrl.grid.registerStyleComputation({
  2387. priority: 6,
  2388. func: update
  2389. });
  2390. }
  2391. };
  2392. }
  2393. };
  2394. }
  2395. ]);
  2396. module.controller('uiGridRenderContainer', ['$scope', 'gridUtil', function($scope, gridUtil) {
  2397. }]);
  2398. })();
  2399. (function() {
  2400. 'use strict';
  2401. angular.module('ui.grid').directive('uiGridRow', ['gridUtil', function(gridUtil) {
  2402. return {
  2403. replace: true,
  2404. // priority: 2001,
  2405. // templateUrl: 'ui-grid/ui-grid-row',
  2406. require: ['^uiGrid', '^uiGridRenderContainer'],
  2407. scope: {
  2408. row: '=uiGridRow',
  2409. //rowRenderIndex is added to scope to give the true visual index of the row to any directives that need it
  2410. rowRenderIndex: '='
  2411. },
  2412. compile: function() {
  2413. return {
  2414. pre: function($scope, $elm, $attrs, controllers) {
  2415. var uiGridCtrl = controllers[0];
  2416. var containerCtrl = controllers[1];
  2417. var grid = uiGridCtrl.grid;
  2418. $scope.grid = uiGridCtrl.grid;
  2419. $scope.colContainer = containerCtrl.colContainer;
  2420. // Function for attaching the template to this scope
  2421. var clonedElement, cloneScope;
  2422. function compileTemplate() {
  2423. $scope.row.getRowTemplateFn.then(function(compiledElementFn) {
  2424. // var compiledElementFn = $scope.row.compiledElementFn;
  2425. // Create a new scope for the contents of this row, so we can destroy it later if need be
  2426. var newScope = $scope.$new();
  2427. compiledElementFn(newScope, function(newElm, scope) {
  2428. // If we already have a cloned element, we need to remove it and destroy its scope
  2429. if (clonedElement) {
  2430. clonedElement.remove();
  2431. cloneScope.$destroy();
  2432. }
  2433. // Empty the row and append the new element
  2434. $elm.empty().append(newElm);
  2435. // Save the new cloned element and scope
  2436. clonedElement = newElm;
  2437. cloneScope = newScope;
  2438. });
  2439. });
  2440. }
  2441. // Initially attach the compiled template to this scope
  2442. compileTemplate();
  2443. // If the row's compiled element function changes, we need to replace this element's contents with the new compiled template
  2444. $scope.$watch('row.getRowTemplateFn', function(newFunc, oldFunc) {
  2445. if (newFunc !== oldFunc) {
  2446. compileTemplate();
  2447. }
  2448. });
  2449. },
  2450. post: function($scope, $elm, $attrs, controllers) {
  2451. }
  2452. };
  2453. }
  2454. };
  2455. }]);
  2456. })();
  2457. (function() {
  2458. // 'use strict';
  2459. /**
  2460. * @ngdoc directive
  2461. * @name ui.grid.directive:uiGridStyle
  2462. * @element style
  2463. * @restrict A
  2464. *
  2465. * @description
  2466. * Allows us to interpolate expressions in `<style>` elements. Angular doesn't do this by default as it can/will/might? break in IE8.
  2467. *
  2468. * @example
  2469. <doc:example module="app">
  2470. <doc:source>
  2471. <script>
  2472. var app = angular.module('app', ['ui.grid']);
  2473. app.controller('MainCtrl', ['$scope', function ($scope) {
  2474. $scope.myStyle = '.blah { border: 1px solid }';
  2475. }]);
  2476. </script>
  2477. <div ng-controller="MainCtrl">
  2478. <style ui-grid-style>{{ myStyle }}</style>
  2479. <span class="blah">I am in a box.</span>
  2480. </div>
  2481. </doc:source>
  2482. <doc:scenario>
  2483. it('should apply the right class to the element', function () {
  2484. element(by.css('.blah')).getCssValue('border-top-width')
  2485. .then(function(c) {
  2486. expect(c).toContain('1px');
  2487. });
  2488. });
  2489. </doc:scenario>
  2490. </doc:example>
  2491. */
  2492. angular.module('ui.grid').directive('uiGridStyle', ['gridUtil', '$interpolate', function(gridUtil, $interpolate) {
  2493. return {
  2494. // restrict: 'A',
  2495. // priority: 1000,
  2496. // require: '?^uiGrid',
  2497. link: function($scope, $elm, $attrs, uiGridCtrl) {
  2498. // gridUtil.logDebug('ui-grid-style link');
  2499. // if (uiGridCtrl === undefined) {
  2500. // gridUtil.logWarn('[ui-grid-style link] uiGridCtrl is undefined!');
  2501. // }
  2502. var interpolateFn = $interpolate($elm.text(), true);
  2503. if (interpolateFn) {
  2504. $scope.$watch(interpolateFn, function(value) {
  2505. $elm.text(value);
  2506. });
  2507. }
  2508. // uiGridCtrl.recalcRowStyles = function() {
  2509. // var offset = (scope.options.offsetTop || 0) - (scope.options.excessRows * scope.options.rowHeight);
  2510. // var rowHeight = scope.options.rowHeight;
  2511. // var ret = '';
  2512. // var rowStyleCount = uiGridCtrl.minRowsToRender() + (scope.options.excessRows * 2);
  2513. // for (var i = 1; i <= rowStyleCount; i++) {
  2514. // ret = ret + ' .grid' + scope.gridId + ' .ui-grid-row:nth-child(' + i + ') { top: ' + offset + 'px; }';
  2515. // offset = offset + rowHeight;
  2516. // }
  2517. // scope.rowStyles = ret;
  2518. // };
  2519. // uiGridCtrl.styleComputions.push(uiGridCtrl.recalcRowStyles);
  2520. }
  2521. };
  2522. }]);
  2523. })();
  2524. (function() {
  2525. 'use strict';
  2526. angular.module('ui.grid').directive('uiGridViewport', ['gridUtil', 'ScrollEvent', 'uiGridConstants', '$log',
  2527. function(gridUtil, ScrollEvent, uiGridConstants, $log) {
  2528. return {
  2529. replace: true,
  2530. scope: {},
  2531. controllerAs: 'Viewport',
  2532. templateUrl: 'ui-grid/uiGridViewport',
  2533. require: ['^uiGrid', '^uiGridRenderContainer'],
  2534. link: function($scope, $elm, $attrs, controllers) {
  2535. // gridUtil.logDebug('viewport post-link');
  2536. var uiGridCtrl = controllers[0];
  2537. var containerCtrl = controllers[1];
  2538. $scope.containerCtrl = containerCtrl;
  2539. var rowContainer = containerCtrl.rowContainer;
  2540. var colContainer = containerCtrl.colContainer;
  2541. var grid = uiGridCtrl.grid;
  2542. $scope.grid = uiGridCtrl.grid;
  2543. // Put the containers in scope so we can get rows and columns from them
  2544. $scope.rowContainer = containerCtrl.rowContainer;
  2545. $scope.colContainer = containerCtrl.colContainer;
  2546. // Register this viewport with its container
  2547. containerCtrl.viewport = $elm;
  2548. $elm.on('scroll', scrollHandler);
  2549. var ignoreScroll = false;
  2550. function scrollHandler(evt) {
  2551. //Leaving in this commented code in case it can someday be used
  2552. //It does improve performance, but because the horizontal scroll is normalized,
  2553. // using this code will lead to the column header getting slightly out of line with columns
  2554. //
  2555. //if (ignoreScroll && (grid.isScrollingHorizontally || grid.isScrollingHorizontally)) {
  2556. // //don't ask for scrollTop if we just set it
  2557. // ignoreScroll = false;
  2558. // return;
  2559. //}
  2560. //ignoreScroll = true;
  2561. var newScrollTop = $elm[0].scrollTop;
  2562. var newScrollLeft = gridUtil.normalizeScrollLeft($elm, grid);
  2563. var vertScrollPercentage = rowContainer.scrollVertical(newScrollTop);
  2564. var horizScrollPercentage = colContainer.scrollHorizontal(newScrollLeft);
  2565. var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.ViewPortScroll);
  2566. scrollEvent.newScrollLeft = newScrollLeft;
  2567. scrollEvent.newScrollTop = newScrollTop;
  2568. if (horizScrollPercentage > -1) {
  2569. scrollEvent.x = { percentage: horizScrollPercentage };
  2570. }
  2571. if (vertScrollPercentage > -1) {
  2572. scrollEvent.y = { percentage: vertScrollPercentage };
  2573. }
  2574. grid.scrollContainers($scope.$parent.containerId, scrollEvent);
  2575. }
  2576. if ($scope.$parent.bindScrollVertical) {
  2577. grid.addVerticalScrollSync($scope.$parent.containerId, syncVerticalScroll);
  2578. }
  2579. if ($scope.$parent.bindScrollHorizontal) {
  2580. grid.addHorizontalScrollSync($scope.$parent.containerId, syncHorizontalScroll);
  2581. grid.addHorizontalScrollSync($scope.$parent.containerId + 'header', syncHorizontalHeader);
  2582. grid.addHorizontalScrollSync($scope.$parent.containerId + 'footer', syncHorizontalFooter);
  2583. }
  2584. function syncVerticalScroll(scrollEvent) {
  2585. containerCtrl.prevScrollArgs = scrollEvent;
  2586. var newScrollTop = scrollEvent.getNewScrollTop(rowContainer, containerCtrl.viewport);
  2587. $elm[0].scrollTop = newScrollTop;
  2588. }
  2589. function syncHorizontalScroll(scrollEvent) {
  2590. containerCtrl.prevScrollArgs = scrollEvent;
  2591. var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
  2592. $elm[0].scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport, newScrollLeft, grid);
  2593. }
  2594. function syncHorizontalHeader(scrollEvent) {
  2595. var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
  2596. if (containerCtrl.headerViewport) {
  2597. containerCtrl.headerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport, newScrollLeft, grid);
  2598. }
  2599. }
  2600. function syncHorizontalFooter(scrollEvent) {
  2601. var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
  2602. if (containerCtrl.footerViewport) {
  2603. containerCtrl.footerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport, newScrollLeft, grid);
  2604. }
  2605. }
  2606. },
  2607. controller: ['$scope', function($scope) {
  2608. this.rowStyle = function(index) {
  2609. var rowContainer = $scope.rowContainer;
  2610. var colContainer = $scope.colContainer;
  2611. var styles = {};
  2612. if (index === 0 && rowContainer.currentTopRow !== 0) {
  2613. // The row offset-top is just the height of the rows above the current top-most row, which are no longer rendered
  2614. var hiddenRowWidth = (rowContainer.currentTopRow) * rowContainer.grid.options.rowHeight;
  2615. // return { 'margin-top': hiddenRowWidth + 'px' };
  2616. styles['margin-top'] = hiddenRowWidth + 'px';
  2617. }
  2618. if (colContainer.currentFirstColumn !== 0) {
  2619. if (colContainer.grid.isRTL()) {
  2620. styles['margin-right'] = colContainer.columnOffset + 'px';
  2621. } else {
  2622. styles['margin-left'] = colContainer.columnOffset + 'px';
  2623. }
  2624. }
  2625. return styles;
  2626. };
  2627. }]
  2628. };
  2629. }
  2630. ]);
  2631. })();
  2632. (function() {
  2633. angular.module('ui.grid')
  2634. .directive('uiGridVisible', function uiGridVisibleAction() {
  2635. return function($scope, $elm, $attr) {
  2636. $scope.$watch($attr.uiGridVisible, function(visible) {
  2637. // $elm.css('visibility', visible ? 'visible' : 'hidden');
  2638. $elm[visible ? 'removeClass' : 'addClass']('ui-grid-invisible');
  2639. });
  2640. };
  2641. });
  2642. })();
  2643. (function() {
  2644. 'use strict';
  2645. angular.module('ui.grid').controller('uiGridController', ['$scope', '$element', '$attrs', 'gridUtil', '$q', 'uiGridConstants',
  2646. '$templateCache', 'gridClassFactory', '$timeout', '$parse', '$compile',
  2647. function($scope, $elm, $attrs, gridUtil, $q, uiGridConstants,
  2648. $templateCache, gridClassFactory, $timeout, $parse, $compile) {
  2649. // gridUtil.logDebug('ui-grid controller');
  2650. var self = this;
  2651. self.grid = gridClassFactory.createGrid($scope.uiGrid);
  2652. //assign $scope.$parent if appScope not already assigned
  2653. self.grid.appScope = self.grid.appScope || $scope.$parent;
  2654. $elm.addClass('grid' + self.grid.id);
  2655. self.grid.rtl = gridUtil.getStyles($elm[0])['direction'] === 'rtl';
  2656. // angular.extend(self.grid.options, );
  2657. //all properties of grid are available on scope
  2658. $scope.grid = self.grid;
  2659. if ($attrs.uiGridColumns) {
  2660. $attrs.$observe('uiGridColumns', function(value) {
  2661. self.grid.options.columnDefs = value;
  2662. self.grid.buildColumns()
  2663. .then(function() {
  2664. self.grid.preCompileCellTemplates();
  2665. self.grid.refreshCanvas(true);
  2666. });
  2667. });
  2668. }
  2669. // if fastWatch is set we watch only the length and the reference, not every individual object
  2670. var deregFunctions = [];
  2671. if (self.grid.options.fastWatch) {
  2672. self.uiGrid = $scope.uiGrid;
  2673. if (angular.isString($scope.uiGrid.data)) {
  2674. deregFunctions.push($scope.$parent.$watch($scope.uiGrid.data, dataWatchFunction));
  2675. deregFunctions.push($scope.$parent.$watch(function() {
  2676. if (self.grid.appScope[$scope.uiGrid.data]) {
  2677. return self.grid.appScope[$scope.uiGrid.data].length;
  2678. } else {
  2679. return undefined;
  2680. }
  2681. }, dataWatchFunction));
  2682. } else {
  2683. deregFunctions.push($scope.$parent.$watch(function() { return $scope.uiGrid.data; }, dataWatchFunction));
  2684. deregFunctions.push($scope.$parent.$watch(function() { return $scope.uiGrid.data.length; }, dataWatchFunction));
  2685. }
  2686. deregFunctions.push($scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction));
  2687. deregFunctions.push($scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs.length; }, columnDefsWatchFunction));
  2688. } else {
  2689. if (angular.isString($scope.uiGrid.data)) {
  2690. deregFunctions.push($scope.$parent.$watchCollection($scope.uiGrid.data, dataWatchFunction));
  2691. } else {
  2692. deregFunctions.push($scope.$parent.$watchCollection(function() { return $scope.uiGrid.data; }, dataWatchFunction));
  2693. }
  2694. deregFunctions.push($scope.$parent.$watchCollection(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction));
  2695. }
  2696. function columnDefsWatchFunction(n, o) {
  2697. if (n && n !== o) {
  2698. self.grid.options.columnDefs = n;
  2699. self.grid.buildColumns({ orderByColumnDefs: true })
  2700. .then(function() {
  2701. self.grid.preCompileCellTemplates();
  2702. self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.COLUMN);
  2703. });
  2704. }
  2705. }
  2706. function dataWatchFunction(newData) {
  2707. // gridUtil.logDebug('dataWatch fired');
  2708. var promises = [];
  2709. if (self.grid.options.fastWatch) {
  2710. if (angular.isString($scope.uiGrid.data)) {
  2711. newData = self.grid.appScope[$scope.uiGrid.data];
  2712. } else {
  2713. newData = $scope.uiGrid.data;
  2714. }
  2715. }
  2716. if (newData) {
  2717. if (
  2718. // 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)
  2719. self.grid.columns.length === (self.grid.rowHeaderColumns ? self.grid.rowHeaderColumns.length : 0) &&
  2720. // ... and we don't have a ui-grid-columns attribute, which would define columns for us
  2721. !$attrs.uiGridColumns &&
  2722. // ... and we have no pre-defined columns
  2723. self.grid.options.columnDefs.length === 0 &&
  2724. // ... but we DO have data
  2725. newData.length > 0
  2726. ) {
  2727. // ... then build the column definitions from the data that we have
  2728. self.grid.buildColumnDefsFromData(newData);
  2729. }
  2730. // If we either have some columns defined, or some data defined
  2731. if (self.grid.options.columnDefs.length > 0 || newData.length > 0) {
  2732. // Build the column set, then pre-compile the column cell templates
  2733. promises.push(self.grid.buildColumns()
  2734. .then(function() {
  2735. self.grid.preCompileCellTemplates();
  2736. }));
  2737. }
  2738. $q.all(promises).then(function() {
  2739. self.grid.modifyRows(newData)
  2740. .then(function() {
  2741. // if (self.viewport) {
  2742. self.grid.redrawInPlace(true);
  2743. // }
  2744. $scope.$evalAsync(function() {
  2745. self.grid.refreshCanvas(true);
  2746. self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.ROW);
  2747. });
  2748. });
  2749. });
  2750. }
  2751. }
  2752. var styleWatchDereg = $scope.$watch(function() { return self.grid.styleComputations; }, function() {
  2753. self.grid.refreshCanvas(true);
  2754. });
  2755. $scope.$on('$destroy', function() {
  2756. deregFunctions.forEach(function(deregFn) { deregFn(); });
  2757. styleWatchDereg();
  2758. });
  2759. self.fireEvent = function(eventName, args) {
  2760. // Add the grid to the event arguments if it's not there
  2761. if (typeof(args) === 'undefined' || args === undefined) {
  2762. args = {};
  2763. }
  2764. if (typeof(args.grid) === 'undefined' || args.grid === undefined) {
  2765. args.grid = self.grid;
  2766. }
  2767. $scope.$broadcast(eventName, args);
  2768. };
  2769. self.innerCompile = function innerCompile(elm) {
  2770. $compile(elm)($scope);
  2771. };
  2772. }
  2773. ]);
  2774. /**
  2775. * @ngdoc directive
  2776. * @name ui.grid.directive:uiGrid
  2777. * @element div
  2778. * @restrict EA
  2779. * @param {Object} uiGrid Options for the grid to use
  2780. *
  2781. * @description Create a very basic grid.
  2782. *
  2783. * @example
  2784. <example module="app">
  2785. <file name="app.js">
  2786. var app = angular.module('app', ['ui.grid']);
  2787. app.controller('MainCtrl', ['$scope', function ($scope) {
  2788. $scope.data = [
  2789. { name: 'Bob', title: 'CEO' },
  2790. { name: 'Frank', title: 'Lowly Developer' }
  2791. ];
  2792. }]);
  2793. </file>
  2794. <file name="index.html">
  2795. <div ng-controller="MainCtrl">
  2796. <div ui-grid="{ data: data }"></div>
  2797. </div>
  2798. </file>
  2799. </example>
  2800. */
  2801. angular.module('ui.grid').directive('uiGrid', uiGridDirective);
  2802. uiGridDirective.$inject = ['$compile', '$templateCache', '$timeout', '$window', 'gridUtil', 'uiGridConstants'];
  2803. function uiGridDirective($compile, $templateCache, $timeout, $window, gridUtil, uiGridConstants) {
  2804. return {
  2805. templateUrl: 'ui-grid/ui-grid',
  2806. scope: {
  2807. uiGrid: '='
  2808. },
  2809. replace: true,
  2810. transclude: true,
  2811. controller: 'uiGridController',
  2812. compile: function() {
  2813. return {
  2814. post: function($scope, $elm, $attrs, uiGridCtrl) {
  2815. var grid = uiGridCtrl.grid;
  2816. // Initialize scrollbars (TODO: move to controller??)
  2817. uiGridCtrl.scrollbars = [];
  2818. grid.element = $elm;
  2819. // See if the grid has a rendered width, if not, wait a bit and try again
  2820. var sizeCheckInterval = 100; // ms
  2821. var maxSizeChecks = 20; // 2 seconds total
  2822. var sizeChecks = 0;
  2823. // Setup (event listeners) the grid
  2824. setup();
  2825. // And initialize it
  2826. init();
  2827. // Mark rendering complete so API events can happen
  2828. grid.renderingComplete();
  2829. // If the grid doesn't have size currently, wait for a bit to see if it gets size
  2830. checkSize();
  2831. /*-- Methods --*/
  2832. function checkSize() {
  2833. // If the grid has no width and we haven't checked more than <maxSizeChecks> times, check again in <sizeCheckInterval> milliseconds
  2834. if ($elm[0].offsetWidth <= 0 && sizeChecks < maxSizeChecks) {
  2835. setTimeout(checkSize, sizeCheckInterval);
  2836. sizeChecks++;
  2837. } else {
  2838. $timeout(init);
  2839. }
  2840. }
  2841. // Setup event listeners and watchers
  2842. function setup() {
  2843. // Bind to window resize events
  2844. angular.element($window).on('resize', gridResize);
  2845. // Unbind from window resize events when the grid is destroyed
  2846. $elm.on('$destroy', function() {
  2847. angular.element($window).off('resize', gridResize);
  2848. });
  2849. // If we add a left container after render, we need to watch and react
  2850. $scope.$watch(function() { return grid.hasLeftContainer(); }, function(newValue, oldValue) {
  2851. if (newValue === oldValue) {
  2852. return;
  2853. }
  2854. grid.refreshCanvas(true);
  2855. });
  2856. // If we add a right container after render, we need to watch and react
  2857. $scope.$watch(function() { return grid.hasRightContainer(); }, function(newValue, oldValue) {
  2858. if (newValue === oldValue) {
  2859. return;
  2860. }
  2861. grid.refreshCanvas(true);
  2862. });
  2863. }
  2864. // Initialize the directive
  2865. function init() {
  2866. grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm);
  2867. // Default canvasWidth to the grid width, in case we don't get any column definitions to calculate it from
  2868. grid.canvasWidth = uiGridCtrl.grid.gridWidth;
  2869. grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);
  2870. // 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
  2871. if (grid.gridHeight < grid.options.rowHeight && grid.options.enableMinHeightCheck) {
  2872. autoAdjustHeight();
  2873. }
  2874. // Run initial canvas refresh
  2875. grid.refreshCanvas(true);
  2876. }
  2877. // Set the grid's height ourselves in the case that its height would be unusably small
  2878. function autoAdjustHeight() {
  2879. // Figure out the new height
  2880. var contentHeight = grid.options.minRowsToShow * grid.options.rowHeight + 12;
  2881. var headerHeight = grid.options.showHeader ? grid.options.headerRowHeight : 0;
  2882. var footerHeight = grid.calcFooterHeight();
  2883. var scrollbarHeight = 0;
  2884. if (grid.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) {
  2885. scrollbarHeight = gridUtil.getScrollbarWidth();
  2886. }
  2887. var maxNumberOfFilters = 0;
  2888. // Calculates the maximum number of filters in the columns
  2889. angular.forEach(grid.options.columnDefs, function(col) {
  2890. if (col.hasOwnProperty('filter')) {
  2891. if (maxNumberOfFilters < 1) {
  2892. maxNumberOfFilters = 1;
  2893. }
  2894. } else if (col.hasOwnProperty('filters')) {
  2895. if (maxNumberOfFilters < col.filters.length) {
  2896. maxNumberOfFilters = col.filters.length;
  2897. }
  2898. }
  2899. });
  2900. if (grid.options.enableFiltering) {
  2901. var allColumnsHaveFilteringTurnedOff = grid.options.columnDefs.every(function(col) {
  2902. return col.enableFiltering === false;
  2903. });
  2904. if (!allColumnsHaveFilteringTurnedOff) {
  2905. maxNumberOfFilters++;
  2906. }
  2907. }
  2908. var filterHeight = maxNumberOfFilters * headerHeight;
  2909. var newHeight = headerHeight + contentHeight + footerHeight + scrollbarHeight + filterHeight;
  2910. $elm.css('height', newHeight + 'px');
  2911. grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);
  2912. }
  2913. // Resize the grid on window resize events
  2914. function gridResize($event) {
  2915. grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm);
  2916. grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);
  2917. grid.refreshCanvas(true);
  2918. }
  2919. }
  2920. };
  2921. }
  2922. };
  2923. }
  2924. })();
  2925. (function() {
  2926. 'use strict';
  2927. // TODO: rename this file to ui-grid-pinned-container.js
  2928. angular.module('ui.grid').directive('uiGridPinnedContainer', ['gridUtil', function(gridUtil) {
  2929. return {
  2930. restrict: 'EA',
  2931. replace: true,
  2932. 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>',
  2933. scope: {
  2934. side: '=uiGridPinnedContainer'
  2935. },
  2936. require: '^uiGrid',
  2937. compile: function compile() {
  2938. return {
  2939. post: function($scope, $elm, $attrs, uiGridCtrl) {
  2940. // gridUtil.logDebug('ui-grid-pinned-container ' + $scope.side + ' link');
  2941. var grid = uiGridCtrl.grid;
  2942. var myWidth = 0;
  2943. $elm.addClass('ui-grid-pinned-container-' + $scope.side);
  2944. // Monkey-patch the viewport width function
  2945. if ($scope.side === 'left' || $scope.side === 'right') {
  2946. grid.renderContainers[$scope.side].getViewportWidth = monkeyPatchedGetViewportWidth;
  2947. }
  2948. function monkeyPatchedGetViewportWidth() {
  2949. /*jshint validthis: true */
  2950. var self = this;
  2951. var viewportWidth = 0;
  2952. self.visibleColumnCache.forEach(function(column) {
  2953. viewportWidth += column.drawnWidth;
  2954. });
  2955. var adjustment = self.getViewportAdjustment();
  2956. viewportWidth = viewportWidth + adjustment.width;
  2957. return viewportWidth;
  2958. }
  2959. function updateContainerWidth() {
  2960. if ($scope.side === 'left' || $scope.side === 'right') {
  2961. var cols = grid.renderContainers[$scope.side].visibleColumnCache;
  2962. var width = 0;
  2963. for (var i = 0; i < cols.length; i++) {
  2964. var col = cols[i];
  2965. width += col.drawnWidth || col.width || 0;
  2966. }
  2967. return width;
  2968. }
  2969. }
  2970. function updateContainerDimensions() {
  2971. var ret = '';
  2972. // Column containers
  2973. if ($scope.side === 'left' || $scope.side === 'right') {
  2974. myWidth = updateContainerWidth();
  2975. // gridUtil.logDebug('myWidth', myWidth);
  2976. // TODO(c0bra): Subtract sum of col widths from grid viewport width and update it
  2977. $elm.attr('style', null);
  2978. // var myHeight = grid.renderContainers.body.getViewportHeight(); // + grid.horizontalScrollbarHeight;
  2979. 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; } ';
  2980. }
  2981. return ret;
  2982. }
  2983. grid.renderContainers.body.registerViewportAdjuster(function(adjustment) {
  2984. myWidth = updateContainerWidth();
  2985. // Subtract our own width
  2986. adjustment.width -= myWidth;
  2987. adjustment.side = $scope.side;
  2988. return adjustment;
  2989. });
  2990. // Register style computation to adjust for columns in `side`'s render container
  2991. grid.registerStyleComputation({
  2992. priority: 15,
  2993. func: updateContainerDimensions
  2994. });
  2995. }
  2996. };
  2997. }
  2998. };
  2999. }]);
  3000. })();
  3001. (function() {
  3002. angular.module('ui.grid')
  3003. .factory('Grid', ['$q', '$compile', '$parse', 'gridUtil', 'uiGridConstants', 'GridOptions', 'GridColumn', 'GridRow', 'GridApi', 'rowSorter', 'rowSearcher', 'GridRenderContainer', '$timeout', 'ScrollEvent',
  3004. function($q, $compile, $parse, gridUtil, uiGridConstants, GridOptions, GridColumn, GridRow, GridApi, rowSorter, rowSearcher, GridRenderContainer, $timeout, ScrollEvent) {
  3005. /**
  3006. * @ngdoc object
  3007. * @name ui.grid.core.api:PublicApi
  3008. * @description Public Api for the core grid features
  3009. *
  3010. */
  3011. /**
  3012. * @ngdoc function
  3013. * @name ui.grid.class:Grid
  3014. * @description Grid is the main viewModel. Any properties or methods needed to maintain state are defined in
  3015. * this prototype. One instance of Grid is created per Grid directive instance.
  3016. * @param {object} options Object map of options to pass into the grid. An 'id' property is expected.
  3017. */
  3018. var Grid = function Grid(options) {
  3019. var self = this;
  3020. // Get the id out of the options, then remove it
  3021. if (options !== undefined && typeof(options.id) !== 'undefined' && options.id) {
  3022. if (!/^[_a-zA-Z0-9-]+$/.test(options.id)) {
  3023. throw new Error("Grid id '" + options.id + '" is invalid. It must follow CSS selector syntax rules.');
  3024. }
  3025. } else {
  3026. throw new Error('No ID provided. An ID must be given when creating a grid.');
  3027. }
  3028. self.id = options.id;
  3029. delete options.id;
  3030. // Get default options
  3031. self.options = GridOptions.initialize(options);
  3032. /**
  3033. * @ngdoc object
  3034. * @name appScope
  3035. * @propertyOf ui.grid.class:Grid
  3036. * @description reference to the application scope (the parent scope of the ui-grid element). Assigned in ui-grid controller
  3037. * <br/>
  3038. * use gridOptions.appScopeProvider to override the default assignment of $scope.$parent with any reference
  3039. */
  3040. self.appScope = self.options.appScopeProvider;
  3041. self.headerHeight = self.options.headerRowHeight;
  3042. /**
  3043. * @ngdoc object
  3044. * @name footerHeight
  3045. * @propertyOf ui.grid.class:Grid
  3046. * @description returns the total footer height gridFooter + columnFooter
  3047. */
  3048. self.footerHeight = self.calcFooterHeight();
  3049. /**
  3050. * @ngdoc object
  3051. * @name columnFooterHeight
  3052. * @propertyOf ui.grid.class:Grid
  3053. * @description returns the total column footer height
  3054. */
  3055. self.columnFooterHeight = self.calcColumnFooterHeight();
  3056. self.rtl = false;
  3057. self.gridHeight = 0;
  3058. self.gridWidth = 0;
  3059. self.columnBuilders = [];
  3060. self.rowBuilders = [];
  3061. self.rowsProcessors = [];
  3062. self.columnsProcessors = [];
  3063. self.styleComputations = [];
  3064. self.viewportAdjusters = [];
  3065. self.rowHeaderColumns = [];
  3066. self.dataChangeCallbacks = {};
  3067. self.verticalScrollSyncCallBackFns = {};
  3068. self.horizontalScrollSyncCallBackFns = {};
  3069. // self.visibleRowCache = [];
  3070. // Set of 'render' containers for self grid, which can render sets of rows
  3071. self.renderContainers = {};
  3072. // Create a
  3073. self.renderContainers.body = new GridRenderContainer('body', self);
  3074. self.cellValueGetterCache = {};
  3075. // Cached function to use with custom row templates
  3076. self.getRowTemplateFn = null;
  3077. //representation of the rows on the grid.
  3078. //these are wrapped references to the actual data rows (options.data)
  3079. self.rows = [];
  3080. //represents the columns on the grid
  3081. self.columns = [];
  3082. /**
  3083. * @ngdoc boolean
  3084. * @name isScrollingVertically
  3085. * @propertyOf ui.grid.class:Grid
  3086. * @description set to true when Grid is scrolling vertically. Set to false via debounced method
  3087. */
  3088. self.isScrollingVertically = false;
  3089. /**
  3090. * @ngdoc boolean
  3091. * @name isScrollingHorizontally
  3092. * @propertyOf ui.grid.class:Grid
  3093. * @description set to true when Grid is scrolling horizontally. Set to false via debounced method
  3094. */
  3095. self.isScrollingHorizontally = false;
  3096. /**
  3097. * @ngdoc property
  3098. * @name scrollDirection
  3099. * @propertyOf ui.grid.class:Grid
  3100. * @description set one of the uiGridConstants.scrollDirection values (UP, DOWN, LEFT, RIGHT, NONE), which tells
  3101. * us which direction we are scrolling. Set to NONE via debounced method
  3102. */
  3103. self.scrollDirection = uiGridConstants.scrollDirection.NONE;
  3104. //if true, grid will not respond to any scroll events
  3105. self.disableScrolling = false;
  3106. function vertical(scrollEvent) {
  3107. self.isScrollingVertically = false;
  3108. self.api.core.raise.scrollEnd(scrollEvent);
  3109. self.scrollDirection = uiGridConstants.scrollDirection.NONE;
  3110. }
  3111. var debouncedVertical = gridUtil.debounce(vertical, self.options.scrollDebounce);
  3112. var debouncedVerticalMinDelay = gridUtil.debounce(vertical, 0);
  3113. function horizontal(scrollEvent) {
  3114. self.isScrollingHorizontally = false;
  3115. self.api.core.raise.scrollEnd(scrollEvent);
  3116. self.scrollDirection = uiGridConstants.scrollDirection.NONE;
  3117. }
  3118. var debouncedHorizontal = gridUtil.debounce(horizontal, self.options.scrollDebounce);
  3119. var debouncedHorizontalMinDelay = gridUtil.debounce(horizontal, 0);
  3120. /**
  3121. * @ngdoc function
  3122. * @name flagScrollingVertically
  3123. * @methodOf ui.grid.class:Grid
  3124. * @description sets isScrollingVertically to true and sets it to false in a debounced function
  3125. */
  3126. self.flagScrollingVertically = function(scrollEvent) {
  3127. if (!self.isScrollingVertically && !self.isScrollingHorizontally) {
  3128. self.api.core.raise.scrollBegin(scrollEvent);
  3129. }
  3130. self.isScrollingVertically = true;
  3131. if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) {
  3132. debouncedVerticalMinDelay(scrollEvent);
  3133. } else {
  3134. debouncedVertical(scrollEvent);
  3135. }
  3136. };
  3137. /**
  3138. * @ngdoc function
  3139. * @name flagScrollingHorizontally
  3140. * @methodOf ui.grid.class:Grid
  3141. * @description sets isScrollingHorizontally to true and sets it to false in a debounced function
  3142. */
  3143. self.flagScrollingHorizontally = function(scrollEvent) {
  3144. if (!self.isScrollingVertically && !self.isScrollingHorizontally) {
  3145. self.api.core.raise.scrollBegin(scrollEvent);
  3146. }
  3147. self.isScrollingHorizontally = true;
  3148. if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) {
  3149. debouncedHorizontalMinDelay(scrollEvent);
  3150. } else {
  3151. debouncedHorizontal(scrollEvent);
  3152. }
  3153. };
  3154. self.scrollbarHeight = 0;
  3155. self.scrollbarWidth = 0;
  3156. if (self.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) {
  3157. self.scrollbarHeight = gridUtil.getScrollbarWidth();
  3158. }
  3159. if (self.options.enableVerticalScrollbar === uiGridConstants.scrollbars.ALWAYS) {
  3160. self.scrollbarWidth = gridUtil.getScrollbarWidth();
  3161. }
  3162. self.api = new GridApi(self);
  3163. /**
  3164. * @ngdoc function
  3165. * @name refresh
  3166. * @methodOf ui.grid.core.api:PublicApi
  3167. * @description Refresh the rendered grid on screen.
  3168. * The refresh method re-runs both the columnProcessors and the
  3169. * rowProcessors, as well as calling refreshCanvas to update all
  3170. * the grid sizing. In general you should prefer to use queueGridRefresh
  3171. * instead, which is basically a debounced version of refresh.
  3172. *
  3173. * If you only want to resize the grid, not regenerate all the rows
  3174. * and columns, you should consider directly calling refreshCanvas instead.
  3175. *
  3176. */
  3177. self.api.registerMethod('core', 'refresh', this.refresh);
  3178. /**
  3179. * @ngdoc function
  3180. * @name queueGridRefresh
  3181. * @methodOf ui.grid.core.api:PublicApi
  3182. * @description Request a refresh of the rendered grid on screen, if multiple
  3183. * calls to queueGridRefresh are made within a digest cycle only one will execute.
  3184. * The refresh method re-runs both the columnProcessors and the
  3185. * rowProcessors, as well as calling refreshCanvas to update all
  3186. * the grid sizing. In general you should prefer to use queueGridRefresh
  3187. * instead, which is basically a debounced version of refresh.
  3188. *
  3189. */
  3190. self.api.registerMethod('core', 'queueGridRefresh', this.queueGridRefresh);
  3191. /**
  3192. * @ngdoc function
  3193. * @name refreshRows
  3194. * @methodOf ui.grid.core.api:PublicApi
  3195. * @description Runs only the rowProcessors, columns remain as they were.
  3196. * It then calls redrawInPlace and refreshCanvas, which adjust the grid sizing.
  3197. * @returns {promise} promise that is resolved when render completes?
  3198. *
  3199. */
  3200. self.api.registerMethod('core', 'refreshRows', this.refreshRows);
  3201. /**
  3202. * @ngdoc function
  3203. * @name queueRefresh
  3204. * @methodOf ui.grid.core.api:PublicApi
  3205. * @description Requests execution of refreshCanvas, if multiple requests are made
  3206. * during a digest cycle only one will run. RefreshCanvas updates the grid sizing.
  3207. * @returns {promise} promise that is resolved when render completes?
  3208. *
  3209. */
  3210. self.api.registerMethod('core', 'queueRefresh', this.queueRefresh);
  3211. /**
  3212. * @ngdoc function
  3213. * @name handleWindowResize
  3214. * @methodOf ui.grid.core.api:PublicApi
  3215. * @description Trigger a grid resize, normally this would be picked
  3216. * up by a watch on window size, but in some circumstances it is necessary
  3217. * to call this manually
  3218. * @returns {promise} promise that is resolved when render completes?
  3219. *
  3220. */
  3221. self.api.registerMethod('core', 'handleWindowResize', this.handleWindowResize);
  3222. /**
  3223. * @ngdoc function
  3224. * @name addRowHeaderColumn
  3225. * @methodOf ui.grid.core.api:PublicApi
  3226. * @description adds a row header column to the grid
  3227. * @param {object} column def
  3228. *
  3229. */
  3230. self.api.registerMethod('core', 'addRowHeaderColumn', this.addRowHeaderColumn);
  3231. /**
  3232. * @ngdoc function
  3233. * @name scrollToIfNecessary
  3234. * @methodOf ui.grid.core.api:PublicApi
  3235. * @description Scrolls the grid to make a certain row and column combo visible,
  3236. * in the case that it is not completely visible on the screen already.
  3237. * @param {GridRow} gridRow row to make visible
  3238. * @param {GridCol} gridCol column to make visible
  3239. * @returns {promise} a promise that is resolved when scrolling is complete
  3240. *
  3241. */
  3242. self.api.registerMethod('core', 'scrollToIfNecessary', function(gridRow, gridCol) { return self.scrollToIfNecessary(gridRow, gridCol); });
  3243. /**
  3244. * @ngdoc function
  3245. * @name scrollTo
  3246. * @methodOf ui.grid.core.api:PublicApi
  3247. * @description Scroll the grid such that the specified
  3248. * row and column is in view
  3249. * @param {object} rowEntity gridOptions.data[] array instance to make visible
  3250. * @param {object} colDef to make visible
  3251. * @returns {promise} a promise that is resolved after any scrolling is finished
  3252. */
  3253. self.api.registerMethod('core', 'scrollTo', function(rowEntity, colDef) { return self.scrollTo(rowEntity, colDef); });
  3254. /**
  3255. * @ngdoc function
  3256. * @name registerRowsProcessor
  3257. * @methodOf ui.grid.core.api:PublicApi
  3258. * @description
  3259. * Register a "rows processor" function. When the rows are updated,
  3260. * the grid calls each registered "rows processor", which has a chance
  3261. * to alter the set of rows (sorting, etc) as long as the count is not
  3262. * modified.
  3263. *
  3264. * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which
  3265. * is run in the context of the grid (i.e. this for the function will be the grid), and must
  3266. * return the updated rows list, which is passed to the next processor in the chain
  3267. * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
  3268. * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier.
  3269. *
  3270. * At present allRowsVisible is running at 50, sort manipulations running at 60-65, filter is running at 100,
  3271. * sort is at 200, grouping and treeview at 400-410, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
  3272. */
  3273. self.api.registerMethod('core', 'registerRowsProcessor', this.registerRowsProcessor);
  3274. /**
  3275. * @ngdoc function
  3276. * @name registerColumnsProcessor
  3277. * @methodOf ui.grid.core.api:PublicApi
  3278. * @description
  3279. * Register a "columns processor" function. When the columns are updated,
  3280. * the grid calls each registered "columns processor", which has a chance
  3281. * to alter the set of columns as long as the count is not
  3282. * modified.
  3283. *
  3284. * @param {function(renderedColumnsToProcess, rows )} processorFunction columns processor function, which
  3285. * is run in the context of the grid (i.e. this for the function will be the grid), and must
  3286. * return the updated columns list, which is passed to the next processor in the chain
  3287. * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
  3288. * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier.
  3289. *
  3290. * 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)
  3291. */
  3292. self.api.registerMethod('core', 'registerColumnsProcessor', this.registerColumnsProcessor);
  3293. /**
  3294. * @ngdoc function
  3295. * @name sortHandleNulls
  3296. * @methodOf ui.grid.core.api:PublicApi
  3297. * @description A null handling method that can be used when building custom sort
  3298. * functions
  3299. * @example
  3300. * <pre>
  3301. * mySortFn = function(a, b) {
  3302. * var nulls = $scope.gridApi.core.sortHandleNulls(a, b);
  3303. * if ( nulls !== null ){
  3304. * return nulls;
  3305. * } else {
  3306. * // your code for sorting here
  3307. * };
  3308. * </pre>
  3309. * @param {object} a sort value a
  3310. * @param {object} b sort value b
  3311. * @returns {number} null if there were no nulls/undefineds, otherwise returns
  3312. * a sort value that should be passed back from the sort function
  3313. *
  3314. */
  3315. self.api.registerMethod('core', 'sortHandleNulls', rowSorter.handleNulls);
  3316. /**
  3317. * @ngdoc function
  3318. * @name sortChanged
  3319. * @methodOf ui.grid.core.api:PublicApi
  3320. * @description The sort criteria on one or more columns has
  3321. * changed. Provides as parameters the grid and the output of
  3322. * getColumnSorting, which is an array of gridColumns
  3323. * that have sorting on them, sorted in priority order.
  3324. *
  3325. * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed.
  3326. * @param {Function} callBack Will be called when the event is emited. The function passes back an array of columns with
  3327. * sorts on them, in priority order.
  3328. *
  3329. * @example
  3330. * <pre>
  3331. * gridApi.core.on.sortChanged( $scope, function(sortColumns){
  3332. * // do something
  3333. * });
  3334. * </pre>
  3335. */
  3336. self.api.registerEvent('core', 'sortChanged');
  3337. /**
  3338. * @ngdoc function
  3339. * @name columnVisibilityChanged
  3340. * @methodOf ui.grid.core.api:PublicApi
  3341. * @description The visibility of a column has changed,
  3342. * the column itself is passed out as a parameter of the event.
  3343. *
  3344. * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed.
  3345. * @param {Function} callBack Will be called when the event is emited. The function passes back the GridCol that has changed.
  3346. *
  3347. * @example
  3348. * <pre>
  3349. * gridApi.core.on.columnVisibilityChanged( $scope, function (column) {
  3350. * // do something
  3351. * } );
  3352. * </pre>
  3353. */
  3354. self.api.registerEvent('core', 'columnVisibilityChanged');
  3355. /**
  3356. * @ngdoc method
  3357. * @name notifyDataChange
  3358. * @methodOf ui.grid.core.api:PublicApi
  3359. * @description Notify the grid that a data or config change has occurred,
  3360. * where that change isn't something the grid was otherwise noticing. This
  3361. * might be particularly relevant where you've changed values within the data
  3362. * and you'd like cell classes to be re-evaluated, or changed config within
  3363. * the columnDef and you'd like headerCellClasses to be re-evaluated.
  3364. * @param {string} type one of the
  3365. * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN), which tells
  3366. * us which refreshes to fire.
  3367. *
  3368. */
  3369. self.api.registerMethod('core', 'notifyDataChange', this.notifyDataChange);
  3370. /**
  3371. * @ngdoc method
  3372. * @name clearAllFilters
  3373. * @methodOf ui.grid.core.api:PublicApi
  3374. * @description Clears all filters and optionally refreshes the visible rows.
  3375. * @param {object} refreshRows Defaults to true.
  3376. * @param {object} clearConditions Defaults to false.
  3377. * @param {object} clearFlags Defaults to false.
  3378. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing.
  3379. */
  3380. self.api.registerMethod('core', 'clearAllFilters', this.clearAllFilters);
  3381. self.registerDataChangeCallback(self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]);
  3382. self.registerDataChangeCallback(self.processRowsCallback, [uiGridConstants.dataChange.EDIT]);
  3383. self.registerDataChangeCallback(self.updateFooterHeightCallback, [uiGridConstants.dataChange.OPTIONS]);
  3384. self.registerStyleComputation({
  3385. priority: 10,
  3386. func: self.getFooterStyles
  3387. });
  3388. };
  3389. Grid.prototype.calcFooterHeight = function() {
  3390. if (!this.hasFooter()) {
  3391. return 0;
  3392. }
  3393. var height = 0;
  3394. // if (this.options.showGridFooter) {
  3395. // height += this.options.gridFooterHeight;
  3396. // }
  3397. height += this.calcColumnFooterHeight();
  3398. return height;
  3399. };
  3400. Grid.prototype.calcColumnFooterHeight = function() {
  3401. var height = 0;
  3402. if (this.options.showColumnFooter) {
  3403. height += this.options.columnFooterHeight;
  3404. }
  3405. return height;
  3406. };
  3407. Grid.prototype.getFooterStyles = function() {
  3408. var style = '.grid' + this.id + ' .ui-grid-footer-aggregates-row { height: ' + this.options.columnFooterHeight + 'px; }';
  3409. style += ' .grid' + this.id + ' .ui-grid-footer-info { height: ' + this.options.gridFooterHeight + 'px; }';
  3410. return style;
  3411. };
  3412. Grid.prototype.hasFooter = function() {
  3413. return this.options.showGridFooter || this.options.showColumnFooter;
  3414. };
  3415. /**
  3416. * @ngdoc function
  3417. * @name isRTL
  3418. * @methodOf ui.grid.class:Grid
  3419. * @description Returns true if grid is RightToLeft
  3420. */
  3421. Grid.prototype.isRTL = function() {
  3422. return this.rtl;
  3423. };
  3424. /**
  3425. * @ngdoc function
  3426. * @name registerColumnBuilder
  3427. * @methodOf ui.grid.class:Grid
  3428. * @description When the build creates columns from column definitions, the columnbuilders will be called to add
  3429. * additional properties to the column.
  3430. * @param {function(colDef, col, gridOptions)} columnBuilder function to be called
  3431. */
  3432. Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) {
  3433. this.columnBuilders.push(columnBuilder);
  3434. };
  3435. /**
  3436. * @ngdoc function
  3437. * @name buildColumnDefsFromData
  3438. * @methodOf ui.grid.class:Grid
  3439. * @description Populates columnDefs from the provided data
  3440. * @param {function(colDef, col, gridOptions)} rowBuilder function to be called
  3441. */
  3442. Grid.prototype.buildColumnDefsFromData = function(dataRows) {
  3443. this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties);
  3444. };
  3445. /**
  3446. * @ngdoc function
  3447. * @name registerRowBuilder
  3448. * @methodOf ui.grid.class:Grid
  3449. * @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add
  3450. * additional properties to the row.
  3451. * @param {function(row, gridOptions)} rowBuilder function to be called
  3452. */
  3453. Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) {
  3454. this.rowBuilders.push(rowBuilder);
  3455. };
  3456. /**
  3457. * @ngdoc function
  3458. * @name registerDataChangeCallback
  3459. * @methodOf ui.grid.class:Grid
  3460. * @description When a data change occurs, the data change callbacks of the specified type
  3461. * will be called. The rules are:
  3462. *
  3463. * - when the data watch fires, that is considered a ROW change (the data watch only notices
  3464. * added or removed rows)
  3465. * - when the api is called to inform us of a change, the declared type of that change is used
  3466. * - when a cell edit completes, the EDIT callbacks are triggered
  3467. * - when the columnDef watch fires, the COLUMN callbacks are triggered
  3468. * - when the options watch fires, the OPTIONS callbacks are triggered
  3469. *
  3470. * For a given event:
  3471. * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks
  3472. * - ROW calls ROW and ALL callbacks
  3473. * - EDIT calls EDIT and ALL callbacks
  3474. * - COLUMN calls COLUMN and ALL callbacks
  3475. * - OPTIONS calls OPTIONS and ALL callbacks
  3476. *
  3477. * @param {function(grid)} callback function to be called
  3478. * @param {array} types the types of data change you want to be informed of. Values from
  3479. * the uiGridConstants.dataChange values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to
  3480. * ALL
  3481. * @returns {function} deregister function - a function that can be called to deregister this callback
  3482. */
  3483. Grid.prototype.registerDataChangeCallback = function registerDataChangeCallback(callback, types, _this) {
  3484. var uid = gridUtil.nextUid();
  3485. if (!types) {
  3486. types = [uiGridConstants.dataChange.ALL];
  3487. }
  3488. if (!Array.isArray(types)) {
  3489. gridUtil.logError("Expected types to be an array or null in registerDataChangeCallback, value passed was: " + types);
  3490. }
  3491. this.dataChangeCallbacks[uid] = { callback: callback, types: types, _this: _this };
  3492. var self = this;
  3493. var deregisterFunction = function() {
  3494. delete self.dataChangeCallbacks[uid];
  3495. };
  3496. return deregisterFunction;
  3497. };
  3498. /**
  3499. * @ngdoc function
  3500. * @name callDataChangeCallbacks
  3501. * @methodOf ui.grid.class:Grid
  3502. * @description Calls the callbacks based on the type of data change that
  3503. * has occurred. Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks if the
  3504. * event type is matching, or if the type is ALL.
  3505. * @param {number} type the type of event that occurred - one of the
  3506. * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN, OPTIONS)
  3507. */
  3508. Grid.prototype.callDataChangeCallbacks = function callDataChangeCallbacks(type, options) {
  3509. angular.forEach(this.dataChangeCallbacks, function(callback, uid) {
  3510. if (callback.types.indexOf(uiGridConstants.dataChange.ALL) !== -1 ||
  3511. callback.types.indexOf(type) !== -1 ||
  3512. type === uiGridConstants.dataChange.ALL) {
  3513. if (callback._this) {
  3514. callback.callback.apply(callback._this, this);
  3515. } else {
  3516. callback.callback(this);
  3517. }
  3518. }
  3519. }, this);
  3520. };
  3521. /**
  3522. * @ngdoc function
  3523. * @name notifyDataChange
  3524. * @methodOf ui.grid.class:Grid
  3525. * @description Notifies us that a data change has occurred, used in the public
  3526. * api for users to tell us when they've changed data or some other event that
  3527. * our watches cannot pick up
  3528. * @param {string} type the type of event that occurred - one of the
  3529. * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN)
  3530. */
  3531. Grid.prototype.notifyDataChange = function notifyDataChange(type) {
  3532. var constants = uiGridConstants.dataChange;
  3533. if (type === constants.ALL ||
  3534. type === constants.COLUMN ||
  3535. type === constants.EDIT ||
  3536. type === constants.ROW ||
  3537. type === constants.OPTIONS) {
  3538. this.callDataChangeCallbacks(type);
  3539. } else {
  3540. gridUtil.logError("Notified of a data change, but the type was not recognised, so no action taken, type was: " + type);
  3541. }
  3542. };
  3543. /**
  3544. * @ngdoc function
  3545. * @name columnRefreshCallback
  3546. * @methodOf ui.grid.class:Grid
  3547. * @description refreshes the grid when a column refresh
  3548. * is notified, which triggers handling of the visible flag.
  3549. * This is called on uiGridConstants.dataChange.COLUMN, and is
  3550. * registered as a dataChangeCallback in grid.js
  3551. * @param {string} name column name
  3552. */
  3553. Grid.prototype.columnRefreshCallback = function columnRefreshCallback(grid) {
  3554. grid.buildColumns();
  3555. grid.queueGridRefresh();
  3556. };
  3557. /**
  3558. * @ngdoc function
  3559. * @name processRowsCallback
  3560. * @methodOf ui.grid.class:Grid
  3561. * @description calls the row processors, specifically
  3562. * intended to reset the sorting when an edit is called,
  3563. * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT
  3564. * @param {string} name column name
  3565. */
  3566. Grid.prototype.processRowsCallback = function processRowsCallback(grid) {
  3567. grid.queueGridRefresh();
  3568. };
  3569. /**
  3570. * @ngdoc function
  3571. * @name updateFooterHeightCallback
  3572. * @methodOf ui.grid.class:Grid
  3573. * @description recalculates the footer height,
  3574. * registered as a dataChangeCallback on uiGridConstants.dataChange.OPTIONS
  3575. * @param {string} name column name
  3576. */
  3577. Grid.prototype.updateFooterHeightCallback = function updateFooterHeightCallback(grid) {
  3578. grid.footerHeight = grid.calcFooterHeight();
  3579. grid.columnFooterHeight = grid.calcColumnFooterHeight();
  3580. };
  3581. /**
  3582. * @ngdoc function
  3583. * @name getColumn
  3584. * @methodOf ui.grid.class:Grid
  3585. * @description returns a grid column for the column name
  3586. * @param {string} name column name
  3587. */
  3588. Grid.prototype.getColumn = function getColumn(name) {
  3589. var columns = this.columns.filter(function(column) {
  3590. return column.colDef.name === name;
  3591. });
  3592. return columns.length > 0 ? columns[0] : null;
  3593. };
  3594. /**
  3595. * @ngdoc function
  3596. * @name getColDef
  3597. * @methodOf ui.grid.class:Grid
  3598. * @description returns a grid colDef for the column name
  3599. * @param {string} name column.field
  3600. */
  3601. Grid.prototype.getColDef = function getColDef(name) {
  3602. var colDefs = this.options.columnDefs.filter(function(colDef) {
  3603. return colDef.name === name;
  3604. });
  3605. return colDefs.length > 0 ? colDefs[0] : null;
  3606. };
  3607. /**
  3608. * @ngdoc function
  3609. * @name assignTypes
  3610. * @methodOf ui.grid.class:Grid
  3611. * @description uses the first row of data to assign colDef.type for any types not defined.
  3612. */
  3613. /**
  3614. * @ngdoc property
  3615. * @name type
  3616. * @propertyOf ui.grid.class:GridOptions.columnDef
  3617. * @description the type of the column, used in sorting. If not provided then the
  3618. * grid will guess the type. Add this only if the grid guessing is not to your
  3619. * satisfaction. One of:
  3620. * - 'string'
  3621. * - 'boolean'
  3622. * - 'number'
  3623. * - 'date'
  3624. * - 'object'
  3625. * - 'numberStr'
  3626. * Note that if you choose date, your dates should be in a javascript date type
  3627. *
  3628. */
  3629. Grid.prototype.assignTypes = function() {
  3630. var self = this;
  3631. self.options.columnDefs.forEach(function(colDef, index) {
  3632. //Assign colDef type if not specified
  3633. if (!colDef.type) {
  3634. var col = new GridColumn(colDef, index, self);
  3635. var firstRow = self.rows.length > 0 ? self.rows[0] : null;
  3636. if (firstRow) {
  3637. colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col));
  3638. } else {
  3639. colDef.type = 'string';
  3640. }
  3641. }
  3642. });
  3643. };
  3644. /**
  3645. * @ngdoc function
  3646. * @name isRowHeaderColumn
  3647. * @methodOf ui.grid.class:Grid
  3648. * @description returns true if the column is a row Header
  3649. * @param {object} column column
  3650. */
  3651. Grid.prototype.isRowHeaderColumn = function isRowHeaderColumn(column) {
  3652. return this.rowHeaderColumns.indexOf(column) !== -1;
  3653. };
  3654. /**
  3655. * @ngdoc function
  3656. * @name addRowHeaderColumn
  3657. * @methodOf ui.grid.class:Grid
  3658. * @description adds a row header column to the grid
  3659. * @param {object} column def
  3660. */
  3661. Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef) {
  3662. var self = this;
  3663. var rowHeaderCol = new GridColumn(colDef, gridUtil.nextUid(), self);
  3664. rowHeaderCol.isRowHeader = true;
  3665. if (self.isRTL()) {
  3666. self.createRightContainer();
  3667. rowHeaderCol.renderContainer = 'right';
  3668. } else {
  3669. self.createLeftContainer();
  3670. rowHeaderCol.renderContainer = 'left';
  3671. }
  3672. // relies on the default column builder being first in array, as it is instantiated
  3673. // as part of grid creation
  3674. self.columnBuilders[0](colDef, rowHeaderCol, self.options)
  3675. .then(function() {
  3676. rowHeaderCol.enableFiltering = false;
  3677. rowHeaderCol.enableSorting = false;
  3678. rowHeaderCol.enableHiding = false;
  3679. self.rowHeaderColumns.push(rowHeaderCol);
  3680. self.buildColumns()
  3681. .then(function() {
  3682. self.preCompileCellTemplates();
  3683. self.queueGridRefresh();
  3684. });
  3685. });
  3686. };
  3687. /**
  3688. * @ngdoc function
  3689. * @name getOnlyDataColumns
  3690. * @methodOf ui.grid.class:Grid
  3691. * @description returns all columns except for rowHeader columns
  3692. */
  3693. Grid.prototype.getOnlyDataColumns = function getOnlyDataColumns() {
  3694. var self = this;
  3695. var cols = [];
  3696. self.columns.forEach(function(col) {
  3697. if (self.rowHeaderColumns.indexOf(col) === -1) {
  3698. cols.push(col);
  3699. }
  3700. });
  3701. return cols;
  3702. };
  3703. /**
  3704. * @ngdoc function
  3705. * @name buildColumns
  3706. * @methodOf ui.grid.class:Grid
  3707. * @description creates GridColumn objects from the columnDefinition. Calls each registered
  3708. * columnBuilder to further process the column
  3709. * @param {object} options An object contains options to use when building columns
  3710. *
  3711. * * **orderByColumnDefs**: defaults to **false**. When true, `buildColumns` will reorder existing columns according to the order within the column definitions.
  3712. *
  3713. * @returns {Promise} a promise to load any needed column resources
  3714. */
  3715. Grid.prototype.buildColumns = function buildColumns(opts) {
  3716. var options = {
  3717. orderByColumnDefs: false
  3718. };
  3719. angular.extend(options, opts);
  3720. // gridUtil.logDebug('buildColumns');
  3721. var self = this;
  3722. var builderPromises = [];
  3723. var headerOffset = self.rowHeaderColumns.length;
  3724. var i;
  3725. // Remove any columns for which a columnDef cannot be found
  3726. // Deliberately don't use forEach, as it doesn't like splice being called in the middle
  3727. // Also don't cache columns.length, as it will change during this operation
  3728. for (i = 0; i < self.columns.length; i++) {
  3729. if (!self.getColDef(self.columns[i].name)) {
  3730. self.columns.splice(i, 1);
  3731. i--;
  3732. }
  3733. }
  3734. //add row header columns to the grid columns array _after_ columns without columnDefs have been removed
  3735. self.rowHeaderColumns.forEach(function(rowHeaderColumn) {
  3736. self.columns.unshift(rowHeaderColumn);
  3737. });
  3738. // look at each column def, and update column properties to match. If the column def
  3739. // doesn't have a column, then splice in a new gridCol
  3740. self.options.columnDefs.forEach(function(colDef, index) {
  3741. self.preprocessColDef(colDef);
  3742. var col = self.getColumn(colDef.name);
  3743. if (!col) {
  3744. col = new GridColumn(colDef, gridUtil.nextUid(), self);
  3745. self.columns.splice(index + headerOffset, 0, col);
  3746. } else {
  3747. // tell updateColumnDef that the column was pre-existing
  3748. col.updateColumnDef(colDef, false);
  3749. }
  3750. self.columnBuilders.forEach(function(builder) {
  3751. builderPromises.push(builder.call(self, colDef, col, self.options));
  3752. });
  3753. });
  3754. /*** Reorder columns if necessary ***/
  3755. if (!!options.orderByColumnDefs) {
  3756. // Create a shallow copy of the columns as a cache
  3757. var columnCache = self.columns.slice(0);
  3758. // We need to allow for the "row headers" when mapping from the column defs array to the columns array
  3759. // 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]
  3760. // 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
  3761. // columns will be shorter than columnDefs. In this situation we'll avoid an error, but the user will still get an unexpected result
  3762. var len = Math.min(self.options.columnDefs.length, self.columns.length);
  3763. for (i = 0; i < len; i++) {
  3764. // If the column at this index has a different name than the column at the same index in the column defs...
  3765. if (self.columns[i + headerOffset].name !== self.options.columnDefs[i].name) {
  3766. // Replace the one in the cache with the appropriate column
  3767. columnCache[i + headerOffset] = self.getColumn(self.options.columnDefs[i].name);
  3768. } else {
  3769. // Otherwise just copy over the one from the initial columns
  3770. columnCache[i + headerOffset] = self.columns[i + headerOffset];
  3771. }
  3772. }
  3773. // Empty out the columns array, non-destructively
  3774. self.columns.length = 0;
  3775. // And splice in the updated, ordered columns from the cache
  3776. Array.prototype.splice.apply(self.columns, [0, 0].concat(columnCache));
  3777. }
  3778. return $q.all(builderPromises).then(function() {
  3779. if (self.rows.length > 0) {
  3780. self.assignTypes();
  3781. }
  3782. });
  3783. };
  3784. /**
  3785. * @ngdoc function
  3786. * @name preCompileCellTemplates
  3787. * @methodOf ui.grid.class:Grid
  3788. * @description precompiles all cell templates
  3789. */
  3790. Grid.prototype.preCompileCellTemplates = function() {
  3791. var self = this;
  3792. var preCompileTemplate = function(col) {
  3793. var html = col.cellTemplate.replace(uiGridConstants.MODEL_COL_FIELD, self.getQualifiedColField(col));
  3794. html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
  3795. var compiledElementFn = $compile(html);
  3796. col.compiledElementFn = compiledElementFn;
  3797. if (col.compiledElementFnDefer) {
  3798. col.compiledElementFnDefer.resolve(col.compiledElementFn);
  3799. }
  3800. };
  3801. this.columns.forEach(function(col) {
  3802. if (col.cellTemplate) {
  3803. preCompileTemplate(col);
  3804. } else if (col.cellTemplatePromise) {
  3805. col.cellTemplatePromise.then(function() {
  3806. preCompileTemplate(col);
  3807. });
  3808. }
  3809. });
  3810. };
  3811. /**
  3812. * @ngdoc function
  3813. * @name getGridQualifiedColField
  3814. * @methodOf ui.grid.class:Grid
  3815. * @description Returns the $parse-able accessor for a column within its $scope
  3816. * @param {GridColumn} col col object
  3817. */
  3818. Grid.prototype.getQualifiedColField = function(col) {
  3819. return 'row.entity.' + gridUtil.preEval(col.field);
  3820. };
  3821. /**
  3822. * @ngdoc function
  3823. * @name createLeftContainer
  3824. * @methodOf ui.grid.class:Grid
  3825. * @description creates the left render container if it doesn't already exist
  3826. */
  3827. Grid.prototype.createLeftContainer = function() {
  3828. if (!this.hasLeftContainer()) {
  3829. this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true });
  3830. }
  3831. };
  3832. /**
  3833. * @ngdoc function
  3834. * @name createRightContainer
  3835. * @methodOf ui.grid.class:Grid
  3836. * @description creates the right render container if it doesn't already exist
  3837. */
  3838. Grid.prototype.createRightContainer = function() {
  3839. if (!this.hasRightContainer()) {
  3840. this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true });
  3841. }
  3842. };
  3843. /**
  3844. * @ngdoc function
  3845. * @name hasLeftContainer
  3846. * @methodOf ui.grid.class:Grid
  3847. * @description returns true if leftContainer exists
  3848. */
  3849. Grid.prototype.hasLeftContainer = function() {
  3850. return this.renderContainers.left !== undefined;
  3851. };
  3852. /**
  3853. * @ngdoc function
  3854. * @name hasRightContainer
  3855. * @methodOf ui.grid.class:Grid
  3856. * @description returns true if rightContainer exists
  3857. */
  3858. Grid.prototype.hasRightContainer = function() {
  3859. return this.renderContainers.right !== undefined;
  3860. };
  3861. /**
  3862. * undocumented function
  3863. * @name preprocessColDef
  3864. * @methodOf ui.grid.class:Grid
  3865. * @description defaults the name property from field to maintain backwards compatibility with 2.x
  3866. * validates that name or field is present
  3867. */
  3868. Grid.prototype.preprocessColDef = function preprocessColDef(colDef) {
  3869. var self = this;
  3870. if (!colDef.field && !colDef.name) {
  3871. throw new Error('colDef.name or colDef.field property is required');
  3872. }
  3873. //maintain backwards compatibility with 2.x
  3874. //field was required in 2.x. now name is required
  3875. if (colDef.name === undefined && colDef.field !== undefined) {
  3876. // See if the column name already exists:
  3877. var newName = colDef.field,
  3878. counter = 2;
  3879. while (self.getColumn(newName)) {
  3880. newName = colDef.field + counter.toString();
  3881. counter++;
  3882. }
  3883. colDef.name = newName;
  3884. }
  3885. };
  3886. // 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
  3887. Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) {
  3888. var self = this;
  3889. var t = [];
  3890. for (var i = 0; i < n.length; i++) {
  3891. var nV = nAccessor ? n[i][nAccessor] : n[i];
  3892. var found = false;
  3893. for (var j = 0; j < o.length; j++) {
  3894. var oV = oAccessor ? o[j][oAccessor] : o[j];
  3895. if (self.options.rowEquality(nV, oV)) {
  3896. found = true;
  3897. break;
  3898. }
  3899. }
  3900. if (!found) {
  3901. t.push(nV);
  3902. }
  3903. }
  3904. return t;
  3905. };
  3906. /**
  3907. * @ngdoc function
  3908. * @name getRow
  3909. * @methodOf ui.grid.class:Grid
  3910. * @description returns the GridRow that contains the rowEntity
  3911. * @param {object} rowEntity the gridOptions.data array element instance
  3912. * @param {array} rows [optional] the rows to look in - if not provided then
  3913. * looks in grid.rows
  3914. */
  3915. Grid.prototype.getRow = function getRow(rowEntity, lookInRows) {
  3916. var self = this;
  3917. lookInRows = typeof(lookInRows) === 'undefined' ? self.rows : lookInRows;
  3918. var rows = lookInRows.filter(function(row) {
  3919. return self.options.rowEquality(row.entity, rowEntity);
  3920. });
  3921. return rows.length > 0 ? rows[0] : null;
  3922. };
  3923. /**
  3924. * @ngdoc function
  3925. * @name modifyRows
  3926. * @methodOf ui.grid.class:Grid
  3927. * @description creates or removes GridRow objects from the newRawData array. Calls each registered
  3928. * rowBuilder to further process the row
  3929. *
  3930. * This method aims to achieve three things:
  3931. * 1. the resulting rows array is in the same order as the newRawData, we'll call
  3932. * rowsProcessors immediately after to sort the data anyway
  3933. * 2. if we have row hashing available, we try to use the rowHash to find the row
  3934. * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected
  3935. *
  3936. * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates
  3937. * the newRows and newHash
  3938. *
  3939. * ```
  3940. * newRawData.forEach newEntity
  3941. * if (hashing enabled)
  3942. * check oldHash for newEntity
  3943. * else
  3944. * look for old row directly in oldRows
  3945. * if !oldRowFound // must be a new row
  3946. * create newRow
  3947. * append to the newRows and add to newHash
  3948. * run the processors
  3949. *
  3950. * Rows are identified using the hashKey if configured. If not configured, then rows
  3951. * are identified using the gridOptions.rowEquality function
  3952. */
  3953. Grid.prototype.modifyRows = function modifyRows(newRawData) {
  3954. var self = this;
  3955. var oldRows = self.rows.slice(0);
  3956. var oldRowHash = self.rowHashMap || self.createRowHashMap();
  3957. self.rowHashMap = self.createRowHashMap();
  3958. self.rows.length = 0;
  3959. newRawData.forEach(function(newEntity, i) {
  3960. var newRow;
  3961. if (self.options.enableRowHashing) {
  3962. // if hashing is enabled, then this row will be in the hash if we already know about it
  3963. newRow = oldRowHash.get(newEntity);
  3964. } else {
  3965. // otherwise, manually search the oldRows to see if we can find this row
  3966. newRow = self.getRow(newEntity, oldRows);
  3967. }
  3968. // if we didn't find the row, it must be new, so create it
  3969. if (!newRow) {
  3970. newRow = self.processRowBuilders(new GridRow(newEntity, i, self));
  3971. }
  3972. self.rows.push(newRow);
  3973. self.rowHashMap.put(newEntity, newRow);
  3974. });
  3975. self.assignTypes();
  3976. var p1 = $q.when(self.processRowsProcessors(self.rows))
  3977. .then(function(renderableRows) {
  3978. return self.setVisibleRows(renderableRows);
  3979. });
  3980. var p2 = $q.when(self.processColumnsProcessors(self.columns))
  3981. .then(function(renderableColumns) {
  3982. return self.setVisibleColumns(renderableColumns);
  3983. });
  3984. return $q.all([p1, p2]);
  3985. };
  3986. /**
  3987. * Private Undocumented Method
  3988. * @name addRows
  3989. * @methodOf ui.grid.class:Grid
  3990. * @description adds the newRawData array of rows to the grid and calls all registered
  3991. * rowBuilders. this keyword will reference the grid
  3992. */
  3993. Grid.prototype.addRows = function addRows(newRawData) {
  3994. var self = this;
  3995. var existingRowCount = self.rows.length;
  3996. for (var i = 0; i < newRawData.length; i++) {
  3997. var newRow = self.processRowBuilders(new GridRow(newRawData[i], i + existingRowCount, self));
  3998. if (self.options.enableRowHashing) {
  3999. var found = self.rowHashMap.get(newRow.entity);
  4000. if (found) {
  4001. found.row = newRow;
  4002. }
  4003. }
  4004. self.rows.push(newRow);
  4005. }
  4006. };
  4007. /**
  4008. * @ngdoc function
  4009. * @name processRowBuilders
  4010. * @methodOf ui.grid.class:Grid
  4011. * @description processes all RowBuilders for the gridRow
  4012. * @param {GridRow} gridRow reference to gridRow
  4013. * @returns {GridRow} the gridRow with all additional behavior added
  4014. */
  4015. Grid.prototype.processRowBuilders = function processRowBuilders(gridRow) {
  4016. var self = this;
  4017. self.rowBuilders.forEach(function(builder) {
  4018. builder.call(self, gridRow, self.options);
  4019. });
  4020. return gridRow;
  4021. };
  4022. /**
  4023. * @ngdoc function
  4024. * @name registerStyleComputation
  4025. * @methodOf ui.grid.class:Grid
  4026. * @description registered a styleComputation function
  4027. *
  4028. * If the function returns a value it will be appended into the grid's `<style>` block
  4029. * @param {function($scope)} styleComputation function
  4030. */
  4031. Grid.prototype.registerStyleComputation = function registerStyleComputation(styleComputationInfo) {
  4032. this.styleComputations.push(styleComputationInfo);
  4033. };
  4034. // NOTE (c0bra): We already have rowBuilders. I think these do exactly the same thing...
  4035. // Grid.prototype.registerRowFilter = function(filter) {
  4036. // // TODO(c0bra): validate filter?
  4037. // this.rowFilters.push(filter);
  4038. // };
  4039. // Grid.prototype.removeRowFilter = function(filter) {
  4040. // var idx = this.rowFilters.indexOf(filter);
  4041. // if (typeof(idx) !== 'undefined' && idx !== undefined) {
  4042. // this.rowFilters.slice(idx, 1);
  4043. // }
  4044. // };
  4045. // Grid.prototype.processRowFilters = function(rows) {
  4046. // var self = this;
  4047. // self.rowFilters.forEach(function (filter) {
  4048. // filter.call(self, rows);
  4049. // });
  4050. // };
  4051. /**
  4052. * @ngdoc function
  4053. * @name registerRowsProcessor
  4054. * @methodOf ui.grid.class:Grid
  4055. * @description
  4056. *
  4057. * Register a "rows processor" function. When the rows are updated,
  4058. * the grid calls each registered "rows processor", which has a chance
  4059. * to alter the set of rows (sorting, etc) as long as the count is not
  4060. * modified.
  4061. *
  4062. * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which
  4063. * is run in the context of the grid (i.e. this for the function will be the grid), and must
  4064. * return the updated rows list, which is passed to the next processor in the chain
  4065. * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
  4066. * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier.
  4067. *
  4068. * 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)
  4069. *
  4070. */
  4071. Grid.prototype.registerRowsProcessor = function registerRowsProcessor(processor, priority) {
  4072. if (!angular.isFunction(processor)) {
  4073. throw 'Attempt to register non-function rows processor: ' + processor;
  4074. }
  4075. this.rowsProcessors.push({ processor: processor, priority: priority });
  4076. this.rowsProcessors.sort(function sortByPriority(a, b) {
  4077. return a.priority - b.priority;
  4078. });
  4079. };
  4080. /**
  4081. * @ngdoc function
  4082. * @name removeRowsProcessor
  4083. * @methodOf ui.grid.class:Grid
  4084. * @param {function(renderableRows)} rows processor function
  4085. * @description Remove a registered rows processor
  4086. */
  4087. Grid.prototype.removeRowsProcessor = function removeRowsProcessor(processor) {
  4088. var idx = -1;
  4089. this.rowsProcessors.forEach(function(rowsProcessor, index) {
  4090. if (rowsProcessor.processor === processor) {
  4091. idx = index;
  4092. }
  4093. });
  4094. if (idx !== -1) {
  4095. this.rowsProcessors.splice(idx, 1);
  4096. }
  4097. };
  4098. /**
  4099. * Private Undocumented Method
  4100. * @name processRowsProcessors
  4101. * @methodOf ui.grid.class:Grid
  4102. * @param {Array[GridRow]} The array of "renderable" rows
  4103. * @param {Array[GridColumn]} The array of columns
  4104. * @description Run all the registered rows processors on the array of renderable rows
  4105. */
  4106. Grid.prototype.processRowsProcessors = function processRowsProcessors(renderableRows) {
  4107. var self = this;
  4108. // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order
  4109. var myRenderableRows = renderableRows.slice(0);
  4110. // Return myRenderableRows with no processing if we have no rows processors
  4111. if (self.rowsProcessors.length === 0) {
  4112. return $q.when(myRenderableRows);
  4113. }
  4114. // Counter for iterating through rows processors
  4115. var i = 0;
  4116. // Promise for when we're done with all the processors
  4117. var finished = $q.defer();
  4118. // This function will call the processor in self.rowsProcessors at index 'i', and then
  4119. // when done will call the next processor in the list, using the output from the processor
  4120. // at i as the argument for 'renderedRowsToProcess' on the next iteration.
  4121. //
  4122. // If we're at the end of the list of processors, we resolve our 'finished' callback with
  4123. // the result.
  4124. function startProcessor(i, renderedRowsToProcess) {
  4125. // Get the processor at 'i'
  4126. var processor = self.rowsProcessors[i].processor;
  4127. // Call the processor, passing in the rows to process and the current columns
  4128. // (note: it's wrapped in $q.when() in case the processor does not return a promise)
  4129. return $q.when(processor.call(self, renderedRowsToProcess, self.columns))
  4130. .then(function handleProcessedRows(processedRows) {
  4131. // Check for errors
  4132. if (!processedRows) {
  4133. throw "Processor at index " + i + " did not return a set of renderable rows";
  4134. }
  4135. if (!angular.isArray(processedRows)) {
  4136. throw "Processor at index " + i + " did not return an array";
  4137. }
  4138. // Processor is done, increment the counter
  4139. i++;
  4140. // If we're not done with the processors, call the next one
  4141. if (i <= self.rowsProcessors.length - 1) {
  4142. return startProcessor(i, processedRows);
  4143. }
  4144. // We're done! Resolve the 'finished' promise
  4145. else {
  4146. finished.resolve(processedRows);
  4147. }
  4148. });
  4149. }
  4150. // Start on the first processor
  4151. startProcessor(0, myRenderableRows);
  4152. return finished.promise;
  4153. };
  4154. Grid.prototype.setVisibleRows = function setVisibleRows(rows) {
  4155. var self = this;
  4156. // Reset all the render container row caches
  4157. for (var i in self.renderContainers) {
  4158. var container = self.renderContainers[i];
  4159. container.canvasHeightShouldUpdate = true;
  4160. if (typeof(container.visibleRowCache) === 'undefined') {
  4161. container.visibleRowCache = [];
  4162. } else {
  4163. container.visibleRowCache.length = 0;
  4164. }
  4165. }
  4166. // rows.forEach(function (row) {
  4167. for (var ri = 0; ri < rows.length; ri++) {
  4168. var row = rows[ri];
  4169. var targetContainer = (typeof(row.renderContainer) !== 'undefined' && row.renderContainer) ? row.renderContainer : 'body';
  4170. // If the row is visible
  4171. if (row.visible) {
  4172. self.renderContainers[targetContainer].visibleRowCache.push(row);
  4173. }
  4174. }
  4175. self.api.core.raise.rowsRendered(this.api);
  4176. };
  4177. /**
  4178. * @ngdoc function
  4179. * @name registerColumnsProcessor
  4180. * @methodOf ui.grid.class:Grid
  4181. * @param {function(renderedColumnsToProcess, rows)} columnProcessor column processor function, which
  4182. * is run in the context of the grid (i.e. this for the function will be the grid), and
  4183. * which must return an updated renderedColumnsToProcess which can be passed to the next processor
  4184. * in the chain
  4185. * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
  4186. * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier.
  4187. *
  4188. * 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)
  4189. * @description
  4190. Register a "columns processor" function. When the columns are updated,
  4191. the grid calls each registered "columns processor", which has a chance
  4192. to alter the set of columns, as long as the count is not modified.
  4193. */
  4194. Grid.prototype.registerColumnsProcessor = function registerColumnsProcessor(processor, priority) {
  4195. if (!angular.isFunction(processor)) {
  4196. throw 'Attempt to register non-function rows processor: ' + processor;
  4197. }
  4198. this.columnsProcessors.push({ processor: processor, priority: priority });
  4199. this.columnsProcessors.sort(function sortByPriority(a, b) {
  4200. return a.priority - b.priority;
  4201. });
  4202. };
  4203. Grid.prototype.removeColumnsProcessor = function removeColumnsProcessor(processor) {
  4204. var idx = this.columnsProcessors.indexOf(processor);
  4205. if (typeof(idx) !== 'undefined' && idx !== undefined) {
  4206. this.columnsProcessors.splice(idx, 1);
  4207. }
  4208. };
  4209. Grid.prototype.processColumnsProcessors = function processColumnsProcessors(renderableColumns) {
  4210. var self = this;
  4211. // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order
  4212. var myRenderableColumns = renderableColumns.slice(0);
  4213. // Return myRenderableRows with no processing if we have no rows processors
  4214. if (self.columnsProcessors.length === 0) {
  4215. return $q.when(myRenderableColumns);
  4216. }
  4217. // Counter for iterating through rows processors
  4218. var i = 0;
  4219. // Promise for when we're done with all the processors
  4220. var finished = $q.defer();
  4221. // This function will call the processor in self.rowsProcessors at index 'i', and then
  4222. // when done will call the next processor in the list, using the output from the processor
  4223. // at i as the argument for 'renderedRowsToProcess' on the next iteration.
  4224. //
  4225. // If we're at the end of the list of processors, we resolve our 'finished' callback with
  4226. // the result.
  4227. function startProcessor(i, renderedColumnsToProcess) {
  4228. // Get the processor at 'i'
  4229. var processor = self.columnsProcessors[i].processor;
  4230. // Call the processor, passing in the rows to process and the current columns
  4231. // (note: it's wrapped in $q.when() in case the processor does not return a promise)
  4232. return $q.when(processor.call(self, renderedColumnsToProcess, self.rows))
  4233. .then(function handleProcessedRows(processedColumns) {
  4234. // Check for errors
  4235. if (!processedColumns) {
  4236. throw "Processor at index " + i + " did not return a set of renderable rows";
  4237. }
  4238. if (!angular.isArray(processedColumns)) {
  4239. throw "Processor at index " + i + " did not return an array";
  4240. }
  4241. // Processor is done, increment the counter
  4242. i++;
  4243. // If we're not done with the processors, call the next one
  4244. if (i <= self.columnsProcessors.length - 1) {
  4245. return startProcessor(i, myRenderableColumns);
  4246. }
  4247. // We're done! Resolve the 'finished' promise
  4248. else {
  4249. finished.resolve(myRenderableColumns);
  4250. }
  4251. });
  4252. }
  4253. // Start on the first processor
  4254. startProcessor(0, myRenderableColumns);
  4255. return finished.promise;
  4256. };
  4257. Grid.prototype.setVisibleColumns = function setVisibleColumns(columns) {
  4258. // gridUtil.logDebug('setVisibleColumns');
  4259. var self = this;
  4260. // Reset all the render container row caches
  4261. for (var i in self.renderContainers) {
  4262. var container = self.renderContainers[i];
  4263. container.visibleColumnCache.length = 0;
  4264. }
  4265. for (var ci = 0; ci < columns.length; ci++) {
  4266. var column = columns[ci];
  4267. // If the column is visible
  4268. if (column.visible) {
  4269. // If the column has a container specified
  4270. if (typeof(column.renderContainer) !== 'undefined' && column.renderContainer) {
  4271. self.renderContainers[column.renderContainer].visibleColumnCache.push(column);
  4272. }
  4273. // If not, put it into the body container
  4274. else {
  4275. self.renderContainers.body.visibleColumnCache.push(column);
  4276. }
  4277. }
  4278. }
  4279. };
  4280. /**
  4281. * @ngdoc function
  4282. * @name handleWindowResize
  4283. * @methodOf ui.grid.class:Grid
  4284. * @description Triggered when the browser window resizes; automatically resizes the grid
  4285. */
  4286. Grid.prototype.handleWindowResize = function handleWindowResize($event) {
  4287. var self = this;
  4288. self.gridWidth = gridUtil.elementWidth(self.element);
  4289. self.gridHeight = gridUtil.elementHeight(self.element);
  4290. self.queueRefresh();
  4291. };
  4292. /**
  4293. * @ngdoc function
  4294. * @name queueRefresh
  4295. * @methodOf ui.grid.class:Grid
  4296. * @description queues a grid refreshCanvas, a way of debouncing all the refreshes we might otherwise issue
  4297. */
  4298. Grid.prototype.queueRefresh = function queueRefresh() {
  4299. var self = this;
  4300. if (self.refreshCanceller) {
  4301. $timeout.cancel(self.refreshCanceller);
  4302. }
  4303. self.refreshCanceller = $timeout(function() {
  4304. self.refreshCanvas(true);
  4305. });
  4306. self.refreshCanceller.then(function() {
  4307. self.refreshCanceller = null;
  4308. });
  4309. return self.refreshCanceller;
  4310. };
  4311. /**
  4312. * @ngdoc function
  4313. * @name queueGridRefresh
  4314. * @methodOf ui.grid.class:Grid
  4315. * @description queues a grid refresh, a way of debouncing all the refreshes we might otherwise issue
  4316. */
  4317. Grid.prototype.queueGridRefresh = function queueGridRefresh() {
  4318. var self = this;
  4319. if (self.gridRefreshCanceller) {
  4320. $timeout.cancel(self.gridRefreshCanceller);
  4321. }
  4322. self.gridRefreshCanceller = $timeout(function() {
  4323. self.refresh(true);
  4324. });
  4325. self.gridRefreshCanceller.then(function() {
  4326. self.gridRefreshCanceller = null;
  4327. });
  4328. return self.gridRefreshCanceller;
  4329. };
  4330. /**
  4331. * @ngdoc function
  4332. * @name updateCanvasHeight
  4333. * @methodOf ui.grid.class:Grid
  4334. * @description flags all render containers to update their canvas height
  4335. */
  4336. Grid.prototype.updateCanvasHeight = function updateCanvasHeight() {
  4337. var self = this;
  4338. for (var containerId in self.renderContainers) {
  4339. if (self.renderContainers.hasOwnProperty(containerId)) {
  4340. var container = self.renderContainers[containerId];
  4341. container.canvasHeightShouldUpdate = true;
  4342. }
  4343. }
  4344. };
  4345. /**
  4346. * @ngdoc function
  4347. * @name buildStyles
  4348. * @methodOf ui.grid.class:Grid
  4349. * @description calls each styleComputation function
  4350. */
  4351. // TODO: this used to take $scope, but couldn't see that it was used
  4352. Grid.prototype.buildStyles = function buildStyles() {
  4353. // gridUtil.logDebug('buildStyles');
  4354. var self = this;
  4355. self.customStyles = '';
  4356. self.styleComputations
  4357. .sort(function(a, b) {
  4358. if (a.priority === null) { return 1; }
  4359. if (b.priority === null) { return -1; }
  4360. if (a.priority === null && b.priority === null) { return 0; }
  4361. return a.priority - b.priority;
  4362. })
  4363. .forEach(function(compInfo) {
  4364. // this used to provide $scope as a second parameter, but I couldn't find any
  4365. // style builders that used it, so removed it as part of moving to grid from controller
  4366. var ret = compInfo.func.call(self);
  4367. if (angular.isString(ret)) {
  4368. self.customStyles += '\n' + ret;
  4369. }
  4370. });
  4371. };
  4372. Grid.prototype.minColumnsToRender = function minColumnsToRender() {
  4373. var self = this;
  4374. var viewport = this.getViewportWidth();
  4375. var min = 0;
  4376. var totalWidth = 0;
  4377. self.columns.forEach(function(col, i) {
  4378. if (totalWidth < viewport) {
  4379. totalWidth += col.drawnWidth;
  4380. min++;
  4381. } else {
  4382. var currWidth = 0;
  4383. for (var j = i; j >= i - min; j--) {
  4384. currWidth += self.columns[j].drawnWidth;
  4385. }
  4386. if (currWidth < viewport) {
  4387. min++;
  4388. }
  4389. }
  4390. });
  4391. return min;
  4392. };
  4393. Grid.prototype.getBodyHeight = function getBodyHeight() {
  4394. // Start with the viewportHeight
  4395. var bodyHeight = this.getViewportHeight();
  4396. // Add the horizontal scrollbar height if there is one
  4397. //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) {
  4398. // bodyHeight = bodyHeight + this.horizontalScrollbarHeight;
  4399. //}
  4400. return bodyHeight;
  4401. };
  4402. // NOTE: viewport drawable height is the height of the grid minus the header row height (including any border)
  4403. // TODO(c0bra): account for footer height
  4404. Grid.prototype.getViewportHeight = function getViewportHeight() {
  4405. var self = this;
  4406. var viewPortHeight = this.gridHeight - this.headerHeight - this.footerHeight;
  4407. // Account for native horizontal scrollbar, if present
  4408. //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) {
  4409. // viewPortHeight = viewPortHeight - this.horizontalScrollbarHeight;
  4410. //}
  4411. var adjustment = self.getViewportAdjustment();
  4412. viewPortHeight = viewPortHeight + adjustment.height;
  4413. //gridUtil.logDebug('viewPortHeight', viewPortHeight);
  4414. return viewPortHeight;
  4415. };
  4416. Grid.prototype.getViewportWidth = function getViewportWidth() {
  4417. var self = this;
  4418. var viewPortWidth = this.gridWidth;
  4419. //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) {
  4420. // viewPortWidth = viewPortWidth - this.verticalScrollbarWidth;
  4421. //}
  4422. var adjustment = self.getViewportAdjustment();
  4423. viewPortWidth = viewPortWidth + adjustment.width;
  4424. //gridUtil.logDebug('getviewPortWidth', viewPortWidth);
  4425. return viewPortWidth;
  4426. };
  4427. Grid.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() {
  4428. var viewPortWidth = this.getViewportWidth();
  4429. //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) {
  4430. // viewPortWidth = viewPortWidth + this.verticalScrollbarWidth;
  4431. //}
  4432. return viewPortWidth;
  4433. };
  4434. Grid.prototype.addVerticalScrollSync = function(containerId, callBackFn) {
  4435. this.verticalScrollSyncCallBackFns[containerId] = callBackFn;
  4436. };
  4437. Grid.prototype.addHorizontalScrollSync = function(containerId, callBackFn) {
  4438. this.horizontalScrollSyncCallBackFns[containerId] = callBackFn;
  4439. };
  4440. /**
  4441. * Scroll needed containers by calling their ScrollSyncs
  4442. * @param sourceContainerId the containerId that has already set it's top/left.
  4443. * can be empty string which means all containers need to set top/left
  4444. * @param scrollEvent
  4445. */
  4446. Grid.prototype.scrollContainers = function(sourceContainerId, scrollEvent) {
  4447. if (scrollEvent.y) {
  4448. //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left)
  4449. var verts = ['body', 'left', 'right'];
  4450. this.flagScrollingVertically(scrollEvent);
  4451. if (sourceContainerId === 'body') {
  4452. verts = ['left', 'right'];
  4453. } else if (sourceContainerId === 'left') {
  4454. verts = ['body', 'right'];
  4455. } else if (sourceContainerId === 'right') {
  4456. verts = ['body', 'left'];
  4457. }
  4458. for (var i = 0; i < verts.length; i++) {
  4459. var id = verts[i];
  4460. if (this.verticalScrollSyncCallBackFns[id]) {
  4461. this.verticalScrollSyncCallBackFns[id](scrollEvent);
  4462. }
  4463. }
  4464. }
  4465. if (scrollEvent.x) {
  4466. //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left)
  4467. var horizs = ['body', 'bodyheader', 'bodyfooter'];
  4468. this.flagScrollingHorizontally(scrollEvent);
  4469. if (sourceContainerId === 'body') {
  4470. horizs = ['bodyheader', 'bodyfooter'];
  4471. }
  4472. for (var j = 0; j < horizs.length; j++) {
  4473. var idh = horizs[j];
  4474. if (this.horizontalScrollSyncCallBackFns[idh]) {
  4475. this.horizontalScrollSyncCallBackFns[idh](scrollEvent);
  4476. }
  4477. }
  4478. }
  4479. };
  4480. Grid.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) {
  4481. this.viewportAdjusters.push(func);
  4482. };
  4483. Grid.prototype.removeViewportAdjuster = function registerViewportAdjuster(func) {
  4484. var idx = this.viewportAdjusters.indexOf(func);
  4485. if (typeof(idx) !== 'undefined' && idx !== undefined) {
  4486. this.viewportAdjusters.splice(idx, 1);
  4487. }
  4488. };
  4489. Grid.prototype.getViewportAdjustment = function getViewportAdjustment() {
  4490. var self = this;
  4491. var adjustment = { height: 0, width: 0 };
  4492. self.viewportAdjusters.forEach(function(func) {
  4493. adjustment = func.call(this, adjustment);
  4494. });
  4495. return adjustment;
  4496. };
  4497. Grid.prototype.getVisibleRowCount = function getVisibleRowCount() {
  4498. // var count = 0;
  4499. // this.rows.forEach(function (row) {
  4500. // if (row.visible) {
  4501. // count++;
  4502. // }
  4503. // });
  4504. // return this.visibleRowCache.length;
  4505. return this.renderContainers.body.visibleRowCache.length;
  4506. };
  4507. Grid.prototype.getVisibleRows = function getVisibleRows() {
  4508. return this.renderContainers.body.visibleRowCache;
  4509. };
  4510. Grid.prototype.getVisibleColumnCount = function getVisibleColumnCount() {
  4511. // var count = 0;
  4512. // this.rows.forEach(function (row) {
  4513. // if (row.visible) {
  4514. // count++;
  4515. // }
  4516. // });
  4517. // return this.visibleRowCache.length;
  4518. return this.renderContainers.body.visibleColumnCache.length;
  4519. };
  4520. Grid.prototype.searchRows = function searchRows(renderableRows) {
  4521. return rowSearcher.search(this, renderableRows, this.columns);
  4522. };
  4523. Grid.prototype.sortByColumn = function sortByColumn(renderableRows) {
  4524. return rowSorter.sort(this, renderableRows, this.columns);
  4525. };
  4526. /**
  4527. * @ngdoc function
  4528. * @name getCellValue
  4529. * @methodOf ui.grid.class:Grid
  4530. * @description Gets the value of a cell for a particular row and column
  4531. * @param {GridRow} row Row to access
  4532. * @param {GridColumn} col Column to access
  4533. */
  4534. Grid.prototype.getCellValue = function getCellValue(row, col) {
  4535. if (typeof(row.entity['$$' + col.uid]) !== 'undefined') {
  4536. return row.entity['$$' + col.uid].rendered;
  4537. } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined') {
  4538. return row.entity[col.field];
  4539. } else {
  4540. if (!col.cellValueGetterCache) {
  4541. col.cellValueGetterCache = $parse(row.getEntityQualifiedColField(col));
  4542. }
  4543. return col.cellValueGetterCache(row);
  4544. }
  4545. };
  4546. /**
  4547. * @ngdoc function
  4548. * @name getCellDisplayValue
  4549. * @methodOf ui.grid.class:Grid
  4550. * @description Gets the displayed value of a cell after applying any the `cellFilter`
  4551. * @param {GridRow} row Row to access
  4552. * @param {GridColumn} col Column to access
  4553. */
  4554. Grid.prototype.getCellDisplayValue = function getCellDisplayValue(row, col) {
  4555. if (!col.cellDisplayGetterCache) {
  4556. var custom_filter = col.cellFilter ? " | " + col.cellFilter : "";
  4557. if (typeof(row.entity['$$' + col.uid]) !== 'undefined') {
  4558. col.cellDisplayGetterCache = $parse(row.entity['$$' + col.uid].rendered + custom_filter);
  4559. } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined') {
  4560. col.cellDisplayGetterCache = $parse(row.entity[col.field] + custom_filter);
  4561. } else {
  4562. col.cellDisplayGetterCache = $parse(row.getEntityQualifiedColField(col) + custom_filter);
  4563. }
  4564. }
  4565. return col.cellDisplayGetterCache(row);
  4566. };
  4567. Grid.prototype.getNextColumnSortPriority = function getNextColumnSortPriority() {
  4568. var self = this,
  4569. p = 0;
  4570. self.columns.forEach(function(col) {
  4571. if (col.sort && col.sort.priority && col.sort.priority > p) {
  4572. p = col.sort.priority;
  4573. }
  4574. });
  4575. return p + 1;
  4576. };
  4577. /**
  4578. * @ngdoc function
  4579. * @name resetColumnSorting
  4580. * @methodOf ui.grid.class:Grid
  4581. * @description Return the columns that the grid is currently being sorted by
  4582. * @param {GridColumn} [excludedColumn] Optional GridColumn to exclude from having its sorting reset
  4583. */
  4584. Grid.prototype.resetColumnSorting = function resetColumnSorting(excludeCol) {
  4585. var self = this;
  4586. self.columns.forEach(function(col) {
  4587. if (col !== excludeCol && !col.suppressRemoveSort) {
  4588. col.sort = {};
  4589. }
  4590. });
  4591. };
  4592. /**
  4593. * @ngdoc function
  4594. * @name getColumnSorting
  4595. * @methodOf ui.grid.class:Grid
  4596. * @description Return the columns that the grid is currently being sorted by
  4597. * @returns {Array[GridColumn]} An array of GridColumn objects
  4598. */
  4599. Grid.prototype.getColumnSorting = function getColumnSorting() {
  4600. var self = this;
  4601. var sortedCols = [],
  4602. myCols;
  4603. // Iterate through all the columns, sorted by priority
  4604. // Make local copy of column list, because sorting is in-place and we do not want to
  4605. // change the original sequence of columns
  4606. myCols = self.columns.slice(0);
  4607. myCols.sort(rowSorter.prioritySort).forEach(function(col) {
  4608. if (col.sort && typeof(col.sort.direction) !== 'undefined' && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) {
  4609. sortedCols.push(col);
  4610. }
  4611. });
  4612. return sortedCols;
  4613. };
  4614. /**
  4615. * @ngdoc function
  4616. * @name sortColumn
  4617. * @methodOf ui.grid.class:Grid
  4618. * @description Set the sorting on a given column, optionally resetting any existing sorting on the Grid.
  4619. * Emits the sortChanged event whenever the sort criteria are changed.
  4620. * @param {GridColumn} column Column to set the sorting on
  4621. * @param {uiGridConstants.ASC|uiGridConstants.DESC} [direction] Direction to sort by, either descending or ascending.
  4622. * If not provided, the column will iterate through the sort directions: ascending, descending, unsorted.
  4623. * @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
  4624. * by this column only
  4625. * @returns {Promise} A resolved promise that supplies the column.
  4626. */
  4627. Grid.prototype.sortColumn = function sortColumn(column, directionOrAdd, add) {
  4628. var self = this,
  4629. direction = null;
  4630. if (typeof(column) === 'undefined' || !column) {
  4631. throw new Error('No column parameter provided');
  4632. }
  4633. // Second argument can either be a direction or whether to add this column to the existing sort.
  4634. // If it's a boolean, it's an add, otherwise, it's a direction
  4635. if (typeof(directionOrAdd) === 'boolean') {
  4636. add = directionOrAdd;
  4637. } else {
  4638. direction = directionOrAdd;
  4639. }
  4640. if (!add) {
  4641. self.resetColumnSorting(column);
  4642. column.sort.priority = 0;
  4643. // Get the actual priority since there may be columns which have suppressRemoveSort set
  4644. column.sort.priority = self.getNextColumnSortPriority();
  4645. } else if (!column.sort.priority) {
  4646. column.sort.priority = self.getNextColumnSortPriority();
  4647. }
  4648. if (!direction) {
  4649. // Figure out the sort direction
  4650. if (column.sort.direction && column.sort.direction === uiGridConstants.ASC) {
  4651. column.sort.direction = uiGridConstants.DESC;
  4652. } else if (column.sort.direction && column.sort.direction === uiGridConstants.DESC) {
  4653. if (column.colDef && column.suppressRemoveSort) {
  4654. column.sort.direction = uiGridConstants.ASC;
  4655. } else {
  4656. column.sort = {};
  4657. }
  4658. } else {
  4659. column.sort.direction = uiGridConstants.ASC;
  4660. }
  4661. } else {
  4662. column.sort.direction = direction;
  4663. }
  4664. self.api.core.raise.sortChanged(self, self.getColumnSorting());
  4665. return $q.when(column);
  4666. };
  4667. /**
  4668. * communicate to outside world that we are done with initial rendering
  4669. */
  4670. Grid.prototype.renderingComplete = function() {
  4671. if (angular.isFunction(this.options.onRegisterApi)) {
  4672. this.options.onRegisterApi(this.api);
  4673. }
  4674. this.api.core.raise.renderingComplete(this.api);
  4675. };
  4676. Grid.prototype.createRowHashMap = function createRowHashMap() {
  4677. var self = this;
  4678. var hashMap = new RowHashMap();
  4679. hashMap.grid = self;
  4680. return hashMap;
  4681. };
  4682. /**
  4683. * @ngdoc function
  4684. * @name refresh
  4685. * @methodOf ui.grid.class:Grid
  4686. * @description Refresh the rendered grid on screen.
  4687. * @param {boolean} [rowsAltered] Optional flag for refreshing when the number of rows has changed.
  4688. */
  4689. Grid.prototype.refresh = function refresh(rowsAltered) {
  4690. var self = this;
  4691. var p1 = self.processRowsProcessors(self.rows).then(function(renderableRows) {
  4692. self.setVisibleRows(renderableRows);
  4693. });
  4694. var p2 = self.processColumnsProcessors(self.columns).then(function(renderableColumns) {
  4695. self.setVisibleColumns(renderableColumns);
  4696. });
  4697. return $q.all([p1, p2]).then(function() {
  4698. self.redrawInPlace(rowsAltered);
  4699. self.refreshCanvas(true);
  4700. });
  4701. };
  4702. /**
  4703. * @ngdoc function
  4704. * @name refreshRows
  4705. * @methodOf ui.grid.class:Grid
  4706. * @description Refresh the rendered rows on screen? Note: not functional at present
  4707. * @returns {promise} promise that is resolved when render completes?
  4708. *
  4709. */
  4710. Grid.prototype.refreshRows = function refreshRows() {
  4711. var self = this;
  4712. return self.processRowsProcessors(self.rows)
  4713. .then(function(renderableRows) {
  4714. self.setVisibleRows(renderableRows);
  4715. self.redrawInPlace();
  4716. self.refreshCanvas(true);
  4717. });
  4718. };
  4719. /**
  4720. * @ngdoc function
  4721. * @name refreshCanvas
  4722. * @methodOf ui.grid.class:Grid
  4723. * @description Builds all styles and recalculates much of the grid sizing
  4724. * @param {object} buildStyles optional parameter. Use TBD
  4725. * @returns {promise} promise that is resolved when the canvas
  4726. * has been refreshed
  4727. *
  4728. */
  4729. Grid.prototype.refreshCanvas = function(buildStyles) {
  4730. var self = this;
  4731. if (buildStyles) {
  4732. self.buildStyles();
  4733. }
  4734. var p = $q.defer();
  4735. // Get all the header heights
  4736. var containerHeadersToRecalc = [];
  4737. for (var containerId in self.renderContainers) {
  4738. if (self.renderContainers.hasOwnProperty(containerId)) {
  4739. var container = self.renderContainers[containerId];
  4740. // Skip containers that have no canvasWidth set yet
  4741. if (container.canvasWidth === null || isNaN(container.canvasWidth)) {
  4742. continue;
  4743. }
  4744. if (container.header || container.headerCanvas) {
  4745. container.explicitHeaderHeight = container.explicitHeaderHeight || null;
  4746. container.explicitHeaderCanvasHeight = container.explicitHeaderCanvasHeight || null;
  4747. containerHeadersToRecalc.push(container);
  4748. }
  4749. }
  4750. }
  4751. /*
  4752. *
  4753. * Here we loop through the headers, measuring each element as well as any header "canvas" it has within it.
  4754. *
  4755. * If any header is less than the largest header height, it will be resized to that so that we don't have headers
  4756. * with different heights, which looks like a rendering problem
  4757. *
  4758. * We'll do the same thing with the header canvases, and give the header CELLS an explicit height if their canvas
  4759. * is smaller than the largest canvas height. That was header cells without extra controls like filtering don't
  4760. * appear shorter than other cells.
  4761. *
  4762. */
  4763. if (containerHeadersToRecalc.length > 0) {
  4764. // Build the styles without the explicit header heights
  4765. if (buildStyles) {
  4766. self.buildStyles();
  4767. }
  4768. // Putting in a timeout as it's not calculating after the grid element is rendered and filled out
  4769. $timeout(function() {
  4770. // var oldHeaderHeight = self.grid.headerHeight;
  4771. // self.grid.headerHeight = gridUtil.outerElementHeight(self.header);
  4772. var rebuildStyles = false;
  4773. // Get all the header heights
  4774. var maxHeaderHeight = 0;
  4775. var maxHeaderCanvasHeight = 0;
  4776. var i, container;
  4777. var getHeight = function(oldVal, newVal) {
  4778. if (oldVal !== newVal) {
  4779. rebuildStyles = true;
  4780. }
  4781. return newVal;
  4782. };
  4783. for (i = 0; i < containerHeadersToRecalc.length; i++) {
  4784. container = containerHeadersToRecalc[i];
  4785. // Skip containers that have no canvasWidth set yet
  4786. if (container.canvasWidth === null || isNaN(container.canvasWidth)) {
  4787. continue;
  4788. }
  4789. if (container.header) {
  4790. var headerHeight = container.headerHeight = getHeight(container.headerHeight, parseInt(gridUtil.outerElementHeight(container.header), 10));
  4791. // 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
  4792. var topBorder = gridUtil.getBorderSize(container.header, 'top');
  4793. var bottomBorder = gridUtil.getBorderSize(container.header, 'bottom');
  4794. var innerHeaderHeight = parseInt(headerHeight - topBorder - bottomBorder, 10);
  4795. innerHeaderHeight = innerHeaderHeight < 0 ? 0 : innerHeaderHeight;
  4796. container.innerHeaderHeight = innerHeaderHeight;
  4797. // If the header doesn't have an explicit height set, save the largest header height for use later
  4798. // 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
  4799. if (!container.explicitHeaderHeight && innerHeaderHeight > maxHeaderHeight) {
  4800. maxHeaderHeight = innerHeaderHeight;
  4801. }
  4802. }
  4803. if (container.headerCanvas) {
  4804. var headerCanvasHeight = container.headerCanvasHeight = getHeight(container.headerCanvasHeight, parseInt(gridUtil.outerElementHeight(container.headerCanvas), 10));
  4805. // If the header doesn't have an explicit canvas height, save the largest header canvas height for use later
  4806. // 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
  4807. if (!container.explicitHeaderCanvasHeight && headerCanvasHeight > maxHeaderCanvasHeight) {
  4808. maxHeaderCanvasHeight = headerCanvasHeight;
  4809. }
  4810. }
  4811. }
  4812. // Go through all the headers
  4813. for (i = 0; i < containerHeadersToRecalc.length; i++) {
  4814. container = containerHeadersToRecalc[i];
  4815. /* If:
  4816. 1. We have a max header height
  4817. 2. This container has a header height defined
  4818. 3. And either this container has an explicit header height set, OR its header height is less than the max
  4819. then:
  4820. Give this container's header an explicit height so it will line up with the tallest header
  4821. */
  4822. if (
  4823. maxHeaderHeight > 0 && typeof(container.headerHeight) !== 'undefined' && container.headerHeight !== null &&
  4824. (container.explicitHeaderHeight || container.headerHeight < maxHeaderHeight)
  4825. ) {
  4826. container.explicitHeaderHeight = getHeight(container.explicitHeaderHeight, maxHeaderHeight);
  4827. }
  4828. // Do the same as above except for the header canvas
  4829. if (
  4830. maxHeaderCanvasHeight > 0 && typeof(container.headerCanvasHeight) !== 'undefined' && container.headerCanvasHeight !== null &&
  4831. (container.explicitHeaderCanvasHeight || container.headerCanvasHeight < maxHeaderCanvasHeight)
  4832. ) {
  4833. container.explicitHeaderCanvasHeight = getHeight(container.explicitHeaderCanvasHeight, maxHeaderCanvasHeight);
  4834. }
  4835. }
  4836. // Rebuild styles if the header height has changed
  4837. // The header height is used in body/viewport calculations and those are then used in other styles so we need it to be available
  4838. if (buildStyles && rebuildStyles) {
  4839. self.buildStyles();
  4840. }
  4841. p.resolve();
  4842. });
  4843. } else {
  4844. // Timeout still needs to be here to trigger digest after styles have been rebuilt
  4845. $timeout(function() {
  4846. p.resolve();
  4847. });
  4848. }
  4849. return p.promise;
  4850. };
  4851. /**
  4852. * @ngdoc function
  4853. * @name redrawCanvas
  4854. * @methodOf ui.grid.class:Grid
  4855. * @description Redraw the rows and columns based on our current scroll position
  4856. * @param {boolean} [rowsAdded] Optional to indicate rows are added and the scroll percentage must be recalculated
  4857. *
  4858. */
  4859. Grid.prototype.redrawInPlace = function redrawInPlace(rowsAdded) {
  4860. // gridUtil.logDebug('redrawInPlace');
  4861. var self = this;
  4862. for (var i in self.renderContainers) {
  4863. var container = self.renderContainers[i];
  4864. // gridUtil.logDebug('redrawing container', i);
  4865. if (rowsAdded) {
  4866. container.adjustRows(container.prevScrollTop, null);
  4867. container.adjustColumns(container.prevScrollLeft, null);
  4868. } else {
  4869. container.adjustRows(null, container.prevScrolltopPercentage);
  4870. container.adjustColumns(null, container.prevScrollleftPercentage);
  4871. }
  4872. }
  4873. };
  4874. /**
  4875. * @ngdoc function
  4876. * @name hasLeftContainerColumns
  4877. * @methodOf ui.grid.class:Grid
  4878. * @description returns true if leftContainer has columns
  4879. */
  4880. Grid.prototype.hasLeftContainerColumns = function() {
  4881. return this.hasLeftContainer() && this.renderContainers.left.renderedColumns.length > 0;
  4882. };
  4883. /**
  4884. * @ngdoc function
  4885. * @name hasRightContainerColumns
  4886. * @methodOf ui.grid.class:Grid
  4887. * @description returns true if rightContainer has columns
  4888. */
  4889. Grid.prototype.hasRightContainerColumns = function() {
  4890. return this.hasRightContainer() && this.renderContainers.right.renderedColumns.length > 0;
  4891. };
  4892. /**
  4893. * @ngdoc method
  4894. * @methodOf ui.grid.class:Grid
  4895. * @name scrollToIfNecessary
  4896. * @description Scrolls the grid to make a certain row and column combo visible,
  4897. * in the case that it is not completely visible on the screen already.
  4898. * @param {GridRow} gridRow row to make visible
  4899. * @param {GridCol} gridCol column to make visible
  4900. * @returns {promise} a promise that is resolved when scrolling is complete
  4901. */
  4902. Grid.prototype.scrollToIfNecessary = function(gridRow, gridCol) {
  4903. var self = this;
  4904. var scrollEvent = new ScrollEvent(self, 'uiGrid.scrollToIfNecessary');
  4905. // Alias the visible row and column caches
  4906. var visRowCache = self.renderContainers.body.visibleRowCache;
  4907. var visColCache = self.renderContainers.body.visibleColumnCache;
  4908. /*-- Get the top, left, right, and bottom "scrolled" edges of the grid --*/
  4909. // 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
  4910. var topBound = self.renderContainers.body.prevScrollTop + self.headerHeight;
  4911. // Don't the let top boundary be less than 0
  4912. topBound = (topBound < 0) ? 0 : topBound;
  4913. // The left boundary is the current X scroll position
  4914. var leftBound = self.renderContainers.body.prevScrollLeft;
  4915. // The bottom boundary is the current Y scroll position, plus the height of the grid, but minus the header height.
  4916. // Basically this is the viewport height added on to the scroll position
  4917. var bottomBound = self.renderContainers.body.prevScrollTop + self.gridHeight - self.renderContainers.body.headerHeight - self.footerHeight - self.scrollbarWidth;
  4918. // If there's a horizontal scrollbar, remove its height from the bottom boundary, otherwise we'll be letting it obscure rows
  4919. //if (self.horizontalScrollbarHeight) {
  4920. // bottomBound = bottomBound - self.horizontalScrollbarHeight;
  4921. //}
  4922. // The right position is the current X scroll position minus the grid width
  4923. var rightBound = self.renderContainers.body.prevScrollLeft + Math.ceil(self.gridWidth);
  4924. // If there's a vertical scrollbar, subtract it from the right boundary or we'll allow it to obscure cells
  4925. //if (self.verticalScrollbarWidth) {
  4926. // rightBound = rightBound - self.verticalScrollbarWidth;
  4927. //}
  4928. // We were given a row to scroll to
  4929. if (gridRow !== null) {
  4930. // This is the index of the row we want to scroll to, within the list of rows that can be visible
  4931. var seekRowIndex = visRowCache.indexOf(gridRow);
  4932. // Total vertical scroll length of the grid
  4933. var scrollLength = (self.renderContainers.body.getCanvasHeight() - self.renderContainers.body.getViewportHeight());
  4934. // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row
  4935. //if (self.horizontalScrollbarHeight && self.horizontalScrollbarHeight > 0) {
  4936. // scrollLength = scrollLength + self.horizontalScrollbarHeight;
  4937. //}
  4938. // This is the minimum amount of pixels we need to scroll vertical in order to see this row.
  4939. var pixelsToSeeRow = ((seekRowIndex + 1) * self.options.rowHeight);
  4940. // Don't let the pixels required to see the row be less than zero
  4941. pixelsToSeeRow = (pixelsToSeeRow < 0) ? 0 : pixelsToSeeRow;
  4942. var scrollPixels, percentage;
  4943. // 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...
  4944. if (pixelsToSeeRow < topBound) {
  4945. // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\
  4946. // to get the full position we need
  4947. scrollPixels = self.renderContainers.body.prevScrollTop - (topBound - pixelsToSeeRow);
  4948. // Turn the scroll position into a percentage and make it an argument for a scroll event
  4949. percentage = scrollPixels / scrollLength;
  4950. scrollEvent.y = { percentage: percentage };
  4951. }
  4952. // 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...
  4953. else if (pixelsToSeeRow > bottomBound) {
  4954. // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position
  4955. // to get the full position we need
  4956. scrollPixels = pixelsToSeeRow - bottomBound + self.renderContainers.body.prevScrollTop;
  4957. // Turn the scroll position into a percentage and make it an argument for a scroll event
  4958. percentage = scrollPixels / scrollLength;
  4959. scrollEvent.y = { percentage: percentage };
  4960. }
  4961. }
  4962. // We were given a column to scroll to
  4963. if (gridCol !== null) {
  4964. // This is the index of the row we want to scroll to, within the list of rows that can be visible
  4965. var seekColumnIndex = visColCache.indexOf(gridCol);
  4966. // Total vertical scroll length of the grid
  4967. var horizScrollLength = (self.renderContainers.body.getCanvasWidth() - self.renderContainers.body.getViewportWidth());
  4968. // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row
  4969. // if (self.verticalScrollbarWidth && self.verticalScrollbarWidth > 0) {
  4970. // horizScrollLength = horizScrollLength + self.verticalScrollbarWidth;
  4971. // }
  4972. // This is the minimum amount of pixels we need to scroll vertical in order to see this column
  4973. var columnLeftEdge = 0;
  4974. for (var i = 0; i < seekColumnIndex; i++) {
  4975. var col = visColCache[i];
  4976. columnLeftEdge += col.drawnWidth;
  4977. }
  4978. columnLeftEdge = (columnLeftEdge < 0) ? 0 : columnLeftEdge;
  4979. var columnRightEdge = columnLeftEdge + gridCol.drawnWidth;
  4980. // Don't let the pixels required to see the column be less than zero
  4981. columnRightEdge = (columnRightEdge < 0) ? 0 : columnRightEdge;
  4982. var horizScrollPixels, horizPercentage;
  4983. // 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...
  4984. if (columnLeftEdge < leftBound) {
  4985. // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\
  4986. // to get the full position we need
  4987. horizScrollPixels = self.renderContainers.body.prevScrollLeft - (leftBound - columnLeftEdge);
  4988. // Turn the scroll position into a percentage and make it an argument for a scroll event
  4989. horizPercentage = horizScrollPixels / horizScrollLength;
  4990. horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage;
  4991. scrollEvent.x = { percentage: horizPercentage };
  4992. }
  4993. // 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...
  4994. else if (columnRightEdge > rightBound) {
  4995. // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position
  4996. // to get the full position we need
  4997. horizScrollPixels = columnRightEdge - rightBound + self.renderContainers.body.prevScrollLeft;
  4998. // Turn the scroll position into a percentage and make it an argument for a scroll event
  4999. horizPercentage = horizScrollPixels / horizScrollLength;
  5000. horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage;
  5001. scrollEvent.x = { percentage: horizPercentage };
  5002. }
  5003. }
  5004. var deferred = $q.defer();
  5005. // If we need to scroll on either the x or y axes, fire a scroll event
  5006. if (scrollEvent.y || scrollEvent.x) {
  5007. scrollEvent.withDelay = false;
  5008. self.scrollContainers('', scrollEvent);
  5009. var dereg = self.api.core.on.scrollEnd(null, function() {
  5010. deferred.resolve(scrollEvent);
  5011. dereg();
  5012. });
  5013. } else {
  5014. deferred.resolve();
  5015. }
  5016. return deferred.promise;
  5017. };
  5018. /**
  5019. * @ngdoc method
  5020. * @methodOf ui.grid.class:Grid
  5021. * @name scrollTo
  5022. * @description Scroll the grid such that the specified
  5023. * row and column is in view
  5024. * @param {object} rowEntity gridOptions.data[] array instance to make visible
  5025. * @param {object} colDef to make visible
  5026. * @returns {promise} a promise that is resolved after any scrolling is finished
  5027. */
  5028. Grid.prototype.scrollTo = function(rowEntity, colDef) {
  5029. var gridRow = null,
  5030. gridCol = null;
  5031. if (rowEntity !== null && typeof(rowEntity) !== 'undefined') {
  5032. gridRow = this.getRow(rowEntity);
  5033. }
  5034. if (colDef !== null && typeof(colDef) !== 'undefined') {
  5035. gridCol = this.getColumn(colDef.name ? colDef.name : colDef.field);
  5036. }
  5037. return this.scrollToIfNecessary(gridRow, gridCol);
  5038. };
  5039. /**
  5040. * @ngdoc function
  5041. * @name clearAllFilters
  5042. * @methodOf ui.grid.class:Grid
  5043. * @description Clears all filters and optionally refreshes the visible rows.
  5044. * @param {object} refreshRows Defaults to true.
  5045. * @param {object} clearConditions Defaults to false.
  5046. * @param {object} clearFlags Defaults to false.
  5047. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing.
  5048. */
  5049. Grid.prototype.clearAllFilters = function clearAllFilters(refreshRows, clearConditions, clearFlags) {
  5050. // Default `refreshRows` to true because it will be the most commonly desired behaviour.
  5051. if (refreshRows === undefined) {
  5052. refreshRows = true;
  5053. }
  5054. if (clearConditions === undefined) {
  5055. clearConditions = false;
  5056. }
  5057. if (clearFlags === undefined) {
  5058. clearFlags = false;
  5059. }
  5060. this.columns.forEach(function(column) {
  5061. column.filters.forEach(function(filter) {
  5062. filter.term = undefined;
  5063. if (clearConditions) {
  5064. filter.condition = undefined;
  5065. }
  5066. if (clearFlags) {
  5067. filter.flags = undefined;
  5068. }
  5069. });
  5070. });
  5071. if (refreshRows) {
  5072. return this.refreshRows();
  5073. }
  5074. };
  5075. // Blatantly stolen from Angular as it isn't exposed (yet? 2.0?)
  5076. function RowHashMap() {}
  5077. RowHashMap.prototype = {
  5078. /**
  5079. * Store key value pair
  5080. * @param key key to store can be any type
  5081. * @param value value to store can be any type
  5082. */
  5083. put: function(key, value) {
  5084. this[this.grid.options.rowIdentity(key)] = value;
  5085. },
  5086. /**
  5087. * @param key
  5088. * @returns {Object} the value for the key
  5089. */
  5090. get: function(key) {
  5091. return this[this.grid.options.rowIdentity(key)];
  5092. },
  5093. /**
  5094. * Remove the key/value pair
  5095. * @param key
  5096. */
  5097. remove: function(key) {
  5098. var value = this[key = this.grid.options.rowIdentity(key)];
  5099. delete this[key];
  5100. return value;
  5101. }
  5102. };
  5103. return Grid;
  5104. }
  5105. ]);
  5106. })();
  5107. (function() {
  5108. angular.module('ui.grid')
  5109. .factory('GridApi', ['$q', '$rootScope', 'gridUtil', 'uiGridConstants', 'GridRow', 'uiGridGridMenuService',
  5110. function($q, $rootScope, gridUtil, uiGridConstants, GridRow, uiGridGridMenuService) {
  5111. /**
  5112. * @ngdoc function
  5113. * @name ui.grid.class:GridApi
  5114. * @description GridApi provides the ability to register public methods events inside the grid and allow
  5115. * for other components to use the api via featureName.raise.methodName and featureName.on.eventName(function(args){}.
  5116. * <br/>
  5117. * To listen to events, you must add a callback to gridOptions.onRegisterApi
  5118. * <pre>
  5119. * $scope.gridOptions.onRegisterApi = function(gridApi){
  5120. * gridApi.cellNav.on.navigate($scope,function(newRowCol, oldRowCol){
  5121. * $log.log('navigation event');
  5122. * });
  5123. * };
  5124. * </pre>
  5125. * @param {object} grid grid that owns api
  5126. */
  5127. var GridApi = function GridApi(grid) {
  5128. this.grid = grid;
  5129. this.listeners = [];
  5130. /**
  5131. * @ngdoc function
  5132. * @name renderingComplete
  5133. * @methodOf ui.grid.core.api:PublicApi
  5134. * @description Rendering is complete, called at the same
  5135. * time as `onRegisterApi`, but provides a way to obtain
  5136. * that same event within features without stopping end
  5137. * users from getting at the onRegisterApi method.
  5138. *
  5139. * Included in gridApi so that it's always there - otherwise
  5140. * there is still a timing problem with when a feature can
  5141. * call this.
  5142. *
  5143. * @param {GridApi} gridApi the grid api, as normally
  5144. * returned in the onRegisterApi method
  5145. *
  5146. * @example
  5147. * <pre>
  5148. * gridApi.core.on.renderingComplete( grid );
  5149. * </pre>
  5150. */
  5151. this.registerEvent('core', 'renderingComplete');
  5152. /**
  5153. * @ngdoc event
  5154. * @name filterChanged
  5155. * @eventOf ui.grid.core.api:PublicApi
  5156. * @description is raised after the filter is changed. The nature
  5157. * of the watch expression doesn't allow notification of what changed,
  5158. * so the receiver of this event will need to re-extract the filter
  5159. * conditions from the columns.
  5160. *
  5161. */
  5162. this.registerEvent('core', 'filterChanged');
  5163. /**
  5164. * @ngdoc function
  5165. * @name setRowInvisible
  5166. * @methodOf ui.grid.core.api:PublicApi
  5167. * @description Sets an override on the row to make it always invisible,
  5168. * which will override any filtering or other visibility calculations.
  5169. * If the row is currently visible then sets it to invisible and calls
  5170. * both grid refresh and emits the rowsVisibleChanged event
  5171. * @param {object} rowEntity gridOptions.data[] array instance
  5172. */
  5173. this.registerMethod('core', 'setRowInvisible', GridRow.prototype.setRowInvisible);
  5174. /**
  5175. * @ngdoc function
  5176. * @name clearRowInvisible
  5177. * @methodOf ui.grid.core.api:PublicApi
  5178. * @description Clears any override on visibility for the row so that it returns to
  5179. * using normal filtering and other visibility calculations.
  5180. * If the row is currently invisible then sets it to visible and calls
  5181. * both grid refresh and emits the rowsVisibleChanged event
  5182. * TODO: if a filter is active then we can't just set it to visible?
  5183. * @param {object} rowEntity gridOptions.data[] array instance
  5184. */
  5185. this.registerMethod('core', 'clearRowInvisible', GridRow.prototype.clearRowInvisible);
  5186. /**
  5187. * @ngdoc function
  5188. * @name getVisibleRows
  5189. * @methodOf ui.grid.core.api:PublicApi
  5190. * @description Returns all visible rows
  5191. * @param {Grid} grid the grid you want to get visible rows from
  5192. * @returns {array} an array of gridRow
  5193. */
  5194. this.registerMethod('core', 'getVisibleRows', this.grid.getVisibleRows);
  5195. /**
  5196. * @ngdoc event
  5197. * @name rowsVisibleChanged
  5198. * @eventOf ui.grid.core.api:PublicApi
  5199. * @description is raised after the rows that are visible
  5200. * change. The filtering is zero-based, so it isn't possible
  5201. * to say which rows changed (unlike in the selection feature).
  5202. * We can plausibly know which row was changed when setRowInvisible
  5203. * is called, but in that situation the user already knows which row
  5204. * they changed. When a filter runs we don't know what changed,
  5205. * and that is the one that would have been useful.
  5206. *
  5207. */
  5208. this.registerEvent('core', 'rowsVisibleChanged');
  5209. /**
  5210. * @ngdoc event
  5211. * @name rowsRendered
  5212. * @eventOf ui.grid.core.api:PublicApi
  5213. * @description is raised after the cache of visible rows is changed.
  5214. */
  5215. this.registerEvent('core', 'rowsRendered');
  5216. /**
  5217. * @ngdoc event
  5218. * @name scrollBegin
  5219. * @eventOf ui.grid.core.api:PublicApi
  5220. * @description is raised when scroll begins. Is throttled, so won't be raised too frequently
  5221. */
  5222. this.registerEvent('core', 'scrollBegin');
  5223. /**
  5224. * @ngdoc event
  5225. * @name scrollEnd
  5226. * @eventOf ui.grid.core.api:PublicApi
  5227. * @description is raised when scroll has finished. Is throttled, so won't be raised too frequently
  5228. */
  5229. this.registerEvent('core', 'scrollEnd');
  5230. /**
  5231. * @ngdoc event
  5232. * @name canvasHeightChanged
  5233. * @eventOf ui.grid.core.api:PublicApi
  5234. * @description is raised when the canvas height has changed
  5235. * <br/>
  5236. * arguments: oldHeight, newHeight
  5237. */
  5238. this.registerEvent('core', 'canvasHeightChanged');
  5239. };
  5240. /**
  5241. * @ngdoc function
  5242. * @name ui.grid.class:suppressEvents
  5243. * @methodOf ui.grid.class:GridApi
  5244. * @description Used to execute a function while disabling the specified event listeners.
  5245. * Disables the listenerFunctions, executes the callbackFn, and then enables
  5246. * the listenerFunctions again
  5247. * @param {object} listenerFuncs listenerFunc or array of listenerFuncs to suppress. These must be the same
  5248. * functions that were used in the .on.eventName method
  5249. * @param {object} callBackFn function to execute
  5250. * @example
  5251. * <pre>
  5252. * var navigate = function (newRowCol, oldRowCol){
  5253. * //do something on navigate
  5254. * }
  5255. *
  5256. * gridApi.cellNav.on.navigate(scope,navigate);
  5257. *
  5258. *
  5259. * //call the scrollTo event and suppress our navigate listener
  5260. * //scrollTo will still raise the event for other listeners
  5261. * gridApi.suppressEvents(navigate, function(){
  5262. * gridApi.cellNav.scrollTo(aRow, aCol);
  5263. * });
  5264. *
  5265. * </pre>
  5266. */
  5267. GridApi.prototype.suppressEvents = function(listenerFuncs, callBackFn) {
  5268. var self = this;
  5269. var listeners = angular.isArray(listenerFuncs) ? listenerFuncs : [listenerFuncs];
  5270. //find all registered listeners
  5271. var foundListeners = self.listeners.filter(function(listener) {
  5272. return listeners.some(function(l) {
  5273. return listener.handler === l;
  5274. });
  5275. });
  5276. //deregister all the listeners
  5277. foundListeners.forEach(function(l) {
  5278. l.dereg();
  5279. });
  5280. callBackFn();
  5281. //reregister all the listeners
  5282. foundListeners.forEach(function(l) {
  5283. l.dereg = registerEventWithAngular(l.eventId, l.handler, self.grid, l._this);
  5284. });
  5285. };
  5286. /**
  5287. * @ngdoc function
  5288. * @name registerEvent
  5289. * @methodOf ui.grid.class:GridApi
  5290. * @description Registers a new event for the given feature. The event will get a
  5291. * .raise and .on prepended to it
  5292. * <br>
  5293. * .raise.eventName() - takes no arguments
  5294. * <br/>
  5295. * <br/>
  5296. * .on.eventName(scope, callBackFn, _this)
  5297. * <br/>
  5298. * scope - a scope reference to add a deregister call to the scopes .$on('destroy'). Scope is optional and can be a null value,
  5299. * but in this case you must deregister it yourself via the returned deregister function
  5300. * <br/>
  5301. * callBackFn - The function to call
  5302. * <br/>
  5303. * _this - optional this context variable for callbackFn. If omitted, grid.api will be used for the context
  5304. * <br/>
  5305. * .on.eventName returns a dereg funtion that will remove the listener. It's not necessary to use it as the listener
  5306. * will be removed when the scope is destroyed.
  5307. * @param {string} featureName name of the feature that raises the event
  5308. * @param {string} eventName name of the event
  5309. */
  5310. GridApi.prototype.registerEvent = function(featureName, eventName) {
  5311. var self = this;
  5312. if (!self[featureName]) {
  5313. self[featureName] = {};
  5314. }
  5315. var feature = self[featureName];
  5316. if (!feature.on) {
  5317. feature.on = {};
  5318. feature.raise = {};
  5319. }
  5320. var eventId = self.grid.id + featureName + eventName;
  5321. // gridUtil.logDebug('Creating raise event method ' + featureName + '.raise.' + eventName);
  5322. feature.raise[eventName] = function() {
  5323. $rootScope.$emit.apply($rootScope, [eventId].concat(Array.prototype.slice.call(arguments)));
  5324. };
  5325. // gridUtil.logDebug('Creating on event method ' + featureName + '.on.' + eventName);
  5326. feature.on[eventName] = function(scope, handler, _this) {
  5327. if (scope !== null && typeof(scope.$on) === 'undefined') {
  5328. 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');
  5329. return;
  5330. }
  5331. var deregAngularOn = registerEventWithAngular(eventId, handler, self.grid, _this);
  5332. //track our listener so we can turn off and on
  5333. var listener = { handler: handler, dereg: deregAngularOn, eventId: eventId, scope: scope, _this: _this };
  5334. self.listeners.push(listener);
  5335. var removeListener = function() {
  5336. listener.dereg();
  5337. var index = self.listeners.indexOf(listener);
  5338. self.listeners.splice(index, 1);
  5339. };
  5340. //destroy tracking when scope is destroyed
  5341. if (scope) {
  5342. scope.$on('$destroy', function() {
  5343. removeListener();
  5344. });
  5345. }
  5346. return removeListener;
  5347. };
  5348. };
  5349. function registerEventWithAngular(eventId, handler, grid, _this) {
  5350. return $rootScope.$on(eventId, function(event) {
  5351. var args = Array.prototype.slice.call(arguments);
  5352. args.splice(0, 1); //remove evt argument
  5353. handler.apply(_this ? _this : grid.api, args);
  5354. });
  5355. }
  5356. /**
  5357. * @ngdoc function
  5358. * @name registerEventsFromObject
  5359. * @methodOf ui.grid.class:GridApi
  5360. * @description Registers features and events from a simple objectMap.
  5361. * eventObjectMap must be in this format (multiple features allowed)
  5362. * <pre>
  5363. * {featureName:
  5364. * {
  5365. * eventNameOne:function(args){},
  5366. * eventNameTwo:function(args){}
  5367. * }
  5368. * }
  5369. * </pre>
  5370. * @param {object} eventObjectMap map of feature/event names
  5371. */
  5372. GridApi.prototype.registerEventsFromObject = function(eventObjectMap) {
  5373. var self = this;
  5374. var features = [];
  5375. angular.forEach(eventObjectMap, function(featProp, featPropName) {
  5376. var feature = { name: featPropName, events: [] };
  5377. angular.forEach(featProp, function(prop, propName) {
  5378. feature.events.push(propName);
  5379. });
  5380. features.push(feature);
  5381. });
  5382. features.forEach(function(feature) {
  5383. feature.events.forEach(function(event) {
  5384. self.registerEvent(feature.name, event);
  5385. });
  5386. });
  5387. };
  5388. /**
  5389. * @ngdoc function
  5390. * @name registerMethod
  5391. * @methodOf ui.grid.class:GridApi
  5392. * @description Registers a new event for the given feature
  5393. * @param {string} featureName name of the feature
  5394. * @param {string} methodName name of the method
  5395. * @param {object} callBackFn function to execute
  5396. * @param {object} _this binds callBackFn 'this' to _this. Defaults to gridApi.grid
  5397. */
  5398. GridApi.prototype.registerMethod = function(featureName, methodName, callBackFn, _this) {
  5399. if (!this[featureName]) {
  5400. this[featureName] = {};
  5401. }
  5402. var feature = this[featureName];
  5403. feature[methodName] = gridUtil.createBoundedWrapper(_this || this.grid, callBackFn);
  5404. };
  5405. /**
  5406. * @ngdoc function
  5407. * @name registerMethodsFromObject
  5408. * @methodOf ui.grid.class:GridApi
  5409. * @description Registers features and methods from a simple objectMap.
  5410. * eventObjectMap must be in this format (multiple features allowed)
  5411. * <br>
  5412. * {featureName:
  5413. * {
  5414. * methodNameOne:function(args){},
  5415. * methodNameTwo:function(args){}
  5416. * }
  5417. * @param {object} eventObjectMap map of feature/event names
  5418. * @param {object} _this binds this to _this for all functions. Defaults to gridApi.grid
  5419. */
  5420. GridApi.prototype.registerMethodsFromObject = function(methodMap, _this) {
  5421. var self = this;
  5422. var features = [];
  5423. angular.forEach(methodMap, function(featProp, featPropName) {
  5424. var feature = { name: featPropName, methods: [] };
  5425. angular.forEach(featProp, function(prop, propName) {
  5426. feature.methods.push({ name: propName, fn: prop });
  5427. });
  5428. features.push(feature);
  5429. });
  5430. features.forEach(function(feature) {
  5431. feature.methods.forEach(function(method) {
  5432. self.registerMethod(feature.name, method.name, method.fn, _this);
  5433. });
  5434. });
  5435. };
  5436. return GridApi;
  5437. }
  5438. ]);
  5439. })();
  5440. (function() {
  5441. angular.module('ui.grid')
  5442. .factory('GridColumn', ['gridUtil', 'uiGridConstants', 'i18nService', function(gridUtil, uiGridConstants, i18nService) {
  5443. /**
  5444. * ******************************************************************************************
  5445. * PaulL1: Ugly hack here in documentation. These properties are clearly properties of GridColumn,
  5446. * and need to be noted as such for those extending and building ui-grid itself.
  5447. * However, from an end-developer perspective, they interact with all these through columnDefs,
  5448. * and they really need to be documented there. I feel like they're relatively static, and
  5449. * I can't find an elegant way for ngDoc to reference to both....so I've duplicated each
  5450. * comment block. Ugh.
  5451. *
  5452. */
  5453. /**
  5454. * @ngdoc property
  5455. * @name name
  5456. * @propertyOf ui.grid.class:GridColumn
  5457. * @description (mandatory) each column should have a name, although for backward
  5458. * compatibility with 2.x name can be omitted if field is present
  5459. *
  5460. */
  5461. /**
  5462. * @ngdoc property
  5463. * @name name
  5464. * @propertyOf ui.grid.class:GridOptions.columnDef
  5465. * @description (mandatory) each column should have a name, although for backward
  5466. * compatibility with 2.x name can be omitted if field is present
  5467. *
  5468. */
  5469. /**
  5470. * @ngdoc property
  5471. * @name displayName
  5472. * @propertyOf ui.grid.class:GridColumn
  5473. * @description Column name that will be shown in the header. If displayName is not
  5474. * provided then one is generated using the name.
  5475. *
  5476. */
  5477. /**
  5478. * @ngdoc property
  5479. * @name displayName
  5480. * @propertyOf ui.grid.class:GridOptions.columnDef
  5481. * @description Column name that will be shown in the header. If displayName is not
  5482. * provided then one is generated using the name.
  5483. *
  5484. */
  5485. /**
  5486. * @ngdoc property
  5487. * @name field
  5488. * @propertyOf ui.grid.class:GridColumn
  5489. * @description field must be provided if you wish to bind to a
  5490. * property in the data source. Should be an angular expression that evaluates against grid.options.data
  5491. * array element. Can be a complex expression: <code>employee.address.city</code>, or can be a function: <code>employee.getFullAddress()</code>.
  5492. * See the angular docs on binding expressions.
  5493. *
  5494. */
  5495. /**
  5496. * @ngdoc property
  5497. * @name field
  5498. * @propertyOf ui.grid.class:GridOptions.columnDef
  5499. * @description field must be provided if you wish to bind to a
  5500. * property in the data source. Should be an angular expression that evaluates against grid.options.data
  5501. * 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. *
  5502. */
  5503. /**
  5504. * @ngdoc property
  5505. * @name filter
  5506. * @propertyOf ui.grid.class:GridColumn
  5507. * @description Filter on this column.
  5508. * @example
  5509. * <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>
  5510. *
  5511. */
  5512. /**
  5513. * @ngdoc object
  5514. * @name ui.grid.class:GridColumn
  5515. * @description Represents the viewModel for each column. Any state or methods needed for a Grid Column
  5516. * are defined on this prototype
  5517. * @param {ColumnDef} colDef the column def to associate with this column
  5518. * @param {number} uid the unique and immutable uid we'd like to allocate to this column
  5519. * @param {Grid} grid the grid we'd like to create this column in
  5520. */
  5521. function GridColumn(colDef, uid, grid) {
  5522. var self = this;
  5523. self.grid = grid;
  5524. self.uid = uid;
  5525. self.updateColumnDef(colDef, true);
  5526. /**
  5527. * @ngdoc function
  5528. * @name hideColumn
  5529. * @methodOf ui.grid.class:GridColumn
  5530. * @description Hides the column by setting colDef.visible = false
  5531. */
  5532. GridColumn.prototype.hideColumn = function() {
  5533. this.colDef.visible = false;
  5534. };
  5535. self.aggregationValue = undefined;
  5536. // The footer cell registers to listen for the rowsRendered event, and calls this. Needed to be
  5537. // in something with a scope so that the dereg would get called
  5538. self.updateAggregationValue = function() {
  5539. // gridUtil.logDebug('getAggregationValue for Column ' + self.colDef.name);
  5540. /**
  5541. * @ngdoc property
  5542. * @name aggregationType
  5543. * @propertyOf ui.grid.class:GridOptions.columnDef
  5544. * @description The aggregation that you'd like to show in the columnFooter for this
  5545. * column. Valid values are in uiGridConstants, and currently include `uiGridConstants.aggregationTypes.count`,
  5546. * `uiGridConstants.aggregationTypes.sum`, `uiGridConstants.aggregationTypes.avg`, `uiGridConstants.aggregationTypes.min`,
  5547. * `uiGridConstants.aggregationTypes.max`.
  5548. *
  5549. * You can also provide a function as the aggregation type, in this case your function needs to accept the full
  5550. * set of visible rows, and return a value that should be shown
  5551. */
  5552. if (!self.aggregationType) {
  5553. self.aggregationValue = undefined;
  5554. return;
  5555. }
  5556. var result = 0;
  5557. var visibleRows = self.grid.getVisibleRows();
  5558. var cellValues = function() {
  5559. var values = [];
  5560. visibleRows.forEach(function(row) {
  5561. var cellValue = self.grid.getCellValue(row, self);
  5562. var cellNumber = Number(cellValue);
  5563. if (!isNaN(cellNumber)) {
  5564. values.push(cellNumber);
  5565. }
  5566. });
  5567. return values;
  5568. };
  5569. if (angular.isFunction(self.aggregationType)) {
  5570. self.aggregationValue = self.aggregationType(visibleRows, self);
  5571. } else if (self.aggregationType === uiGridConstants.aggregationTypes.count) {
  5572. self.aggregationValue = self.grid.getVisibleRowCount();
  5573. } else if (self.aggregationType === uiGridConstants.aggregationTypes.sum) {
  5574. cellValues().forEach(function(value) {
  5575. result += value;
  5576. });
  5577. self.aggregationValue = result;
  5578. } else if (self.aggregationType === uiGridConstants.aggregationTypes.avg) {
  5579. cellValues().forEach(function(value) {
  5580. result += value;
  5581. });
  5582. result = result / cellValues().length;
  5583. self.aggregationValue = result;
  5584. } else if (self.aggregationType === uiGridConstants.aggregationTypes.min) {
  5585. self.aggregationValue = Math.min.apply(null, cellValues());
  5586. } else if (self.aggregationType === uiGridConstants.aggregationTypes.max) {
  5587. self.aggregationValue = Math.max.apply(null, cellValues());
  5588. } else {
  5589. self.aggregationValue = '\u00A0';
  5590. }
  5591. };
  5592. // var throttledUpdateAggregationValue = gridUtil.throttle(updateAggregationValue, self.grid.options.aggregationCalcThrottle, { trailing: true, context: self.name });
  5593. /**
  5594. * @ngdoc function
  5595. * @name getAggregationValue
  5596. * @methodOf ui.grid.class:GridColumn
  5597. * @description gets the aggregation value based on the aggregation type for this column.
  5598. * Debounced using scrollDebounce option setting
  5599. */
  5600. this.getAggregationValue = function() {
  5601. // if (!self.grid.isScrollingVertically && !self.grid.isScrollingHorizontally) {
  5602. // throttledUpdateAggregationValue();
  5603. // }
  5604. return self.aggregationValue;
  5605. };
  5606. }
  5607. /**
  5608. * @ngdoc method
  5609. * @methodOf ui.grid.class:GridColumn
  5610. * @name setPropertyOrDefault
  5611. * @description Sets a property on the column using the passed in columnDef, and
  5612. * setting the defaultValue if the value cannot be found on the colDef
  5613. * @param {ColumnDef} colDef the column def to look in for the property value
  5614. * @param {string} propName the property name we'd like to set
  5615. * @param {object} defaultValue the value to use if the colDef doesn't provide the setting
  5616. */
  5617. GridColumn.prototype.setPropertyOrDefault = function(colDef, propName, defaultValue) {
  5618. var self = this;
  5619. // Use the column definition filter if we were passed it
  5620. if (typeof(colDef[propName]) !== 'undefined' && colDef[propName]) {
  5621. self[propName] = colDef[propName];
  5622. }
  5623. // Otherwise use our own if it's set
  5624. else if (typeof(self[propName]) !== 'undefined') {
  5625. self[propName] = self[propName];
  5626. }
  5627. // Default to empty object for the filter
  5628. else {
  5629. self[propName] = defaultValue ? defaultValue : {};
  5630. }
  5631. };
  5632. /**
  5633. * @ngdoc property
  5634. * @name width
  5635. * @propertyOf ui.grid.class:GridOptions.columnDef
  5636. * @description sets the column width. Can be either
  5637. * a number or a percentage, or an * for auto.
  5638. * @example
  5639. * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', width: 100},
  5640. * { field: 'field2', width: '20%'},
  5641. * { field: 'field3', width: '*' }]; </pre>
  5642. *
  5643. */
  5644. /**
  5645. * @ngdoc property
  5646. * @name minWidth
  5647. * @propertyOf ui.grid.class:GridOptions.columnDef
  5648. * @description sets the minimum column width. Should be a number.
  5649. * @example
  5650. * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', minWidth: 100}]; </pre>
  5651. *
  5652. */
  5653. /**
  5654. * @ngdoc property
  5655. * @name maxWidth
  5656. * @propertyOf ui.grid.class:GridOptions.columnDef
  5657. * @description sets the maximum column width. Should be a number.
  5658. * @example
  5659. * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', maxWidth: 100}]; </pre>
  5660. *
  5661. */
  5662. /**
  5663. * @ngdoc property
  5664. * @name visible
  5665. * @propertyOf ui.grid.class:GridOptions.columnDef
  5666. * @description sets whether or not the column is visible
  5667. * </br>Default is true
  5668. * @example
  5669. * <pre> $scope.gridOptions.columnDefs = [
  5670. * { field: 'field1', visible: true},
  5671. * { field: 'field2', visible: false }
  5672. * ]; </pre>
  5673. *
  5674. */
  5675. /**
  5676. * @ngdoc property
  5677. * @name sort
  5678. * @propertyOf ui.grid.class:GridOptions.columnDef
  5679. * @description An object of sort information, attributes are:
  5680. *
  5681. * - direction: values are uiGridConstants.ASC or uiGridConstants.DESC
  5682. * - ignoreSort: if set to true this sort is ignored (used by tree to manipulate the sort functionality)
  5683. * - priority: says what order to sort the columns in (lower priority gets sorted first).
  5684. * @example
  5685. * <pre>
  5686. * $scope.gridOptions.columnDefs = [{
  5687. * field: 'field1',
  5688. * sort: {
  5689. * direction: uiGridConstants.ASC,
  5690. * ignoreSort: true,
  5691. * priority: 0
  5692. * }
  5693. * }];
  5694. * </pre>
  5695. */
  5696. /**
  5697. * @ngdoc property
  5698. * @name sortingAlgorithm
  5699. * @propertyOf ui.grid.class:GridColumn
  5700. * @description Algorithm to use for sorting this column. Takes 'a' and 'b' parameters
  5701. * like any normal sorting function.
  5702. *
  5703. */
  5704. /**
  5705. * @ngdoc property
  5706. * @name sortingAlgorithm
  5707. * @propertyOf ui.grid.class:GridOptions.columnDef
  5708. * @description Algorithm to use for sorting this column. Takes 'a' and 'b' parameters
  5709. * like any normal sorting function.
  5710. *
  5711. */
  5712. /**
  5713. * @ngdoc array
  5714. * @name filters
  5715. * @propertyOf ui.grid.class:GridOptions.columnDef
  5716. * @description Specify multiple filter fields.
  5717. * @example
  5718. * <pre>$scope.gridOptions.columnDefs = [
  5719. * {
  5720. * field: 'field1', filters: [
  5721. * {
  5722. * term: 'aa',
  5723. * condition: uiGridConstants.filter.STARTS_WITH,
  5724. * placeholder: 'starts with...',
  5725. * ariaLabel: 'Filter for field1',
  5726. * flags: { caseSensitive: false },
  5727. * type: uiGridConstants.filter.SELECT,
  5728. * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ]
  5729. * },
  5730. * {
  5731. * condition: uiGridConstants.filter.ENDS_WITH,
  5732. * placeholder: 'ends with...'
  5733. * }
  5734. * ]
  5735. * }
  5736. * ]; </pre>
  5737. *
  5738. *
  5739. */
  5740. /**
  5741. * @ngdoc array
  5742. * @name filters
  5743. * @propertyOf ui.grid.class:GridColumn
  5744. * @description Filters for this column. Includes 'term' property bound to filter input elements.
  5745. * @example
  5746. * <pre>[
  5747. * {
  5748. * term: 'foo', // ngModel for <input>
  5749. * condition: uiGridConstants.filter.STARTS_WITH,
  5750. * placeholder: 'starts with...',
  5751. * ariaLabel: 'Filter for foo',
  5752. * flags: { caseSensitive: false },
  5753. * type: uiGridConstants.filter.SELECT,
  5754. * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ]
  5755. * },
  5756. * {
  5757. * term: 'baz',
  5758. * condition: uiGridConstants.filter.ENDS_WITH,
  5759. * placeholder: 'ends with...'
  5760. * }
  5761. * ] </pre>
  5762. *
  5763. *
  5764. */
  5765. /**
  5766. * @ngdoc array
  5767. * @name menuItems
  5768. * @propertyOf ui.grid.class:GridOptions.columnDef
  5769. * @description used to add menu items to a column. Refer to the tutorial on this
  5770. * functionality. A number of settings are supported:
  5771. *
  5772. * - title: controls the title that is displayed in the menu
  5773. * - icon: the icon shown alongside that title
  5774. * - action: the method to call when the menu is clicked
  5775. * - shown: a function to evaluate to determine whether or not to show the item
  5776. * - active: a function to evaluate to determine whether or not the item is currently selected
  5777. * - context: context to pass to the action function, available in this.context in your handler
  5778. * - leaveOpen: if set to true, the menu should stay open after the action, defaults to false
  5779. * @example
  5780. * <pre> $scope.gridOptions.columnDefs = [
  5781. * { field: 'field1', menuItems: [
  5782. * {
  5783. * title: 'Outer Scope Alert',
  5784. * icon: 'ui-grid-icon-info-circled',
  5785. * action: function($event) {
  5786. * this.context.blargh(); // $scope.blargh() would work too, this is just an example
  5787. * },
  5788. * shown: function() { return true; },
  5789. * active: function() { return true; },
  5790. * context: $scope
  5791. * },
  5792. * {
  5793. * title: 'Grid ID',
  5794. * action: function() {
  5795. * alert('Grid ID: ' + this.grid.id);
  5796. * }
  5797. * }
  5798. * ] }]; </pre>
  5799. *
  5800. */
  5801. /**
  5802. * @ngdoc method
  5803. * @methodOf ui.grid.class:GridColumn
  5804. * @name updateColumnDef
  5805. * @description Moves settings from the columnDef down onto the column,
  5806. * and sets properties as appropriate
  5807. * @param {ColumnDef} colDef the column def to look in for the property value
  5808. * @param {boolean} isNew whether the column is being newly created, if not
  5809. * we're updating an existing column, and some items such as the sort shouldn't
  5810. * be copied down
  5811. */
  5812. GridColumn.prototype.updateColumnDef = function(colDef, isNew) {
  5813. var self = this;
  5814. self.colDef = colDef;
  5815. if (colDef.name === undefined) {
  5816. throw new Error('colDef.name is required for column at index ' + self.grid.options.columnDefs.indexOf(colDef));
  5817. }
  5818. self.displayName = (colDef.displayName === undefined) ? gridUtil.readableColumnName(colDef.name) : colDef.displayName;
  5819. if (!angular.isNumber(self.width) || !self.hasCustomWidth || colDef.allowCustomWidthOverride) {
  5820. var colDefWidth = colDef.width;
  5821. var parseErrorMsg = "Cannot parse column width '" + colDefWidth + "' for column named '" + colDef.name + "'";
  5822. self.hasCustomWidth = false;
  5823. if (!angular.isString(colDefWidth) && !angular.isNumber(colDefWidth)) {
  5824. self.width = '*';
  5825. } else if (angular.isString(colDefWidth)) {
  5826. // See if it ends with a percent
  5827. if (gridUtil.endsWith(colDefWidth, '%')) {
  5828. // If so we should be able to parse the non-percent-sign part to a number
  5829. var percentStr = colDefWidth.replace(/%/g, '');
  5830. var percent = parseInt(percentStr, 10);
  5831. if (isNaN(percent)) {
  5832. throw new Error(parseErrorMsg);
  5833. }
  5834. self.width = colDefWidth;
  5835. }
  5836. // And see if it's a number string
  5837. else if (colDefWidth.match(/^(\d+)$/)) {
  5838. self.width = parseInt(colDefWidth.match(/^(\d+)$/)[1], 10);
  5839. }
  5840. // Otherwise it should be a string of asterisks
  5841. else if (colDefWidth.match(/^\*+$/)) {
  5842. self.width = colDefWidth;
  5843. }
  5844. // No idea, throw an Error
  5845. else {
  5846. throw new Error(parseErrorMsg);
  5847. }
  5848. }
  5849. // Is a number, use it as the width
  5850. else {
  5851. self.width = colDefWidth;
  5852. }
  5853. }
  5854. ['minWidth', 'maxWidth'].forEach(function(name) {
  5855. var minOrMaxWidth = colDef[name];
  5856. var parseErrorMsg = "Cannot parse column " + name + " '" + minOrMaxWidth + "' for column named '" + colDef.name + "'";
  5857. if (!angular.isString(minOrMaxWidth) && !angular.isNumber(minOrMaxWidth)) {
  5858. //Sets default minWidth and maxWidth values
  5859. self[name] = ((name === 'minWidth') ? 34 : 9000);
  5860. } else if (angular.isString(minOrMaxWidth)) {
  5861. if (minOrMaxWidth.match(/^(\d+)$/)) {
  5862. self[name] = parseInt(minOrMaxWidth.match(/^(\d+)$/)[1], 10);
  5863. } else {
  5864. throw new Error(parseErrorMsg);
  5865. }
  5866. } else {
  5867. self[name] = minOrMaxWidth;
  5868. }
  5869. });
  5870. //use field if it is defined; name if it is not
  5871. self.field = (colDef.field === undefined) ? colDef.name : colDef.field;
  5872. if (typeof(self.field) !== 'string') {
  5873. gridUtil.logError('Field is not a string, this is likely to break the code, Field is: ' + self.field);
  5874. }
  5875. self.name = colDef.name;
  5876. // Use colDef.displayName as long as it's not undefined, otherwise default to the field name
  5877. self.displayName = (colDef.displayName === undefined) ? gridUtil.readableColumnName(colDef.name) : colDef.displayName;
  5878. //self.originalIndex = index;
  5879. self.aggregationType = angular.isDefined(colDef.aggregationType) ? colDef.aggregationType : null;
  5880. self.footerCellTemplate = angular.isDefined(colDef.footerCellTemplate) ? colDef.footerCellTemplate : null;
  5881. /**
  5882. * @ngdoc property
  5883. * @name cellTooltip
  5884. * @propertyOf ui.grid.class:GridOptions.columnDef
  5885. * @description Whether or not to show a tooltip when a user hovers over the cell.
  5886. * If set to false, no tooltip. If true, the cell value is shown in the tooltip (useful
  5887. * if you have long values in your cells), if a function then that function is called
  5888. * passing in the row and the col `cellTooltip( row, col )`, and the return value is shown in the tooltip,
  5889. * if it is a static string then displays that static string.
  5890. *
  5891. * Defaults to false
  5892. *
  5893. */
  5894. if (typeof(colDef.cellTooltip) === 'undefined' || colDef.cellTooltip === false) {
  5895. self.cellTooltip = false;
  5896. } else if (colDef.cellTooltip === true) {
  5897. self.cellTooltip = function(row, col) {
  5898. return self.grid.getCellValue(row, col);
  5899. };
  5900. } else if (typeof(colDef.cellTooltip) === 'function') {
  5901. self.cellTooltip = colDef.cellTooltip;
  5902. } else {
  5903. self.cellTooltip = function(row, col) {
  5904. return col.colDef.cellTooltip;
  5905. };
  5906. }
  5907. /**
  5908. * @ngdoc property
  5909. * @name headerTooltip
  5910. * @propertyOf ui.grid.class:GridOptions.columnDef
  5911. * @description Whether or not to show a tooltip when a user hovers over the header cell.
  5912. * If set to false, no tooltip. If true, the displayName is shown in the tooltip (useful
  5913. * if you have long values in your headers), if a function then that function is called
  5914. * passing in the row and the col `headerTooltip( col )`, and the return value is shown in the tooltip,
  5915. * if a static string then shows that static string.
  5916. *
  5917. * Defaults to false
  5918. *
  5919. */
  5920. if (typeof(colDef.headerTooltip) === 'undefined' || colDef.headerTooltip === false) {
  5921. self.headerTooltip = false;
  5922. } else if (colDef.headerTooltip === true) {
  5923. self.headerTooltip = function(col) {
  5924. return col.displayName;
  5925. };
  5926. } else if (typeof(colDef.headerTooltip) === 'function') {
  5927. self.headerTooltip = colDef.headerTooltip;
  5928. } else {
  5929. self.headerTooltip = function(col) {
  5930. return col.colDef.headerTooltip;
  5931. };
  5932. }
  5933. /**
  5934. * @ngdoc property
  5935. * @name footerCellClass
  5936. * @propertyOf ui.grid.class:GridOptions.columnDef
  5937. * @description footerCellClass can be a string specifying the class to append to a cell
  5938. * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name
  5939. *
  5940. */
  5941. self.footerCellClass = colDef.footerCellClass;
  5942. /**
  5943. * @ngdoc property
  5944. * @name cellClass
  5945. * @propertyOf ui.grid.class:GridOptions.columnDef
  5946. * @description cellClass can be a string specifying the class to append to a cell
  5947. * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name
  5948. *
  5949. */
  5950. self.cellClass = colDef.cellClass;
  5951. /**
  5952. * @ngdoc property
  5953. * @name headerCellClass
  5954. * @propertyOf ui.grid.class:GridOptions.columnDef
  5955. * @description headerCellClass can be a string specifying the class to append to a cell
  5956. * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name
  5957. *
  5958. */
  5959. self.headerCellClass = colDef.headerCellClass;
  5960. /**
  5961. * @ngdoc property
  5962. * @name cellFilter
  5963. * @propertyOf ui.grid.class:GridOptions.columnDef
  5964. * @description cellFilter is a filter to apply to the content of each cell
  5965. * @example
  5966. * <pre>
  5967. * gridOptions.columnDefs[0].cellFilter = 'date'
  5968. *
  5969. */
  5970. self.cellFilter = colDef.cellFilter ? colDef.cellFilter : "";
  5971. /**
  5972. * @ngdoc boolean
  5973. * @name sortCellFiltered
  5974. * @propertyOf ui.grid.class:GridOptions.columnDef
  5975. * @description (optional) False by default. When `true` uiGrid will apply the cellFilter before
  5976. * sorting the data. Note that when using this option uiGrid will assume that the displayed value is
  5977. * a string, and use the {@link ui.grid.class:RowSorter#sortAlpha sortAlpha} `sortFn`. It is possible
  5978. * 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}
  5979. * for the column which hanldes the returned type. You may specify one of the `sortingAlgorithms`
  5980. * found in the {@link ui.grid.RowSorter rowSorter} service.
  5981. */
  5982. self.sortCellFiltered = colDef.sortCellFiltered ? true : false;
  5983. /**
  5984. * @ngdoc boolean
  5985. * @name filterCellFiltered
  5986. * @propertyOf ui.grid.class:GridOptions.columnDef
  5987. * @description (optional) False by default. When `true` uiGrid will apply the cellFilter before
  5988. * applying "search" `filters`.
  5989. */
  5990. self.filterCellFiltered = colDef.filterCellFiltered ? true : false;
  5991. /**
  5992. * @ngdoc property
  5993. * @name headerCellFilter
  5994. * @propertyOf ui.grid.class:GridOptions.columnDef
  5995. * @description headerCellFilter is a filter to apply to the content of the column header
  5996. * @example
  5997. * <pre>
  5998. * gridOptions.columnDefs[0].headerCellFilter = 'translate'
  5999. *
  6000. */
  6001. self.headerCellFilter = colDef.headerCellFilter ? colDef.headerCellFilter : "";
  6002. /**
  6003. * @ngdoc property
  6004. * @name footerCellFilter
  6005. * @propertyOf ui.grid.class:GridOptions.columnDef
  6006. * @description footerCellFilter is a filter to apply to the content of the column footer
  6007. * @example
  6008. * <pre>
  6009. * gridOptions.columnDefs[0].footerCellFilter = 'date'
  6010. *
  6011. */
  6012. self.footerCellFilter = colDef.footerCellFilter ? colDef.footerCellFilter : "";
  6013. self.visible = gridUtil.isNullOrUndefined(colDef.visible) || colDef.visible;
  6014. self.headerClass = colDef.headerClass;
  6015. //self.cursor = self.sortable ? 'pointer' : 'default';
  6016. // Turn on sorting by default
  6017. self.enableSorting = typeof(colDef.enableSorting) !== 'undefined' ? colDef.enableSorting : true;
  6018. self.sortingAlgorithm = colDef.sortingAlgorithm;
  6019. /**
  6020. * @ngdoc boolean
  6021. * @name suppressRemoveSort
  6022. * @propertyOf ui.grid.class:GridOptions.columnDef
  6023. * @description (optional) False by default. When enabled, this setting hides the removeSort option
  6024. * in the menu, and prevents users from manually removing the sort
  6025. */
  6026. if (typeof(self.suppressRemoveSort) === 'undefined') {
  6027. self.suppressRemoveSort = typeof(colDef.suppressRemoveSort) !== 'undefined' ? colDef.suppressRemoveSort : false;
  6028. }
  6029. /**
  6030. * @ngdoc property
  6031. * @name enableFiltering
  6032. * @propertyOf ui.grid.class:GridOptions.columnDef
  6033. * @description turn off filtering for an individual column, where
  6034. * you've turned on filtering for the overall grid
  6035. * @example
  6036. * <pre>
  6037. * gridOptions.columnDefs[0].enableFiltering = false;
  6038. *
  6039. */
  6040. // Turn on filtering by default (it's disabled by default at the Grid level)
  6041. self.enableFiltering = typeof(colDef.enableFiltering) !== 'undefined' ? colDef.enableFiltering : true;
  6042. // self.menuItems = colDef.menuItems;
  6043. self.setPropertyOrDefault(colDef, 'menuItems', []);
  6044. // Use the column definition sort if we were passed it, but only if this is a newly added column
  6045. if (isNew) {
  6046. self.setPropertyOrDefault(colDef, 'sort');
  6047. }
  6048. // Set up default filters array for when one is not provided.
  6049. // In other words, this (in column def):
  6050. //
  6051. // filter: { term: 'something', flags: {}, condition: [CONDITION] }
  6052. //
  6053. // is just shorthand for this:
  6054. //
  6055. // filters: [{ term: 'something', flags: {}, condition: [CONDITION] }]
  6056. //
  6057. var defaultFilters = [];
  6058. if (colDef.filter) {
  6059. defaultFilters.push(colDef.filter);
  6060. } else if (colDef.filters) {
  6061. defaultFilters = colDef.filters;
  6062. } else {
  6063. // Add an empty filter definition object, which will
  6064. // translate to a guessed condition and no pre-populated
  6065. // value for the filter <input>.
  6066. defaultFilters.push({});
  6067. }
  6068. /**
  6069. * @ngdoc property
  6070. * @name filter
  6071. * @propertyOf ui.grid.class:GridOptions.columnDef
  6072. * @description Specify a single filter field on this column.
  6073. *
  6074. * A filter consists of a condition, a term, and a placeholder:
  6075. *
  6076. * - condition defines how rows are chosen as matching the filter term. This can be set to
  6077. * one of the constants in uiGridConstants.filter, or you can supply a custom filter function
  6078. * that gets passed the following arguments: [searchTerm, cellValue, row, column].
  6079. * - term: If set, the filter field will be pre-populated
  6080. * with this value.
  6081. * - placeholder: String that will be set to the `<input>.placeholder` attribute.
  6082. * - ariaLabel: String that will be set to the `<input>.ariaLabel` attribute. This is what is read as a label to screen reader users.
  6083. * - noTerm: set this to true if you have defined a custom function in condition, and
  6084. * your custom function doesn't require a term (so it can run even when the term is null)
  6085. * - flags: only flag currently available is `caseSensitive`, set to false if you don't want
  6086. * case sensitive matching
  6087. * - type: defaults to uiGridConstants.filter.INPUT, which gives a text box. If set to uiGridConstants.filter.SELECT
  6088. * then a select box will be shown with options selectOptions
  6089. * - selectOptions: options in the format `[ { value: 1, label: 'male' }]`. No i18n filter is provided, you need
  6090. * to perform the i18n on the values before you provide them
  6091. * - disableCancelFilterButton: defaults to false. If set to true then the 'x' button that cancels/clears the filter
  6092. * will not be shown.
  6093. * @example
  6094. * <pre>$scope.gridOptions.columnDefs = [
  6095. * {
  6096. * field: 'field1',
  6097. * filter: {
  6098. * term: 'xx',
  6099. * condition: uiGridConstants.filter.STARTS_WITH,
  6100. * placeholder: 'starts with...',
  6101. * ariaLabel: 'Starts with filter for field1',
  6102. * flags: { caseSensitive: false },
  6103. * type: uiGridConstants.filter.SELECT,
  6104. * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ],
  6105. * disableCancelFilterButton: true
  6106. * }
  6107. * }
  6108. * ]; </pre>
  6109. *
  6110. */
  6111. /*
  6112. /*
  6113. self.filters = [
  6114. {
  6115. term: 'search term'
  6116. condition: uiGridConstants.filter.CONTAINS,
  6117. placeholder: 'my placeholder',
  6118. ariaLabel: 'Starts with filter for field1',
  6119. flags: {
  6120. caseSensitive: true
  6121. }
  6122. }
  6123. ]
  6124. */
  6125. // Only set filter if this is a newly added column, if we're updating an existing
  6126. // column then we don't want to put the default filter back if the user may have already
  6127. // removed it.
  6128. // However, we do want to keep the settings if they change, just not the term
  6129. if (isNew) {
  6130. self.setPropertyOrDefault(colDef, 'filter');
  6131. self.setPropertyOrDefault(colDef, 'filters', defaultFilters);
  6132. } else if (self.filters.length === defaultFilters.length) {
  6133. self.filters.forEach(function(filter, index) {
  6134. if (typeof(defaultFilters[index].placeholder) !== 'undefined') {
  6135. filter.placeholder = defaultFilters[index].placeholder;
  6136. }
  6137. if (typeof(defaultFilters[index].ariaLabel) !== 'undefined') {
  6138. filter.ariaLabel = defaultFilters[index].ariaLabel;
  6139. }
  6140. if (typeof(defaultFilters[index].flags) !== 'undefined') {
  6141. filter.flags = defaultFilters[index].flags;
  6142. }
  6143. if (typeof(defaultFilters[index].type) !== 'undefined') {
  6144. filter.type = defaultFilters[index].type;
  6145. }
  6146. if (typeof(defaultFilters[index].selectOptions) !== 'undefined') {
  6147. filter.selectOptions = defaultFilters[index].selectOptions;
  6148. }
  6149. });
  6150. }
  6151. // Remove this column from the grid sorting, include inside build columns so has
  6152. // access to self - all seems a bit dodgy but doesn't work otherwise so have left
  6153. // as is
  6154. GridColumn.prototype.unsort = function() {
  6155. this.sort = {};
  6156. self.grid.api.core.raise.sortChanged(self.grid, self.grid.getColumnSorting());
  6157. };
  6158. };
  6159. /**
  6160. * @ngdoc function
  6161. * @name getColClass
  6162. * @methodOf ui.grid.class:GridColumn
  6163. * @description Returns the class name for the column
  6164. * @param {bool} prefixDot if true, will return .className instead of className
  6165. */
  6166. GridColumn.prototype.getColClass = function(prefixDot) {
  6167. var cls = uiGridConstants.COL_CLASS_PREFIX + this.uid;
  6168. return prefixDot ? '.' + cls : cls;
  6169. };
  6170. /**
  6171. * @ngdoc function
  6172. * @name isPinnedLeft
  6173. * @methodOf ui.grid.class:GridColumn
  6174. * @description Returns true if column is in the left render container
  6175. */
  6176. GridColumn.prototype.isPinnedLeft = function() {
  6177. return this.renderContainer === 'left';
  6178. };
  6179. /**
  6180. * @ngdoc function
  6181. * @name isPinnedRight
  6182. * @methodOf ui.grid.class:GridColumn
  6183. * @description Returns true if column is in the right render container
  6184. */
  6185. GridColumn.prototype.isPinnedRight = function() {
  6186. return this.renderContainer === 'right';
  6187. };
  6188. /**
  6189. * @ngdoc function
  6190. * @name getColClassDefinition
  6191. * @methodOf ui.grid.class:GridColumn
  6192. * @description Returns the class definition for th column
  6193. */
  6194. GridColumn.prototype.getColClassDefinition = function() {
  6195. return ' .grid' + this.grid.id + ' ' + this.getColClass(true) + ' { min-width: ' + this.drawnWidth + 'px; max-width: ' + this.drawnWidth + 'px; }';
  6196. };
  6197. /**
  6198. * @ngdoc function
  6199. * @name getRenderContainer
  6200. * @methodOf ui.grid.class:GridColumn
  6201. * @description Returns the render container object that this column belongs to.
  6202. *
  6203. * Columns will be default be in the `body` render container if they aren't allocated to one specifically.
  6204. */
  6205. GridColumn.prototype.getRenderContainer = function getRenderContainer() {
  6206. var self = this;
  6207. var containerId = self.renderContainer;
  6208. if (containerId === null || containerId === '' || containerId === undefined) {
  6209. containerId = 'body';
  6210. }
  6211. return self.grid.renderContainers[containerId];
  6212. };
  6213. /**
  6214. * @ngdoc function
  6215. * @name showColumn
  6216. * @methodOf ui.grid.class:GridColumn
  6217. * @description Makes the column visible by setting colDef.visible = true
  6218. */
  6219. GridColumn.prototype.showColumn = function() {
  6220. this.colDef.visible = true;
  6221. };
  6222. /**
  6223. * @ngdoc property
  6224. * @name aggregationHideLabel
  6225. * @propertyOf ui.grid.class:GridOptions.columnDef
  6226. * @description defaults to false, if set to true hides the label text
  6227. * in the aggregation footer, so only the value is displayed.
  6228. *
  6229. */
  6230. /**
  6231. * @ngdoc function
  6232. * @name getAggregationText
  6233. * @methodOf ui.grid.class:GridColumn
  6234. * @description Gets the aggregation label from colDef.aggregationLabel if
  6235. * specified or by using i18n, including deciding whether or not to display
  6236. * based on colDef.aggregationHideLabel.
  6237. *
  6238. * @param {string} label the i18n lookup value to use for the column label
  6239. *
  6240. */
  6241. GridColumn.prototype.getAggregationText = function() {
  6242. var self = this;
  6243. if (self.colDef.aggregationHideLabel) {
  6244. return '';
  6245. } else if (self.colDef.aggregationLabel) {
  6246. return self.colDef.aggregationLabel;
  6247. } else {
  6248. switch (self.colDef.aggregationType) {
  6249. case uiGridConstants.aggregationTypes.count:
  6250. return i18nService.getSafeText('aggregation.count');
  6251. case uiGridConstants.aggregationTypes.sum:
  6252. return i18nService.getSafeText('aggregation.sum');
  6253. case uiGridConstants.aggregationTypes.avg:
  6254. return i18nService.getSafeText('aggregation.avg');
  6255. case uiGridConstants.aggregationTypes.min:
  6256. return i18nService.getSafeText('aggregation.min');
  6257. case uiGridConstants.aggregationTypes.max:
  6258. return i18nService.getSafeText('aggregation.max');
  6259. default:
  6260. return '';
  6261. }
  6262. }
  6263. };
  6264. GridColumn.prototype.getCellTemplate = function() {
  6265. var self = this;
  6266. return self.cellTemplatePromise;
  6267. };
  6268. GridColumn.prototype.getCompiledElementFn = function() {
  6269. var self = this;
  6270. return self.compiledElementFnDefer.promise;
  6271. };
  6272. return GridColumn;
  6273. }]);
  6274. })();
  6275. (function() {
  6276. angular.module('ui.grid')
  6277. .factory('GridOptions', ['gridUtil', 'uiGridConstants', function(gridUtil, uiGridConstants) {
  6278. /**
  6279. * @ngdoc function
  6280. * @name ui.grid.class:GridOptions
  6281. * @description Default GridOptions class. GridOptions are defined by the application developer and overlaid
  6282. * over this object. Setting gridOptions within your controller is the most common method for an application
  6283. * developer to configure the behaviour of their ui-grid
  6284. *
  6285. * @example To define your gridOptions within your controller:
  6286. * <pre>$scope.gridOptions = {
  6287. * data: $scope.myData,
  6288. * columnDefs: [
  6289. * { name: 'field1', displayName: 'pretty display name' },
  6290. * { name: 'field2', visible: false }
  6291. * ]
  6292. * };</pre>
  6293. *
  6294. * You can then use this within your html template, when you define your grid:
  6295. * <pre>&lt;div ui-grid="gridOptions"&gt;&lt;/div&gt;</pre>
  6296. *
  6297. * To provide default options for all of the grids within your application, use an angular
  6298. * decorator to modify the GridOptions factory.
  6299. * <pre>
  6300. * app.config(function($provide){
  6301. * $provide.decorator('GridOptions',function($delegate){
  6302. * var gridOptions;
  6303. * gridOptions = angular.copy($delegate);
  6304. * gridOptions.initialize = function(options) {
  6305. * var initOptions;
  6306. * initOptions = $delegate.initialize(options);
  6307. * initOptions.enableColumnMenus = false;
  6308. * return initOptions;
  6309. * };
  6310. * return gridOptions;
  6311. * });
  6312. * });
  6313. * </pre>
  6314. */
  6315. return {
  6316. initialize: function(baseOptions) {
  6317. /**
  6318. * @ngdoc function
  6319. * @name onRegisterApi
  6320. * @propertyOf ui.grid.class:GridOptions
  6321. * @description A callback that returns the gridApi once the grid is instantiated, which is
  6322. * then used to interact with the grid programatically.
  6323. *
  6324. * Note that the gridApi.core.renderingComplete event is identical to this
  6325. * callback, but has the advantage that it can be called from multiple places
  6326. * if needed
  6327. *
  6328. * @example
  6329. * <pre>
  6330. * $scope.gridOptions.onRegisterApi = function ( gridApi ) {
  6331. * $scope.gridApi = gridApi;
  6332. * $scope.gridApi.selection.selectAllRows( $scope.gridApi.grid );
  6333. * };
  6334. * </pre>
  6335. *
  6336. */
  6337. baseOptions.onRegisterApi = baseOptions.onRegisterApi || angular.noop();
  6338. /**
  6339. * @ngdoc object
  6340. * @name data
  6341. * @propertyOf ui.grid.class:GridOptions
  6342. * @description (mandatory) Array of data to be rendered into the grid, providing the data source or data binding for
  6343. * the grid.
  6344. *
  6345. * Most commonly the data is an array of objects, where each object has a number of attributes.
  6346. * Each attribute automatically becomes a column in your grid. This array could, for example, be sourced from
  6347. * an angularJS $resource query request. The array can also contain complex objects, refer the binding tutorial
  6348. * for examples of that.
  6349. *
  6350. * The most flexible usage is to set your data on $scope:
  6351. *
  6352. * `$scope.data = data;`
  6353. *
  6354. * And then direct the grid to resolve whatever is in $scope.data:
  6355. *
  6356. * `$scope.gridOptions.data = 'data';`
  6357. *
  6358. * This is the most flexible approach as it allows you to replace $scope.data whenever you feel like it without
  6359. * getting pointer issues.
  6360. *
  6361. * Alternatively you can directly set the data array:
  6362. *
  6363. * `$scope.gridOptions.data = [ ];`
  6364. * or
  6365. *
  6366. * `$http.get('/data/100.json')
  6367. * .success(function(data) {
  6368. * $scope.myData = data;
  6369. * $scope.gridOptions.data = $scope.myData;
  6370. * });`
  6371. *
  6372. * Where you do this, you need to take care in updating the data - you can't just update `$scope.myData` to some other
  6373. * array, you need to update $scope.gridOptions.data to point to that new array as well.
  6374. *
  6375. */
  6376. baseOptions.data = baseOptions.data || [];
  6377. /**
  6378. * @ngdoc array
  6379. * @name columnDefs
  6380. * @propertyOf ui.grid.class:GridOptions
  6381. * @description Array of columnDef objects. Only required property is name.
  6382. * The individual options available in columnDefs are documented in the
  6383. * {@link ui.grid.class:GridOptions.columnDef columnDef} section
  6384. * </br>_field property can be used in place of name for backwards compatibility with 2.x_
  6385. * @example
  6386. *
  6387. * <pre>var columnDefs = [{name:'field1'}, {name:'field2'}];</pre>
  6388. *
  6389. */
  6390. baseOptions.columnDefs = baseOptions.columnDefs || [];
  6391. /**
  6392. * @ngdoc object
  6393. * @name ui.grid.class:GridOptions.columnDef
  6394. * @description Definition / configuration of an individual column, which would typically be
  6395. * one of many column definitions within the gridOptions.columnDefs array
  6396. * @example
  6397. * <pre>{name:'field1', field: 'field1', filter: { term: 'xxx' }}</pre>
  6398. *
  6399. */
  6400. /**
  6401. * @ngdoc array
  6402. * @name excludeProperties
  6403. * @propertyOf ui.grid.class:GridOptions
  6404. * @description Array of property names in data to ignore when auto-generating column names. Provides the
  6405. * inverse of columnDefs - columnDefs is a list of columns to include, excludeProperties is a list of columns
  6406. * to exclude.
  6407. *
  6408. * If columnDefs is defined, this will be ignored.
  6409. *
  6410. * Defaults to ['$$hashKey']
  6411. */
  6412. baseOptions.excludeProperties = baseOptions.excludeProperties || ['$$hashKey'];
  6413. /**
  6414. * @ngdoc boolean
  6415. * @name enableRowHashing
  6416. * @propertyOf ui.grid.class:GridOptions
  6417. * @description True by default. When enabled, this setting allows uiGrid to add
  6418. * `$$hashKey`-type properties (similar to Angular) to elements in the `data` array. This allows
  6419. * the grid to maintain state while vastly speeding up the process of altering `data` by adding/moving/removing rows.
  6420. *
  6421. * Note that this DOES add properties to your data that you may not want, but they are stripped out when using `angular.toJson()`. IF
  6422. * 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
  6423. * and are altering the data set often.
  6424. */
  6425. baseOptions.enableRowHashing = baseOptions.enableRowHashing !== false;
  6426. /**
  6427. * @ngdoc function
  6428. * @name rowIdentity
  6429. * @methodOf ui.grid.class:GridOptions
  6430. * @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).
  6431. *
  6432. * By default it returns the `$$hashKey` property if it exists. If it doesn't it uses gridUtil.nextUid() to generate one
  6433. */
  6434. baseOptions.rowIdentity = baseOptions.rowIdentity || function rowIdentity(row) {
  6435. return gridUtil.hashKey(row);
  6436. };
  6437. /**
  6438. * @ngdoc function
  6439. * @name getRowIdentity
  6440. * @methodOf ui.grid.class:GridOptions
  6441. * @description This function returns the identity value uniquely identifying this row, if one is not present it does not set it.
  6442. *
  6443. * By default it returns the `$$hashKey` property but can be overridden to use any property or set of properties you want.
  6444. */
  6445. baseOptions.getRowIdentity = baseOptions.getRowIdentity || function getRowIdentity(row) {
  6446. return row.$$hashKey;
  6447. };
  6448. /**
  6449. * @ngdoc property
  6450. * @name flatEntityAccess
  6451. * @propertyOf ui.grid.class:GridOptions
  6452. * @description Set to true if your columns are all related directly to fields in a flat object structure - i.e.
  6453. * each of your columns associate directly with a property on each of the entities in your data array.
  6454. *
  6455. * In that situation we can avoid all the logic associated with complex binding to functions or to properties of sub-objects,
  6456. * which can provide a significant speed improvement with large data sets when filtering or sorting.
  6457. *
  6458. * By default false
  6459. */
  6460. baseOptions.flatEntityAccess = baseOptions.flatEntityAccess === true;
  6461. /**
  6462. * @ngdoc property
  6463. * @name showHeader
  6464. * @propertyOf ui.grid.class:GridOptions
  6465. * @description True by default. When set to false, this setting will replace the
  6466. * standard header template with '<div></div>', resulting in no header being shown.
  6467. */
  6468. baseOptions.showHeader = typeof(baseOptions.showHeader) !== "undefined" ? baseOptions.showHeader : true;
  6469. /* (NOTE): Don't show this in the docs. We only use it internally
  6470. * @ngdoc property
  6471. * @name headerRowHeight
  6472. * @propertyOf ui.grid.class:GridOptions
  6473. * @description The height of the header in pixels, defaults to 30
  6474. *
  6475. */
  6476. if (!baseOptions.showHeader) {
  6477. baseOptions.headerRowHeight = 0;
  6478. } else {
  6479. baseOptions.headerRowHeight = typeof(baseOptions.headerRowHeight) !== "undefined" ? baseOptions.headerRowHeight : 34;
  6480. }
  6481. /**
  6482. * @ngdoc property
  6483. * @name rowHeight
  6484. * @propertyOf ui.grid.class:GridOptions
  6485. * @description The height of the row in pixels, defaults to 30
  6486. *
  6487. */
  6488. baseOptions.rowHeight = baseOptions.rowHeight || 34;
  6489. /**
  6490. * @ngdoc integer
  6491. * @name minRowsToShow
  6492. * @propertyOf ui.grid.class:GridOptions
  6493. * @description Minimum number of rows to show when the grid doesn't have a defined height. Defaults to "10".
  6494. */
  6495. baseOptions.minRowsToShow = typeof(baseOptions.minRowsToShow) !== "undefined" ? baseOptions.minRowsToShow : 11;
  6496. /**
  6497. * @ngdoc property
  6498. * @name showGridFooter
  6499. * @propertyOf ui.grid.class:GridOptions
  6500. * @description Whether or not to show the footer, defaults to false
  6501. * The footer display Total Rows and Visible Rows (filtered rows)
  6502. */
  6503. baseOptions.showGridFooter = baseOptions.showGridFooter === true;
  6504. /**
  6505. * @ngdoc property
  6506. * @name showColumnFooter
  6507. * @propertyOf ui.grid.class:GridOptions
  6508. * @description Whether or not to show the column footer, defaults to false
  6509. * The column footer displays column aggregates
  6510. */
  6511. baseOptions.showColumnFooter = baseOptions.showColumnFooter === true;
  6512. /**
  6513. * @ngdoc property
  6514. * @name columnFooterHeight
  6515. * @propertyOf ui.grid.class:GridOptions
  6516. * @description The height of the footer rows (column footer and grid footer) in pixels
  6517. *
  6518. */
  6519. baseOptions.columnFooterHeight = typeof(baseOptions.columnFooterHeight) !== "undefined" ? baseOptions.columnFooterHeight : 34;
  6520. baseOptions.gridFooterHeight = typeof(baseOptions.gridFooterHeight) !== "undefined" ? baseOptions.gridFooterHeight : 34;
  6521. baseOptions.columnWidth = typeof(baseOptions.columnWidth) !== "undefined" ? baseOptions.columnWidth : 50;
  6522. /**
  6523. * @ngdoc property
  6524. * @name maxVisibleColumnCount
  6525. * @propertyOf ui.grid.class:GridOptions
  6526. * @description Defaults to 200
  6527. *
  6528. */
  6529. baseOptions.maxVisibleColumnCount = typeof(baseOptions.maxVisibleColumnCount) !== "undefined" ? baseOptions.maxVisibleColumnCount : 200;
  6530. /**
  6531. * @ngdoc property
  6532. * @name virtualizationThreshold
  6533. * @propertyOf ui.grid.class:GridOptions
  6534. * @description Turn virtualization on when number of data elements goes over this number, defaults to 20
  6535. */
  6536. baseOptions.virtualizationThreshold = typeof(baseOptions.virtualizationThreshold) !== "undefined" ? baseOptions.virtualizationThreshold : 20;
  6537. /**
  6538. * @ngdoc property
  6539. * @name columnVirtualizationThreshold
  6540. * @propertyOf ui.grid.class:GridOptions
  6541. * @description Turn virtualization on when number of columns goes over this number, defaults to 10
  6542. */
  6543. baseOptions.columnVirtualizationThreshold = typeof(baseOptions.columnVirtualizationThreshold) !== "undefined" ? baseOptions.columnVirtualizationThreshold : 10;
  6544. /**
  6545. * @ngdoc property
  6546. * @name excessRows
  6547. * @propertyOf ui.grid.class:GridOptions
  6548. * @description Extra rows to to render outside of the viewport, which helps with smoothness of scrolling.
  6549. * Defaults to 4
  6550. */
  6551. baseOptions.excessRows = typeof(baseOptions.excessRows) !== "undefined" ? baseOptions.excessRows : 4;
  6552. /**
  6553. * @ngdoc property
  6554. * @name scrollThreshold
  6555. * @propertyOf ui.grid.class:GridOptions
  6556. * @description Defaults to 4
  6557. */
  6558. baseOptions.scrollThreshold = typeof(baseOptions.scrollThreshold) !== "undefined" ? baseOptions.scrollThreshold : 4;
  6559. /**
  6560. * @ngdoc property
  6561. * @name excessColumns
  6562. * @propertyOf ui.grid.class:GridOptions
  6563. * @description Extra columns to to render outside of the viewport, which helps with smoothness of scrolling.
  6564. * Defaults to 4
  6565. */
  6566. baseOptions.excessColumns = typeof(baseOptions.excessColumns) !== "undefined" ? baseOptions.excessColumns : 4;
  6567. /**
  6568. * @ngdoc property
  6569. * @name horizontalScrollThreshold
  6570. * @propertyOf ui.grid.class:GridOptions
  6571. * @description Defaults to 4
  6572. */
  6573. baseOptions.horizontalScrollThreshold = typeof(baseOptions.horizontalScrollThreshold) !== "undefined" ? baseOptions.horizontalScrollThreshold : 2;
  6574. /**
  6575. * @ngdoc property
  6576. * @name aggregationCalcThrottle
  6577. * @propertyOf ui.grid.class:GridOptions
  6578. * @description Default time in milliseconds to throttle aggregation calcuations, defaults to 500ms
  6579. */
  6580. baseOptions.aggregationCalcThrottle = typeof(baseOptions.aggregationCalcThrottle) !== "undefined" ? baseOptions.aggregationCalcThrottle : 500;
  6581. /**
  6582. * @ngdoc property
  6583. * @name wheelScrollThrottle
  6584. * @propertyOf ui.grid.class:GridOptions
  6585. * @description Default time in milliseconds to throttle scroll events to, defaults to 70ms
  6586. */
  6587. baseOptions.wheelScrollThrottle = typeof(baseOptions.wheelScrollThrottle) !== "undefined" ? baseOptions.wheelScrollThrottle : 70;
  6588. /**
  6589. * @ngdoc property
  6590. * @name scrollDebounce
  6591. * @propertyOf ui.grid.class:GridOptions
  6592. * @description Default time in milliseconds to debounce scroll events, defaults to 300ms
  6593. */
  6594. baseOptions.scrollDebounce = typeof(baseOptions.scrollDebounce) !== "undefined" ? baseOptions.scrollDebounce : 300;
  6595. /**
  6596. * @ngdoc boolean
  6597. * @name enableSorting
  6598. * @propertyOf ui.grid.class:GridOptions
  6599. * @description True by default. When enabled, this setting adds sort
  6600. * widgets to the column headers, allowing sorting of the data for the entire grid.
  6601. * Sorting can then be disabled on individual columns using the columnDefs.
  6602. */
  6603. baseOptions.enableSorting = baseOptions.enableSorting !== false;
  6604. /**
  6605. * @ngdoc boolean
  6606. * @name enableFiltering
  6607. * @propertyOf ui.grid.class:GridOptions
  6608. * @description False by default. When enabled, this setting adds filter
  6609. * boxes to each column header, allowing filtering within the column for the entire grid.
  6610. * Filtering can then be disabled on individual columns using the columnDefs.
  6611. */
  6612. baseOptions.enableFiltering = baseOptions.enableFiltering === true;
  6613. /**
  6614. * @ngdoc boolean
  6615. * @name enableColumnMenus
  6616. * @propertyOf ui.grid.class:GridOptions
  6617. * @description True by default. When enabled, this setting displays a column
  6618. * menu within each column.
  6619. */
  6620. baseOptions.enableColumnMenus = baseOptions.enableColumnMenus !== false;
  6621. /**
  6622. * @ngdoc boolean
  6623. * @name enableVerticalScrollbar
  6624. * @propertyOf ui.grid.class:GridOptions
  6625. * @description uiGridConstants.scrollbars.ALWAYS by default. This settings controls the vertical scrollbar for the grid.
  6626. * Supported values: uiGridConstants.scrollbars.ALWAYS, uiGridConstants.scrollbars.NEVER
  6627. */
  6628. baseOptions.enableVerticalScrollbar = typeof(baseOptions.enableVerticalScrollbar) !== "undefined" ? baseOptions.enableVerticalScrollbar : uiGridConstants.scrollbars.ALWAYS;
  6629. /**
  6630. * @ngdoc boolean
  6631. * @name enableHorizontalScrollbar
  6632. * @propertyOf ui.grid.class:GridOptions
  6633. * @description uiGridConstants.scrollbars.ALWAYS by default. This settings controls the horizontal scrollbar for the grid.
  6634. * Supported values: uiGridConstants.scrollbars.ALWAYS, uiGridConstants.scrollbars.NEVER
  6635. */
  6636. baseOptions.enableHorizontalScrollbar = typeof(baseOptions.enableHorizontalScrollbar) !== "undefined" ? baseOptions.enableHorizontalScrollbar : uiGridConstants.scrollbars.ALWAYS;
  6637. /**
  6638. * @ngdoc boolean
  6639. * @name enableMinHeightCheck
  6640. * @propertyOf ui.grid.class:GridOptions
  6641. * @description True by default. When enabled, a newly initialized grid will check to see if it is tall enough to display
  6642. * at least one row of data. If the grid is not tall enough, it will resize the DOM element to display minRowsToShow number
  6643. * of rows.
  6644. */
  6645. baseOptions.enableMinHeightCheck = baseOptions.enableMinHeightCheck !== false;
  6646. /**
  6647. * @ngdoc boolean
  6648. * @name minimumColumnSize
  6649. * @propertyOf ui.grid.class:GridOptions
  6650. * @description Columns can't be smaller than this, defaults to 10 pixels
  6651. */
  6652. baseOptions.minimumColumnSize = typeof(baseOptions.minimumColumnSize) !== "undefined" ? baseOptions.minimumColumnSize : 10;
  6653. /**
  6654. * @ngdoc function
  6655. * @name rowEquality
  6656. * @methodOf ui.grid.class:GridOptions
  6657. * @description By default, rows are compared using object equality. This option can be overridden
  6658. * to compare on any data item property or function
  6659. * @param {object} entityA First Data Item to compare
  6660. * @param {object} entityB Second Data Item to compare
  6661. */
  6662. baseOptions.rowEquality = baseOptions.rowEquality || function(entityA, entityB) {
  6663. return entityA === entityB;
  6664. };
  6665. /**
  6666. * @ngdoc string
  6667. * @name headerTemplate
  6668. * @propertyOf ui.grid.class:GridOptions
  6669. * @description Null by default. When provided, this setting uses a custom header
  6670. * template, rather than the default template. Can be set to either the name of a template file:
  6671. * <pre> $scope.gridOptions.headerTemplate = 'header_template.html';</pre>
  6672. * inline html
  6673. * <pre> $scope.gridOptions.headerTemplate = '<div class="ui-grid-top-panel" style="text-align: center">I am a Custom Grid Header</div>'</pre>
  6674. * or the id of a precompiled template (TBD how to use this).
  6675. * </br>Refer to the custom header tutorial for more information.
  6676. * If you want no header at all, you can set to an empty div:
  6677. * <pre> $scope.gridOptions.headerTemplate = '<div></div>';</pre>
  6678. *
  6679. * If you want to only have a static header, then you can set to static content. If
  6680. * you want to tailor the existing column headers, then you should look at the
  6681. * current 'ui-grid-header.html' template in github as your starting point.
  6682. *
  6683. */
  6684. baseOptions.headerTemplate = baseOptions.headerTemplate || null;
  6685. /**
  6686. * @ngdoc string
  6687. * @name footerTemplate
  6688. * @propertyOf ui.grid.class:GridOptions
  6689. * @description (optional) ui-grid/ui-grid-footer by default. This footer shows the per-column
  6690. * aggregation totals.
  6691. * 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
  6692. * <pre>'<div class="ui-grid-bottom-panel" style="text-align: center">I am a Custom Grid Footer</div>'</pre>, or the id
  6693. * of a precompiled template (TBD how to use this). Refer to the custom footer tutorial for more information.
  6694. */
  6695. baseOptions.footerTemplate = baseOptions.footerTemplate || 'ui-grid/ui-grid-footer';
  6696. /**
  6697. * @ngdoc string
  6698. * @name gridFooterTemplate
  6699. * @propertyOf ui.grid.class:GridOptions
  6700. * @description (optional) ui-grid/ui-grid-grid-footer by default. This template by default shows the
  6701. * total items at the bottom of the grid, and the selected items if selection is enabled.
  6702. */
  6703. baseOptions.gridFooterTemplate = baseOptions.gridFooterTemplate || 'ui-grid/ui-grid-grid-footer';
  6704. /**
  6705. * @ngdoc string
  6706. * @name rowTemplate
  6707. * @propertyOf ui.grid.class:GridOptions
  6708. * @description 'ui-grid/ui-grid-row' by default. When provided, this setting uses a
  6709. * custom row template. Can be set to either the name of a template file:
  6710. * <pre> $scope.gridOptions.rowTemplate = 'row_template.html';</pre>
  6711. * inline html
  6712. * <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>
  6713. * or the id of a precompiled template (TBD how to use this) can be provided.
  6714. * </br>Refer to the custom row template tutorial for more information.
  6715. */
  6716. baseOptions.rowTemplate = baseOptions.rowTemplate || 'ui-grid/ui-grid-row';
  6717. /**
  6718. * @ngdoc object
  6719. * @name appScopeProvider
  6720. * @propertyOf ui.grid.class:GridOptions
  6721. * @description by default, the parent scope of the ui-grid element will be assigned to grid.appScope
  6722. * this property allows you to assign any reference you want to grid.appScope
  6723. */
  6724. baseOptions.appScopeProvider = baseOptions.appScopeProvider || null;
  6725. return baseOptions;
  6726. }
  6727. };
  6728. }]);
  6729. })();
  6730. (function() {
  6731. angular.module('ui.grid')
  6732. /**
  6733. * @ngdoc function
  6734. * @name ui.grid.class:GridRenderContainer
  6735. * @description The grid has render containers, allowing the ability to have pinned columns. If the grid
  6736. * is right-to-left then there may be a right render container, if left-to-right then there may
  6737. * be a left render container. There is always a body render container.
  6738. * @param {string} name The name of the render container ('body', 'left', or 'right')
  6739. * @param {Grid} grid the grid the render container is in
  6740. * @param {object} options the render container options
  6741. */
  6742. .factory('GridRenderContainer', ['gridUtil', 'uiGridConstants', function(gridUtil, uiGridConstants) {
  6743. function GridRenderContainer(name, grid, options) {
  6744. var self = this;
  6745. // if (gridUtil.type(grid) !== 'Grid') {
  6746. // throw new Error('Grid argument is not a Grid object');
  6747. // }
  6748. self.name = name;
  6749. self.grid = grid;
  6750. // self.rowCache = [];
  6751. // self.columnCache = [];
  6752. self.visibleRowCache = [];
  6753. self.visibleColumnCache = [];
  6754. self.renderedRows = [];
  6755. self.renderedColumns = [];
  6756. self.prevScrollTop = 0;
  6757. self.prevScrolltopPercentage = 0;
  6758. self.prevRowScrollIndex = 0;
  6759. self.prevScrollLeft = 0;
  6760. self.prevScrollleftPercentage = 0;
  6761. self.prevColumnScrollIndex = 0;
  6762. self.columnStyles = "";
  6763. self.viewportAdjusters = [];
  6764. /**
  6765. * @ngdoc boolean
  6766. * @name hasHScrollbar
  6767. * @propertyOf ui.grid.class:GridRenderContainer
  6768. * @description flag to signal that container has a horizontal scrollbar
  6769. */
  6770. self.hasHScrollbar = false;
  6771. /**
  6772. * @ngdoc boolean
  6773. * @name hasVScrollbar
  6774. * @propertyOf ui.grid.class:GridRenderContainer
  6775. * @description flag to signal that container has a vertical scrollbar
  6776. */
  6777. self.hasVScrollbar = false;
  6778. /**
  6779. * @ngdoc boolean
  6780. * @name canvasHeightShouldUpdate
  6781. * @propertyOf ui.grid.class:GridRenderContainer
  6782. * @description flag to signal that container should recalculate the canvas size
  6783. */
  6784. self.canvasHeightShouldUpdate = true;
  6785. /**
  6786. * @ngdoc boolean
  6787. * @name canvasHeight
  6788. * @propertyOf ui.grid.class:GridRenderContainer
  6789. * @description last calculated canvas height value
  6790. */
  6791. self.$$canvasHeight = 0;
  6792. if (options && angular.isObject(options)) {
  6793. angular.extend(self, options);
  6794. }
  6795. grid.registerStyleComputation({
  6796. priority: 5,
  6797. func: function() {
  6798. self.updateColumnWidths();
  6799. return self.columnStyles;
  6800. }
  6801. });
  6802. }
  6803. GridRenderContainer.prototype.reset = function reset() {
  6804. // this.rowCache.length = 0;
  6805. // this.columnCache.length = 0;
  6806. this.visibleColumnCache.length = 0;
  6807. this.visibleRowCache.length = 0;
  6808. this.renderedRows.length = 0;
  6809. this.renderedColumns.length = 0;
  6810. };
  6811. // TODO(c0bra): calculate size?? Should this be in a stackable directive?
  6812. GridRenderContainer.prototype.containsColumn = function(col) {
  6813. return this.visibleColumnCache.indexOf(col) !== -1;
  6814. };
  6815. GridRenderContainer.prototype.minRowsToRender = function minRowsToRender() {
  6816. var self = this;
  6817. var minRows = 0;
  6818. var rowAddedHeight = 0;
  6819. var viewPortHeight = self.getViewportHeight();
  6820. for (var i = self.visibleRowCache.length - 1; rowAddedHeight < viewPortHeight && i >= 0; i--) {
  6821. rowAddedHeight += self.visibleRowCache[i].height;
  6822. minRows++;
  6823. }
  6824. return minRows;
  6825. };
  6826. GridRenderContainer.prototype.minColumnsToRender = function minColumnsToRender() {
  6827. var self = this;
  6828. var viewportWidth = this.getViewportWidth();
  6829. var min = 0;
  6830. var totalWidth = 0;
  6831. // self.columns.forEach(function(col, i) {
  6832. for (var i = 0; i < self.visibleColumnCache.length; i++) {
  6833. var col = self.visibleColumnCache[i];
  6834. if (totalWidth < viewportWidth) {
  6835. totalWidth += col.drawnWidth ? col.drawnWidth : 0;
  6836. min++;
  6837. } else {
  6838. var currWidth = 0;
  6839. for (var j = i; j >= i - min; j--) {
  6840. currWidth += self.visibleColumnCache[j].drawnWidth ? self.visibleColumnCache[j].drawnWidth : 0;
  6841. }
  6842. if (currWidth < viewportWidth) {
  6843. min++;
  6844. }
  6845. }
  6846. }
  6847. return min;
  6848. };
  6849. GridRenderContainer.prototype.getVisibleRowCount = function getVisibleRowCount() {
  6850. return this.visibleRowCache.length;
  6851. };
  6852. /**
  6853. * @ngdoc function
  6854. * @name registerViewportAdjuster
  6855. * @methodOf ui.grid.class:GridRenderContainer
  6856. * @description Registers an adjuster to the render container's available width or height. Adjusters are used
  6857. * to tell the render container that there is something else consuming space, and to adjust it's size
  6858. * appropriately.
  6859. * @param {function} func the adjuster function we want to register
  6860. */
  6861. GridRenderContainer.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) {
  6862. this.viewportAdjusters.push(func);
  6863. };
  6864. /**
  6865. * @ngdoc function
  6866. * @name removeViewportAdjuster
  6867. * @methodOf ui.grid.class:GridRenderContainer
  6868. * @description Removes an adjuster, should be used when your element is destroyed
  6869. * @param {function} func the adjuster function we want to remove
  6870. */
  6871. GridRenderContainer.prototype.removeViewportAdjuster = function removeViewportAdjuster(func) {
  6872. var idx = this.viewportAdjusters.indexOf(func);
  6873. if (idx > -1) {
  6874. this.viewportAdjusters.splice(idx, 1);
  6875. }
  6876. };
  6877. /**
  6878. * @ngdoc function
  6879. * @name getViewportAdjustment
  6880. * @methodOf ui.grid.class:GridRenderContainer
  6881. * @description Gets the adjustment based on the viewportAdjusters.
  6882. * @returns {object} a hash of { height: x, width: y }. Usually the values will be negative
  6883. */
  6884. GridRenderContainer.prototype.getViewportAdjustment = function getViewportAdjustment() {
  6885. var self = this;
  6886. var adjustment = { height: 0, width: 0 };
  6887. self.viewportAdjusters.forEach(function(func) {
  6888. adjustment = func.call(this, adjustment);
  6889. });
  6890. return adjustment;
  6891. };
  6892. GridRenderContainer.prototype.getMargin = function getMargin(side) {
  6893. var self = this;
  6894. var amount = 0;
  6895. self.viewportAdjusters.forEach(function(func) {
  6896. var adjustment = func.call(this, { height: 0, width: 0 });
  6897. if (adjustment.side && adjustment.side === side) {
  6898. amount += adjustment.width * -1;
  6899. }
  6900. });
  6901. return amount;
  6902. };
  6903. GridRenderContainer.prototype.getViewportHeight = function getViewportHeight() {
  6904. var self = this;
  6905. var headerHeight = (self.headerHeight) ? self.headerHeight : self.grid.headerHeight;
  6906. var viewPortHeight = self.grid.gridHeight - headerHeight - self.grid.footerHeight;
  6907. var adjustment = self.getViewportAdjustment();
  6908. viewPortHeight = viewPortHeight + adjustment.height;
  6909. return viewPortHeight;
  6910. };
  6911. GridRenderContainer.prototype.getViewportWidth = function getViewportWidth() {
  6912. var self = this;
  6913. var viewportWidth = self.grid.gridWidth;
  6914. //if (typeof(self.grid.verticalScrollbarWidth) !== 'undefined' && self.grid.verticalScrollbarWidth !== undefined && self.grid.verticalScrollbarWidth > 0) {
  6915. // viewPortWidth = viewPortWidth - self.grid.verticalScrollbarWidth;
  6916. //}
  6917. // var viewportWidth = 0;\
  6918. // self.visibleColumnCache.forEach(function (column) {
  6919. // viewportWidth += column.drawnWidth;
  6920. // });
  6921. var adjustment = self.getViewportAdjustment();
  6922. viewportWidth = viewportWidth + adjustment.width;
  6923. return viewportWidth;
  6924. };
  6925. GridRenderContainer.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() {
  6926. var self = this;
  6927. var viewportWidth = this.getViewportWidth();
  6928. //if (typeof(self.grid.verticalScrollbarWidth) !== 'undefined' && self.grid.verticalScrollbarWidth !== undefined && self.grid.verticalScrollbarWidth > 0) {
  6929. // viewPortWidth = viewPortWidth + self.grid.verticalScrollbarWidth;
  6930. //}
  6931. // var adjustment = self.getViewportAdjustment();
  6932. // viewPortWidth = viewPortWidth + adjustment.width;
  6933. return viewportWidth;
  6934. };
  6935. /**
  6936. * @ngdoc function
  6937. * @name getCanvasHeight
  6938. * @methodOf ui.grid.class:GridRenderContainer
  6939. * @description Returns the total canvas height. Only recalculates if canvasHeightShouldUpdate = false
  6940. * @returns {number} total height of all the visible rows in the container
  6941. */
  6942. GridRenderContainer.prototype.getCanvasHeight = function getCanvasHeight() {
  6943. var self = this;
  6944. if (!self.canvasHeightShouldUpdate) {
  6945. return self.$$canvasHeight;
  6946. }
  6947. var oldCanvasHeight = self.$$canvasHeight;
  6948. self.$$canvasHeight = 0;
  6949. self.visibleRowCache.forEach(function(row) {
  6950. self.$$canvasHeight += row.height;
  6951. });
  6952. self.canvasHeightShouldUpdate = false;
  6953. self.grid.api.core.raise.canvasHeightChanged(oldCanvasHeight, self.$$canvasHeight);
  6954. return self.$$canvasHeight;
  6955. };
  6956. GridRenderContainer.prototype.getVerticalScrollLength = function getVerticalScrollLength() {
  6957. return this.getCanvasHeight() - this.getViewportHeight() + this.grid.scrollbarHeight;
  6958. };
  6959. GridRenderContainer.prototype.getCanvasWidth = function getCanvasWidth() {
  6960. var self = this;
  6961. var ret = self.canvasWidth;
  6962. return ret;
  6963. };
  6964. GridRenderContainer.prototype.setRenderedRows = function setRenderedRows(newRows) {
  6965. this.renderedRows.length = newRows.length;
  6966. for (var i = 0; i < newRows.length; i++) {
  6967. this.renderedRows[i] = newRows[i];
  6968. }
  6969. };
  6970. GridRenderContainer.prototype.setRenderedColumns = function setRenderedColumns(newColumns) {
  6971. var self = this;
  6972. // OLD:
  6973. this.renderedColumns.length = newColumns.length;
  6974. for (var i = 0; i < newColumns.length; i++) {
  6975. this.renderedColumns[i] = newColumns[i];
  6976. }
  6977. this.updateColumnOffset();
  6978. };
  6979. GridRenderContainer.prototype.updateColumnOffset = function updateColumnOffset() {
  6980. // Calculate the width of the columns on the left side that are no longer rendered.
  6981. // That will be the offset for the columns as we scroll horizontally.
  6982. var hiddenColumnsWidth = 0;
  6983. for (var i = 0; i < this.currentFirstColumn; i++) {
  6984. hiddenColumnsWidth += this.visibleColumnCache[i].drawnWidth;
  6985. }
  6986. this.columnOffset = hiddenColumnsWidth;
  6987. };
  6988. GridRenderContainer.prototype.scrollVertical = function(newScrollTop) {
  6989. var vertScrollPercentage = -1;
  6990. if (newScrollTop !== this.prevScrollTop) {
  6991. var yDiff = newScrollTop - this.prevScrollTop;
  6992. if (yDiff > 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.DOWN; }
  6993. if (yDiff < 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.UP; }
  6994. var vertScrollLength = this.getVerticalScrollLength();
  6995. vertScrollPercentage = newScrollTop / vertScrollLength;
  6996. // console.log('vert', vertScrollPercentage, newScrollTop, vertScrollLength);
  6997. if (vertScrollPercentage > 1) { vertScrollPercentage = 1; }
  6998. if (vertScrollPercentage < 0) { vertScrollPercentage = 0; }
  6999. this.adjustScrollVertical(newScrollTop, vertScrollPercentage);
  7000. return vertScrollPercentage;
  7001. }
  7002. };
  7003. GridRenderContainer.prototype.scrollHorizontal = function(newScrollLeft) {
  7004. var horizScrollPercentage = -1;
  7005. // Handle RTL here
  7006. if (newScrollLeft !== this.prevScrollLeft) {
  7007. var xDiff = newScrollLeft - this.prevScrollLeft;
  7008. if (xDiff > 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.RIGHT; }
  7009. if (xDiff < 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.LEFT; }
  7010. var horizScrollLength = (this.canvasWidth - this.getViewportWidth());
  7011. if (horizScrollLength !== 0) {
  7012. horizScrollPercentage = newScrollLeft / horizScrollLength;
  7013. } else {
  7014. horizScrollPercentage = 0;
  7015. }
  7016. this.adjustScrollHorizontal(newScrollLeft, horizScrollPercentage);
  7017. return horizScrollPercentage;
  7018. }
  7019. };
  7020. GridRenderContainer.prototype.adjustScrollVertical = function adjustScrollVertical(scrollTop, scrollPercentage, force) {
  7021. if (this.prevScrollTop === scrollTop && !force) {
  7022. return;
  7023. }
  7024. if (typeof(scrollTop) === 'undefined' || scrollTop === undefined || scrollTop === null) {
  7025. scrollTop = (this.getCanvasHeight() - this.getViewportHeight()) * scrollPercentage;
  7026. }
  7027. this.adjustRows(scrollTop, scrollPercentage, false);
  7028. this.prevScrollTop = scrollTop;
  7029. this.prevScrolltopPercentage = scrollPercentage;
  7030. this.grid.queueRefresh();
  7031. };
  7032. GridRenderContainer.prototype.adjustScrollHorizontal = function adjustScrollHorizontal(scrollLeft, scrollPercentage, force) {
  7033. if (this.prevScrollLeft === scrollLeft && !force) {
  7034. return;
  7035. }
  7036. if (typeof(scrollLeft) === 'undefined' || scrollLeft === undefined || scrollLeft === null) {
  7037. scrollLeft = (this.getCanvasWidth() - this.getViewportWidth()) * scrollPercentage;
  7038. }
  7039. this.adjustColumns(scrollLeft, scrollPercentage);
  7040. this.prevScrollLeft = scrollLeft;
  7041. this.prevScrollleftPercentage = scrollPercentage;
  7042. this.grid.queueRefresh();
  7043. };
  7044. GridRenderContainer.prototype.adjustRows = function adjustRows(scrollTop, scrollPercentage, postDataLoaded) {
  7045. var self = this;
  7046. var minRows = self.minRowsToRender();
  7047. var rowCache = self.visibleRowCache;
  7048. var maxRowIndex = rowCache.length - minRows;
  7049. // console.log('scroll%1', scrollPercentage);
  7050. // Calculate the scroll percentage according to the scrollTop location, if no percentage was provided
  7051. if ((typeof(scrollPercentage) === 'undefined' || scrollPercentage === null) && scrollTop) {
  7052. scrollPercentage = scrollTop / self.getVerticalScrollLength();
  7053. }
  7054. var rowIndex = Math.ceil(Math.min(maxRowIndex, maxRowIndex * scrollPercentage));
  7055. // console.log('maxRowIndex / scroll%', maxRowIndex, scrollPercentage, rowIndex);
  7056. // Define a max row index that we can't scroll past
  7057. if (rowIndex > maxRowIndex) {
  7058. rowIndex = maxRowIndex;
  7059. }
  7060. var newRange = [];
  7061. if (rowCache.length > self.grid.options.virtualizationThreshold) {
  7062. if (!(typeof(scrollTop) === 'undefined' || scrollTop === null)) {
  7063. // Have we hit the threshold going down?
  7064. if (!self.grid.suppressParentScrollDown && self.prevScrollTop < scrollTop && rowIndex < self.prevRowScrollIndex + self.grid.options.scrollThreshold && rowIndex < maxRowIndex) {
  7065. return;
  7066. }
  7067. //Have we hit the threshold going up?
  7068. if (!self.grid.suppressParentScrollUp && self.prevScrollTop > scrollTop && rowIndex > self.prevRowScrollIndex - self.grid.options.scrollThreshold && rowIndex < maxRowIndex) {
  7069. return;
  7070. }
  7071. }
  7072. var rangeStart = {};
  7073. var rangeEnd = {};
  7074. rangeStart = Math.max(0, rowIndex - self.grid.options.excessRows);
  7075. rangeEnd = Math.min(rowCache.length, rowIndex + minRows + self.grid.options.excessRows);
  7076. newRange = [rangeStart, rangeEnd];
  7077. } else {
  7078. var maxLen = self.visibleRowCache.length;
  7079. newRange = [0, Math.max(maxLen, minRows + self.grid.options.excessRows)];
  7080. }
  7081. self.updateViewableRowRange(newRange);
  7082. self.prevRowScrollIndex = rowIndex;
  7083. };
  7084. GridRenderContainer.prototype.adjustColumns = function adjustColumns(scrollLeft, scrollPercentage) {
  7085. var self = this;
  7086. var minCols = self.minColumnsToRender();
  7087. var columnCache = self.visibleColumnCache;
  7088. var maxColumnIndex = columnCache.length - minCols;
  7089. // Calculate the scroll percentage according to the scrollLeft location, if no percentage was provided
  7090. if ((typeof(scrollPercentage) === 'undefined' || scrollPercentage === null) && scrollLeft) {
  7091. var horizScrollLength = (self.getCanvasWidth() - self.getViewportWidth());
  7092. scrollPercentage = scrollLeft / horizScrollLength;
  7093. }
  7094. var colIndex = Math.ceil(Math.min(maxColumnIndex, maxColumnIndex * scrollPercentage));
  7095. // Define a max row index that we can't scroll past
  7096. if (colIndex > maxColumnIndex) {
  7097. colIndex = maxColumnIndex;
  7098. }
  7099. var newRange = [];
  7100. if (columnCache.length > self.grid.options.columnVirtualizationThreshold && self.getCanvasWidth() > self.getViewportWidth()) {
  7101. /* Commented the following lines because otherwise the moved column wasn't visible immediately on the new position
  7102. * in the case of many columns with horizontal scroll, one had to scroll left or right and then return in order to see it
  7103. // Have we hit the threshold going down?
  7104. if (self.prevScrollLeft < scrollLeft && colIndex < self.prevColumnScrollIndex + self.grid.options.horizontalScrollThreshold && colIndex < maxColumnIndex) {
  7105. return;
  7106. }
  7107. //Have we hit the threshold going up?
  7108. if (self.prevScrollLeft > scrollLeft && colIndex > self.prevColumnScrollIndex - self.grid.options.horizontalScrollThreshold && colIndex < maxColumnIndex) {
  7109. return;
  7110. }*/
  7111. var rangeStart = Math.max(0, colIndex - self.grid.options.excessColumns);
  7112. var rangeEnd = Math.min(columnCache.length, colIndex + minCols + self.grid.options.excessColumns);
  7113. newRange = [rangeStart, rangeEnd];
  7114. } else {
  7115. var maxLen = self.visibleColumnCache.length;
  7116. newRange = [0, Math.max(maxLen, minCols + self.grid.options.excessColumns)];
  7117. }
  7118. self.updateViewableColumnRange(newRange);
  7119. self.prevColumnScrollIndex = colIndex;
  7120. };
  7121. // Method for updating the visible rows
  7122. GridRenderContainer.prototype.updateViewableRowRange = function updateViewableRowRange(renderedRange) {
  7123. // Slice out the range of rows from the data
  7124. // var rowArr = uiGridCtrl.grid.rows.slice(renderedRange[0], renderedRange[1]);
  7125. var rowArr = this.visibleRowCache.slice(renderedRange[0], renderedRange[1]);
  7126. // Define the top-most rendered row
  7127. this.currentTopRow = renderedRange[0];
  7128. this.setRenderedRows(rowArr);
  7129. };
  7130. // Method for updating the visible columns
  7131. GridRenderContainer.prototype.updateViewableColumnRange = function updateViewableColumnRange(renderedRange) {
  7132. // Slice out the range of rows from the data
  7133. // var columnArr = uiGridCtrl.grid.columns.slice(renderedRange[0], renderedRange[1]);
  7134. var columnArr = this.visibleColumnCache.slice(renderedRange[0], renderedRange[1]);
  7135. // Define the left-most rendered columns
  7136. this.currentFirstColumn = renderedRange[0];
  7137. this.setRenderedColumns(columnArr);
  7138. };
  7139. GridRenderContainer.prototype.headerCellWrapperStyle = function() {
  7140. var self = this;
  7141. if (self.currentFirstColumn !== 0) {
  7142. var offset = self.columnOffset;
  7143. if (self.grid.isRTL()) {
  7144. return { 'margin-right': offset + 'px' };
  7145. } else {
  7146. return { 'margin-left': offset + 'px' };
  7147. }
  7148. }
  7149. return null;
  7150. };
  7151. /**
  7152. * @ngdoc boolean
  7153. * @name updateColumnWidths
  7154. * @propertyOf ui.grid.class:GridRenderContainer
  7155. * @description Determine the appropriate column width of each column across all render containers.
  7156. *
  7157. * Column width is easy when each column has a specified width. When columns are variable width (i.e.
  7158. * have an * or % of the viewport) then we try to calculate so that things fit in. The problem is that
  7159. * we have multiple render containers, and we don't want one render container to just take the whole viewport
  7160. * when it doesn't need to - we want things to balance out across the render containers.
  7161. *
  7162. * To do this, we use this method to calculate all the renderContainers, recognising that in a given render
  7163. * cycle it'll get called once per render container, so it needs to return the same values each time.
  7164. *
  7165. * The constraints on this method are therefore:
  7166. * - must return the same value when called multiple times, to do this it needs to rely on properties of the
  7167. * columns, but not properties that change when this is called (so it shouldn't rely on drawnWidth)
  7168. *
  7169. * The general logic of this method is:
  7170. * - calculate our total available width
  7171. * - look at all the columns across all render containers, and work out which have widths and which have
  7172. * constraints such as % or * or something else
  7173. * - for those with *, count the total number of * we see and add it onto a running total, add this column to an * array
  7174. * - for those with a %, allocate the % as a percentage of the viewport, having consideration of min and max
  7175. * - for those with manual width (in pixels) we set the drawnWidth to the specified width
  7176. * - we end up with an asterisks array still to process
  7177. * - we look at our remaining width. If it's greater than zero, we divide it up among the asterisk columns, then process
  7178. * them for min and max width constraints
  7179. * - if it's zero or less, we set the asterisk columns to their minimum widths
  7180. * - we use parseInt quite a bit, as we try to make all our column widths integers
  7181. */
  7182. GridRenderContainer.prototype.updateColumnWidths = function() {
  7183. var self = this;
  7184. var asterisksArray = [],
  7185. asteriskNum = 0,
  7186. usedWidthSum = 0,
  7187. ret = '';
  7188. // Get the width of the viewport
  7189. var availableWidth = self.grid.getViewportWidth() - self.grid.scrollbarWidth;
  7190. // get all the columns across all render containers, we have to calculate them all or one render container
  7191. // could consume the whole viewport
  7192. var columnCache = [];
  7193. angular.forEach(self.grid.renderContainers, function(container, name) {
  7194. columnCache = columnCache.concat(container.visibleColumnCache);
  7195. });
  7196. // look at each column, process any manual values or %, put the * into an array to look at later
  7197. columnCache.forEach(function(column, i) {
  7198. var width = 0;
  7199. // Skip hidden columns
  7200. if (!column.visible) { return; }
  7201. if (angular.isNumber(column.width)) {
  7202. // pixel width, set to this value
  7203. width = parseInt(column.width, 10);
  7204. usedWidthSum = usedWidthSum + width;
  7205. column.drawnWidth = width;
  7206. } else if (gridUtil.endsWith(column.width, "%")) {
  7207. // percentage width, set to percentage of the viewport
  7208. width = parseInt(parseInt(column.width.replace(/%/g, ''), 10) / 100 * availableWidth);
  7209. if (width > column.maxWidth) {
  7210. width = column.maxWidth;
  7211. }
  7212. if (width < column.minWidth) {
  7213. width = column.minWidth;
  7214. }
  7215. usedWidthSum = usedWidthSum + width;
  7216. column.drawnWidth = width;
  7217. } else if (angular.isString(column.width) && column.width.indexOf('*') !== -1) {
  7218. // is an asterisk column, the gridColumn already checked the string consists only of '****'
  7219. asteriskNum = asteriskNum + column.width.length;
  7220. asterisksArray.push(column);
  7221. }
  7222. });
  7223. // Get the remaining width (available width subtracted by the used widths sum)
  7224. var remainingWidth = availableWidth - usedWidthSum;
  7225. var i, column, colWidth;
  7226. if (asterisksArray.length > 0) {
  7227. // the width that each asterisk value would be assigned (this can be negative)
  7228. var asteriskVal = remainingWidth / asteriskNum;
  7229. asterisksArray.forEach(function(column) {
  7230. var width = parseInt(column.width.length * asteriskVal, 10);
  7231. if (width > column.maxWidth) {
  7232. width = column.maxWidth;
  7233. }
  7234. if (width < column.minWidth) {
  7235. width = column.minWidth;
  7236. }
  7237. usedWidthSum = usedWidthSum + width;
  7238. column.drawnWidth = width;
  7239. });
  7240. }
  7241. // If the grid width didn't divide evenly into the column widths and we have pixels left over, or our
  7242. // calculated widths would have the grid narrower than the available space,
  7243. // dole the remainder out one by one to make everything fit
  7244. var processColumnUpwards = function(column) {
  7245. if (column.drawnWidth < column.maxWidth && leftoverWidth > 0) {
  7246. column.drawnWidth++;
  7247. usedWidthSum++;
  7248. leftoverWidth--;
  7249. columnsToChange = true;
  7250. }
  7251. };
  7252. var leftoverWidth = availableWidth - usedWidthSum;
  7253. var columnsToChange = true;
  7254. while (leftoverWidth > 0 && columnsToChange) {
  7255. columnsToChange = false;
  7256. asterisksArray.forEach(processColumnUpwards);
  7257. }
  7258. // We can end up with too much width even though some columns aren't at their max width, in this situation
  7259. // we can trim the columns a little
  7260. var processColumnDownwards = function(column) {
  7261. if (column.drawnWidth > column.minWidth && excessWidth > 0) {
  7262. column.drawnWidth--;
  7263. usedWidthSum--;
  7264. excessWidth--;
  7265. columnsToChange = true;
  7266. }
  7267. };
  7268. var excessWidth = usedWidthSum - availableWidth;
  7269. columnsToChange = true;
  7270. while (excessWidth > 0 && columnsToChange) {
  7271. columnsToChange = false;
  7272. asterisksArray.forEach(processColumnDownwards);
  7273. }
  7274. // all that was across all the renderContainers, now we need to work out what that calculation decided for
  7275. // our renderContainer
  7276. var canvasWidth = 0;
  7277. self.visibleColumnCache.forEach(function(column) {
  7278. if (column.visible) {
  7279. canvasWidth = canvasWidth + column.drawnWidth;
  7280. }
  7281. });
  7282. // Build the CSS
  7283. columnCache.forEach(function(column) {
  7284. ret = ret + column.getColClassDefinition();
  7285. });
  7286. self.canvasWidth = canvasWidth;
  7287. // Return the styles back to buildStyles which pops them into the `customStyles` scope variable
  7288. // return ret;
  7289. // Set this render container's column styles so they can be used in style computation
  7290. this.columnStyles = ret;
  7291. };
  7292. GridRenderContainer.prototype.needsHScrollbarPlaceholder = function() {
  7293. return this.grid.options.enableHorizontalScrollbar && !this.hasHScrollbar;
  7294. };
  7295. GridRenderContainer.prototype.getViewportStyle = function() {
  7296. var self = this;
  7297. var styles = {};
  7298. self.hasHScrollbar = false;
  7299. self.hasVScrollbar = false;
  7300. if (self.grid.disableScrolling) {
  7301. styles['overflow-x'] = 'hidden';
  7302. styles['overflow-y'] = 'hidden';
  7303. return styles;
  7304. }
  7305. if (self.name === 'body') {
  7306. self.hasHScrollbar = self.grid.options.enableHorizontalScrollbar !== uiGridConstants.scrollbars.NEVER;
  7307. if (!self.grid.isRTL()) {
  7308. if (!self.grid.hasRightContainerColumns()) {
  7309. self.hasVScrollbar = self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER;
  7310. }
  7311. } else {
  7312. if (!self.grid.hasLeftContainerColumns()) {
  7313. self.hasVScrollbar = self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER;
  7314. }
  7315. }
  7316. } else if (self.name === 'left') {
  7317. self.hasVScrollbar = self.grid.isRTL() ? self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER : false;
  7318. } else {
  7319. self.hasVScrollbar = !self.grid.isRTL() ? self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER : false;
  7320. }
  7321. styles['overflow-x'] = self.hasHScrollbar ? 'scroll' : 'hidden';
  7322. styles['overflow-y'] = self.hasVScrollbar ? 'scroll' : 'hidden';
  7323. return styles;
  7324. };
  7325. return GridRenderContainer;
  7326. }]);
  7327. })();
  7328. (function() {
  7329. angular.module('ui.grid')
  7330. .factory('GridRow', ['gridUtil', function(gridUtil) {
  7331. /**
  7332. * @ngdoc function
  7333. * @name ui.grid.class:GridRow
  7334. * @description GridRow is the viewModel for one logical row on the grid. A grid Row is not necessarily a one-to-one
  7335. * relation to gridOptions.data.
  7336. * @param {object} entity the array item from GridOptions.data
  7337. * @param {number} index the current position of the row in the array
  7338. * @param {Grid} reference to the parent grid
  7339. */
  7340. function GridRow(entity, index, grid) {
  7341. /**
  7342. * @ngdoc object
  7343. * @name grid
  7344. * @propertyOf ui.grid.class:GridRow
  7345. * @description A reference back to the grid
  7346. */
  7347. this.grid = grid;
  7348. /**
  7349. * @ngdoc object
  7350. * @name entity
  7351. * @propertyOf ui.grid.class:GridRow
  7352. * @description A reference to an item in gridOptions.data[]
  7353. */
  7354. this.entity = entity;
  7355. /**
  7356. * @ngdoc object
  7357. * @name uid
  7358. * @propertyOf ui.grid.class:GridRow
  7359. * @description UniqueId of row
  7360. */
  7361. this.uid = gridUtil.nextUid();
  7362. /**
  7363. * @ngdoc object
  7364. * @name visible
  7365. * @propertyOf ui.grid.class:GridRow
  7366. * @description If true, the row will be rendered
  7367. */
  7368. // Default to true
  7369. this.visible = true;
  7370. this.$$height = grid.options.rowHeight;
  7371. }
  7372. /**
  7373. * @ngdoc object
  7374. * @name height
  7375. * @propertyOf ui.grid.class:GridRow
  7376. * @description height of each individual row. changing the height will flag all
  7377. * row renderContainers to recalculate their canvas height
  7378. */
  7379. Object.defineProperty(GridRow.prototype, 'height', {
  7380. get: function() {
  7381. return this.$$height;
  7382. },
  7383. set: function(height) {
  7384. if (height !== this.$$height) {
  7385. this.grid.updateCanvasHeight();
  7386. this.$$height = height;
  7387. }
  7388. }
  7389. });
  7390. /**
  7391. * @ngdoc function
  7392. * @name getQualifiedColField
  7393. * @methodOf ui.grid.class:GridRow
  7394. * @description returns the qualified field name as it exists on scope
  7395. * ie: row.entity.fieldA
  7396. * @param {GridCol} col column instance
  7397. * @returns {string} resulting name that can be evaluated on scope
  7398. */
  7399. GridRow.prototype.getQualifiedColField = function(col) {
  7400. return 'row.' + this.getEntityQualifiedColField(col);
  7401. };
  7402. /**
  7403. * @ngdoc function
  7404. * @name getEntityQualifiedColField
  7405. * @methodOf ui.grid.class:GridRow
  7406. * @description returns the qualified field name minus the row path
  7407. * ie: entity.fieldA
  7408. * @param {GridCol} col column instance
  7409. * @returns {string} resulting name that can be evaluated against a row
  7410. */
  7411. GridRow.prototype.getEntityQualifiedColField = function(col) {
  7412. return gridUtil.preEval('entity.' + col.field);
  7413. };
  7414. /**
  7415. * @ngdoc function
  7416. * @name setRowInvisible
  7417. * @methodOf ui.grid.class:GridRow
  7418. * @description Sets an override on the row that forces it to always
  7419. * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility.
  7420. *
  7421. * This method can be called from the api, passing in the gridRow we want
  7422. * altered. It should really work by calling gridRow.setRowInvisible, but that's
  7423. * not the way I coded it, and too late to change now. Changed to just call
  7424. * the internal function row.setThisRowInvisible().
  7425. *
  7426. * @param {GridRow} row the row we want to set to invisible
  7427. *
  7428. */
  7429. GridRow.prototype.setRowInvisible = function(row) {
  7430. if (row && row.setThisRowInvisible) {
  7431. row.setThisRowInvisible('user');
  7432. }
  7433. };
  7434. /**
  7435. * @ngdoc function
  7436. * @name clearRowInvisible
  7437. * @methodOf ui.grid.class:GridRow
  7438. * @description Clears an override on the row that forces it to always
  7439. * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility.
  7440. *
  7441. * This method can be called from the api, passing in the gridRow we want
  7442. * altered. It should really work by calling gridRow.clearRowInvisible, but that's
  7443. * not the way I coded it, and too late to change now. Changed to just call
  7444. * the internal function row.clearThisRowInvisible().
  7445. *
  7446. * @param {GridRow} row the row we want to clear the invisible flag
  7447. *
  7448. */
  7449. GridRow.prototype.clearRowInvisible = function(row) {
  7450. if (row && row.clearThisRowInvisible) {
  7451. row.clearThisRowInvisible('user');
  7452. }
  7453. };
  7454. /**
  7455. * @ngdoc function
  7456. * @name setThisRowInvisible
  7457. * @methodOf ui.grid.class:GridRow
  7458. * @description Sets an override on the row that forces it to always
  7459. * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility
  7460. *
  7461. * @param {string} reason the reason (usually the module) for the row to be invisible.
  7462. * E.g. grouping, user, filter
  7463. * @param {boolean} fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility
  7464. */
  7465. GridRow.prototype.setThisRowInvisible = function(reason, fromRowsProcessor) {
  7466. if (!this.invisibleReason) {
  7467. this.invisibleReason = {};
  7468. }
  7469. this.invisibleReason[reason] = true;
  7470. this.evaluateRowVisibility(fromRowsProcessor);
  7471. };
  7472. /**
  7473. * @ngdoc function
  7474. * @name clearRowInvisible
  7475. * @methodOf ui.grid.class:GridRow
  7476. * @description Clears any override on the row visibility, returning it
  7477. * to normal visibility calculations. Emits the rowsVisibleChanged
  7478. * event
  7479. *
  7480. * @param {string} reason the reason (usually the module) for the row to be invisible.
  7481. * E.g. grouping, user, filter
  7482. * @param {boolean} fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility
  7483. */
  7484. GridRow.prototype.clearThisRowInvisible = function(reason, fromRowsProcessor) {
  7485. if (typeof(this.invisibleReason) !== 'undefined') {
  7486. delete this.invisibleReason[reason];
  7487. }
  7488. this.evaluateRowVisibility(fromRowsProcessor);
  7489. };
  7490. /**
  7491. * @ngdoc function
  7492. * @name evaluateRowVisibility
  7493. * @methodOf ui.grid.class:GridRow
  7494. * @description Determines whether the row should be visible based on invisibleReason,
  7495. * and if it changes the row visibility, then emits the rowsVisibleChanged event.
  7496. *
  7497. * Queues a grid refresh, but doesn't call it directly to avoid hitting lots of grid refreshes.
  7498. * @param {boolean} fromRowProcessor if true, then it won't raise events or queue the refresh, the
  7499. * row processor does that already
  7500. */
  7501. GridRow.prototype.evaluateRowVisibility = function(fromRowProcessor) {
  7502. var newVisibility = true;
  7503. if (typeof(this.invisibleReason) !== 'undefined') {
  7504. angular.forEach(this.invisibleReason, function(value, key) {
  7505. if (value) {
  7506. newVisibility = false;
  7507. }
  7508. });
  7509. }
  7510. if (typeof(this.visible) === 'undefined' || this.visible !== newVisibility) {
  7511. this.visible = newVisibility;
  7512. if (!fromRowProcessor) {
  7513. this.grid.queueGridRefresh();
  7514. this.grid.api.core.raise.rowsVisibleChanged(this);
  7515. }
  7516. }
  7517. };
  7518. return GridRow;
  7519. }]);
  7520. })();
  7521. (function() {
  7522. 'use strict';
  7523. /**
  7524. * @ngdoc object
  7525. * @name ui.grid.class:GridRowColumn
  7526. * @param {GridRow} row The row for this pair
  7527. * @param {GridColumn} column The column for this pair
  7528. * @description A row and column pair that represents the intersection of these two entities.
  7529. * Must be instantiated as a constructor using the `new` keyword.
  7530. */
  7531. angular.module('ui.grid')
  7532. .factory('GridRowColumn', ['$parse', '$filter',
  7533. function GridRowColumnFactory($parse, $filter) {
  7534. var GridRowColumn = function GridRowColumn(row, col) {
  7535. if (!(this instanceof GridRowColumn)) {
  7536. throw "Using GridRowColumn as a function insead of as a constructor. Must be called with `new` keyword";
  7537. }
  7538. /**
  7539. * @ngdoc object
  7540. * @name row
  7541. * @propertyOf ui.grid.class:GridRowColumn
  7542. * @description {@link ui.grid.class:GridRow }
  7543. */
  7544. this.row = row;
  7545. /**
  7546. * @ngdoc object
  7547. * @name col
  7548. * @propertyOf ui.grid.class:GridRowColumn
  7549. * @description {@link ui.grid.class:GridColumn }
  7550. */
  7551. this.col = col;
  7552. };
  7553. /**
  7554. * @ngdoc function
  7555. * @name getIntersectionValueRaw
  7556. * @methodOf ui.grid.class:GridRowColumn
  7557. * @description Gets the intersection of where the row and column meet.
  7558. * @returns {String|Number|Object} The value from the grid data that this GridRowColumn points too.
  7559. * If the column has a cellFilter this will NOT return the filtered value.
  7560. */
  7561. GridRowColumn.prototype.getIntersectionValueRaw = function() {
  7562. var getter = $parse(this.row.getEntityQualifiedColField(this.col));
  7563. var context = this.row;
  7564. return getter(context);
  7565. };
  7566. /**
  7567. * @ngdoc function
  7568. * @name getIntersectionValueFiltered
  7569. * @methodOf ui.grid.class:GridRowColumn
  7570. * @description Gets the intersection of where the row and column meet.
  7571. * @returns {String|Number|Object} The value from the grid data that this GridRowColumn points too.
  7572. * If the column has a cellFilter this will also apply the filter to it and return the value that the filter displays.
  7573. */
  7574. GridRowColumn.prototype.getIntersectionValueFiltered = function() {
  7575. var value = this.getIntersectionValueRaw();
  7576. if (this.col.cellFilter && this.col.cellFilter !== '') {
  7577. var getFilterIfExists = function(filterName) {
  7578. try {
  7579. return $filter(filterName);
  7580. } catch (e) {
  7581. return null;
  7582. }
  7583. };
  7584. var filter = getFilterIfExists(this.col.cellFilter);
  7585. if (filter) { // Check if this is filter name or a filter string
  7586. value = filter(value);
  7587. } else { // We have the template version of a filter so we need to parse it apart
  7588. // Get the filter params out using a regex
  7589. // Test out this regex here https://regex101.com/r/rC5eR5/2
  7590. var re = /([^:]*):([^:]*):?([\s\S]+)?/;
  7591. var matches;
  7592. if ((matches = re.exec(this.col.cellFilter)) !== null) {
  7593. // View your result using the matches-variable.
  7594. // eg matches[0] etc.
  7595. value = $filter(matches[1])(value, matches[2], matches[3]);
  7596. }
  7597. }
  7598. }
  7599. return value;
  7600. };
  7601. return GridRowColumn;
  7602. }
  7603. ]);
  7604. })();
  7605. (function() {
  7606. angular.module('ui.grid')
  7607. .factory('ScrollEvent', ['gridUtil', function(gridUtil) {
  7608. /**
  7609. * @ngdoc function
  7610. * @name ui.grid.class:ScrollEvent
  7611. * @description Model for all scrollEvents
  7612. * @param {Grid} grid that owns the scroll event
  7613. * @param {GridRenderContainer} sourceRowContainer that owns the scroll event. Can be null
  7614. * @param {GridRenderContainer} sourceColContainer that owns the scroll event. Can be null
  7615. * @param {string} source the source of the event - from uiGridConstants.scrollEventSources or a string value of directive/service/factory.functionName
  7616. */
  7617. function ScrollEvent(grid, sourceRowContainer, sourceColContainer, source) {
  7618. var self = this;
  7619. if (!grid) {
  7620. throw new Error("grid argument is required");
  7621. }
  7622. /**
  7623. * @ngdoc object
  7624. * @name grid
  7625. * @propertyOf ui.grid.class:ScrollEvent
  7626. * @description A reference back to the grid
  7627. */
  7628. self.grid = grid;
  7629. /**
  7630. * @ngdoc object
  7631. * @name source
  7632. * @propertyOf ui.grid.class:ScrollEvent
  7633. * @description the source of the scroll event. limited to values from uiGridConstants.scrollEventSources
  7634. */
  7635. self.source = source;
  7636. /**
  7637. * @ngdoc object
  7638. * @name noDelay
  7639. * @propertyOf ui.grid.class:ScrollEvent
  7640. * @description most scroll events from the mouse or trackpad require delay to operate properly
  7641. * set to false to eliminate delay. Useful for scroll events that the grid causes, such as scrolling to make a row visible.
  7642. */
  7643. self.withDelay = true;
  7644. self.sourceRowContainer = sourceRowContainer;
  7645. self.sourceColContainer = sourceColContainer;
  7646. self.newScrollLeft = null;
  7647. self.newScrollTop = null;
  7648. self.x = null;
  7649. self.y = null;
  7650. self.verticalScrollLength = -9999999;
  7651. self.horizontalScrollLength = -999999;
  7652. /**
  7653. * @ngdoc function
  7654. * @name fireThrottledScrollingEvent
  7655. * @methodOf ui.grid.class:ScrollEvent
  7656. * @description fires a throttled event using grid.api.core.raise.scrollEvent
  7657. */
  7658. self.fireThrottledScrollingEvent = gridUtil.throttle(function(sourceContainerId) {
  7659. self.grid.scrollContainers(sourceContainerId, self);
  7660. }, self.grid.options.wheelScrollThrottle, { trailing: true });
  7661. }
  7662. /**
  7663. * @ngdoc function
  7664. * @name getNewScrollLeft
  7665. * @methodOf ui.grid.class:ScrollEvent
  7666. * @description returns newScrollLeft property if available; calculates a new value if it isn't
  7667. */
  7668. ScrollEvent.prototype.getNewScrollLeft = function(colContainer, viewport) {
  7669. var self = this;
  7670. if (!self.newScrollLeft) {
  7671. var scrollWidth = (colContainer.getCanvasWidth() - colContainer.getViewportWidth());
  7672. var oldScrollLeft = gridUtil.normalizeScrollLeft(viewport, self.grid);
  7673. var scrollXPercentage;
  7674. if (typeof(self.x.percentage) !== 'undefined' && self.x.percentage !== undefined) {
  7675. scrollXPercentage = self.x.percentage;
  7676. } else if (typeof(self.x.pixels) !== 'undefined' && self.x.pixels !== undefined) {
  7677. scrollXPercentage = self.x.percentage = (oldScrollLeft + self.x.pixels) / scrollWidth;
  7678. } else {
  7679. throw new Error("No percentage or pixel value provided for scroll event X axis");
  7680. }
  7681. return Math.max(0, scrollXPercentage * scrollWidth);
  7682. }
  7683. return self.newScrollLeft;
  7684. };
  7685. /**
  7686. * @ngdoc function
  7687. * @name getNewScrollTop
  7688. * @methodOf ui.grid.class:ScrollEvent
  7689. * @description returns newScrollTop property if available; calculates a new value if it isn't
  7690. */
  7691. ScrollEvent.prototype.getNewScrollTop = function(rowContainer, viewport) {
  7692. var self = this;
  7693. if (!self.newScrollTop) {
  7694. var scrollLength = rowContainer.getVerticalScrollLength();
  7695. var oldScrollTop = viewport[0].scrollTop;
  7696. var scrollYPercentage;
  7697. if (typeof(self.y.percentage) !== 'undefined' && self.y.percentage !== undefined) {
  7698. scrollYPercentage = self.y.percentage;
  7699. } else if (typeof(self.y.pixels) !== 'undefined' && self.y.pixels !== undefined) {
  7700. scrollYPercentage = self.y.percentage = (oldScrollTop + self.y.pixels) / scrollLength;
  7701. } else {
  7702. throw new Error("No percentage or pixel value provided for scroll event Y axis");
  7703. }
  7704. return Math.max(0, scrollYPercentage * scrollLength);
  7705. }
  7706. return self.newScrollTop;
  7707. };
  7708. ScrollEvent.prototype.atTop = function(scrollTop) {
  7709. return (this.y && (this.y.percentage === 0 || this.verticalScrollLength < 0) && scrollTop === 0);
  7710. };
  7711. ScrollEvent.prototype.atBottom = function(scrollTop) {
  7712. return (this.y && (this.y.percentage === 1 || this.verticalScrollLength === 0) && scrollTop > 0);
  7713. };
  7714. ScrollEvent.prototype.atLeft = function(scrollLeft) {
  7715. return (this.x && (this.x.percentage === 0 || this.horizontalScrollLength < 0) && scrollLeft === 0);
  7716. };
  7717. ScrollEvent.prototype.atRight = function(scrollLeft) {
  7718. return (this.x && (this.x.percentage === 1 || this.horizontalScrollLength === 0) && scrollLeft > 0);
  7719. };
  7720. ScrollEvent.Sources = {
  7721. ViewPortScroll: 'ViewPortScroll',
  7722. RenderContainerMouseWheel: 'RenderContainerMouseWheel',
  7723. RenderContainerTouchMove: 'RenderContainerTouchMove',
  7724. Other: 99
  7725. };
  7726. return ScrollEvent;
  7727. }]);
  7728. })();
  7729. (function() {
  7730. 'use strict';
  7731. /**
  7732. * @ngdoc object
  7733. * @name ui.grid.service:gridClassFactory
  7734. *
  7735. * @description factory to return dom specific instances of a grid
  7736. *
  7737. */
  7738. angular.module('ui.grid').service('gridClassFactory', ['gridUtil', '$q', '$compile', '$templateCache', 'uiGridConstants', 'Grid', 'GridColumn', 'GridRow',
  7739. function(gridUtil, $q, $compile, $templateCache, uiGridConstants, Grid, GridColumn, GridRow) {
  7740. var service = {
  7741. /**
  7742. * @ngdoc method
  7743. * @name createGrid
  7744. * @methodOf ui.grid.service:gridClassFactory
  7745. * @description Creates a new grid instance. Each instance will have a unique id
  7746. * @param {object} options An object map of options to pass into the created grid instance.
  7747. * @returns {Grid} grid
  7748. */
  7749. createGrid: function(options) {
  7750. options = (typeof(options) !== 'undefined') ? options : {};
  7751. options.id = gridUtil.newId();
  7752. var grid = new Grid(options);
  7753. // NOTE/TODO: rowTemplate should always be defined...
  7754. if (grid.options.rowTemplate) {
  7755. var rowTemplateFnPromise = $q.defer();
  7756. grid.getRowTemplateFn = rowTemplateFnPromise.promise;
  7757. gridUtil.getTemplate(grid.options.rowTemplate)
  7758. .then(
  7759. function(template) {
  7760. var rowTemplateFn = $compile(template);
  7761. rowTemplateFnPromise.resolve(rowTemplateFn);
  7762. },
  7763. function(res) {
  7764. // Todo handle response error here?
  7765. throw new Error("Couldn't fetch/use row template '" + grid.options.rowTemplate + "'");
  7766. });
  7767. }
  7768. grid.registerColumnBuilder(service.defaultColumnBuilder);
  7769. // Row builder for custom row templates
  7770. grid.registerRowBuilder(service.rowTemplateAssigner);
  7771. // Reset all rows to visible initially
  7772. grid.registerRowsProcessor(function allRowsVisible(rows) {
  7773. rows.forEach(function(row) {
  7774. row.evaluateRowVisibility(true);
  7775. }, 50);
  7776. return rows;
  7777. });
  7778. grid.registerColumnsProcessor(function allColumnsVisible(columns) {
  7779. columns.forEach(function(column) {
  7780. column.visible = true;
  7781. });
  7782. return columns;
  7783. }, 50);
  7784. grid.registerColumnsProcessor(function(renderableColumns) {
  7785. renderableColumns.forEach(function(column) {
  7786. if (column.colDef.visible === false) {
  7787. column.visible = false;
  7788. }
  7789. });
  7790. return renderableColumns;
  7791. }, 50);
  7792. grid.registerRowsProcessor(grid.searchRows, 100);
  7793. // Register the default row processor, it sorts rows by selected columns
  7794. if (grid.options.externalSort && angular.isFunction(grid.options.externalSort)) {
  7795. grid.registerRowsProcessor(grid.options.externalSort, 200);
  7796. } else {
  7797. grid.registerRowsProcessor(grid.sortByColumn, 200);
  7798. }
  7799. return grid;
  7800. },
  7801. /**
  7802. * @ngdoc function
  7803. * @name defaultColumnBuilder
  7804. * @methodOf ui.grid.service:gridClassFactory
  7805. * @description Processes designTime column definitions and applies them to col for the
  7806. * core grid features
  7807. * @param {object} colDef reference to column definition
  7808. * @param {GridColumn} col reference to gridCol
  7809. * @param {object} gridOptions reference to grid options
  7810. */
  7811. defaultColumnBuilder: function(colDef, col, gridOptions) {
  7812. var templateGetPromises = [];
  7813. // Abstracts the standard template processing we do for every template type.
  7814. var processTemplate = function(templateType, providedType, defaultTemplate, filterType, tooltipType) {
  7815. if (!colDef[templateType]) {
  7816. col[providedType] = defaultTemplate;
  7817. } else {
  7818. col[providedType] = colDef[templateType];
  7819. }
  7820. templateGetPromises.push(gridUtil.getTemplate(col[providedType])
  7821. .then(
  7822. function(template) {
  7823. if (angular.isFunction(template)) { template = template(); }
  7824. var tooltipCall = (tooltipType === 'cellTooltip') ? 'col.cellTooltip(row,col)' : 'col.headerTooltip(col)';
  7825. if (tooltipType && col[tooltipType] === false) {
  7826. template = template.replace(uiGridConstants.TOOLTIP, '');
  7827. } else if (tooltipType && col[tooltipType]) {
  7828. template = template.replace(uiGridConstants.TOOLTIP, 'title="{{' + tooltipCall + ' CUSTOM_FILTERS }}"');
  7829. }
  7830. if (filterType) {
  7831. col[templateType] = template.replace(uiGridConstants.CUSTOM_FILTERS, function() {
  7832. return col[filterType] ? "|" + col[filterType] : "";
  7833. });
  7834. } else {
  7835. col[templateType] = template;
  7836. }
  7837. },
  7838. function(res) {
  7839. throw new Error("Couldn't fetch/use colDef." + templateType + " '" + colDef[templateType] + "'");
  7840. })
  7841. );
  7842. };
  7843. /**
  7844. * @ngdoc property
  7845. * @name cellTemplate
  7846. * @propertyOf ui.grid.class:GridOptions.columnDef
  7847. * @description a custom template for each cell in this column. The default
  7848. * is ui-grid/uiGridCell. If you are using the cellNav feature, this template
  7849. * must contain a div that can receive focus.
  7850. *
  7851. */
  7852. processTemplate('cellTemplate', 'providedCellTemplate', 'ui-grid/uiGridCell', 'cellFilter', 'cellTooltip');
  7853. col.cellTemplatePromise = templateGetPromises[0];
  7854. /**
  7855. * @ngdoc property
  7856. * @name headerCellTemplate
  7857. * @propertyOf ui.grid.class:GridOptions.columnDef
  7858. * @description a custom template for the header for this column. The default
  7859. * is ui-grid/uiGridHeaderCell
  7860. *
  7861. */
  7862. processTemplate('headerCellTemplate', 'providedHeaderCellTemplate', 'ui-grid/uiGridHeaderCell', 'headerCellFilter', 'headerTooltip');
  7863. /**
  7864. * @ngdoc property
  7865. * @name footerCellTemplate
  7866. * @propertyOf ui.grid.class:GridOptions.columnDef
  7867. * @description a custom template for the footer for this column. The default
  7868. * is ui-grid/uiGridFooterCell
  7869. *
  7870. */
  7871. processTemplate('footerCellTemplate', 'providedFooterCellTemplate', 'ui-grid/uiGridFooterCell', 'footerCellFilter');
  7872. /**
  7873. * @ngdoc property
  7874. * @name filterHeaderTemplate
  7875. * @propertyOf ui.grid.class:GridOptions.columnDef
  7876. * @description a custom template for the filter input. The default is ui-grid/ui-grid-filter
  7877. *
  7878. */
  7879. processTemplate('filterHeaderTemplate', 'providedFilterHeaderTemplate', 'ui-grid/ui-grid-filter');
  7880. // Create a promise for the compiled element function
  7881. col.compiledElementFnDefer = $q.defer();
  7882. return $q.all(templateGetPromises);
  7883. },
  7884. rowTemplateAssigner: function rowTemplateAssigner(row) {
  7885. var grid = this;
  7886. // Row has no template assigned to it
  7887. if (!row.rowTemplate) {
  7888. // Use the default row template from the grid
  7889. row.rowTemplate = grid.options.rowTemplate;
  7890. // Use the grid's function for fetching the compiled row template function
  7891. row.getRowTemplateFn = grid.getRowTemplateFn;
  7892. }
  7893. // Row has its own template assigned
  7894. else {
  7895. // Create a promise for the compiled row template function
  7896. var perRowTemplateFnPromise = $q.defer();
  7897. row.getRowTemplateFn = perRowTemplateFnPromise.promise;
  7898. // Get the row template
  7899. gridUtil.getTemplate(row.rowTemplate)
  7900. .then(function(template) {
  7901. // Compile the template
  7902. var rowTemplateFn = $compile(template);
  7903. // Resolve the compiled template function promise
  7904. perRowTemplateFnPromise.resolve(rowTemplateFn);
  7905. },
  7906. function(res) {
  7907. // Todo handle response error here?
  7908. throw new Error("Couldn't fetch/use row template '" + row.rowTemplate + "'");
  7909. });
  7910. }
  7911. return row.getRowTemplateFn;
  7912. }
  7913. };
  7914. //class definitions (moved to separate factories)
  7915. return service;
  7916. }
  7917. ]);
  7918. })();
  7919. (function() {
  7920. var module = angular.module('ui.grid');
  7921. function escapeRegExp(str) {
  7922. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  7923. }
  7924. /**
  7925. * @ngdoc service
  7926. * @name ui.grid.service:rowSearcher
  7927. *
  7928. * @description Service for searching/filtering rows based on column value conditions.
  7929. */
  7930. module.service('rowSearcher', ['gridUtil', 'uiGridConstants', function(gridUtil, uiGridConstants) {
  7931. var defaultCondition = uiGridConstants.filter.CONTAINS;
  7932. var rowSearcher = {};
  7933. /**
  7934. * @ngdoc function
  7935. * @name getTerm
  7936. * @methodOf ui.grid.service:rowSearcher
  7937. * @description Get the term from a filter
  7938. * Trims leading and trailing whitespace
  7939. * @param {object} filter object to use
  7940. * @returns {object} Parsed term
  7941. */
  7942. rowSearcher.getTerm = function getTerm(filter) {
  7943. if (typeof(filter.term) === 'undefined') { return filter.term; }
  7944. var term = filter.term;
  7945. // Strip leading and trailing whitespace if the term is a string
  7946. if (typeof(term) === 'string') {
  7947. term = term.trim();
  7948. }
  7949. return term;
  7950. };
  7951. /**
  7952. * @ngdoc function
  7953. * @name stripTerm
  7954. * @methodOf ui.grid.service:rowSearcher
  7955. * @description Remove leading and trailing asterisk (*) from the filter's term
  7956. * @param {object} filter object to use
  7957. * @returns {uiGridConstants.filter<int>} Value representing the condition constant value
  7958. */
  7959. rowSearcher.stripTerm = function stripTerm(filter) {
  7960. var term = rowSearcher.getTerm(filter);
  7961. if (typeof(term) === 'string') {
  7962. return escapeRegExp(term.replace(/(^\*|\*$)/g, ''));
  7963. } else {
  7964. return term;
  7965. }
  7966. };
  7967. /**
  7968. * @ngdoc function
  7969. * @name guessCondition
  7970. * @methodOf ui.grid.service:rowSearcher
  7971. * @description Guess the condition for a filter based on its term
  7972. * <br>
  7973. * Defaults to STARTS_WITH. Uses CONTAINS for strings beginning and ending with *s (*bob*).
  7974. * Uses STARTS_WITH for strings ending with * (bo*). Uses ENDS_WITH for strings starting with * (*ob).
  7975. * @param {object} filter object to use
  7976. * @returns {uiGridConstants.filter<int>} Value representing the condition constant value
  7977. */
  7978. rowSearcher.guessCondition = function guessCondition(filter) {
  7979. if (typeof(filter.term) === 'undefined' || !filter.term) {
  7980. return defaultCondition;
  7981. }
  7982. var term = rowSearcher.getTerm(filter);
  7983. if (/\*/.test(term)) {
  7984. var regexpFlags = '';
  7985. if (!filter.flags || !filter.flags.caseSensitive) {
  7986. regexpFlags += 'i';
  7987. }
  7988. var reText = term.replace(/(\\)?\*/g, function($0, $1) { return $1 ? $0 : '[\\s\\S]*?'; });
  7989. return new RegExp('^' + reText + '$', regexpFlags);
  7990. }
  7991. // Otherwise default to default condition
  7992. else {
  7993. return defaultCondition;
  7994. }
  7995. };
  7996. /**
  7997. * @ngdoc function
  7998. * @name setupFilters
  7999. * @methodOf ui.grid.service:rowSearcher
  8000. * @description For a given columns filters (either col.filters, or [col.filter] can be passed in),
  8001. * do all the parsing and pre-processing and store that data into a new filters object. The object
  8002. * has the condition, the flags, the stripped term, and a parsed reg exp if there was one.
  8003. *
  8004. * We could use a forEach in here, since it's much less performance sensitive, but since we're using
  8005. * for loops everywhere else in this module...
  8006. *
  8007. * @param {array} filters the filters from the column (col.filters or [col.filter])
  8008. * @returns {array} An array of parsed/preprocessed filters
  8009. */
  8010. rowSearcher.setupFilters = function setupFilters(filters) {
  8011. var newFilters = [];
  8012. var filtersLength = filters.length;
  8013. for (var i = 0; i < filtersLength; i++) {
  8014. var filter = filters[i];
  8015. if (filter.noTerm || !gridUtil.isNullOrUndefined(filter.term)) {
  8016. var newFilter = {};
  8017. var regexpFlags = '';
  8018. if (!filter.flags || !filter.flags.caseSensitive) {
  8019. regexpFlags += 'i';
  8020. }
  8021. if (!gridUtil.isNullOrUndefined(filter.term)) {
  8022. // it is possible to have noTerm. We don't need to copy that across, it was just a flag to avoid
  8023. // getting the filter ignored if the filter was a function that didn't use a term
  8024. newFilter.term = rowSearcher.stripTerm(filter);
  8025. }
  8026. if (filter.condition) {
  8027. newFilter.condition = filter.condition;
  8028. } else {
  8029. newFilter.condition = rowSearcher.guessCondition(filter);
  8030. }
  8031. newFilter.flags = angular.extend({ caseSensitive: false, date: false }, filter.flags);
  8032. if (newFilter.condition === uiGridConstants.filter.STARTS_WITH) {
  8033. newFilter.startswithRE = new RegExp('^' + newFilter.term, regexpFlags);
  8034. }
  8035. if (newFilter.condition === uiGridConstants.filter.ENDS_WITH) {
  8036. newFilter.endswithRE = new RegExp(newFilter.term + '$', regexpFlags);
  8037. }
  8038. if (newFilter.condition === uiGridConstants.filter.CONTAINS) {
  8039. newFilter.containsRE = new RegExp(newFilter.term, regexpFlags);
  8040. }
  8041. if (newFilter.condition === uiGridConstants.filter.EXACT) {
  8042. newFilter.exactRE = new RegExp('^' + newFilter.term + '$', regexpFlags);
  8043. }
  8044. newFilters.push(newFilter);
  8045. }
  8046. }
  8047. return newFilters;
  8048. };
  8049. /**
  8050. * @ngdoc function
  8051. * @name runColumnFilter
  8052. * @methodOf ui.grid.service:rowSearcher
  8053. * @description Runs a single pre-parsed filter against a cell, returning true
  8054. * if the cell matches that one filter.
  8055. *
  8056. * @param {Grid} grid the grid we're working against
  8057. * @param {GridRow} row the row we're matching against
  8058. * @param {GridCol} column the column that we're working against
  8059. * @param {object} filter the specific, preparsed, filter that we want to test
  8060. * @returns {boolean} true if we match (row stays visible)
  8061. */
  8062. rowSearcher.runColumnFilter = function runColumnFilter(grid, row, column, filter) {
  8063. // Cache typeof condition
  8064. var conditionType = typeof(filter.condition);
  8065. // Term to search for.
  8066. var term = filter.term;
  8067. // Get the column value for this row
  8068. var value;
  8069. if (column.filterCellFiltered) {
  8070. value = grid.getCellDisplayValue(row, column);
  8071. } else {
  8072. value = grid.getCellValue(row, column);
  8073. }
  8074. // If the filter's condition is a RegExp, then use it
  8075. if (filter.condition instanceof RegExp) {
  8076. return filter.condition.test(value);
  8077. }
  8078. // If the filter's condition is a function, run it
  8079. if (conditionType === 'function') {
  8080. return filter.condition(term, value, row, column);
  8081. }
  8082. if (filter.startswithRE) {
  8083. return filter.startswithRE.test(value);
  8084. }
  8085. if (filter.endswithRE) {
  8086. return filter.endswithRE.test(value);
  8087. }
  8088. if (filter.containsRE) {
  8089. return filter.containsRE.test(value);
  8090. }
  8091. if (filter.exactRE) {
  8092. return filter.exactRE.test(value);
  8093. }
  8094. if (filter.condition === uiGridConstants.filter.NOT_EQUAL) {
  8095. var regex = new RegExp('^' + term + '$');
  8096. return !regex.exec(value);
  8097. }
  8098. if (typeof(value) === 'number' && typeof(term) === 'string') {
  8099. // if the term has a decimal in it, it comes through as '9\.4', we need to take out the \
  8100. // the same for negative numbers
  8101. // TODO: I suspect the right answer is to look at escapeRegExp at the top of this code file, maybe it's not needed?
  8102. var tempFloat = parseFloat(term.replace(/\\\./, '.').replace(/\\\-/, '-'));
  8103. if (!isNaN(tempFloat)) {
  8104. term = tempFloat;
  8105. }
  8106. }
  8107. if (filter.flags.date === true) {
  8108. value = new Date(value);
  8109. // If the term has a dash in it, it comes through as '\-' -- we need to take out the '\'.
  8110. term = new Date(term.replace(/\\/g, ''));
  8111. }
  8112. if (filter.condition === uiGridConstants.filter.GREATER_THAN) {
  8113. return (value > term);
  8114. }
  8115. if (filter.condition === uiGridConstants.filter.GREATER_THAN_OR_EQUAL) {
  8116. return (value >= term);
  8117. }
  8118. if (filter.condition === uiGridConstants.filter.LESS_THAN) {
  8119. return (value < term);
  8120. }
  8121. if (filter.condition === uiGridConstants.filter.LESS_THAN_OR_EQUAL) {
  8122. return (value <= term);
  8123. }
  8124. return true;
  8125. };
  8126. /**
  8127. * @ngdoc boolean
  8128. * @name useExternalFiltering
  8129. * @propertyOf ui.grid.class:GridOptions
  8130. * @description False by default. When enabled, this setting suppresses the internal filtering.
  8131. * All UI logic will still operate, allowing filter conditions to be set and modified.
  8132. *
  8133. * The external filter logic can listen for the `filterChange` event, which fires whenever
  8134. * a filter has been adjusted.
  8135. */
  8136. /**
  8137. * @ngdoc function
  8138. * @name searchColumn
  8139. * @methodOf ui.grid.service:rowSearcher
  8140. * @description Process provided filters on provided column against a given row. If the row meets
  8141. * the conditions on all the filters, return true.
  8142. * @param {Grid} grid Grid to search in
  8143. * @param {GridRow} row Row to search on
  8144. * @param {GridCol} column Column with the filters to use
  8145. * @param {array} filters array of pre-parsed/preprocessed filters to apply
  8146. * @returns {boolean} Whether the column matches or not.
  8147. */
  8148. rowSearcher.searchColumn = function searchColumn(grid, row, column, filters) {
  8149. if (grid.options.useExternalFiltering) {
  8150. return true;
  8151. }
  8152. var filtersLength = filters.length;
  8153. for (var i = 0; i < filtersLength; i++) {
  8154. var filter = filters[i];
  8155. var ret = rowSearcher.runColumnFilter(grid, row, column, filter);
  8156. if (!ret) {
  8157. return false;
  8158. }
  8159. }
  8160. return true;
  8161. };
  8162. /**
  8163. * @ngdoc function
  8164. * @name search
  8165. * @methodOf ui.grid.service:rowSearcher
  8166. * @description Run a search across the given rows and columns, marking any rows that don't
  8167. * match the stored col.filters or col.filter as invisible.
  8168. * @param {Grid} grid Grid instance to search inside
  8169. * @param {Array[GridRow]} rows GridRows to filter
  8170. * @param {Array[GridColumn]} columns GridColumns with filters to process
  8171. */
  8172. rowSearcher.search = function search(grid, rows, columns) {
  8173. /*
  8174. * Added performance optimisations into this code base, as this logic creates deeply nested
  8175. * loops and is therefore very performance sensitive. In particular, avoiding forEach as
  8176. * this impacts some browser optimisers (particularly Chrome), using iterators instead
  8177. */
  8178. // Don't do anything if we weren't passed any rows
  8179. if (!rows) {
  8180. return;
  8181. }
  8182. // don't filter if filtering currently disabled
  8183. if (!grid.options.enableFiltering) {
  8184. return rows;
  8185. }
  8186. // Build list of filters to apply
  8187. var filterData = [];
  8188. var colsLength = columns.length;
  8189. var hasTerm = function(filters) {
  8190. var hasTerm = false;
  8191. filters.forEach(function(filter) {
  8192. if (!gridUtil.isNullOrUndefined(filter.term) && filter.term !== '' || filter.noTerm) {
  8193. hasTerm = true;
  8194. }
  8195. });
  8196. return hasTerm;
  8197. };
  8198. for (var i = 0; i < colsLength; i++) {
  8199. var col = columns[i];
  8200. if (typeof(col.filters) !== 'undefined' && hasTerm(col.filters)) {
  8201. filterData.push({ col: col, filters: rowSearcher.setupFilters(col.filters) });
  8202. }
  8203. }
  8204. if (filterData.length > 0) {
  8205. // define functions outside the loop, performance optimisation
  8206. var foreachRow = function(grid, row, col, filters) {
  8207. if (row.visible && !rowSearcher.searchColumn(grid, row, col, filters)) {
  8208. row.visible = false;
  8209. }
  8210. };
  8211. var foreachFilterCol = function(grid, filterData) {
  8212. var rowsLength = rows.length;
  8213. for (var i = 0; i < rowsLength; i++) {
  8214. foreachRow(grid, rows[i], filterData.col, filterData.filters);
  8215. }
  8216. };
  8217. // nested loop itself - foreachFilterCol, which in turn calls foreachRow
  8218. var filterDataLength = filterData.length;
  8219. for (var j = 0; j < filterDataLength; j++) {
  8220. foreachFilterCol(grid, filterData[j]);
  8221. }
  8222. if (grid.api.core.raise.rowsVisibleChanged) {
  8223. grid.api.core.raise.rowsVisibleChanged();
  8224. }
  8225. // drop any invisible rows
  8226. // 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
  8227. // rows = rows.filter(function(row){ return row.visible; });
  8228. }
  8229. return rows;
  8230. };
  8231. return rowSearcher;
  8232. }]);
  8233. })();
  8234. (function() {
  8235. var module = angular.module('ui.grid');
  8236. /**
  8237. * @ngdoc object
  8238. * @name ui.grid.class:RowSorter
  8239. * @description RowSorter provides the default sorting mechanisms,
  8240. * including guessing column types and applying appropriate sort
  8241. * algorithms
  8242. *
  8243. */
  8244. module.service('rowSorter', ['$parse', 'uiGridConstants', function($parse, uiGridConstants) {
  8245. var currencyRegexStr =
  8246. '(' +
  8247. uiGridConstants.CURRENCY_SYMBOLS
  8248. .map(function(a) { return '\\' + a; }) // Escape all the currency symbols ($ at least will jack up this regex)
  8249. .join('|') + // Join all the symbols together with |s
  8250. ')?';
  8251. // /^[-+]?[£$¤¥]?[\d,.]+%?$/
  8252. var numberStrRegex = new RegExp('^[-+]?' + currencyRegexStr + '[\\d,.]+' + currencyRegexStr + '%?$');
  8253. var rowSorter = {
  8254. // Cache of sorting functions. Once we create them, we don't want to keep re-doing it
  8255. // this takes a piece of data from the cell and tries to determine its type and what sorting
  8256. // function to use for it
  8257. colSortFnCache: {}
  8258. };
  8259. /**
  8260. * @ngdoc method
  8261. * @methodOf ui.grid.class:RowSorter
  8262. * @name guessSortFn
  8263. * @description Assigns a sort function to use based on the itemType in the column
  8264. * @param {string} itemType one of 'number', 'boolean', 'string', 'date', 'object'. And
  8265. * error will be thrown for any other type.
  8266. * @returns {function} a sort function that will sort that type
  8267. */
  8268. rowSorter.guessSortFn = function guessSortFn(itemType) {
  8269. switch (itemType) {
  8270. case "number":
  8271. return rowSorter.sortNumber;
  8272. case "numberStr":
  8273. return rowSorter.sortNumberStr;
  8274. case "boolean":
  8275. return rowSorter.sortBool;
  8276. case "string":
  8277. return rowSorter.sortAlpha;
  8278. case "date":
  8279. return rowSorter.sortDate;
  8280. case "object":
  8281. return rowSorter.basicSort;
  8282. default:
  8283. throw new Error('No sorting function found for type:' + itemType);
  8284. }
  8285. };
  8286. /**
  8287. * @ngdoc method
  8288. * @methodOf ui.grid.class:RowSorter
  8289. * @name handleNulls
  8290. * @description Sorts nulls and undefined to the bottom (top when
  8291. * descending). Called by each of the internal sorters before
  8292. * attempting to sort. Note that this method is available on the core api
  8293. * via gridApi.core.sortHandleNulls
  8294. * @param {object} a sort value a
  8295. * @param {object} b sort value b
  8296. * @returns {number} null if there were no nulls/undefineds, otherwise returns
  8297. * a sort value that should be passed back from the sort function
  8298. */
  8299. rowSorter.handleNulls = function handleNulls(a, b) {
  8300. // We want to allow zero values and false values to be evaluated in the sort function
  8301. if ((!a && a !== 0 && a !== false) || (!b && b !== 0 && b !== false)) {
  8302. // We want to force nulls and such to the bottom when we sort... which effectively is "greater than"
  8303. if ((!a && a !== 0 && a !== false) && (!b && b !== 0 && b !== false)) {
  8304. return 0;
  8305. } else if (!a && a !== 0 && a !== false) {
  8306. return 1;
  8307. } else if (!b && b !== 0 && b !== false) {
  8308. return -1;
  8309. }
  8310. }
  8311. return null;
  8312. };
  8313. /**
  8314. * @ngdoc method
  8315. * @methodOf ui.grid.class:RowSorter
  8316. * @name basicSort
  8317. * @description Sorts any values that provide the < method, including strings
  8318. * or numbers. Handles nulls and undefined through calling handleNulls
  8319. * @param {object} a sort value a
  8320. * @param {object} b sort value b
  8321. * @returns {number} normal sort function, returns -ve, 0, +ve
  8322. */
  8323. rowSorter.basicSort = function basicSort(a, b) {
  8324. var nulls = rowSorter.handleNulls(a, b);
  8325. if (nulls !== null) {
  8326. return nulls;
  8327. } else {
  8328. if (a === b) {
  8329. return 0;
  8330. }
  8331. if (a < b) {
  8332. return -1;
  8333. }
  8334. return 1;
  8335. }
  8336. };
  8337. /**
  8338. * @ngdoc method
  8339. * @methodOf ui.grid.class:RowSorter
  8340. * @name sortNumber
  8341. * @description Sorts numerical values. Handles nulls and undefined through calling handleNulls
  8342. * @param {object} a sort value a
  8343. * @param {object} b sort value b
  8344. * @returns {number} normal sort function, returns -ve, 0, +ve
  8345. */
  8346. rowSorter.sortNumber = function sortNumber(a, b) {
  8347. var nulls = rowSorter.handleNulls(a, b);
  8348. if (nulls !== null) {
  8349. return nulls;
  8350. } else {
  8351. return a - b;
  8352. }
  8353. };
  8354. /**
  8355. * @ngdoc method
  8356. * @methodOf ui.grid.class:RowSorter
  8357. * @name sortNumberStr
  8358. * @description Sorts numerical values that are stored in a string (i.e. parses them to numbers first).
  8359. * Handles nulls and undefined through calling handleNulls
  8360. * @param {object} a sort value a
  8361. * @param {object} b sort value b
  8362. * @returns {number} normal sort function, returns -ve, 0, +ve
  8363. */
  8364. rowSorter.sortNumberStr = function sortNumberStr(a, b) {
  8365. var nulls = rowSorter.handleNulls(a, b);
  8366. if (nulls !== null) {
  8367. return nulls;
  8368. } else {
  8369. var numA, // The parsed number form of 'a'
  8370. numB, // The parsed number form of 'b'
  8371. badA = false,
  8372. badB = false;
  8373. // Try to parse 'a' to a float
  8374. numA = parseFloat(a.replace(/[^0-9.-]/g, ''));
  8375. // If 'a' couldn't be parsed to float, flag it as bad
  8376. if (isNaN(numA)) {
  8377. badA = true;
  8378. }
  8379. // Try to parse 'b' to a float
  8380. numB = parseFloat(b.replace(/[^0-9.-]/g, ''));
  8381. // If 'b' couldn't be parsed to float, flag it as bad
  8382. if (isNaN(numB)) {
  8383. badB = true;
  8384. }
  8385. // We want bad ones to get pushed to the bottom... which effectively is "greater than"
  8386. if (badA && badB) {
  8387. return 0;
  8388. }
  8389. if (badA) {
  8390. return 1;
  8391. }
  8392. if (badB) {
  8393. return -1;
  8394. }
  8395. return numA - numB;
  8396. }
  8397. };
  8398. /**
  8399. * @ngdoc method
  8400. * @methodOf ui.grid.class:RowSorter
  8401. * @name sortAlpha
  8402. * @description Sorts string values. Handles nulls and undefined through calling handleNulls
  8403. * @param {object} a sort value a
  8404. * @param {object} b sort value b
  8405. * @returns {number} normal sort function, returns -ve, 0, +ve
  8406. */
  8407. rowSorter.sortAlpha = function sortAlpha(a, b) {
  8408. var nulls = rowSorter.handleNulls(a, b);
  8409. if (nulls !== null) {
  8410. return nulls;
  8411. } else {
  8412. var strA = a.toString().toLowerCase(),
  8413. strB = b.toString().toLowerCase();
  8414. return strA === strB ? 0 : (strA < strB ? -1 : 1);
  8415. }
  8416. };
  8417. /**
  8418. * @ngdoc method
  8419. * @methodOf ui.grid.class:RowSorter
  8420. * @name sortDate
  8421. * @description Sorts date values. Handles nulls and undefined through calling handleNulls.
  8422. * Handles date strings by converting to Date object if not already an instance of Date
  8423. * @param {object} a sort value a
  8424. * @param {object} b sort value b
  8425. * @returns {number} normal sort function, returns -ve, 0, +ve
  8426. */
  8427. rowSorter.sortDate = function sortDate(a, b) {
  8428. var nulls = rowSorter.handleNulls(a, b);
  8429. if (nulls !== null) {
  8430. return nulls;
  8431. } else {
  8432. if (!(a instanceof Date)) {
  8433. a = new Date(a);
  8434. }
  8435. if (!(b instanceof Date)) {
  8436. b = new Date(b);
  8437. }
  8438. var timeA = a.getTime(),
  8439. timeB = b.getTime();
  8440. return timeA === timeB ? 0 : (timeA < timeB ? -1 : 1);
  8441. }
  8442. };
  8443. /**
  8444. * @ngdoc method
  8445. * @methodOf ui.grid.class:RowSorter
  8446. * @name sortBool
  8447. * @description Sorts boolean values, true is considered larger than false.
  8448. * Handles nulls and undefined through calling handleNulls
  8449. * @param {object} a sort value a
  8450. * @param {object} b sort value b
  8451. * @returns {number} normal sort function, returns -ve, 0, +ve
  8452. */
  8453. rowSorter.sortBool = function sortBool(a, b) {
  8454. var nulls = rowSorter.handleNulls(a, b);
  8455. if (nulls !== null) {
  8456. return nulls;
  8457. } else {
  8458. if (a && b) {
  8459. return 0;
  8460. }
  8461. if (!a && !b) {
  8462. return 0;
  8463. } else {
  8464. return a ? 1 : -1;
  8465. }
  8466. }
  8467. };
  8468. /**
  8469. * @ngdoc method
  8470. * @methodOf ui.grid.class:RowSorter
  8471. * @name getSortFn
  8472. * @description Get the sort function for the column. Looks first in
  8473. * rowSorter.colSortFnCache using the column name, failing that it
  8474. * looks at col.sortingAlgorithm (and puts it in the cache), failing that
  8475. * it guesses the sort algorithm based on the data type.
  8476. *
  8477. * The cache currently seems a bit pointless, as none of the work we do is
  8478. * processor intensive enough to need caching. Presumably in future we might
  8479. * inspect the row data itself to guess the sort function, and in that case
  8480. * it would make sense to have a cache, the infrastructure is in place to allow
  8481. * that.
  8482. *
  8483. * @param {Grid} grid the grid to consider
  8484. * @param {GridCol} col the column to find a function for
  8485. * @param {array} rows an array of grid rows. Currently unused, but presumably in future
  8486. * we might inspect the rows themselves to decide what sort of data might be there
  8487. * @returns {function} the sort function chosen for the column
  8488. */
  8489. rowSorter.getSortFn = function getSortFn(grid, col, rows) {
  8490. var sortFn, item;
  8491. // See if we already figured out what to use to sort the column and have it in the cache
  8492. if (rowSorter.colSortFnCache[col.colDef.name]) {
  8493. sortFn = rowSorter.colSortFnCache[col.colDef.name];
  8494. }
  8495. // If the column has its OWN sorting algorithm, use that
  8496. else if (col.sortingAlgorithm !== undefined) {
  8497. sortFn = col.sortingAlgorithm;
  8498. rowSorter.colSortFnCache[col.colDef.name] = col.sortingAlgorithm;
  8499. }
  8500. // Always default to sortAlpha when sorting after a cellFilter
  8501. else if (col.sortCellFiltered && col.cellFilter) {
  8502. sortFn = rowSorter.sortAlpha;
  8503. rowSorter.colSortFnCache[col.colDef.name] = sortFn;
  8504. }
  8505. // Try and guess what sort function to use
  8506. else {
  8507. // Guess the sort function
  8508. sortFn = rowSorter.guessSortFn(col.colDef.type);
  8509. // If we found a sort function, cache it
  8510. if (sortFn) {
  8511. rowSorter.colSortFnCache[col.colDef.name] = sortFn;
  8512. } else {
  8513. // We assign the alpha sort because anything that is null/undefined will never get passed to
  8514. // the actual sorting function. It will get caught in our null check and returned to be sorted
  8515. // down to the bottom
  8516. sortFn = rowSorter.sortAlpha;
  8517. }
  8518. }
  8519. return sortFn;
  8520. };
  8521. /**
  8522. * @ngdoc method
  8523. * @methodOf ui.grid.class:RowSorter
  8524. * @name prioritySort
  8525. * @description Used where multiple columns are present in the sort criteria,
  8526. * we determine which column should take precedence in the sort by sorting
  8527. * the columns based on their sort.priority
  8528. *
  8529. * @param {gridColumn} a column a
  8530. * @param {gridColumn} b column b
  8531. * @returns {number} normal sort function, returns -ve, 0, +ve
  8532. */
  8533. rowSorter.prioritySort = function(a, b) {
  8534. // Both columns have a sort priority
  8535. if (a.sort.priority !== undefined && b.sort.priority !== undefined) {
  8536. // A is higher priority
  8537. if (a.sort.priority < b.sort.priority) {
  8538. return -1;
  8539. }
  8540. // Equal
  8541. else if (a.sort.priority === b.sort.priority) {
  8542. return 0;
  8543. }
  8544. // B is higher
  8545. else {
  8546. return 1;
  8547. }
  8548. }
  8549. // Only A has a priority
  8550. else if (a.sort.priority || a.sort.priority === 0) {
  8551. return -1;
  8552. }
  8553. // Only B has a priority
  8554. else if (b.sort.priority || b.sort.priority === 0) {
  8555. return 1;
  8556. }
  8557. // Neither has a priority
  8558. else {
  8559. return 0;
  8560. }
  8561. };
  8562. /**
  8563. * @ngdoc object
  8564. * @name useExternalSorting
  8565. * @propertyOf ui.grid.class:GridOptions
  8566. * @description Prevents the internal sorting from executing. Events will
  8567. * still be fired when the sort changes, and the sort information on
  8568. * the columns will be updated, allowing an external sorter (for example,
  8569. * server sorting) to be implemented. Defaults to false.
  8570. *
  8571. */
  8572. /**
  8573. * @ngdoc method
  8574. * @methodOf ui.grid.class:RowSorter
  8575. * @name sort
  8576. * @description sorts the grid
  8577. * @param {Object} grid the grid itself
  8578. * @param {array} rows the rows to be sorted
  8579. * @param {array} columns the columns in which to look
  8580. * for sort criteria
  8581. * @returns {array} sorted rows
  8582. */
  8583. rowSorter.sort = function rowSorterSort(grid, rows, columns) {
  8584. // first make sure we are even supposed to do work
  8585. if (!rows) {
  8586. return;
  8587. }
  8588. if (grid.options.useExternalSorting) {
  8589. return rows;
  8590. }
  8591. // Build the list of columns to sort by
  8592. var sortCols = [];
  8593. columns.forEach(function(col) {
  8594. if (col.sort && !col.sort.ignoreSort && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) {
  8595. sortCols.push(col);
  8596. }
  8597. });
  8598. // Sort the "sort columns" by their sort priority
  8599. sortCols = sortCols.sort(rowSorter.prioritySort);
  8600. // Now rows to sort by, maintain original order
  8601. if (sortCols.length === 0) {
  8602. return rows;
  8603. }
  8604. // Re-usable variables
  8605. var col, direction;
  8606. // put a custom index field on each row, used to make a stable sort out of unstable sorts (e.g. Chrome)
  8607. var setIndex = function(row, idx) {
  8608. row.entity.$$uiGridIndex = idx;
  8609. };
  8610. rows.forEach(setIndex);
  8611. // IE9-11 HACK.... the 'rows' variable would be empty where we call rowSorter.getSortFn(...) below. We have to use a separate reference
  8612. // var d = data.slice(0);
  8613. var r = rows.slice(0);
  8614. // Now actually sort the data
  8615. var rowSortFn = function(rowA, rowB) {
  8616. var tem = 0,
  8617. idx = 0,
  8618. sortFn;
  8619. while (tem === 0 && idx < sortCols.length) {
  8620. // grab the metadata for the rest of the logic
  8621. col = sortCols[idx];
  8622. direction = sortCols[idx].sort.direction;
  8623. sortFn = rowSorter.getSortFn(grid, col, r);
  8624. var propA, propB;
  8625. if (col.sortCellFiltered) {
  8626. propA = grid.getCellDisplayValue(rowA, col);
  8627. propB = grid.getCellDisplayValue(rowB, col);
  8628. } else {
  8629. propA = grid.getCellValue(rowA, col);
  8630. propB = grid.getCellValue(rowB, col);
  8631. }
  8632. tem = sortFn(propA, propB);
  8633. idx++;
  8634. }
  8635. // Chrome doesn't implement a stable sort function. If our sort returns 0
  8636. // (i.e. the items are equal), and we're at the last sort column in the list,
  8637. // then return the previous order using our custom
  8638. // index variable
  8639. if (tem === 0) {
  8640. return rowA.entity.$$uiGridIndex - rowB.entity.$$uiGridIndex;
  8641. }
  8642. // Made it this far, we don't have to worry about null & undefined
  8643. if (direction === uiGridConstants.ASC) {
  8644. return tem;
  8645. } else {
  8646. return 0 - tem;
  8647. }
  8648. };
  8649. var newRows = rows.sort(rowSortFn);
  8650. // remove the custom index field on each row, used to make a stable sort out of unstable sorts (e.g. Chrome)
  8651. var clearIndex = function(row, idx) {
  8652. delete row.entity.$$uiGridIndex;
  8653. };
  8654. rows.forEach(clearIndex);
  8655. return newRows;
  8656. };
  8657. return rowSorter;
  8658. }]);
  8659. })();
  8660. (function() {
  8661. var module = angular.module('ui.grid');
  8662. var bindPolyfill;
  8663. if (typeof Function.prototype.bind !== "function") {
  8664. bindPolyfill = function() {
  8665. var slice = Array.prototype.slice;
  8666. return function(context) {
  8667. var fn = this,
  8668. args = slice.call(arguments, 1);
  8669. if (args.length) {
  8670. return function() {
  8671. return arguments.length ? fn.apply(context, args.concat(slice.call(arguments))) : fn.apply(context, args);
  8672. };
  8673. }
  8674. return function() {
  8675. return arguments.length ? fn.apply(context, arguments) : fn.call(context);
  8676. };
  8677. };
  8678. };
  8679. }
  8680. function getStyles(elem) {
  8681. var e = elem;
  8682. if (typeof(e.length) !== 'undefined' && e.length) {
  8683. e = elem[0];
  8684. }
  8685. return e.ownerDocument.defaultView.getComputedStyle(e, null);
  8686. }
  8687. var rnumnonpx = new RegExp("^(" + (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source + ")(?!px)[a-z%]+$", "i"),
  8688. // swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
  8689. // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
  8690. rdisplayswap = /^(block|none|table(?!-c[ea]).+)/,
  8691. cssShow = { position: "absolute", visibility: "hidden", display: "block" };
  8692. function augmentWidthOrHeight(elem, name, extra, isBorderBox, styles) {
  8693. var i = extra === (isBorderBox ? 'border' : 'content') ?
  8694. // If we already have the right measurement, avoid augmentation
  8695. 4 :
  8696. // Otherwise initialize for horizontal or vertical properties
  8697. name === 'width' ? 1 : 0,
  8698. val = 0;
  8699. var sides = ['Top', 'Right', 'Bottom', 'Left'];
  8700. for (; i < 4; i += 2) {
  8701. var side = sides[i];
  8702. // dump('side', side);
  8703. // both box models exclude margin, so add it if we want it
  8704. if (extra === 'margin') {
  8705. var marg = parseFloat(styles[extra + side]);
  8706. if (!isNaN(marg)) {
  8707. val += marg;
  8708. }
  8709. }
  8710. // dump('val1', val);
  8711. if (isBorderBox) {
  8712. // border-box includes padding, so remove it if we want content
  8713. if (extra === 'content') {
  8714. var padd = parseFloat(styles['padding' + side]);
  8715. if (!isNaN(padd)) {
  8716. val -= padd;
  8717. // dump('val2', val);
  8718. }
  8719. }
  8720. // at this point, extra isn't border nor margin, so remove border
  8721. if (extra !== 'margin') {
  8722. var bordermarg = parseFloat(styles['border' + side + 'Width']);
  8723. if (!isNaN(bordermarg)) {
  8724. val -= bordermarg;
  8725. // dump('val3', val);
  8726. }
  8727. }
  8728. } else {
  8729. // at this point, extra isn't content, so add padding
  8730. var nocontentPad = parseFloat(styles['padding' + side]);
  8731. if (!isNaN(nocontentPad)) {
  8732. val += nocontentPad;
  8733. // dump('val4', val);
  8734. }
  8735. // at this point, extra isn't content nor padding, so add border
  8736. if (extra !== 'padding') {
  8737. var nocontentnopad = parseFloat(styles['border' + side + 'Width']);
  8738. if (!isNaN(nocontentnopad)) {
  8739. val += nocontentnopad;
  8740. // dump('val5', val);
  8741. }
  8742. }
  8743. }
  8744. }
  8745. // dump('augVal', val);
  8746. return val;
  8747. }
  8748. function getWidthOrHeight(elem, name, extra) {
  8749. // Start with offset property, which is equivalent to the border-box value
  8750. var valueIsBorderBox = true,
  8751. val, // = name === 'width' ? elem.offsetWidth : elem.offsetHeight,
  8752. styles = getStyles(elem),
  8753. isBorderBox = styles['boxSizing'] === 'border-box';
  8754. // some non-html elements return undefined for offsetWidth, so check for null/undefined
  8755. // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
  8756. // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
  8757. if (val <= 0 || val == null) {
  8758. // Fall back to computed then uncomputed css if necessary
  8759. val = styles[name];
  8760. if (val < 0 || val == null) {
  8761. val = elem.style[name];
  8762. }
  8763. // Computed unit is not pixels. Stop here and return.
  8764. if (rnumnonpx.test(val)) {
  8765. return val;
  8766. }
  8767. // we need the check for style in case a browser which returns unreliable values
  8768. // for getComputedStyle silently falls back to the reliable elem.style
  8769. valueIsBorderBox = isBorderBox &&
  8770. (true || val === elem.style[name]); // use 'true' instead of 'support.boxSizingReliable()'
  8771. // Normalize "", auto, and prepare for extra
  8772. val = parseFloat(val) || 0;
  8773. }
  8774. // use the active box-sizing model to add/subtract irrelevant styles
  8775. var ret = (val +
  8776. augmentWidthOrHeight(
  8777. elem,
  8778. name,
  8779. extra || (isBorderBox ? "border" : "content"),
  8780. valueIsBorderBox,
  8781. styles
  8782. )
  8783. );
  8784. // dump('ret', ret, val);
  8785. return ret;
  8786. }
  8787. function getLineHeight(elm) {
  8788. elm = angular.element(elm)[0];
  8789. var parent = elm.parentElement;
  8790. if (!parent) {
  8791. parent = document.getElementsByTagName('body')[0];
  8792. }
  8793. return parseInt(getStyles(parent).fontSize) || parseInt(getStyles(elm).fontSize) || 16;
  8794. }
  8795. var uid = ['0', '0', '0', '0'];
  8796. var uidPrefix = 'uiGrid-';
  8797. /**
  8798. * @ngdoc service
  8799. * @name ui.grid.service:GridUtil
  8800. *
  8801. * @description Grid utility functions
  8802. */
  8803. module.service('gridUtil', ['$log', '$window', '$document', '$http', '$templateCache', '$timeout', '$interval', '$injector', '$q', '$interpolate', 'uiGridConstants',
  8804. function($log, $window, $document, $http, $templateCache, $timeout, $interval, $injector, $q, $interpolate, uiGridConstants) {
  8805. var s = {
  8806. augmentWidthOrHeight: augmentWidthOrHeight,
  8807. getStyles: getStyles,
  8808. /**
  8809. * @ngdoc method
  8810. * @name createBoundedWrapper
  8811. * @methodOf ui.grid.service:GridUtil
  8812. *
  8813. * @param {object} Object to bind 'this' to
  8814. * @param {method} Method to bind
  8815. * @returns {Function} The wrapper that performs the binding
  8816. *
  8817. * @description
  8818. * Binds given method to given object.
  8819. *
  8820. * By means of a wrapper, ensures that ``method`` is always bound to
  8821. * ``object`` regardless of its calling environment.
  8822. * Iow, inside ``method``, ``this`` always points to ``object``.
  8823. *
  8824. * See http://alistapart.com/article/getoutbindingsituations
  8825. *
  8826. */
  8827. createBoundedWrapper: function(object, method) {
  8828. return function() {
  8829. return method.apply(object, arguments);
  8830. };
  8831. },
  8832. /**
  8833. * @ngdoc method
  8834. * @name readableColumnName
  8835. * @methodOf ui.grid.service:GridUtil
  8836. *
  8837. * @param {string} columnName Column name as a string
  8838. * @returns {string} Column name appropriately capitalized and split apart
  8839. *
  8840. @example
  8841. <example module="app">
  8842. <file name="app.js">
  8843. var app = angular.module('app', ['ui.grid']);
  8844. app.controller('MainCtrl', ['$scope', 'gridUtil', function ($scope, gridUtil) {
  8845. $scope.name = 'firstName';
  8846. $scope.columnName = function(name) {
  8847. return gridUtil.readableColumnName(name);
  8848. };
  8849. }]);
  8850. </file>
  8851. <file name="index.html">
  8852. <div ng-controller="MainCtrl">
  8853. <strong>Column name:</strong> <input ng-model="name" />
  8854. <br>
  8855. <strong>Output:</strong> <span ng-bind="columnName(name)"></span>
  8856. </div>
  8857. </file>
  8858. </example>
  8859. */
  8860. readableColumnName: function(columnName) {
  8861. // Convert underscores to spaces
  8862. if (typeof(columnName) === 'undefined' || columnName === undefined || columnName === null) { return columnName; }
  8863. if (typeof(columnName) !== 'string') {
  8864. columnName = String(columnName);
  8865. }
  8866. return columnName.replace(/_+/g, ' ')
  8867. // Replace a completely all-capsed word with a first-letter-capitalized version
  8868. .replace(/^[A-Z]+$/, function(match) {
  8869. return angular.lowercase(angular.uppercase(match.charAt(0)) + match.slice(1));
  8870. })
  8871. // Capitalize the first letter of words
  8872. .replace(/([\w\u00C0-\u017F]+)/g, function(match) {
  8873. return angular.uppercase(match.charAt(0)) + match.slice(1);
  8874. })
  8875. // Put a space in between words that have partial capilizations (i.e. 'firstName' becomes 'First Name')
  8876. // .replace(/([A-Z]|[A-Z]\w+)([A-Z])/g, "$1 $2");
  8877. // .replace(/(\w+?|\w)([A-Z])/g, "$1 $2");
  8878. .replace(/(\w+?(?=[A-Z]))/g, '$1 ');
  8879. },
  8880. /**
  8881. * @ngdoc method
  8882. * @name getColumnsFromData
  8883. * @methodOf ui.grid.service:GridUtil
  8884. * @description Return a list of column names, given a data set
  8885. *
  8886. * @param {string} data Data array for grid
  8887. * @returns {Object} Column definitions with field accessor and column name
  8888. *
  8889. * @example
  8890. <pre>
  8891. var data = [
  8892. { firstName: 'Bob', lastName: 'Jones' },
  8893. { firstName: 'Frank', lastName: 'Smith' }
  8894. ];
  8895. var columnDefs = GridUtil.getColumnsFromData(data, excludeProperties);
  8896. columnDefs == [
  8897. {
  8898. field: 'firstName',
  8899. name: 'First Name'
  8900. },
  8901. {
  8902. field: 'lastName',
  8903. name: 'Last Name'
  8904. }
  8905. ];
  8906. </pre>
  8907. */
  8908. getColumnsFromData: function(data, excludeProperties) {
  8909. var columnDefs = [];
  8910. if (!data || typeof(data[0]) === 'undefined' || data[0] === undefined) { return []; }
  8911. if (angular.isUndefined(excludeProperties)) { excludeProperties = []; }
  8912. var item = data[0];
  8913. angular.forEach(item, function(prop, propName) {
  8914. if (excludeProperties.indexOf(propName) === -1) {
  8915. columnDefs.push({
  8916. name: propName
  8917. });
  8918. }
  8919. });
  8920. return columnDefs;
  8921. },
  8922. /**
  8923. * @ngdoc method
  8924. * @name newId
  8925. * @methodOf ui.grid.service:GridUtil
  8926. * @description Return a unique ID string
  8927. *
  8928. * @returns {string} Unique string
  8929. *
  8930. * @example
  8931. <pre>
  8932. var id = GridUtil.newId();
  8933. # 1387305700482;
  8934. </pre>
  8935. */
  8936. newId: (function() {
  8937. var seedId = new Date().getTime();
  8938. return function() {
  8939. return seedId += 1;
  8940. };
  8941. })(),
  8942. /**
  8943. * @ngdoc method
  8944. * @name getTemplate
  8945. * @methodOf ui.grid.service:GridUtil
  8946. * @description Get's template from cache / element / url
  8947. *
  8948. * @param {string|element|promise} Either a string representing the template id, a string representing the template url,
  8949. * an jQuery/Angualr element, or a promise that returns the template contents to use.
  8950. * @returns {object} a promise resolving to template contents
  8951. *
  8952. * @example
  8953. <pre>
  8954. GridUtil.getTemplate(url).then(function (contents) {
  8955. alert(contents);
  8956. })
  8957. </pre>
  8958. */
  8959. getTemplate: function(template) {
  8960. // Try to fetch the template out of the templateCache
  8961. if ($templateCache.get(template)) {
  8962. return s.postProcessTemplate($templateCache.get(template));
  8963. }
  8964. // See if the template is itself a promise
  8965. if (template.hasOwnProperty('then')) {
  8966. return template.then(s.postProcessTemplate);
  8967. }
  8968. // If the template is an element, return the element
  8969. try {
  8970. if (angular.element(template).length > 0) {
  8971. return $q.when(template).then(s.postProcessTemplate);
  8972. }
  8973. } catch (err) {
  8974. //do nothing; not valid html
  8975. }
  8976. s.logDebug('fetching url', template);
  8977. // Default to trying to fetch the template as a url with $http
  8978. return $http({ method: 'GET', url: template })
  8979. .then(
  8980. function(result) {
  8981. var templateHtml = result.data.trim();
  8982. //put in templateCache for next call
  8983. $templateCache.put(template, templateHtml);
  8984. return templateHtml;
  8985. },
  8986. function(err) {
  8987. throw new Error("Could not get template " + template + ": " + err);
  8988. }
  8989. )
  8990. .then(s.postProcessTemplate);
  8991. },
  8992. //
  8993. postProcessTemplate: function(template) {
  8994. var startSym = $interpolate.startSymbol(),
  8995. endSym = $interpolate.endSymbol();
  8996. // If either of the interpolation symbols have been changed, we need to alter this template
  8997. if (startSym !== '{{' || endSym !== '}}') {
  8998. template = template.replace(/\{\{/g, startSym);
  8999. template = template.replace(/\}\}/g, endSym);
  9000. }
  9001. return $q.when(template);
  9002. },
  9003. /**
  9004. * @ngdoc method
  9005. * @name guessType
  9006. * @methodOf ui.grid.service:GridUtil
  9007. * @description guesses the type of an argument
  9008. *
  9009. * @param {string/number/bool/object} item variable to examine
  9010. * @returns {string} one of the following
  9011. * - 'string'
  9012. * - 'boolean'
  9013. * - 'number'
  9014. * - 'date'
  9015. * - 'object'
  9016. */
  9017. guessType: function(item) {
  9018. var itemType = typeof(item);
  9019. // Check for numbers and booleans
  9020. switch (itemType) {
  9021. case "number":
  9022. case "boolean":
  9023. case "string":
  9024. return itemType;
  9025. default:
  9026. if (angular.isDate(item)) {
  9027. return "date";
  9028. }
  9029. return "object";
  9030. }
  9031. },
  9032. /**
  9033. * @ngdoc method
  9034. * @name elementWidth
  9035. * @methodOf ui.grid.service:GridUtil
  9036. *
  9037. * @param {element} element DOM element
  9038. * @param {string} [extra] Optional modifier for calculation. Use 'margin' to account for margins on element
  9039. *
  9040. * @returns {number} Element width in pixels, accounting for any borders, etc.
  9041. */
  9042. elementWidth: function(elem) {
  9043. },
  9044. /**
  9045. * @ngdoc method
  9046. * @name elementHeight
  9047. * @methodOf ui.grid.service:GridUtil
  9048. *
  9049. * @param {element} element DOM element
  9050. * @param {string} [extra] Optional modifier for calculation. Use 'margin' to account for margins on element
  9051. *
  9052. * @returns {number} Element height in pixels, accounting for any borders, etc.
  9053. */
  9054. elementHeight: function(elem) {
  9055. },
  9056. // Thanks to http://stackoverflow.com/a/13382873/888165
  9057. getScrollbarWidth: function() {
  9058. var outer = document.createElement("div");
  9059. outer.style.visibility = "hidden";
  9060. outer.style.width = "100px";
  9061. outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
  9062. document.body.appendChild(outer);
  9063. var widthNoScroll = outer.offsetWidth;
  9064. // force scrollbars
  9065. outer.style.overflow = "scroll";
  9066. // add innerdiv
  9067. var inner = document.createElement("div");
  9068. inner.style.width = "100%";
  9069. outer.appendChild(inner);
  9070. var widthWithScroll = inner.offsetWidth;
  9071. // remove divs
  9072. outer.parentNode.removeChild(outer);
  9073. return widthNoScroll - widthWithScroll;
  9074. },
  9075. swap: function(elem, options, callback, args) {
  9076. var ret, name,
  9077. old = {};
  9078. // Remember the old values, and insert the new ones
  9079. for (name in options) {
  9080. old[name] = elem.style[name];
  9081. elem.style[name] = options[name];
  9082. }
  9083. ret = callback.apply(elem, args || []);
  9084. // Revert the old values
  9085. for (name in options) {
  9086. elem.style[name] = old[name];
  9087. }
  9088. return ret;
  9089. },
  9090. fakeElement: function(elem, options, callback, args) {
  9091. var ret, name,
  9092. newElement = angular.element(elem).clone()[0];
  9093. for (name in options) {
  9094. newElement.style[name] = options[name];
  9095. }
  9096. angular.element(document.body).append(newElement);
  9097. ret = callback.call(newElement, newElement);
  9098. angular.element(newElement).remove();
  9099. return ret;
  9100. },
  9101. /**
  9102. * @ngdoc method
  9103. * @name normalizeWheelEvent
  9104. * @methodOf ui.grid.service:GridUtil
  9105. *
  9106. * @param {event} event A mouse wheel event
  9107. *
  9108. * @returns {event} A normalized event
  9109. *
  9110. * @description
  9111. * Given an event from this list:
  9112. *
  9113. * `wheel, mousewheel, DomMouseScroll, MozMousePixelScroll`
  9114. *
  9115. * "normalize" it
  9116. * so that it stays consistent no matter what browser it comes from (i.e. scale it correctly and make sure the direction is right.)
  9117. */
  9118. normalizeWheelEvent: function(event) {
  9119. // var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
  9120. // var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
  9121. var lowestDelta, lowestDeltaXY;
  9122. var orgEvent = event || window.event,
  9123. args = [].slice.call(arguments, 1),
  9124. delta = 0,
  9125. deltaX = 0,
  9126. deltaY = 0,
  9127. absDelta = 0,
  9128. absDeltaXY = 0,
  9129. fn;
  9130. // event = $.event.fix(orgEvent);
  9131. // event.type = 'mousewheel';
  9132. // NOTE: jQuery masks the event and stores it in the event as originalEvent
  9133. if (orgEvent.originalEvent) {
  9134. orgEvent = orgEvent.originalEvent;
  9135. }
  9136. // Old school scrollwheel delta
  9137. if (orgEvent.wheelDelta) { delta = orgEvent.wheelDelta; }
  9138. if (orgEvent.detail) { delta = orgEvent.detail * -1; }
  9139. // At a minimum, setup the deltaY to be delta
  9140. deltaY = delta;
  9141. // Firefox < 17 related to DOMMouseScroll event
  9142. if (orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) {
  9143. deltaY = 0;
  9144. deltaX = delta * -1;
  9145. }
  9146. // New school wheel delta (wheel event)
  9147. if (orgEvent.deltaY) {
  9148. deltaY = orgEvent.deltaY * -1;
  9149. delta = deltaY;
  9150. }
  9151. if (orgEvent.deltaX) {
  9152. deltaX = orgEvent.deltaX;
  9153. delta = deltaX * -1;
  9154. }
  9155. // Webkit
  9156. if (orgEvent.wheelDeltaY !== undefined) { deltaY = orgEvent.wheelDeltaY; }
  9157. if (orgEvent.wheelDeltaX !== undefined) { deltaX = orgEvent.wheelDeltaX; }
  9158. // Look for lowest delta to normalize the delta values
  9159. absDelta = Math.abs(delta);
  9160. if (!lowestDelta || absDelta < lowestDelta) { lowestDelta = absDelta; }
  9161. absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
  9162. if (!lowestDeltaXY || absDeltaXY < lowestDeltaXY) { lowestDeltaXY = absDeltaXY; }
  9163. // Get a whole value for the deltas
  9164. fn = delta > 0 ? 'floor' : 'ceil';
  9165. delta = Math[fn](delta / lowestDelta);
  9166. deltaX = Math[fn](deltaX / lowestDeltaXY);
  9167. deltaY = Math[fn](deltaY / lowestDeltaXY);
  9168. return {
  9169. delta: delta,
  9170. deltaX: deltaX,
  9171. deltaY: deltaY
  9172. };
  9173. },
  9174. // Stolen from Modernizr
  9175. // TODO: make this, and everythign that flows from it, robust
  9176. //http://www.stucox.com/blog/you-cant-detect-a-touchscreen/
  9177. isTouchEnabled: function() {
  9178. var bool;
  9179. if (('ontouchstart' in $window) || $window.DocumentTouch && $document instanceof DocumentTouch) {
  9180. bool = true;
  9181. }
  9182. return bool;
  9183. },
  9184. isNullOrUndefined: function(obj) {
  9185. if (obj === undefined || obj === null) {
  9186. return true;
  9187. }
  9188. return false;
  9189. },
  9190. endsWith: function(str, suffix) {
  9191. if (!str || !suffix || typeof str !== "string") {
  9192. return false;
  9193. }
  9194. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  9195. },
  9196. arrayContainsObjectWithProperty: function(array, propertyName, propertyValue) {
  9197. var found = false;
  9198. angular.forEach(array, function(object) {
  9199. if (object[propertyName] === propertyValue) {
  9200. found = true;
  9201. }
  9202. });
  9203. return found;
  9204. },
  9205. //// Shim requestAnimationFrame
  9206. //requestAnimationFrame: $window.requestAnimationFrame && $window.requestAnimationFrame.bind($window) ||
  9207. // $window.webkitRequestAnimationFrame && $window.webkitRequestAnimationFrame.bind($window) ||
  9208. // function(fn) {
  9209. // return $timeout(fn, 10, false);
  9210. // },
  9211. numericAndNullSort: function(a, b) {
  9212. if (a === null) { return 1; }
  9213. if (b === null) { return -1; }
  9214. if (a === null && b === null) { return 0; }
  9215. return a - b;
  9216. },
  9217. // Disable ngAnimate animations on an element
  9218. disableAnimations: function(element) {
  9219. var $animate;
  9220. try {
  9221. $animate = $injector.get('$animate');
  9222. // See: http://brianhann.com/angular-1-4-breaking-changes-to-be-aware-of/#animate
  9223. if (angular.version.major > 1 || (angular.version.major === 1 && angular.version.minor >= 4)) {
  9224. $animate.enabled(element, false);
  9225. } else {
  9226. $animate.enabled(false, element);
  9227. }
  9228. } catch (e) {}
  9229. },
  9230. enableAnimations: function(element) {
  9231. var $animate;
  9232. try {
  9233. $animate = $injector.get('$animate');
  9234. // See: http://brianhann.com/angular-1-4-breaking-changes-to-be-aware-of/#animate
  9235. if (angular.version.major > 1 || (angular.version.major === 1 && angular.version.minor >= 4)) {
  9236. $animate.enabled(element, true);
  9237. } else {
  9238. $animate.enabled(true, element);
  9239. }
  9240. return $animate;
  9241. } catch (e) {}
  9242. },
  9243. // Blatantly stolen from Angular as it isn't exposed (yet. 2.0 maybe?)
  9244. nextUid: function nextUid() {
  9245. var index = uid.length;
  9246. var digit;
  9247. while (index) {
  9248. index--;
  9249. digit = uid[index].charCodeAt(0);
  9250. if (digit === 57 /*'9'*/ ) {
  9251. uid[index] = 'A';
  9252. return uidPrefix + uid.join('');
  9253. }
  9254. if (digit === 90 /*'Z'*/ ) {
  9255. uid[index] = '0';
  9256. } else {
  9257. uid[index] = String.fromCharCode(digit + 1);
  9258. return uidPrefix + uid.join('');
  9259. }
  9260. }
  9261. uid.unshift('0');
  9262. return uidPrefix + uid.join('');
  9263. },
  9264. // Blatantly stolen from Angular as it isn't exposed (yet. 2.0 maybe?)
  9265. hashKey: function hashKey(obj) {
  9266. var objType = typeof obj,
  9267. key;
  9268. if (objType === 'object' && obj !== null) {
  9269. if (typeof(key = obj.$$hashKey) === 'function') {
  9270. // must invoke on object to keep the right this
  9271. key = obj.$$hashKey();
  9272. } else if (typeof(obj.$$hashKey) !== 'undefined' && obj.$$hashKey) {
  9273. key = obj.$$hashKey;
  9274. } else if (key === undefined) {
  9275. key = obj.$$hashKey = s.nextUid();
  9276. }
  9277. } else {
  9278. key = obj;
  9279. }
  9280. return objType + ':' + key;
  9281. },
  9282. resetUids: function() {
  9283. uid = ['0', '0', '0'];
  9284. },
  9285. /**
  9286. * @ngdoc method
  9287. * @methodOf ui.grid.service:GridUtil
  9288. * @name logError
  9289. * @description wraps the $log method, allowing us to choose different
  9290. * treatment within ui-grid if we so desired. At present we only log
  9291. * error messages if uiGridConstants.LOG_ERROR_MESSAGES is set to true
  9292. * @param {string} logMessage message to be logged to the console
  9293. *
  9294. */
  9295. logError: function(logMessage) {
  9296. if (uiGridConstants.LOG_ERROR_MESSAGES) {
  9297. $log.error(logMessage);
  9298. }
  9299. },
  9300. /**
  9301. * @ngdoc method
  9302. * @methodOf ui.grid.service:GridUtil
  9303. * @name logWarn
  9304. * @description wraps the $log method, allowing us to choose different
  9305. * treatment within ui-grid if we so desired. At present we only log
  9306. * warning messages if uiGridConstants.LOG_WARN_MESSAGES is set to true
  9307. * @param {string} logMessage message to be logged to the console
  9308. *
  9309. */
  9310. logWarn: function(logMessage) {
  9311. if (uiGridConstants.LOG_WARN_MESSAGES) {
  9312. $log.warn(logMessage);
  9313. }
  9314. },
  9315. /**
  9316. * @ngdoc method
  9317. * @methodOf ui.grid.service:GridUtil
  9318. * @name logDebug
  9319. * @description wraps the $log method, allowing us to choose different
  9320. * treatment within ui-grid if we so desired. At present we only log
  9321. * debug messages if uiGridConstants.LOG_DEBUG_MESSAGES is set to true
  9322. *
  9323. */
  9324. logDebug: function() {
  9325. if (uiGridConstants.LOG_DEBUG_MESSAGES) {
  9326. $log.debug.apply($log, arguments);
  9327. }
  9328. }
  9329. };
  9330. /**
  9331. * @ngdoc object
  9332. * @name focus
  9333. * @propertyOf ui.grid.service:GridUtil
  9334. * @description Provies a set of methods to set the document focus inside the grid.
  9335. * See {@link ui.grid.service:GridUtil.focus} for more information.
  9336. */
  9337. /**
  9338. * @ngdoc object
  9339. * @name ui.grid.service:GridUtil.focus
  9340. * @description Provies a set of methods to set the document focus inside the grid.
  9341. * Timeouts are utilized to ensure that the focus is invoked after any other event has been triggered.
  9342. * e.g. click events that need to run before the focus or
  9343. * inputs elements that are in a disabled state but are enabled when those events
  9344. * are triggered.
  9345. */
  9346. s.focus = {
  9347. queue: [],
  9348. //http://stackoverflow.com/questions/25596399/set-element-focus-in-angular-way
  9349. /**
  9350. * @ngdoc method
  9351. * @methodOf ui.grid.service:GridUtil.focus
  9352. * @name byId
  9353. * @description Sets the focus of the document to the given id value.
  9354. * If provided with the grid object it will automatically append the grid id.
  9355. * This is done to encourage unique dom id's as it allows for multiple grids on a
  9356. * page.
  9357. * @param {String} id the id of the dom element to set the focus on
  9358. * @param {Object=} Grid the grid object for this grid instance. See: {@link ui.grid.class:Grid}
  9359. * @param {Number} Grid.id the unique id for this grid. Already set on an initialized grid object.
  9360. * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated.
  9361. * then the promise will fail with the `'canceled'` reason.
  9362. */
  9363. byId: function(id, Grid) {
  9364. this._purgeQueue();
  9365. var promise = $timeout(function() {
  9366. var elementID = (Grid && Grid.id ? Grid.id + '-' : '') + id;
  9367. var element = $window.document.getElementById(elementID);
  9368. if (element) {
  9369. element.focus();
  9370. } else {
  9371. s.logWarn('[focus.byId] Element id ' + elementID + ' was not found.');
  9372. }
  9373. });
  9374. this.queue.push(promise);
  9375. return promise;
  9376. },
  9377. /**
  9378. * @ngdoc method
  9379. * @methodOf ui.grid.service:GridUtil.focus
  9380. * @name byElement
  9381. * @description Sets the focus of the document to the given dom element.
  9382. * @param {(element|angular.element)} element the DOM element to set the focus on
  9383. * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated.
  9384. * then the promise will fail with the `'canceled'` reason.
  9385. */
  9386. byElement: function(element) {
  9387. if (!angular.isElement(element)) {
  9388. s.logWarn("Trying to focus on an element that isn\'t an element.");
  9389. return $q.reject('not-element');
  9390. }
  9391. element = angular.element(element);
  9392. this._purgeQueue();
  9393. var promise = $timeout(function() {
  9394. if (element) {
  9395. element[0].focus();
  9396. }
  9397. });
  9398. this.queue.push(promise);
  9399. return promise;
  9400. },
  9401. /**
  9402. * @ngdoc method
  9403. * @methodOf ui.grid.service:GridUtil.focus
  9404. * @name bySelector
  9405. * @description Sets the focus of the document to the given dom element.
  9406. * @param {(element|angular.element)} parentElement the parent/ancestor of the dom element that you are selecting using the query selector
  9407. * @param {String} querySelector finds the dom element using the {@link http://www.w3schools.com/jsref/met_document_queryselector.asp querySelector}
  9408. * @param {boolean} [aSync=false] If true then the selector will be querried inside of a timeout. Otherwise the selector will be querried imidately
  9409. * then the focus will be called.
  9410. * @returns {Promise} The `$timeout` promise that will be resolved once focus is set. If another focus is requested before this request is evaluated.
  9411. * then the promise will fail with the `'canceled'` reason.
  9412. */
  9413. bySelector: function(parentElement, querySelector, aSync) {
  9414. var self = this;
  9415. if (!angular.isElement(parentElement)) {
  9416. throw new Error("The parent element is not an element.");
  9417. }
  9418. // Ensure that this is an angular element.
  9419. // It is fine if this is already an angular element.
  9420. parentElement = angular.element(parentElement);
  9421. var focusBySelector = function() {
  9422. var element = parentElement[0].querySelector(querySelector);
  9423. return self.byElement(element);
  9424. };
  9425. this._purgeQueue();
  9426. if (aSync) { //Do this asynchronysly
  9427. var promise = $timeout(focusBySelector);
  9428. this.queue.push($timeout(focusBySelector));
  9429. return promise;
  9430. } else {
  9431. return focusBySelector();
  9432. }
  9433. },
  9434. _purgeQueue: function() {
  9435. this.queue.forEach(function(element) {
  9436. $timeout.cancel(element);
  9437. });
  9438. this.queue = [];
  9439. }
  9440. };
  9441. ['width', 'height'].forEach(function(name) {
  9442. var capsName = angular.uppercase(name.charAt(0)) + name.substr(1);
  9443. s['element' + capsName] = function(elem, extra) {
  9444. var e = elem;
  9445. if (e && typeof(e.length) !== 'undefined' && e.length) {
  9446. e = elem[0];
  9447. }
  9448. if (e) {
  9449. var styles = getStyles(e);
  9450. return e.offsetWidth === 0 && rdisplayswap.test(styles.display) ?
  9451. s.swap(e, cssShow, function() {
  9452. return getWidthOrHeight(e, name, extra);
  9453. }) :
  9454. getWidthOrHeight(e, name, extra);
  9455. } else {
  9456. return null;
  9457. }
  9458. };
  9459. s['outerElement' + capsName] = function(elem, margin) {
  9460. return elem ? s['element' + capsName].call(this, elem, margin ? 'margin' : 'border') : null;
  9461. };
  9462. });
  9463. // http://stackoverflow.com/a/24107550/888165
  9464. s.closestElm = function closestElm(el, selector) {
  9465. if (typeof(el.length) !== 'undefined' && el.length) {
  9466. el = el[0];
  9467. }
  9468. var matchesFn;
  9469. // find vendor prefix
  9470. ['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'].some(function(fn) {
  9471. if (typeof document.body[fn] === 'function') {
  9472. matchesFn = fn;
  9473. return true;
  9474. }
  9475. return false;
  9476. });
  9477. // traverse parents
  9478. var parent;
  9479. while (el !== null) {
  9480. parent = el.parentElement;
  9481. if (parent !== null && parent[matchesFn](selector)) {
  9482. return parent;
  9483. }
  9484. el = parent;
  9485. }
  9486. return null;
  9487. };
  9488. s.type = function(obj) {
  9489. var text = Function.prototype.toString.call(obj.constructor);
  9490. return text.match(/function (.*?)\(/)[1];
  9491. };
  9492. s.getBorderSize = function getBorderSize(elem, borderType) {
  9493. if (typeof(elem.length) !== 'undefined' && elem.length) {
  9494. elem = elem[0];
  9495. }
  9496. var styles = getStyles(elem);
  9497. // If a specific border is supplied, like 'top', read the 'borderTop' style property
  9498. if (borderType) {
  9499. borderType = 'border' + borderType.charAt(0).toUpperCase() + borderType.slice(1);
  9500. } else {
  9501. borderType = 'border';
  9502. }
  9503. borderType += 'Width';
  9504. var val = parseInt(styles[borderType], 10);
  9505. if (isNaN(val)) {
  9506. return 0;
  9507. } else {
  9508. return val;
  9509. }
  9510. };
  9511. // http://stackoverflow.com/a/22948274/888165
  9512. // TODO: Opera? Mobile?
  9513. s.detectBrowser = function detectBrowser() {
  9514. var userAgent = $window.navigator.userAgent;
  9515. var browsers = { chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer|trident\//i };
  9516. for (var key in browsers) {
  9517. if (browsers[key].test(userAgent)) {
  9518. return key;
  9519. }
  9520. }
  9521. return 'unknown';
  9522. };
  9523. // Borrowed from https://github.com/othree/jquery.rtl-scroll-type
  9524. // Determine the scroll "type" this browser is using for RTL
  9525. s.rtlScrollType = function rtlScrollType() {
  9526. if (rtlScrollType.type) {
  9527. return rtlScrollType.type;
  9528. }
  9529. var definer = angular.element('<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>')[0],
  9530. type = 'reverse';
  9531. document.body.appendChild(definer);
  9532. if (definer.scrollLeft > 0) {
  9533. type = 'default';
  9534. } else {
  9535. definer.scrollLeft = 1;
  9536. if (definer.scrollLeft === 0) {
  9537. type = 'negative';
  9538. }
  9539. }
  9540. angular.element(definer).remove();
  9541. rtlScrollType.type = type;
  9542. return type;
  9543. };
  9544. /**
  9545. * @ngdoc method
  9546. * @name normalizeScrollLeft
  9547. * @methodOf ui.grid.service:GridUtil
  9548. *
  9549. * @param {element} element The element to get the `scrollLeft` from.
  9550. * @param {grid} grid - grid used to normalize (uses the rtl property)
  9551. *
  9552. * @returns {number} A normalized scrollLeft value for the current browser.
  9553. *
  9554. * @description
  9555. * Browsers currently handle RTL in different ways, resulting in inconsistent scrollLeft values. This method normalizes them
  9556. */
  9557. s.normalizeScrollLeft = function normalizeScrollLeft(element, grid) {
  9558. if (typeof(element.length) !== 'undefined' && element.length) {
  9559. element = element[0];
  9560. }
  9561. var scrollLeft = element.scrollLeft;
  9562. if (grid.isRTL()) {
  9563. switch (s.rtlScrollType()) {
  9564. case 'default':
  9565. return element.scrollWidth - scrollLeft - element.clientWidth;
  9566. case 'negative':
  9567. return Math.abs(scrollLeft);
  9568. case 'reverse':
  9569. return scrollLeft;
  9570. }
  9571. }
  9572. return scrollLeft;
  9573. };
  9574. /**
  9575. * @ngdoc method
  9576. * @name denormalizeScrollLeft
  9577. * @methodOf ui.grid.service:GridUtil
  9578. *
  9579. * @param {element} element The element to normalize the `scrollLeft` value for
  9580. * @param {number} scrollLeft The `scrollLeft` value to denormalize.
  9581. * @param {grid} grid The grid that owns the scroll event.
  9582. *
  9583. * @returns {number} A normalized scrollLeft value for the current browser.
  9584. *
  9585. * @description
  9586. * Browsers currently handle RTL in different ways, resulting in inconsistent scrollLeft values. This method denormalizes a value for the current browser.
  9587. */
  9588. s.denormalizeScrollLeft = function denormalizeScrollLeft(element, scrollLeft, grid) {
  9589. if (typeof(element.length) !== 'undefined' && element.length) {
  9590. element = element[0];
  9591. }
  9592. if (grid.isRTL()) {
  9593. switch (s.rtlScrollType()) {
  9594. case 'default':
  9595. // Get the max scroll for the element
  9596. var maxScrollLeft = element.scrollWidth - element.clientWidth;
  9597. // Subtract the current scroll amount from the max scroll
  9598. return maxScrollLeft - scrollLeft;
  9599. case 'negative':
  9600. return scrollLeft * -1;
  9601. case 'reverse':
  9602. return scrollLeft;
  9603. }
  9604. }
  9605. return scrollLeft;
  9606. };
  9607. /**
  9608. * @ngdoc method
  9609. * @name preEval
  9610. * @methodOf ui.grid.service:GridUtil
  9611. *
  9612. * @param {string} path Path to evaluate
  9613. *
  9614. * @returns {string} A path that is normalized.
  9615. *
  9616. * @description
  9617. * Takes a field path and converts it to bracket notation to allow for special characters in path
  9618. * @example
  9619. * <pre>
  9620. * gridUtil.preEval('property') == 'property'
  9621. * gridUtil.preEval('nested.deep.prop-erty') = "nested['deep']['prop-erty']"
  9622. * </pre>
  9623. */
  9624. s.preEval = function(path) {
  9625. var m = uiGridConstants.BRACKET_REGEXP.exec(path);
  9626. if (m) {
  9627. return (m[1] ? s.preEval(m[1]) : m[1]) + m[2] + (m[3] ? s.preEval(m[3]) : m[3]);
  9628. } else {
  9629. path = path.replace(uiGridConstants.APOS_REGEXP, '\\\'');
  9630. var parts = path.split(uiGridConstants.DOT_REGEXP);
  9631. var preparsed = [parts.shift()]; // first item must be var notation, thus skip
  9632. angular.forEach(parts, function(part) {
  9633. preparsed.push(part.replace(uiGridConstants.FUNC_REGEXP, '\']$1'));
  9634. });
  9635. return preparsed.join('[\'');
  9636. }
  9637. };
  9638. /**
  9639. * @ngdoc method
  9640. * @name debounce
  9641. * @methodOf ui.grid.service:GridUtil
  9642. *
  9643. * @param {function} func function to debounce
  9644. * @param {number} wait milliseconds to delay
  9645. * @param {boolean} immediate execute before delay
  9646. *
  9647. * @returns {function} A function that can be executed as debounced function
  9648. *
  9649. * @description
  9650. * Copied from https://github.com/shahata/angular-debounce
  9651. * Takes a function, decorates it to execute only 1 time after multiple calls, and returns the decorated function
  9652. * @example
  9653. * <pre>
  9654. * var debouncedFunc = gridUtil.debounce(function(){alert('debounced');}, 500);
  9655. * debouncedFunc();
  9656. * debouncedFunc();
  9657. * debouncedFunc();
  9658. * </pre>
  9659. */
  9660. s.debounce = function(func, wait, immediate) {
  9661. var timeout, args, context, result;
  9662. function debounce() {
  9663. /* jshint validthis:true */
  9664. context = this;
  9665. args = arguments;
  9666. var later = function() {
  9667. timeout = null;
  9668. if (!immediate) {
  9669. result = func.apply(context, args);
  9670. }
  9671. };
  9672. var callNow = immediate && !timeout;
  9673. if (timeout) {
  9674. $timeout.cancel(timeout);
  9675. }
  9676. timeout = $timeout(later, wait);
  9677. if (callNow) {
  9678. result = func.apply(context, args);
  9679. }
  9680. return result;
  9681. }
  9682. debounce.cancel = function() {
  9683. $timeout.cancel(timeout);
  9684. timeout = null;
  9685. };
  9686. return debounce;
  9687. };
  9688. /**
  9689. * @ngdoc method
  9690. * @name throttle
  9691. * @methodOf ui.grid.service:GridUtil
  9692. *
  9693. * @param {function} func function to throttle
  9694. * @param {number} wait milliseconds to delay after first trigger
  9695. * @param {Object} params to use in throttle.
  9696. *
  9697. * @returns {function} A function that can be executed as throttled function
  9698. *
  9699. * @description
  9700. * Adapted from debounce function (above)
  9701. * Potential keys for Params Object are:
  9702. * trailing (bool) - whether to trigger after throttle time ends if called multiple times
  9703. * Updated to use $interval rather than $timeout, as protractor (e2e tests) is able to work with $interval,
  9704. * but not with $timeout
  9705. *
  9706. * Note that when using throttle, you need to use throttle to create a new function upfront, then use the function
  9707. * return from that call each time you need to call throttle. If you call throttle itself repeatedly, the lastCall
  9708. * variable will get overwritten and the throttling won't work
  9709. *
  9710. * @example
  9711. * <pre>
  9712. * var throttledFunc = gridUtil.throttle(function(){console.log('throttled');}, 500, {trailing: true});
  9713. * throttledFunc(); //=> logs throttled
  9714. * throttledFunc(); //=> queues attempt to log throttled for ~500ms (since trailing param is truthy)
  9715. * throttledFunc(); //=> updates arguments to keep most-recent request, but does not do anything else.
  9716. * </pre>
  9717. */
  9718. s.throttle = function(func, wait, options) {
  9719. options = options || {};
  9720. var lastCall = 0,
  9721. queued = null,
  9722. context, args;
  9723. function runFunc(endDate) {
  9724. lastCall = +new Date();
  9725. func.apply(context, args);
  9726. $interval(function() { queued = null; }, 0, 1);
  9727. }
  9728. return function() {
  9729. /* jshint validthis:true */
  9730. context = this;
  9731. args = arguments;
  9732. if (queued === null) {
  9733. var sinceLast = +new Date() - lastCall;
  9734. if (sinceLast > wait) {
  9735. runFunc();
  9736. } else if (options.trailing) {
  9737. queued = $interval(runFunc, wait - sinceLast, 1);
  9738. }
  9739. }
  9740. };
  9741. };
  9742. s.on = {};
  9743. s.off = {};
  9744. s._events = {};
  9745. s.addOff = function(eventName) {
  9746. s.off[eventName] = function(elm, fn) {
  9747. var idx = s._events[eventName].indexOf(fn);
  9748. if (idx > 0) {
  9749. s._events[eventName].removeAt(idx);
  9750. }
  9751. };
  9752. };
  9753. var mouseWheeltoBind = ('onwheel' in document || document.documentMode >= 9) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
  9754. nullLowestDeltaTimeout,
  9755. lowestDelta;
  9756. s.on.mousewheel = function(elm, fn) {
  9757. if (!elm || !fn) { return; }
  9758. var $elm = angular.element(elm);
  9759. // Store the line height and page height for this particular element
  9760. $elm.data('mousewheel-line-height', getLineHeight($elm));
  9761. $elm.data('mousewheel-page-height', s.elementHeight($elm));
  9762. if (!$elm.data('mousewheel-callbacks')) { $elm.data('mousewheel-callbacks', {}); }
  9763. var cbs = $elm.data('mousewheel-callbacks');
  9764. cbs[fn] = (Function.prototype.bind || bindPolyfill).call(mousewheelHandler, $elm[0], fn);
  9765. // Bind all the mousew heel events
  9766. for (var i = mouseWheeltoBind.length; i;) {
  9767. $elm.on(mouseWheeltoBind[--i], cbs[fn]);
  9768. }
  9769. };
  9770. s.off.mousewheel = function(elm, fn) {
  9771. var $elm = angular.element(elm);
  9772. var cbs = $elm.data('mousewheel-callbacks');
  9773. var handler = cbs[fn];
  9774. if (handler) {
  9775. for (var i = mouseWheeltoBind.length; i;) {
  9776. $elm.off(mouseWheeltoBind[--i], handler);
  9777. }
  9778. }
  9779. delete cbs[fn];
  9780. if (Object.keys(cbs).length === 0) {
  9781. $elm.removeData('mousewheel-line-height');
  9782. $elm.removeData('mousewheel-page-height');
  9783. $elm.removeData('mousewheel-callbacks');
  9784. }
  9785. };
  9786. function mousewheelHandler(fn, event) {
  9787. var $elm = angular.element(this);
  9788. var delta = 0,
  9789. deltaX = 0,
  9790. deltaY = 0,
  9791. absDelta = 0,
  9792. offsetX = 0,
  9793. offsetY = 0;
  9794. // jQuery masks events
  9795. if (event.originalEvent) { event = event.originalEvent; }
  9796. if ('detail' in event) { deltaY = event.detail * -1; }
  9797. if ('wheelDelta' in event) { deltaY = event.wheelDelta; }
  9798. if ('wheelDeltaY' in event) { deltaY = event.wheelDeltaY; }
  9799. if ('wheelDeltaX' in event) { deltaX = event.wheelDeltaX * -1; }
  9800. // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
  9801. if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
  9802. deltaX = deltaY * -1;
  9803. deltaY = 0;
  9804. }
  9805. // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
  9806. delta = deltaY === 0 ? deltaX : deltaY;
  9807. // New school wheel delta (wheel event)
  9808. if ('deltaY' in event) {
  9809. deltaY = event.deltaY * -1;
  9810. delta = deltaY;
  9811. }
  9812. if ('deltaX' in event) {
  9813. deltaX = event.deltaX;
  9814. if (deltaY === 0) { delta = deltaX * -1; }
  9815. }
  9816. // No change actually happened, no reason to go any further
  9817. if (deltaY === 0 && deltaX === 0) { return; }
  9818. // Need to convert lines and pages to pixels if we aren't already in pixels
  9819. // There are three delta modes:
  9820. // * deltaMode 0 is by pixels, nothing to do
  9821. // * deltaMode 1 is by lines
  9822. // * deltaMode 2 is by pages
  9823. if (event.deltaMode === 1) {
  9824. var lineHeight = $elm.data('mousewheel-line-height');
  9825. delta *= lineHeight;
  9826. deltaY *= lineHeight;
  9827. deltaX *= lineHeight;
  9828. } else if (event.deltaMode === 2) {
  9829. var pageHeight = $elm.data('mousewheel-page-height');
  9830. delta *= pageHeight;
  9831. deltaY *= pageHeight;
  9832. deltaX *= pageHeight;
  9833. }
  9834. // Store lowest absolute delta to normalize the delta values
  9835. absDelta = Math.max(Math.abs(deltaY), Math.abs(deltaX));
  9836. if (!lowestDelta || absDelta < lowestDelta) {
  9837. lowestDelta = absDelta;
  9838. // Adjust older deltas if necessary
  9839. if (shouldAdjustOldDeltas(event, absDelta)) {
  9840. lowestDelta /= 40;
  9841. }
  9842. }
  9843. // Get a whole, normalized value for the deltas
  9844. delta = Math[delta >= 1 ? 'floor' : 'ceil'](delta / lowestDelta);
  9845. deltaX = Math[deltaX >= 1 ? 'floor' : 'ceil'](deltaX / lowestDelta);
  9846. deltaY = Math[deltaY >= 1 ? 'floor' : 'ceil'](deltaY / lowestDelta);
  9847. event.deltaMode = 0;
  9848. // Normalise offsetX and offsetY properties
  9849. // if ($elm[0].getBoundingClientRect ) {
  9850. // var boundingRect = $(elm)[0].getBoundingClientRect();
  9851. // offsetX = event.clientX - boundingRect.left;
  9852. // offsetY = event.clientY - boundingRect.top;
  9853. // }
  9854. // event.deltaX = deltaX;
  9855. // event.deltaY = deltaY;
  9856. // event.deltaFactor = lowestDelta;
  9857. var newEvent = {
  9858. originalEvent: event,
  9859. deltaX: deltaX,
  9860. deltaY: deltaY,
  9861. deltaFactor: lowestDelta,
  9862. preventDefault: function() { event.preventDefault(); },
  9863. stopPropagation: function() { event.stopPropagation(); }
  9864. };
  9865. // Clearout lowestDelta after sometime to better
  9866. // handle multiple device types that give
  9867. // a different lowestDelta
  9868. // Ex: trackpad = 3 and mouse wheel = 120
  9869. if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
  9870. nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);
  9871. fn.call($elm[0], newEvent);
  9872. }
  9873. function nullLowestDelta() {
  9874. lowestDelta = null;
  9875. }
  9876. function shouldAdjustOldDeltas(orgEvent, absDelta) {
  9877. // If this is an older event and the delta is divisable by 120,
  9878. // then we are assuming that the browser is treating this as an
  9879. // older mouse wheel event and that we should divide the deltas
  9880. // by 40 to try and get a more usable deltaFactor.
  9881. // Side note, this actually impacts the reported scroll distance
  9882. // in older browsers and can cause scrolling to be slower than native.
  9883. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
  9884. return orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
  9885. }
  9886. return s;
  9887. }
  9888. ]);
  9889. // Add 'px' to the end of a number string if it doesn't have it already
  9890. module.filter('px', function() {
  9891. return function(str) {
  9892. if (str.match(/^[\d\.]+$/)) {
  9893. return str + 'px';
  9894. } else {
  9895. return str;
  9896. }
  9897. };
  9898. });
  9899. })();
  9900. (function() {
  9901. angular.module('ui.grid').config(['$provide', function($provide) {
  9902. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  9903. var lang = {
  9904. aggregate: {
  9905. label: 'položky'
  9906. },
  9907. groupPanel: {
  9908. description: 'Přesuntě záhlaví zde pro vytvoření skupiny dle sloupce.'
  9909. },
  9910. search: {
  9911. placeholder: 'Hledat...',
  9912. showingItems: 'Zobrazuji položky:',
  9913. selectedItems: 'Vybrané položky:',
  9914. totalItems: 'Celkem položek:',
  9915. size: 'Velikost strany:',
  9916. first: 'První strana',
  9917. next: 'Další strana',
  9918. previous: 'Předchozí strana',
  9919. last: 'Poslední strana'
  9920. },
  9921. menu: {
  9922. text: 'Vyberte sloupec:'
  9923. },
  9924. sort: {
  9925. ascending: 'Seřadit od A-Z',
  9926. descending: 'Seřadit od Z-A',
  9927. remove: 'Odebrat seřazení'
  9928. },
  9929. column: {
  9930. hide: 'Schovat sloupec'
  9931. },
  9932. aggregation: {
  9933. count: 'celkem řádků: ',
  9934. sum: 'celkem: ',
  9935. avg: 'avg: ',
  9936. min: 'min.: ',
  9937. max: 'max.: '
  9938. },
  9939. pinning: {
  9940. pinLeft: 'Zamknout v levo',
  9941. pinRight: 'Zamknout v pravo',
  9942. unpin: 'Odemknout'
  9943. },
  9944. gridMenu: {
  9945. columns: 'Sloupce:',
  9946. importerTitle: 'Importovat soubor',
  9947. exporterAllAsCsv: 'Exportovat všechny data do csv',
  9948. exporterVisibleAsCsv: 'Exportovat viditelné data do csv',
  9949. exporterSelectedAsCsv: 'Exportovat vybranné data do csv',
  9950. exporterAllAsPdf: 'Exportovat všechny data do pdf',
  9951. exporterVisibleAsPdf: 'Exportovat viditelné data do pdf',
  9952. exporterSelectedAsPdf: 'Exportovat vybranné data do pdf',
  9953. clearAllFilters: 'Vyčistěte všechny filtry'
  9954. },
  9955. importer: {
  9956. noHeaders: 'Názvy sloupců se nepodařilo získat, obsahuje soubor záhlaví?',
  9957. noObjects: 'Data se nepodařilo zpracovat, obsahuje soubor řádky mimo záhlaví?',
  9958. invalidCsv: 'Soubor nelze zpracovat, jedná se CSV?',
  9959. invalidJson: 'Soubor nelze zpracovat, je to JSON?',
  9960. jsonNotArray: 'Soubor musí obsahovat json. Ukončuji..'
  9961. },
  9962. pagination: {
  9963. sizes: 'položek na stránku',
  9964. totalItems: 'položek'
  9965. },
  9966. grouping: {
  9967. group: 'Seskupit',
  9968. ungroup: 'Odebrat seskupení',
  9969. aggregate_count: 'Agregace: Count',
  9970. aggregate_sum: 'Agregace: Sum',
  9971. aggregate_max: 'Agregace: Max',
  9972. aggregate_min: 'Agregace: Min',
  9973. aggregate_avg: 'Agregace: Avg',
  9974. aggregate_remove: 'Agregace: Odebrat'
  9975. }
  9976. };
  9977. // support varianty of different czech keys.
  9978. $delegate.add('cs', lang);
  9979. $delegate.add('cz', lang);
  9980. $delegate.add('cs-cz', lang);
  9981. $delegate.add('cs-CZ', lang);
  9982. return $delegate;
  9983. }]);
  9984. }]);
  9985. })();
  9986. (function() {
  9987. angular.module('ui.grid').config(['$provide', function($provide) {
  9988. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  9989. $delegate.add('da', {
  9990. aggregate: {
  9991. label: 'artikler'
  9992. },
  9993. groupPanel: {
  9994. description: 'Grupér rækker udfra en kolonne ved at trække dens overskift hertil.'
  9995. },
  9996. search: {
  9997. placeholder: 'Søg...',
  9998. showingItems: 'Viste rækker:',
  9999. selectedItems: 'Valgte rækker:',
  10000. totalItems: 'Rækker totalt:',
  10001. size: 'Side størrelse:',
  10002. first: 'Første side',
  10003. next: 'Næste side',
  10004. previous: 'Forrige side',
  10005. last: 'Sidste side'
  10006. },
  10007. menu: {
  10008. text: 'Vælg kolonner:'
  10009. },
  10010. column: {
  10011. hide: 'Skjul kolonne'
  10012. },
  10013. aggregation: {
  10014. count: 'samlede rækker: ',
  10015. sum: 'smalede: ',
  10016. avg: 'gns: ',
  10017. min: 'min: ',
  10018. max: 'max: '
  10019. },
  10020. gridMenu: {
  10021. columns: 'Columns:',
  10022. importerTitle: 'Import file',
  10023. exporterAllAsCsv: 'Export all data as csv',
  10024. exporterVisibleAsCsv: 'Export visible data as csv',
  10025. exporterSelectedAsCsv: 'Export selected data as csv',
  10026. exporterAllAsPdf: 'Export all data as pdf',
  10027. exporterVisibleAsPdf: 'Export visible data as pdf',
  10028. exporterSelectedAsPdf: 'Export selected data as pdf',
  10029. clearAllFilters: 'Clear all filters'
  10030. },
  10031. importer: {
  10032. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  10033. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  10034. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  10035. invalidJson: 'File was unable to be processed, is it valid Json?',
  10036. jsonNotArray: 'Imported json file must contain an array, aborting.'
  10037. }
  10038. });
  10039. return $delegate;
  10040. }]);
  10041. }]);
  10042. })();
  10043. (function() {
  10044. angular.module('ui.grid').config(['$provide', function($provide) {
  10045. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10046. $delegate.add('de', {
  10047. aggregate: {
  10048. label: 'Eintrag'
  10049. },
  10050. groupPanel: {
  10051. description: 'Ziehen Sie eine Spaltenüberschrift hierhin, um nach dieser Spalte zu gruppieren.'
  10052. },
  10053. search: {
  10054. placeholder: 'Suche...',
  10055. showingItems: 'Zeige Einträge:',
  10056. selectedItems: 'Ausgewählte Einträge:',
  10057. totalItems: 'Einträge gesamt:',
  10058. size: 'Einträge pro Seite:',
  10059. first: 'Erste Seite',
  10060. next: 'Nächste Seite',
  10061. previous: 'Vorherige Seite',
  10062. last: 'Letzte Seite'
  10063. },
  10064. menu: {
  10065. text: 'Spalten auswählen:'
  10066. },
  10067. sort: {
  10068. ascending: 'aufsteigend sortieren',
  10069. descending: 'absteigend sortieren',
  10070. remove: 'Sortierung zurücksetzen'
  10071. },
  10072. column: {
  10073. hide: 'Spalte ausblenden'
  10074. },
  10075. aggregation: {
  10076. count: 'Zeilen insgesamt: ',
  10077. sum: 'gesamt: ',
  10078. avg: 'Durchschnitt: ',
  10079. min: 'min: ',
  10080. max: 'max: '
  10081. },
  10082. pinning: {
  10083. pinLeft: 'Links anheften',
  10084. pinRight: 'Rechts anheften',
  10085. unpin: 'Lösen'
  10086. },
  10087. gridMenu: {
  10088. columns: 'Spalten:',
  10089. importerTitle: 'Datei importieren',
  10090. exporterAllAsCsv: 'Alle Daten als CSV exportieren',
  10091. exporterVisibleAsCsv: 'sichtbare Daten als CSV exportieren',
  10092. exporterSelectedAsCsv: 'markierte Daten als CSV exportieren',
  10093. exporterAllAsPdf: 'Alle Daten als PDF exportieren',
  10094. exporterVisibleAsPdf: 'sichtbare Daten als PDF exportieren',
  10095. exporterSelectedAsPdf: 'markierte Daten als CSV exportieren',
  10096. clearAllFilters: 'Alle filter reinigen'
  10097. },
  10098. importer: {
  10099. noHeaders: 'Es konnten keine Spaltennamen ermittelt werden. Sind in der Datei Spaltendefinitionen enthalten?',
  10100. noObjects: 'Es konnten keine Zeileninformationen gelesen werden, Sind in der Datei außer den Spaltendefinitionen auch Daten enthalten?',
  10101. invalidCsv: 'Die Datei konnte nicht eingelesen werden, ist es eine gültige CSV-Datei?',
  10102. invalidJson: 'Die Datei konnte nicht eingelesen werden. Enthält sie gültiges JSON?',
  10103. jsonNotArray: 'Die importierte JSON-Datei muß ein Array enthalten. Breche Import ab.'
  10104. },
  10105. pagination: {
  10106. sizes: 'Einträge pro Seite',
  10107. totalItems: 'Einträge'
  10108. },
  10109. grouping: {
  10110. group: 'Gruppieren',
  10111. ungroup: 'Gruppierung aufheben',
  10112. aggregate_count: 'Agg: Anzahl',
  10113. aggregate_sum: 'Agg: Summe',
  10114. aggregate_max: 'Agg: Maximum',
  10115. aggregate_min: 'Agg: Minimum',
  10116. aggregate_avg: 'Agg: Mittelwert',
  10117. aggregate_remove: 'Aggregation entfernen'
  10118. }
  10119. });
  10120. return $delegate;
  10121. }]);
  10122. }]);
  10123. })();
  10124. (function() {
  10125. angular.module('ui.grid').config(['$provide', function($provide) {
  10126. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10127. // $delegate.add('zh-cn', {
  10128. // headerCell: {
  10129. // aria: {
  10130. // defaultFilterLabel: '过滤列',
  10131. // removeFilter: '重置过滤项',
  10132. // columnMenuButtonLabel: '列菜单'
  10133. // },
  10134. // priority: '优先:',
  10135. // filterLabel: "过滤: "
  10136. // },
  10137. // aggregate: {
  10138. // label: '项'
  10139. // },
  10140. // groupPanel: {
  10141. // description: '拖动表头按表头分组.'
  10142. // },
  10143. // search: {
  10144. // placeholder: '查询...',
  10145. // showingItems: '显示项:',
  10146. // selectedItems: '选择了:',
  10147. // totalItems: '总共查询记录数:',
  10148. // size: '总页数:',
  10149. // first: '第一页',
  10150. // next: '下一页',
  10151. // previous: '前一页',
  10152. // last: '最后一页'
  10153. // },
  10154. // menu: {
  10155. // text: '选择列:'
  10156. // },
  10157. // sort: {
  10158. // ascending: '顺序排序',
  10159. // descending: '逆序排序',
  10160. // none: '不排序',
  10161. // remove: '去除排序'
  10162. // },
  10163. // column: {
  10164. // hide: '隐藏列'
  10165. // },
  10166. // aggregation: {
  10167. // count: '总行数: ',
  10168. // sum: '合计: ',
  10169. // avg: '平均: ',
  10170. // min: '最小: ',
  10171. // max: '最大: '
  10172. // },
  10173. // pinning: {
  10174. // pinLeft: 'Pin Left',
  10175. // pinRight: 'Pin Right',
  10176. // unpin: 'Unpin'
  10177. // },
  10178. // columnMenu: {
  10179. // close: 'Close'
  10180. // },
  10181. // gridMenu: {
  10182. // aria: {
  10183. // buttonLabel: 'Grid Menu'
  10184. // },
  10185. // columns: 'Columns:',
  10186. // importerTitle: 'Import file',
  10187. // exporterAllAsCsv: 'Export all data as csv',
  10188. // exporterVisibleAsCsv: 'Export visible data as csv',
  10189. // exporterSelectedAsCsv: 'Export selected data as csv',
  10190. // exporterAllAsPdf: 'Export all data as pdf',
  10191. // exporterVisibleAsPdf: 'Export visible data as pdf',
  10192. // exporterSelectedAsPdf: 'Export selected data as pdf',
  10193. // clearAllFilters: 'Clear all filters'
  10194. // },
  10195. // importer: {
  10196. // noHeaders: 'Column names were unable to be derived, does the file have a header?',
  10197. // noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  10198. // invalidCsv: 'File was unable to be processed, is it valid CSV?',
  10199. // invalidJson: 'File was unable to be processed, is it valid Json?',
  10200. // jsonNotArray: 'Imported json file must contain an array, aborting.'
  10201. // },
  10202. // pagination: {
  10203. // aria: {
  10204. // pageToFirst: 'Page to first',
  10205. // pageBack: 'Page back',
  10206. // pageSelected: 'Selected page',
  10207. // pageForward: 'Page forward',
  10208. // pageToLast: 'Page to last'
  10209. // },
  10210. // sizes: '行每页',
  10211. // totalItems: '条',
  10212. // through: 'through',
  10213. // of: 'of'
  10214. // },
  10215. // grouping: {
  10216. // group: 'Group',
  10217. // ungroup: 'Ungroup',
  10218. // aggregate_count: 'Agg: Count',
  10219. // aggregate_sum: 'Agg: Sum',
  10220. // aggregate_max: 'Agg: Max',
  10221. // aggregate_min: 'Agg: Min',
  10222. // aggregate_avg: 'Agg: Avg',
  10223. // aggregate_remove: 'Agg: Remove'
  10224. // }
  10225. // });
  10226. $delegate.add('en', {
  10227. headerCell: {
  10228. aria: {
  10229. defaultFilterLabel: 'Filter for column',
  10230. removeFilter: 'Remove Filter',
  10231. columnMenuButtonLabel: 'Column Menu'
  10232. },
  10233. priority: 'Priority:',
  10234. filterLabel: "Filter for column: "
  10235. },
  10236. aggregate: {
  10237. label: 'items'
  10238. },
  10239. groupPanel: {
  10240. description: 'Drag a column header here and drop it to group by that column.'
  10241. },
  10242. search: {
  10243. placeholder: 'Search...',
  10244. showingItems: 'Showing Items:',
  10245. selectedItems: 'Selected Items:',
  10246. totalItems: 'Total Items:',
  10247. size: 'Page Size:',
  10248. first: 'First Page',
  10249. next: 'Next Page',
  10250. previous: 'Previous Page',
  10251. last: 'Last Page'
  10252. },
  10253. menu: {
  10254. text: 'Choose Columns:'
  10255. },
  10256. sort: {
  10257. ascending: 'Sort Ascending',
  10258. descending: 'Sort Descending',
  10259. none: 'Sort None',
  10260. remove: 'Remove Sort'
  10261. },
  10262. column: {
  10263. hide: 'Hide Column'
  10264. },
  10265. aggregation: {
  10266. count: 'total rows: ',
  10267. sum: 'total: ',
  10268. avg: 'avg: ',
  10269. min: 'min: ',
  10270. max: 'max: '
  10271. },
  10272. pinning: {
  10273. pinLeft: 'Pin Left',
  10274. pinRight: 'Pin Right',
  10275. unpin: 'Unpin'
  10276. },
  10277. columnMenu: {
  10278. close: 'Close'
  10279. },
  10280. gridMenu: {
  10281. aria: {
  10282. buttonLabel: 'Grid Menu'
  10283. },
  10284. columns: 'Columns:',
  10285. importerTitle: 'Import file',
  10286. exporterAllAsCsv: 'Export all data as csv',
  10287. exporterVisibleAsCsv: 'Export visible data as csv',
  10288. exporterSelectedAsCsv: 'Export selected data as csv',
  10289. exporterAllAsPdf: 'Export all data as pdf',
  10290. exporterVisibleAsPdf: 'Export visible data as pdf',
  10291. exporterSelectedAsPdf: 'Export selected data as pdf',
  10292. clearAllFilters: 'Clear all filters'
  10293. },
  10294. importer: {
  10295. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  10296. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  10297. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  10298. invalidJson: 'File was unable to be processed, is it valid Json?',
  10299. jsonNotArray: 'Imported json file must contain an array, aborting.'
  10300. },
  10301. pagination: {
  10302. aria: {
  10303. pageToFirst: 'Page to first',
  10304. pageBack: 'Page back',
  10305. pageSelected: 'Selected page',
  10306. pageForward: 'Page forward',
  10307. pageToLast: 'Page to last'
  10308. },
  10309. sizes: 'items per page',
  10310. totalItems: 'items',
  10311. through: 'through',
  10312. of: 'of'
  10313. },
  10314. grouping: {
  10315. group: 'Group',
  10316. ungroup: 'Ungroup',
  10317. aggregate_count: 'Agg: Count',
  10318. aggregate_sum: 'Agg: Sum',
  10319. aggregate_max: 'Agg: Max',
  10320. aggregate_min: 'Agg: Min',
  10321. aggregate_avg: 'Agg: Avg',
  10322. aggregate_remove: 'Agg: Remove'
  10323. }
  10324. });
  10325. return $delegate;
  10326. }]);
  10327. }]);
  10328. })();
  10329. (function() {
  10330. angular.module('ui.grid').config(['$provide', function($provide) {
  10331. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10332. $delegate.add('es', {
  10333. aggregate: {
  10334. label: 'Artículos'
  10335. },
  10336. groupPanel: {
  10337. description: 'Arrastre un encabezado de columna aquí y suéltelo para agrupar por esa columna.'
  10338. },
  10339. search: {
  10340. placeholder: 'Buscar...',
  10341. showingItems: 'Artículos Mostrados:',
  10342. selectedItems: 'Artículos Seleccionados:',
  10343. totalItems: 'Artículos Totales:',
  10344. size: 'Tamaño de Página:',
  10345. first: 'Primera Página',
  10346. next: 'Página Siguiente',
  10347. previous: 'Página Anterior',
  10348. last: 'Última Página'
  10349. },
  10350. menu: {
  10351. text: 'Elegir columnas:'
  10352. },
  10353. sort: {
  10354. ascending: 'Orden Ascendente',
  10355. descending: 'Orden Descendente',
  10356. remove: 'Sin Ordenar'
  10357. },
  10358. column: {
  10359. hide: 'Ocultar la columna'
  10360. },
  10361. aggregation: {
  10362. count: 'filas totales: ',
  10363. sum: 'total: ',
  10364. avg: 'media: ',
  10365. min: 'min: ',
  10366. max: 'max: '
  10367. },
  10368. pinning: {
  10369. pinLeft: 'Fijar a la Izquierda',
  10370. pinRight: 'Fijar a la Derecha',
  10371. unpin: 'Quitar Fijación'
  10372. },
  10373. gridMenu: {
  10374. columns: 'Columnas:',
  10375. importerTitle: 'Importar archivo',
  10376. exporterAllAsCsv: 'Exportar todo como csv',
  10377. exporterVisibleAsCsv: 'Exportar vista como csv',
  10378. exporterSelectedAsCsv: 'Exportar selección como csv',
  10379. exporterAllAsPdf: 'Exportar todo como pdf',
  10380. exporterVisibleAsPdf: 'Exportar vista como pdf',
  10381. exporterSelectedAsPdf: 'Exportar selección como pdf',
  10382. clearAllFilters: 'Limpiar todos los filtros'
  10383. },
  10384. importer: {
  10385. noHeaders: 'No fue posible derivar los nombres de las columnas, ¿tiene encabezados el archivo?',
  10386. noObjects: 'No fue posible obtener registros, ¿contiene datos el archivo, aparte de los encabezados?',
  10387. invalidCsv: 'No fue posible procesar el archivo, ¿es un CSV válido?',
  10388. invalidJson: 'No fue posible procesar el archivo, ¿es un Json válido?',
  10389. jsonNotArray: 'El archivo json importado debe contener un array, abortando.'
  10390. },
  10391. pagination: {
  10392. sizes: 'registros por página',
  10393. totalItems: 'registros',
  10394. of: 'de'
  10395. },
  10396. grouping: {
  10397. group: 'Agrupar',
  10398. ungroup: 'Desagrupar',
  10399. aggregate_count: 'Agr: Cont',
  10400. aggregate_sum: 'Agr: Sum',
  10401. aggregate_max: 'Agr: Máx',
  10402. aggregate_min: 'Agr: Min',
  10403. aggregate_avg: 'Agr: Prom',
  10404. aggregate_remove: 'Agr: Quitar'
  10405. }
  10406. });
  10407. return $delegate;
  10408. }]);
  10409. }]);
  10410. })();
  10411. /**
  10412. * Translated by: R. Salarmehr
  10413. * M. Hosseynzade
  10414. * Using Vajje.com online dictionary.
  10415. */
  10416. (function() {
  10417. angular.module('ui.grid').config(['$provide', function($provide) {
  10418. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10419. $delegate.add('fa', {
  10420. aggregate: {
  10421. label: 'قلم'
  10422. },
  10423. groupPanel: {
  10424. description: 'عنوان یک ستون را بگیر و به گروهی از آن ستون رها کن.'
  10425. },
  10426. search: {
  10427. placeholder: 'جستجو...',
  10428. showingItems: 'نمایش اقلام:',
  10429. selectedItems: 'قلم\u200cهای انتخاب شده:',
  10430. totalItems: 'مجموع اقلام:',
  10431. size: 'اندازه\u200cی صفحه:',
  10432. first: 'اولین صفحه',
  10433. next: 'صفحه\u200cی\u200cبعدی',
  10434. previous: 'صفحه\u200cی\u200c قبلی',
  10435. last: 'آخرین صفحه'
  10436. },
  10437. menu: {
  10438. text: 'ستون\u200cهای انتخابی:'
  10439. },
  10440. sort: {
  10441. ascending: 'ترتیب صعودی',
  10442. descending: 'ترتیب نزولی',
  10443. remove: 'حذف مرتب کردن'
  10444. },
  10445. column: {
  10446. hide: 'پنهان\u200cکردن ستون'
  10447. },
  10448. aggregation: {
  10449. count: 'تعداد: ',
  10450. sum: 'مجموع: ',
  10451. avg: 'میانگین: ',
  10452. min: 'کمترین: ',
  10453. max: 'بیشترین: '
  10454. },
  10455. pinning: {
  10456. pinLeft: 'پین کردن سمت چپ',
  10457. pinRight: 'پین کردن سمت راست',
  10458. unpin: 'حذف پین'
  10459. },
  10460. gridMenu: {
  10461. columns: 'ستون\u200cها:',
  10462. importerTitle: 'وارد کردن فایل',
  10463. exporterAllAsCsv: 'خروجی تمام داده\u200cها در فایل csv',
  10464. exporterVisibleAsCsv: 'خروجی داده\u200cهای قابل مشاهده در فایل csv',
  10465. exporterSelectedAsCsv: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل csv',
  10466. exporterAllAsPdf: 'خروجی تمام داده\u200cها در فایل pdf',
  10467. exporterVisibleAsPdf: 'خروجی داده\u200cهای قابل مشاهده در فایل pdf',
  10468. exporterSelectedAsPdf: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل pdf',
  10469. clearAllFilters: 'پاک کردن تمام فیلتر'
  10470. },
  10471. importer: {
  10472. noHeaders: 'نام ستون قابل استخراج نیست. آیا فایل عنوان دارد؟',
  10473. noObjects: 'اشیا قابل استخراج نیستند. آیا به جز عنوان\u200cها در فایل داده وجود دارد؟',
  10474. invalidCsv: 'فایل قابل پردازش نیست. آیا فرمت csv معتبر است؟',
  10475. invalidJson: 'فایل قابل پردازش نیست. آیا فرمت json معتبر است؟',
  10476. jsonNotArray: 'فایل json وارد شده باید حاوی آرایه باشد. عملیات ساقط شد.'
  10477. },
  10478. pagination: {
  10479. sizes: 'اقلام در هر صفحه',
  10480. totalItems: 'اقلام',
  10481. of: 'از'
  10482. },
  10483. grouping: {
  10484. group: 'گروه\u200cبندی',
  10485. ungroup: 'حذف گروه\u200cبندی',
  10486. aggregate_count: 'Agg: تعداد',
  10487. aggregate_sum: 'Agg: جمع',
  10488. aggregate_max: 'Agg: بیشینه',
  10489. aggregate_min: 'Agg: کمینه',
  10490. aggregate_avg: 'Agg: میانگین',
  10491. aggregate_remove: 'Agg: حذف'
  10492. }
  10493. });
  10494. return $delegate;
  10495. }]);
  10496. }]);
  10497. })();
  10498. (function() {
  10499. angular.module('ui.grid').config(['$provide', function($provide) {
  10500. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10501. $delegate.add('fi', {
  10502. aggregate: {
  10503. label: 'rivit'
  10504. },
  10505. groupPanel: {
  10506. description: 'Raahaa ja pudota otsikko tähän ryhmittääksesi sarakkeen mukaan.'
  10507. },
  10508. search: {
  10509. placeholder: 'Hae...',
  10510. showingItems: 'Näytetään rivejä:',
  10511. selectedItems: 'Valitut rivit:',
  10512. totalItems: 'Rivejä yht.:',
  10513. size: 'Näytä:',
  10514. first: 'Ensimmäinen sivu',
  10515. next: 'Seuraava sivu',
  10516. previous: 'Edellinen sivu',
  10517. last: 'Viimeinen sivu'
  10518. },
  10519. menu: {
  10520. text: 'Valitse sarakkeet:'
  10521. },
  10522. sort: {
  10523. ascending: 'Järjestä nouseva',
  10524. descending: 'Järjestä laskeva',
  10525. remove: 'Poista järjestys'
  10526. },
  10527. column: {
  10528. hide: 'Piilota sarake'
  10529. },
  10530. aggregation: {
  10531. count: 'Rivejä yht.: ',
  10532. sum: 'Summa: ',
  10533. avg: 'K.a.: ',
  10534. min: 'Min: ',
  10535. max: 'Max: '
  10536. },
  10537. pinning: {
  10538. pinLeft: 'Lukitse vasemmalle',
  10539. pinRight: 'Lukitse oikealle',
  10540. unpin: 'Poista lukitus'
  10541. },
  10542. gridMenu: {
  10543. columns: 'Sarakkeet:',
  10544. importerTitle: 'Tuo tiedosto',
  10545. exporterAllAsCsv: 'Vie tiedot csv-muodossa',
  10546. exporterVisibleAsCsv: 'Vie näkyvä tieto csv-muodossa',
  10547. exporterSelectedAsCsv: 'Vie valittu tieto csv-muodossa',
  10548. exporterAllAsPdf: 'Vie tiedot pdf-muodossa',
  10549. exporterVisibleAsPdf: 'Vie näkyvä tieto pdf-muodossa',
  10550. exporterSelectedAsPdf: 'Vie valittu tieto pdf-muodossa',
  10551. clearAllFilters: 'Puhdista kaikki suodattimet'
  10552. },
  10553. importer: {
  10554. noHeaders: 'Sarakkeen nimiä ei voitu päätellä, onko tiedostossa otsikkoriviä?',
  10555. noObjects: 'Tietoja ei voitu lukea, onko tiedostossa muuta kuin otsikkot?',
  10556. invalidCsv: 'Tiedostoa ei voitu käsitellä, oliko se CSV-muodossa?',
  10557. invalidJson: 'Tiedostoa ei voitu käsitellä, oliko se JSON-muodossa?',
  10558. jsonNotArray: 'Tiedosto ei sisältänyt taulukkoa, lopetetaan.'
  10559. }
  10560. });
  10561. return $delegate;
  10562. }]);
  10563. }]);
  10564. })();
  10565. (function() {
  10566. angular.module('ui.grid').config(['$provide', function($provide) {
  10567. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10568. $delegate.add('fr', {
  10569. aggregate: {
  10570. label: 'éléments'
  10571. },
  10572. groupPanel: {
  10573. description: 'Faites glisser une en-tête de colonne ici pour créer un groupe de colonnes.'
  10574. },
  10575. search: {
  10576. placeholder: 'Recherche...',
  10577. showingItems: 'Affichage des éléments :',
  10578. selectedItems: 'Éléments sélectionnés :',
  10579. totalItems: 'Nombre total d\'éléments:',
  10580. size: 'Taille de page:',
  10581. first: 'Première page',
  10582. next: 'Page Suivante',
  10583. previous: 'Page précédente',
  10584. last: 'Dernière page'
  10585. },
  10586. menu: {
  10587. text: 'Choisir des colonnes :'
  10588. },
  10589. sort: {
  10590. ascending: 'Trier par ordre croissant',
  10591. descending: 'Trier par ordre décroissant',
  10592. remove: 'Enlever le tri'
  10593. },
  10594. column: {
  10595. hide: 'Cacher la colonne'
  10596. },
  10597. aggregation: {
  10598. count: 'lignes totales: ',
  10599. sum: 'total: ',
  10600. avg: 'moy: ',
  10601. min: 'min: ',
  10602. max: 'max: '
  10603. },
  10604. pinning: {
  10605. pinLeft: 'Épingler à gauche',
  10606. pinRight: 'Épingler à droite',
  10607. unpin: 'Détacher'
  10608. },
  10609. gridMenu: {
  10610. columns: 'Colonnes:',
  10611. importerTitle: 'Importer un fichier',
  10612. exporterAllAsCsv: 'Exporter toutes les données en CSV',
  10613. exporterVisibleAsCsv: 'Exporter les données visibles en CSV',
  10614. exporterSelectedAsCsv: 'Exporter les données sélectionnées en CSV',
  10615. exporterAllAsPdf: 'Exporter toutes les données en PDF',
  10616. exporterVisibleAsPdf: 'Exporter les données visibles en PDF',
  10617. exporterSelectedAsPdf: 'Exporter les données sélectionnées en PDF',
  10618. clearAllFilters: 'Nettoyez tous les filtres'
  10619. },
  10620. importer: {
  10621. noHeaders: 'Impossible de déterminer le nom des colonnes, le fichier possède-t-il une en-tête ?',
  10622. noObjects: 'Aucun objet trouvé, le fichier possède-t-il des données autres que l\'en-tête ?',
  10623. invalidCsv: 'Le fichier n\'a pas pu être traité, le CSV est-il valide ?',
  10624. invalidJson: 'Le fichier n\'a pas pu être traité, le JSON est-il valide ?',
  10625. jsonNotArray: 'Le fichier JSON importé doit contenir un tableau, abandon.'
  10626. },
  10627. pagination: {
  10628. sizes: 'éléments par page',
  10629. totalItems: 'éléments',
  10630. of: 'sur'
  10631. },
  10632. grouping: {
  10633. group: 'Grouper',
  10634. ungroup: 'Dégrouper',
  10635. aggregate_count: 'Agg: Compte',
  10636. aggregate_sum: 'Agg: Somme',
  10637. aggregate_max: 'Agg: Max',
  10638. aggregate_min: 'Agg: Min',
  10639. aggregate_avg: 'Agg: Moy',
  10640. aggregate_remove: 'Agg: Retirer'
  10641. }
  10642. });
  10643. return $delegate;
  10644. }]);
  10645. }]);
  10646. })();
  10647. (function() {
  10648. angular.module('ui.grid').config(['$provide', function($provide) {
  10649. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10650. $delegate.add('he', {
  10651. aggregate: {
  10652. label: 'items'
  10653. },
  10654. groupPanel: {
  10655. description: 'גרור עמודה לכאן ושחרר בכדי לקבץ עמודה זו.'
  10656. },
  10657. search: {
  10658. placeholder: 'חפש...',
  10659. showingItems: 'מציג:',
  10660. selectedItems: 'סה"כ נבחרו:',
  10661. totalItems: 'סה"כ רשומות:',
  10662. size: 'תוצאות בדף:',
  10663. first: 'דף ראשון',
  10664. next: 'דף הבא',
  10665. previous: 'דף קודם',
  10666. last: 'דף אחרון'
  10667. },
  10668. menu: {
  10669. text: 'בחר עמודות:'
  10670. },
  10671. sort: {
  10672. ascending: 'סדר עולה',
  10673. descending: 'סדר יורד',
  10674. remove: 'בטל'
  10675. },
  10676. column: {
  10677. hide: 'טור הסתר'
  10678. },
  10679. aggregation: {
  10680. count: 'total rows: ',
  10681. sum: 'total: ',
  10682. avg: 'avg: ',
  10683. min: 'min: ',
  10684. max: 'max: '
  10685. },
  10686. gridMenu: {
  10687. columns: 'Columns:',
  10688. importerTitle: 'Import file',
  10689. exporterAllAsCsv: 'Export all data as csv',
  10690. exporterVisibleAsCsv: 'Export visible data as csv',
  10691. exporterSelectedAsCsv: 'Export selected data as csv',
  10692. exporterAllAsPdf: 'Export all data as pdf',
  10693. exporterVisibleAsPdf: 'Export visible data as pdf',
  10694. exporterSelectedAsPdf: 'Export selected data as pdf',
  10695. clearAllFilters: 'Clean all filters'
  10696. },
  10697. importer: {
  10698. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  10699. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  10700. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  10701. invalidJson: 'File was unable to be processed, is it valid Json?',
  10702. jsonNotArray: 'Imported json file must contain an array, aborting.'
  10703. }
  10704. });
  10705. return $delegate;
  10706. }]);
  10707. }]);
  10708. })();
  10709. (function() {
  10710. angular.module('ui.grid').config(['$provide', function($provide) {
  10711. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10712. $delegate.add('hy', {
  10713. aggregate: {
  10714. label: 'տվյալներ'
  10715. },
  10716. groupPanel: {
  10717. description: 'Ըստ սյան խմբավորելու համար քաշեք և գցեք վերնագիրն այստեղ։'
  10718. },
  10719. search: {
  10720. placeholder: 'Փնտրում...',
  10721. showingItems: 'Ցուցադրված տվյալներ՝',
  10722. selectedItems: 'Ընտրված:',
  10723. totalItems: 'Ընդամենը՝',
  10724. size: 'Տողերի քանակը էջում՝',
  10725. first: 'Առաջին էջ',
  10726. next: 'Հաջորդ էջ',
  10727. previous: 'Նախորդ էջ',
  10728. last: 'Վերջին էջ'
  10729. },
  10730. menu: {
  10731. text: 'Ընտրել սյուները:'
  10732. },
  10733. sort: {
  10734. ascending: 'Աճման կարգով',
  10735. descending: 'Նվազման կարգով',
  10736. remove: 'Հանել '
  10737. },
  10738. column: {
  10739. hide: 'Թաքցնել սյունը'
  10740. },
  10741. aggregation: {
  10742. count: 'ընդամենը տող՝ ',
  10743. sum: 'ընդամենը՝ ',
  10744. avg: 'միջին՝ ',
  10745. min: 'մին՝ ',
  10746. max: 'մաքս՝ '
  10747. },
  10748. pinning: {
  10749. pinLeft: 'Կպցնել ձախ կողմում',
  10750. pinRight: 'Կպցնել աջ կողմում',
  10751. unpin: 'Արձակել'
  10752. },
  10753. gridMenu: {
  10754. columns: 'Սյուներ:',
  10755. importerTitle: 'Ներմուծել ֆայլ',
  10756. exporterAllAsCsv: 'Արտահանել ամբողջը CSV',
  10757. exporterVisibleAsCsv: 'Արտահանել երևացող տվյալները CSV',
  10758. exporterSelectedAsCsv: 'Արտահանել ընտրված տվյալները CSV',
  10759. exporterAllAsPdf: 'Արտահանել PDF',
  10760. exporterVisibleAsPdf: 'Արտահանել երևացող տվյալները PDF',
  10761. exporterSelectedAsPdf: 'Արտահանել ընտրված տվյալները PDF',
  10762. clearAllFilters: 'Մաքրել բոլոր ֆիլտրերը'
  10763. },
  10764. importer: {
  10765. noHeaders: 'Հնարավոր չեղավ որոշել սյան վերնագրերը։ Արդյո՞ք ֆայլը ունի վերնագրեր։',
  10766. noObjects: 'Հնարավոր չեղավ կարդալ տվյալները։ Արդյո՞ք ֆայլում կան տվյալներ։',
  10767. invalidCsv: 'Հնարավոր չեղավ մշակել ֆայլը։ Արդյո՞ք այն վավեր CSV է։',
  10768. invalidJson: 'Հնարավոր չեղավ մշակել ֆայլը։ Արդյո՞ք այն վավեր Json է։',
  10769. jsonNotArray: 'Ներմուծված json ֆայլը պետք է պարունակի զանգված, կասեցվում է։'
  10770. }
  10771. });
  10772. return $delegate;
  10773. }]);
  10774. }]);
  10775. })();
  10776. (function() {
  10777. angular.module('ui.grid').config(['$provide', function($provide) {
  10778. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10779. $delegate.add('it', {
  10780. aggregate: {
  10781. label: 'elementi'
  10782. },
  10783. groupPanel: {
  10784. description: 'Trascina un\'intestazione all\'interno del gruppo della colonna.'
  10785. },
  10786. search: {
  10787. placeholder: 'Ricerca...',
  10788. showingItems: 'Mostra:',
  10789. selectedItems: 'Selezionati:',
  10790. totalItems: 'Totali:',
  10791. size: 'Tot Pagine:',
  10792. first: 'Prima',
  10793. next: 'Prossima',
  10794. previous: 'Precedente',
  10795. last: 'Ultima'
  10796. },
  10797. menu: {
  10798. text: 'Scegli le colonne:'
  10799. },
  10800. sort: {
  10801. ascending: 'Asc.',
  10802. descending: 'Desc.',
  10803. remove: 'Annulla ordinamento'
  10804. },
  10805. column: {
  10806. hide: 'Nascondi'
  10807. },
  10808. aggregation: {
  10809. count: 'righe totali: ',
  10810. sum: 'tot: ',
  10811. avg: 'media: ',
  10812. min: 'minimo: ',
  10813. max: 'massimo: '
  10814. },
  10815. pinning: {
  10816. pinLeft: 'Blocca a sx',
  10817. pinRight: 'Blocca a dx',
  10818. unpin: 'Blocca in alto'
  10819. },
  10820. gridMenu: {
  10821. columns: 'Colonne:',
  10822. importerTitle: 'Importa',
  10823. exporterAllAsCsv: 'Esporta tutti i dati in CSV',
  10824. exporterVisibleAsCsv: 'Esporta i dati visibili in CSV',
  10825. exporterSelectedAsCsv: 'Esporta i dati selezionati in CSV',
  10826. exporterAllAsPdf: 'Esporta tutti i dati in PDF',
  10827. exporterVisibleAsPdf: 'Esporta i dati visibili in PDF',
  10828. exporterSelectedAsPdf: 'Esporta i dati selezionati in PDF',
  10829. clearAllFilters: 'Pulire tutti i filtri'
  10830. },
  10831. importer: {
  10832. noHeaders: 'Impossibile reperire i nomi delle colonne, sicuro che siano indicati all\'interno del file?',
  10833. noObjects: 'Impossibile reperire gli oggetti, sicuro che siano indicati all\'interno del file?',
  10834. invalidCsv: 'Impossibile elaborare il file, sicuro che sia un CSV?',
  10835. invalidJson: 'Impossibile elaborare il file, sicuro che sia un JSON valido?',
  10836. jsonNotArray: 'Errore! Il file JSON da importare deve contenere un array.'
  10837. },
  10838. grouping: {
  10839. group: 'Raggruppa',
  10840. ungroup: 'Separa',
  10841. aggregate_count: 'Agg: N. Elem.',
  10842. aggregate_sum: 'Agg: Somma',
  10843. aggregate_max: 'Agg: Massimo',
  10844. aggregate_min: 'Agg: Minimo',
  10845. aggregate_avg: 'Agg: Media',
  10846. aggregate_remove: 'Agg: Rimuovi'
  10847. }
  10848. });
  10849. return $delegate;
  10850. }]);
  10851. }]);
  10852. })();
  10853. (function() {
  10854. angular.module('ui.grid').config(['$provide', function($provide) {
  10855. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10856. $delegate.add('ja', {
  10857. aggregate: {
  10858. label: '項目'
  10859. },
  10860. groupPanel: {
  10861. description: 'ここに列ヘッダをドラッグアンドドロップして、その列でグループ化します。'
  10862. },
  10863. search: {
  10864. placeholder: '検索...',
  10865. showingItems: '表示中の項目:',
  10866. selectedItems: '選択した項目:',
  10867. totalItems: '項目の総数:',
  10868. size: 'ページサイズ:',
  10869. first: '最初のページ',
  10870. next: '次のページ',
  10871. previous: '前のページ',
  10872. last: '前のページ'
  10873. },
  10874. menu: {
  10875. text: '列の選択:'
  10876. },
  10877. sort: {
  10878. ascending: '昇順に並べ替え',
  10879. descending: '降順に並べ替え',
  10880. remove: '並べ替えの解除'
  10881. },
  10882. column: {
  10883. hide: '列の非表示'
  10884. },
  10885. aggregation: {
  10886. count: '合計行数: ',
  10887. sum: '合計: ',
  10888. avg: '平均: ',
  10889. min: '最小: ',
  10890. max: '最大: '
  10891. },
  10892. pinning: {
  10893. pinLeft: '左に固定',
  10894. pinRight: '右に固定',
  10895. unpin: '固定解除'
  10896. },
  10897. gridMenu: {
  10898. columns: '列:',
  10899. importerTitle: 'ファイルのインポート',
  10900. exporterAllAsCsv: 'すべてのデータをCSV形式でエクスポート',
  10901. exporterVisibleAsCsv: '表示中のデータをCSV形式でエクスポート',
  10902. exporterSelectedAsCsv: '選択したデータをCSV形式でエクスポート',
  10903. exporterAllAsPdf: 'すべてのデータをPDF形式でエクスポート',
  10904. exporterVisibleAsPdf: '表示中のデータをPDF形式でエクスポート',
  10905. exporterSelectedAsPdf: '選択したデータをPDF形式でエクスポート',
  10906. clearAllFilters: 'すべてのフィルタを清掃してください'
  10907. },
  10908. importer: {
  10909. noHeaders: '列名を取得できません。ファイルにヘッダが含まれていることを確認してください。',
  10910. noObjects: 'オブジェクトを取得できません。ファイルにヘッダ以外のデータが含まれていることを確認してください。',
  10911. invalidCsv: 'ファイルを処理できません。ファイルが有効なCSV形式であることを確認してください。',
  10912. invalidJson: 'ファイルを処理できません。ファイルが有効なJSON形式であることを確認してください。',
  10913. jsonNotArray: 'インポートしたJSONファイルには配列が含まれている必要があります。処理を中止します。'
  10914. },
  10915. pagination: {
  10916. sizes: '項目/ページ',
  10917. totalItems: '項目'
  10918. }
  10919. });
  10920. return $delegate;
  10921. }]);
  10922. }]);
  10923. })();
  10924. (function() {
  10925. angular.module('ui.grid').config(['$provide', function($provide) {
  10926. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10927. $delegate.add('ko', {
  10928. aggregate: {
  10929. label: '아이템'
  10930. },
  10931. groupPanel: {
  10932. description: '컬럼으로 그룹핑하기 위해서는 컬럼 헤더를 끌어 떨어뜨려 주세요.'
  10933. },
  10934. search: {
  10935. placeholder: '검색...',
  10936. showingItems: '항목 보여주기:',
  10937. selectedItems: '선택 항목:',
  10938. totalItems: '전체 항목:',
  10939. size: '페이지 크기:',
  10940. first: '첫번째 페이지',
  10941. next: '다음 페이지',
  10942. previous: '이전 페이지',
  10943. last: '마지막 페이지'
  10944. },
  10945. menu: {
  10946. text: '컬럼을 선택하세요:'
  10947. },
  10948. sort: {
  10949. ascending: '오름차순 정렬',
  10950. descending: '내림차순 정렬',
  10951. remove: '소팅 제거'
  10952. },
  10953. column: {
  10954. hide: '컬럼 제거'
  10955. },
  10956. aggregation: {
  10957. count: '전체 갯수: ',
  10958. sum: '전체: ',
  10959. avg: '평균: ',
  10960. min: '최소: ',
  10961. max: '최대: '
  10962. },
  10963. pinning: {
  10964. pinLeft: '왼쪽 핀',
  10965. pinRight: '오른쪽 핀',
  10966. unpin: '핀 제거'
  10967. },
  10968. gridMenu: {
  10969. columns: '컬럼:',
  10970. importerTitle: '파일 가져오기',
  10971. exporterAllAsCsv: 'csv로 모든 데이터 내보내기',
  10972. exporterVisibleAsCsv: 'csv로 보이는 데이터 내보내기',
  10973. exporterSelectedAsCsv: 'csv로 선택된 데이터 내보내기',
  10974. exporterAllAsPdf: 'pdf로 모든 데이터 내보내기',
  10975. exporterVisibleAsPdf: 'pdf로 보이는 데이터 내보내기',
  10976. exporterSelectedAsPdf: 'pdf로 선택 데이터 내보내기',
  10977. clearAllFilters: '모든 필터를 청소'
  10978. },
  10979. importer: {
  10980. noHeaders: '컬럼명이 지정되어 있지 않습니다. 파일에 헤더가 명시되어 있는지 확인해 주세요.',
  10981. noObjects: '데이터가 지정되어 있지 않습니다. 데이터가 파일에 있는지 확인해 주세요.',
  10982. invalidCsv: '파일을 처리할 수 없습니다. 올바른 csv인지 확인해 주세요.',
  10983. invalidJson: '파일을 처리할 수 없습니다. 올바른 json인지 확인해 주세요.',
  10984. jsonNotArray: 'json 파일은 배열을 포함해야 합니다.'
  10985. },
  10986. pagination: {
  10987. sizes: '페이지당 항목',
  10988. totalItems: '전체 항목'
  10989. }
  10990. });
  10991. return $delegate;
  10992. }]);
  10993. }]);
  10994. })();
  10995. (function() {
  10996. angular.module('ui.grid').config(['$provide', function($provide) {
  10997. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  10998. $delegate.add('nl', {
  10999. aggregate: {
  11000. label: 'items'
  11001. },
  11002. groupPanel: {
  11003. description: 'Sleep hier een kolomnaam heen om op te groeperen.'
  11004. },
  11005. search: {
  11006. placeholder: 'Zoeken...',
  11007. showingItems: 'Getoonde items:',
  11008. selectedItems: 'Geselecteerde items:',
  11009. totalItems: 'Totaal aantal items:',
  11010. size: 'Items per pagina:',
  11011. first: 'Eerste pagina',
  11012. next: 'Volgende pagina',
  11013. previous: 'Vorige pagina',
  11014. last: 'Laatste pagina'
  11015. },
  11016. menu: {
  11017. text: 'Kies kolommen:'
  11018. },
  11019. sort: {
  11020. ascending: 'Sorteer oplopend',
  11021. descending: 'Sorteer aflopend',
  11022. remove: 'Verwijder sortering'
  11023. },
  11024. column: {
  11025. hide: 'Verberg kolom'
  11026. },
  11027. aggregation: {
  11028. count: 'Aantal rijen: ',
  11029. sum: 'Som: ',
  11030. avg: 'Gemiddelde: ',
  11031. min: 'Min: ',
  11032. max: 'Max: '
  11033. },
  11034. pinning: {
  11035. pinLeft: 'Zet links vast',
  11036. pinRight: 'Zet rechts vast',
  11037. unpin: 'Maak los'
  11038. },
  11039. gridMenu: {
  11040. columns: 'Kolommen:',
  11041. importerTitle: 'Importeer bestand',
  11042. exporterAllAsCsv: 'Exporteer alle data als csv',
  11043. exporterVisibleAsCsv: 'Exporteer zichtbare data als csv',
  11044. exporterSelectedAsCsv: 'Exporteer geselecteerde data als csv',
  11045. exporterAllAsPdf: 'Exporteer alle data als pdf',
  11046. exporterVisibleAsPdf: 'Exporteer zichtbare data als pdf',
  11047. exporterSelectedAsPdf: 'Exporteer geselecteerde data als pdf',
  11048. clearAllFilters: 'Reinig alle filters'
  11049. },
  11050. importer: {
  11051. noHeaders: 'Kolomnamen kunnen niet worden afgeleid. Heeft het bestand een header?',
  11052. noObjects: 'Objecten kunnen niet worden afgeleid. Bevat het bestand data naast de headers?',
  11053. invalidCsv: 'Het bestand kan niet verwerkt worden. Is het een valide csv bestand?',
  11054. invalidJson: 'Het bestand kan niet verwerkt worden. Is het valide json?',
  11055. jsonNotArray: 'Het json bestand moet een array bevatten. De actie wordt geannuleerd.'
  11056. },
  11057. pagination: {
  11058. sizes: 'items per pagina',
  11059. totalItems: 'items'
  11060. },
  11061. grouping: {
  11062. group: 'Groepeer',
  11063. ungroup: 'Groepering opheffen',
  11064. aggregate_count: 'Agg: Aantal',
  11065. aggregate_sum: 'Agg: Som',
  11066. aggregate_max: 'Agg: Max',
  11067. aggregate_min: 'Agg: Min',
  11068. aggregate_avg: 'Agg: Gem',
  11069. aggregate_remove: 'Agg: Verwijder'
  11070. }
  11071. });
  11072. return $delegate;
  11073. }]);
  11074. }]);
  11075. })();
  11076. (function() {
  11077. angular.module('ui.grid').config(['$provide', function($provide) {
  11078. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11079. $delegate.add('pt-br', {
  11080. aggregate: {
  11081. label: 'itens'
  11082. },
  11083. groupPanel: {
  11084. description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna'
  11085. },
  11086. search: {
  11087. placeholder: 'Procurar...',
  11088. showingItems: 'Mostrando os Itens:',
  11089. selectedItems: 'Items Selecionados:',
  11090. totalItems: 'Total de Itens:',
  11091. size: 'Tamanho da Página:',
  11092. first: 'Primeira Página',
  11093. next: 'Próxima Página',
  11094. previous: 'Página Anterior',
  11095. last: 'Última Página'
  11096. },
  11097. menu: {
  11098. text: 'Selecione as colunas:'
  11099. },
  11100. sort: {
  11101. ascending: 'Ordenar Ascendente',
  11102. descending: 'Ordenar Descendente',
  11103. remove: 'Remover Ordenação'
  11104. },
  11105. column: {
  11106. hide: 'Esconder coluna'
  11107. },
  11108. aggregation: {
  11109. count: 'total de linhas: ',
  11110. sum: 'total: ',
  11111. avg: 'med: ',
  11112. min: 'min: ',
  11113. max: 'max: '
  11114. },
  11115. pinning: {
  11116. pinLeft: 'Fixar Esquerda',
  11117. pinRight: 'Fixar Direita',
  11118. unpin: 'Desprender'
  11119. },
  11120. gridMenu: {
  11121. columns: 'Colunas:',
  11122. importerTitle: 'Importar arquivo',
  11123. exporterAllAsCsv: 'Exportar todos os dados como csv',
  11124. exporterVisibleAsCsv: 'Exportar dados visíveis como csv',
  11125. exporterSelectedAsCsv: 'Exportar dados selecionados como csv',
  11126. exporterAllAsPdf: 'Exportar todos os dados como pdf',
  11127. exporterVisibleAsPdf: 'Exportar dados visíveis como pdf',
  11128. exporterSelectedAsPdf: 'Exportar dados selecionados como pdf',
  11129. clearAllFilters: 'Limpar todos os filtros'
  11130. },
  11131. importer: {
  11132. noHeaders: 'Nomes de colunas não puderam ser derivados. O arquivo tem um cabeçalho?',
  11133. noObjects: 'Objetos não puderam ser derivados. Havia dados no arquivo, além dos cabeçalhos?',
  11134. invalidCsv: 'Arquivo não pode ser processado. É um CSV válido?',
  11135. invalidJson: 'Arquivo não pode ser processado. É um Json válido?',
  11136. jsonNotArray: 'Arquivo json importado tem que conter um array. Abortando.'
  11137. },
  11138. pagination: {
  11139. sizes: 'itens por página',
  11140. totalItems: 'itens'
  11141. },
  11142. grouping: {
  11143. group: 'Agrupar',
  11144. ungroup: 'Desagrupar',
  11145. aggregate_count: 'Agr: Contar',
  11146. aggregate_sum: 'Agr: Soma',
  11147. aggregate_max: 'Agr: Max',
  11148. aggregate_min: 'Agr: Min',
  11149. aggregate_avg: 'Agr: Med',
  11150. aggregate_remove: 'Agr: Remover'
  11151. }
  11152. });
  11153. return $delegate;
  11154. }]);
  11155. }]);
  11156. })();
  11157. (function() {
  11158. angular.module('ui.grid').config(['$provide', function($provide) {
  11159. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11160. $delegate.add('pt', {
  11161. aggregate: {
  11162. label: 'itens'
  11163. },
  11164. groupPanel: {
  11165. description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna'
  11166. },
  11167. search: {
  11168. placeholder: 'Procurar...',
  11169. showingItems: 'Mostrando os Itens:',
  11170. selectedItems: 'Itens Selecionados:',
  11171. totalItems: 'Total de Itens:',
  11172. size: 'Tamanho da Página:',
  11173. first: 'Primeira Página',
  11174. next: 'Próxima Página',
  11175. previous: 'Página Anterior',
  11176. last: 'Última Página'
  11177. },
  11178. menu: {
  11179. text: 'Selecione as colunas:'
  11180. },
  11181. sort: {
  11182. ascending: 'Ordenar Ascendente',
  11183. descending: 'Ordenar Descendente',
  11184. remove: 'Remover Ordenação'
  11185. },
  11186. column: {
  11187. hide: 'Esconder coluna'
  11188. },
  11189. aggregation: {
  11190. count: 'total de linhas: ',
  11191. sum: 'total: ',
  11192. avg: 'med: ',
  11193. min: 'min: ',
  11194. max: 'max: '
  11195. },
  11196. pinning: {
  11197. pinLeft: 'Fixar Esquerda',
  11198. pinRight: 'Fixar Direita',
  11199. unpin: 'Desprender'
  11200. },
  11201. gridMenu: {
  11202. columns: 'Colunas:',
  11203. importerTitle: 'Importar ficheiro',
  11204. exporterAllAsCsv: 'Exportar todos os dados como csv',
  11205. exporterVisibleAsCsv: 'Exportar dados visíveis como csv',
  11206. exporterSelectedAsCsv: 'Exportar dados selecionados como csv',
  11207. exporterAllAsPdf: 'Exportar todos os dados como pdf',
  11208. exporterVisibleAsPdf: 'Exportar dados visíveis como pdf',
  11209. exporterSelectedAsPdf: 'Exportar dados selecionados como pdf',
  11210. clearAllFilters: 'Limpar todos os filtros'
  11211. },
  11212. importer: {
  11213. noHeaders: 'Nomes de colunas não puderam ser derivados. O ficheiro tem um cabeçalho?',
  11214. noObjects: 'Objetos não puderam ser derivados. Havia dados no ficheiro, além dos cabeçalhos?',
  11215. invalidCsv: 'Ficheiro não pode ser processado. É um CSV válido?',
  11216. invalidJson: 'Ficheiro não pode ser processado. É um Json válido?',
  11217. jsonNotArray: 'Ficheiro json importado tem que conter um array. Interrompendo.'
  11218. },
  11219. pagination: {
  11220. sizes: 'itens por página',
  11221. totalItems: 'itens',
  11222. of: 'de'
  11223. },
  11224. grouping: {
  11225. group: 'Agrupar',
  11226. ungroup: 'Desagrupar',
  11227. aggregate_count: 'Agr: Contar',
  11228. aggregate_sum: 'Agr: Soma',
  11229. aggregate_max: 'Agr: Max',
  11230. aggregate_min: 'Agr: Min',
  11231. aggregate_avg: 'Agr: Med',
  11232. aggregate_remove: 'Agr: Remover'
  11233. }
  11234. });
  11235. return $delegate;
  11236. }]);
  11237. }]);
  11238. })();
  11239. (function() {
  11240. angular.module('ui.grid').config(['$provide', function($provide) {
  11241. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11242. $delegate.add('ru', {
  11243. aggregate: {
  11244. label: 'элементы'
  11245. },
  11246. groupPanel: {
  11247. description: 'Для группировки по столбцу перетащите сюда его название.'
  11248. },
  11249. search: {
  11250. placeholder: 'Поиск...',
  11251. showingItems: 'Показать элементы:',
  11252. selectedItems: 'Выбранные элементы:',
  11253. totalItems: 'Всего элементов:',
  11254. size: 'Размер страницы:',
  11255. first: 'Первая страница',
  11256. next: 'Следующая страница',
  11257. previous: 'Предыдущая страница',
  11258. last: 'Последняя страница'
  11259. },
  11260. menu: {
  11261. text: 'Выбрать столбцы:'
  11262. },
  11263. sort: {
  11264. ascending: 'По возрастанию',
  11265. descending: 'По убыванию',
  11266. remove: 'Убрать сортировку'
  11267. },
  11268. column: {
  11269. hide: 'Спрятать столбец'
  11270. },
  11271. aggregation: {
  11272. count: 'всего строк: ',
  11273. sum: 'итого: ',
  11274. avg: 'среднее: ',
  11275. min: 'мин: ',
  11276. max: 'макс: '
  11277. },
  11278. pinning: {
  11279. pinLeft: 'Закрепить слева',
  11280. pinRight: 'Закрепить справа',
  11281. unpin: 'Открепить'
  11282. },
  11283. gridMenu: {
  11284. columns: 'Столбцы:',
  11285. importerTitle: 'Import file',
  11286. exporterAllAsCsv: 'Экспортировать всё в CSV',
  11287. exporterVisibleAsCsv: 'Экспортировать видимые данные в CSV',
  11288. exporterSelectedAsCsv: 'Экспортировать выбранные данные в CSV',
  11289. exporterAllAsPdf: 'Экспортировать всё в PDF',
  11290. exporterVisibleAsPdf: 'Экспортировать видимые данные в PDF',
  11291. exporterSelectedAsPdf: 'Экспортировать выбранные данные в PDF',
  11292. clearAllFilters: 'Очистите все фильтры'
  11293. },
  11294. importer: {
  11295. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  11296. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  11297. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  11298. invalidJson: 'File was unable to be processed, is it valid Json?',
  11299. jsonNotArray: 'Imported json file must contain an array, aborting.'
  11300. }
  11301. });
  11302. return $delegate;
  11303. }]);
  11304. }]);
  11305. })();
  11306. (function() {
  11307. angular.module('ui.grid').config(['$provide', function($provide) {
  11308. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11309. $delegate.add('sk', {
  11310. aggregate: {
  11311. label: 'items'
  11312. },
  11313. groupPanel: {
  11314. description: 'Pretiahni sem názov stĺpca pre zoskupenie podľa toho stĺpca.'
  11315. },
  11316. search: {
  11317. placeholder: 'Hľadaj...',
  11318. showingItems: 'Zobrazujem položky:',
  11319. selectedItems: 'Vybraté položky:',
  11320. totalItems: 'Počet položiek:',
  11321. size: 'Počet:',
  11322. first: 'Prvá strana',
  11323. next: 'Ďalšia strana',
  11324. previous: 'Predchádzajúca strana',
  11325. last: 'Posledná strana'
  11326. },
  11327. menu: {
  11328. text: 'Vyberte stĺpce:'
  11329. },
  11330. sort: {
  11331. ascending: 'Zotriediť vzostupne',
  11332. descending: 'Zotriediť zostupne',
  11333. remove: 'Vymazať triedenie'
  11334. },
  11335. aggregation: {
  11336. count: 'total rows: ',
  11337. sum: 'total: ',
  11338. avg: 'avg: ',
  11339. min: 'min: ',
  11340. max: 'max: '
  11341. },
  11342. gridMenu: {
  11343. columns: 'Columns:',
  11344. importerTitle: 'Import file',
  11345. exporterAllAsCsv: 'Export all data as csv',
  11346. exporterVisibleAsCsv: 'Export visible data as csv',
  11347. exporterSelectedAsCsv: 'Export selected data as csv',
  11348. exporterAllAsPdf: 'Export all data as pdf',
  11349. exporterVisibleAsPdf: 'Export visible data as pdf',
  11350. exporterSelectedAsPdf: 'Export selected data as pdf',
  11351. clearAllFilters: 'Clear all filters'
  11352. },
  11353. importer: {
  11354. noHeaders: 'Column names were unable to be derived, does the file have a header?',
  11355. noObjects: 'Objects were not able to be derived, was there data in the file other than headers?',
  11356. invalidCsv: 'File was unable to be processed, is it valid CSV?',
  11357. invalidJson: 'File was unable to be processed, is it valid Json?',
  11358. jsonNotArray: 'Imported json file must contain an array, aborting.'
  11359. }
  11360. });
  11361. return $delegate;
  11362. }]);
  11363. }]);
  11364. })();
  11365. (function() {
  11366. angular.module('ui.grid').config(['$provide', function($provide) {
  11367. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11368. $delegate.add('sv', {
  11369. aggregate: {
  11370. label: 'Artiklar'
  11371. },
  11372. groupPanel: {
  11373. description: 'Dra en kolumnrubrik hit och släpp den för att gruppera efter den kolumnen.'
  11374. },
  11375. search: {
  11376. placeholder: 'Sök...',
  11377. showingItems: 'Visar artiklar:',
  11378. selectedItems: 'Valda artiklar:',
  11379. totalItems: 'Antal artiklar:',
  11380. size: 'Sidstorlek:',
  11381. first: 'Första sidan',
  11382. next: 'Nästa sida',
  11383. previous: 'Föregående sida',
  11384. last: 'Sista sidan'
  11385. },
  11386. menu: {
  11387. text: 'Välj kolumner:'
  11388. },
  11389. sort: {
  11390. ascending: 'Sortera stigande',
  11391. descending: 'Sortera fallande',
  11392. remove: 'Inaktivera sortering'
  11393. },
  11394. column: {
  11395. hide: 'Göm kolumn'
  11396. },
  11397. aggregation: {
  11398. count: 'Antal rader: ',
  11399. sum: 'Summa: ',
  11400. avg: 'Genomsnitt: ',
  11401. min: 'Min: ',
  11402. max: 'Max: '
  11403. },
  11404. pinning: {
  11405. pinLeft: 'Fäst vänster',
  11406. pinRight: 'Fäst höger',
  11407. unpin: 'Lösgör'
  11408. },
  11409. gridMenu: {
  11410. columns: 'Kolumner:',
  11411. importerTitle: 'Importera fil',
  11412. exporterAllAsCsv: 'Exportera all data som CSV',
  11413. exporterVisibleAsCsv: 'Exportera synlig data som CSV',
  11414. exporterSelectedAsCsv: 'Exportera markerad data som CSV',
  11415. exporterAllAsPdf: 'Exportera all data som PDF',
  11416. exporterVisibleAsPdf: 'Exportera synlig data som PDF',
  11417. exporterSelectedAsPdf: 'Exportera markerad data som PDF',
  11418. clearAllFilters: 'Rengör alla filter'
  11419. },
  11420. importer: {
  11421. noHeaders: 'Kolumnnamn kunde inte härledas. Har filen ett sidhuvud?',
  11422. noObjects: 'Objekt kunde inte härledas. Har filen data undantaget sidhuvud?',
  11423. invalidCsv: 'Filen kunde inte behandlas, är den en giltig CSV?',
  11424. invalidJson: 'Filen kunde inte behandlas, är den en giltig JSON?',
  11425. jsonNotArray: 'Importerad JSON-fil måste innehålla ett fält. Import avbruten.'
  11426. },
  11427. pagination: {
  11428. sizes: 'Artiklar per sida',
  11429. totalItems: 'Artiklar'
  11430. }
  11431. });
  11432. return $delegate;
  11433. }]);
  11434. }]);
  11435. })();
  11436. (function() {
  11437. angular.module('ui.grid').config(['$provide', function($provide) {
  11438. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11439. $delegate.add('ta', {
  11440. aggregate: {
  11441. label: 'உருப்படிகள்'
  11442. },
  11443. groupPanel: {
  11444. description: 'ஒரு பத்தியை குழுவாக அமைக்க அப்பத்தியின் தலைப்பை இங்கே இழுத்து வரவும் '
  11445. },
  11446. search: {
  11447. placeholder: 'தேடல் ...',
  11448. showingItems: 'உருப்படிகளை காண்பித்தல்:',
  11449. selectedItems: 'தேர்ந்தெடுக்கப்பட்ட உருப்படிகள்:',
  11450. totalItems: 'மொத்த உருப்படிகள்:',
  11451. size: 'பக்க அளவு: ',
  11452. first: 'முதல் பக்கம்',
  11453. next: 'அடுத்த பக்கம்',
  11454. previous: 'முந்தைய பக்கம் ',
  11455. last: 'இறுதி பக்கம்'
  11456. },
  11457. menu: {
  11458. text: 'பத்திகளை தேர்ந்தெடு:'
  11459. },
  11460. sort: {
  11461. ascending: 'மேலிருந்து கீழாக',
  11462. descending: 'கீழிருந்து மேலாக',
  11463. remove: 'வரிசையை நீக்கு'
  11464. },
  11465. column: {
  11466. hide: 'பத்தியை மறைத்து வை '
  11467. },
  11468. aggregation: {
  11469. count: 'மொத்த வரிகள்:',
  11470. sum: 'மொத்தம்: ',
  11471. avg: 'சராசரி: ',
  11472. min: 'குறைந்தபட்ச: ',
  11473. max: 'அதிகபட்ச: '
  11474. },
  11475. pinning: {
  11476. pinLeft: 'இடதுபுறமாக தைக்க ',
  11477. pinRight: 'வலதுபுறமாக தைக்க',
  11478. unpin: 'பிரி'
  11479. },
  11480. gridMenu: {
  11481. columns: 'பத்திகள்:',
  11482. importerTitle: 'கோப்பு : படித்தல்',
  11483. exporterAllAsCsv: 'எல்லா தரவுகளையும் கோப்பாக்கு: csv',
  11484. exporterVisibleAsCsv: 'இருக்கும் தரவுகளை கோப்பாக்கு: csv',
  11485. exporterSelectedAsCsv: 'தேர்ந்தெடுத்த தரவுகளை கோப்பாக்கு: csv',
  11486. exporterAllAsPdf: 'எல்லா தரவுகளையும் கோப்பாக்கு: pdf',
  11487. exporterVisibleAsPdf: 'இருக்கும் தரவுகளை கோப்பாக்கு: pdf',
  11488. exporterSelectedAsPdf: 'தேர்ந்தெடுத்த தரவுகளை கோப்பாக்கு: pdf',
  11489. clearAllFilters: 'Clear all filters'
  11490. },
  11491. importer: {
  11492. noHeaders: 'பத்தியின் தலைப்புகளை பெற இயலவில்லை, கோப்பிற்கு தலைப்பு உள்ளதா?',
  11493. noObjects: 'இலக்குகளை உருவாக்க முடியவில்லை, கோப்பில் தலைப்புகளை தவிர தரவு ஏதேனும் உள்ளதா? ',
  11494. invalidCsv: 'சரிவர நடைமுறை படுத்த இயலவில்லை, கோப்பு சரிதானா? - csv',
  11495. invalidJson: 'சரிவர நடைமுறை படுத்த இயலவில்லை, கோப்பு சரிதானா? - json',
  11496. jsonNotArray: 'படித்த கோப்பில் வரிசைகள் உள்ளது, நடைமுறை ரத்து செய் : json'
  11497. },
  11498. pagination: {
  11499. sizes: 'உருப்படிகள் / பக்கம்',
  11500. totalItems: 'உருப்படிகள் '
  11501. },
  11502. grouping: {
  11503. group: 'குழு',
  11504. ungroup: 'பிரி',
  11505. aggregate_count: 'மதிப்பீட்டு : எண்ணு',
  11506. aggregate_sum: 'மதிப்பீட்டு : கூட்டல்',
  11507. aggregate_max: 'மதிப்பீட்டு : அதிகபட்சம்',
  11508. aggregate_min: 'மதிப்பீட்டு : குறைந்தபட்சம்',
  11509. aggregate_avg: 'மதிப்பீட்டு : சராசரி',
  11510. aggregate_remove: 'மதிப்பீட்டு : நீக்கு'
  11511. }
  11512. });
  11513. return $delegate;
  11514. }]);
  11515. }]);
  11516. })();
  11517. /**
  11518. * @ngdoc overview
  11519. * @name ui.grid.i18n
  11520. * @description
  11521. *
  11522. * # ui.grid.i18n
  11523. * This module provides i18n functions to ui.grid and any application that wants to use it
  11524. *
  11525. * <div doc-module-components="ui.grid.i18n"></div>
  11526. */
  11527. (function() {
  11528. var DIRECTIVE_ALIASES = ['uiT', 'uiTranslate'];
  11529. var FILTER_ALIASES = ['t', 'uiTranslate'];
  11530. var module = angular.module('ui.grid.i18n');
  11531. /**
  11532. * @ngdoc object
  11533. * @name ui.grid.i18n.constant:i18nConstants
  11534. *
  11535. * @description constants available in i18n module
  11536. */
  11537. module.constant('i18nConstants', {
  11538. MISSING: '[MISSING]',
  11539. UPDATE_EVENT: '$uiI18n',
  11540. LOCALE_DIRECTIVE_ALIAS: 'uiI18n',
  11541. // default to english
  11542. DEFAULT_LANG: 'en'
  11543. });
  11544. // module.config(['$provide', function($provide) {
  11545. // $provide.decorator('i18nService', ['$delegate', function($delegate) {}])}]);
  11546. /**
  11547. * @ngdoc service
  11548. * @name ui.grid.i18n.service:i18nService
  11549. *
  11550. * @description Services for i18n
  11551. */
  11552. module.service('i18nService', ['$log', 'i18nConstants', '$rootScope',
  11553. function($log, i18nConstants, $rootScope) {
  11554. var langCache = {
  11555. _langs: {},
  11556. current: null,
  11557. get: function(lang) {
  11558. return this._langs[lang.toLowerCase()];
  11559. },
  11560. add: function(lang, strings) {
  11561. var lower = lang.toLowerCase();
  11562. if (!this._langs[lower]) {
  11563. this._langs[lower] = {};
  11564. }
  11565. angular.extend(this._langs[lower], strings);
  11566. },
  11567. getAllLangs: function() {
  11568. var langs = [];
  11569. if (!this._langs) {
  11570. return langs;
  11571. }
  11572. for (var key in this._langs) {
  11573. langs.push(key);
  11574. }
  11575. return langs;
  11576. },
  11577. setCurrent: function(lang) {
  11578. this.current = lang.toLowerCase();
  11579. },
  11580. getCurrentLang: function() {
  11581. return this.current;
  11582. }
  11583. };
  11584. var service = {
  11585. /**
  11586. * @ngdoc service
  11587. * @name add
  11588. * @methodOf ui.grid.i18n.service:i18nService
  11589. * @description Adds the languages and strings to the cache. Decorate this service to
  11590. * add more translation strings
  11591. * @param {string} lang language to add
  11592. * @param {object} stringMaps of strings to add grouped by property names
  11593. * @example
  11594. * <pre>
  11595. * i18nService.add('en', {
  11596. * aggregate: {
  11597. * label1: 'items',
  11598. * label2: 'some more items'
  11599. * }
  11600. * },
  11601. * groupPanel: {
  11602. * description: 'Drag a column header here and drop it to group by that column.'
  11603. * }
  11604. * }
  11605. * </pre>
  11606. */
  11607. add: function(langs, stringMaps) {
  11608. if (typeof(langs) === 'object') {
  11609. angular.forEach(langs, function(lang) {
  11610. if (lang) {
  11611. langCache.add(lang, stringMaps);
  11612. }
  11613. });
  11614. } else {
  11615. langCache.add(langs, stringMaps);
  11616. }
  11617. },
  11618. /**
  11619. * @ngdoc service
  11620. * @name getAllLangs
  11621. * @methodOf ui.grid.i18n.service:i18nService
  11622. * @description return all currently loaded languages
  11623. * @returns {array} string
  11624. */
  11625. getAllLangs: function() {
  11626. return langCache.getAllLangs();
  11627. },
  11628. /**
  11629. * @ngdoc service
  11630. * @name get
  11631. * @methodOf ui.grid.i18n.service:i18nService
  11632. * @description return all currently loaded languages
  11633. * @param {string} lang to return. If not specified, returns current language
  11634. * @returns {object} the translation string maps for the language
  11635. */
  11636. get: function(lang) {
  11637. var language = lang ? lang : service.getCurrentLang();
  11638. return langCache.get(language);
  11639. },
  11640. /**
  11641. * @ngdoc service
  11642. * @name getSafeText
  11643. * @methodOf ui.grid.i18n.service:i18nService
  11644. * @description returns the text specified in the path or a Missing text if text is not found
  11645. * @param {string} path property path to use for retrieving text from string map
  11646. * @param {string} lang to return. If not specified, returns current language
  11647. * @returns {object} the translation for the path
  11648. * @example
  11649. * <pre>
  11650. * i18nService.getSafeText('sort.ascending')
  11651. * </pre>
  11652. */
  11653. getSafeText: function(path, lang) {
  11654. var language = lang ? lang : service.getCurrentLang();
  11655. var trans = langCache.get(language);
  11656. if (!trans) {
  11657. return i18nConstants.MISSING;
  11658. }
  11659. var paths = path.split('.');
  11660. var current = trans;
  11661. for (var i = 0; i < paths.length; ++i) {
  11662. if (current[paths[i]] === undefined || current[paths[i]] === null) {
  11663. return i18nConstants.MISSING;
  11664. } else {
  11665. current = current[paths[i]];
  11666. }
  11667. }
  11668. return current;
  11669. },
  11670. /**
  11671. * @ngdoc service
  11672. * @name setCurrentLang
  11673. * @methodOf ui.grid.i18n.service:i18nService
  11674. * @description sets the current language to use in the application
  11675. * $broadcasts the Update_Event on the $rootScope
  11676. * @param {string} lang to set
  11677. * @example
  11678. * <pre>
  11679. * i18nService.setCurrentLang('fr');
  11680. * </pre>
  11681. */
  11682. setCurrentLang: function(lang) {
  11683. if (lang) {
  11684. langCache.setCurrent(lang);
  11685. $rootScope.$broadcast(i18nConstants.UPDATE_EVENT);
  11686. }
  11687. },
  11688. /**
  11689. * @ngdoc service
  11690. * @name getCurrentLang
  11691. * @methodOf ui.grid.i18n.service:i18nService
  11692. * @description returns the current language used in the application
  11693. */
  11694. getCurrentLang: function() {
  11695. var lang = langCache.getCurrentLang();
  11696. if (!lang) {
  11697. lang = i18nConstants.DEFAULT_LANG;
  11698. langCache.setCurrent(lang);
  11699. }
  11700. return lang;
  11701. }
  11702. };
  11703. return service;
  11704. }
  11705. ]);
  11706. var localeDirective = function(i18nService, i18nConstants) {
  11707. return {
  11708. compile: function() {
  11709. return {
  11710. pre: function($scope, $elm, $attrs) {
  11711. var alias = i18nConstants.LOCALE_DIRECTIVE_ALIAS;
  11712. // check for watchable property
  11713. var lang = $scope.$eval($attrs[alias]);
  11714. if (lang) {
  11715. $scope.$watch($attrs[alias], function() {
  11716. i18nService.setCurrentLang(lang);
  11717. });
  11718. } else if ($attrs.$$observers) {
  11719. $attrs.$observe(alias, function() {
  11720. i18nService.setCurrentLang($attrs[alias] || i18nConstants.DEFAULT_LANG);
  11721. });
  11722. }
  11723. }
  11724. };
  11725. }
  11726. };
  11727. };
  11728. module.directive('uiI18n', ['i18nService', 'i18nConstants', localeDirective]);
  11729. // directive syntax
  11730. var uitDirective = function($parse, i18nService, i18nConstants) {
  11731. return {
  11732. restrict: 'EA',
  11733. compile: function() {
  11734. return {
  11735. pre: function($scope, $elm, $attrs) {
  11736. var alias1 = DIRECTIVE_ALIASES[0],
  11737. alias2 = DIRECTIVE_ALIASES[1];
  11738. var token = $attrs[alias1] || $attrs[alias2] || $elm.html();
  11739. var missing = i18nConstants.MISSING + token;
  11740. var observer;
  11741. if ($attrs.$$observers) {
  11742. var prop = $attrs[alias1] ? alias1 : alias2;
  11743. observer = $attrs.$observe(prop, function(result) {
  11744. if (result) {
  11745. $elm.html($parse(result)(i18nService.getCurrentLang()) || missing);
  11746. }
  11747. });
  11748. }
  11749. var getter = $parse(token);
  11750. var listener = $scope.$on(i18nConstants.UPDATE_EVENT, function(evt) {
  11751. if (observer) {
  11752. observer($attrs[alias1] || $attrs[alias2]);
  11753. } else {
  11754. // set text based on i18n current language
  11755. $elm.html(getter(i18nService.get()) || missing);
  11756. }
  11757. });
  11758. $scope.$on('$destroy', listener);
  11759. $elm.html(getter(i18nService.get()) || missing);
  11760. }
  11761. };
  11762. }
  11763. };
  11764. };
  11765. angular.forEach(DIRECTIVE_ALIASES, function(alias) {
  11766. module.directive(alias, ['$parse', 'i18nService', 'i18nConstants', uitDirective]);
  11767. });
  11768. // optional filter syntax
  11769. var uitFilter = function($parse, i18nService, i18nConstants) {
  11770. return function(data) {
  11771. var getter = $parse(data);
  11772. // set text based on i18n current language
  11773. return getter(i18nService.get()) || i18nConstants.MISSING + data;
  11774. };
  11775. };
  11776. angular.forEach(FILTER_ALIASES, function(alias) {
  11777. module.filter(alias, ['$parse', 'i18nService', 'i18nConstants', uitFilter]);
  11778. });
  11779. })();
  11780. (function() {
  11781. angular.module('ui.grid').config(['$provide', function($provide) {
  11782. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11783. $delegate.add('zh-cn', {
  11784. headerCell: {
  11785. aria: {
  11786. defaultFilterLabel: '列过滤器',
  11787. removeFilter: '移除过滤器',
  11788. columnMenuButtonLabel: '列菜单'
  11789. },
  11790. priority: '优先级:',
  11791. filterLabel: "列过滤器: "
  11792. },
  11793. aggregate: {
  11794. label: '行'
  11795. },
  11796. groupPanel: {
  11797. description: '拖曳表头到此处进行分组'
  11798. },
  11799. search: {
  11800. placeholder: '查找',
  11801. showingItems: '已显示行数:',
  11802. selectedItems: '已选择行数:',
  11803. totalItems: '总行数:',
  11804. size: '每页显示行数:',
  11805. first: '首页',
  11806. next: '下一页',
  11807. previous: '上一页',
  11808. last: '末页'
  11809. },
  11810. menu: {
  11811. text: '选择列:'
  11812. },
  11813. sort: {
  11814. ascending: '升序',
  11815. descending: '降序',
  11816. none: '无序',
  11817. remove: '取消排序'
  11818. },
  11819. column: {
  11820. hide: '隐藏列'
  11821. },
  11822. aggregation: {
  11823. count: '计数:',
  11824. sum: '求和:',
  11825. avg: '均值:',
  11826. min: '最小值:',
  11827. max: '最大值:'
  11828. },
  11829. pinning: {
  11830. pinLeft: '左侧固定',
  11831. pinRight: '右侧固定',
  11832. unpin: '取消固定'
  11833. },
  11834. columnMenu: {
  11835. close: '关闭'
  11836. },
  11837. gridMenu: {
  11838. aria: {
  11839. buttonLabel: '表格菜单'
  11840. },
  11841. columns: '列:',
  11842. importerTitle: '导入文件',
  11843. exporterAllAsCsv: '导出全部数据到CSV',
  11844. exporterVisibleAsCsv: '导出可见数据到CSV',
  11845. exporterSelectedAsCsv: '导出已选数据到CSV',
  11846. exporterAllAsPdf: '导出全部数据到PDF',
  11847. exporterVisibleAsPdf: '导出可见数据到PDF',
  11848. exporterSelectedAsPdf: '导出已选数据到PDF',
  11849. clearAllFilters: '清除所有过滤器'
  11850. },
  11851. importer: {
  11852. noHeaders: '无法获取列名,确定文件包含表头?',
  11853. noObjects: '无法获取数据,确定文件包含数据?',
  11854. invalidCsv: '无法处理文件,确定是合法的CSV文件?',
  11855. invalidJson: '无法处理文件,确定是合法的JSON文件?',
  11856. jsonNotArray: '导入的文件不是JSON数组!'
  11857. },
  11858. pagination: {
  11859. aria: {
  11860. pageToFirst: '第一页',
  11861. pageBack: '上一页',
  11862. pageSelected: '当前页',
  11863. pageForward: '下一页',
  11864. pageToLast: '最后一页'
  11865. },
  11866. sizes: '行每页',
  11867. totalItems: '行',
  11868. through: '至',
  11869. of: '共'
  11870. },
  11871. grouping: {
  11872. group: '分组',
  11873. ungroup: '取消分组',
  11874. aggregate_count: '合计: 计数',
  11875. aggregate_sum: '合计: 求和',
  11876. aggregate_max: '合计: 最大',
  11877. aggregate_min: '合计: 最小',
  11878. aggregate_avg: '合计: 平均',
  11879. aggregate_remove: '合计: 移除'
  11880. }
  11881. });
  11882. return $delegate;
  11883. }]);
  11884. }]);
  11885. })();
  11886. (function() {
  11887. angular.module('ui.grid').config(['$provide', function($provide) {
  11888. $provide.decorator('i18nService', ['$delegate', function($delegate) {
  11889. $delegate.add('zh-tw', {
  11890. aggregate: {
  11891. label: '行'
  11892. },
  11893. groupPanel: {
  11894. description: '拖曳表頭到此處進行分組'
  11895. },
  11896. search: {
  11897. placeholder: '查找',
  11898. showingItems: '已顯示行數:',
  11899. selectedItems: '已選擇行數:',
  11900. totalItems: '總行數:',
  11901. size: '每頁顯示行數:',
  11902. first: '首頁',
  11903. next: '下壹頁',
  11904. previous: '上壹頁',
  11905. last: '末頁'
  11906. },
  11907. menu: {
  11908. text: '選擇列:'
  11909. },
  11910. sort: {
  11911. ascending: '升序',
  11912. descending: '降序',
  11913. remove: '取消排序'
  11914. },
  11915. column: {
  11916. hide: '隱藏列'
  11917. },
  11918. aggregation: {
  11919. count: '計數:',
  11920. sum: '求和:',
  11921. avg: '均值:',
  11922. min: '最小值:',
  11923. max: '最大值:'
  11924. },
  11925. pinning: {
  11926. pinLeft: '左側固定',
  11927. pinRight: '右側固定',
  11928. unpin: '取消固定'
  11929. },
  11930. gridMenu: {
  11931. columns: '列:',
  11932. importerTitle: '導入文件',
  11933. exporterAllAsCsv: '導出全部數據到CSV',
  11934. exporterVisibleAsCsv: '導出可見數據到CSV',
  11935. exporterSelectedAsCsv: '導出已選數據到CSV',
  11936. exporterAllAsPdf: '導出全部數據到PDF',
  11937. exporterVisibleAsPdf: '導出可見數據到PDF',
  11938. exporterSelectedAsPdf: '導出已選數據到PDF',
  11939. clearAllFilters: '清除所有过滤器'
  11940. },
  11941. importer: {
  11942. noHeaders: '無法獲取列名,確定文件包含表頭?',
  11943. noObjects: '無法獲取數據,確定文件包含數據?',
  11944. invalidCsv: '無法處理文件,確定是合法的CSV文件?',
  11945. invalidJson: '無法處理文件,確定是合法的JSON文件?',
  11946. jsonNotArray: '導入的文件不是JSON數組!'
  11947. },
  11948. pagination: {
  11949. sizes: '行每頁',
  11950. totalItems: '行'
  11951. }
  11952. });
  11953. return $delegate;
  11954. }]);
  11955. }]);
  11956. })();
  11957. (function() {
  11958. 'use strict';
  11959. /**
  11960. * @ngdoc overview
  11961. * @name ui.grid.autoResize
  11962. *
  11963. * @description
  11964. *
  11965. * #ui.grid.autoResize
  11966. *
  11967. * <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>
  11968. *
  11969. * This module provides auto-resizing functionality to UI-Grid.
  11970. */
  11971. var module = angular.module('ui.grid.autoResize', ['ui.grid']);
  11972. module.directive('uiGridAutoResize', ['$timeout', 'gridUtil', function($timeout, gridUtil) {
  11973. return {
  11974. require: 'uiGrid',
  11975. scope: false,
  11976. link: function($scope, $elm, $attrs, uiGridCtrl) {
  11977. var prevGridWidth, prevGridHeight;
  11978. function getDimensions() {
  11979. prevGridHeight = gridUtil.elementHeight($elm);
  11980. prevGridWidth = gridUtil.elementWidth($elm);
  11981. }
  11982. // Initialize the dimensions
  11983. getDimensions();
  11984. var resizeTimeoutId;
  11985. function startTimeout() {
  11986. clearTimeout(resizeTimeoutId);
  11987. resizeTimeoutId = setTimeout(function() {
  11988. var newGridHeight = gridUtil.elementHeight($elm);
  11989. var newGridWidth = gridUtil.elementWidth($elm);
  11990. if (newGridHeight !== prevGridHeight || newGridWidth !== prevGridWidth) {
  11991. uiGridCtrl.grid.gridHeight = newGridHeight;
  11992. uiGridCtrl.grid.gridWidth = newGridWidth;
  11993. $scope.$apply(function() {
  11994. uiGridCtrl.grid.refresh()
  11995. .then(function() {
  11996. getDimensions();
  11997. startTimeout();
  11998. });
  11999. });
  12000. } else {
  12001. startTimeout();
  12002. }
  12003. }, 250);
  12004. }
  12005. startTimeout();
  12006. $scope.$on('$destroy', function() {
  12007. clearTimeout(resizeTimeoutId);
  12008. });
  12009. }
  12010. };
  12011. }]);
  12012. })();
  12013. (function() {
  12014. 'use strict';
  12015. /**
  12016. * @ngdoc overview
  12017. * @name ui.grid.cellNav
  12018. *
  12019. * @description
  12020. #ui.grid.cellNav
  12021. <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>
  12022. This module provides auto-resizing functionality to UI-Grid.
  12023. */
  12024. var module = angular.module('ui.grid.cellNav', ['ui.grid']);
  12025. /**
  12026. * @ngdoc object
  12027. * @name ui.grid.cellNav.constant:uiGridCellNavConstants
  12028. *
  12029. * @description constants available in cellNav
  12030. */
  12031. module.constant('uiGridCellNavConstants', {
  12032. FEATURE_NAME: 'gridCellNav',
  12033. CELL_NAV_EVENT: 'cellNav',
  12034. direction: { LEFT: 0, RIGHT: 1, UP: 2, DOWN: 3, PG_UP: 4, PG_DOWN: 5 },
  12035. EVENT_TYPE: {
  12036. KEYDOWN: 0,
  12037. CLICK: 1,
  12038. CLEAR: 2
  12039. }
  12040. });
  12041. module.factory('uiGridCellNavFactory', ['gridUtil', 'uiGridConstants', 'uiGridCellNavConstants', 'GridRowColumn', '$q',
  12042. function(gridUtil, uiGridConstants, uiGridCellNavConstants, GridRowColumn, $q) {
  12043. /**
  12044. * @ngdoc object
  12045. * @name ui.grid.cellNav.object:CellNav
  12046. * @description returns a CellNav prototype function
  12047. * @param {object} rowContainer container for rows
  12048. * @param {object} colContainer parent column container
  12049. * @param {object} leftColContainer column container to the left of parent
  12050. * @param {object} rightColContainer column container to the right of parent
  12051. */
  12052. var UiGridCellNav = function UiGridCellNav(rowContainer, colContainer, leftColContainer, rightColContainer) {
  12053. this.rows = rowContainer.visibleRowCache;
  12054. this.columns = colContainer.visibleColumnCache;
  12055. this.leftColumns = leftColContainer ? leftColContainer.visibleColumnCache : [];
  12056. this.rightColumns = rightColContainer ? rightColContainer.visibleColumnCache : [];
  12057. this.bodyContainer = rowContainer;
  12058. };
  12059. /** returns focusable columns of all containers */
  12060. UiGridCellNav.prototype.getFocusableCols = function() {
  12061. var allColumns = this.leftColumns.concat(this.columns, this.rightColumns);
  12062. return allColumns.filter(function(col) {
  12063. return col.colDef.allowCellFocus;
  12064. });
  12065. };
  12066. /**
  12067. * @ngdoc object
  12068. * @name ui.grid.cellNav.api:GridRow
  12069. *
  12070. * @description GridRow settings for cellNav feature, these are available to be
  12071. * set only internally (for example, by other features)
  12072. */
  12073. /**
  12074. * @ngdoc object
  12075. * @name allowCellFocus
  12076. * @propertyOf ui.grid.cellNav.api:GridRow
  12077. * @description Enable focus on a cell within this row. If set to false then no cells
  12078. * in this row can be focused - group header rows as an example would set this to false.
  12079. * <br/>Defaults to true
  12080. */
  12081. /** returns focusable rows */
  12082. UiGridCellNav.prototype.getFocusableRows = function() {
  12083. return this.rows.filter(function(row) {
  12084. return row.allowCellFocus !== false;
  12085. });
  12086. };
  12087. UiGridCellNav.prototype.getNextRowCol = function(direction, curRow, curCol) {
  12088. switch (direction) {
  12089. case uiGridCellNavConstants.direction.LEFT:
  12090. return this.getRowColLeft(curRow, curCol);
  12091. case uiGridCellNavConstants.direction.RIGHT:
  12092. return this.getRowColRight(curRow, curCol);
  12093. case uiGridCellNavConstants.direction.UP:
  12094. return this.getRowColUp(curRow, curCol);
  12095. case uiGridCellNavConstants.direction.DOWN:
  12096. return this.getRowColDown(curRow, curCol);
  12097. case uiGridCellNavConstants.direction.PG_UP:
  12098. return this.getRowColPageUp(curRow, curCol);
  12099. case uiGridCellNavConstants.direction.PG_DOWN:
  12100. return this.getRowColPageDown(curRow, curCol);
  12101. }
  12102. };
  12103. UiGridCellNav.prototype.initializeSelection = function() {
  12104. var focusableCols = this.getFocusableCols();
  12105. var focusableRows = this.getFocusableRows();
  12106. if (focusableCols.length === 0 || focusableRows.length === 0) {
  12107. return null;
  12108. }
  12109. var curRowIndex = 0;
  12110. var curColIndex = 0;
  12111. return new GridRowColumn(focusableRows[0], focusableCols[0]); //return same row
  12112. };
  12113. UiGridCellNav.prototype.getRowColLeft = function(curRow, curCol) {
  12114. var focusableCols = this.getFocusableCols();
  12115. var focusableRows = this.getFocusableRows();
  12116. var curColIndex = focusableCols.indexOf(curCol);
  12117. var curRowIndex = focusableRows.indexOf(curRow);
  12118. //could not find column in focusable Columns so set it to 1
  12119. if (curColIndex === -1) {
  12120. curColIndex = 1;
  12121. }
  12122. var nextColIndex = curColIndex === 0 ? focusableCols.length - 1 : curColIndex - 1;
  12123. //get column to left
  12124. if (nextColIndex > curColIndex) {
  12125. // On the first row
  12126. // if (curRowIndex === 0 && curColIndex === 0) {
  12127. // return null;
  12128. // }
  12129. if (curRowIndex === 0) {
  12130. return new GridRowColumn(curRow, focusableCols[nextColIndex]); //return same row
  12131. } else {
  12132. //up one row and far right column
  12133. return new GridRowColumn(focusableRows[curRowIndex - 1], focusableCols[nextColIndex]);
  12134. }
  12135. } else {
  12136. return new GridRowColumn(curRow, focusableCols[nextColIndex]);
  12137. }
  12138. };
  12139. UiGridCellNav.prototype.getRowColRight = function(curRow, curCol) {
  12140. var focusableCols = this.getFocusableCols();
  12141. var focusableRows = this.getFocusableRows();
  12142. var curColIndex = focusableCols.indexOf(curCol);
  12143. var curRowIndex = focusableRows.indexOf(curRow);
  12144. //could not find column in focusable Columns so set it to 0
  12145. if (curColIndex === -1) {
  12146. curColIndex = 0;
  12147. }
  12148. var nextColIndex = curColIndex === focusableCols.length - 1 ? 0 : curColIndex + 1;
  12149. if (nextColIndex < curColIndex) {
  12150. if (curRowIndex === focusableRows.length - 1) {
  12151. return new GridRowColumn(curRow, focusableCols[nextColIndex]); //return same row
  12152. } else {
  12153. //down one row and far left column
  12154. return new GridRowColumn(focusableRows[curRowIndex + 1], focusableCols[nextColIndex]);
  12155. }
  12156. } else {
  12157. return new GridRowColumn(curRow, focusableCols[nextColIndex]);
  12158. }
  12159. };
  12160. UiGridCellNav.prototype.getRowColDown = function(curRow, curCol) {
  12161. var focusableCols = this.getFocusableCols();
  12162. var focusableRows = this.getFocusableRows();
  12163. var curColIndex = focusableCols.indexOf(curCol);
  12164. var curRowIndex = focusableRows.indexOf(curRow);
  12165. //could not find column in focusable Columns so set it to 0
  12166. if (curColIndex === -1) {
  12167. curColIndex = 0;
  12168. }
  12169. if (curRowIndex === focusableRows.length - 1) {
  12170. return new GridRowColumn(curRow, focusableCols[curColIndex]); //return same row
  12171. } else {
  12172. //down one row
  12173. return new GridRowColumn(focusableRows[curRowIndex + 1], focusableCols[curColIndex]);
  12174. }
  12175. };
  12176. UiGridCellNav.prototype.getRowColPageDown = function(curRow, curCol) {
  12177. var focusableCols = this.getFocusableCols();
  12178. var focusableRows = this.getFocusableRows();
  12179. var curColIndex = focusableCols.indexOf(curCol);
  12180. var curRowIndex = focusableRows.indexOf(curRow);
  12181. //could not find column in focusable Columns so set it to 0
  12182. if (curColIndex === -1) {
  12183. curColIndex = 0;
  12184. }
  12185. var pageSize = this.bodyContainer.minRowsToRender();
  12186. if (curRowIndex >= focusableRows.length - pageSize) {
  12187. return new GridRowColumn(focusableRows[focusableRows.length - 1], focusableCols[curColIndex]); //return last row
  12188. } else {
  12189. //down one page
  12190. return new GridRowColumn(focusableRows[curRowIndex + pageSize], focusableCols[curColIndex]);
  12191. }
  12192. };
  12193. UiGridCellNav.prototype.getRowColUp = function(curRow, curCol) {
  12194. var focusableCols = this.getFocusableCols();
  12195. var focusableRows = this.getFocusableRows();
  12196. var curColIndex = focusableCols.indexOf(curCol);
  12197. var curRowIndex = focusableRows.indexOf(curRow);
  12198. //could not find column in focusable Columns so set it to 0
  12199. if (curColIndex === -1) {
  12200. curColIndex = 0;
  12201. }
  12202. if (curRowIndex === 0) {
  12203. return new GridRowColumn(curRow, focusableCols[curColIndex]); //return same row
  12204. } else {
  12205. //up one row
  12206. return new GridRowColumn(focusableRows[curRowIndex - 1], focusableCols[curColIndex]);
  12207. }
  12208. };
  12209. UiGridCellNav.prototype.getRowColPageUp = function(curRow, curCol) {
  12210. var focusableCols = this.getFocusableCols();
  12211. var focusableRows = this.getFocusableRows();
  12212. var curColIndex = focusableCols.indexOf(curCol);
  12213. var curRowIndex = focusableRows.indexOf(curRow);
  12214. //could not find column in focusable Columns so set it to 0
  12215. if (curColIndex === -1) {
  12216. curColIndex = 0;
  12217. }
  12218. var pageSize = this.bodyContainer.minRowsToRender();
  12219. if (curRowIndex - pageSize < 0) {
  12220. return new GridRowColumn(focusableRows[0], focusableCols[curColIndex]); //return first row
  12221. } else {
  12222. //up one page
  12223. return new GridRowColumn(focusableRows[curRowIndex - pageSize], focusableCols[curColIndex]);
  12224. }
  12225. };
  12226. return UiGridCellNav;
  12227. }
  12228. ]);
  12229. /**
  12230. * @ngdoc service
  12231. * @name ui.grid.cellNav.service:uiGridCellNavService
  12232. *
  12233. * @description Services for cell navigation features. If you don't like the key maps we use,
  12234. * or the direction cells navigation, override with a service decorator (see angular docs)
  12235. */
  12236. module.service('uiGridCellNavService', ['gridUtil', 'uiGridConstants', 'uiGridCellNavConstants', '$q', 'uiGridCellNavFactory', 'GridRowColumn', 'ScrollEvent',
  12237. function(gridUtil, uiGridConstants, uiGridCellNavConstants, $q, UiGridCellNav, GridRowColumn, ScrollEvent) {
  12238. var service = {
  12239. initializeGrid: function(grid) {
  12240. grid.registerColumnBuilder(service.cellNavColumnBuilder);
  12241. /**
  12242. * @ngdoc object
  12243. * @name ui.grid.cellNav:Grid.cellNav
  12244. * @description cellNav properties added to grid class
  12245. */
  12246. grid.cellNav = {};
  12247. grid.cellNav.lastRowCol = null;
  12248. grid.cellNav.focusedCells = [];
  12249. service.defaultGridOptions(grid.options);
  12250. /**
  12251. * @ngdoc object
  12252. * @name ui.grid.cellNav.api:PublicApi
  12253. *
  12254. * @description Public Api for cellNav feature
  12255. */
  12256. var publicApi = {
  12257. events: {
  12258. cellNav: {
  12259. /**
  12260. * @ngdoc event
  12261. * @name navigate
  12262. * @eventOf ui.grid.cellNav.api:PublicApi
  12263. * @description raised when the active cell is changed
  12264. * <pre>
  12265. * gridApi.cellNav.on.navigate(scope,function(newRowcol, oldRowCol){})
  12266. * </pre>
  12267. * @param {object} newRowCol new position
  12268. * @param {object} oldRowCol old position
  12269. */
  12270. navigate: function(newRowCol, oldRowCol) {},
  12271. /**
  12272. * @ngdoc event
  12273. * @name viewPortKeyDown
  12274. * @eventOf ui.grid.cellNav.api:PublicApi
  12275. * @description is raised when the viewPort receives a keyDown event. Cells never get focus in uiGrid
  12276. * due to the difficulties of setting focus on a cell that is not visible in the viewport. Use this
  12277. * event whenever you need a keydown event on a cell
  12278. * <br/>
  12279. * @param {object} event keydown event
  12280. * @param {object} rowCol current rowCol position
  12281. */
  12282. viewPortKeyDown: function(event, rowCol) {},
  12283. /**
  12284. * @ngdoc event
  12285. * @name viewPortKeyPress
  12286. * @eventOf ui.grid.cellNav.api:PublicApi
  12287. * @description is raised when the viewPort receives a keyPress event. Cells never get focus in uiGrid
  12288. * due to the difficulties of setting focus on a cell that is not visible in the viewport. Use this
  12289. * event whenever you need a keypress event on a cell
  12290. * <br/>
  12291. * @param {object} event keypress event
  12292. * @param {object} rowCol current rowCol position
  12293. */
  12294. viewPortKeyPress: function(event, rowCol) {}
  12295. }
  12296. },
  12297. methods: {
  12298. cellNav: {
  12299. /**
  12300. * @ngdoc function
  12301. * @name scrollToFocus
  12302. * @methodOf ui.grid.cellNav.api:PublicApi
  12303. * @description brings the specified row and column into view, and sets focus
  12304. * to that cell
  12305. * @param {object} rowEntity gridOptions.data[] array instance to make visible and set focus
  12306. * @param {object} colDef to make visible and set focus
  12307. * @returns {promise} a promise that is resolved after any scrolling is finished
  12308. */
  12309. scrollToFocus: function(rowEntity, colDef) {
  12310. return service.scrollToFocus(grid, rowEntity, colDef);
  12311. },
  12312. /**
  12313. * @ngdoc function
  12314. * @name getFocusedCell
  12315. * @methodOf ui.grid.cellNav.api:PublicApi
  12316. * @description returns the current (or last if Grid does not have focus) focused row and column
  12317. * <br> value is null if no selection has occurred
  12318. */
  12319. getFocusedCell: function() {
  12320. return grid.cellNav.lastRowCol;
  12321. },
  12322. /**
  12323. * @ngdoc function
  12324. * @name getCurrentSelection
  12325. * @methodOf ui.grid.cellNav.api:PublicApi
  12326. * @description returns an array containing the current selection
  12327. * <br> array is empty if no selection has occurred
  12328. */
  12329. getCurrentSelection: function() {
  12330. return grid.cellNav.focusedCells;
  12331. },
  12332. /**
  12333. * @ngdoc function
  12334. * @name rowColSelectIndex
  12335. * @methodOf ui.grid.cellNav.api:PublicApi
  12336. * @description returns the index in the order in which the GridRowColumn was selected, returns -1 if the GridRowColumn
  12337. * isn't selected
  12338. * @param {object} rowCol the rowCol to evaluate
  12339. */
  12340. rowColSelectIndex: function(rowCol) {
  12341. //return gridUtil.arrayContainsObjectWithProperty(grid.cellNav.focusedCells, 'col.uid', rowCol.col.uid) &&
  12342. var index = -1;
  12343. for (var i = 0; i < grid.cellNav.focusedCells.length; i++) {
  12344. if (grid.cellNav.focusedCells[i].col.uid === rowCol.col.uid &&
  12345. grid.cellNav.focusedCells[i].row.uid === rowCol.row.uid) {
  12346. index = i;
  12347. break;
  12348. }
  12349. }
  12350. return index;
  12351. }
  12352. }
  12353. }
  12354. };
  12355. grid.api.registerEventsFromObject(publicApi.events);
  12356. grid.api.registerMethodsFromObject(publicApi.methods);
  12357. },
  12358. defaultGridOptions: function(gridOptions) {
  12359. /**
  12360. * @ngdoc object
  12361. * @name ui.grid.cellNav.api:GridOptions
  12362. *
  12363. * @description GridOptions for cellNav feature, these are available to be
  12364. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  12365. */
  12366. /**
  12367. * @ngdoc object
  12368. * @name modifierKeysToMultiSelectCells
  12369. * @propertyOf ui.grid.cellNav.api:GridOptions
  12370. * @description Enable multiple cell selection only when using the ctrlKey or shiftKey.
  12371. * <br/>Defaults to false
  12372. */
  12373. gridOptions.modifierKeysToMultiSelectCells = gridOptions.modifierKeysToMultiSelectCells === true;
  12374. },
  12375. /**
  12376. * @ngdoc service
  12377. * @name decorateRenderContainers
  12378. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12379. * @description decorates grid renderContainers with cellNav functions
  12380. */
  12381. decorateRenderContainers: function(grid) {
  12382. var rightContainer = grid.hasRightContainer() ? grid.renderContainers.right : null;
  12383. var leftContainer = grid.hasLeftContainer() ? grid.renderContainers.left : null;
  12384. if (leftContainer !== null) {
  12385. grid.renderContainers.left.cellNav = new UiGridCellNav(grid.renderContainers.body, leftContainer, rightContainer, grid.renderContainers.body);
  12386. }
  12387. if (rightContainer !== null) {
  12388. grid.renderContainers.right.cellNav = new UiGridCellNav(grid.renderContainers.body, rightContainer, grid.renderContainers.body, leftContainer);
  12389. }
  12390. grid.renderContainers.body.cellNav = new UiGridCellNav(grid.renderContainers.body, grid.renderContainers.body, leftContainer, rightContainer);
  12391. },
  12392. /**
  12393. * @ngdoc service
  12394. * @name getDirection
  12395. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12396. * @description determines which direction to for a given keyDown event
  12397. * @returns {uiGridCellNavConstants.direction} direction
  12398. */
  12399. getDirection: function(evt) {
  12400. if (evt.keyCode === uiGridConstants.keymap.LEFT ||
  12401. (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey)) {
  12402. return uiGridCellNavConstants.direction.LEFT;
  12403. }
  12404. if (evt.keyCode === uiGridConstants.keymap.RIGHT ||
  12405. evt.keyCode === uiGridConstants.keymap.TAB) {
  12406. return uiGridCellNavConstants.direction.RIGHT;
  12407. }
  12408. if (evt.keyCode === uiGridConstants.keymap.UP ||
  12409. (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey)) {
  12410. return uiGridCellNavConstants.direction.UP;
  12411. }
  12412. if (evt.keyCode === uiGridConstants.keymap.PG_UP) {
  12413. return uiGridCellNavConstants.direction.PG_UP;
  12414. }
  12415. if (evt.keyCode === uiGridConstants.keymap.DOWN ||
  12416. evt.keyCode === uiGridConstants.keymap.ENTER && !(evt.ctrlKey || evt.altKey)) {
  12417. return uiGridCellNavConstants.direction.DOWN;
  12418. }
  12419. if (evt.keyCode === uiGridConstants.keymap.PG_DOWN) {
  12420. return uiGridCellNavConstants.direction.PG_DOWN;
  12421. }
  12422. return null;
  12423. },
  12424. /**
  12425. * @ngdoc service
  12426. * @name cellNavColumnBuilder
  12427. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12428. * @description columnBuilder function that adds cell navigation properties to grid column
  12429. * @returns {promise} promise that will load any needed templates when resolved
  12430. */
  12431. cellNavColumnBuilder: function(colDef, col, gridOptions) {
  12432. var promises = [];
  12433. /**
  12434. * @ngdoc object
  12435. * @name ui.grid.cellNav.api:ColumnDef
  12436. *
  12437. * @description Column Definitions for cellNav feature, these are available to be
  12438. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  12439. */
  12440. /**
  12441. * @ngdoc object
  12442. * @name allowCellFocus
  12443. * @propertyOf ui.grid.cellNav.api:ColumnDef
  12444. * @description Enable focus on a cell within this column.
  12445. * <br/>Defaults to true
  12446. */
  12447. colDef.allowCellFocus = colDef.allowCellFocus === undefined ? true : colDef.allowCellFocus;
  12448. return $q.all(promises);
  12449. },
  12450. /**
  12451. * @ngdoc method
  12452. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12453. * @name scrollToFocus
  12454. * @description Scroll the grid such that the specified
  12455. * row and column is in view, and set focus to the cell in that row and column
  12456. * @param {Grid} grid the grid you'd like to act upon, usually available
  12457. * from gridApi.grid
  12458. * @param {object} rowEntity gridOptions.data[] array instance to make visible and set focus to
  12459. * @param {object} colDef to make visible and set focus to
  12460. * @returns {promise} a promise that is resolved after any scrolling is finished
  12461. */
  12462. scrollToFocus: function(grid, rowEntity, colDef) {
  12463. var gridRow = null,
  12464. gridCol = null;
  12465. if (typeof(rowEntity) !== 'undefined' && rowEntity !== null) {
  12466. gridRow = grid.getRow(rowEntity);
  12467. }
  12468. if (typeof(colDef) !== 'undefined' && colDef !== null) {
  12469. gridCol = grid.getColumn(colDef.name ? colDef.name : colDef.field);
  12470. }
  12471. return grid.api.core.scrollToIfNecessary(gridRow, gridCol).then(function() {
  12472. var rowCol = { row: gridRow, col: gridCol };
  12473. // Broadcast the navigation
  12474. if (gridRow !== null && gridCol !== null) {
  12475. grid.cellNav.broadcastCellNav(rowCol);
  12476. }
  12477. });
  12478. },
  12479. /**
  12480. * @ngdoc method
  12481. * @methodOf ui.grid.cellNav.service:uiGridCellNavService
  12482. * @name getLeftWidth
  12483. * @description Get the current drawn width of the columns in the
  12484. * grid up to the numbered column, and add an apportionment for the
  12485. * column that we're on. So if we are on column 0, we want to scroll
  12486. * 0% (i.e. exclude this column from calc). If we're on the last column
  12487. * we want to scroll to 100% (i.e. include this column in the calc). So
  12488. * we include (thisColIndex / totalNumberCols) % of this column width
  12489. * @param {Grid} grid the grid you'd like to act upon, usually available
  12490. * from gridApi.grid
  12491. * @param {gridCol} upToCol the column to total up to and including
  12492. */
  12493. getLeftWidth: function(grid, upToCol) {
  12494. var width = 0;
  12495. if (!upToCol) {
  12496. return width;
  12497. }
  12498. var lastIndex = grid.renderContainers.body.visibleColumnCache.indexOf(upToCol);
  12499. // total column widths up-to but not including the passed in column
  12500. grid.renderContainers.body.visibleColumnCache.forEach(function(col, index) {
  12501. if (index < lastIndex) {
  12502. width += col.drawnWidth;
  12503. }
  12504. });
  12505. // pro-rata the final column based on % of total columns.
  12506. var percentage = lastIndex === 0 ? 0 : (lastIndex + 1) / grid.renderContainers.body.visibleColumnCache.length;
  12507. width += upToCol.drawnWidth * percentage;
  12508. return width;
  12509. }
  12510. };
  12511. return service;
  12512. }
  12513. ]);
  12514. /**
  12515. * @ngdoc directive
  12516. * @name ui.grid.cellNav.directive:uiCellNav
  12517. * @element div
  12518. * @restrict EA
  12519. *
  12520. * @description Adds cell navigation features to the grid columns
  12521. *
  12522. * @example
  12523. <example module="app">
  12524. <file name="app.js">
  12525. var app = angular.module('app', ['ui.grid', 'ui.grid.cellNav']);
  12526. app.controller('MainCtrl', ['$scope', function ($scope) {
  12527. $scope.data = [
  12528. { name: 'Bob', title: 'CEO' },
  12529. { name: 'Frank', title: 'Lowly Developer' }
  12530. ];
  12531. $scope.columnDefs = [
  12532. {name: 'name'},
  12533. {name: 'title'}
  12534. ];
  12535. }]);
  12536. </file>
  12537. <file name="index.html">
  12538. <div ng-controller="MainCtrl">
  12539. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-cellnav></div>
  12540. </div>
  12541. </file>
  12542. </example>
  12543. */
  12544. module.directive('uiGridCellnav', ['gridUtil', 'uiGridCellNavService', 'uiGridCellNavConstants', 'uiGridConstants', 'GridRowColumn', '$timeout', '$compile',
  12545. function(gridUtil, uiGridCellNavService, uiGridCellNavConstants, uiGridConstants, GridRowColumn, $timeout, $compile) {
  12546. return {
  12547. replace: true,
  12548. priority: -150,
  12549. require: '^uiGrid',
  12550. scope: false,
  12551. controller: function() {},
  12552. compile: function() {
  12553. return {
  12554. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  12555. var _scope = $scope;
  12556. var grid = uiGridCtrl.grid;
  12557. uiGridCellNavService.initializeGrid(grid);
  12558. uiGridCtrl.cellNav = {};
  12559. //Ensure that the object has all of the methods we expect it to
  12560. uiGridCtrl.cellNav.makeRowCol = function(obj) {
  12561. if (!(obj instanceof GridRowColumn)) {
  12562. obj = new GridRowColumn(obj.row, obj.col);
  12563. }
  12564. return obj;
  12565. };
  12566. uiGridCtrl.cellNav.getActiveCell = function() {
  12567. var elms = $elm[0].getElementsByClassName('ui-grid-cell-focus');
  12568. if (elms.length > 0) {
  12569. return elms[0];
  12570. }
  12571. return undefined;
  12572. };
  12573. uiGridCtrl.cellNav.broadcastCellNav = grid.cellNav.broadcastCellNav = function(newRowCol, modifierDown, originEvt) {
  12574. modifierDown = !(modifierDown === undefined || !modifierDown);
  12575. newRowCol = uiGridCtrl.cellNav.makeRowCol(newRowCol);
  12576. uiGridCtrl.cellNav.broadcastFocus(newRowCol, modifierDown, originEvt);
  12577. _scope.$broadcast(uiGridCellNavConstants.CELL_NAV_EVENT, newRowCol, modifierDown, originEvt);
  12578. };
  12579. uiGridCtrl.cellNav.clearFocus = grid.cellNav.clearFocus = function() {
  12580. grid.cellNav.focusedCells = [];
  12581. _scope.$broadcast(uiGridCellNavConstants.CELL_NAV_EVENT);
  12582. };
  12583. uiGridCtrl.cellNav.broadcastFocus = function(rowCol, modifierDown, originEvt) {
  12584. modifierDown = !(modifierDown === undefined || !modifierDown);
  12585. rowCol = uiGridCtrl.cellNav.makeRowCol(rowCol);
  12586. var row = rowCol.row,
  12587. col = rowCol.col;
  12588. var rowColSelectIndex = uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol);
  12589. if (grid.cellNav.lastRowCol === null || rowColSelectIndex === -1) {
  12590. var newRowCol = new GridRowColumn(row, col);
  12591. grid.api.cellNav.raise.navigate(newRowCol, grid.cellNav.lastRowCol);
  12592. grid.cellNav.lastRowCol = newRowCol;
  12593. if (uiGridCtrl.grid.options.modifierKeysToMultiSelectCells && modifierDown) {
  12594. grid.cellNav.focusedCells.push(rowCol);
  12595. } else {
  12596. grid.cellNav.focusedCells = [rowCol];
  12597. }
  12598. } else if (grid.options.modifierKeysToMultiSelectCells && modifierDown &&
  12599. rowColSelectIndex >= 0) {
  12600. grid.cellNav.focusedCells.splice(rowColSelectIndex, 1);
  12601. }
  12602. };
  12603. uiGridCtrl.cellNav.handleKeyDown = function(evt) {
  12604. var direction = uiGridCellNavService.getDirection(evt);
  12605. if (direction === null) {
  12606. return null;
  12607. }
  12608. var containerId = 'body';
  12609. if (evt.uiGridTargetRenderContainerId) {
  12610. containerId = evt.uiGridTargetRenderContainerId;
  12611. }
  12612. // Get the last-focused row+col combo
  12613. var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12614. if (lastRowCol) {
  12615. // Figure out which new row+combo we're navigating to
  12616. var rowCol = uiGridCtrl.grid.renderContainers[containerId].cellNav.getNextRowCol(direction, lastRowCol.row, lastRowCol.col);
  12617. var focusableCols = uiGridCtrl.grid.renderContainers[containerId].cellNav.getFocusableCols();
  12618. var rowColSelectIndex = uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol);
  12619. // Shift+tab on top-left cell should exit cellnav on render container
  12620. if (
  12621. // Navigating left
  12622. direction === uiGridCellNavConstants.direction.LEFT &&
  12623. // New col is last col (i.e. wrap around)
  12624. rowCol.col === focusableCols[focusableCols.length - 1] &&
  12625. // Staying on same row, which means we're at first row
  12626. rowCol.row === lastRowCol.row &&
  12627. evt.keyCode === uiGridConstants.keymap.TAB &&
  12628. evt.shiftKey
  12629. ) {
  12630. grid.cellNav.focusedCells.splice(rowColSelectIndex, 1);
  12631. uiGridCtrl.cellNav.clearFocus();
  12632. return true;
  12633. }
  12634. // Tab on bottom-right cell should exit cellnav on render container
  12635. else if (
  12636. direction === uiGridCellNavConstants.direction.RIGHT &&
  12637. // New col is first col (i.e. wrap around)
  12638. rowCol.col === focusableCols[0] &&
  12639. // Staying on same row, which means we're at first row
  12640. rowCol.row === lastRowCol.row &&
  12641. evt.keyCode === uiGridConstants.keymap.TAB &&
  12642. !evt.shiftKey
  12643. ) {
  12644. grid.cellNav.focusedCells.splice(rowColSelectIndex, 1);
  12645. uiGridCtrl.cellNav.clearFocus();
  12646. return true;
  12647. }
  12648. // Scroll to the new cell, if it's not completely visible within the render container's viewport
  12649. grid.scrollToIfNecessary(rowCol.row, rowCol.col).then(function() {
  12650. uiGridCtrl.cellNav.broadcastCellNav(rowCol);
  12651. });
  12652. evt.stopPropagation();
  12653. evt.preventDefault();
  12654. return false;
  12655. }
  12656. };
  12657. },
  12658. post: function($scope, $elm, $attrs, uiGridCtrl) {
  12659. var _scope = $scope;
  12660. var grid = uiGridCtrl.grid;
  12661. function addAriaLiveRegion() {
  12662. // Thanks to google docs for the inspiration behind how to do this
  12663. // XXX: Why is this entire mess nessasary?
  12664. // Because browsers take a lot of coercing to get them to read out live regions
  12665. //http://www.paciellogroup.com/blog/2012/06/html5-accessibility-chops-aria-rolealert-browser-support/
  12666. var ariaNotifierDomElt = '<div ' +
  12667. 'id="' + grid.id + '-aria-speakable" ' +
  12668. 'class="ui-grid-a11y-ariascreenreader-speakable ui-grid-offscreen" ' +
  12669. 'aria-live="assertive" ' +
  12670. 'role="region" ' +
  12671. 'aria-atomic="true" ' +
  12672. 'aria-hidden="false" ' +
  12673. 'aria-relevant="additions" ' +
  12674. '>' +
  12675. '&nbsp;' +
  12676. '</div>';
  12677. var ariaNotifier = $compile(ariaNotifierDomElt)($scope);
  12678. $elm.prepend(ariaNotifier);
  12679. $scope.$on(uiGridCellNavConstants.CELL_NAV_EVENT, function(evt, rowCol, modifierDown, originEvt) {
  12680. /*
  12681. * If the cell nav event was because of a focus event then we don't want to
  12682. * change the notifier text.
  12683. * Reasoning: Voice Over fires a focus events when moving arround the grid.
  12684. * If the screen reader is handing the grid nav properly then we don't need to
  12685. * use the alert to notify the user of the movement.
  12686. * In all other cases we do want a notification event.
  12687. */
  12688. if (originEvt && originEvt.type === 'focus') { return; }
  12689. function setNotifyText(text) {
  12690. if (text === ariaNotifier.text()) { return; }
  12691. ariaNotifier[0].style.clip = 'rect(0px,0px,0px,0px)';
  12692. /*
  12693. * This is how google docs handles clearing the div. Seems to work better than setting the text of the div to ''
  12694. */
  12695. ariaNotifier[0].innerHTML = "";
  12696. ariaNotifier[0].style.visibility = 'hidden';
  12697. ariaNotifier[0].style.visibility = 'visible';
  12698. if (text !== '') {
  12699. ariaNotifier[0].style.clip = 'auto';
  12700. /*
  12701. * The space after the text is something that google docs does.
  12702. */
  12703. ariaNotifier[0].appendChild(document.createTextNode(text + " "));
  12704. ariaNotifier[0].style.visibility = 'hidden';
  12705. ariaNotifier[0].style.visibility = 'visible';
  12706. }
  12707. }
  12708. var values = [];
  12709. var currentSelection = grid.api.cellNav.getCurrentSelection();
  12710. for (var i = 0; i < currentSelection.length; i++) {
  12711. values.push(currentSelection[i].getIntersectionValueFiltered());
  12712. }
  12713. var cellText = values.toString();
  12714. setNotifyText(cellText);
  12715. });
  12716. }
  12717. addAriaLiveRegion();
  12718. }
  12719. };
  12720. }
  12721. };
  12722. }
  12723. ]);
  12724. module.directive('uiGridRenderContainer', ['$timeout', '$document', 'gridUtil', 'uiGridConstants', 'uiGridCellNavService', '$compile', 'uiGridCellNavConstants',
  12725. function($timeout, $document, gridUtil, uiGridConstants, uiGridCellNavService, $compile, uiGridCellNavConstants) {
  12726. return {
  12727. replace: true,
  12728. priority: -99999, //this needs to run very last
  12729. require: ['^uiGrid', 'uiGridRenderContainer', '?^uiGridCellnav'],
  12730. scope: false,
  12731. compile: function() {
  12732. return {
  12733. post: function($scope, $elm, $attrs, controllers) {
  12734. var uiGridCtrl = controllers[0],
  12735. renderContainerCtrl = controllers[1],
  12736. uiGridCellnavCtrl = controllers[2];
  12737. // Skip attaching cell-nav specific logic if the directive is not attached above us
  12738. if (!uiGridCtrl.grid.api.cellNav) { return; }
  12739. var containerId = renderContainerCtrl.containerId;
  12740. var grid = uiGridCtrl.grid;
  12741. //run each time a render container is created
  12742. uiGridCellNavService.decorateRenderContainers(grid);
  12743. // focusser only created for body
  12744. if (containerId !== 'body') {
  12745. return;
  12746. }
  12747. if (uiGridCtrl.grid.options.modifierKeysToMultiSelectCells) {
  12748. $elm.attr('aria-multiselectable', true);
  12749. } else {
  12750. $elm.attr('aria-multiselectable', false);
  12751. }
  12752. //add an element with no dimensions that can be used to set focus and capture keystrokes
  12753. 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);
  12754. $elm.append(focuser);
  12755. focuser.on('focus', function(evt) {
  12756. evt.uiGridTargetRenderContainerId = containerId;
  12757. var rowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12758. if (rowCol === null) {
  12759. rowCol = uiGridCtrl.grid.renderContainers[containerId].cellNav.getNextRowCol(uiGridCellNavConstants.direction.DOWN, null, null);
  12760. if (rowCol.row && rowCol.col) {
  12761. uiGridCtrl.cellNav.broadcastCellNav(rowCol);
  12762. }
  12763. }
  12764. });
  12765. uiGridCellnavCtrl.setAriaActivedescendant = function(id) {
  12766. $elm.attr('aria-activedescendant', id);
  12767. };
  12768. uiGridCellnavCtrl.removeAriaActivedescendant = function(id) {
  12769. if ($elm.attr('aria-activedescendant') === id) {
  12770. $elm.attr('aria-activedescendant', '');
  12771. }
  12772. };
  12773. uiGridCtrl.focus = function() {
  12774. gridUtil.focus.byElement(focuser[0]);
  12775. //allow for first time grid focus
  12776. };
  12777. var viewPortKeyDownWasRaisedForRowCol = null;
  12778. // Bind to keydown events in the render container
  12779. focuser.on('keydown', function(evt) {
  12780. evt.uiGridTargetRenderContainerId = containerId;
  12781. var rowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12782. var result = uiGridCtrl.cellNav.handleKeyDown(evt);
  12783. if (result === null) {
  12784. uiGridCtrl.grid.api.cellNav.raise.viewPortKeyDown(evt, rowCol);
  12785. viewPortKeyDownWasRaisedForRowCol = rowCol;
  12786. }
  12787. });
  12788. //Bind to keypress events in the render container
  12789. //keypress events are needed by edit function so the key press
  12790. //that initiated an edit is not lost
  12791. //must fire the event in a timeout so the editor can
  12792. //initialize and subscribe to the event on another event loop
  12793. focuser.on('keypress', function(evt) {
  12794. if (viewPortKeyDownWasRaisedForRowCol) {
  12795. $timeout(function() {
  12796. uiGridCtrl.grid.api.cellNav.raise.viewPortKeyPress(evt, viewPortKeyDownWasRaisedForRowCol);
  12797. }, 4);
  12798. viewPortKeyDownWasRaisedForRowCol = null;
  12799. }
  12800. });
  12801. $scope.$on('$destroy', function() {
  12802. //Remove all event handlers associated with this focuser.
  12803. focuser.off();
  12804. });
  12805. }
  12806. };
  12807. }
  12808. };
  12809. }
  12810. ]);
  12811. module.directive('uiGridViewport', ['$timeout', '$document', 'gridUtil', 'uiGridConstants', 'uiGridCellNavService', 'uiGridCellNavConstants', '$log', '$compile',
  12812. function($timeout, $document, gridUtil, uiGridConstants, uiGridCellNavService, uiGridCellNavConstants, $log, $compile) {
  12813. return {
  12814. replace: true,
  12815. priority: -99999, //this needs to run very last
  12816. require: ['^uiGrid', '^uiGridRenderContainer', '?^uiGridCellnav'],
  12817. scope: false,
  12818. compile: function() {
  12819. return {
  12820. pre: function($scope, $elm, $attrs, uiGridCtrl) {},
  12821. post: function($scope, $elm, $attrs, controllers) {
  12822. var uiGridCtrl = controllers[0],
  12823. renderContainerCtrl = controllers[1];
  12824. // Skip attaching cell-nav specific logic if the directive is not attached above us
  12825. if (!uiGridCtrl.grid.api.cellNav) { return; }
  12826. var containerId = renderContainerCtrl.containerId;
  12827. //no need to process for other containers
  12828. if (containerId !== 'body') {
  12829. return;
  12830. }
  12831. var grid = uiGridCtrl.grid;
  12832. grid.api.core.on.scrollBegin($scope, function(args) {
  12833. // Skip if there's no currently-focused cell
  12834. var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12835. if (lastRowCol === null) {
  12836. return;
  12837. }
  12838. //if not in my container, move on
  12839. //todo: worry about horiz scroll
  12840. if (!renderContainerCtrl.colContainer.containsColumn(lastRowCol.col)) {
  12841. return;
  12842. }
  12843. uiGridCtrl.cellNav.clearFocus();
  12844. });
  12845. grid.api.core.on.scrollEnd($scope, function(args) {
  12846. // Skip if there's no currently-focused cell
  12847. var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell();
  12848. if (lastRowCol === null) {
  12849. return;
  12850. }
  12851. //if not in my container, move on
  12852. //todo: worry about horiz scroll
  12853. if (!renderContainerCtrl.colContainer.containsColumn(lastRowCol.col)) {
  12854. return;
  12855. }
  12856. uiGridCtrl.cellNav.broadcastCellNav(lastRowCol);
  12857. });
  12858. grid.api.cellNav.on.navigate($scope, function() {
  12859. //focus again because it can be lost
  12860. uiGridCtrl.focus();
  12861. });
  12862. }
  12863. };
  12864. }
  12865. };
  12866. }
  12867. ]);
  12868. /**
  12869. * @ngdoc directive
  12870. * @name ui.grid.cellNav.directive:uiGridCell
  12871. * @element div
  12872. * @restrict A
  12873. * @description Stacks on top of ui.grid.uiGridCell to provide cell navigation
  12874. */
  12875. module.directive('uiGridCell', ['$timeout', '$document', 'uiGridCellNavService', 'gridUtil', 'uiGridCellNavConstants', 'uiGridConstants', 'GridRowColumn',
  12876. function($timeout, $document, uiGridCellNavService, gridUtil, uiGridCellNavConstants, uiGridConstants, GridRowColumn) {
  12877. return {
  12878. priority: -150, // run after default uiGridCell directive and ui.grid.edit uiGridCell
  12879. restrict: 'A',
  12880. require: ['^uiGrid', '?^uiGridCellnav'],
  12881. scope: false,
  12882. link: function($scope, $elm, $attrs, controllers) {
  12883. var uiGridCtrl = controllers[0],
  12884. uiGridCellnavCtrl = controllers[1];
  12885. // Skip attaching cell-nav specific logic if the directive is not attached above us
  12886. if (!uiGridCtrl.grid.api.cellNav) { return; }
  12887. if (!$scope.col.colDef.allowCellFocus) {
  12888. return;
  12889. }
  12890. //Convinience local variables
  12891. var grid = uiGridCtrl.grid;
  12892. $scope.focused = false;
  12893. // Make this cell focusable but only with javascript/a mouse click
  12894. $elm.attr('tabindex', -1);
  12895. // When a cell is clicked, broadcast a cellNav event saying that this row+col combo is now focused
  12896. $elm.find('div').on('click', function(evt) {
  12897. uiGridCtrl.cellNav.broadcastCellNav(new GridRowColumn($scope.row, $scope.col), evt.ctrlKey || evt.metaKey, evt);
  12898. evt.stopPropagation();
  12899. $scope.$apply();
  12900. });
  12901. /*
  12902. * XXX Hack for screen readers.
  12903. * This allows the grid to focus using only the screen reader cursor.
  12904. * Since the focus event doesn't include key press information we can't use it
  12905. * as our primary source of the event.
  12906. */
  12907. $elm.on('mousedown', preventMouseDown);
  12908. //turn on and off for edit events
  12909. if (uiGridCtrl.grid.api.edit) {
  12910. uiGridCtrl.grid.api.edit.on.beginCellEdit($scope, function() {
  12911. $elm.off('mousedown', preventMouseDown);
  12912. });
  12913. uiGridCtrl.grid.api.edit.on.afterCellEdit($scope, function() {
  12914. $elm.on('mousedown', preventMouseDown);
  12915. });
  12916. uiGridCtrl.grid.api.edit.on.cancelCellEdit($scope, function() {
  12917. $elm.on('mousedown', preventMouseDown);
  12918. });
  12919. }
  12920. function preventMouseDown(evt) {
  12921. //Prevents the foucus event from firing if the click event is already going to fire.
  12922. //If both events fire it will cause bouncing behavior.
  12923. evt.preventDefault();
  12924. }
  12925. //You can only focus on elements with a tabindex value
  12926. $elm.on('focus', function(evt) {
  12927. uiGridCtrl.cellNav.broadcastCellNav(new GridRowColumn($scope.row, $scope.col), false, evt);
  12928. evt.stopPropagation();
  12929. $scope.$apply();
  12930. });
  12931. // This event is fired for all cells. If the cell matches, then focus is set
  12932. $scope.$on(uiGridCellNavConstants.CELL_NAV_EVENT, function(evt, rowCol, modifierDown) {
  12933. var isFocused = grid.cellNav.focusedCells.some(function(focusedRowCol, index) {
  12934. return (focusedRowCol.row === $scope.row && focusedRowCol.col === $scope.col);
  12935. });
  12936. if (isFocused) {
  12937. setFocused();
  12938. } else {
  12939. clearFocus();
  12940. }
  12941. });
  12942. function setFocused() {
  12943. if (!$scope.focused) {
  12944. var div = $elm.find('div');
  12945. // div.addClass('ui-grid-cell-focus');
  12946. $elm.attr('aria-selected', true);
  12947. uiGridCellnavCtrl.setAriaActivedescendant($elm.attr('id'));
  12948. $scope.focused = true;
  12949. }
  12950. }
  12951. function clearFocus() {
  12952. if ($scope.focused) {
  12953. var div = $elm.find('div');
  12954. div.removeClass('ui-grid-cell-focus');
  12955. $elm.attr('aria-selected', false);
  12956. uiGridCellnavCtrl.removeAriaActivedescendant($elm.attr('id'));
  12957. $scope.focused = false;
  12958. }
  12959. }
  12960. $scope.$on('$destroy', function() {
  12961. //.off withouth paramaters removes all handlers
  12962. $elm.find('div').off();
  12963. $elm.off();
  12964. });
  12965. }
  12966. };
  12967. }
  12968. ]);
  12969. })();
  12970. (function() {
  12971. 'use strict';
  12972. /**
  12973. * @ngdoc overview
  12974. * @name ui.grid.edit
  12975. * @description
  12976. *
  12977. * # ui.grid.edit
  12978. *
  12979. * <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>
  12980. *
  12981. * This module provides cell editing capability to ui.grid. The goal was to emulate keying data in a spreadsheet via
  12982. * a keyboard.
  12983. * <br/>
  12984. * <br/>
  12985. * To really get the full spreadsheet-like data entry, the ui.grid.cellNav module should be used. This will allow the
  12986. * user to key data and then tab, arrow, or enter to the cells beside or below.
  12987. *
  12988. * <div doc-module-components="ui.grid.edit"></div>
  12989. */
  12990. var module = angular.module('ui.grid.edit', ['ui.grid']);
  12991. /**
  12992. * @ngdoc object
  12993. * @name ui.grid.edit.constant:uiGridEditConstants
  12994. *
  12995. * @description constants available in edit module
  12996. */
  12997. module.constant('uiGridEditConstants', {
  12998. EDITABLE_CELL_TEMPLATE: /EDITABLE_CELL_TEMPLATE/g,
  12999. //must be lowercase because template bulder converts to lower
  13000. EDITABLE_CELL_DIRECTIVE: /editable_cell_directive/g,
  13001. events: {
  13002. BEGIN_CELL_EDIT: 'uiGridEventBeginCellEdit',
  13003. END_CELL_EDIT: 'uiGridEventEndCellEdit',
  13004. CANCEL_CELL_EDIT: 'uiGridEventCancelCellEdit'
  13005. }
  13006. });
  13007. /**
  13008. * @ngdoc service
  13009. * @name ui.grid.edit.service:uiGridEditService
  13010. *
  13011. * @description Services for editing features
  13012. */
  13013. module.service('uiGridEditService', ['$q', 'uiGridConstants', 'gridUtil',
  13014. function($q, uiGridConstants, gridUtil) {
  13015. var service = {
  13016. initializeGrid: function(grid) {
  13017. service.defaultGridOptions(grid.options);
  13018. grid.registerColumnBuilder(service.editColumnBuilder);
  13019. grid.edit = {};
  13020. /**
  13021. * @ngdoc object
  13022. * @name ui.grid.edit.api:PublicApi
  13023. *
  13024. * @description Public Api for edit feature
  13025. */
  13026. var publicApi = {
  13027. events: {
  13028. edit: {
  13029. /**
  13030. * @ngdoc event
  13031. * @name afterCellEdit
  13032. * @eventOf ui.grid.edit.api:PublicApi
  13033. * @description raised when cell editing is complete
  13034. * <pre>
  13035. * gridApi.edit.on.afterCellEdit(scope,function(rowEntity, colDef){})
  13036. * </pre>
  13037. * @param {object} rowEntity the options.data element that was edited
  13038. * @param {object} colDef the column that was edited
  13039. * @param {object} newValue new value
  13040. * @param {object} oldValue old value
  13041. */
  13042. afterCellEdit: function(rowEntity, colDef, newValue, oldValue) {},
  13043. /**
  13044. * @ngdoc event
  13045. * @name beginCellEdit
  13046. * @eventOf ui.grid.edit.api:PublicApi
  13047. * @description raised when cell editing starts on a cell
  13048. * <pre>
  13049. * gridApi.edit.on.beginCellEdit(scope,function(rowEntity, colDef){})
  13050. * </pre>
  13051. * @param {object} rowEntity the options.data element that was edited
  13052. * @param {object} colDef the column that was edited
  13053. * @param {object} triggerEvent the event that triggered the edit. Useful to prevent losing keystrokes on some
  13054. * complex editors
  13055. */
  13056. beginCellEdit: function(rowEntity, colDef, triggerEvent) {},
  13057. /**
  13058. * @ngdoc event
  13059. * @name cancelCellEdit
  13060. * @eventOf ui.grid.edit.api:PublicApi
  13061. * @description raised when cell editing is cancelled on a cell
  13062. * <pre>
  13063. * gridApi.edit.on.cancelCellEdit(scope,function(rowEntity, colDef){})
  13064. * </pre>
  13065. * @param {object} rowEntity the options.data element that was edited
  13066. * @param {object} colDef the column that was edited
  13067. */
  13068. cancelCellEdit: function(rowEntity, colDef) {}
  13069. }
  13070. },
  13071. methods: {
  13072. edit: {}
  13073. }
  13074. };
  13075. grid.api.registerEventsFromObject(publicApi.events);
  13076. //grid.api.registerMethodsFromObject(publicApi.methods);
  13077. },
  13078. defaultGridOptions: function(gridOptions) {
  13079. /**
  13080. * @ngdoc object
  13081. * @name ui.grid.edit.api:GridOptions
  13082. *
  13083. * @description Options for configuring the edit feature, these are available to be
  13084. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  13085. */
  13086. /**
  13087. * @ngdoc object
  13088. * @name enableCellEdit
  13089. * @propertyOf ui.grid.edit.api:GridOptions
  13090. * @description If defined, sets the default value for the editable flag on each individual colDefs
  13091. * if their individual enableCellEdit configuration is not defined. Defaults to undefined.
  13092. */
  13093. /**
  13094. * @ngdoc object
  13095. * @name cellEditableCondition
  13096. * @propertyOf ui.grid.edit.api:GridOptions
  13097. * @description If specified, either a value or function to be used by all columns before editing.
  13098. * If falsy, then editing of cell is not allowed.
  13099. * @example
  13100. * <pre>
  13101. * function($scope){
  13102. * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed
  13103. * return true;
  13104. * }
  13105. * </pre>
  13106. */
  13107. gridOptions.cellEditableCondition = gridOptions.cellEditableCondition === undefined ? true : gridOptions.cellEditableCondition;
  13108. /**
  13109. * @ngdoc object
  13110. * @name editableCellTemplate
  13111. * @propertyOf ui.grid.edit.api:GridOptions
  13112. * @description If specified, cellTemplate to use as the editor for all columns.
  13113. * <br/> defaults to 'ui-grid/cellTextEditor'
  13114. */
  13115. /**
  13116. * @ngdoc object
  13117. * @name enableCellEditOnFocus
  13118. * @propertyOf ui.grid.edit.api:GridOptions
  13119. * @description If true, then editor is invoked as soon as cell receives focus. Default false.
  13120. * <br/>_requires cellNav feature and the edit feature to be enabled_
  13121. */
  13122. //enableCellEditOnFocus can only be used if cellnav module is used
  13123. gridOptions.enableCellEditOnFocus = gridOptions.enableCellEditOnFocus === undefined ? false : gridOptions.enableCellEditOnFocus;
  13124. },
  13125. /**
  13126. * @ngdoc service
  13127. * @name editColumnBuilder
  13128. * @methodOf ui.grid.edit.service:uiGridEditService
  13129. * @description columnBuilder function that adds edit properties to grid column
  13130. * @returns {promise} promise that will load any needed templates when resolved
  13131. */
  13132. editColumnBuilder: function(colDef, col, gridOptions) {
  13133. var promises = [];
  13134. /**
  13135. * @ngdoc object
  13136. * @name ui.grid.edit.api:ColumnDef
  13137. *
  13138. * @description Column Definition for edit feature, these are available to be
  13139. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  13140. */
  13141. /**
  13142. * @ngdoc object
  13143. * @name enableCellEdit
  13144. * @propertyOf ui.grid.edit.api:ColumnDef
  13145. * @description enable editing on column
  13146. */
  13147. colDef.enableCellEdit = colDef.enableCellEdit === undefined ? (gridOptions.enableCellEdit === undefined ?
  13148. (colDef.type !== 'object') : gridOptions.enableCellEdit) : colDef.enableCellEdit;
  13149. /**
  13150. * @ngdoc object
  13151. * @name cellEditableCondition
  13152. * @propertyOf ui.grid.edit.api:ColumnDef
  13153. * @description If specified, either a value or function evaluated before editing cell. If falsy, then editing of cell is not allowed.
  13154. * @example
  13155. * <pre>
  13156. * function($scope){
  13157. * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed
  13158. * return true;
  13159. * }
  13160. * </pre>
  13161. */
  13162. colDef.cellEditableCondition = colDef.cellEditableCondition === undefined ? gridOptions.cellEditableCondition : colDef.cellEditableCondition;
  13163. /**
  13164. * @ngdoc object
  13165. * @name editableCellTemplate
  13166. * @propertyOf ui.grid.edit.api:ColumnDef
  13167. * @description cell template to be used when editing this column. Can be Url or text template
  13168. * <br/>Defaults to gridOptions.editableCellTemplate
  13169. */
  13170. if (colDef.enableCellEdit) {
  13171. colDef.editableCellTemplate = colDef.editableCellTemplate || gridOptions.editableCellTemplate || 'ui-grid/cellEditor';
  13172. promises.push(gridUtil.getTemplate(colDef.editableCellTemplate)
  13173. .then(
  13174. function(template) {
  13175. col.editableCellTemplate = template;
  13176. },
  13177. function(res) {
  13178. // Todo handle response error here?
  13179. throw new Error("Couldn't fetch/use colDef.editableCellTemplate '" + colDef.editableCellTemplate + "'");
  13180. }));
  13181. }
  13182. /**
  13183. * @ngdoc object
  13184. * @name enableCellEditOnFocus
  13185. * @propertyOf ui.grid.edit.api:ColumnDef
  13186. * @requires ui.grid.cellNav
  13187. * @description If true, then editor is invoked as soon as cell receives focus. Default false.
  13188. * <br>_requires both the cellNav feature and the edit feature to be enabled_
  13189. */
  13190. //enableCellEditOnFocus can only be used if cellnav module is used
  13191. colDef.enableCellEditOnFocus = colDef.enableCellEditOnFocus === undefined ? gridOptions.enableCellEditOnFocus : colDef.enableCellEditOnFocus;
  13192. /**
  13193. * @ngdoc string
  13194. * @name editModelField
  13195. * @propertyOf ui.grid.edit.api:ColumnDef
  13196. * @description a bindable string value that is used when binding to edit controls instead of colDef.field
  13197. * <br/> example: You have a complex property on and object like state:{abbrev:'MS',name:'Mississippi'}. The
  13198. * grid should display state.name in the cell and sort/filter based on the state.name property but the editor
  13199. * requires the full state object.
  13200. * <br/>colDef.field = 'state.name'
  13201. * <br/>colDef.editModelField = 'state'
  13202. */
  13203. //colDef.editModelField
  13204. return $q.all(promises);
  13205. },
  13206. /**
  13207. * @ngdoc service
  13208. * @name isStartEditKey
  13209. * @methodOf ui.grid.edit.service:uiGridEditService
  13210. * @description Determines if a keypress should start editing. Decorate this service to override with your
  13211. * own key events. See service decorator in angular docs.
  13212. * @param {Event} evt keydown event
  13213. * @returns {boolean} true if an edit should start
  13214. */
  13215. isStartEditKey: function(evt) {
  13216. if (evt.metaKey ||
  13217. evt.keyCode === uiGridConstants.keymap.ESC ||
  13218. evt.keyCode === uiGridConstants.keymap.SHIFT ||
  13219. evt.keyCode === uiGridConstants.keymap.CTRL ||
  13220. evt.keyCode === uiGridConstants.keymap.ALT ||
  13221. evt.keyCode === uiGridConstants.keymap.WIN ||
  13222. evt.keyCode === uiGridConstants.keymap.CAPSLOCK ||
  13223. evt.keyCode === uiGridConstants.keymap.LEFT ||
  13224. (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey) ||
  13225. evt.keyCode === uiGridConstants.keymap.RIGHT ||
  13226. evt.keyCode === uiGridConstants.keymap.TAB ||
  13227. evt.keyCode === uiGridConstants.keymap.UP ||
  13228. (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) ||
  13229. evt.keyCode === uiGridConstants.keymap.DOWN ||
  13230. evt.keyCode === uiGridConstants.keymap.ENTER) {
  13231. return false;
  13232. }
  13233. return true;
  13234. }
  13235. };
  13236. return service;
  13237. }
  13238. ]);
  13239. /**
  13240. * @ngdoc directive
  13241. * @name ui.grid.edit.directive:uiGridEdit
  13242. * @element div
  13243. * @restrict A
  13244. *
  13245. * @description Adds editing features to the ui-grid directive.
  13246. *
  13247. * @example
  13248. <example module="app">
  13249. <file name="app.js">
  13250. var app = angular.module('app', ['ui.grid', 'ui.grid.edit']);
  13251. app.controller('MainCtrl', ['$scope', function ($scope) {
  13252. $scope.data = [
  13253. { name: 'Bob', title: 'CEO' },
  13254. { name: 'Frank', title: 'Lowly Developer' }
  13255. ];
  13256. $scope.columnDefs = [
  13257. {name: 'name', enableCellEdit: true},
  13258. {name: 'title', enableCellEdit: true}
  13259. ];
  13260. }]);
  13261. </file>
  13262. <file name="index.html">
  13263. <div ng-controller="MainCtrl">
  13264. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-edit></div>
  13265. </div>
  13266. </file>
  13267. </example>
  13268. */
  13269. module.directive('uiGridEdit', ['gridUtil', 'uiGridEditService', function(gridUtil, uiGridEditService) {
  13270. return {
  13271. replace: true,
  13272. priority: 0,
  13273. require: '^uiGrid',
  13274. scope: false,
  13275. compile: function() {
  13276. return {
  13277. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  13278. uiGridEditService.initializeGrid(uiGridCtrl.grid);
  13279. },
  13280. post: function($scope, $elm, $attrs, uiGridCtrl) {}
  13281. };
  13282. }
  13283. };
  13284. }]);
  13285. /**
  13286. * @ngdoc directive
  13287. * @name ui.grid.edit.directive:uiGridRenderContainer
  13288. * @element div
  13289. * @restrict A
  13290. *
  13291. * @description Adds keydown listeners to renderContainer element so we can capture when to begin edits
  13292. *
  13293. */
  13294. module.directive('uiGridViewport', ['uiGridEditConstants',
  13295. function(uiGridEditConstants) {
  13296. return {
  13297. replace: true,
  13298. priority: -99998, //run before cellNav
  13299. require: ['^uiGrid', '^uiGridRenderContainer'],
  13300. scope: false,
  13301. compile: function() {
  13302. return {
  13303. post: function($scope, $elm, $attrs, controllers) {
  13304. var uiGridCtrl = controllers[0];
  13305. // Skip attaching if edit and cellNav is not enabled
  13306. if (!uiGridCtrl.grid.api.edit || !uiGridCtrl.grid.api.cellNav) { return; }
  13307. var containerId = controllers[1].containerId;
  13308. //no need to process for other containers
  13309. if (containerId !== 'body') {
  13310. return;
  13311. }
  13312. //refocus on the grid
  13313. $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function() {
  13314. uiGridCtrl.focus();
  13315. });
  13316. $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function() {
  13317. uiGridCtrl.focus();
  13318. });
  13319. }
  13320. };
  13321. }
  13322. };
  13323. }
  13324. ]);
  13325. /**
  13326. * @ngdoc directive
  13327. * @name ui.grid.edit.directive:uiGridCell
  13328. * @element div
  13329. * @restrict A
  13330. *
  13331. * @description Stacks on top of ui.grid.uiGridCell to provide in-line editing capabilities to the cell
  13332. * Editing Actions.
  13333. *
  13334. * Binds edit start events to the uiGridCell element. When the events fire, the gridCell element is appended
  13335. * with the columnDef.editableCellTemplate element ('cellEditor.html' by default).
  13336. *
  13337. * The editableCellTemplate should respond to uiGridEditConstants.events.BEGIN\_CELL\_EDIT angular event
  13338. * and do the initial steps needed to edit the cell (setfocus on input element, etc).
  13339. *
  13340. * When the editableCellTemplate recognizes that the editing is ended (blur event, Enter key, etc.)
  13341. * it should emit the uiGridEditConstants.events.END\_CELL\_EDIT event.
  13342. *
  13343. * If editableCellTemplate recognizes that the editing has been cancelled (esc key)
  13344. * it should emit the uiGridEditConstants.events.CANCEL\_CELL\_EDIT event. The original value
  13345. * will be set back on the model by the uiGridCell directive.
  13346. *
  13347. * Events that invoke editing:
  13348. * - dblclick
  13349. * - F2 keydown (when using cell selection)
  13350. *
  13351. * Events that end editing:
  13352. * - Dependent on the specific editableCellTemplate
  13353. * - Standards should be blur and enter keydown
  13354. *
  13355. * Events that cancel editing:
  13356. * - Dependent on the specific editableCellTemplate
  13357. * - Standards should be Esc keydown
  13358. *
  13359. * Grid Events that end editing:
  13360. * - uiGridConstants.events.GRID_SCROLL
  13361. *
  13362. */
  13363. /**
  13364. * @ngdoc object
  13365. * @name ui.grid.edit.api:GridRow
  13366. *
  13367. * @description GridRow options for edit feature, these are available to be
  13368. * set internally only, by other features
  13369. */
  13370. /**
  13371. * @ngdoc object
  13372. * @name enableCellEdit
  13373. * @propertyOf ui.grid.edit.api:GridRow
  13374. * @description enable editing on row, grouping for example might disable editing on group header rows
  13375. */
  13376. module.directive('uiGridCell', ['$compile', '$injector', '$timeout', 'uiGridConstants', 'uiGridEditConstants', 'gridUtil', '$parse', 'uiGridEditService', '$rootScope',
  13377. function($compile, $injector, $timeout, uiGridConstants, uiGridEditConstants, gridUtil, $parse, uiGridEditService, $rootScope) {
  13378. var touchstartTimeout = 500;
  13379. if ($injector.has('uiGridCellNavService')) {
  13380. var uiGridCellNavService = $injector.get('uiGridCellNavService');
  13381. }
  13382. return {
  13383. priority: -100, // run after default uiGridCell directive
  13384. restrict: 'A',
  13385. scope: false,
  13386. require: '?^uiGrid',
  13387. link: function($scope, $elm, $attrs, uiGridCtrl) {
  13388. var html;
  13389. var origCellValue;
  13390. var inEdit = false;
  13391. var cellModel;
  13392. var cancelTouchstartTimeout;
  13393. var editCellScope;
  13394. if (!$scope.col.colDef.enableCellEdit) {
  13395. return;
  13396. }
  13397. var cellNavNavigateDereg = function() {};
  13398. var viewPortKeyDownDereg = function() {};
  13399. var setEditable = function() {
  13400. if ($scope.col.colDef.enableCellEdit && $scope.row.enableCellEdit !== false) {
  13401. if (!$scope.beginEditEventsWired) { //prevent multiple attachments
  13402. registerBeginEditEvents();
  13403. }
  13404. } else {
  13405. if ($scope.beginEditEventsWired) {
  13406. cancelBeginEditEvents();
  13407. }
  13408. }
  13409. };
  13410. setEditable();
  13411. var rowWatchDereg = $scope.$watch('row', function(n, o) {
  13412. if (n !== o) {
  13413. setEditable();
  13414. }
  13415. });
  13416. $scope.$on('$destroy', rowWatchDereg);
  13417. function registerBeginEditEvents() {
  13418. $elm.on('dblclick', beginEdit);
  13419. // Add touchstart handling. If the users starts a touch and it doesn't end after X milliseconds, then start the edit
  13420. $elm.on('touchstart', touchStart);
  13421. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13422. viewPortKeyDownDereg = uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function(evt, rowCol) {
  13423. if (rowCol === null) {
  13424. return;
  13425. }
  13426. if (rowCol.row === $scope.row && rowCol.col === $scope.col && !$scope.col.colDef.enableCellEditOnFocus) {
  13427. //important to do this before scrollToIfNecessary
  13428. beginEditKeyDown(evt);
  13429. }
  13430. });
  13431. cellNavNavigateDereg = uiGridCtrl.grid.api.cellNav.on.navigate($scope, function(newRowCol, oldRowCol) {
  13432. if ($scope.col.colDef.enableCellEditOnFocus) {
  13433. // Don't begin edit if the cell hasn't changed
  13434. if ((!oldRowCol || newRowCol.row !== oldRowCol.row || newRowCol.col !== oldRowCol.col) &&
  13435. newRowCol.row === $scope.row && newRowCol.col === $scope.col) {
  13436. $timeout(function() {
  13437. beginEdit();
  13438. });
  13439. }
  13440. }
  13441. });
  13442. }
  13443. $scope.beginEditEventsWired = true;
  13444. }
  13445. function touchStart(event) {
  13446. // jQuery masks events
  13447. if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) {
  13448. event = event.originalEvent;
  13449. }
  13450. // Bind touchend handler
  13451. $elm.on('touchend', touchEnd);
  13452. // Start a timeout
  13453. cancelTouchstartTimeout = $timeout(function() {}, touchstartTimeout);
  13454. // Timeout's done! Start the edit
  13455. cancelTouchstartTimeout.then(function() {
  13456. // Use setTimeout to start the edit because beginEdit expects to be outside of $digest
  13457. setTimeout(beginEdit, 0);
  13458. // Undbind the touchend handler, we don't need it anymore
  13459. $elm.off('touchend', touchEnd);
  13460. });
  13461. }
  13462. // Cancel any touchstart timeout
  13463. function touchEnd(event) {
  13464. $timeout.cancel(cancelTouchstartTimeout);
  13465. $elm.off('touchend', touchEnd);
  13466. }
  13467. function cancelBeginEditEvents() {
  13468. $elm.off('dblclick', beginEdit);
  13469. $elm.off('keydown', beginEditKeyDown);
  13470. $elm.off('touchstart', touchStart);
  13471. cellNavNavigateDereg();
  13472. viewPortKeyDownDereg();
  13473. $scope.beginEditEventsWired = false;
  13474. }
  13475. function beginEditKeyDown(evt) {
  13476. if (uiGridEditService.isStartEditKey(evt)) {
  13477. beginEdit(evt);
  13478. }
  13479. }
  13480. function shouldEdit(col, row) {
  13481. return !row.isSaving &&
  13482. (angular.isFunction(col.colDef.cellEditableCondition) ?
  13483. col.colDef.cellEditableCondition($scope) :
  13484. col.colDef.cellEditableCondition);
  13485. }
  13486. function beginEdit(triggerEvent) {
  13487. //we need to scroll the cell into focus before invoking the editor
  13488. $scope.grid.api.core.scrollToIfNecessary($scope.row, $scope.col)
  13489. .then(function() {
  13490. beginEditAfterScroll(triggerEvent);
  13491. });
  13492. }
  13493. /**
  13494. * @ngdoc property
  13495. * @name editDropdownOptionsArray
  13496. * @propertyOf ui.grid.edit.api:ColumnDef
  13497. * @description an array of values in the format
  13498. * [ {id: xxx, value: xxx} ], which is populated
  13499. * into the edit dropdown
  13500. *
  13501. */
  13502. /**
  13503. * @ngdoc property
  13504. * @name editDropdownIdLabel
  13505. * @propertyOf ui.grid.edit.api:ColumnDef
  13506. * @description the label for the "id" field
  13507. * in the editDropdownOptionsArray. Defaults
  13508. * to 'id'
  13509. * @example
  13510. * <pre>
  13511. * $scope.gridOptions = {
  13512. * columnDefs: [
  13513. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  13514. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  13515. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  13516. * ],
  13517. * </pre>
  13518. *
  13519. */
  13520. /**
  13521. * @ngdoc property
  13522. * @name editDropdownRowEntityOptionsArrayPath
  13523. * @propertyOf ui.grid.edit.api:ColumnDef
  13524. * @description a path to a property on row.entity containing an
  13525. * array of values in the format
  13526. * [ {id: xxx, value: xxx} ], which will be used to populate
  13527. * the edit dropdown. This can be used when the dropdown values are dependent on
  13528. * the backing row entity.
  13529. * If this property is set then editDropdownOptionsArray will be ignored.
  13530. * @example
  13531. * <pre>
  13532. * $scope.gridOptions = {
  13533. * columnDefs: [
  13534. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  13535. * editDropdownRowEntityOptionsArrayPath: 'foo.bars[0].baz',
  13536. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  13537. * ],
  13538. * </pre>
  13539. *
  13540. */
  13541. /**
  13542. * @ngdoc property
  13543. * @name editDropdownValueLabel
  13544. * @propertyOf ui.grid.edit.api:ColumnDef
  13545. * @description the label for the "value" field
  13546. * in the editDropdownOptionsArray. Defaults
  13547. * to 'value'
  13548. * @example
  13549. * <pre>
  13550. * $scope.gridOptions = {
  13551. * columnDefs: [
  13552. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  13553. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  13554. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  13555. * ],
  13556. * </pre>
  13557. *
  13558. */
  13559. /**
  13560. * @ngdoc property
  13561. * @name editDropdownFilter
  13562. * @propertyOf ui.grid.edit.api:ColumnDef
  13563. * @description A filter that you would like to apply to the values in the options list
  13564. * of the dropdown. For example if you were using angular-translate you might set this
  13565. * to `'translate'`
  13566. * @example
  13567. * <pre>
  13568. * $scope.gridOptions = {
  13569. * columnDefs: [
  13570. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  13571. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  13572. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status', editDropdownFilter: 'translate' }
  13573. * ],
  13574. * </pre>
  13575. *
  13576. */
  13577. function beginEditAfterScroll(triggerEvent) {
  13578. // If we are already editing, then just skip this so we don't try editing twice...
  13579. if (inEdit) {
  13580. return;
  13581. }
  13582. if (!shouldEdit($scope.col, $scope.row)) {
  13583. return;
  13584. }
  13585. cellModel = $parse($scope.row.getQualifiedColField($scope.col));
  13586. //get original value from the cell
  13587. origCellValue = cellModel($scope);
  13588. html = $scope.col.editableCellTemplate;
  13589. if ($scope.col.colDef.editModelField) {
  13590. html = html.replace(uiGridConstants.MODEL_COL_FIELD, gridUtil.preEval('row.entity.' + $scope.col.colDef.editModelField));
  13591. } else {
  13592. html = html.replace(uiGridConstants.MODEL_COL_FIELD, $scope.row.getQualifiedColField($scope.col));
  13593. }
  13594. html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
  13595. var optionFilter = $scope.col.colDef.editDropdownFilter ? '|' + $scope.col.colDef.editDropdownFilter : '';
  13596. html = html.replace(uiGridConstants.CUSTOM_FILTERS, optionFilter);
  13597. var inputType = 'text';
  13598. switch ($scope.col.colDef.type) {
  13599. case 'boolean':
  13600. inputType = 'checkbox';
  13601. break;
  13602. case 'number':
  13603. inputType = 'number';
  13604. break;
  13605. case 'date':
  13606. inputType = 'date';
  13607. break;
  13608. }
  13609. html = html.replace('INPUT_TYPE', inputType);
  13610. var editDropdownRowEntityOptionsArrayPath = $scope.col.colDef.editDropdownRowEntityOptionsArrayPath;
  13611. if (editDropdownRowEntityOptionsArrayPath) {
  13612. $scope.editDropdownOptionsArray = resolveObjectFromPath($scope.row.entity, editDropdownRowEntityOptionsArrayPath);
  13613. } else {
  13614. $scope.editDropdownOptionsArray = $scope.col.colDef.editDropdownOptionsArray;
  13615. }
  13616. $scope.editDropdownIdLabel = $scope.col.colDef.editDropdownIdLabel ? $scope.col.colDef.editDropdownIdLabel : 'id';
  13617. $scope.editDropdownValueLabel = $scope.col.colDef.editDropdownValueLabel ? $scope.col.colDef.editDropdownValueLabel : 'value';
  13618. var cellElement;
  13619. var createEditor = function() {
  13620. inEdit = true;
  13621. cancelBeginEditEvents();
  13622. var cellElement = angular.element(html);
  13623. $elm.append(cellElement);
  13624. editCellScope = $scope.$new();
  13625. $compile(cellElement)(editCellScope);
  13626. var gridCellContentsEl = angular.element($elm.children()[0]);
  13627. gridCellContentsEl.addClass('ui-grid-cell-contents-hidden');
  13628. };
  13629. if (!$rootScope.$$phase) {
  13630. $scope.$apply(createEditor);
  13631. } else {
  13632. createEditor();
  13633. }
  13634. //stop editing when grid is scrolled
  13635. var deregOnGridScroll = $scope.col.grid.api.core.on.scrollBegin($scope, function() {
  13636. endEdit();
  13637. $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue);
  13638. deregOnGridScroll();
  13639. deregOnEndCellEdit();
  13640. deregOnCancelCellEdit();
  13641. });
  13642. //end editing
  13643. var deregOnEndCellEdit = $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function() {
  13644. endEdit();
  13645. $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue);
  13646. deregOnEndCellEdit();
  13647. deregOnGridScroll();
  13648. deregOnCancelCellEdit();
  13649. });
  13650. //cancel editing
  13651. var deregOnCancelCellEdit = $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function() {
  13652. cancelEdit();
  13653. deregOnCancelCellEdit();
  13654. deregOnGridScroll();
  13655. deregOnEndCellEdit();
  13656. });
  13657. $scope.$broadcast(uiGridEditConstants.events.BEGIN_CELL_EDIT, triggerEvent);
  13658. $timeout(function() {
  13659. //execute in a timeout to give any complex editor templates a cycle to completely render
  13660. $scope.grid.api.edit.raise.beginCellEdit($scope.row.entity, $scope.col.colDef, triggerEvent);
  13661. });
  13662. }
  13663. function endEdit() {
  13664. $scope.grid.disableScrolling = false;
  13665. if (!inEdit) {
  13666. return;
  13667. }
  13668. //sometimes the events can't keep up with the keyboard and grid focus is lost, so always focus
  13669. //back to grid here. The focus call needs to be before the $destroy and removal of the control,
  13670. //otherwise ng-model-options of UpdateOn: 'blur' will not work.
  13671. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13672. uiGridCtrl.focus();
  13673. }
  13674. var gridCellContentsEl = angular.element($elm.children()[0]);
  13675. //remove edit element
  13676. editCellScope.$destroy();
  13677. angular.element($elm.children()[1]).remove();
  13678. gridCellContentsEl.removeClass('ui-grid-cell-contents-hidden');
  13679. inEdit = false;
  13680. registerBeginEditEvents();
  13681. $scope.grid.api.core.notifyDataChange(uiGridConstants.dataChange.EDIT);
  13682. }
  13683. function cancelEdit() {
  13684. $scope.grid.disableScrolling = false;
  13685. if (!inEdit) {
  13686. return;
  13687. }
  13688. cellModel.assign($scope, origCellValue);
  13689. $scope.$apply();
  13690. $scope.grid.api.edit.raise.cancelCellEdit($scope.row.entity, $scope.col.colDef);
  13691. endEdit();
  13692. }
  13693. // resolves a string path against the given object
  13694. // shamelessly borrowed from
  13695. // http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key
  13696. function resolveObjectFromPath(object, path) {
  13697. path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
  13698. path = path.replace(/^\./, ''); // strip a leading dot
  13699. var a = path.split('.');
  13700. while (a.length) {
  13701. var n = a.shift();
  13702. if (n in object) {
  13703. object = object[n];
  13704. } else {
  13705. return;
  13706. }
  13707. }
  13708. return object;
  13709. }
  13710. }
  13711. };
  13712. }
  13713. ]);
  13714. /**
  13715. * @ngdoc directive
  13716. * @name ui.grid.edit.directive:uiGridEditor
  13717. * @element div
  13718. * @restrict A
  13719. *
  13720. * @description input editor directive for editable fields.
  13721. * Provides EndEdit and CancelEdit events
  13722. *
  13723. * Events that end editing:
  13724. * blur and enter keydown
  13725. *
  13726. * Events that cancel editing:
  13727. * - Esc keydown
  13728. *
  13729. */
  13730. module.directive('uiGridEditor', ['gridUtil', 'uiGridConstants', 'uiGridEditConstants', '$timeout', 'uiGridEditService',
  13731. function(gridUtil, uiGridConstants, uiGridEditConstants, $timeout, uiGridEditService) {
  13732. return {
  13733. scope: true,
  13734. require: ['?^uiGrid', '?^uiGridRenderContainer', 'ngModel'],
  13735. compile: function() {
  13736. return {
  13737. pre: function($scope, $elm, $attrs) {
  13738. },
  13739. post: function($scope, $elm, $attrs, controllers) {
  13740. var uiGridCtrl, renderContainerCtrl, ngModel;
  13741. if (controllers[0]) { uiGridCtrl = controllers[0]; }
  13742. if (controllers[1]) { renderContainerCtrl = controllers[1]; }
  13743. if (controllers[2]) { ngModel = controllers[2]; }
  13744. //set focus at start of edit
  13745. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function(evt, triggerEvent) {
  13746. $timeout(function() {
  13747. $elm[0].focus();
  13748. //only select text if it is not being replaced below in the cellNav viewPortKeyPress
  13749. if ($scope.col.colDef.enableCellEditOnFocus || !(uiGridCtrl && uiGridCtrl.grid.api.cellNav)) {
  13750. $elm[0].select();
  13751. } else {
  13752. //some browsers (Chrome) stupidly, imo, support the w3 standard that number, email, ...
  13753. //fields should not allow setSelectionRange. We ignore the error for those browsers
  13754. //https://www.w3.org/Bugs/Public/show_bug.cgi?id=24796
  13755. try {
  13756. $elm[0].setSelectionRange($elm[0].value.length, $elm[0].value.length);
  13757. } catch (ex) {
  13758. //ignore
  13759. }
  13760. }
  13761. });
  13762. //set the keystroke that started the edit event
  13763. //we must do this because the BeginEdit is done in a different event loop than the intitial
  13764. //keydown event
  13765. //fire this event for the keypress that is received
  13766. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13767. var viewPortKeyDownUnregister = uiGridCtrl.grid.api.cellNav.on.viewPortKeyPress($scope, function(evt, rowCol) {
  13768. if (uiGridEditService.isStartEditKey(evt)) {
  13769. ngModel.$setViewValue(String.fromCharCode(evt.keyCode), evt);
  13770. ngModel.$render();
  13771. }
  13772. viewPortKeyDownUnregister();
  13773. });
  13774. }
  13775. $elm.on('blur', function(evt) {
  13776. $scope.stopEdit(evt);
  13777. });
  13778. });
  13779. $scope.deepEdit = false;
  13780. $scope.stopEdit = function(evt) {
  13781. if ($scope.inputForm && !$scope.inputForm.$valid) {
  13782. evt.stopPropagation();
  13783. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  13784. } else {
  13785. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  13786. }
  13787. $scope.deepEdit = false;
  13788. };
  13789. $elm.on('click', function(evt) {
  13790. if ($elm[0].type !== 'checkbox') {
  13791. $scope.deepEdit = true;
  13792. $timeout(function() {
  13793. $scope.grid.disableScrolling = true;
  13794. });
  13795. }
  13796. });
  13797. $elm.on('keydown', function(evt) {
  13798. switch (evt.keyCode) {
  13799. case uiGridConstants.keymap.ESC:
  13800. evt.stopPropagation();
  13801. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  13802. break;
  13803. }
  13804. if ($scope.deepEdit &&
  13805. (evt.keyCode === uiGridConstants.keymap.LEFT ||
  13806. evt.keyCode === uiGridConstants.keymap.RIGHT ||
  13807. evt.keyCode === uiGridConstants.keymap.UP ||
  13808. evt.keyCode === uiGridConstants.keymap.DOWN)) {
  13809. evt.stopPropagation();
  13810. }
  13811. // Pass the keydown event off to the cellNav service, if it exists
  13812. else if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13813. evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
  13814. if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
  13815. $scope.stopEdit(evt);
  13816. }
  13817. } else {
  13818. //handle enter and tab for editing not using cellNav
  13819. switch (evt.keyCode) {
  13820. case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
  13821. case uiGridConstants.keymap.TAB:
  13822. evt.stopPropagation();
  13823. evt.preventDefault();
  13824. $scope.stopEdit(evt);
  13825. break;
  13826. }
  13827. }
  13828. return true;
  13829. });
  13830. }
  13831. };
  13832. }
  13833. };
  13834. }
  13835. ]);
  13836. /**
  13837. * @ngdoc directive
  13838. * @name ui.grid.edit.directive:input
  13839. * @element input
  13840. * @restrict E
  13841. *
  13842. * @description directive to provide binding between input[date] value and ng-model for angular 1.2
  13843. * It is similar to input[date] directive of angular 1.3
  13844. *
  13845. * Supported date format for input is 'yyyy-MM-dd'
  13846. * The directive will set the $valid property of input element and the enclosing form to false if
  13847. * model is invalid date or value of input is entered wrong.
  13848. *
  13849. */
  13850. module.directive('uiGridEditor', ['$filter', function($filter) {
  13851. function parseDateString(dateString) {
  13852. if (typeof(dateString) === 'undefined' || dateString === '') {
  13853. return null;
  13854. }
  13855. var parts = dateString.split('-');
  13856. if (parts.length !== 3) {
  13857. return null;
  13858. }
  13859. var year = parseInt(parts[0], 10);
  13860. var month = parseInt(parts[1], 10);
  13861. var day = parseInt(parts[2], 10);
  13862. if (month < 1 || year < 1 || day < 1) {
  13863. return null;
  13864. }
  13865. return new Date(year, (month - 1), day);
  13866. }
  13867. return {
  13868. priority: -100, // run after default uiGridEditor directive
  13869. require: '?ngModel',
  13870. link: function(scope, element, attrs, ngModel) {
  13871. if (angular.version.minor === 2 && attrs.type && attrs.type === 'date' && ngModel) {
  13872. ngModel.$formatters.push(function(modelValue) {
  13873. ngModel.$setValidity(null, (!modelValue || !isNaN(modelValue.getTime())));
  13874. return $filter('date')(modelValue, 'yyyy-MM-dd');
  13875. });
  13876. ngModel.$parsers.push(function(viewValue) {
  13877. if (viewValue && viewValue.length > 0) {
  13878. var dateValue = parseDateString(viewValue);
  13879. ngModel.$setValidity(null, (dateValue && !isNaN(dateValue.getTime())));
  13880. return dateValue;
  13881. } else {
  13882. ngModel.$setValidity(null, true);
  13883. return null;
  13884. }
  13885. });
  13886. }
  13887. }
  13888. };
  13889. }]);
  13890. /**
  13891. * @ngdoc directive
  13892. * @name ui.grid.edit.directive:uiGridEditDropdown
  13893. * @element div
  13894. * @restrict A
  13895. *
  13896. * @description dropdown editor for editable fields.
  13897. * Provides EndEdit and CancelEdit events
  13898. *
  13899. * Events that end editing:
  13900. * blur and enter keydown, and any left/right nav
  13901. *
  13902. * Events that cancel editing:
  13903. * - Esc keydown
  13904. *
  13905. */
  13906. module.directive('uiGridEditDropdown', ['uiGridConstants', 'uiGridEditConstants',
  13907. function(uiGridConstants, uiGridEditConstants) {
  13908. return {
  13909. require: ['?^uiGrid', '?^uiGridRenderContainer'],
  13910. scope: true,
  13911. compile: function() {
  13912. return {
  13913. pre: function($scope, $elm, $attrs) {
  13914. },
  13915. post: function($scope, $elm, $attrs, controllers) {
  13916. var uiGridCtrl = controllers[0];
  13917. var renderContainerCtrl = controllers[1];
  13918. //set focus at start of edit
  13919. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function() {
  13920. $elm[0].focus();
  13921. $elm[0].style.width = ($elm[0].parentElement.offsetWidth - 1) + 'px';
  13922. $elm.on('blur', function(evt) {
  13923. $scope.stopEdit(evt);
  13924. });
  13925. });
  13926. $scope.stopEdit = function(evt) {
  13927. // no need to validate a dropdown - invalid values shouldn't be
  13928. // available in the list
  13929. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  13930. };
  13931. $elm.on('keydown', function(evt) {
  13932. switch (evt.keyCode) {
  13933. case uiGridConstants.keymap.ESC:
  13934. evt.stopPropagation();
  13935. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  13936. break;
  13937. }
  13938. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  13939. evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
  13940. if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
  13941. $scope.stopEdit(evt);
  13942. }
  13943. } else {
  13944. //handle enter and tab for editing not using cellNav
  13945. switch (evt.keyCode) {
  13946. case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
  13947. case uiGridConstants.keymap.TAB:
  13948. evt.stopPropagation();
  13949. evt.preventDefault();
  13950. $scope.stopEdit(evt);
  13951. break;
  13952. }
  13953. }
  13954. return true;
  13955. });
  13956. }
  13957. };
  13958. }
  13959. };
  13960. }
  13961. ]);
  13962. /**
  13963. * @ngdoc directive
  13964. * @name ui.grid.edit.directive:uiGridEditFileChooser
  13965. * @element div
  13966. * @restrict A
  13967. *
  13968. * @description input editor directive for editable fields.
  13969. * Provides EndEdit and CancelEdit events
  13970. *
  13971. * Events that end editing:
  13972. * blur and enter keydown
  13973. *
  13974. * Events that cancel editing:
  13975. * - Esc keydown
  13976. *
  13977. */
  13978. module.directive('uiGridEditFileChooser', ['gridUtil', 'uiGridConstants', 'uiGridEditConstants', '$timeout',
  13979. function(gridUtil, uiGridConstants, uiGridEditConstants, $timeout) {
  13980. return {
  13981. scope: true,
  13982. require: ['?^uiGrid', '?^uiGridRenderContainer'],
  13983. compile: function() {
  13984. return {
  13985. pre: function($scope, $elm, $attrs) {
  13986. },
  13987. post: function($scope, $elm, $attrs, controllers) {
  13988. var uiGridCtrl, renderContainerCtrl;
  13989. if (controllers[0]) { uiGridCtrl = controllers[0]; }
  13990. if (controllers[1]) { renderContainerCtrl = controllers[1]; }
  13991. var grid = uiGridCtrl.grid;
  13992. var handleFileSelect = function(event) {
  13993. var target = event.srcElement || event.target;
  13994. if (target && target.files && target.files.length > 0) {
  13995. /**
  13996. * @ngdoc property
  13997. * @name editFileChooserCallback
  13998. * @propertyOf ui.grid.edit.api:ColumnDef
  13999. * @description A function that should be called when any files have been chosen
  14000. * by the user. You should use this to process the files appropriately for your
  14001. * application.
  14002. *
  14003. * It passes the gridCol, the gridRow (from which you can get gridRow.entity),
  14004. * and the files. The files are in the format as returned from the file chooser,
  14005. * an array of files, with each having useful information such as:
  14006. * - `files[0].lastModifiedDate`
  14007. * - `files[0].name`
  14008. * - `files[0].size` (appears to be in bytes)
  14009. * - `files[0].type` (MIME type by the looks)
  14010. *
  14011. * Typically you would do something with these files - most commonly you would
  14012. * use the filename or read the file itself in. The example function does both.
  14013. *
  14014. * @example
  14015. * <pre>
  14016. * editFileChooserCallBack: function(gridRow, gridCol, files ){
  14017. * // ignore all but the first file, it can only choose one anyway
  14018. * // set the filename into this column
  14019. * gridRow.entity.filename = file[0].name;
  14020. *
  14021. * // read the file and set it into a hidden column, which we may do stuff with later
  14022. * var setFile = function(fileContent){
  14023. * gridRow.entity.file = fileContent.currentTarget.result;
  14024. * };
  14025. * var reader = new FileReader();
  14026. * reader.onload = setFile;
  14027. * reader.readAsText( files[0] );
  14028. * }
  14029. * </pre>
  14030. */
  14031. if (typeof($scope.col.colDef.editFileChooserCallback) === 'function') {
  14032. $scope.col.colDef.editFileChooserCallback($scope.row, $scope.col, target.files);
  14033. } else {
  14034. gridUtil.logError('You need to set colDef.editFileChooserCallback to use the file chooser');
  14035. }
  14036. target.form.reset();
  14037. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  14038. } else {
  14039. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  14040. }
  14041. };
  14042. $elm[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google
  14043. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function() {
  14044. $elm[0].focus();
  14045. $elm[0].select();
  14046. $elm.on('blur', function(evt) {
  14047. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  14048. });
  14049. });
  14050. }
  14051. };
  14052. }
  14053. };
  14054. }
  14055. ]);
  14056. })();
  14057. (function() {
  14058. 'use strict';
  14059. /**
  14060. * @ngdoc overview
  14061. * @name ui.grid.expandable
  14062. * @description
  14063. *
  14064. * # ui.grid.expandable
  14065. *
  14066. * <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>
  14067. *
  14068. * This module provides the ability to create subgrids with the ability to expand a row
  14069. * to show the subgrid.
  14070. *
  14071. * <div doc-module-components="ui.grid.expandable"></div>
  14072. */
  14073. var module = angular.module('ui.grid.expandable', ['ui.grid']);
  14074. /**
  14075. * @ngdoc service
  14076. * @name ui.grid.expandable.service:uiGridExpandableService
  14077. *
  14078. * @description Services for the expandable grid
  14079. */
  14080. module.service('uiGridExpandableService', ['gridUtil', '$compile', function(gridUtil, $compile) {
  14081. var service = {
  14082. initializeGrid: function(grid) {
  14083. grid.expandable = {};
  14084. grid.expandable.expandedAll = false;
  14085. /**
  14086. * @ngdoc object
  14087. * @name enableExpandable
  14088. * @propertyOf ui.grid.expandable.api:GridOptions
  14089. * @description Whether or not to use expandable feature, allows you to turn off expandable on specific grids
  14090. * within your application, or in specific modes on _this_ grid. Defaults to true.
  14091. * @example
  14092. * <pre>
  14093. * $scope.gridOptions = {
  14094. * enableExpandable: false
  14095. * }
  14096. * </pre>
  14097. */
  14098. grid.options.enableExpandable = grid.options.enableExpandable !== false;
  14099. /**
  14100. * @ngdoc object
  14101. * @name expandableRowHeight
  14102. * @propertyOf ui.grid.expandable.api:GridOptions
  14103. * @description Height in pixels of the expanded subgrid. Defaults to
  14104. * 150
  14105. * @example
  14106. * <pre>
  14107. * $scope.gridOptions = {
  14108. * expandableRowHeight: 150
  14109. * }
  14110. * </pre>
  14111. */
  14112. grid.options.expandableRowHeight = grid.options.expandableRowHeight || 150;
  14113. /**
  14114. * @ngdoc object
  14115. * @name
  14116. * @propertyOf ui.grid.expandable.api:GridOptions
  14117. * @description Width in pixels of the expandable column. Defaults to 40
  14118. * @example
  14119. * <pre>
  14120. * $scope.gridOptions = {
  14121. * expandableRowHeaderWidth: 40
  14122. * }
  14123. * </pre>
  14124. */
  14125. grid.options.expandableRowHeaderWidth = grid.options.expandableRowHeaderWidth || 40;
  14126. /**
  14127. * @ngdoc object
  14128. * @name expandableRowTemplate
  14129. * @propertyOf ui.grid.expandable.api:GridOptions
  14130. * @description Mandatory. The template for your expanded row
  14131. * @example
  14132. * <pre>
  14133. * $scope.gridOptions = {
  14134. * expandableRowTemplate: 'expandableRowTemplate.html'
  14135. * }
  14136. * </pre>
  14137. */
  14138. if (grid.options.enableExpandable && !grid.options.expandableRowTemplate) {
  14139. gridUtil.logError('You have not set the expandableRowTemplate, disabling expandable module');
  14140. grid.options.enableExpandable = false;
  14141. }
  14142. /**
  14143. * @ngdoc object
  14144. * @name ui.grid.expandable.api:PublicApi
  14145. *
  14146. * @description Public Api for expandable feature
  14147. */
  14148. /**
  14149. * @ngdoc object
  14150. * @name ui.grid.expandable.api:GridOptions
  14151. *
  14152. * @description Options for configuring the expandable feature, these are available to be
  14153. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  14154. */
  14155. var publicApi = {
  14156. events: {
  14157. expandable: {
  14158. /**
  14159. * @ngdoc event
  14160. * @name rowExpandedStateChanged
  14161. * @eventOf ui.grid.expandable.api:PublicApi
  14162. * @description raised when cell editing is complete
  14163. * <pre>
  14164. * gridApi.expandable.on.rowExpandedStateChanged(scope,function(row){})
  14165. * </pre>
  14166. * @param {GridRow} row the row that was expanded
  14167. */
  14168. rowExpandedStateChanged: function(scope, row) {}
  14169. }
  14170. },
  14171. methods: {
  14172. expandable: {
  14173. /**
  14174. * @ngdoc method
  14175. * @name toggleRowExpansion
  14176. * @methodOf ui.grid.expandable.api:PublicApi
  14177. * @description Toggle a specific row
  14178. * <pre>
  14179. * gridApi.expandable.toggleRowExpansion(rowEntity);
  14180. * </pre>
  14181. * @param {object} rowEntity the data entity for the row you want to expand
  14182. */
  14183. toggleRowExpansion: function(rowEntity) {
  14184. var row = grid.getRow(rowEntity);
  14185. if (row !== null) {
  14186. service.toggleRowExpansion(grid, row);
  14187. }
  14188. },
  14189. /**
  14190. * @ngdoc method
  14191. * @name expandAllRows
  14192. * @methodOf ui.grid.expandable.api:PublicApi
  14193. * @description Expand all subgrids.
  14194. * <pre>
  14195. * gridApi.expandable.expandAllRows();
  14196. * </pre>
  14197. */
  14198. expandAllRows: function() {
  14199. service.expandAllRows(grid);
  14200. },
  14201. /**
  14202. * @ngdoc method
  14203. * @name collapseAllRows
  14204. * @methodOf ui.grid.expandable.api:PublicApi
  14205. * @description Collapse all subgrids.
  14206. * <pre>
  14207. * gridApi.expandable.collapseAllRows();
  14208. * </pre>
  14209. */
  14210. collapseAllRows: function() {
  14211. service.collapseAllRows(grid);
  14212. },
  14213. /**
  14214. * @ngdoc method
  14215. * @name toggleAllRows
  14216. * @methodOf ui.grid.expandable.api:PublicApi
  14217. * @description Toggle all subgrids.
  14218. * <pre>
  14219. * gridApi.expandable.toggleAllRows();
  14220. * </pre>
  14221. */
  14222. toggleAllRows: function() {
  14223. service.toggleAllRows(grid);
  14224. }
  14225. }
  14226. }
  14227. };
  14228. grid.api.registerEventsFromObject(publicApi.events);
  14229. grid.api.registerMethodsFromObject(publicApi.methods);
  14230. },
  14231. toggleRowExpansion: function(grid, row) {
  14232. row.isExpanded = !row.isExpanded;
  14233. if (row.isExpanded) {
  14234. row.height = row.grid.options.rowHeight + grid.options.expandableRowHeight;
  14235. } else {
  14236. row.height = row.grid.options.rowHeight;
  14237. grid.expandable.expandedAll = false;
  14238. }
  14239. grid.api.expandable.raise.rowExpandedStateChanged(row);
  14240. },
  14241. expandAllRows: function(grid, $scope) {
  14242. grid.renderContainers.body.visibleRowCache.forEach(function(row) {
  14243. if (!row.isExpanded) {
  14244. service.toggleRowExpansion(grid, row);
  14245. }
  14246. });
  14247. grid.expandable.expandedAll = true;
  14248. grid.queueGridRefresh();
  14249. },
  14250. collapseAllRows: function(grid) {
  14251. grid.renderContainers.body.visibleRowCache.forEach(function(row) {
  14252. if (row.isExpanded) {
  14253. service.toggleRowExpansion(grid, row);
  14254. }
  14255. });
  14256. grid.expandable.expandedAll = false;
  14257. grid.queueGridRefresh();
  14258. },
  14259. toggleAllRows: function(grid) {
  14260. if (grid.expandable.expandedAll) {
  14261. service.collapseAllRows(grid);
  14262. } else {
  14263. service.expandAllRows(grid);
  14264. }
  14265. }
  14266. };
  14267. return service;
  14268. }]);
  14269. /**
  14270. * @ngdoc object
  14271. * @name enableExpandableRowHeader
  14272. * @propertyOf ui.grid.expandable.api:GridOptions
  14273. * @description Show a rowHeader to provide the expandable buttons. If set to false then implies
  14274. * you're going to use a custom method for expanding and collapsing the subgrids. Defaults to true.
  14275. * @example
  14276. * <pre>
  14277. * $scope.gridOptions = {
  14278. * enableExpandableRowHeader: false
  14279. * }
  14280. * </pre>
  14281. */
  14282. module.directive('uiGridExpandable', ['uiGridExpandableService', '$templateCache',
  14283. function(uiGridExpandableService, $templateCache) {
  14284. return {
  14285. replace: true,
  14286. priority: 0,
  14287. require: '^uiGrid',
  14288. scope: false,
  14289. compile: function() {
  14290. return {
  14291. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  14292. if (uiGridCtrl.grid.options.enableExpandableRowHeader !== false) {
  14293. var expandableRowHeaderColDef = {
  14294. name: 'expandableButtons',
  14295. displayName: '',
  14296. exporterSuppressExport: true,
  14297. enableColumnResizing: false,
  14298. enableColumnMenu: false,
  14299. width: uiGridCtrl.grid.options.expandableRowHeaderWidth || 40
  14300. };
  14301. expandableRowHeaderColDef.cellTemplate = $templateCache.get('ui-grid/expandableRowHeader');
  14302. expandableRowHeaderColDef.headerCellTemplate = $templateCache.get('ui-grid/expandableTopRowHeader');
  14303. uiGridCtrl.grid.addRowHeaderColumn(expandableRowHeaderColDef);
  14304. }
  14305. uiGridExpandableService.initializeGrid(uiGridCtrl.grid);
  14306. },
  14307. post: function($scope, $elm, $attrs, uiGridCtrl) {}
  14308. };
  14309. }
  14310. };
  14311. }
  14312. ]);
  14313. /**
  14314. * @ngdoc directive
  14315. * @name ui.grid.expandable.directive:uiGrid
  14316. * @description stacks on the uiGrid directive to register child grid with parent row when child is created
  14317. */
  14318. module.directive('uiGrid', ['uiGridExpandableService', '$templateCache',
  14319. function(uiGridExpandableService, $templateCache) {
  14320. return {
  14321. replace: true,
  14322. priority: 599,
  14323. require: '^uiGrid',
  14324. scope: false,
  14325. compile: function() {
  14326. return {
  14327. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  14328. uiGridCtrl.grid.api.core.on.renderingComplete($scope, function() {
  14329. //if a parent grid row is on the scope, then add the parentRow property to this childGrid
  14330. if ($scope.row && $scope.row.grid && $scope.row.grid.options && $scope.row.grid.options.enableExpandable) {
  14331. /**
  14332. * @ngdoc directive
  14333. * @name ui.grid.expandable.class:Grid
  14334. * @description Additional Grid properties added by expandable module
  14335. */
  14336. /**
  14337. * @ngdoc object
  14338. * @name parentRow
  14339. * @propertyOf ui.grid.expandable.class:Grid
  14340. * @description reference to the expanded parent row that owns this grid
  14341. */
  14342. uiGridCtrl.grid.parentRow = $scope.row;
  14343. //todo: adjust height on parent row when child grid height changes. we need some sort of gridHeightChanged event
  14344. // uiGridCtrl.grid.core.on.canvasHeightChanged($scope, function(oldHeight, newHeight) {
  14345. // uiGridCtrl.grid.parentRow = newHeight;
  14346. // });
  14347. }
  14348. });
  14349. },
  14350. post: function($scope, $elm, $attrs, uiGridCtrl) {
  14351. }
  14352. };
  14353. }
  14354. };
  14355. }
  14356. ]);
  14357. /**
  14358. * @ngdoc directive
  14359. * @name ui.grid.expandable.directive:uiGridExpandableRow
  14360. * @description directive to render the expandable row template
  14361. */
  14362. module.directive('uiGridExpandableRow', ['uiGridExpandableService', '$timeout', '$compile', 'uiGridConstants', 'gridUtil', '$interval', '$log',
  14363. function(uiGridExpandableService, $timeout, $compile, uiGridConstants, gridUtil, $interval, $log) {
  14364. return {
  14365. replace: false,
  14366. priority: 0,
  14367. scope: false,
  14368. compile: function() {
  14369. return {
  14370. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  14371. gridUtil.getTemplate($scope.grid.options.expandableRowTemplate).then(
  14372. function(template) {
  14373. if ($scope.grid.options.expandableRowScope) {
  14374. var expandableRowScope = $scope.grid.options.expandableRowScope;
  14375. for (var property in expandableRowScope) {
  14376. if (expandableRowScope.hasOwnProperty(property)) {
  14377. $scope[property] = expandableRowScope[property];
  14378. }
  14379. }
  14380. }
  14381. var expandedRowElement = $compile(template)($scope);
  14382. $elm.append(expandedRowElement);
  14383. $scope.row.expandedRendered = true;
  14384. });
  14385. },
  14386. post: function($scope, $elm, $attrs, uiGridCtrl) {
  14387. $scope.$on('$destroy', function() {
  14388. $scope.row.expandedRendered = false;
  14389. });
  14390. }
  14391. };
  14392. }
  14393. };
  14394. }
  14395. ]);
  14396. /**
  14397. * @ngdoc directive
  14398. * @name ui.grid.expandable.directive:uiGridRow
  14399. * @description stacks on the uiGridRow directive to add support for expandable rows
  14400. */
  14401. module.directive('uiGridRow', ['$compile', 'gridUtil', '$templateCache',
  14402. function($compile, gridUtil, $templateCache) {
  14403. return {
  14404. priority: -200,
  14405. scope: false,
  14406. compile: function($elm, $attrs) {
  14407. return {
  14408. pre: function($scope, $elm, $attrs, controllers) {
  14409. $scope.expandableRow = {};
  14410. $scope.expandableRow.shouldRenderExpand = function() {
  14411. var ret = $scope.colContainer.name === 'body' && $scope.grid.options.enableExpandable !== false && $scope.row.isExpanded && (!$scope.grid.isScrollingVertically || $scope.row.expandedRendered);
  14412. return ret;
  14413. };
  14414. $scope.expandableRow.shouldRenderFiller = function() {
  14415. var ret = $scope.row.isExpanded && ($scope.colContainer.name !== 'body' || ($scope.grid.isScrollingVertically && !$scope.row.expandedRendered));
  14416. return ret;
  14417. };
  14418. /*
  14419. * Commented out @PaulL1. This has no purpose that I can see, and causes #2964. If this code needs to be reinstated for some
  14420. * reason it needs to use drawnWidth, not width, and needs to check column visibility. It should really use render container
  14421. * visible column cache also instead of checking column.renderContainer.
  14422. function updateRowContainerWidth() {
  14423. var grid = $scope.grid;
  14424. var colWidth = 0;
  14425. grid.columns.forEach( function (column) {
  14426. if (column.renderContainer === 'left') {
  14427. colWidth += column.width;
  14428. }
  14429. });
  14430. colWidth = Math.floor(colWidth);
  14431. return '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.colContainer.name + ', .grid' + grid.id +
  14432. ' .ui-grid-pinned-container-' + $scope.colContainer.name + ' .ui-grid-render-container-' + $scope.colContainer.name +
  14433. ' .ui-grid-viewport .ui-grid-canvas .ui-grid-row { width: ' + colWidth + 'px; }';
  14434. }
  14435. if ($scope.colContainer.name === 'left') {
  14436. $scope.grid.registerStyleComputation({
  14437. priority: 15,
  14438. func: updateRowContainerWidth
  14439. });
  14440. }*/
  14441. },
  14442. post: function($scope, $elm, $attrs, controllers) {}
  14443. };
  14444. }
  14445. };
  14446. }
  14447. ]);
  14448. /**
  14449. * @ngdoc directive
  14450. * @name ui.grid.expandable.directive:uiGridViewport
  14451. * @description stacks on the uiGridViewport directive to append the expandable row html elements to the
  14452. * default gridRow template
  14453. */
  14454. module.directive('uiGridViewport', ['$compile', 'gridUtil', '$templateCache',
  14455. function($compile, gridUtil, $templateCache) {
  14456. return {
  14457. priority: -200,
  14458. scope: false,
  14459. compile: function($elm, $attrs) {
  14460. var rowRepeatDiv = angular.element($elm.children().children()[0]);
  14461. var expandedRowFillerElement = $templateCache.get('ui-grid/expandableScrollFiller');
  14462. var expandedRowElement = $templateCache.get('ui-grid/expandableRow');
  14463. rowRepeatDiv.append(expandedRowElement);
  14464. rowRepeatDiv.append(expandedRowFillerElement);
  14465. return {
  14466. pre: function($scope, $elm, $attrs, controllers) {},
  14467. post: function($scope, $elm, $attrs, controllers) {}
  14468. };
  14469. }
  14470. };
  14471. }
  14472. ]);
  14473. })();
  14474. /* global console */
  14475. (function() {
  14476. 'use strict';
  14477. /**
  14478. * @ngdoc overview
  14479. * @name ui.grid.exporter
  14480. * @description
  14481. *
  14482. * # ui.grid.exporter
  14483. *
  14484. * <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>
  14485. *
  14486. * This module provides the ability to exporter data from the grid.
  14487. *
  14488. * Data can be exported in a range of formats, and all data, visible
  14489. * data, or selected rows can be exported, with all columns or visible
  14490. * columns.
  14491. *
  14492. * No UI is provided, the caller should provide their own UI/buttons
  14493. * as appropriate, or enable the gridMenu
  14494. *
  14495. * <br/>
  14496. * <br/>
  14497. *
  14498. * <div doc-module-components="ui.grid.exporter"></div>
  14499. */
  14500. var module = angular.module('ui.grid.exporter', ['ui.grid']);
  14501. /**
  14502. * @ngdoc object
  14503. * @name ui.grid.exporter.constant:uiGridExporterConstants
  14504. *
  14505. * @description constants available in exporter module
  14506. */
  14507. /**
  14508. * @ngdoc property
  14509. * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
  14510. * @name ALL
  14511. * @description export all data, including data not visible. Can
  14512. * be set for either rowTypes or colTypes
  14513. */
  14514. /**
  14515. * @ngdoc property
  14516. * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
  14517. * @name VISIBLE
  14518. * @description export only visible data, including data not visible. Can
  14519. * be set for either rowTypes or colTypes
  14520. */
  14521. /**
  14522. * @ngdoc property
  14523. * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
  14524. * @name SELECTED
  14525. * @description export all data, including data not visible. Can
  14526. * be set only for rowTypes, selection of only some columns is
  14527. * not supported
  14528. */
  14529. module.constant('uiGridExporterConstants', {
  14530. featureName: 'exporter',
  14531. ALL: 'all',
  14532. VISIBLE: 'visible',
  14533. SELECTED: 'selected',
  14534. CSV_CONTENT: 'CSV_CONTENT',
  14535. BUTTON_LABEL: 'BUTTON_LABEL',
  14536. FILE_NAME: 'FILE_NAME'
  14537. });
  14538. /**
  14539. * @ngdoc service
  14540. * @name ui.grid.exporter.service:uiGridExporterService
  14541. *
  14542. * @description Services for exporter feature
  14543. */
  14544. module.service('uiGridExporterService', ['$q', 'uiGridExporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService',
  14545. function($q, uiGridExporterConstants, gridUtil, $compile, $interval, i18nService) {
  14546. var service = {
  14547. delay: 100,
  14548. initializeGrid: function(grid) {
  14549. //add feature namespace and any properties to grid for needed state
  14550. grid.exporter = {};
  14551. this.defaultGridOptions(grid.options);
  14552. /**
  14553. * @ngdoc object
  14554. * @name ui.grid.exporter.api:PublicApi
  14555. *
  14556. * @description Public Api for exporter feature
  14557. */
  14558. var publicApi = {
  14559. events: {
  14560. exporter: {}
  14561. },
  14562. methods: {
  14563. exporter: {
  14564. /**
  14565. * @ngdoc function
  14566. * @name csvExport
  14567. * @methodOf ui.grid.exporter.api:PublicApi
  14568. * @description Exports rows from the grid in csv format,
  14569. * the data exported is selected based on the provided options
  14570. * @param {string} rowTypes which rows to export, valid values are
  14571. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  14572. * uiGridExporterConstants.SELECTED
  14573. * @param {string} colTypes which columns to export, valid values are
  14574. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE
  14575. */
  14576. csvExport: function(rowTypes, colTypes) {
  14577. service.csvExport(grid, rowTypes, colTypes);
  14578. },
  14579. /**
  14580. * @ngdoc function
  14581. * @name pdfExport
  14582. * @methodOf ui.grid.exporter.api:PublicApi
  14583. * @description Exports rows from the grid in pdf format,
  14584. * the data exported is selected based on the provided options
  14585. * Note that this function has a dependency on pdfMake, all
  14586. * going well this has been installed for you.
  14587. * The resulting pdf opens in a new browser window.
  14588. * @param {string} rowTypes which rows to export, valid values are
  14589. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  14590. * uiGridExporterConstants.SELECTED
  14591. * @param {string} colTypes which columns to export, valid values are
  14592. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE
  14593. */
  14594. pdfExport: function(rowTypes, colTypes) {
  14595. service.pdfExport(grid, rowTypes, colTypes);
  14596. }
  14597. }
  14598. }
  14599. };
  14600. grid.api.registerEventsFromObject(publicApi.events);
  14601. grid.api.registerMethodsFromObject(publicApi.methods);
  14602. if (grid.api.core.addToGridMenu) {
  14603. service.addToMenu(grid);
  14604. } else {
  14605. // order of registration is not guaranteed, register in a little while
  14606. $interval(function() {
  14607. if (grid.api.core.addToGridMenu) {
  14608. service.addToMenu(grid);
  14609. }
  14610. }, this.delay, 1);
  14611. }
  14612. },
  14613. defaultGridOptions: function(gridOptions) {
  14614. //default option to true unless it was explicitly set to false
  14615. /**
  14616. * @ngdoc object
  14617. * @name ui.grid.exporter.api:GridOptions
  14618. *
  14619. * @description GridOptions for exporter feature, these are available to be
  14620. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  14621. */
  14622. /**
  14623. * @ngdoc object
  14624. * @name ui.grid.exporter.api:ColumnDef
  14625. * @description ColumnDef settings for exporter
  14626. */
  14627. /**
  14628. * @ngdoc object
  14629. * @name exporterSuppressMenu
  14630. * @propertyOf ui.grid.exporter.api:GridOptions
  14631. * @description Don't show the export menu button, implying the user
  14632. * will roll their own UI for calling the exporter
  14633. * <br/>Defaults to false
  14634. */
  14635. gridOptions.exporterSuppressMenu = gridOptions.exporterSuppressMenu === true;
  14636. /**
  14637. * @ngdoc object
  14638. * @name exporterMenuLabel
  14639. * @propertyOf ui.grid.exporter.api:GridOptions
  14640. * @description The text to show on the exporter menu button
  14641. * link
  14642. * <br/>Defaults to 'Export'
  14643. */
  14644. gridOptions.exporterMenuLabel = gridOptions.exporterMenuLabel ? gridOptions.exporterMenuLabel : 'Export';
  14645. /**
  14646. * @ngdoc object
  14647. * @name exporterSuppressColumns
  14648. * @propertyOf ui.grid.exporter.api:GridOptions
  14649. * @description Columns that should not be exported. The selectionRowHeader is already automatically
  14650. * suppressed, but if you had a button column or some other "system" column that shouldn't be shown in the
  14651. * output then add it in this list. You should provide an array of column names.
  14652. * <br/>Defaults to: []
  14653. * <pre>
  14654. * gridOptions.exporterSuppressColumns = [ 'buttons' ];
  14655. * </pre>
  14656. */
  14657. gridOptions.exporterSuppressColumns = gridOptions.exporterSuppressColumns ? gridOptions.exporterSuppressColumns : [];
  14658. /**
  14659. * @ngdoc object
  14660. * @name exporterCsvColumnSeparator
  14661. * @propertyOf ui.grid.exporter.api:GridOptions
  14662. * @description The character to use as column separator
  14663. * link
  14664. * <br/>Defaults to ','
  14665. */
  14666. gridOptions.exporterCsvColumnSeparator = gridOptions.exporterCsvColumnSeparator ? gridOptions.exporterCsvColumnSeparator : ',';
  14667. /**
  14668. * @ngdoc object
  14669. * @name exporterCsvFilename
  14670. * @propertyOf ui.grid.exporter.api:GridOptions
  14671. * @description The default filename to use when saving the downloaded csv.
  14672. * This will only work in some browsers.
  14673. * <br/>Defaults to 'download.csv'
  14674. */
  14675. gridOptions.exporterCsvFilename = gridOptions.exporterCsvFilename ? gridOptions.exporterCsvFilename : 'download.csv';
  14676. /**
  14677. * @ngdoc object
  14678. * @name exporterPdfFilename
  14679. * @propertyOf ui.grid.exporter.api:GridOptions
  14680. * @description The default filename to use when saving the downloaded pdf, only used in IE (other browsers open pdfs in a new window)
  14681. * <br/>Defaults to 'download.pdf'
  14682. */
  14683. gridOptions.exporterPdfFilename = gridOptions.exporterPdfFilename ? gridOptions.exporterPdfFilename : 'download.pdf';
  14684. /**
  14685. * @ngdoc object
  14686. * @name exporterOlderExcelCompatibility
  14687. * @propertyOf ui.grid.exporter.api:GridOptions
  14688. * @description Some versions of excel don't like the utf-16 BOM on the front, and it comes
  14689. * through as  in the first column header. Setting this option to false will suppress this, at the
  14690. * expense of proper utf-16 handling in applications that do recognise the BOM
  14691. * <br/>Defaults to false
  14692. */
  14693. gridOptions.exporterOlderExcelCompatibility = gridOptions.exporterOlderExcelCompatibility === true;
  14694. /**
  14695. * @ngdoc object
  14696. * @name exporterPdfDefaultStyle
  14697. * @propertyOf ui.grid.exporter.api:GridOptions
  14698. * @description The default style in pdfMake format
  14699. * <br/>Defaults to:
  14700. * <pre>
  14701. * {
  14702. * fontSize: 11
  14703. * }
  14704. * </pre>
  14705. */
  14706. gridOptions.exporterPdfDefaultStyle = gridOptions.exporterPdfDefaultStyle ? gridOptions.exporterPdfDefaultStyle : { fontSize: 11 };
  14707. /**
  14708. * @ngdoc object
  14709. * @name exporterPdfTableStyle
  14710. * @propertyOf ui.grid.exporter.api:GridOptions
  14711. * @description The table style in pdfMake format
  14712. * <br/>Defaults to:
  14713. * <pre>
  14714. * {
  14715. * margin: [0, 5, 0, 15]
  14716. * }
  14717. * </pre>
  14718. */
  14719. gridOptions.exporterPdfTableStyle = gridOptions.exporterPdfTableStyle ? gridOptions.exporterPdfTableStyle : { margin: [0, 5, 0, 15] };
  14720. /**
  14721. * @ngdoc object
  14722. * @name exporterPdfTableHeaderStyle
  14723. * @propertyOf ui.grid.exporter.api:GridOptions
  14724. * @description The tableHeader style in pdfMake format
  14725. * <br/>Defaults to:
  14726. * <pre>
  14727. * {
  14728. * bold: true,
  14729. * fontSize: 12,
  14730. * color: 'black'
  14731. * }
  14732. * </pre>
  14733. */
  14734. gridOptions.exporterPdfTableHeaderStyle = gridOptions.exporterPdfTableHeaderStyle ? gridOptions.exporterPdfTableHeaderStyle : { bold: true, fontSize: 12, color: 'black' };
  14735. /**
  14736. * @ngdoc object
  14737. * @name exporterPdfHeader
  14738. * @propertyOf ui.grid.exporter.api:GridOptions
  14739. * @description The header section for pdf exports. Can be
  14740. * simple text:
  14741. * <pre>
  14742. * gridOptions.exporterPdfHeader = 'My Header';
  14743. * </pre>
  14744. * Can be a more complex object in pdfMake format:
  14745. * <pre>
  14746. * gridOptions.exporterPdfHeader = {
  14747. * columns: [
  14748. * 'Left part',
  14749. * { text: 'Right part', alignment: 'right' }
  14750. * ]
  14751. * };
  14752. * </pre>
  14753. * Or can be a function, allowing page numbers and the like
  14754. * <pre>
  14755. * gridOptions.exporterPdfHeader: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; };
  14756. * </pre>
  14757. */
  14758. gridOptions.exporterPdfHeader = gridOptions.exporterPdfHeader ? gridOptions.exporterPdfHeader : null;
  14759. /**
  14760. * @ngdoc object
  14761. * @name exporterPdfFooter
  14762. * @propertyOf ui.grid.exporter.api:GridOptions
  14763. * @description The header section for pdf exports. Can be
  14764. * simple text:
  14765. * <pre>
  14766. * gridOptions.exporterPdfFooter = 'My Footer';
  14767. * </pre>
  14768. * Can be a more complex object in pdfMake format:
  14769. * <pre>
  14770. * gridOptions.exporterPdfFooter = {
  14771. * columns: [
  14772. * 'Left part',
  14773. * { text: 'Right part', alignment: 'right' }
  14774. * ]
  14775. * };
  14776. * </pre>
  14777. * Or can be a function, allowing page numbers and the like
  14778. * <pre>
  14779. * gridOptions.exporterPdfFooter: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; };
  14780. * </pre>
  14781. */
  14782. gridOptions.exporterPdfFooter = gridOptions.exporterPdfFooter ? gridOptions.exporterPdfFooter : null;
  14783. /**
  14784. * @ngdoc object
  14785. * @name exporterPdfOrientation
  14786. * @propertyOf ui.grid.exporter.api:GridOptions
  14787. * @description The orientation, should be a valid pdfMake value,
  14788. * 'landscape' or 'portrait'
  14789. * <br/>Defaults to landscape
  14790. */
  14791. gridOptions.exporterPdfOrientation = gridOptions.exporterPdfOrientation ? gridOptions.exporterPdfOrientation : 'landscape';
  14792. /**
  14793. * @ngdoc object
  14794. * @name exporterPdfPageSize
  14795. * @propertyOf ui.grid.exporter.api:GridOptions
  14796. * @description The orientation, should be a valid pdfMake
  14797. * paper size, usually 'A4' or 'LETTER'
  14798. * {@link https://github.com/bpampuch/pdfmake/blob/master/src/standardPageSizes.js pdfMake page sizes}
  14799. * <br/>Defaults to A4
  14800. */
  14801. gridOptions.exporterPdfPageSize = gridOptions.exporterPdfPageSize ? gridOptions.exporterPdfPageSize : 'A4';
  14802. /**
  14803. * @ngdoc object
  14804. * @name exporterPdfMaxGridWidth
  14805. * @propertyOf ui.grid.exporter.api:GridOptions
  14806. * @description The maxium grid width - the current grid width
  14807. * will be scaled to match this, with any fixed width columns
  14808. * being adjusted accordingly.
  14809. * <br/>Defaults to 720 (for A4 landscape), use 670 for LETTER
  14810. */
  14811. gridOptions.exporterPdfMaxGridWidth = gridOptions.exporterPdfMaxGridWidth ? gridOptions.exporterPdfMaxGridWidth : 720;
  14812. /**
  14813. * @ngdoc object
  14814. * @name exporterPdfTableLayout
  14815. * @propertyOf ui.grid.exporter.api:GridOptions
  14816. * @description A tableLayout in pdfMake format,
  14817. * controls gridlines and the like. We use the default
  14818. * layout usually.
  14819. * <br/>Defaults to null, which means no layout
  14820. */
  14821. /**
  14822. * @ngdoc object
  14823. * @name exporterMenuAllData
  14824. * @porpertyOf ui.grid.exporter.api:GridOptions
  14825. * @description Add export all data as cvs/pdf menu items to the ui-grid grid menu, if it's present. Defaults to true.
  14826. */
  14827. gridOptions.exporterMenuAllData = gridOptions.exporterMenuAllData !== undefined ? gridOptions.exporterMenuAllData : true;
  14828. /**
  14829. * @ngdoc object
  14830. * @name exporterMenuCsv
  14831. * @propertyOf ui.grid.exporter.api:GridOptions
  14832. * @description Add csv export menu items to the ui-grid grid menu, if it's present. Defaults to true.
  14833. */
  14834. gridOptions.exporterMenuCsv = gridOptions.exporterMenuCsv !== undefined ? gridOptions.exporterMenuCsv : true;
  14835. /**
  14836. * @ngdoc object
  14837. * @name exporterMenuPdf
  14838. * @propertyOf ui.grid.exporter.api:GridOptions
  14839. * @description Add pdf export menu items to the ui-grid grid menu, if it's present. Defaults to true.
  14840. */
  14841. gridOptions.exporterMenuPdf = gridOptions.exporterMenuPdf !== undefined ? gridOptions.exporterMenuPdf : true;
  14842. /**
  14843. * @ngdoc object
  14844. * @name exporterPdfCustomFormatter
  14845. * @propertyOf ui.grid.exporter.api:GridOptions
  14846. * @description A custom callback routine that changes the pdf document, adding any
  14847. * custom styling or content that is supported by pdfMake. Takes in the complete docDefinition, and
  14848. * must return an updated docDefinition ready for pdfMake.
  14849. * @example
  14850. * In this example we add a style to the style array, so that we can use it in our
  14851. * footer definition.
  14852. * <pre>
  14853. * gridOptions.exporterPdfCustomFormatter = function ( docDefinition ) {
  14854. * docDefinition.styles.footerStyle = { bold: true, fontSize: 10 };
  14855. * return docDefinition;
  14856. * }
  14857. *
  14858. * gridOptions.exporterPdfFooter = { text: 'My footer', style: 'footerStyle' }
  14859. * </pre>
  14860. */
  14861. gridOptions.exporterPdfCustomFormatter = (gridOptions.exporterPdfCustomFormatter && typeof(gridOptions.exporterPdfCustomFormatter) === 'function') ? gridOptions.exporterPdfCustomFormatter : function(docDef) { return docDef; };
  14862. /**
  14863. * @ngdoc object
  14864. * @name exporterHeaderFilterUseName
  14865. * @propertyOf ui.grid.exporter.api:GridOptions
  14866. * @description Defaults to false, which leads to `displayName` being passed into the headerFilter.
  14867. * If set to true, then will pass `name` instead.
  14868. *
  14869. *
  14870. * @example
  14871. * <pre>
  14872. * gridOptions.exporterHeaderFilterUseName = true;
  14873. * </pre>
  14874. */
  14875. gridOptions.exporterHeaderFilterUseName = gridOptions.exporterHeaderFilterUseName === true;
  14876. /**
  14877. * @ngdoc object
  14878. * @name exporterHeaderFilter
  14879. * @propertyOf ui.grid.exporter.api:GridOptions
  14880. * @description A function to apply to the header displayNames before exporting. Useful for internationalisation,
  14881. * for example if you were using angular-translate you'd set this to `$translate.instant`. Note that this
  14882. * call must be synchronous, it cannot be a call that returns a promise.
  14883. *
  14884. * Behaviour can be changed to pass in `name` instead of `displayName` through use of `exporterHeaderFilterUseName: true`.
  14885. *
  14886. * @example
  14887. * <pre>
  14888. * gridOptions.exporterHeaderFilter = function( displayName ){ return 'col: ' + name; };
  14889. * </pre>
  14890. * OR
  14891. * <pre>
  14892. * gridOptions.exporterHeaderFilter = $translate.instant;
  14893. * </pre>
  14894. */
  14895. /**
  14896. * @ngdoc function
  14897. * @name exporterFieldCallback
  14898. * @propertyOf ui.grid.exporter.api:GridOptions
  14899. * @description A function to call for each field before exporting it. Allows
  14900. * massaging of raw data into a display format, for example if you have applied
  14901. * filters to convert codes into decodes, or you require
  14902. * a specific date format in the exported content.
  14903. *
  14904. * The method is called once for each field exported, and provides the grid, the
  14905. * gridCol and the GridRow for you to use as context in massaging the data.
  14906. *
  14907. * @param {Grid} grid provides the grid in case you have need of it
  14908. * @param {GridRow} row the row from which the data comes
  14909. * @param {GridCol} col the column from which the data comes
  14910. * @param {object} value the value for your massaging
  14911. * @returns {object} you must return the massaged value ready for exporting
  14912. *
  14913. * @example
  14914. * <pre>
  14915. * gridOptions.exporterFieldCallback = function ( grid, row, col, value ){
  14916. * if ( col.name === 'status' ){
  14917. * value = decodeStatus( value );
  14918. * }
  14919. * return value;
  14920. * }
  14921. * </pre>
  14922. */
  14923. gridOptions.exporterFieldCallback = gridOptions.exporterFieldCallback ? gridOptions.exporterFieldCallback : function(grid, row, col, value) { return value; };
  14924. /**
  14925. * @ngdoc function
  14926. * @name exporterAllDataFn
  14927. * @propertyOf ui.grid.exporter.api:GridOptions
  14928. * @description This promise is needed when exporting all rows,
  14929. * and the data need to be provided by server side. Default is null.
  14930. * @returns {Promise} a promise to load all data from server
  14931. *
  14932. * @example
  14933. * <pre>
  14934. * gridOptions.exporterAllDataFn = function () {
  14935. * return $http.get('/data/100.json')
  14936. * }
  14937. * </pre>
  14938. */
  14939. gridOptions.exporterAllDataFn = gridOptions.exporterAllDataFn ? gridOptions.exporterAllDataFn : null;
  14940. /**
  14941. * @ngdoc function
  14942. * @name exporterAllDataPromise
  14943. * @propertyOf ui.grid.exporter.api:GridOptions
  14944. * @description DEPRECATED - exporterAllDataFn used to be
  14945. * called this, but it wasn't a promise, it was a function that returned
  14946. * a promise. Deprecated, but supported for backward compatibility, use
  14947. * exporterAllDataFn instead.
  14948. * @returns {Promise} a promise to load all data from server
  14949. *
  14950. * @example
  14951. * <pre>
  14952. * gridOptions.exporterAllDataFn = function () {
  14953. * return $http.get('/data/100.json')
  14954. * }
  14955. * </pre>
  14956. */
  14957. if (gridOptions.exporterAllDataFn == null && gridOptions.exporterAllDataPromise) {
  14958. gridOptions.exporterAllDataFn = gridOptions.exporterAllDataPromise;
  14959. }
  14960. },
  14961. /**
  14962. * @ngdoc function
  14963. * @name addToMenu
  14964. * @methodOf ui.grid.exporter.service:uiGridExporterService
  14965. * @description Adds export items to the grid menu,
  14966. * allowing the user to select export options
  14967. * @param {Grid} grid the grid from which data should be exported
  14968. */
  14969. addToMenu: function(grid) {
  14970. grid.api.core.addToGridMenu(grid, [{
  14971. title: i18nService.getSafeText('gridMenu.exporterAllAsCsv'),
  14972. action: function($event) {
  14973. this.grid.api.exporter.csvExport(uiGridExporterConstants.ALL, uiGridExporterConstants.ALL);
  14974. },
  14975. shown: function() {
  14976. return this.grid.options.exporterMenuCsv && this.grid.options.exporterMenuAllData;
  14977. },
  14978. order: 200
  14979. },
  14980. {
  14981. title: i18nService.getSafeText('gridMenu.exporterVisibleAsCsv'),
  14982. action: function($event) {
  14983. this.grid.api.exporter.csvExport(uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE);
  14984. },
  14985. shown: function() {
  14986. return this.grid.options.exporterMenuCsv;
  14987. },
  14988. order: 201
  14989. },
  14990. {
  14991. title: i18nService.getSafeText('gridMenu.exporterSelectedAsCsv'),
  14992. action: function($event) {
  14993. this.grid.api.exporter.csvExport(uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE);
  14994. },
  14995. shown: function() {
  14996. return this.grid.options.exporterMenuCsv &&
  14997. (this.grid.api.selection && this.grid.api.selection.getSelectedRows().length > 0);
  14998. },
  14999. order: 202
  15000. },
  15001. {
  15002. title: i18nService.getSafeText('gridMenu.exporterAllAsPdf'),
  15003. action: function($event) {
  15004. this.grid.api.exporter.pdfExport(uiGridExporterConstants.ALL, uiGridExporterConstants.ALL);
  15005. },
  15006. shown: function() {
  15007. return this.grid.options.exporterMenuPdf && this.grid.options.exporterMenuAllData;
  15008. },
  15009. order: 203
  15010. },
  15011. {
  15012. title: i18nService.getSafeText('gridMenu.exporterVisibleAsPdf'),
  15013. action: function($event) {
  15014. this.grid.api.exporter.pdfExport(uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE);
  15015. },
  15016. shown: function() {
  15017. return this.grid.options.exporterMenuPdf;
  15018. },
  15019. order: 204
  15020. },
  15021. {
  15022. title: i18nService.getSafeText('gridMenu.exporterSelectedAsPdf'),
  15023. action: function($event) {
  15024. this.grid.api.exporter.pdfExport(uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE);
  15025. },
  15026. shown: function() {
  15027. return this.grid.options.exporterMenuPdf &&
  15028. (this.grid.api.selection && this.grid.api.selection.getSelectedRows().length > 0);
  15029. },
  15030. order: 205
  15031. }
  15032. ]);
  15033. },
  15034. /**
  15035. * @ngdoc function
  15036. * @name csvExport
  15037. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15038. * @description Exports rows from the grid in csv format,
  15039. * the data exported is selected based on the provided options
  15040. * @param {Grid} grid the grid from which data should be exported
  15041. * @param {string} rowTypes which rows to export, valid values are
  15042. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15043. * uiGridExporterConstants.SELECTED
  15044. * @param {string} colTypes which columns to export, valid values are
  15045. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15046. * uiGridExporterConstants.SELECTED
  15047. */
  15048. csvExport: function(grid, rowTypes, colTypes) {
  15049. var self = this;
  15050. this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function() {
  15051. var exportColumnHeaders = self.getColumnHeaders(grid, colTypes);
  15052. var exportData = self.getData(grid, rowTypes, colTypes);
  15053. var csvContent = self.formatAsCsv(exportColumnHeaders, exportData, grid.options.exporterCsvColumnSeparator);
  15054. self.downloadFile(grid.options.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
  15055. });
  15056. },
  15057. /**
  15058. * @ngdoc function
  15059. * @name loadAllDataIfNeeded
  15060. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15061. * @description When using server side pagination, use exporterAllDataFn to
  15062. * load all data before continuing processing.
  15063. * When using client side pagination, return a resolved promise so processing
  15064. * continues immediately
  15065. * @param {Grid} grid the grid from which data should be exported
  15066. * @param {string} rowTypes which rows to export, valid values are
  15067. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15068. * uiGridExporterConstants.SELECTED
  15069. * @param {string} colTypes which columns to export, valid values are
  15070. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15071. * uiGridExporterConstants.SELECTED
  15072. */
  15073. loadAllDataIfNeeded: function(grid, rowTypes, colTypes) {
  15074. if (rowTypes === uiGridExporterConstants.ALL && grid.rows.length !== grid.options.totalItems && grid.options.exporterAllDataFn) {
  15075. return grid.options.exporterAllDataFn()
  15076. .then(function() {
  15077. grid.modifyRows(grid.options.data);
  15078. });
  15079. } else {
  15080. var deferred = $q.defer();
  15081. deferred.resolve();
  15082. return deferred.promise;
  15083. }
  15084. },
  15085. /**
  15086. * @ngdoc property
  15087. * @propertyOf ui.grid.exporter.api:ColumnDef
  15088. * @name exporterSuppressExport
  15089. * @description Suppresses export for this column. Used by selection and expandable.
  15090. */
  15091. /**
  15092. * @ngdoc function
  15093. * @name getColumnHeaders
  15094. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15095. * @description Gets the column headers from the grid to use
  15096. * as a title row for the exported file, all headers have
  15097. * headerCellFilters applied as appropriate.
  15098. *
  15099. * Column headers are an array of objects, each object has
  15100. * name, displayName, width and align attributes. Only name is
  15101. * used for csv, all attributes are used for pdf.
  15102. *
  15103. * @param {Grid} grid the grid from which data should be exported
  15104. * @param {string} colTypes which columns to export, valid values are
  15105. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15106. * uiGridExporterConstants.SELECTED
  15107. */
  15108. getColumnHeaders: function(grid, colTypes) {
  15109. var headers = [];
  15110. var columns;
  15111. if (colTypes === uiGridExporterConstants.ALL) {
  15112. columns = grid.columns;
  15113. } else {
  15114. var leftColumns = grid.renderContainers.left ? grid.renderContainers.left.visibleColumnCache.filter(function(column) { return column.visible; }) : [];
  15115. var bodyColumns = grid.renderContainers.body ? grid.renderContainers.body.visibleColumnCache.filter(function(column) { return column.visible; }) : [];
  15116. var rightColumns = grid.renderContainers.right ? grid.renderContainers.right.visibleColumnCache.filter(function(column) { return column.visible; }) : [];
  15117. columns = leftColumns.concat(bodyColumns, rightColumns);
  15118. }
  15119. columns.forEach(function(gridCol, index) {
  15120. if (gridCol.colDef.exporterSuppressExport !== true &&
  15121. grid.options.exporterSuppressColumns.indexOf(gridCol.name) === -1) {
  15122. headers.push({
  15123. name: gridCol.field,
  15124. displayName: grid.options.exporterHeaderFilter ? (grid.options.exporterHeaderFilterUseName ? grid.options.exporterHeaderFilter(gridCol.name) : grid.options.exporterHeaderFilter(gridCol.displayName)) : gridCol.displayName,
  15125. width: gridCol.drawnWidth ? gridCol.drawnWidth : gridCol.width,
  15126. align: gridCol.colDef.type === 'number' ? 'right' : 'left'
  15127. });
  15128. }
  15129. });
  15130. return headers;
  15131. },
  15132. /**
  15133. * @ngdoc property
  15134. * @propertyOf ui.grid.exporter.api:ColumnDef
  15135. * @name exporterPdfAlign
  15136. * @description the alignment you'd like for this specific column when
  15137. * exported into a pdf. Can be 'left', 'right', 'center' or any other
  15138. * valid pdfMake alignment option.
  15139. */
  15140. /**
  15141. * @ngdoc object
  15142. * @name ui.grid.exporter.api:GridRow
  15143. * @description GridRow settings for exporter
  15144. */
  15145. /**
  15146. * @ngdoc object
  15147. * @name exporterEnableExporting
  15148. * @propertyOf ui.grid.exporter.api:GridRow
  15149. * @description If set to false, then don't export this row, notwithstanding visible or
  15150. * other settings
  15151. * <br/>Defaults to true
  15152. */
  15153. /**
  15154. * @ngdoc function
  15155. * @name getData
  15156. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15157. * @description Gets data from the grid based on the provided options,
  15158. * all cells have cellFilters applied as appropriate. Any rows marked
  15159. * `exporterEnableExporting: false` will not be exported
  15160. * @param {Grid} grid the grid from which data should be exported
  15161. * @param {string} rowTypes which rows to export, valid values are
  15162. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15163. * uiGridExporterConstants.SELECTED
  15164. * @param {string} colTypes which columns to export, valid values are
  15165. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15166. * uiGridExporterConstants.SELECTED
  15167. */
  15168. getData: function(grid, rowTypes, colTypes) {
  15169. var data = [];
  15170. var rows;
  15171. var columns;
  15172. switch (rowTypes) {
  15173. case uiGridExporterConstants.ALL:
  15174. rows = grid.rows;
  15175. break;
  15176. case uiGridExporterConstants.VISIBLE:
  15177. rows = grid.getVisibleRows();
  15178. break;
  15179. case uiGridExporterConstants.SELECTED:
  15180. if (grid.api.selection) {
  15181. rows = grid.api.selection.getSelectedGridRows();
  15182. } else {
  15183. gridUtil.logError('selection feature must be enabled to allow selected rows to be exported');
  15184. }
  15185. break;
  15186. }
  15187. if (colTypes === uiGridExporterConstants.ALL) {
  15188. columns = grid.columns;
  15189. } else {
  15190. var leftColumns = grid.renderContainers.left ? grid.renderContainers.left.visibleColumnCache.filter(function(column) { return column.visible; }) : [];
  15191. var bodyColumns = grid.renderContainers.body ? grid.renderContainers.body.visibleColumnCache.filter(function(column) { return column.visible; }) : [];
  15192. var rightColumns = grid.renderContainers.right ? grid.renderContainers.right.visibleColumnCache.filter(function(column) { return column.visible; }) : [];
  15193. columns = leftColumns.concat(bodyColumns, rightColumns);
  15194. }
  15195. rows.forEach(function(row, index) {
  15196. if (row.exporterEnableExporting !== false) {
  15197. var extractedRow = [];
  15198. columns.forEach(function(gridCol, index) {
  15199. if ((gridCol.visible || colTypes === uiGridExporterConstants.ALL) &&
  15200. gridCol.colDef.exporterSuppressExport !== true &&
  15201. grid.options.exporterSuppressColumns.indexOf(gridCol.name) === -1) {
  15202. var extractedField = { value: grid.options.exporterFieldCallback(grid, row, gridCol, grid.getCellValue(row, gridCol)) };
  15203. if (gridCol.colDef.exporterPdfAlign) {
  15204. extractedField.alignment = gridCol.colDef.exporterPdfAlign;
  15205. }
  15206. extractedRow.push(extractedField);
  15207. }
  15208. });
  15209. data.push(extractedRow);
  15210. }
  15211. });
  15212. return data;
  15213. },
  15214. /**
  15215. * @ngdoc function
  15216. * @name formatAsCSV
  15217. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15218. * @description Formats the column headers and data as a CSV,
  15219. * and sends that data to the user
  15220. * @param {array} exportColumnHeaders an array of column headers,
  15221. * where each header is an object with name, width and maybe alignment
  15222. * @param {array} exportData an array of rows, where each row is
  15223. * an array of column data
  15224. * @returns {string} csv the formatted csv as a string
  15225. */
  15226. formatAsCsv: function(exportColumnHeaders, exportData, separator) {
  15227. var self = this;
  15228. var bareHeaders = exportColumnHeaders.map(function(header) { return { value: header.displayName }; });
  15229. var csv = self.formatRowAsCsv(this, separator)(bareHeaders) + '\n';
  15230. csv += exportData.map(this.formatRowAsCsv(this, separator)).join('\n');
  15231. return csv;
  15232. },
  15233. /**
  15234. * @ngdoc function
  15235. * @name formatRowAsCsv
  15236. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15237. * @description Renders a single field as a csv field, including
  15238. * quotes around the value
  15239. * @param {exporterService} exporter pass in exporter
  15240. * @param {array} row the row to be turned into a csv string
  15241. * @returns {string} a csv-ified version of the row
  15242. */
  15243. formatRowAsCsv: function(exporter, separator) {
  15244. return function(row) {
  15245. return row.map(exporter.formatFieldAsCsv).join(separator);
  15246. };
  15247. },
  15248. /**
  15249. * @ngdoc function
  15250. * @name formatFieldAsCsv
  15251. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15252. * @description Renders a single field as a csv field, including
  15253. * quotes around the value
  15254. * @param {field} field the field to be turned into a csv string,
  15255. * may be of any type
  15256. * @returns {string} a csv-ified version of the field
  15257. */
  15258. formatFieldAsCsv: function(field) {
  15259. if (field.value == null) { // we want to catch anything null-ish, hence just == not ===
  15260. return '';
  15261. }
  15262. if (typeof(field.value) === 'number') {
  15263. return field.value;
  15264. }
  15265. if (typeof(field.value) === 'boolean') {
  15266. return (field.value ? 'TRUE' : 'FALSE');
  15267. }
  15268. if (typeof(field.value) === 'string') {
  15269. return '"' + field.value.replace(/"/g, '""') + '"';
  15270. }
  15271. return JSON.stringify(field.value);
  15272. },
  15273. /**
  15274. * @ngdoc function
  15275. * @name isIE
  15276. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15277. * @description Checks whether current browser is IE and returns it's version if it is
  15278. */
  15279. isIE: function() {
  15280. var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/);
  15281. return match ? parseInt(match[1]) : false;
  15282. },
  15283. /**
  15284. * @ngdoc function
  15285. * @name downloadFile
  15286. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15287. * @description Triggers download of a csv file. Logic provided
  15288. * by @cssensei (from his colleagues at https://github.com/ifeelgoods) in issue #2391
  15289. * @param {string} fileName the filename we'd like our file to be
  15290. * given
  15291. * @param {string} csvContent the csv content that we'd like to
  15292. * download as a file
  15293. * @param {boolean} exporterOlderExcelCompatibility whether or not we put a utf-16 BOM on the from (\uFEFF)
  15294. */
  15295. downloadFile: function(fileName, csvContent, exporterOlderExcelCompatibility) {
  15296. var D = document;
  15297. var a = D.createElement('a');
  15298. var strMimeType = 'application/octet-stream;charset=utf-8';
  15299. var rawFile;
  15300. var ieVersion;
  15301. ieVersion = this.isIE();
  15302. if (ieVersion && ieVersion < 10) {
  15303. var frame = D.createElement('iframe');
  15304. document.body.appendChild(frame);
  15305. frame.contentWindow.document.open("text/html", "replace");
  15306. frame.contentWindow.document.write('sep=,\r\n' + csvContent);
  15307. frame.contentWindow.document.close();
  15308. frame.contentWindow.focus();
  15309. frame.contentWindow.document.execCommand('SaveAs', true, fileName);
  15310. document.body.removeChild(frame);
  15311. return true;
  15312. }
  15313. // IE10+
  15314. if (navigator.msSaveBlob) {
  15315. return navigator.msSaveOrOpenBlob(
  15316. new Blob(
  15317. [exporterOlderExcelCompatibility ? "\uFEFF" : '', csvContent], { type: strMimeType }),
  15318. fileName
  15319. );
  15320. }
  15321. //html5 A[download]
  15322. if ('download' in a) {
  15323. var blob = new Blob(
  15324. [exporterOlderExcelCompatibility ? "\uFEFF" : '', csvContent], { type: strMimeType }
  15325. );
  15326. rawFile = URL.createObjectURL(blob);
  15327. a.setAttribute('download', fileName);
  15328. } else {
  15329. rawFile = 'data:' + strMimeType + ',' + encodeURIComponent(csvContent);
  15330. a.setAttribute('target', '_blank');
  15331. }
  15332. a.href = rawFile;
  15333. a.setAttribute('style', 'display:none;');
  15334. D.body.appendChild(a);
  15335. setTimeout(function() {
  15336. if (a.click) {
  15337. a.click();
  15338. // Workaround for Safari 5
  15339. } else if (document.createEvent) {
  15340. var eventObj = document.createEvent('MouseEvents');
  15341. eventObj.initEvent('click', true, true);
  15342. a.dispatchEvent(eventObj);
  15343. }
  15344. D.body.removeChild(a);
  15345. }, this.delay);
  15346. },
  15347. /**
  15348. * @ngdoc function
  15349. * @name pdfExport
  15350. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15351. * @description Exports rows from the grid in pdf format,
  15352. * the data exported is selected based on the provided options.
  15353. * Note that this function has a dependency on pdfMake, which must
  15354. * be installed. The resulting pdf opens in a new
  15355. * browser window.
  15356. * @param {Grid} grid the grid from which data should be exported
  15357. * @param {string} rowTypes which rows to export, valid values are
  15358. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15359. * uiGridExporterConstants.SELECTED
  15360. * @param {string} colTypes which columns to export, valid values are
  15361. * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
  15362. * uiGridExporterConstants.SELECTED
  15363. */
  15364. pdfExport: function(grid, rowTypes, colTypes) {
  15365. var self = this;
  15366. this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function() {
  15367. var exportColumnHeaders = self.getColumnHeaders(grid, colTypes);
  15368. var exportData = self.getData(grid, rowTypes, colTypes);
  15369. var docDefinition = self.prepareAsPdf(grid, exportColumnHeaders, exportData);
  15370. if (self.isIE()) {
  15371. self.downloadPDF(grid.options.exporterPdfFilename, docDefinition);
  15372. } else {
  15373. pdfMake.createPdf(docDefinition).open();
  15374. }
  15375. });
  15376. },
  15377. /**
  15378. * @ngdoc function
  15379. * @name downloadPdf
  15380. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15381. * @description Generates and retrieves the pdf as a blob, then downloads
  15382. * it as a file. Only used in IE, in all other browsers we use the native
  15383. * pdfMake.open function to just open the PDF
  15384. * @param {string} fileName the filename to give to the pdf, can be set
  15385. * through exporterPdfFilename
  15386. * @param {object} docDefinition a pdf docDefinition that we can generate
  15387. * and get a blob from
  15388. */
  15389. downloadPDF: function(fileName, docDefinition) {
  15390. var D = document;
  15391. var a = D.createElement('a');
  15392. var strMimeType = 'application/octet-stream;charset=utf-8';
  15393. var rawFile;
  15394. var ieVersion;
  15395. ieVersion = this.isIE();
  15396. var doc = pdfMake.createPdf(docDefinition);
  15397. var blob;
  15398. doc.getBuffer(function(buffer) {
  15399. blob = new Blob([buffer]);
  15400. if (ieVersion && ieVersion < 10) {
  15401. var frame = D.createElement('iframe');
  15402. document.body.appendChild(frame);
  15403. frame.contentWindow.document.open("text/html", "replace");
  15404. frame.contentWindow.document.write(blob);
  15405. frame.contentWindow.document.close();
  15406. frame.contentWindow.focus();
  15407. frame.contentWindow.document.execCommand('SaveAs', true, fileName);
  15408. document.body.removeChild(frame);
  15409. return true;
  15410. }
  15411. // IE10+
  15412. if (navigator.msSaveBlob) {
  15413. return navigator.msSaveBlob(
  15414. blob, fileName
  15415. );
  15416. }
  15417. });
  15418. },
  15419. /**
  15420. * @ngdoc function
  15421. * @name renderAsPdf
  15422. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15423. * @description Renders the data into a pdf, and opens that pdf.
  15424. *
  15425. * @param {Grid} grid the grid from which data should be exported
  15426. * @param {array} exportColumnHeaders an array of column headers,
  15427. * where each header is an object with name, width and maybe alignment
  15428. * @param {array} exportData an array of rows, where each row is
  15429. * an array of column data
  15430. * @returns {object} a pdfMake format document definition, ready
  15431. * for generation
  15432. */
  15433. prepareAsPdf: function(grid, exportColumnHeaders, exportData) {
  15434. var headerWidths = this.calculatePdfHeaderWidths(grid, exportColumnHeaders);
  15435. var headerColumns = exportColumnHeaders.map(function(header) {
  15436. return { text: header.displayName, style: 'tableHeader' };
  15437. });
  15438. var stringData = exportData.map(this.formatRowAsPdf(this));
  15439. var allData = [headerColumns].concat(stringData);
  15440. var docDefinition = {
  15441. pageOrientation: grid.options.exporterPdfOrientation,
  15442. pageSize: grid.options.exporterPdfPageSize,
  15443. content: [{
  15444. style: 'tableStyle',
  15445. table: {
  15446. headerRows: 1,
  15447. widths: headerWidths,
  15448. body: allData
  15449. }
  15450. }],
  15451. styles: {
  15452. tableStyle: grid.options.exporterPdfTableStyle,
  15453. tableHeader: grid.options.exporterPdfTableHeaderStyle
  15454. },
  15455. defaultStyle: grid.options.exporterPdfDefaultStyle
  15456. };
  15457. if (grid.options.exporterPdfLayout) {
  15458. docDefinition.layout = grid.options.exporterPdfLayout;
  15459. }
  15460. if (grid.options.exporterPdfHeader) {
  15461. docDefinition.header = grid.options.exporterPdfHeader;
  15462. }
  15463. if (grid.options.exporterPdfFooter) {
  15464. docDefinition.footer = grid.options.exporterPdfFooter;
  15465. }
  15466. if (grid.options.exporterPdfCustomFormatter) {
  15467. docDefinition = grid.options.exporterPdfCustomFormatter(docDefinition);
  15468. }
  15469. return docDefinition;
  15470. },
  15471. /**
  15472. * @ngdoc function
  15473. * @name calculatePdfHeaderWidths
  15474. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15475. * @description Determines the column widths base on the
  15476. * widths we got from the grid. If the column is drawn
  15477. * then we have a drawnWidth. If the column is not visible
  15478. * then we have '*', 'x%' or a width. When columns are
  15479. * not visible they don't contribute to the overall gridWidth,
  15480. * so we need to adjust to allow for extra columns
  15481. *
  15482. * Our basic heuristic is to take the current gridWidth, plus
  15483. * numeric columns and call this the base gridwidth.
  15484. *
  15485. * To that we add 100 for any '*' column, and x% of the base gridWidth
  15486. * for any column that is a %
  15487. *
  15488. * @param {Grid} grid the grid from which data should be exported
  15489. * @param {array} exportHeaders array of header information
  15490. * @returns {object} an array of header widths
  15491. */
  15492. calculatePdfHeaderWidths: function(grid, exportHeaders) {
  15493. var baseGridWidth = 0;
  15494. exportHeaders.forEach(function(value) {
  15495. if (typeof(value.width) === 'number') {
  15496. baseGridWidth += value.width;
  15497. }
  15498. });
  15499. var extraColumns = 0;
  15500. exportHeaders.forEach(function(value) {
  15501. if (value.width === '*') {
  15502. extraColumns += 100;
  15503. }
  15504. if (typeof(value.width) === 'string' && value.width.match(/(\d)*%/)) {
  15505. var percent = parseInt(value.width.match(/(\d)*%/)[0]);
  15506. value.width = baseGridWidth * percent / 100;
  15507. extraColumns += value.width;
  15508. }
  15509. });
  15510. var gridWidth = baseGridWidth + extraColumns;
  15511. return exportHeaders.map(function(header) {
  15512. return header.width === '*' ? header.width : header.width * grid.options.exporterPdfMaxGridWidth / gridWidth;
  15513. });
  15514. },
  15515. /**
  15516. * @ngdoc function
  15517. * @name formatRowAsPdf
  15518. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15519. * @description Renders a row in a format consumable by PDF,
  15520. * mainly meaning casting everything to a string
  15521. * @param {exporterService} exporter pass in exporter
  15522. * @param {array} row the row to be turned into a csv string
  15523. * @returns {string} a csv-ified version of the row
  15524. */
  15525. formatRowAsPdf: function(exporter) {
  15526. return function(row) {
  15527. return row.map(exporter.formatFieldAsPdfString);
  15528. };
  15529. },
  15530. /**
  15531. * @ngdoc function
  15532. * @name formatFieldAsCsv
  15533. * @methodOf ui.grid.exporter.service:uiGridExporterService
  15534. * @description Renders a single field as a pdf-able field, which
  15535. * is different from a csv field only in that strings don't have quotes
  15536. * around them
  15537. * @param {field} field the field to be turned into a pdf string,
  15538. * may be of any type
  15539. * @returns {string} a string-ified version of the field
  15540. */
  15541. formatFieldAsPdfString: function(field) {
  15542. var returnVal;
  15543. if (field.value == null) { // we want to catch anything null-ish, hence just == not ===
  15544. returnVal = '';
  15545. } else if (typeof(field.value) === 'number') {
  15546. returnVal = field.value.toString();
  15547. } else if (typeof(field.value) === 'boolean') {
  15548. returnVal = (field.value ? 'TRUE' : 'FALSE');
  15549. } else if (typeof(field.value) === 'string') {
  15550. returnVal = field.value.replace(/"/g, '""');
  15551. } else {
  15552. returnVal = JSON.stringify(field.value).replace(/^"/, '').replace(/"$/, '');
  15553. }
  15554. if (field.alignment && typeof(field.alignment) === 'string') {
  15555. returnVal = { text: returnVal, alignment: field.alignment };
  15556. }
  15557. return returnVal;
  15558. }
  15559. };
  15560. return service;
  15561. }
  15562. ]);
  15563. /**
  15564. * @ngdoc directive
  15565. * @name ui.grid.exporter.directive:uiGridExporter
  15566. * @element div
  15567. * @restrict A
  15568. *
  15569. * @description Adds exporter features to grid
  15570. *
  15571. * @example
  15572. <example module="app">
  15573. <file name="app.js">
  15574. var app = angular.module('app', ['ui.grid', 'ui.grid.exporter']);
  15575. app.controller('MainCtrl', ['$scope', function ($scope) {
  15576. $scope.data = [
  15577. { name: 'Bob', title: 'CEO' },
  15578. { name: 'Frank', title: 'Lowly Developer' }
  15579. ];
  15580. $scope.gridOptions = {
  15581. enableGridMenu: true,
  15582. exporterMenuCsv: false,
  15583. columnDefs: [
  15584. {name: 'name', enableCellEdit: true},
  15585. {name: 'title', enableCellEdit: true}
  15586. ],
  15587. data: $scope.data
  15588. };
  15589. }]);
  15590. </file>
  15591. <file name="index.html">
  15592. <div ng-controller="MainCtrl">
  15593. <div ui-grid="gridOptions" ui-grid-exporter></div>
  15594. </div>
  15595. </file>
  15596. </example>
  15597. */
  15598. module.directive('uiGridExporter', ['uiGridExporterConstants', 'uiGridExporterService', 'gridUtil', '$compile',
  15599. function(uiGridExporterConstants, uiGridExporterService, gridUtil, $compile) {
  15600. return {
  15601. replace: true,
  15602. priority: 0,
  15603. require: '^uiGrid',
  15604. scope: false,
  15605. link: function($scope, $elm, $attrs, uiGridCtrl) {
  15606. uiGridExporterService.initializeGrid(uiGridCtrl.grid);
  15607. uiGridCtrl.grid.exporter.$scope = $scope;
  15608. }
  15609. };
  15610. }
  15611. ]);
  15612. })();
  15613. (function() {
  15614. 'use strict';
  15615. /**
  15616. * @ngdoc overview
  15617. * @name ui.grid.grouping
  15618. * @description
  15619. *
  15620. * # ui.grid.grouping
  15621. *
  15622. * <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>
  15623. *
  15624. * This module provides grouping of rows based on the data in them, similar
  15625. * in concept to excel grouping. You can group multiple columns, resulting in
  15626. * nested grouping.
  15627. *
  15628. * In concept this feature is similar to sorting + grid footer/aggregation, it
  15629. * sorts the data based on the grouped columns, then creates group rows that
  15630. * reflect a break in the data. Each of those group rows can have aggregations for
  15631. * the data within that group.
  15632. *
  15633. * This feature leverages treeBase to provide the tree functionality itself,
  15634. * the key thing this feature does therefore is to set treeLevels on the rows
  15635. * and insert the group headers.
  15636. *
  15637. * Design information:
  15638. * -------------------
  15639. *
  15640. * Each column will get new menu items - group by, and aggregate by. Group by
  15641. * will cause this column to be sorted (if not already), and will move this column
  15642. * to the front of the sorted columns (i.e. grouped columns take precedence over
  15643. * sorted columns). It will respect the sort order already set if there is one,
  15644. * and it will allow the sorting logic to change that sort order, it just forces
  15645. * the column to the front of the sorting. You can group by multiple columns, the
  15646. * logic will add this column to the sorting after any already grouped columns.
  15647. *
  15648. * Once a grouping is defined, grouping logic is added to the rowsProcessors. This
  15649. * will process the rows, identifying a break in the data value, and inserting a grouping row.
  15650. * Grouping rows have specific attributes on them:
  15651. *
  15652. * - internalRow = true: tells us that this isn't a real row, so we can ignore it
  15653. * from any processing that it looking at core data rows. This is used by the core
  15654. * logic (or will be one day), as it's not grouping specific
  15655. * - groupHeader = true: tells us this is a groupHeader. This is used by the grouping logic
  15656. * to know if this is a groupHeader row or not
  15657. *
  15658. * Since the logic is baked into the rowsProcessors, it should get triggered whenever
  15659. * row order or filtering or anything like that is changed. In order to avoid the row instantiation
  15660. * time, and to preserve state across invocations, we hold a cache of the rows that we created
  15661. * last time, and we use them again this time if we can.
  15662. *
  15663. * By default rows are collapsed, which means all data rows have their visible property
  15664. * set to false, and only level 0 group rows are set to visible.
  15665. *
  15666. * <br/>
  15667. * <br/>
  15668. *
  15669. * <div doc-module-components="ui.grid.grouping"></div>
  15670. */
  15671. var module = angular.module('ui.grid.grouping', ['ui.grid', 'ui.grid.treeBase']);
  15672. /**
  15673. * @ngdoc object
  15674. * @name ui.grid.grouping.constant:uiGridGroupingConstants
  15675. *
  15676. * @description constants available in grouping module, this includes
  15677. * all the constants declared in the treeBase module (these are manually copied
  15678. * as there isn't an easy way to include constants in another constants file, and
  15679. * we don't want to make users include treeBase)
  15680. *
  15681. */
  15682. module.constant('uiGridGroupingConstants', {
  15683. featureName: "grouping",
  15684. rowHeaderColName: 'treeBaseRowHeaderCol',
  15685. EXPANDED: 'expanded',
  15686. COLLAPSED: 'collapsed',
  15687. aggregation: {
  15688. COUNT: 'count',
  15689. SUM: 'sum',
  15690. MAX: 'max',
  15691. MIN: 'min',
  15692. AVG: 'avg'
  15693. }
  15694. });
  15695. /**
  15696. * @ngdoc service
  15697. * @name ui.grid.grouping.service:uiGridGroupingService
  15698. *
  15699. * @description Services for grouping features
  15700. */
  15701. module.service('uiGridGroupingService', ['$q', 'uiGridGroupingConstants', 'gridUtil', 'rowSorter', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'uiGridTreeBaseService',
  15702. function($q, uiGridGroupingConstants, gridUtil, rowSorter, GridRow, gridClassFactory, i18nService, uiGridConstants, uiGridTreeBaseService) {
  15703. var service = {
  15704. initializeGrid: function(grid, $scope) {
  15705. uiGridTreeBaseService.initializeGrid(grid, $scope);
  15706. //add feature namespace and any properties to grid for needed
  15707. /**
  15708. * @ngdoc object
  15709. * @name ui.grid.grouping.grid:grouping
  15710. *
  15711. * @description Grid properties and functions added for grouping
  15712. */
  15713. grid.grouping = {};
  15714. /**
  15715. * @ngdoc property
  15716. * @propertyOf ui.grid.grouping.grid:grouping
  15717. * @name groupHeaderCache
  15718. *
  15719. * @description Cache that holds the group header rows we created last time, we'll
  15720. * reuse these next time, not least because they hold our expanded states.
  15721. *
  15722. * We need to take care with these that they don't become a memory leak, we
  15723. * create a new cache each time using the values from the old cache. This works
  15724. * so long as we're creating group rows for invisible rows as well.
  15725. *
  15726. * The cache is a nested hash, indexed on the value we grouped by. So if we
  15727. * grouped by gender then age, we'd maybe have something like:
  15728. * ```
  15729. * {
  15730. * male: {
  15731. * row: <pointer to the old row>,
  15732. * children: {
  15733. * 22: { row: <pointer to the old row> },
  15734. * 31: { row: <pointer to the old row> }
  15735. * },
  15736. * female: {
  15737. * row: <pointer to the old row>,
  15738. * children: {
  15739. * 28: { row: <pointer to the old row> },
  15740. * 55: { row: <pointer to the old row> }
  15741. * }
  15742. * }
  15743. * ```
  15744. *
  15745. * We create new rows for any missing rows, this means that they come in as collapsed.
  15746. *
  15747. */
  15748. grid.grouping.groupHeaderCache = {};
  15749. service.defaultGridOptions(grid.options);
  15750. grid.registerRowsProcessor(service.groupRows, 400);
  15751. grid.registerColumnBuilder(service.groupingColumnBuilder);
  15752. grid.registerColumnsProcessor(service.groupingColumnProcessor, 400);
  15753. /**
  15754. * @ngdoc object
  15755. * @name ui.grid.grouping.api:PublicApi
  15756. *
  15757. * @description Public Api for grouping feature
  15758. */
  15759. var publicApi = {
  15760. events: {
  15761. grouping: {
  15762. /**
  15763. * @ngdoc event
  15764. * @eventOf ui.grid.grouping.api:PublicApi
  15765. * @name aggregationChanged
  15766. * @description raised whenever aggregation is changed, added or removed from a column
  15767. *
  15768. * <pre>
  15769. * gridApi.grouping.on.aggregationChanged(scope,function(col){})
  15770. * </pre>
  15771. * @param {gridCol} col the column which on which aggregation changed. The aggregation
  15772. * type is available as `col.treeAggregation.type`
  15773. */
  15774. aggregationChanged: {},
  15775. /**
  15776. * @ngdoc event
  15777. * @eventOf ui.grid.grouping.api:PublicApi
  15778. * @name groupingChanged
  15779. * @description raised whenever the grouped columns changes
  15780. *
  15781. * <pre>
  15782. * gridApi.grouping.on.groupingChanged(scope,function(col){})
  15783. * </pre>
  15784. * @param {gridCol} col the column which on which grouping changed. The new grouping is
  15785. * available as `col.grouping`
  15786. */
  15787. groupingChanged: {}
  15788. }
  15789. },
  15790. methods: {
  15791. grouping: {
  15792. /**
  15793. * @ngdoc function
  15794. * @name getGrouping
  15795. * @methodOf ui.grid.grouping.api:PublicApi
  15796. * @description Get the grouping configuration for this grid,
  15797. * used by the saveState feature. Adds expandedState to the information
  15798. * provided by the internal getGrouping, and removes any aggregations that have a source
  15799. * of grouping (i.e. will be automatically reapplied when we regroup the column)
  15800. * Returned grouping is an object
  15801. * `{ grouping: groupArray, treeAggregations: aggregateArray, expandedState: hash }`
  15802. * where grouping contains an array of objects:
  15803. * `{ field: column.field, colName: column.name, groupPriority: column.grouping.groupPriority }`
  15804. * and aggregations contains an array of objects:
  15805. * `{ field: column.field, colName: column.name, aggregation: column.grouping.aggregation }`
  15806. * and expandedState is a hash of the currently expanded nodes
  15807. *
  15808. * The groupArray will be sorted by groupPriority.
  15809. *
  15810. * @param {boolean} getExpanded whether or not to return the expanded state
  15811. * @returns {object} grouping configuration
  15812. */
  15813. getGrouping: function(getExpanded) {
  15814. var grouping = service.getGrouping(grid);
  15815. grouping.grouping.forEach(function(group) {
  15816. group.colName = group.col.name;
  15817. delete group.col;
  15818. });
  15819. grouping.aggregations.forEach(function(aggregation) {
  15820. aggregation.colName = aggregation.col.name;
  15821. delete aggregation.col;
  15822. });
  15823. grouping.aggregations = grouping.aggregations.filter(function(aggregation) {
  15824. return !aggregation.aggregation.source || aggregation.aggregation.source !== 'grouping';
  15825. });
  15826. if (getExpanded) {
  15827. grouping.rowExpandedStates = service.getRowExpandedStates(grid.grouping.groupingHeaderCache);
  15828. }
  15829. return grouping;
  15830. },
  15831. /**
  15832. * @ngdoc function
  15833. * @name setGrouping
  15834. * @methodOf ui.grid.grouping.api:PublicApi
  15835. * @description Set the grouping configuration for this grid,
  15836. * used by the saveState feature, but can also be used by any
  15837. * user to specify a combined grouping and aggregation configuration
  15838. * @param {object} config the config you want to apply, in the format
  15839. * provided out by getGrouping
  15840. */
  15841. setGrouping: function(config) {
  15842. service.setGrouping(grid, config);
  15843. },
  15844. /**
  15845. * @ngdoc function
  15846. * @name groupColumn
  15847. * @methodOf ui.grid.grouping.api:PublicApi
  15848. * @description Adds this column to the existing grouping, at the end of the priority order.
  15849. * If the column doesn't have a sort, adds one, by default ASC
  15850. *
  15851. * This column will move to the left of any non-group columns, the
  15852. * move is handled in a columnProcessor, so gets called as part of refresh
  15853. *
  15854. * @param {string} columnName the name of the column we want to group
  15855. */
  15856. groupColumn: function(columnName) {
  15857. var column = grid.getColumn(columnName);
  15858. service.groupColumn(grid, column);
  15859. },
  15860. /**
  15861. * @ngdoc function
  15862. * @name ungroupColumn
  15863. * @methodOf ui.grid.grouping.api:PublicApi
  15864. * @description Removes the groupPriority from this column. If the
  15865. * column was previously aggregated the aggregation will come back.
  15866. * The sort will remain.
  15867. *
  15868. * This column will move to the right of any other group columns, the
  15869. * move is handled in a columnProcessor, so gets called as part of refresh
  15870. *
  15871. * @param {string} columnName the name of the column we want to ungroup
  15872. */
  15873. ungroupColumn: function(columnName) {
  15874. var column = grid.getColumn(columnName);
  15875. service.ungroupColumn(grid, column);
  15876. },
  15877. /**
  15878. * @ngdoc function
  15879. * @name clearGrouping
  15880. * @methodOf ui.grid.grouping.api:PublicApi
  15881. * @description Clear any grouped columns and any aggregations. Doesn't remove sorting,
  15882. * as we don't know whether that sorting was added by grouping or was there beforehand
  15883. *
  15884. */
  15885. clearGrouping: function() {
  15886. service.clearGrouping(grid);
  15887. },
  15888. /**
  15889. * @ngdoc function
  15890. * @name aggregateColumn
  15891. * @methodOf ui.grid.grouping.api:PublicApi
  15892. * @description Sets the aggregation type on a column, if the
  15893. * column is currently grouped then it removes the grouping first.
  15894. * If the aggregationDef is null then will result in the aggregation
  15895. * being removed
  15896. *
  15897. * @param {string} columnName the column we want to aggregate
  15898. * @param {string} or {function} aggregationDef one of the recognised types
  15899. * from uiGridGroupingConstants or a custom aggregation function.
  15900. * @param {string} aggregationLabel (optional) The label to use for this aggregation.
  15901. */
  15902. aggregateColumn: function(columnName, aggregationDef, aggregationLabel) {
  15903. var column = grid.getColumn(columnName);
  15904. service.aggregateColumn(grid, column, aggregationDef, aggregationLabel);
  15905. }
  15906. }
  15907. }
  15908. };
  15909. grid.api.registerEventsFromObject(publicApi.events);
  15910. grid.api.registerMethodsFromObject(publicApi.methods);
  15911. grid.api.core.on.sortChanged($scope, service.tidyPriorities);
  15912. },
  15913. defaultGridOptions: function(gridOptions) {
  15914. //default option to true unless it was explicitly set to false
  15915. /**
  15916. * @ngdoc object
  15917. * @name ui.grid.grouping.api:GridOptions
  15918. *
  15919. * @description GridOptions for grouping feature, these are available to be
  15920. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  15921. */
  15922. /**
  15923. * @ngdoc object
  15924. * @name enableGrouping
  15925. * @propertyOf ui.grid.grouping.api:GridOptions
  15926. * @description Enable row grouping for entire grid.
  15927. * <br/>Defaults to true
  15928. */
  15929. gridOptions.enableGrouping = gridOptions.enableGrouping !== false;
  15930. /**
  15931. * @ngdoc object
  15932. * @name groupingShowCounts
  15933. * @propertyOf ui.grid.grouping.api:GridOptions
  15934. * @description shows counts on the groupHeader rows. Not that if you are using a cellFilter or a
  15935. * sortingAlgorithm which relies on a specific format or data type, showing counts may cause that
  15936. * to break, since the group header rows will always be a string with groupingShowCounts enabled.
  15937. * <br/>Defaults to true except on columns of type 'date'
  15938. */
  15939. gridOptions.groupingShowCounts = gridOptions.groupingShowCounts !== false;
  15940. /**
  15941. * @ngdoc object
  15942. * @name groupingNullLabel
  15943. * @propertyOf ui.grid.grouping.api:GridOptions
  15944. * @description The string to use for the grouping header row label on rows which contain a null or undefined value in the grouped column.
  15945. * <br/>Defaults to "Null"
  15946. */
  15947. gridOptions.groupingNullLabel = typeof(gridOptions.groupingNullLabel) === 'undefined' ? 'Null' : gridOptions.groupingNullLabel;
  15948. /**
  15949. * @ngdoc object
  15950. * @name enableGroupHeaderSelection
  15951. * @propertyOf ui.grid.grouping.api:GridOptions
  15952. * @description Allows group header rows to be selected.
  15953. * <br/>Defaults to false
  15954. */
  15955. gridOptions.enableGroupHeaderSelection = gridOptions.enableGroupHeaderSelection === true;
  15956. },
  15957. /**
  15958. * @ngdoc function
  15959. * @name groupingColumnBuilder
  15960. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  15961. * @description Sets the grouping defaults based on the columnDefs
  15962. *
  15963. * @param {object} colDef columnDef we're basing on
  15964. * @param {GridCol} col the column we're to update
  15965. * @param {object} gridOptions the options we should use
  15966. * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved
  15967. */
  15968. groupingColumnBuilder: function(colDef, col, gridOptions) {
  15969. /**
  15970. * @ngdoc object
  15971. * @name ui.grid.grouping.api:ColumnDef
  15972. *
  15973. * @description ColumnDef for grouping feature, these are available to be
  15974. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  15975. */
  15976. /**
  15977. * @ngdoc object
  15978. * @name enableGrouping
  15979. * @propertyOf ui.grid.grouping.api:ColumnDef
  15980. * @description Enable grouping on this column
  15981. * <br/>Defaults to true.
  15982. */
  15983. if (colDef.enableGrouping === false) {
  15984. return;
  15985. }
  15986. /**
  15987. * @ngdoc object
  15988. * @name grouping
  15989. * @propertyOf ui.grid.grouping.api:ColumnDef
  15990. * @description Set the grouping for a column. Format is:
  15991. * ```
  15992. * {
  15993. * groupPriority: <number, starts at 0, if less than 0 or undefined then we're aggregating in this column>
  15994. * }
  15995. * ```
  15996. *
  15997. * **Note that aggregation used to be included in grouping, but is now separately set on the column via treeAggregation
  15998. * setting in treeBase**
  15999. *
  16000. * We group in the priority order given, this will also put these columns to the high order of the sort irrespective
  16001. * of the sort priority given them. If there is no sort defined then we sort ascending, if there is a sort defined then
  16002. * we use that sort.
  16003. *
  16004. * If the groupPriority is undefined or less than 0, then we expect to be aggregating, and we look at the
  16005. * aggregation types to determine what sort of aggregation we can do. Values are in the constants file, but
  16006. * include SUM, COUNT, MAX, MIN
  16007. *
  16008. * groupPriorities should generally be sequential, if they're not then the next time getGrouping is called
  16009. * we'll renumber them to be sequential.
  16010. * <br/>Defaults to undefined.
  16011. */
  16012. if (typeof(col.grouping) === 'undefined' && typeof(colDef.grouping) !== 'undefined') {
  16013. col.grouping = angular.copy(colDef.grouping);
  16014. if (typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority > -1) {
  16015. col.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn;
  16016. col.treeAggregationFinalizerFn = service.groupedFinalizerFn;
  16017. }
  16018. } else if (typeof(col.grouping) === 'undefined') {
  16019. col.grouping = {};
  16020. }
  16021. if (typeof(col.grouping) !== 'undefined' && typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority >= 0) {
  16022. col.suppressRemoveSort = true;
  16023. }
  16024. var groupColumn = {
  16025. name: 'ui.grid.grouping.group',
  16026. title: i18nService.get().grouping.group,
  16027. icon: 'ui-grid-icon-indent-right',
  16028. shown: function() {
  16029. return typeof(this.context.col.grouping) === 'undefined' ||
  16030. typeof(this.context.col.grouping.groupPriority) === 'undefined' ||
  16031. this.context.col.grouping.groupPriority < 0;
  16032. },
  16033. action: function() {
  16034. service.groupColumn(this.context.col.grid, this.context.col);
  16035. }
  16036. };
  16037. var ungroupColumn = {
  16038. name: 'ui.grid.grouping.ungroup',
  16039. title: i18nService.get().grouping.ungroup,
  16040. icon: 'ui-grid-icon-indent-left',
  16041. shown: function() {
  16042. return typeof(this.context.col.grouping) !== 'undefined' &&
  16043. typeof(this.context.col.grouping.groupPriority) !== 'undefined' &&
  16044. this.context.col.grouping.groupPriority >= 0;
  16045. },
  16046. action: function() {
  16047. service.ungroupColumn(this.context.col.grid, this.context.col);
  16048. }
  16049. };
  16050. var aggregateRemove = {
  16051. name: 'ui.grid.grouping.aggregateRemove',
  16052. title: i18nService.get().grouping.aggregate_remove,
  16053. shown: function() {
  16054. return typeof(this.context.col.treeAggregationFn) !== 'undefined';
  16055. },
  16056. action: function() {
  16057. service.aggregateColumn(this.context.col.grid, this.context.col, null);
  16058. }
  16059. };
  16060. // generic adder for the aggregation menus, which follow a pattern
  16061. var addAggregationMenu = function(type, title) {
  16062. title = title || i18nService.get().grouping['aggregate_' + type] || type;
  16063. var menuItem = {
  16064. name: 'ui.grid.grouping.aggregate' + type,
  16065. title: title,
  16066. shown: function() {
  16067. return typeof(this.context.col.treeAggregation) === 'undefined' ||
  16068. typeof(this.context.col.treeAggregation.type) === 'undefined' ||
  16069. this.context.col.treeAggregation.type !== type;
  16070. },
  16071. action: function() {
  16072. service.aggregateColumn(this.context.col.grid, this.context.col, type);
  16073. }
  16074. };
  16075. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregate' + type)) {
  16076. col.menuItems.push(menuItem);
  16077. }
  16078. };
  16079. /**
  16080. * @ngdoc object
  16081. * @name groupingShowGroupingMenu
  16082. * @propertyOf ui.grid.grouping.api:ColumnDef
  16083. * @description Show the grouping (group and ungroup items) menu on this column
  16084. * <br/>Defaults to true.
  16085. */
  16086. if (col.colDef.groupingShowGroupingMenu !== false) {
  16087. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.group')) {
  16088. col.menuItems.push(groupColumn);
  16089. }
  16090. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.ungroup')) {
  16091. col.menuItems.push(ungroupColumn);
  16092. }
  16093. }
  16094. /**
  16095. * @ngdoc object
  16096. * @name groupingShowAggregationMenu
  16097. * @propertyOf ui.grid.grouping.api:ColumnDef
  16098. * @description Show the aggregation menu on this column
  16099. * <br/>Defaults to true.
  16100. */
  16101. if (col.colDef.groupingShowAggregationMenu !== false) {
  16102. angular.forEach(uiGridTreeBaseService.nativeAggregations(), function(aggregationDef, name) {
  16103. addAggregationMenu(name);
  16104. });
  16105. angular.forEach(gridOptions.treeCustomAggregations, function(aggregationDef, name) {
  16106. addAggregationMenu(name, aggregationDef.menuTitle);
  16107. });
  16108. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregateRemove')) {
  16109. col.menuItems.push(aggregateRemove);
  16110. }
  16111. }
  16112. },
  16113. /**
  16114. * @ngdoc function
  16115. * @name groupingColumnProcessor
  16116. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16117. * @description Moves the columns around based on which are grouped
  16118. *
  16119. * @param {array} columns the columns to consider rendering
  16120. * @param {array} rows the grid rows, which we don't use but are passed to us
  16121. * @returns {array} updated columns array
  16122. */
  16123. groupingColumnProcessor: function(columns, rows) {
  16124. var grid = this;
  16125. columns = service.moveGroupColumns(this, columns, rows);
  16126. return columns;
  16127. },
  16128. /**
  16129. * @ngdoc function
  16130. * @name groupedFinalizerFn
  16131. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16132. * @description Used on group columns to display the rendered value and optionally
  16133. * display the count of rows.
  16134. *
  16135. * @param {aggregation} the aggregation entity for a grouped column
  16136. */
  16137. groupedFinalizerFn: function(aggregation) {
  16138. var col = this;
  16139. if (typeof(aggregation.groupVal) !== 'undefined') {
  16140. aggregation.rendered = aggregation.groupVal;
  16141. if (col.grid.options.groupingShowCounts && col.colDef.type !== 'date') {
  16142. aggregation.rendered += (' (' + aggregation.value + ')');
  16143. }
  16144. } else {
  16145. aggregation.rendered = null;
  16146. }
  16147. },
  16148. /**
  16149. * @ngdoc function
  16150. * @name moveGroupColumns
  16151. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16152. * @description Moves the column order so that the grouped columns are lined up
  16153. * to the left (well, unless you're RTL, then it's the right). By doing this in
  16154. * the columnsProcessor, we make it transient - when the column is ungrouped it'll
  16155. * go back to where it was.
  16156. *
  16157. * Does nothing if the option `moveGroupColumns` is set to false.
  16158. *
  16159. * @param {Grid} grid grid object
  16160. * @param {array} columns the columns that we should process/move
  16161. * @param {array} rows the grid rows
  16162. * @returns {array} updated columns
  16163. */
  16164. moveGroupColumns: function(grid, columns, rows) {
  16165. if (grid.options.moveGroupColumns === false) {
  16166. return columns;
  16167. }
  16168. columns.forEach(function(column, index) {
  16169. // position used to make stable sort in moveGroupColumns
  16170. column.groupingPosition = index;
  16171. });
  16172. columns.sort(function(a, b) {
  16173. var a_group, b_group;
  16174. if (a.isRowHeader) {
  16175. a_group = -1000;
  16176. } else if (typeof(a.grouping) === 'undefined' || typeof(a.grouping.groupPriority) === 'undefined' || a.grouping.groupPriority < 0) {
  16177. a_group = null;
  16178. } else {
  16179. a_group = a.grouping.groupPriority;
  16180. }
  16181. if (b.isRowHeader) {
  16182. b_group = -1000;
  16183. } else if (typeof(b.grouping) === 'undefined' || typeof(b.grouping.groupPriority) === 'undefined' || b.grouping.groupPriority < 0) {
  16184. b_group = null;
  16185. } else {
  16186. b_group = b.grouping.groupPriority;
  16187. }
  16188. // groups get sorted to the top
  16189. if (a_group !== null && b_group === null) { return -1; }
  16190. if (b_group !== null && a_group === null) { return 1; }
  16191. if (a_group !== null && b_group !== null) { return a_group - b_group; }
  16192. return a.groupingPosition - b.groupingPosition;
  16193. });
  16194. columns.forEach(function(column, index) {
  16195. delete column.groupingPosition;
  16196. });
  16197. return columns;
  16198. },
  16199. /**
  16200. * @ngdoc function
  16201. * @name groupColumn
  16202. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16203. * @description Adds this column to the existing grouping, at the end of the priority order.
  16204. * If the column doesn't have a sort, adds one, by default ASC
  16205. *
  16206. * This column will move to the left of any non-group columns, the
  16207. * move is handled in a columnProcessor, so gets called as part of refresh
  16208. *
  16209. * @param {Grid} grid grid object
  16210. * @param {GridCol} column the column we want to group
  16211. */
  16212. groupColumn: function(grid, column) {
  16213. if (typeof(column.grouping) === 'undefined') {
  16214. column.grouping = {};
  16215. }
  16216. // set the group priority to the next number in the hierarchy
  16217. var existingGrouping = service.getGrouping(grid);
  16218. column.grouping.groupPriority = existingGrouping.grouping.length;
  16219. // add sort if not present
  16220. if (!column.sort) {
  16221. column.sort = { direction: uiGridConstants.ASC };
  16222. } else if (typeof(column.sort.direction) === 'undefined' || column.sort.direction === null) {
  16223. column.sort.direction = uiGridConstants.ASC;
  16224. }
  16225. column.treeAggregation = { type: uiGridGroupingConstants.aggregation.COUNT, source: 'grouping' };
  16226. column.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn;
  16227. column.treeAggregationFinalizerFn = service.groupedFinalizerFn;
  16228. grid.api.grouping.raise.groupingChanged(column);
  16229. // This indirectly calls service.tidyPriorities( grid );
  16230. grid.api.core.raise.sortChanged(grid, grid.getColumnSorting());
  16231. grid.queueGridRefresh();
  16232. },
  16233. /**
  16234. * @ngdoc function
  16235. * @name ungroupColumn
  16236. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16237. * @description Removes the groupPriority from this column. If the
  16238. * column was previously aggregated the aggregation will come back.
  16239. * The sort will remain.
  16240. *
  16241. * This column will move to the right of any other group columns, the
  16242. * move is handled in a columnProcessor, so gets called as part of refresh
  16243. *
  16244. * @param {Grid} grid grid object
  16245. * @param {GridCol} column the column we want to ungroup
  16246. */
  16247. ungroupColumn: function(grid, column) {
  16248. if (typeof(column.grouping) === 'undefined') {
  16249. return;
  16250. }
  16251. delete column.grouping.groupPriority;
  16252. delete column.treeAggregation;
  16253. delete column.customTreeAggregationFinalizer;
  16254. service.tidyPriorities(grid);
  16255. grid.api.grouping.raise.groupingChanged(column);
  16256. grid.queueGridRefresh();
  16257. },
  16258. /**
  16259. * @ngdoc function
  16260. * @name aggregateColumn
  16261. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16262. * @description Sets the aggregation type on a column, if the
  16263. * column is currently grouped then it removes the grouping first.
  16264. *
  16265. * @param {Grid} grid grid object
  16266. * @param {GridCol} column the column we want to aggregate
  16267. * @param {string} one of the recognised types from uiGridGroupingConstants or one of the custom aggregations from gridOptions
  16268. */
  16269. aggregateColumn: function(grid, column, aggregationType) {
  16270. if (typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0) {
  16271. service.ungroupColumn(grid, column);
  16272. }
  16273. var aggregationDef = {};
  16274. if (typeof(grid.options.treeCustomAggregations[aggregationType]) !== 'undefined') {
  16275. aggregationDef = grid.options.treeCustomAggregations[aggregationType];
  16276. } else if (typeof(uiGridTreeBaseService.nativeAggregations()[aggregationType]) !== 'undefined') {
  16277. aggregationDef = uiGridTreeBaseService.nativeAggregations()[aggregationType];
  16278. }
  16279. column.treeAggregation = { type: aggregationType, label: i18nService.get().aggregation[aggregationDef.label] || aggregationDef.label };
  16280. column.treeAggregationFn = aggregationDef.aggregationFn;
  16281. column.treeAggregationFinalizerFn = aggregationDef.finalizerFn;
  16282. grid.api.grouping.raise.aggregationChanged(column);
  16283. grid.queueGridRefresh();
  16284. },
  16285. /**
  16286. * @ngdoc function
  16287. * @name setGrouping
  16288. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16289. * @description Set the grouping based on a config object, used by the save state feature
  16290. * (more specifically, by the restore function in that feature )
  16291. *
  16292. * @param {Grid} grid grid object
  16293. * @param {object} config the config we want to set, same format as that returned by getGrouping
  16294. */
  16295. setGrouping: function(grid, config) {
  16296. if (typeof(config) === 'undefined') {
  16297. return;
  16298. }
  16299. // first remove any existing grouping
  16300. service.clearGrouping(grid);
  16301. if (config.grouping && config.grouping.length && config.grouping.length > 0) {
  16302. config.grouping.forEach(function(group) {
  16303. var col = grid.getColumn(group.colName);
  16304. if (col) {
  16305. service.groupColumn(grid, col);
  16306. }
  16307. });
  16308. }
  16309. if (config.aggregations && config.aggregations.length) {
  16310. config.aggregations.forEach(function(aggregation) {
  16311. var col = grid.getColumn(aggregation.colName);
  16312. if (col) {
  16313. service.aggregateColumn(grid, col, aggregation.aggregation.type);
  16314. }
  16315. });
  16316. }
  16317. if (config.rowExpandedStates) {
  16318. service.applyRowExpandedStates(grid.grouping.groupingHeaderCache, config.rowExpandedStates);
  16319. }
  16320. },
  16321. /**
  16322. * @ngdoc function
  16323. * @name clearGrouping
  16324. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16325. * @description Clear any grouped columns and any aggregations. Doesn't remove sorting,
  16326. * as we don't know whether that sorting was added by grouping or was there beforehand
  16327. *
  16328. * @param {Grid} grid grid object
  16329. */
  16330. clearGrouping: function(grid) {
  16331. var currentGrouping = service.getGrouping(grid);
  16332. if (currentGrouping.grouping.length > 0) {
  16333. currentGrouping.grouping.forEach(function(group) {
  16334. if (!group.col) {
  16335. // should have a group.colName if there's no col
  16336. group.col = grid.getColumn(group.colName);
  16337. }
  16338. service.ungroupColumn(grid, group.col);
  16339. });
  16340. }
  16341. if (currentGrouping.aggregations.length > 0) {
  16342. currentGrouping.aggregations.forEach(function(aggregation) {
  16343. if (!aggregation.col) {
  16344. // should have a group.colName if there's no col
  16345. aggregation.col = grid.getColumn(aggregation.colName);
  16346. }
  16347. service.aggregateColumn(grid, aggregation.col, null);
  16348. });
  16349. }
  16350. },
  16351. /**
  16352. * @ngdoc function
  16353. * @name tidyPriorities
  16354. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16355. * @description Renumbers groupPriority and sortPriority such that
  16356. * groupPriority is contiguous, and sortPriority either matches
  16357. * groupPriority (for group columns), and otherwise is contiguous and
  16358. * higher than groupPriority.
  16359. *
  16360. * @param {Grid} grid grid object
  16361. */
  16362. tidyPriorities: function(grid) {
  16363. // if we're called from sortChanged, grid is in this, not passed as param, the param can be a column or undefined
  16364. if ((typeof(grid) === 'undefined' || typeof(grid.grid) !== 'undefined') && typeof(this.grid) !== 'undefined') {
  16365. grid = this.grid;
  16366. }
  16367. var groupArray = [];
  16368. var sortArray = [];
  16369. grid.columns.forEach(function(column, index) {
  16370. if (typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0) {
  16371. groupArray.push(column);
  16372. } else if (typeof(column.sort) !== 'undefined' && typeof(column.sort.priority) !== 'undefined' && column.sort.priority >= 0) {
  16373. sortArray.push(column);
  16374. }
  16375. });
  16376. groupArray.sort(function(a, b) { return a.grouping.groupPriority - b.grouping.groupPriority; });
  16377. groupArray.forEach(function(column, index) {
  16378. column.grouping.groupPriority = index;
  16379. column.suppressRemoveSort = true;
  16380. if (typeof(column.sort) === 'undefined') {
  16381. column.sort = {};
  16382. }
  16383. column.sort.priority = index;
  16384. });
  16385. var i = groupArray.length;
  16386. sortArray.sort(function(a, b) { return a.sort.priority - b.sort.priority; });
  16387. sortArray.forEach(function(column, index) {
  16388. column.sort.priority = i;
  16389. column.suppressRemoveSort = column.colDef.suppressRemoveSort;
  16390. i++;
  16391. });
  16392. },
  16393. /**
  16394. * @ngdoc function
  16395. * @name groupRows
  16396. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16397. * @description The rowProcessor that creates the groupHeaders (i.e. does
  16398. * the actual grouping).
  16399. *
  16400. * Assumes it is always called after the sorting processor, guaranteed by the priority setting
  16401. *
  16402. * Processes all the rows in order, inserting a groupHeader row whenever there is a change
  16403. * in value of a grouped row, based on the sortAlgorithm used for the column. The group header row
  16404. * is looked up in the groupHeaderCache, and used from there if there is one. The entity is reset
  16405. * to {} if one is found.
  16406. *
  16407. * As it processes it maintains a `processingState` array. This records, for each level of grouping we're
  16408. * working with, the following information:
  16409. * ```
  16410. * {
  16411. * fieldName: name,
  16412. * col: col,
  16413. * initialised: boolean,
  16414. * currentValue: value,
  16415. * currentRow: gridRow,
  16416. * }
  16417. * ```
  16418. * We look for changes in the currentValue at any of the levels. Where we find a change we:
  16419. *
  16420. * - create a new groupHeader row in the array
  16421. *
  16422. * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor
  16423. * @returns {array} the updated rows, including our new group rows
  16424. */
  16425. groupRows: function(renderableRows) {
  16426. if (renderableRows.length === 0) {
  16427. return renderableRows;
  16428. }
  16429. var grid = this;
  16430. grid.grouping.oldGroupingHeaderCache = grid.grouping.groupingHeaderCache || {};
  16431. grid.grouping.groupingHeaderCache = {};
  16432. var processingState = service.initialiseProcessingState(grid);
  16433. // processes each of the fields we are grouping by, checks if the value has changed and inserts a groupHeader
  16434. // Broken out as shouldn't create functions in a loop.
  16435. var updateProcessingState = function(groupFieldState, stateIndex) {
  16436. var fieldValue = grid.getCellValue(row, groupFieldState.col);
  16437. // look for change of value - and insert a header
  16438. if (!groupFieldState.initialised || rowSorter.getSortFn(grid, groupFieldState.col, renderableRows)(fieldValue, groupFieldState.currentValue) !== 0) {
  16439. service.insertGroupHeader(grid, renderableRows, i, processingState, stateIndex);
  16440. i++;
  16441. }
  16442. };
  16443. // use a for loop because it's tolerant of the array length changing whilst we go - we can
  16444. // manipulate the iterator when we insert groupHeader rows
  16445. for (var i = 0; i < renderableRows.length; i++) {
  16446. var row = renderableRows[i];
  16447. if (row.visible) {
  16448. processingState.forEach(updateProcessingState);
  16449. }
  16450. }
  16451. delete grid.grouping.oldGroupingHeaderCache;
  16452. return renderableRows;
  16453. },
  16454. /**
  16455. * @ngdoc function
  16456. * @name initialiseProcessingState
  16457. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16458. * @description Creates the processing state array that is used
  16459. * for groupRows.
  16460. *
  16461. * @param {Grid} grid grid object
  16462. * @returns {array} an array in the format described in the groupRows method,
  16463. * initialised with blank values
  16464. */
  16465. initialiseProcessingState: function(grid) {
  16466. var processingState = [];
  16467. var columnSettings = service.getGrouping(grid);
  16468. columnSettings.grouping.forEach(function(groupItem, index) {
  16469. processingState.push({
  16470. fieldName: groupItem.field,
  16471. col: groupItem.col,
  16472. initialised: false,
  16473. currentValue: null,
  16474. currentRow: null
  16475. });
  16476. });
  16477. return processingState;
  16478. },
  16479. /**
  16480. * @ngdoc function
  16481. * @name getGrouping
  16482. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16483. * @description Get the grouping settings from the columns. As a side effect
  16484. * this always renumbers the grouping starting at 0
  16485. * @param {Grid} grid grid object
  16486. * @returns {array} an array of the group fields, in order of priority
  16487. */
  16488. getGrouping: function(grid) {
  16489. var groupArray = [];
  16490. var aggregateArray = [];
  16491. // get all the grouping
  16492. grid.columns.forEach(function(column, columnIndex) {
  16493. if (column.grouping) {
  16494. if (typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0) {
  16495. groupArray.push({ field: column.field, col: column, groupPriority: column.grouping.groupPriority, grouping: column.grouping });
  16496. }
  16497. }
  16498. if (column.treeAggregation && column.treeAggregation.type) {
  16499. aggregateArray.push({ field: column.field, col: column, aggregation: column.treeAggregation });
  16500. }
  16501. });
  16502. // sort grouping into priority order
  16503. groupArray.sort(function(a, b) {
  16504. return a.groupPriority - b.groupPriority;
  16505. });
  16506. // renumber the priority in case it was somewhat messed up, then remove the grouping reference
  16507. groupArray.forEach(function(group, index) {
  16508. group.grouping.groupPriority = index;
  16509. group.groupPriority = index;
  16510. delete group.grouping;
  16511. });
  16512. return { grouping: groupArray, aggregations: aggregateArray };
  16513. },
  16514. /**
  16515. * @ngdoc function
  16516. * @name insertGroupHeader
  16517. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16518. * @description Create a group header row, and link it to the various configuration
  16519. * items that we use.
  16520. *
  16521. * Look for the row in the oldGroupingHeaderCache, write the row into the new groupingHeaderCache.
  16522. *
  16523. * @param {Grid} grid grid object
  16524. * @param {array} renderableRows the rows that we are processing
  16525. * @param {number} rowIndex the row we were up to processing
  16526. * @param {array} processingState the current processing state
  16527. * @param {number} stateIndex the processing state item that we were on when we triggered a new group header -
  16528. * i.e. the column that we want to create a header for
  16529. */
  16530. insertGroupHeader: function(grid, renderableRows, rowIndex, processingState, stateIndex) {
  16531. // set the value that caused the end of a group into the header row and the processing state
  16532. var fieldName = processingState[stateIndex].fieldName;
  16533. var col = processingState[stateIndex].col;
  16534. var newValue = grid.getCellValue(renderableRows[rowIndex], col);
  16535. var newDisplayValue = newValue;
  16536. if (typeof(newValue) === 'undefined' || newValue === null) {
  16537. newDisplayValue = grid.options.groupingNullLabel;
  16538. }
  16539. var cacheItem = grid.grouping.oldGroupingHeaderCache;
  16540. for (var i = 0; i < stateIndex; i++) {
  16541. if (cacheItem && cacheItem[processingState[i].currentValue]) {
  16542. cacheItem = cacheItem[processingState[i].currentValue].children;
  16543. }
  16544. }
  16545. var headerRow;
  16546. if (cacheItem && cacheItem[newValue]) {
  16547. headerRow = cacheItem[newValue].row;
  16548. headerRow.entity = {};
  16549. } else {
  16550. headerRow = new GridRow({}, null, grid);
  16551. gridClassFactory.rowTemplateAssigner.call(grid, headerRow);
  16552. }
  16553. headerRow.entity['$$' + processingState[stateIndex].col.uid] = { groupVal: newDisplayValue };
  16554. headerRow.treeLevel = stateIndex;
  16555. headerRow.groupHeader = true;
  16556. headerRow.internalRow = true;
  16557. headerRow.enableCellEdit = false;
  16558. headerRow.enableSelection = grid.options.enableGroupHeaderSelection;
  16559. processingState[stateIndex].initialised = true;
  16560. processingState[stateIndex].currentValue = newValue;
  16561. processingState[stateIndex].currentRow = headerRow;
  16562. // set all processing states below this one to not be initialised - change of this state
  16563. // means all those need to start again
  16564. service.finaliseProcessingState(processingState, stateIndex + 1);
  16565. // insert our new header row
  16566. renderableRows.splice(rowIndex, 0, headerRow);
  16567. // add our new header row to the cache
  16568. cacheItem = grid.grouping.groupingHeaderCache;
  16569. for (i = 0; i < stateIndex; i++) {
  16570. cacheItem = cacheItem[processingState[i].currentValue].children;
  16571. }
  16572. cacheItem[newValue] = { row: headerRow, children: {} };
  16573. },
  16574. /**
  16575. * @ngdoc function
  16576. * @name finaliseProcessingState
  16577. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16578. * @description Set all processing states lower than the one that had a break in value to
  16579. * no longer be initialised. Render the counts into the entity ready for display.
  16580. *
  16581. * @param {Grid} grid grid object
  16582. * @param {array} processingState the current processing state
  16583. * @param {number} stateIndex the processing state item that we were on when we triggered a new group header, all
  16584. * processing states after this need to be finalised
  16585. */
  16586. finaliseProcessingState: function(processingState, stateIndex) {
  16587. for (var i = stateIndex; i < processingState.length; i++) {
  16588. processingState[i].initialised = false;
  16589. processingState[i].currentRow = null;
  16590. processingState[i].currentValue = null;
  16591. }
  16592. },
  16593. /**
  16594. * @ngdoc function
  16595. * @name getRowExpandedStates
  16596. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16597. * @description Extract the groupHeaderCache hash, pulling out only the states.
  16598. *
  16599. * The example below shows a grid that is grouped by gender then age
  16600. *
  16601. * <pre>
  16602. * {
  16603. * male: {
  16604. * state: 'expanded',
  16605. * children: {
  16606. * 22: { state: 'expanded' },
  16607. * 30: { state: 'collapsed' }
  16608. * }
  16609. * },
  16610. * female: {
  16611. * state: 'expanded',
  16612. * children: {
  16613. * 28: { state: 'expanded' },
  16614. * 55: { state: 'collapsed' }
  16615. * }
  16616. * }
  16617. * }
  16618. * </pre>
  16619. *
  16620. * @param {Grid} grid grid object
  16621. * @returns {hash} the expanded states as a hash
  16622. */
  16623. getRowExpandedStates: function(treeChildren) {
  16624. if (typeof(treeChildren) === 'undefined') {
  16625. return {};
  16626. }
  16627. var newChildren = {};
  16628. angular.forEach(treeChildren, function(value, key) {
  16629. newChildren[key] = { state: value.row.treeNode.state };
  16630. if (value.children) {
  16631. newChildren[key].children = service.getRowExpandedStates(value.children);
  16632. } else {
  16633. newChildren[key].children = {};
  16634. }
  16635. });
  16636. return newChildren;
  16637. },
  16638. /**
  16639. * @ngdoc function
  16640. * @name applyRowExpandedStates
  16641. * @methodOf ui.grid.grouping.service:uiGridGroupingService
  16642. * @description Take a hash in the format as created by getRowExpandedStates,
  16643. * and apply it to the grid.grouping.groupHeaderCache.
  16644. *
  16645. * Takes a treeSubset, and applies to a treeSubset - so can be called
  16646. * recursively.
  16647. *
  16648. * @param {object} currentNode can be grid.grouping.groupHeaderCache, or any of
  16649. * the children of that hash
  16650. * @returns {hash} expandedStates can be the full expanded states, or children
  16651. * of that expanded states (which hopefully matches the subset of the groupHeaderCache)
  16652. */
  16653. applyRowExpandedStates: function(currentNode, expandedStates) {
  16654. if (typeof(expandedStates) === 'undefined') {
  16655. return;
  16656. }
  16657. angular.forEach(expandedStates, function(value, key) {
  16658. if (currentNode[key]) {
  16659. currentNode[key].row.treeNode.state = value.state;
  16660. if (value.children && currentNode[key].children) {
  16661. service.applyRowExpandedStates(currentNode[key].children, value.children);
  16662. }
  16663. }
  16664. });
  16665. }
  16666. };
  16667. return service;
  16668. }
  16669. ]);
  16670. /**
  16671. * @ngdoc directive
  16672. * @name ui.grid.grouping.directive:uiGridGrouping
  16673. * @element div
  16674. * @restrict A
  16675. *
  16676. * @description Adds grouping features to grid
  16677. *
  16678. * @example
  16679. <example module="app">
  16680. <file name="app.js">
  16681. var app = angular.module('app', ['ui.grid', 'ui.grid.grouping']);
  16682. app.controller('MainCtrl', ['$scope', function ($scope) {
  16683. $scope.data = [
  16684. { name: 'Bob', title: 'CEO' },
  16685. { name: 'Frank', title: 'Lowly Developer' }
  16686. ];
  16687. $scope.columnDefs = [
  16688. {name: 'name', enableCellEdit: true},
  16689. {name: 'title', enableCellEdit: true}
  16690. ];
  16691. $scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data };
  16692. }]);
  16693. </file>
  16694. <file name="index.html">
  16695. <div ng-controller="MainCtrl">
  16696. <div ui-grid="gridOptions" ui-grid-grouping></div>
  16697. </div>
  16698. </file>
  16699. </example>
  16700. */
  16701. module.directive('uiGridGrouping', ['uiGridGroupingConstants', 'uiGridGroupingService', '$templateCache',
  16702. function(uiGridGroupingConstants, uiGridGroupingService, $templateCache) {
  16703. return {
  16704. replace: true,
  16705. priority: 0,
  16706. require: '^uiGrid',
  16707. scope: false,
  16708. compile: function() {
  16709. return {
  16710. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  16711. if (uiGridCtrl.grid.options.enableGrouping !== false) {
  16712. uiGridGroupingService.initializeGrid(uiGridCtrl.grid, $scope);
  16713. }
  16714. },
  16715. post: function($scope, $elm, $attrs, uiGridCtrl) {}
  16716. };
  16717. }
  16718. };
  16719. }
  16720. ]);
  16721. })();
  16722. (function() {
  16723. 'use strict';
  16724. /**
  16725. * @ngdoc overview
  16726. * @name ui.grid.importer
  16727. * @description
  16728. *
  16729. * # ui.grid.importer
  16730. *
  16731. * <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>
  16732. *
  16733. * This module provides the ability to import data into the grid. It
  16734. * uses the column defs to work out which data belongs in which column,
  16735. * and creates entities from a configured class (typically a $resource).
  16736. *
  16737. * If the rowEdit feature is enabled, it also calls save on those newly
  16738. * created objects, and then displays any errors in the imported data.
  16739. *
  16740. * Currently the importer imports only CSV and json files, although provision has been
  16741. * made to process other file formats, and these can be added over time.
  16742. *
  16743. * For json files, the properties within each object in the json must match the column names
  16744. * (to put it another way, the importer doesn't process the json, it just copies the objects
  16745. * within the json into a new instance of the specified object type)
  16746. *
  16747. * For CSV import, the default column identification relies on each column in the
  16748. * header row matching a column.name or column.displayName. Optionally, a column identification
  16749. * callback can be used. This allows matching using other attributes, which is particularly
  16750. * useful if your application has internationalised column headings (i.e. the headings that
  16751. * the user sees don't match the column names).
  16752. *
  16753. * The importer makes use of the grid menu as the UI for requesting an
  16754. * import.
  16755. *
  16756. * <div ui-grid-importer></div>
  16757. */
  16758. var module = angular.module('ui.grid.importer', ['ui.grid']);
  16759. /**
  16760. * @ngdoc object
  16761. * @name ui.grid.importer.constant:uiGridImporterConstants
  16762. *
  16763. * @description constants available in importer module
  16764. */
  16765. module.constant('uiGridImporterConstants', {
  16766. featureName: 'importer'
  16767. });
  16768. /**
  16769. * @ngdoc service
  16770. * @name ui.grid.importer.service:uiGridImporterService
  16771. *
  16772. * @description Services for importer feature
  16773. */
  16774. module.service('uiGridImporterService', ['$q', 'uiGridConstants', 'uiGridImporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService', '$window',
  16775. function($q, uiGridConstants, uiGridImporterConstants, gridUtil, $compile, $interval, i18nService, $window) {
  16776. var service = {
  16777. initializeGrid: function($scope, grid) {
  16778. //add feature namespace and any properties to grid for needed state
  16779. grid.importer = {
  16780. $scope: $scope
  16781. };
  16782. this.defaultGridOptions(grid.options);
  16783. /**
  16784. * @ngdoc object
  16785. * @name ui.grid.importer.api:PublicApi
  16786. *
  16787. * @description Public Api for importer feature
  16788. */
  16789. var publicApi = {
  16790. events: {
  16791. importer: {}
  16792. },
  16793. methods: {
  16794. importer: {
  16795. /**
  16796. * @ngdoc function
  16797. * @name importFile
  16798. * @methodOf ui.grid.importer.api:PublicApi
  16799. * @description Imports a file into the grid using the file object
  16800. * provided. Bypasses the grid menu
  16801. * @param {File} fileObject the file we want to import, as a javascript
  16802. * File object
  16803. */
  16804. importFile: function(fileObject) {
  16805. service.importThisFile(grid, fileObject);
  16806. }
  16807. }
  16808. }
  16809. };
  16810. grid.api.registerEventsFromObject(publicApi.events);
  16811. grid.api.registerMethodsFromObject(publicApi.methods);
  16812. if (grid.options.enableImporter && grid.options.importerShowMenu) {
  16813. if (grid.api.core.addToGridMenu) {
  16814. service.addToMenu(grid);
  16815. } else {
  16816. // order of registration is not guaranteed, register in a little while
  16817. $interval(function() {
  16818. if (grid.api.core.addToGridMenu) {
  16819. service.addToMenu(grid);
  16820. }
  16821. }, 100, 1);
  16822. }
  16823. }
  16824. },
  16825. defaultGridOptions: function(gridOptions) {
  16826. //default option to true unless it was explicitly set to false
  16827. /**
  16828. * @ngdoc object
  16829. * @name ui.grid.importer.api:GridOptions
  16830. *
  16831. * @description GridOptions for importer feature, these are available to be
  16832. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  16833. */
  16834. /**
  16835. * @ngdoc property
  16836. * @propertyOf ui.grid.importer.api:GridOptions
  16837. * @name enableImporter
  16838. * @description Whether or not importer is enabled. Automatically set
  16839. * to false if the user's browser does not support the required fileApi.
  16840. * Otherwise defaults to true.
  16841. *
  16842. */
  16843. if (gridOptions.enableImporter || gridOptions.enableImporter === undefined) {
  16844. if (!($window.hasOwnProperty('File') && $window.hasOwnProperty('FileReader') && $window.hasOwnProperty('FileList') && $window.hasOwnProperty('Blob'))) {
  16845. gridUtil.logError('The File APIs are not fully supported in this browser, grid importer cannot be used.');
  16846. gridOptions.enableImporter = false;
  16847. } else {
  16848. gridOptions.enableImporter = true;
  16849. }
  16850. } else {
  16851. gridOptions.enableImporter = false;
  16852. }
  16853. /**
  16854. * @ngdoc method
  16855. * @name importerProcessHeaders
  16856. * @methodOf ui.grid.importer.api:GridOptions
  16857. * @description A callback function that will process headers using custom
  16858. * logic. Set this callback function if the headers that your user will provide in their
  16859. * import file don't necessarily match the grid header or field names. This might commonly
  16860. * occur where your application is internationalised, and therefore the field names
  16861. * that the user recognises are in a different language than the field names that
  16862. * ui-grid knows about.
  16863. *
  16864. * Defaults to the internal `processHeaders` method, which seeks to match using both
  16865. * displayName and column.name. Any non-matching columns are discarded.
  16866. *
  16867. * Your callback routine should respond by processing the header array, and returning an array
  16868. * of matching column names. A null value in any given position means "don't import this column"
  16869. *
  16870. * <pre>
  16871. * gridOptions.importerProcessHeaders: function( headerArray ) {
  16872. * var myHeaderColumns = [];
  16873. * var thisCol;
  16874. * headerArray.forEach( function( value, index ) {
  16875. * thisCol = mySpecialLookupFunction( value );
  16876. * myHeaderColumns.push( thisCol.name );
  16877. * });
  16878. *
  16879. * return myHeaderCols;
  16880. * })
  16881. * </pre>
  16882. * @param {Grid} grid the grid we're importing into
  16883. * @param {array} headerArray an array of the text from the first row of the csv file,
  16884. * which you need to match to column.names
  16885. * @returns {array} array of matching column names, in the same order as the headerArray
  16886. *
  16887. */
  16888. gridOptions.importerProcessHeaders = gridOptions.importerProcessHeaders || service.processHeaders;
  16889. /**
  16890. * @ngdoc method
  16891. * @name importerHeaderFilter
  16892. * @methodOf ui.grid.importer.api:GridOptions
  16893. * @description A callback function that will filter (usually translate) a single
  16894. * header. Used when you want to match the passed in column names to the column
  16895. * displayName after the header filter.
  16896. *
  16897. * Your callback routine needs to return the filtered header value.
  16898. * <pre>
  16899. * gridOptions.importerHeaderFilter: function( displayName ) {
  16900. * return $translate.instant( displayName );
  16901. * })
  16902. * </pre>
  16903. *
  16904. * or:
  16905. * <pre>
  16906. * gridOptions.importerHeaderFilter: $translate.instant
  16907. * </pre>
  16908. * @param {string} displayName the displayName that we'd like to translate
  16909. * @returns {string} the translated name
  16910. *
  16911. */
  16912. gridOptions.importerHeaderFilter = gridOptions.importerHeaderFilter || function(displayName) { return displayName; };
  16913. /**
  16914. * @ngdoc method
  16915. * @name importerErrorCallback
  16916. * @methodOf ui.grid.importer.api:GridOptions
  16917. * @description A callback function that provides custom error handling, rather
  16918. * than the standard grid behaviour of an alert box and a console message. You
  16919. * might use this to internationalise the console log messages, or to write to a
  16920. * custom logging routine that returned errors to the server.
  16921. *
  16922. * <pre>
  16923. * gridOptions.importerErrorCallback: function( grid, errorKey, consoleMessage, context ) {
  16924. * myUserDisplayRoutine( errorKey );
  16925. * myLoggingRoutine( consoleMessage, context );
  16926. * })
  16927. * </pre>
  16928. * @param {Grid} grid the grid we're importing into, may be useful if you're positioning messages
  16929. * in some way
  16930. * @param {string} errorKey one of the i18n keys the importer can return - importer.noHeaders,
  16931. * importer.noObjects, importer.invalidCsv, importer.invalidJson, importer.jsonNotArray
  16932. * @param {string} consoleMessage the English console message that importer would have written
  16933. * @param {object} context the context data that importer would have appended to that console message,
  16934. * often the file content itself or the element that is in error
  16935. *
  16936. */
  16937. if (!gridOptions.importerErrorCallback || typeof(gridOptions.importerErrorCallback) !== 'function') {
  16938. delete gridOptions.importerErrorCallback;
  16939. }
  16940. /**
  16941. * @ngdoc method
  16942. * @name importerDataAddCallback
  16943. * @methodOf ui.grid.importer.api:GridOptions
  16944. * @description A mandatory callback function that adds data to the source data array. The grid
  16945. * generally doesn't add rows to the source data array, it is tidier to handle this through a user
  16946. * callback.
  16947. *
  16948. * <pre>
  16949. * gridOptions.importerDataAddCallback: function( grid, newObjects ) {
  16950. * $scope.myData = $scope.myData.concat( newObjects );
  16951. * })
  16952. * </pre>
  16953. * @param {Grid} grid the grid we're importing into, may be useful in some way
  16954. * @param {array} newObjects an array of new objects that you should add to your data
  16955. *
  16956. */
  16957. if (gridOptions.enableImporter === true && !gridOptions.importerDataAddCallback) {
  16958. gridUtil.logError("You have not set an importerDataAddCallback, importer is disabled");
  16959. gridOptions.enableImporter = false;
  16960. }
  16961. /**
  16962. * @ngdoc object
  16963. * @name importerNewObject
  16964. * @propertyOf ui.grid.importer.api:GridOptions
  16965. * @description An object on which we call `new` to create each new row before inserting it into
  16966. * the data array. Typically this would be a $resource entity, which means that if you're using
  16967. * the rowEdit feature, you can directly call save on this entity when the save event is triggered.
  16968. *
  16969. * Defaults to a vanilla javascript object
  16970. *
  16971. * @example
  16972. * <pre>
  16973. * gridOptions.importerNewObject = MyRes;
  16974. * </pre>
  16975. *
  16976. */
  16977. /**
  16978. * @ngdoc property
  16979. * @propertyOf ui.grid.importer.api:GridOptions
  16980. * @name importerShowMenu
  16981. * @description Whether or not to show an item in the grid menu. Defaults to true.
  16982. *
  16983. */
  16984. gridOptions.importerShowMenu = gridOptions.importerShowMenu !== false;
  16985. /**
  16986. * @ngdoc method
  16987. * @methodOf ui.grid.importer.api:GridOptions
  16988. * @name importerObjectCallback
  16989. * @description A callback that massages the data for each object. For example,
  16990. * you might have data stored as a code value, but display the decode. This callback
  16991. * can be used to change the decoded value back into a code. Defaults to doing nothing.
  16992. * @param {Grid} grid in case you need it
  16993. * @param {object} newObject the new object as importer has created it, modify it
  16994. * then return the modified version
  16995. * @returns {object} the modified object
  16996. * @example
  16997. * <pre>
  16998. * gridOptions.importerObjectCallback = function ( grid, newObject ) {
  16999. * switch newObject.status {
  17000. * case 'Active':
  17001. * newObject.status = 1;
  17002. * break;
  17003. * case 'Inactive':
  17004. * newObject.status = 2;
  17005. * break;
  17006. * }
  17007. * return newObject;
  17008. * };
  17009. * </pre>
  17010. */
  17011. gridOptions.importerObjectCallback = gridOptions.importerObjectCallback || function(grid, newObject) { return newObject; };
  17012. },
  17013. /**
  17014. * @ngdoc function
  17015. * @name addToMenu
  17016. * @methodOf ui.grid.importer.service:uiGridImporterService
  17017. * @description Adds import menu item to the grid menu,
  17018. * allowing the user to request import of a file
  17019. * @param {Grid} grid the grid into which data should be imported
  17020. */
  17021. addToMenu: function(grid) {
  17022. grid.api.core.addToGridMenu(grid, [{
  17023. title: i18nService.getSafeText('gridMenu.importerTitle'),
  17024. order: 150
  17025. },
  17026. {
  17027. templateUrl: 'ui-grid/importerMenuItemContainer',
  17028. action: function($event) {
  17029. this.grid.api.importer.importAFile(grid);
  17030. },
  17031. order: 151
  17032. }
  17033. ]);
  17034. },
  17035. /**
  17036. * @ngdoc function
  17037. * @name importThisFile
  17038. * @methodOf ui.grid.importer.service:uiGridImporterService
  17039. * @description Imports the provided file into the grid using the file object
  17040. * provided. Bypasses the grid menu
  17041. * @param {Grid} grid the grid we're importing into
  17042. * @param {File} fileObject the file we want to import, as returned from the File
  17043. * javascript object
  17044. */
  17045. importThisFile: function(grid, fileObject) {
  17046. if (!fileObject) {
  17047. gridUtil.logError('No file object provided to importThisFile, should be impossible, aborting');
  17048. return;
  17049. }
  17050. var reader = new FileReader();
  17051. switch (fileObject.type) {
  17052. case 'application/json':
  17053. reader.onload = service.importJsonClosure(grid);
  17054. break;
  17055. default:
  17056. reader.onload = service.importCsvClosure(grid);
  17057. break;
  17058. }
  17059. reader.readAsText(fileObject);
  17060. },
  17061. /**
  17062. * @ngdoc function
  17063. * @name importJson
  17064. * @methodOf ui.grid.importer.service:uiGridImporterService
  17065. * @description Creates a function that imports a json file into the grid.
  17066. * The json data is imported into new objects of type `gridOptions.importerNewObject`,
  17067. * and if the rowEdit feature is enabled the rows are marked as dirty
  17068. * @param {Grid} grid the grid we want to import into
  17069. * @param {FileObject} importFile the file that we want to import, as
  17070. * a FileObject
  17071. */
  17072. importJsonClosure: function(grid) {
  17073. return function(importFile) {
  17074. var newObjects = [];
  17075. var newObject;
  17076. var importArray = service.parseJson(grid, importFile);
  17077. if (importArray === null) {
  17078. return;
  17079. }
  17080. importArray.forEach(function(value, index) {
  17081. newObject = service.newObject(grid);
  17082. angular.extend(newObject, value);
  17083. newObject = grid.options.importerObjectCallback(grid, newObject);
  17084. newObjects.push(newObject);
  17085. });
  17086. service.addObjects(grid, newObjects);
  17087. };
  17088. },
  17089. /**
  17090. * @ngdoc function
  17091. * @name parseJson
  17092. * @methodOf ui.grid.importer.service:uiGridImporterService
  17093. * @description Parses a json file, returns the parsed data.
  17094. * Displays an error if file doesn't parse
  17095. * @param {Grid} grid the grid that we want to import into
  17096. * @param {FileObject} importFile the file that we want to import, as
  17097. * a FileObject
  17098. * @returns {array} array of objects from the imported json
  17099. */
  17100. parseJson: function(grid, importFile) {
  17101. var loadedObjects;
  17102. try {
  17103. loadedObjects = JSON.parse(importFile.target.result);
  17104. } catch (e) {
  17105. service.alertError(grid, 'importer.invalidJson', 'File could not be processed, is it valid json? Content was: ', importFile.target.result);
  17106. return;
  17107. }
  17108. if (!Array.isArray(loadedObjects)) {
  17109. service.alertError(grid, 'importer.jsonNotarray', 'Import failed, file is not an array, file was: ', importFile.target.result);
  17110. return [];
  17111. } else {
  17112. return loadedObjects;
  17113. }
  17114. },
  17115. /**
  17116. * @ngdoc function
  17117. * @name importCsvClosure
  17118. * @methodOf ui.grid.importer.service:uiGridImporterService
  17119. * @description Creates a function that imports a csv file into the grid
  17120. * (allowing it to be used in the reader.onload event)
  17121. * @param {Grid} grid the grid that we want to import into
  17122. * @param {FileObject} importFile the file that we want to import, as
  17123. * a file object
  17124. */
  17125. importCsvClosure: function(grid) {
  17126. return function(importFile) {
  17127. var importArray = service.parseCsv(importFile);
  17128. if (!importArray || importArray.length < 1) {
  17129. service.alertError(grid, 'importer.invalidCsv', 'File could not be processed, is it valid csv? Content was: ', importFile.target.result);
  17130. return;
  17131. }
  17132. var newObjects = service.createCsvObjects(grid, importArray);
  17133. if (!newObjects || newObjects.length === 0) {
  17134. service.alertError(grid, 'importer.noObjects', 'Objects were not able to be derived, content was: ', importFile.target.result);
  17135. return;
  17136. }
  17137. service.addObjects(grid, newObjects);
  17138. };
  17139. },
  17140. /**
  17141. * @ngdoc function
  17142. * @name parseCsv
  17143. * @methodOf ui.grid.importer.service:uiGridImporterService
  17144. * @description Parses a csv file into an array of arrays, with the first
  17145. * array being the headers, and the remaining arrays being the data.
  17146. * The logic for this comes from https://github.com/thetalecrafter/excel.js/blob/master/src/csv.js,
  17147. * which is noted as being under the MIT license. The code is modified to pass the jscs yoda condition
  17148. * checker
  17149. * @param {FileObject} importFile the file that we want to import, as a
  17150. * file object
  17151. */
  17152. parseCsv: function(importFile) {
  17153. var csv = importFile.target.result;
  17154. // use the CSV-JS library to parse
  17155. return CSV.parse(csv);
  17156. },
  17157. /**
  17158. * @ngdoc function
  17159. * @name createCsvObjects
  17160. * @methodOf ui.grid.importer.service:uiGridImporterService
  17161. * @description Converts an array of arrays (representing the csv file)
  17162. * into a set of objects. Uses the provided `gridOptions.importerNewObject`
  17163. * to create the objects, and maps the header row into the individual columns
  17164. * using either `gridOptions.importerProcessHeaders`, or by using a native method
  17165. * of matching to either the displayName, column name or column field of
  17166. * the columns in the column defs. The resulting objects will have attributes
  17167. * that are named based on the column.field or column.name, in that order.
  17168. * @param {Grid} grid the grid that we want to import into
  17169. * @param {Array} importArray the data that we want to import, as an array
  17170. */
  17171. createCsvObjects: function(grid, importArray) {
  17172. // pull off header row and turn into headers
  17173. var headerMapping = grid.options.importerProcessHeaders(grid, importArray.shift());
  17174. if (!headerMapping || headerMapping.length === 0) {
  17175. service.alertError(grid, 'importer.noHeaders', 'Column names could not be derived, content was: ', importArray);
  17176. return [];
  17177. }
  17178. var newObjects = [];
  17179. var newObject;
  17180. importArray.forEach(function(row, index) {
  17181. newObject = service.newObject(grid);
  17182. if (row !== null) {
  17183. row.forEach(function(field, index) {
  17184. if (headerMapping[index] !== null) {
  17185. newObject[headerMapping[index]] = field;
  17186. }
  17187. });
  17188. }
  17189. newObject = grid.options.importerObjectCallback(grid, newObject);
  17190. newObjects.push(newObject);
  17191. });
  17192. return newObjects;
  17193. },
  17194. /**
  17195. * @ngdoc function
  17196. * @name processHeaders
  17197. * @methodOf ui.grid.importer.service:uiGridImporterService
  17198. * @description Determines the columns that the header row from
  17199. * a csv (or other) file represents.
  17200. * @param {Grid} grid the grid we're importing into
  17201. * @param {array} headerRow the header row that we wish to match against
  17202. * the column definitions
  17203. * @returns {array} an array of the attribute names that should be used
  17204. * for that column, based on matching the headers or creating the headers
  17205. *
  17206. */
  17207. processHeaders: function(grid, headerRow) {
  17208. var headers = [];
  17209. if (!grid.options.columnDefs || grid.options.columnDefs.length === 0) {
  17210. // we are going to create new columnDefs for all these columns, so just remove
  17211. // spaces from the names to create fields
  17212. headerRow.forEach(function(value, index) {
  17213. headers.push(value.replace(/[^0-9a-zA-Z\-_]/g, '_'));
  17214. });
  17215. return headers;
  17216. } else {
  17217. var lookupHash = service.flattenColumnDefs(grid, grid.options.columnDefs);
  17218. headerRow.forEach(function(value, index) {
  17219. if (lookupHash[value]) {
  17220. headers.push(lookupHash[value]);
  17221. } else if (lookupHash[value.toLowerCase()]) {
  17222. headers.push(lookupHash[value.toLowerCase()]);
  17223. } else {
  17224. headers.push(null);
  17225. }
  17226. });
  17227. return headers;
  17228. }
  17229. },
  17230. /**
  17231. * @name flattenColumnDefs
  17232. * @methodOf ui.grid.importer.service:uiGridImporterService
  17233. * @description Runs through the column defs and creates a hash of
  17234. * the displayName, name and field, and of each of those values forced to lower case,
  17235. * with each pointing to the field or name
  17236. * (whichever is present). Used to lookup column headers and decide what
  17237. * attribute name to give to the resulting field.
  17238. * @param {Grid} grid the grid we're importing into
  17239. * @param {array} columnDefs the columnDefs that we should flatten
  17240. * @returns {hash} the flattened version of the column def information, allowing
  17241. * us to look up a value by `flattenedHash[ headerValue ]`
  17242. */
  17243. flattenColumnDefs: function(grid, columnDefs) {
  17244. var flattenedHash = {};
  17245. columnDefs.forEach(function(columnDef, index) {
  17246. if (columnDef.name) {
  17247. flattenedHash[columnDef.name] = columnDef.field || columnDef.name;
  17248. flattenedHash[columnDef.name.toLowerCase()] = columnDef.field || columnDef.name;
  17249. }
  17250. if (columnDef.field) {
  17251. flattenedHash[columnDef.field] = columnDef.field || columnDef.name;
  17252. flattenedHash[columnDef.field.toLowerCase()] = columnDef.field || columnDef.name;
  17253. }
  17254. if (columnDef.displayName) {
  17255. flattenedHash[columnDef.displayName] = columnDef.field || columnDef.name;
  17256. flattenedHash[columnDef.displayName.toLowerCase()] = columnDef.field || columnDef.name;
  17257. }
  17258. if (columnDef.displayName && grid.options.importerHeaderFilter) {
  17259. flattenedHash[grid.options.importerHeaderFilter(columnDef.displayName)] = columnDef.field || columnDef.name;
  17260. flattenedHash[grid.options.importerHeaderFilter(columnDef.displayName).toLowerCase()] = columnDef.field || columnDef.name;
  17261. }
  17262. });
  17263. return flattenedHash;
  17264. },
  17265. /**
  17266. * @ngdoc function
  17267. * @name addObjects
  17268. * @methodOf ui.grid.importer.service:uiGridImporterService
  17269. * @description Inserts our new objects into the grid data, and
  17270. * sets the rows to dirty if the rowEdit feature is being used
  17271. *
  17272. * Does this by registering a watch on dataChanges, which essentially
  17273. * is waiting on the result of the grid data watch, and downstream processing.
  17274. *
  17275. * When the callback is called, it deregisters itself - we don't want to run
  17276. * again next time data is added.
  17277. *
  17278. * If we never get called, we deregister on destroy.
  17279. *
  17280. * @param {Grid} grid the grid we're importing into
  17281. * @param {array} newObjects the objects we want to insert into the grid data
  17282. * @returns {object} the new object
  17283. */
  17284. addObjects: function(grid, newObjects, $scope) {
  17285. if (grid.api.rowEdit) {
  17286. var dataChangeDereg = grid.registerDataChangeCallback(function() {
  17287. grid.api.rowEdit.setRowsDirty(newObjects);
  17288. dataChangeDereg();
  17289. }, [uiGridConstants.dataChange.ROW]);
  17290. grid.importer.$scope.$on('$destroy', dataChangeDereg);
  17291. }
  17292. grid.importer.$scope.$apply(grid.options.importerDataAddCallback(grid, newObjects));
  17293. },
  17294. /**
  17295. * @ngdoc function
  17296. * @name newObject
  17297. * @methodOf ui.grid.importer.service:uiGridImporterService
  17298. * @description Makes a new object based on `gridOptions.importerNewObject`,
  17299. * or based on an empty object if not present
  17300. * @param {Grid} grid the grid we're importing into
  17301. * @returns {object} the new object
  17302. */
  17303. newObject: function(grid) {
  17304. if (typeof(grid.options) !== "undefined" && typeof(grid.options.importerNewObject) !== "undefined") {
  17305. return new grid.options.importerNewObject();
  17306. } else {
  17307. return {};
  17308. }
  17309. },
  17310. /**
  17311. * @ngdoc function
  17312. * @name alertError
  17313. * @methodOf ui.grid.importer.service:uiGridImporterService
  17314. * @description Provides an internationalised user alert for the failure,
  17315. * and logs a console message including diagnostic content.
  17316. * Optionally, if the the `gridOptions.importerErrorCallback` routine
  17317. * is defined, then calls that instead, allowing user specified error routines
  17318. * @param {Grid} grid the grid we're importing into
  17319. * @param {array} headerRow the header row that we wish to match against
  17320. * the column definitions
  17321. */
  17322. alertError: function(grid, alertI18nToken, consoleMessage, context) {
  17323. if (grid.options.importerErrorCallback) {
  17324. grid.options.importerErrorCallback(grid, alertI18nToken, consoleMessage, context);
  17325. } else {
  17326. $window.alert(i18nService.getSafeText(alertI18nToken));
  17327. gridUtil.logError(consoleMessage + context);
  17328. }
  17329. }
  17330. };
  17331. return service;
  17332. }
  17333. ]);
  17334. /**
  17335. * @ngdoc directive
  17336. * @name ui.grid.importer.directive:uiGridImporter
  17337. * @element div
  17338. * @restrict A
  17339. *
  17340. * @description Adds importer features to grid
  17341. *
  17342. */
  17343. module.directive('uiGridImporter', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile',
  17344. function(uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) {
  17345. return {
  17346. replace: true,
  17347. priority: 0,
  17348. require: '^uiGrid',
  17349. scope: false,
  17350. link: function($scope, $elm, $attrs, uiGridCtrl) {
  17351. uiGridImporterService.initializeGrid($scope, uiGridCtrl.grid);
  17352. }
  17353. };
  17354. }
  17355. ]);
  17356. /**
  17357. * @ngdoc directive
  17358. * @name ui.grid.importer.directive:uiGridImporterMenuItem
  17359. * @element div
  17360. * @restrict A
  17361. *
  17362. * @description Handles the processing from the importer menu item - once a file is
  17363. * selected
  17364. *
  17365. */
  17366. module.directive('uiGridImporterMenuItem', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile',
  17367. function(uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) {
  17368. return {
  17369. replace: true,
  17370. priority: 0,
  17371. require: '^uiGrid',
  17372. scope: false,
  17373. templateUrl: 'ui-grid/importerMenuItem',
  17374. link: function($scope, $elm, $attrs, uiGridCtrl) {
  17375. var handleFileSelect = function(event) {
  17376. var target = event.srcElement || event.target;
  17377. if (target && target.files && target.files.length === 1) {
  17378. var fileObject = target.files[0];
  17379. uiGridImporterService.importThisFile(grid, fileObject);
  17380. target.form.reset();
  17381. }
  17382. };
  17383. var fileChooser = $elm[0].querySelectorAll('.ui-grid-importer-file-chooser');
  17384. var grid = uiGridCtrl.grid;
  17385. if (fileChooser.length !== 1) {
  17386. gridUtil.logError('Found > 1 or < 1 file choosers within the menu item, error, cannot continue');
  17387. } else {
  17388. fileChooser[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google
  17389. }
  17390. }
  17391. };
  17392. }
  17393. ]);
  17394. })();
  17395. (function() {
  17396. 'use strict';
  17397. /**
  17398. * @ngdoc overview
  17399. * @name ui.grid.infiniteScroll
  17400. *
  17401. * @description
  17402. *
  17403. * #ui.grid.infiniteScroll
  17404. *
  17405. * <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>
  17406. *
  17407. * This module provides infinite scroll functionality to ui-grid
  17408. *
  17409. */
  17410. var module = angular.module('ui.grid.infiniteScroll', ['ui.grid']);
  17411. /**
  17412. * @ngdoc service
  17413. * @name ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17414. *
  17415. * @description Service for infinite scroll features
  17416. */
  17417. module.service('uiGridInfiniteScrollService', ['gridUtil', '$compile', '$timeout', 'uiGridConstants', 'ScrollEvent', '$q', function(gridUtil, $compile, $timeout, uiGridConstants, ScrollEvent, $q) {
  17418. var service = {
  17419. /**
  17420. * @ngdoc function
  17421. * @name initializeGrid
  17422. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17423. * @description This method register events and methods into grid public API
  17424. */
  17425. initializeGrid: function(grid, $scope) {
  17426. service.defaultGridOptions(grid.options);
  17427. if (!grid.options.enableInfiniteScroll) {
  17428. return;
  17429. }
  17430. grid.infiniteScroll = { dataLoading: false };
  17431. service.setScrollDirections(grid, grid.options.infiniteScrollUp, grid.options.infiniteScrollDown);
  17432. grid.api.core.on.scrollEnd($scope, service.handleScroll);
  17433. /**
  17434. * @ngdoc object
  17435. * @name ui.grid.infiniteScroll.api:PublicAPI
  17436. *
  17437. * @description Public API for infinite scroll feature
  17438. */
  17439. var publicApi = {
  17440. events: {
  17441. infiniteScroll: {
  17442. /**
  17443. * @ngdoc event
  17444. * @name needLoadMoreData
  17445. * @eventOf ui.grid.infiniteScroll.api:PublicAPI
  17446. * @description This event fires when scroll reaches bottom percentage of grid
  17447. * and needs to load data
  17448. */
  17449. needLoadMoreData: function($scope, fn) {},
  17450. /**
  17451. * @ngdoc event
  17452. * @name needLoadMoreDataTop
  17453. * @eventOf ui.grid.infiniteScroll.api:PublicAPI
  17454. * @description This event fires when scroll reaches top percentage of grid
  17455. * and needs to load data
  17456. */
  17457. needLoadMoreDataTop: function($scope, fn) {}
  17458. }
  17459. },
  17460. methods: {
  17461. infiniteScroll: {
  17462. /**
  17463. * @ngdoc function
  17464. * @name dataLoaded
  17465. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17466. * @description Call this function when you have loaded the additional data
  17467. * requested. You should set scrollUp and scrollDown to indicate
  17468. * whether there are still more pages in each direction.
  17469. *
  17470. * If you call dataLoaded without first calling `saveScrollPercentage` then we will
  17471. * scroll the user to the start of the newly loaded data, which usually gives a smooth scroll
  17472. * experience, but can give a jumpy experience with large `infiniteScrollRowsFromEnd` values, and
  17473. * on variable speed internet connections. Using `saveScrollPercentage` as demonstrated in the tutorial
  17474. * should give a smoother scrolling experience for users.
  17475. *
  17476. * See infinite_scroll tutorial for example of usage
  17477. * @param {boolean} scrollUp if set to false flags that there are no more pages upwards, so don't fire
  17478. * any more infinite scroll events upward
  17479. * @param {boolean} scrollDown if set to false flags that there are no more pages downwards, so don't
  17480. * fire any more infinite scroll events downward
  17481. * @returns {promise} a promise that is resolved when the grid scrolling is fully adjusted. If you're
  17482. * planning to remove pages, you should wait on this promise first, or you'll break the scroll positioning
  17483. */
  17484. dataLoaded: function(scrollUp, scrollDown) {
  17485. service.setScrollDirections(grid, scrollUp, scrollDown);
  17486. var promise = service.adjustScroll(grid).then(function() {
  17487. grid.infiniteScroll.dataLoading = false;
  17488. });
  17489. return promise;
  17490. },
  17491. /**
  17492. * @ngdoc function
  17493. * @name resetScroll
  17494. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17495. * @description Call this function when you have taken some action that makes the current
  17496. * scroll position invalid. For example, if you're using external sorting and you've resorted
  17497. * then you might reset the scroll, or if you've otherwise substantially changed the data, perhaps
  17498. * you've reused an existing grid for a new data set
  17499. *
  17500. * You must tell us whether there is data upwards or downwards after the reset
  17501. *
  17502. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17503. * infinite scroll events upward
  17504. * @param {boolean} scrollDown flag that there are pages downwards, so
  17505. * fire infinite scroll events downward
  17506. * @returns {promise} promise that is resolved when the scroll reset is complete
  17507. */
  17508. resetScroll: function(scrollUp, scrollDown) {
  17509. service.setScrollDirections(grid, scrollUp, scrollDown);
  17510. return service.adjustInfiniteScrollPosition(grid, 0);
  17511. },
  17512. /**
  17513. * @ngdoc function
  17514. * @name saveScrollPercentage
  17515. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17516. * @description Saves the scroll percentage and number of visible rows before you adjust the data,
  17517. * used if you're subsequently going to call `dataRemovedTop` or `dataRemovedBottom`
  17518. */
  17519. saveScrollPercentage: function() {
  17520. grid.infiniteScroll.prevScrollTop = grid.renderContainers.body.prevScrollTop;
  17521. grid.infiniteScroll.previousVisibleRows = grid.getVisibleRowCount();
  17522. },
  17523. /**
  17524. * @ngdoc function
  17525. * @name dataRemovedTop
  17526. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17527. * @description Adjusts the scroll position after you've removed data at the top
  17528. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17529. * infinite scroll events upward
  17530. * @param {boolean} scrollDown flag that there are pages downwards, so
  17531. * fire infinite scroll events downward
  17532. */
  17533. dataRemovedTop: function(scrollUp, scrollDown) {
  17534. service.dataRemovedTop(grid, scrollUp, scrollDown);
  17535. },
  17536. /**
  17537. * @ngdoc function
  17538. * @name dataRemovedBottom
  17539. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17540. * @description Adjusts the scroll position after you've removed data at the bottom
  17541. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17542. * infinite scroll events upward
  17543. * @param {boolean} scrollDown flag that there are pages downwards, so
  17544. * fire infinite scroll events downward
  17545. */
  17546. dataRemovedBottom: function(scrollUp, scrollDown) {
  17547. service.dataRemovedBottom(grid, scrollUp, scrollDown);
  17548. },
  17549. /**
  17550. * @ngdoc function
  17551. * @name setScrollDirections
  17552. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17553. * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined,
  17554. * and also sets the grid.suppressParentScroll
  17555. * @param {boolean} scrollUp whether there are pages available up - defaults to false
  17556. * @param {boolean} scrollDown whether there are pages available down - defaults to true
  17557. */
  17558. setScrollDirections: function(scrollUp, scrollDown) {
  17559. service.setScrollDirections(grid, scrollUp, scrollDown);
  17560. }
  17561. }
  17562. }
  17563. };
  17564. grid.api.registerEventsFromObject(publicApi.events);
  17565. grid.api.registerMethodsFromObject(publicApi.methods);
  17566. },
  17567. defaultGridOptions: function(gridOptions) {
  17568. //default option to true unless it was explicitly set to false
  17569. /**
  17570. * @ngdoc object
  17571. * @name ui.grid.infiniteScroll.api:GridOptions
  17572. *
  17573. * @description GridOptions for infinite scroll feature, these are available to be
  17574. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  17575. */
  17576. /**
  17577. * @ngdoc object
  17578. * @name enableInfiniteScroll
  17579. * @propertyOf ui.grid.infiniteScroll.api:GridOptions
  17580. * @description Enable infinite scrolling for this grid
  17581. * <br/>Defaults to true
  17582. */
  17583. gridOptions.enableInfiniteScroll = gridOptions.enableInfiniteScroll !== false;
  17584. /**
  17585. * @ngdoc property
  17586. * @name infiniteScrollRowsFromEnd
  17587. * @propertyOf ui.grid.class:GridOptions
  17588. * @description This setting controls how close to the end of the dataset a user gets before
  17589. * more data is requested by the infinite scroll, whether scrolling up or down. This allows you to
  17590. * 'prefetch' rows before the user actually runs out of scrolling.
  17591. *
  17592. * Note that if you set this value too high it may give jumpy scrolling behaviour, if you're getting
  17593. * this behaviour you could use the `saveScrollPercentageMethod` right before loading your data, and we'll
  17594. * preserve that scroll position
  17595. *
  17596. * <br> Defaults to 20
  17597. */
  17598. gridOptions.infiniteScrollRowsFromEnd = gridOptions.infiniteScrollRowsFromEnd || 20;
  17599. /**
  17600. * @ngdoc property
  17601. * @name infiniteScrollUp
  17602. * @propertyOf ui.grid.class:GridOptions
  17603. * @description Whether you allow infinite scroll up, implying that the first page of data
  17604. * you have displayed is in the middle of your data set. If set to true then we trigger the
  17605. * needMoreDataTop event when the user hits the top of the scrollbar.
  17606. * <br> Defaults to false
  17607. */
  17608. gridOptions.infiniteScrollUp = gridOptions.infiniteScrollUp === true;
  17609. /**
  17610. * @ngdoc property
  17611. * @name infiniteScrollDown
  17612. * @propertyOf ui.grid.class:GridOptions
  17613. * @description Whether you allow infinite scroll down, implying that the first page of data
  17614. * you have displayed is in the middle of your data set. If set to true then we trigger the
  17615. * needMoreData event when the user hits the bottom of the scrollbar.
  17616. * <br> Defaults to true
  17617. */
  17618. gridOptions.infiniteScrollDown = gridOptions.infiniteScrollDown !== false;
  17619. },
  17620. /**
  17621. * @ngdoc function
  17622. * @name setScrollDirections
  17623. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17624. * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined,
  17625. * and also sets the grid.suppressParentScroll
  17626. * @param {grid} grid the grid we're operating on
  17627. * @param {boolean} scrollUp whether there are pages available up - defaults to false
  17628. * @param {boolean} scrollDown whether there are pages available down - defaults to true
  17629. */
  17630. setScrollDirections: function(grid, scrollUp, scrollDown) {
  17631. grid.infiniteScroll.scrollUp = (scrollUp === true);
  17632. grid.suppressParentScrollUp = (scrollUp === true);
  17633. grid.infiniteScroll.scrollDown = (scrollDown !== false);
  17634. grid.suppressParentScrollDown = (scrollDown !== false);
  17635. },
  17636. /**
  17637. * @ngdoc function
  17638. * @name handleScroll
  17639. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17640. * @description Called whenever the grid scrolls, determines whether the scroll should
  17641. * trigger an infinite scroll request for more data
  17642. * @param {object} args the args from the event
  17643. */
  17644. handleScroll: function(args) {
  17645. // don't request data if already waiting for data, or if source is coming from ui.grid.adjustInfiniteScrollPosition() function
  17646. if (args.grid.infiniteScroll && args.grid.infiniteScroll.dataLoading || args.source === 'ui.grid.adjustInfiniteScrollPosition') {
  17647. return;
  17648. }
  17649. if (args.y) {
  17650. var percentage;
  17651. var targetPercentage = args.grid.options.infiniteScrollRowsFromEnd / args.grid.renderContainers.body.visibleRowCache.length;
  17652. if (args.grid.scrollDirection === uiGridConstants.scrollDirection.UP) {
  17653. percentage = args.y.percentage;
  17654. if (percentage <= targetPercentage) {
  17655. service.loadData(args.grid);
  17656. }
  17657. } else if (args.grid.scrollDirection === uiGridConstants.scrollDirection.DOWN) {
  17658. percentage = 1 - args.y.percentage;
  17659. if (percentage <= targetPercentage) {
  17660. service.loadData(args.grid);
  17661. }
  17662. }
  17663. }
  17664. },
  17665. /**
  17666. * @ngdoc function
  17667. * @name loadData
  17668. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17669. * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection
  17670. * and whether there are more pages upwards or downwards. It also stores the number of rows that we had previously,
  17671. * and clears out any saved scroll position so that we know whether or not the user calls `saveScrollPercentage`
  17672. * @param {Grid} grid the grid we're working on
  17673. */
  17674. loadData: function(grid) {
  17675. // save number of currently visible rows to calculate new scroll position later - we know that we want
  17676. // to be at approximately the row we're currently at
  17677. grid.infiniteScroll.previousVisibleRows = grid.renderContainers.body.visibleRowCache.length;
  17678. grid.infiniteScroll.direction = grid.scrollDirection;
  17679. delete grid.infiniteScroll.prevScrollTop;
  17680. if (grid.scrollDirection === uiGridConstants.scrollDirection.UP && grid.infiniteScroll.scrollUp) {
  17681. grid.infiniteScroll.dataLoading = true;
  17682. grid.api.infiniteScroll.raise.needLoadMoreDataTop();
  17683. } else if (grid.scrollDirection === uiGridConstants.scrollDirection.DOWN && grid.infiniteScroll.scrollDown) {
  17684. grid.infiniteScroll.dataLoading = true;
  17685. grid.api.infiniteScroll.raise.needLoadMoreData();
  17686. }
  17687. },
  17688. /**
  17689. * @ngdoc function
  17690. * @name adjustScroll
  17691. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17692. * @description Once we are informed that data has been loaded, adjust the scroll position to account for that
  17693. * addition and to make things look clean.
  17694. *
  17695. * If we're scrolling up we scroll to the first row of the old data set -
  17696. * so we're assuming that you would have gotten to the top of the grid (from the 20% need more data trigger) by
  17697. * 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
  17698. * assuming that you would have gotten to the bottom of the grid (from the 80% need more data trigger) by the time
  17699. * the data comes back.
  17700. *
  17701. * Neither of these are good assumptions, but making this a smoother experience really requires
  17702. * 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
  17703. * 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
  17704. * somewhere else in the mean-time, in which case they'll get a jump back to the new data. Anyway, this will do for
  17705. * now, until someone wants to do better.
  17706. * @param {Grid} grid the grid we're working on
  17707. * @returns {promise} a promise that is resolved when scrolling has finished
  17708. */
  17709. adjustScroll: function(grid) {
  17710. var promise = $q.defer();
  17711. $timeout(function() {
  17712. var newPercentage, viewportHeight, rowHeight, newVisibleRows, oldTop, newTop;
  17713. viewportHeight = grid.getViewportHeight() + grid.headerHeight - grid.renderContainers.body.headerHeight - grid.scrollbarHeight;
  17714. rowHeight = grid.options.rowHeight;
  17715. if (grid.infiniteScroll.direction === undefined) {
  17716. // called from initialize, tweak our scroll up a little
  17717. service.adjustInfiniteScrollPosition(grid, 0);
  17718. }
  17719. newVisibleRows = grid.getVisibleRowCount();
  17720. if (grid.infiniteScroll.direction === uiGridConstants.scrollDirection.UP) {
  17721. oldTop = grid.infiniteScroll.prevScrollTop || 0;
  17722. newTop = oldTop + (newVisibleRows - grid.infiniteScroll.previousVisibleRows) * rowHeight;
  17723. service.adjustInfiniteScrollPosition(grid, newTop);
  17724. $timeout(function() {
  17725. promise.resolve();
  17726. });
  17727. }
  17728. if (grid.infiniteScroll.direction === uiGridConstants.scrollDirection.DOWN) {
  17729. newTop = grid.infiniteScroll.prevScrollTop || (grid.infiniteScroll.previousVisibleRows * rowHeight - viewportHeight);
  17730. service.adjustInfiniteScrollPosition(grid, newTop);
  17731. $timeout(function() {
  17732. promise.resolve();
  17733. });
  17734. }
  17735. }, 0);
  17736. return promise.promise;
  17737. },
  17738. /**
  17739. * @ngdoc function
  17740. * @name adjustInfiniteScrollPosition
  17741. * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
  17742. * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection
  17743. * @param {Grid} grid the grid we're working on
  17744. * @param {number} scrollTop the position through the grid that we want to scroll to
  17745. * @returns {promise} a promise that is resolved when the scrolling finishes
  17746. */
  17747. adjustInfiniteScrollPosition: function(grid, scrollTop) {
  17748. var scrollEvent = new ScrollEvent(grid, null, null, 'ui.grid.adjustInfiniteScrollPosition'),
  17749. visibleRows = grid.getVisibleRowCount(),
  17750. viewportHeight = grid.getViewportHeight() + grid.headerHeight - grid.renderContainers.body.headerHeight - grid.scrollbarHeight,
  17751. rowHeight = grid.options.rowHeight,
  17752. scrollHeight = visibleRows * rowHeight - viewportHeight;
  17753. //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
  17754. if (scrollTop === 0 && grid.infiniteScroll.scrollUp) {
  17755. // using pixels results in a relative scroll, hence we have to use percentage
  17756. scrollEvent.y = { percentage: 1 / scrollHeight };
  17757. } else {
  17758. scrollEvent.y = { percentage: scrollTop / scrollHeight };
  17759. }
  17760. grid.scrollContainers('', scrollEvent);
  17761. },
  17762. /**
  17763. * @ngdoc function
  17764. * @name dataRemovedTop
  17765. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17766. * @description Adjusts the scroll position after you've removed data at the top. You should
  17767. * have called `saveScrollPercentage` before you remove the data, and if you're doing this in
  17768. * response to a `needMoreData` you should wait until the promise from `loadData` has resolved
  17769. * before you start removing data
  17770. * @param {Grid} grid the grid we're working on
  17771. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17772. * infinite scroll events upward
  17773. * @param {boolean} scrollDown flag that there are pages downwards, so
  17774. * fire infinite scroll events downward
  17775. * @returns {promise} a promise that is resolved when the scrolling finishes
  17776. */
  17777. dataRemovedTop: function(grid, scrollUp, scrollDown) {
  17778. var newVisibleRows, oldTop, newTop, rowHeight;
  17779. service.setScrollDirections(grid, scrollUp, scrollDown);
  17780. newVisibleRows = grid.renderContainers.body.visibleRowCache.length;
  17781. oldTop = grid.infiniteScroll.prevScrollTop;
  17782. rowHeight = grid.options.rowHeight;
  17783. // since we removed from the top, our new scroll row will be the old scroll row less the number
  17784. // of rows removed
  17785. newTop = oldTop - (grid.infiniteScroll.previousVisibleRows - newVisibleRows) * rowHeight;
  17786. return service.adjustInfiniteScrollPosition(grid, newTop);
  17787. },
  17788. /**
  17789. * @ngdoc function
  17790. * @name dataRemovedBottom
  17791. * @methodOf ui.grid.infiniteScroll.api:PublicAPI
  17792. * @description Adjusts the scroll position after you've removed data at the bottom. You should
  17793. * have called `saveScrollPercentage` before you remove the data, and if you're doing this in
  17794. * response to a `needMoreData` you should wait until the promise from `loadData` has resolved
  17795. * before you start removing data
  17796. * @param {Grid} grid the grid we're working on
  17797. * @param {boolean} scrollUp flag that there are pages upwards, fire
  17798. * infinite scroll events upward
  17799. * @param {boolean} scrollDown flag that there are pages downwards, so
  17800. * fire infinite scroll events downward
  17801. */
  17802. dataRemovedBottom: function(grid, scrollUp, scrollDown) {
  17803. var newTop;
  17804. service.setScrollDirections(grid, scrollUp, scrollDown);
  17805. newTop = grid.infiniteScroll.prevScrollTop;
  17806. return service.adjustInfiniteScrollPosition(grid, newTop);
  17807. }
  17808. };
  17809. return service;
  17810. }]);
  17811. /**
  17812. * @ngdoc directive
  17813. * @name ui.grid.infiniteScroll.directive:uiGridInfiniteScroll
  17814. * @element div
  17815. * @restrict A
  17816. *
  17817. * @description Adds infinite scroll features to grid
  17818. *
  17819. * @example
  17820. <example module="app">
  17821. <file name="app.js">
  17822. var app = angular.module('app', ['ui.grid', 'ui.grid.infiniteScroll']);
  17823. app.controller('MainCtrl', ['$scope', function ($scope) {
  17824. $scope.data = [
  17825. { name: 'Alex', car: 'Toyota' },
  17826. { name: 'Sam', car: 'Lexus' }
  17827. ];
  17828. $scope.columnDefs = [
  17829. {name: 'name'},
  17830. {name: 'car'}
  17831. ];
  17832. }]);
  17833. </file>
  17834. <file name="index.html">
  17835. <div ng-controller="MainCtrl">
  17836. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-infinite-scroll="20"></div>
  17837. </div>
  17838. </file>
  17839. </example>
  17840. */
  17841. module.directive('uiGridInfiniteScroll', ['uiGridInfiniteScrollService',
  17842. function(uiGridInfiniteScrollService) {
  17843. return {
  17844. priority: -200,
  17845. scope: false,
  17846. require: '^uiGrid',
  17847. compile: function($scope, $elm, $attr) {
  17848. return {
  17849. pre: function($scope, $elm, $attr, uiGridCtrl) {
  17850. uiGridInfiniteScrollService.initializeGrid(uiGridCtrl.grid, $scope);
  17851. },
  17852. post: function($scope, $elm, $attr) {}
  17853. };
  17854. }
  17855. };
  17856. }
  17857. ]);
  17858. })();
  17859. (function() {
  17860. 'use strict';
  17861. /**
  17862. * @ngdoc overview
  17863. * @name ui.grid.moveColumns
  17864. * @description
  17865. *
  17866. * # ui.grid.moveColumns
  17867. *
  17868. * <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>
  17869. *
  17870. * This module provides column moving capability to ui.grid. It enables to change the position of columns.
  17871. * <div doc-module-components="ui.grid.moveColumns"></div>
  17872. */
  17873. var module = angular.module('ui.grid.moveColumns', ['ui.grid']);
  17874. /**
  17875. * @ngdoc service
  17876. * @name ui.grid.moveColumns.service:uiGridMoveColumnService
  17877. * @description Service for column moving feature.
  17878. */
  17879. module.service('uiGridMoveColumnService', ['$q', '$timeout', '$log', 'ScrollEvent', 'uiGridConstants', 'gridUtil', function($q, $timeout, $log, ScrollEvent, uiGridConstants, gridUtil) {
  17880. var service = {
  17881. initializeGrid: function(grid) {
  17882. var self = this;
  17883. this.registerPublicApi(grid);
  17884. this.defaultGridOptions(grid.options);
  17885. grid.moveColumns = { orderCache: [] }; // Used to cache the order before columns are rebuilt
  17886. grid.registerColumnBuilder(self.movableColumnBuilder);
  17887. grid.registerDataChangeCallback(self.verifyColumnOrder, [uiGridConstants.dataChange.COLUMN]);
  17888. },
  17889. registerPublicApi: function(grid) {
  17890. var self = this;
  17891. /**
  17892. * @ngdoc object
  17893. * @name ui.grid.moveColumns.api:PublicApi
  17894. * @description Public Api for column moving feature.
  17895. */
  17896. var publicApi = {
  17897. events: {
  17898. /**
  17899. * @ngdoc event
  17900. * @name columnPositionChanged
  17901. * @eventOf ui.grid.moveColumns.api:PublicApi
  17902. * @description raised when column is moved
  17903. * <pre>
  17904. * gridApi.colMovable.on.columnPositionChanged(scope,function(colDef, originalPosition, newPosition){})
  17905. * </pre>
  17906. * @param {object} colDef the column that was moved
  17907. * @param {integer} originalPosition of the column
  17908. * @param {integer} finalPosition of the column
  17909. */
  17910. colMovable: {
  17911. columnPositionChanged: function(colDef, originalPosition, newPosition) {}
  17912. }
  17913. },
  17914. methods: {
  17915. /**
  17916. * @ngdoc method
  17917. * @name moveColumn
  17918. * @methodOf ui.grid.moveColumns.api:PublicApi
  17919. * @description Method can be used to change column position.
  17920. * <pre>
  17921. * gridApi.colMovable.moveColumn(oldPosition, newPosition)
  17922. * </pre>
  17923. * @param {integer} originalPosition of the column
  17924. * @param {integer} finalPosition of the column
  17925. */
  17926. colMovable: {
  17927. moveColumn: function(originalPosition, finalPosition) {
  17928. var columns = grid.columns;
  17929. if (!angular.isNumber(originalPosition) || !angular.isNumber(finalPosition)) {
  17930. gridUtil.logError('MoveColumn: Please provide valid values for originalPosition and finalPosition');
  17931. return;
  17932. }
  17933. var nonMovableColumns = 0;
  17934. for (var i = 0; i < columns.length; i++) {
  17935. if ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true) {
  17936. nonMovableColumns++;
  17937. }
  17938. }
  17939. if (originalPosition >= (columns.length - nonMovableColumns) || finalPosition >= (columns.length - nonMovableColumns)) {
  17940. gridUtil.logError('MoveColumn: Invalid values for originalPosition, finalPosition');
  17941. return;
  17942. }
  17943. var findPositionForRenderIndex = function(index) {
  17944. var position = index;
  17945. for (var i = 0; i <= position; i++) {
  17946. if (angular.isDefined(columns[i]) && ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true)) {
  17947. position++;
  17948. }
  17949. }
  17950. return position;
  17951. };
  17952. self.redrawColumnAtPosition(grid, findPositionForRenderIndex(originalPosition), findPositionForRenderIndex(finalPosition));
  17953. }
  17954. }
  17955. }
  17956. };
  17957. grid.api.registerEventsFromObject(publicApi.events);
  17958. grid.api.registerMethodsFromObject(publicApi.methods);
  17959. },
  17960. defaultGridOptions: function(gridOptions) {
  17961. /**
  17962. * @ngdoc object
  17963. * @name ui.grid.moveColumns.api:GridOptions
  17964. *
  17965. * @description Options for configuring the move column feature, these are available to be
  17966. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  17967. */
  17968. /**
  17969. * @ngdoc object
  17970. * @name enableColumnMoving
  17971. * @propertyOf ui.grid.moveColumns.api:GridOptions
  17972. * @description If defined, sets the default value for the colMovable flag on each individual colDefs
  17973. * if their individual enableColumnMoving configuration is not defined. Defaults to true.
  17974. */
  17975. gridOptions.enableColumnMoving = gridOptions.enableColumnMoving !== false;
  17976. },
  17977. movableColumnBuilder: function(colDef, col, gridOptions) {
  17978. var promises = [];
  17979. /**
  17980. * @ngdoc object
  17981. * @name ui.grid.moveColumns.api:ColumnDef
  17982. *
  17983. * @description Column Definition for move column feature, these are available to be
  17984. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  17985. */
  17986. /**
  17987. * @ngdoc object
  17988. * @name enableColumnMoving
  17989. * @propertyOf ui.grid.moveColumns.api:ColumnDef
  17990. * @description Enable column moving for the column.
  17991. */
  17992. colDef.enableColumnMoving = colDef.enableColumnMoving === undefined ? gridOptions.enableColumnMoving :
  17993. colDef.enableColumnMoving;
  17994. return $q.all(promises);
  17995. },
  17996. /**
  17997. * @ngdoc method
  17998. * @name updateColumnCache
  17999. * @methodOf ui.grid.moveColumns
  18000. * @description Cache the current order of columns, so we can restore them after new columnDefs are defined
  18001. */
  18002. updateColumnCache: function(grid) {
  18003. grid.moveColumns.orderCache = grid.getOnlyDataColumns();
  18004. },
  18005. /**
  18006. * @ngdoc method
  18007. * @name verifyColumnOrder
  18008. * @methodOf ui.grid.moveColumns
  18009. * @description dataChangeCallback which uses the cached column order to restore the column order
  18010. * when it is reset by altering the columnDefs array.
  18011. */
  18012. verifyColumnOrder: function(grid) {
  18013. var headerRowOffset = grid.rowHeaderColumns.length;
  18014. var newIndex;
  18015. angular.forEach(grid.moveColumns.orderCache, function(cacheCol, cacheIndex) {
  18016. newIndex = grid.columns.indexOf(cacheCol);
  18017. if (newIndex !== -1 && newIndex - headerRowOffset !== cacheIndex) {
  18018. var column = grid.columns.splice(newIndex, 1)[0];
  18019. grid.columns.splice(cacheIndex + headerRowOffset, 0, column);
  18020. }
  18021. });
  18022. },
  18023. redrawColumnAtPosition: function(grid, originalPosition, newPosition) {
  18024. var columns = grid.columns;
  18025. var originalColumn = columns[originalPosition];
  18026. if (originalColumn.colDef.enableColumnMoving) {
  18027. if (originalPosition > newPosition) {
  18028. for (var i1 = originalPosition; i1 > newPosition; i1--) {
  18029. columns[i1] = columns[i1 - 1];
  18030. }
  18031. } else if (newPosition > originalPosition) {
  18032. for (var i2 = originalPosition; i2 < newPosition; i2++) {
  18033. columns[i2] = columns[i2 + 1];
  18034. }
  18035. }
  18036. columns[newPosition] = originalColumn;
  18037. service.updateColumnCache(grid);
  18038. grid.queueGridRefresh();
  18039. $timeout(function() {
  18040. grid.api.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
  18041. grid.api.colMovable.raise.columnPositionChanged(originalColumn.colDef, originalPosition, newPosition);
  18042. });
  18043. }
  18044. }
  18045. };
  18046. return service;
  18047. }]);
  18048. /**
  18049. * @ngdoc directive
  18050. * @name ui.grid.moveColumns.directive:uiGridMoveColumns
  18051. * @element div
  18052. * @restrict A
  18053. * @description Adds column moving features to the ui-grid directive.
  18054. * @example
  18055. <example module="app">
  18056. <file name="app.js">
  18057. var app = angular.module('app', ['ui.grid', 'ui.grid.moveColumns']);
  18058. app.controller('MainCtrl', ['$scope', function ($scope) {
  18059. $scope.data = [
  18060. { name: 'Bob', title: 'CEO', age: 45 },
  18061. { name: 'Frank', title: 'Lowly Developer', age: 25 },
  18062. { name: 'Jenny', title: 'Highly Developer', age: 35 }
  18063. ];
  18064. $scope.columnDefs = [
  18065. {name: 'name'},
  18066. {name: 'title'},
  18067. {name: 'age'}
  18068. ];
  18069. }]);
  18070. </file>
  18071. <file name="main.css">
  18072. .grid {
  18073. width: 100%;
  18074. height: 150px;
  18075. }
  18076. </file>
  18077. <file name="index.html">
  18078. <div ng-controller="MainCtrl">
  18079. <div class="grid" ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-move-columns></div>
  18080. </div>
  18081. </file>
  18082. </example>
  18083. */
  18084. module.directive('uiGridMoveColumns', ['uiGridMoveColumnService', function(uiGridMoveColumnService) {
  18085. return {
  18086. replace: true,
  18087. priority: 0,
  18088. require: '^uiGrid',
  18089. scope: false,
  18090. compile: function() {
  18091. return {
  18092. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  18093. uiGridMoveColumnService.initializeGrid(uiGridCtrl.grid);
  18094. },
  18095. post: function($scope, $elm, $attrs, uiGridCtrl) {}
  18096. };
  18097. }
  18098. };
  18099. }]);
  18100. /**
  18101. * @ngdoc directive
  18102. * @name ui.grid.moveColumns.directive:uiGridHeaderCell
  18103. * @element div
  18104. * @restrict A
  18105. *
  18106. * @description Stacks on top of ui.grid.uiGridHeaderCell to provide capability to be able to move it to reposition column.
  18107. *
  18108. * On receiving mouseDown event headerCell is cloned, now as the mouse moves the cloned header cell also moved in the grid.
  18109. * In case the moving cloned header cell reaches the left or right extreme of grid, grid scrolling is triggered (if horizontal scroll exists).
  18110. * On mouseUp event column is repositioned at position where mouse is released and cloned header cell is removed.
  18111. *
  18112. * Events that invoke cloning of header cell:
  18113. * - mousedown
  18114. *
  18115. * Events that invoke movement of cloned header cell:
  18116. * - mousemove
  18117. *
  18118. * Events that invoke repositioning of column:
  18119. * - mouseup
  18120. */
  18121. module.directive('uiGridHeaderCell', ['$q', 'gridUtil', 'uiGridMoveColumnService', '$document', '$log', 'uiGridConstants', 'ScrollEvent',
  18122. function($q, gridUtil, uiGridMoveColumnService, $document, $log, uiGridConstants, ScrollEvent) {
  18123. return {
  18124. priority: -10,
  18125. require: '^uiGrid',
  18126. compile: function() {
  18127. return {
  18128. post: function($scope, $elm, $attrs, uiGridCtrl) {
  18129. if ($scope.col.colDef.enableColumnMoving) {
  18130. /*
  18131. * Our general approach to column move is that we listen to a touchstart or mousedown
  18132. * event over the column header. When we hear one, then we wait for a move of the same type
  18133. * - if we are a touchstart then we listen for a touchmove, if we are a mousedown we listen for
  18134. * a mousemove (i.e. a drag) before we decide that there's a move underway. If there's never a move,
  18135. * and we instead get a mouseup or a touchend, then we just drop out again and do nothing.
  18136. *
  18137. */
  18138. var $contentsElm = angular.element($elm[0].querySelectorAll('.ui-grid-cell-contents'));
  18139. var gridLeft;
  18140. var previousMouseX;
  18141. var totalMouseMovement;
  18142. var rightMoveLimit;
  18143. var elmCloned = false;
  18144. var movingElm;
  18145. var reducedWidth;
  18146. var moveOccurred = false;
  18147. var downFn = function(event) {
  18148. //Setting some variables required for calculations.
  18149. gridLeft = $scope.grid.element[0].getBoundingClientRect().left;
  18150. if ($scope.grid.hasLeftContainer()) {
  18151. gridLeft += $scope.grid.renderContainers.left.header[0].getBoundingClientRect().width;
  18152. }
  18153. previousMouseX = event.pageX;
  18154. totalMouseMovement = 0;
  18155. rightMoveLimit = gridLeft + $scope.grid.getViewportWidth();
  18156. if (event.type === 'mousedown') {
  18157. $document.on('mousemove', moveFn);
  18158. $document.on('mouseup', upFn);
  18159. } else if (event.type === 'touchstart') {
  18160. $document.on('touchmove', moveFn);
  18161. $document.on('touchend', upFn);
  18162. }
  18163. };
  18164. var moveFn = function(event) {
  18165. var changeValue = event.pageX - previousMouseX;
  18166. if (changeValue === 0) { return; }
  18167. //Disable text selection in Chrome during column move
  18168. document.onselectstart = function() { return false; };
  18169. moveOccurred = true;
  18170. if (!elmCloned) {
  18171. cloneElement();
  18172. } else if (elmCloned) {
  18173. moveElement(changeValue);
  18174. previousMouseX = event.pageX;
  18175. }
  18176. };
  18177. var upFn = function(event) {
  18178. //Re-enable text selection after column move
  18179. document.onselectstart = null;
  18180. //Remove the cloned element on mouse up.
  18181. if (movingElm) {
  18182. movingElm.remove();
  18183. elmCloned = false;
  18184. }
  18185. offAllEvents();
  18186. onDownEvents();
  18187. if (!moveOccurred) {
  18188. return;
  18189. }
  18190. var columns = $scope.grid.columns;
  18191. var columnIndex = 0;
  18192. for (var i = 0; i < columns.length; i++) {
  18193. if (columns[i].colDef.name !== $scope.col.colDef.name) {
  18194. columnIndex++;
  18195. } else {
  18196. break;
  18197. }
  18198. }
  18199. //Case where column should be moved to a position on its left
  18200. if (totalMouseMovement < 0) {
  18201. var totalColumnsLeftWidth = 0;
  18202. for (var il = columnIndex - 1; il >= 0; il--) {
  18203. if (angular.isUndefined(columns[il].colDef.visible) || columns[il].colDef.visible === true) {
  18204. totalColumnsLeftWidth += columns[il].drawnWidth || columns[il].width || columns[il].colDef.width;
  18205. if (totalColumnsLeftWidth > Math.abs(totalMouseMovement)) {
  18206. uiGridMoveColumnService.redrawColumnAtPosition($scope.grid, columnIndex, il + 1);
  18207. break;
  18208. }
  18209. }
  18210. }
  18211. //Case where column should be moved to beginning of the grid.
  18212. if (totalColumnsLeftWidth < Math.abs(totalMouseMovement)) {
  18213. uiGridMoveColumnService.redrawColumnAtPosition($scope.grid, columnIndex, 0);
  18214. }
  18215. }
  18216. //Case where column should be moved to a position on its right
  18217. else if (totalMouseMovement > 0) {
  18218. var totalColumnsRightWidth = 0;
  18219. for (var ir = columnIndex + 1; ir < columns.length; ir++) {
  18220. if (angular.isUndefined(columns[ir].colDef.visible) || columns[ir].colDef.visible === true) {
  18221. totalColumnsRightWidth += columns[ir].drawnWidth || columns[ir].width || columns[ir].colDef.width;
  18222. if (totalColumnsRightWidth > totalMouseMovement) {
  18223. uiGridMoveColumnService.redrawColumnAtPosition($scope.grid, columnIndex, ir - 1);
  18224. break;
  18225. }
  18226. }
  18227. }
  18228. //Case where column should be moved to end of the grid.
  18229. if (totalColumnsRightWidth < totalMouseMovement) {
  18230. uiGridMoveColumnService.redrawColumnAtPosition($scope.grid, columnIndex, columns.length - 1);
  18231. }
  18232. }
  18233. };
  18234. var onDownEvents = function() {
  18235. $contentsElm.on('touchstart', downFn);
  18236. $contentsElm.on('mousedown', downFn);
  18237. };
  18238. var offAllEvents = function() {
  18239. $contentsElm.off('touchstart', downFn);
  18240. $contentsElm.off('mousedown', downFn);
  18241. $document.off('mousemove', moveFn);
  18242. $document.off('touchmove', moveFn);
  18243. $document.off('mouseup', upFn);
  18244. $document.off('touchend', upFn);
  18245. };
  18246. onDownEvents();
  18247. var cloneElement = function() {
  18248. elmCloned = true;
  18249. //Cloning header cell and appending to current header cell.
  18250. movingElm = $elm.clone();
  18251. $elm.parent().append(movingElm);
  18252. //Left of cloned element should be aligned to original header cell.
  18253. movingElm.addClass('movingColumn');
  18254. var movingElementStyles = {};
  18255. var elmLeft;
  18256. if (gridUtil.detectBrowser() === 'safari') {
  18257. //Correction for Safari getBoundingClientRect,
  18258. //which does not correctly compute when there is an horizontal scroll
  18259. elmLeft = $elm[0].offsetLeft + $elm[0].offsetWidth - $elm[0].getBoundingClientRect().width;
  18260. } else {
  18261. elmLeft = $elm[0].getBoundingClientRect().left;
  18262. }
  18263. movingElementStyles.left = (elmLeft - gridLeft) + 'px';
  18264. var gridRight = $scope.grid.element[0].getBoundingClientRect().right;
  18265. var elmRight = $elm[0].getBoundingClientRect().right;
  18266. if (elmRight > gridRight) {
  18267. reducedWidth = $scope.col.drawnWidth + (gridRight - elmRight);
  18268. movingElementStyles.width = reducedWidth + 'px';
  18269. }
  18270. movingElm.css(movingElementStyles);
  18271. };
  18272. var moveElement = function(changeValue) {
  18273. //Calculate total column width
  18274. var columns = $scope.grid.columns;
  18275. var totalColumnWidth = 0;
  18276. for (var i = 0; i < columns.length; i++) {
  18277. if (angular.isUndefined(columns[i].colDef.visible) || columns[i].colDef.visible === true) {
  18278. totalColumnWidth += columns[i].drawnWidth || columns[i].width || columns[i].colDef.width;
  18279. }
  18280. }
  18281. //Calculate new position of left of column
  18282. var currentElmLeft = movingElm[0].getBoundingClientRect().left - 1;
  18283. var currentElmRight = movingElm[0].getBoundingClientRect().right;
  18284. var newElementLeft;
  18285. newElementLeft = currentElmLeft - gridLeft + changeValue;
  18286. newElementLeft = newElementLeft < rightMoveLimit ? newElementLeft : rightMoveLimit;
  18287. //Update css of moving column to adjust to new left value or fire scroll in case column has reached edge of grid
  18288. if ((currentElmLeft >= gridLeft || changeValue > 0) && (currentElmRight <= rightMoveLimit || changeValue < 0)) {
  18289. movingElm.css({ visibility: 'visible', 'left': newElementLeft + 'px' });
  18290. } else if (totalColumnWidth > Math.ceil(uiGridCtrl.grid.gridWidth)) {
  18291. changeValue *= 8;
  18292. var scrollEvent = new ScrollEvent($scope.col.grid, null, null, 'uiGridHeaderCell.moveElement');
  18293. scrollEvent.x = { pixels: changeValue };
  18294. scrollEvent.grid.scrollContainers('', scrollEvent);
  18295. }
  18296. //Calculate total width of columns on the left of the moving column and the mouse movement
  18297. var totalColumnsLeftWidth = 0;
  18298. for (var il = 0; il < columns.length; il++) {
  18299. if (angular.isUndefined(columns[il].colDef.visible) || columns[il].colDef.visible === true) {
  18300. if (columns[il].colDef.name !== $scope.col.colDef.name) {
  18301. totalColumnsLeftWidth += columns[il].drawnWidth || columns[il].width || columns[il].colDef.width;
  18302. } else {
  18303. break;
  18304. }
  18305. }
  18306. }
  18307. if ($scope.newScrollLeft === undefined) {
  18308. totalMouseMovement += changeValue;
  18309. } else {
  18310. totalMouseMovement = $scope.newScrollLeft + newElementLeft - totalColumnsLeftWidth;
  18311. }
  18312. //Increase width of moving column, in case the rightmost column was moved and its width was
  18313. //decreased because of overflow
  18314. if (reducedWidth < $scope.col.drawnWidth) {
  18315. reducedWidth += Math.abs(changeValue);
  18316. movingElm.css({ 'width': reducedWidth + 'px' });
  18317. }
  18318. };
  18319. }
  18320. }
  18321. };
  18322. }
  18323. };
  18324. }
  18325. ]);
  18326. })();
  18327. (function() {
  18328. 'use strict';
  18329. /**
  18330. * @ngdoc overview
  18331. * @name ui.grid.pagination
  18332. *
  18333. * @description
  18334. *
  18335. * # ui.grid.pagination
  18336. *
  18337. * <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>
  18338. *
  18339. * This module provides pagination support to ui-grid
  18340. */
  18341. var module = angular.module('ui.grid.pagination', ['ng', 'ui.grid']);
  18342. /**
  18343. * @ngdoc service
  18344. * @name ui.grid.pagination.service:uiGridPaginationService
  18345. *
  18346. * @description Service for the pagination feature
  18347. */
  18348. module.service('uiGridPaginationService', ['gridUtil', '$rootScope',
  18349. function(gridUtil, $rootScope) {
  18350. var service = {
  18351. /**
  18352. * @ngdoc method
  18353. * @name initializeGrid
  18354. * @methodOf ui.grid.pagination.service:uiGridPaginationService
  18355. * @description Attaches the service to a certain grid
  18356. * @param {Grid} grid The grid we want to work with
  18357. */
  18358. initializeGrid: function(grid) {
  18359. service.defaultGridOptions(grid.options);
  18360. /**
  18361. * @ngdoc object
  18362. * @name ui.grid.pagination.api:PublicAPI
  18363. *
  18364. * @description Public API for the pagination feature
  18365. */
  18366. var publicApi = {
  18367. events: {
  18368. pagination: {
  18369. /**
  18370. * @ngdoc event
  18371. * @name paginationChanged
  18372. * @eventOf ui.grid.pagination.api:PublicAPI
  18373. * @description This event fires when the pageSize or currentPage changes
  18374. * @param {int} currentPage requested page number
  18375. * @param {int} pageSize requested page size
  18376. */
  18377. paginationChanged: function(currentPage, pageSize) {}
  18378. }
  18379. },
  18380. methods: {
  18381. pagination: {
  18382. /**
  18383. * @ngdoc method
  18384. * @name getPage
  18385. * @methodOf ui.grid.pagination.api:PublicAPI
  18386. * @description Returns the number of the current page
  18387. */
  18388. getPage: function() {
  18389. return grid.options.enablePagination ? grid.options.paginationCurrentPage : null;
  18390. },
  18391. /**
  18392. * @ngdoc method
  18393. * @name getTotalPages
  18394. * @methodOf ui.grid.pagination.api:PublicAPI
  18395. * @description Returns the total number of pages
  18396. */
  18397. getTotalPages: function() {
  18398. if (!grid.options.enablePagination) {
  18399. return null;
  18400. }
  18401. return (grid.options.totalItems === 0) ? 1 : Math.ceil(grid.options.totalItems / grid.options.paginationPageSize);
  18402. },
  18403. /**
  18404. * @ngdoc method
  18405. * @name nextPage
  18406. * @methodOf ui.grid.pagination.api:PublicAPI
  18407. * @description Moves to the next page, if possible
  18408. */
  18409. nextPage: function() {
  18410. if (!grid.options.enablePagination) {
  18411. return;
  18412. }
  18413. if (grid.options.totalItems > 0) {
  18414. grid.options.paginationCurrentPage = Math.min(
  18415. grid.options.paginationCurrentPage + 1,
  18416. publicApi.methods.pagination.getTotalPages()
  18417. );
  18418. } else {
  18419. grid.options.paginationCurrentPage++;
  18420. }
  18421. },
  18422. /**
  18423. * @ngdoc method
  18424. * @name previousPage
  18425. * @methodOf ui.grid.pagination.api:PublicAPI
  18426. * @description Moves to the previous page, if we're not on the first page
  18427. */
  18428. previousPage: function() {
  18429. if (!grid.options.enablePagination) {
  18430. return;
  18431. }
  18432. grid.options.paginationCurrentPage = Math.max(grid.options.paginationCurrentPage - 1, 1);
  18433. },
  18434. /**
  18435. * @ngdoc method
  18436. * @name seek
  18437. * @methodOf ui.grid.pagination.api:PublicAPI
  18438. * @description Moves to the requested page
  18439. * @param {int} page The number of the page that should be displayed
  18440. */
  18441. seek: function(page) {
  18442. if (!grid.options.enablePagination) {
  18443. return;
  18444. }
  18445. if (!angular.isNumber(page) || page < 1) {
  18446. throw 'Invalid page number: ' + page;
  18447. }
  18448. grid.options.paginationCurrentPage = Math.min(page, publicApi.methods.pagination.getTotalPages());
  18449. }
  18450. }
  18451. }
  18452. };
  18453. grid.api.registerEventsFromObject(publicApi.events);
  18454. grid.api.registerMethodsFromObject(publicApi.methods);
  18455. var processPagination = function(renderableRows) {
  18456. if (grid.options.useExternalPagination || !grid.options.enablePagination) {
  18457. return renderableRows;
  18458. }
  18459. //client side pagination
  18460. var pageSize = parseInt(grid.options.paginationPageSize, 10);
  18461. var currentPage = parseInt(grid.options.paginationCurrentPage, 10);
  18462. var visibleRows = renderableRows.filter(function(row) { return row.visible; });
  18463. grid.options.totalItems = visibleRows.length;
  18464. var firstRow = (currentPage - 1) * pageSize;
  18465. if (firstRow > visibleRows.length) {
  18466. currentPage = grid.options.paginationCurrentPage = 1;
  18467. firstRow = (currentPage - 1) * pageSize;
  18468. }
  18469. return visibleRows.slice(firstRow, firstRow + pageSize);
  18470. };
  18471. grid.registerRowsProcessor(processPagination, 900);
  18472. },
  18473. defaultGridOptions: function(gridOptions) {
  18474. /**
  18475. * @ngdoc object
  18476. * @name ui.grid.pagination.api:GridOptions
  18477. *
  18478. * @description GridOptions for the pagination feature, these are available to be
  18479. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  18480. */
  18481. /**
  18482. * @ngdoc property
  18483. * @name enablePagination
  18484. * @propertyOf ui.grid.pagination.api:GridOptions
  18485. * @description Enables pagination, defaults to true
  18486. */
  18487. gridOptions.enablePagination = gridOptions.enablePagination !== false;
  18488. /**
  18489. * @ngdoc property
  18490. * @name enablePaginationControls
  18491. * @propertyOf ui.grid.pagination.api:GridOptions
  18492. * @description Enables the paginator at the bottom of the grid. Turn this off, if you want to implement your
  18493. * own controls outside the grid.
  18494. */
  18495. gridOptions.enablePaginationControls = gridOptions.enablePaginationControls !== false;
  18496. /**
  18497. * @ngdoc property
  18498. * @name useExternalPagination
  18499. * @propertyOf ui.grid.pagination.api:GridOptions
  18500. * @description Disables client side pagination. When true, handle the paginationChanged event and set data
  18501. * and totalItems, defaults to `false`
  18502. */
  18503. gridOptions.useExternalPagination = gridOptions.useExternalPagination === true;
  18504. /**
  18505. * @ngdoc property
  18506. * @name totalItems
  18507. * @propertyOf ui.grid.pagination.api:GridOptions
  18508. * @description Total number of items, set automatically when client side pagination, needs set by user
  18509. * for server side pagination
  18510. */
  18511. if (gridUtil.isNullOrUndefined(gridOptions.totalItems)) {
  18512. gridOptions.totalItems = 0;
  18513. }
  18514. /**
  18515. * @ngdoc property
  18516. * @name paginationPageSizes
  18517. * @propertyOf ui.grid.pagination.api:GridOptions
  18518. * @description Array of page sizes, defaults to `[250, 500, 1000]`
  18519. */
  18520. if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSizes)) {
  18521. gridOptions.paginationPageSizes = [10, 20, 50, 100];
  18522. }
  18523. /**
  18524. * @ngdoc property
  18525. * @name paginationPageSize
  18526. * @propertyOf ui.grid.pagination.api:GridOptions
  18527. * @description Page size, defaults to the first item in paginationPageSizes, or 0 if paginationPageSizes is empty
  18528. */
  18529. if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSize)) {
  18530. if (gridOptions.paginationPageSizes.length > 0) {
  18531. gridOptions.paginationPageSize = gridOptions.paginationPageSizes[0];
  18532. } else {
  18533. gridOptions.paginationPageSize = 0;
  18534. }
  18535. }
  18536. /**
  18537. * @ngdoc property
  18538. * @name paginationCurrentPage
  18539. * @propertyOf ui.grid.pagination.api:GridOptions
  18540. * @description Current page number, defaults to 1
  18541. */
  18542. gridOptions.refresh = function() {
  18543. gridOptions.paginationCurrentPage = 1;
  18544. }
  18545. if (gridUtil.isNullOrUndefined(gridOptions.paginationCurrentPage)) {
  18546. 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') {
  18547. gridOptions.paginationCurrentPage = $rootScope.idx;
  18548. $rootScope.cmdbs = ''
  18549. }
  18550. // $rootScope.cmdbs=''
  18551. else { gridOptions.paginationCurrentPage = 1; }
  18552. }
  18553. /**
  18554. * @ngdoc property
  18555. * @name paginationTemplate
  18556. * @propertyOf ui.grid.pagination.api:GridOptions
  18557. * @description A custom template for the pager, defaults to `ui-grid/pagination`
  18558. */
  18559. if (gridUtil.isNullOrUndefined(gridOptions.paginationTemplate)) {
  18560. gridOptions.paginationTemplate = 'ui-grid/pagination';
  18561. }
  18562. },
  18563. /**
  18564. * @ngdoc method
  18565. * @methodOf ui.grid.pagination.service:uiGridPaginationService
  18566. * @name uiGridPaginationService
  18567. * @description Raises paginationChanged and calls refresh for client side pagination
  18568. * @param {Grid} grid the grid for which the pagination changed
  18569. * @param {int} currentPage requested page number
  18570. * @param {int} pageSize requested page size
  18571. */
  18572. onPaginationChanged: function(grid, currentPage, pageSize) {
  18573. grid.api.pagination.raise.paginationChanged(currentPage, pageSize);
  18574. // grid.selection.selectAll = false;
  18575. if (!grid.options.useExternalPagination) {
  18576. grid.queueGridRefresh(); //client side pagination
  18577. }
  18578. }
  18579. };
  18580. return service;
  18581. }
  18582. ]);
  18583. /**
  18584. * @ngdoc directive
  18585. * @name ui.grid.pagination.directive:uiGridPagination
  18586. * @element div
  18587. * @restrict A
  18588. *
  18589. * @description Adds pagination features to grid
  18590. * @example
  18591. <example module="app">
  18592. <file name="app.js">
  18593. var app = angular.module('app', ['ui.grid', 'ui.grid.pagination']);
  18594. app.controller('MainCtrl', ['$scope', function ($scope) {
  18595. $scope.data = [
  18596. { name: 'Alex', car: 'Toyota' },
  18597. { name: 'Sam', car: 'Lexus' },
  18598. { name: 'Joe', car: 'Dodge' },
  18599. { name: 'Bob', car: 'Buick' },
  18600. { name: 'Cindy', car: 'Ford' },
  18601. { name: 'Brian', car: 'Audi' },
  18602. { name: 'Malcom', car: 'Mercedes Benz' },
  18603. { name: 'Dave', car: 'Ford' },
  18604. { name: 'Stacey', car: 'Audi' },
  18605. { name: 'Amy', car: 'Acura' },
  18606. { name: 'Scott', car: 'Toyota' },
  18607. { name: 'Ryan', car: 'BMW' },
  18608. ];
  18609. $scope.gridOptions = {
  18610. data: 'data',
  18611. paginationPageSizes: [5, 10, 25],
  18612. paginationPageSize: 5,
  18613. columnDefs: [
  18614. {name: 'name'},
  18615. {name: 'car'}
  18616. ]
  18617. }
  18618. }]);
  18619. </file>
  18620. <file name="index.html">
  18621. <div ng-controller="MainCtrl">
  18622. <div ui-grid="gridOptions" ui-grid-pagination></div>
  18623. </div>
  18624. </file>
  18625. </example>
  18626. */
  18627. module.directive('uiGridPagination', ['gridUtil', 'uiGridPaginationService',
  18628. function(gridUtil, uiGridPaginationService) {
  18629. return {
  18630. priority: -200,
  18631. scope: false,
  18632. require: 'uiGrid',
  18633. link: {
  18634. pre: function($scope, $elm, $attr, uiGridCtrl) {
  18635. uiGridPaginationService.initializeGrid(uiGridCtrl.grid);
  18636. gridUtil.getTemplate(uiGridCtrl.grid.options.paginationTemplate)
  18637. .then(function(contents) {
  18638. var template = angular.element(contents);
  18639. $elm.append(template);
  18640. uiGridCtrl.innerCompile(template);
  18641. });
  18642. }
  18643. }
  18644. };
  18645. }
  18646. ]);
  18647. /**
  18648. * @ngdoc directive
  18649. * @name ui.grid.pagination.directive:uiGridPager
  18650. * @element div
  18651. *
  18652. * @description Panel for handling pagination
  18653. */
  18654. module.directive('uiGridPager', ['uiGridPaginationService', 'uiGridConstants', 'gridUtil', 'i18nService',
  18655. function(uiGridPaginationService, uiGridConstants, gridUtil, i18nService) {
  18656. return {
  18657. priority: -200,
  18658. scope: true,
  18659. require: '^uiGrid',
  18660. link: function($scope, $elm, $attr, uiGridCtrl) {
  18661. var defaultFocusElementSelector = '.ui-grid-pager-control-input';
  18662. $scope.aria = i18nService.getSafeText('pagination.aria'); //Returns an object with all of the aria labels
  18663. $scope.paginationApi = uiGridCtrl.grid.api.pagination;
  18664. $scope.sizesLabel = i18nService.getSafeText('pagination.sizes');
  18665. $scope.totalItemsLabel = i18nService.getSafeText('pagination.totalItems');
  18666. $scope.paginationOf = i18nService.getSafeText('pagination.of');
  18667. $scope.paginationThrough = i18nService.getSafeText('pagination.through');
  18668. var options = uiGridCtrl.grid.options;
  18669. uiGridCtrl.grid.renderContainers.body.registerViewportAdjuster(function(adjustment) {
  18670. adjustment.height = adjustment.height - gridUtil.elementHeight($elm);
  18671. return adjustment;
  18672. });
  18673. var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback(function(grid) {
  18674. if (!grid.options.useExternalPagination) {
  18675. grid.options.totalItems = grid.rows.length;
  18676. }
  18677. }, [uiGridConstants.dataChange.ROW]);
  18678. $scope.$on('$destroy', dataChangeDereg);
  18679. var setShowing = function() {
  18680. $scope.showingLow = ((options.paginationCurrentPage - 1) * options.paginationPageSize) + 1;
  18681. $scope.showingHigh = Math.min(options.paginationCurrentPage * options.paginationPageSize, options.totalItems);
  18682. };
  18683. var deregT = $scope.$watch('grid.options.totalItems + grid.options.paginationPageSize', setShowing);
  18684. var deregP = $scope.$watch('grid.options.paginationCurrentPage + grid.options.paginationPageSize', function(newValues, oldValues) {
  18685. if (newValues === oldValues || oldValues === undefined) {
  18686. return;
  18687. }
  18688. if (!angular.isNumber(options.paginationCurrentPage) || options.paginationCurrentPage < 1) {
  18689. options.paginationCurrentPage = 1;
  18690. return;
  18691. }
  18692. if (options.totalItems > 0 && options.paginationCurrentPage > $scope.paginationApi.getTotalPages()) {
  18693. options.paginationCurrentPage = $scope.paginationApi.getTotalPages();
  18694. return;
  18695. }
  18696. setShowing();
  18697. uiGridPaginationService.onPaginationChanged($scope.grid, options.paginationCurrentPage, options.paginationPageSize);
  18698. });
  18699. $scope.$on('$destroy', function() {
  18700. deregT();
  18701. deregP();
  18702. });
  18703. $scope.cantPageForward = function() {
  18704. if (options.totalItems > 0) {
  18705. return options.paginationCurrentPage >= $scope.paginationApi.getTotalPages();
  18706. } else {
  18707. return options.data.length < 1;
  18708. }
  18709. };
  18710. $scope.cantPageToLast = function() {
  18711. if (options.totalItems > 0) {
  18712. return $scope.cantPageForward();
  18713. } else {
  18714. return true;
  18715. }
  18716. };
  18717. $scope.cantPageBackward = function() {
  18718. return options.paginationCurrentPage <= 1;
  18719. };
  18720. var focusToInputIf = function(condition) {
  18721. if (condition) {
  18722. gridUtil.focus.bySelector($elm, defaultFocusElementSelector);
  18723. }
  18724. };
  18725. //Takes care of setting focus to the middle element when focus is lost
  18726. $scope.pageFirstPageClick = function() {
  18727. $scope.paginationApi.seek(1);
  18728. focusToInputIf($scope.cantPageBackward());
  18729. };
  18730. $scope.pagePreviousPageClick = function() {
  18731. $scope.paginationApi.previousPage();
  18732. focusToInputIf($scope.cantPageBackward());
  18733. };
  18734. $scope.pageNextPageClick = function() {
  18735. $scope.paginationApi.nextPage();
  18736. focusToInputIf($scope.cantPageForward());
  18737. };
  18738. $scope.pageLastPageClick = function() {
  18739. $scope.paginationApi.seek($scope.paginationApi.getTotalPages());
  18740. focusToInputIf($scope.cantPageToLast());
  18741. };
  18742. }
  18743. };
  18744. }
  18745. ]);
  18746. })();
  18747. (function() {
  18748. 'use strict';
  18749. /**
  18750. * @ngdoc overview
  18751. * @name ui.grid.pinning
  18752. * @description
  18753. *
  18754. * # ui.grid.pinning
  18755. *
  18756. * <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>
  18757. *
  18758. * This module provides column pinning to the end user via menu options in the column header
  18759. *
  18760. * <div doc-module-components="ui.grid.pinning"></div>
  18761. */
  18762. var module = angular.module('ui.grid.pinning', ['ui.grid']);
  18763. module.constant('uiGridPinningConstants', {
  18764. container: {
  18765. LEFT: 'left',
  18766. RIGHT: 'right',
  18767. NONE: ''
  18768. }
  18769. });
  18770. module.service('uiGridPinningService', ['gridUtil', 'GridRenderContainer', 'i18nService', 'uiGridPinningConstants', function(gridUtil, GridRenderContainer, i18nService, uiGridPinningConstants) {
  18771. var service = {
  18772. initializeGrid: function(grid) {
  18773. service.defaultGridOptions(grid.options);
  18774. // Register a column builder to add new menu items for pinning left and right
  18775. grid.registerColumnBuilder(service.pinningColumnBuilder);
  18776. /**
  18777. * @ngdoc object
  18778. * @name ui.grid.pinning.api:PublicApi
  18779. *
  18780. * @description Public Api for pinning feature
  18781. */
  18782. var publicApi = {
  18783. events: {
  18784. pinning: {
  18785. /**
  18786. * @ngdoc event
  18787. * @name columnPin
  18788. * @eventOf ui.grid.pinning.api:PublicApi
  18789. * @description raised when column pin state has changed
  18790. * <pre>
  18791. * gridApi.pinning.on.columnPinned(scope, function(colDef){})
  18792. * </pre>
  18793. * @param {object} colDef the column that was changed
  18794. * @param {string} container the render container the column is in ('left', 'right', '')
  18795. */
  18796. columnPinned: function(colDef, container) {}
  18797. }
  18798. },
  18799. methods: {
  18800. pinning: {
  18801. /**
  18802. * @ngdoc function
  18803. * @name pinColumn
  18804. * @methodOf ui.grid.pinning.api:PublicApi
  18805. * @description pin column left, right, or none
  18806. * <pre>
  18807. * gridApi.pinning.pinColumn(col, uiGridPinningConstants.container.LEFT)
  18808. * </pre>
  18809. * @param {gridColumn} col the column being pinned
  18810. * @param {string} container one of the recognised types
  18811. * from uiGridPinningConstants
  18812. */
  18813. pinColumn: function(col, container) {
  18814. service.pinColumn(grid, col, container);
  18815. }
  18816. }
  18817. }
  18818. };
  18819. grid.api.registerEventsFromObject(publicApi.events);
  18820. grid.api.registerMethodsFromObject(publicApi.methods);
  18821. },
  18822. defaultGridOptions: function(gridOptions) {
  18823. //default option to true unless it was explicitly set to false
  18824. /**
  18825. * @ngdoc object
  18826. * @name ui.grid.pinning.api:GridOptions
  18827. *
  18828. * @description GridOptions for pinning feature, these are available to be
  18829. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  18830. */
  18831. /**
  18832. * @ngdoc object
  18833. * @name enablePinning
  18834. * @propertyOf ui.grid.pinning.api:GridOptions
  18835. * @description Enable pinning for the entire grid.
  18836. * <br/>Defaults to true
  18837. */
  18838. gridOptions.enablePinning = gridOptions.enablePinning !== false;
  18839. },
  18840. pinningColumnBuilder: function(colDef, col, gridOptions) {
  18841. //default to true unless gridOptions or colDef is explicitly false
  18842. /**
  18843. * @ngdoc object
  18844. * @name ui.grid.pinning.api:ColumnDef
  18845. *
  18846. * @description ColumnDef for pinning feature, these are available to be
  18847. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  18848. */
  18849. /**
  18850. * @ngdoc object
  18851. * @name enablePinning
  18852. * @propertyOf ui.grid.pinning.api:ColumnDef
  18853. * @description Enable pinning for the individual column.
  18854. * <br/>Defaults to true
  18855. */
  18856. colDef.enablePinning = colDef.enablePinning === undefined ? gridOptions.enablePinning : colDef.enablePinning;
  18857. /**
  18858. * @ngdoc object
  18859. * @name pinnedLeft
  18860. * @propertyOf ui.grid.pinning.api:ColumnDef
  18861. * @description Column is pinned left when grid is rendered
  18862. * <br/>Defaults to false
  18863. */
  18864. /**
  18865. * @ngdoc object
  18866. * @name pinnedRight
  18867. * @propertyOf ui.grid.pinning.api:ColumnDef
  18868. * @description Column is pinned right when grid is rendered
  18869. * <br/>Defaults to false
  18870. */
  18871. if (colDef.pinnedLeft) {
  18872. col.renderContainer = 'left';
  18873. col.grid.createLeftContainer();
  18874. } else if (colDef.pinnedRight) {
  18875. col.renderContainer = 'right';
  18876. col.grid.createRightContainer();
  18877. }
  18878. if (!colDef.enablePinning) {
  18879. return;
  18880. }
  18881. var pinColumnLeftAction = {
  18882. name: 'ui.grid.pinning.pinLeft',
  18883. title: i18nService.get().pinning.pinLeft,
  18884. icon: 'ui-grid-icon-left-open',
  18885. shown: function() {
  18886. return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'left';
  18887. },
  18888. action: function() {
  18889. service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.LEFT);
  18890. }
  18891. };
  18892. var pinColumnRightAction = {
  18893. name: 'ui.grid.pinning.pinRight',
  18894. title: i18nService.get().pinning.pinRight,
  18895. icon: 'ui-grid-icon-right-open',
  18896. shown: function() {
  18897. return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'right';
  18898. },
  18899. action: function() {
  18900. service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.RIGHT);
  18901. }
  18902. };
  18903. var removePinAction = {
  18904. name: 'ui.grid.pinning.unpin',
  18905. title: i18nService.get().pinning.unpin,
  18906. icon: 'ui-grid-icon-cancel',
  18907. shown: function() {
  18908. return typeof(this.context.col.renderContainer) !== 'undefined' && this.context.col.renderContainer !== null && this.context.col.renderContainer !== 'body';
  18909. },
  18910. action: function() {
  18911. service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.UNPIN);
  18912. }
  18913. };
  18914. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinLeft')) {
  18915. col.menuItems.push(pinColumnLeftAction);
  18916. }
  18917. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinRight')) {
  18918. col.menuItems.push(pinColumnRightAction);
  18919. }
  18920. if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.unpin')) {
  18921. col.menuItems.push(removePinAction);
  18922. }
  18923. },
  18924. pinColumn: function(grid, col, container) {
  18925. if (container === uiGridPinningConstants.container.NONE) {
  18926. col.renderContainer = null;
  18927. } else {
  18928. col.renderContainer = container;
  18929. if (container === uiGridPinningConstants.container.LEFT) {
  18930. grid.createLeftContainer();
  18931. } else if (container === uiGridPinningConstants.container.RIGHT) {
  18932. grid.createRightContainer();
  18933. }
  18934. }
  18935. grid.refresh()
  18936. .then(function() {
  18937. grid.api.pinning.raise.columnPinned(col.colDef, container);
  18938. });
  18939. }
  18940. };
  18941. return service;
  18942. }]);
  18943. module.directive('uiGridPinning', ['gridUtil', 'uiGridPinningService',
  18944. function(gridUtil, uiGridPinningService) {
  18945. return {
  18946. require: 'uiGrid',
  18947. scope: false,
  18948. compile: function() {
  18949. return {
  18950. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  18951. uiGridPinningService.initializeGrid(uiGridCtrl.grid);
  18952. },
  18953. post: function($scope, $elm, $attrs, uiGridCtrl) {}
  18954. };
  18955. }
  18956. };
  18957. }
  18958. ]);
  18959. })();
  18960. (function() {
  18961. 'use strict';
  18962. /**
  18963. * @ngdoc overview
  18964. * @name ui.grid.resizeColumns
  18965. * @description
  18966. *
  18967. * # ui.grid.resizeColumns
  18968. *
  18969. * <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>
  18970. *
  18971. * This module allows columns to be resized.
  18972. */
  18973. var module = angular.module('ui.grid.resizeColumns', ['ui.grid']);
  18974. module.service('uiGridResizeColumnsService', ['gridUtil', '$q', '$timeout',
  18975. function(gridUtil, $q, $timeout) {
  18976. var service = {
  18977. defaultGridOptions: function(gridOptions) {
  18978. //default option to true unless it was explicitly set to false
  18979. /**
  18980. * @ngdoc object
  18981. * @name ui.grid.resizeColumns.api:GridOptions
  18982. *
  18983. * @description GridOptions for resizeColumns feature, these are available to be
  18984. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  18985. */
  18986. /**
  18987. * @ngdoc object
  18988. * @name enableColumnResizing
  18989. * @propertyOf ui.grid.resizeColumns.api:GridOptions
  18990. * @description Enable column resizing on the entire grid
  18991. * <br/>Defaults to true
  18992. */
  18993. gridOptions.enableColumnResizing = gridOptions.enableColumnResizing !== false;
  18994. //legacy support
  18995. //use old name if it is explicitly false
  18996. if (gridOptions.enableColumnResize === false) {
  18997. gridOptions.enableColumnResizing = false;
  18998. }
  18999. },
  19000. colResizerColumnBuilder: function(colDef, col, gridOptions) {
  19001. var promises = [];
  19002. /**
  19003. * @ngdoc object
  19004. * @name ui.grid.resizeColumns.api:ColumnDef
  19005. *
  19006. * @description ColumnDef for resizeColumns feature, these are available to be
  19007. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  19008. */
  19009. /**
  19010. * @ngdoc object
  19011. * @name enableColumnResizing
  19012. * @propertyOf ui.grid.resizeColumns.api:ColumnDef
  19013. * @description Enable column resizing on an individual column
  19014. * <br/>Defaults to GridOptions.enableColumnResizing
  19015. */
  19016. //default to true unless gridOptions or colDef is explicitly false
  19017. colDef.enableColumnResizing = colDef.enableColumnResizing === undefined ? gridOptions.enableColumnResizing : colDef.enableColumnResizing;
  19018. //legacy support of old option name
  19019. if (colDef.enableColumnResize === false) {
  19020. colDef.enableColumnResizing = false;
  19021. }
  19022. return $q.all(promises);
  19023. },
  19024. registerPublicApi: function(grid) {
  19025. /**
  19026. * @ngdoc object
  19027. * @name ui.grid.resizeColumns.api:PublicApi
  19028. * @description Public Api for column resize feature.
  19029. */
  19030. var publicApi = {
  19031. events: {
  19032. /**
  19033. * @ngdoc event
  19034. * @name columnSizeChanged
  19035. * @eventOf ui.grid.resizeColumns.api:PublicApi
  19036. * @description raised when column is resized
  19037. * <pre>
  19038. * gridApi.colResizable.on.columnSizeChanged(scope,function(colDef, deltaChange){})
  19039. * </pre>
  19040. * @param {object} colDef the column that was resized
  19041. * @param {integer} delta of the column size change
  19042. */
  19043. colResizable: {
  19044. columnSizeChanged: function(colDef, deltaChange) {}
  19045. }
  19046. }
  19047. };
  19048. grid.api.registerEventsFromObject(publicApi.events);
  19049. },
  19050. fireColumnSizeChanged: function(grid, colDef, deltaChange) {
  19051. $timeout(function() {
  19052. if (grid.api.colResizable) {
  19053. grid.api.colResizable.raise.columnSizeChanged(colDef, deltaChange);
  19054. } else {
  19055. 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.");
  19056. }
  19057. });
  19058. },
  19059. // get either this column, or the column next to this column, to resize,
  19060. // returns the column we're going to resize
  19061. findTargetCol: function(col, position, rtlMultiplier) {
  19062. var renderContainer = col.getRenderContainer();
  19063. if (position === 'left') {
  19064. // Get the column to the left of this one
  19065. var colIndex = renderContainer.visibleColumnCache.indexOf(col);
  19066. return renderContainer.visibleColumnCache[colIndex - 1 * rtlMultiplier];
  19067. } else {
  19068. return col;
  19069. }
  19070. }
  19071. };
  19072. return service;
  19073. }
  19074. ]);
  19075. /**
  19076. * @ngdoc directive
  19077. * @name ui.grid.resizeColumns.directive:uiGridResizeColumns
  19078. * @element div
  19079. * @restrict A
  19080. * @description
  19081. * 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
  19082. * option to false. This prevents resizing for the entire grid, regardless of individual columnDef options.
  19083. *
  19084. * @example
  19085. <doc:example module="app">
  19086. <doc:source>
  19087. <script>
  19088. var app = angular.module('app', ['ui.grid', 'ui.grid.resizeColumns']);
  19089. app.controller('MainCtrl', ['$scope', function ($scope) {
  19090. $scope.gridOpts = {
  19091. data: [
  19092. { "name": "Ethel Price", "gender": "female", "company": "Enersol" },
  19093. { "name": "Claudine Neal", "gender": "female", "company": "Sealoud" },
  19094. { "name": "Beryl Rice", "gender": "female", "company": "Velity" },
  19095. { "name": "Wilder Gonzales", "gender": "male", "company": "Geekko" }
  19096. ]
  19097. };
  19098. }]);
  19099. </script>
  19100. <div ng-controller="MainCtrl">
  19101. <div class="testGrid" ui-grid="gridOpts" ui-grid-resize-columns ></div>
  19102. </div>
  19103. </doc:source>
  19104. <doc:scenario>
  19105. </doc:scenario>
  19106. </doc:example>
  19107. */
  19108. module.directive('uiGridResizeColumns', ['gridUtil', 'uiGridResizeColumnsService', function(gridUtil, uiGridResizeColumnsService) {
  19109. return {
  19110. replace: true,
  19111. priority: 0,
  19112. require: '^uiGrid',
  19113. scope: false,
  19114. compile: function() {
  19115. return {
  19116. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  19117. uiGridResizeColumnsService.defaultGridOptions(uiGridCtrl.grid.options);
  19118. uiGridCtrl.grid.registerColumnBuilder(uiGridResizeColumnsService.colResizerColumnBuilder);
  19119. uiGridResizeColumnsService.registerPublicApi(uiGridCtrl.grid);
  19120. },
  19121. post: function($scope, $elm, $attrs, uiGridCtrl) {}
  19122. };
  19123. }
  19124. };
  19125. }]);
  19126. // Extend the uiGridHeaderCell directive
  19127. module.directive('uiGridHeaderCell', ['gridUtil', '$templateCache', '$compile', '$q', 'uiGridResizeColumnsService', 'uiGridConstants', '$timeout', function(gridUtil, $templateCache, $compile, $q, uiGridResizeColumnsService, uiGridConstants, $timeout) {
  19128. return {
  19129. // Run after the original uiGridHeaderCell
  19130. priority: -10,
  19131. require: '^uiGrid',
  19132. // scope: false,
  19133. compile: function() {
  19134. return {
  19135. post: function($scope, $elm, $attrs, uiGridCtrl) {
  19136. var grid = uiGridCtrl.grid;
  19137. if (grid.options.enableColumnResizing) {
  19138. var columnResizerElm = $templateCache.get('ui-grid/columnResizer');
  19139. var rtlMultiplier = 1;
  19140. //when in RTL mode reverse the direction using the rtlMultiplier and change the position to left
  19141. if (grid.isRTL()) {
  19142. $scope.position = 'left';
  19143. rtlMultiplier = -1;
  19144. }
  19145. var displayResizers = function() {
  19146. // remove any existing resizers.
  19147. var resizers = $elm[0].getElementsByClassName('ui-grid-column-resizer');
  19148. for (var i = 0; i < resizers.length; i++) {
  19149. angular.element(resizers[i]).remove();
  19150. }
  19151. // get the target column for the left resizer
  19152. var otherCol = uiGridResizeColumnsService.findTargetCol($scope.col, 'left', rtlMultiplier);
  19153. var renderContainer = $scope.col.getRenderContainer();
  19154. // Don't append the left resizer if this is the first column or the column to the left of this one has resizing disabled
  19155. if (otherCol && renderContainer.visibleColumnCache.indexOf($scope.col) !== 0 && otherCol.colDef.enableColumnResizing !== false) {
  19156. var resizerLeft = angular.element(columnResizerElm).clone();
  19157. resizerLeft.attr('position', 'left');
  19158. $elm.prepend(resizerLeft);
  19159. $compile(resizerLeft)($scope);
  19160. }
  19161. // Don't append the right resizer if this column has resizing disabled
  19162. if ($scope.col.colDef.enableColumnResizing !== false) {
  19163. var resizerRight = angular.element(columnResizerElm).clone();
  19164. resizerRight.attr('position', 'right');
  19165. $elm.append(resizerRight);
  19166. $compile(resizerRight)($scope);
  19167. }
  19168. };
  19169. displayResizers();
  19170. var waitDisplay = function() {
  19171. $timeout(displayResizers);
  19172. };
  19173. var dataChangeDereg = grid.registerDataChangeCallback(waitDisplay, [uiGridConstants.dataChange.COLUMN]);
  19174. $scope.$on('$destroy', dataChangeDereg);
  19175. }
  19176. }
  19177. };
  19178. }
  19179. };
  19180. }]);
  19181. /**
  19182. * @ngdoc directive
  19183. * @name ui.grid.resizeColumns.directive:uiGridColumnResizer
  19184. * @element div
  19185. * @restrict A
  19186. *
  19187. * @description
  19188. * Draggable handle that controls column resizing.
  19189. *
  19190. * @example
  19191. <doc:example module="app">
  19192. <doc:source>
  19193. <script>
  19194. var app = angular.module('app', ['ui.grid', 'ui.grid.resizeColumns']);
  19195. app.controller('MainCtrl', ['$scope', function ($scope) {
  19196. $scope.gridOpts = {
  19197. enableColumnResizing: true,
  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"></div>
  19209. </div>
  19210. </doc:source>
  19211. <doc:scenario>
  19212. // TODO: e2e specs?
  19213. // TODO: post-resize a horizontal scroll event should be fired
  19214. </doc:scenario>
  19215. </doc:example>
  19216. */
  19217. module.directive('uiGridColumnResizer', ['$document', 'gridUtil', 'uiGridConstants', 'uiGridResizeColumnsService', function($document, gridUtil, uiGridConstants, uiGridResizeColumnsService) {
  19218. var resizeOverlay = angular.element('<div class="ui-grid-resize-overlay"></div>');
  19219. var resizer = {
  19220. priority: 0,
  19221. scope: {
  19222. col: '=',
  19223. position: '@',
  19224. renderIndex: '='
  19225. },
  19226. require: '?^uiGrid',
  19227. link: function($scope, $elm, $attrs, uiGridCtrl) {
  19228. var startX = 0,
  19229. x = 0,
  19230. gridLeft = 0,
  19231. rtlMultiplier = 1;
  19232. //when in RTL mode reverse the direction using the rtlMultiplier and change the position to left
  19233. if (uiGridCtrl.grid.isRTL()) {
  19234. $scope.position = 'left';
  19235. rtlMultiplier = -1;
  19236. }
  19237. if ($scope.position === 'left') {
  19238. $elm.addClass('left');
  19239. } else if ($scope.position === 'right') {
  19240. $elm.addClass('right');
  19241. }
  19242. // Refresh the grid canvas
  19243. // takes an argument representing the diff along the X-axis that the resize had
  19244. function refreshCanvas(xDiff) {
  19245. // Then refresh the grid canvas, rebuilding the styles so that the scrollbar updates its size
  19246. uiGridCtrl.grid.refreshCanvas(true).then(function() {
  19247. uiGridCtrl.grid.queueGridRefresh();
  19248. });
  19249. }
  19250. // Check that the requested width isn't wider than the maxWidth, or narrower than the minWidth
  19251. // Returns the new recommended with, after constraints applied
  19252. function constrainWidth(col, width) {
  19253. var newWidth = width;
  19254. // If the new width would be less than the column's allowably minimum width, don't allow it
  19255. if (col.minWidth && newWidth < col.minWidth) {
  19256. newWidth = col.minWidth;
  19257. } else if (col.maxWidth && newWidth > col.maxWidth) {
  19258. newWidth = col.maxWidth;
  19259. }
  19260. return newWidth;
  19261. }
  19262. /*
  19263. * Our approach to event handling aims to deal with both touch devices and mouse devices
  19264. * We register down handlers on both touch and mouse. When a touchstart or mousedown event
  19265. * occurs, we register the corresponding touchmove/touchend, or mousemove/mouseend events.
  19266. *
  19267. * This way we can listen for both without worrying about the fact many touch devices also emulate
  19268. * mouse events - basically whichever one we hear first is what we'll go with.
  19269. */
  19270. function moveFunction(event, args) {
  19271. if (event.originalEvent) { event = event.originalEvent; }
  19272. event.preventDefault();
  19273. x = (event.targetTouches ? event.targetTouches[0] : event).clientX - gridLeft;
  19274. if (x < 0) { x = 0; } else if (x > uiGridCtrl.grid.gridWidth) { x = uiGridCtrl.grid.gridWidth; }
  19275. var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier);
  19276. // Don't resize if it's disabled on this column
  19277. if (col.colDef.enableColumnResizing === false) {
  19278. return;
  19279. }
  19280. if (!uiGridCtrl.grid.element.hasClass('column-resizing')) {
  19281. uiGridCtrl.grid.element.addClass('column-resizing');
  19282. }
  19283. // Get the diff along the X axis
  19284. var xDiff = x - startX;
  19285. // Get the width that this mouse would give the column
  19286. var newWidth = parseInt(col.drawnWidth + xDiff * rtlMultiplier, 10);
  19287. // check we're not outside the allowable bounds for this column
  19288. x = x + (constrainWidth(col, newWidth) - newWidth) * rtlMultiplier;
  19289. resizeOverlay.css({ left: x + 'px' });
  19290. uiGridCtrl.fireEvent(uiGridConstants.events.ITEM_DRAGGING);
  19291. }
  19292. function upFunction(event, args) {
  19293. if (event.originalEvent) { event = event.originalEvent; }
  19294. event.preventDefault();
  19295. uiGridCtrl.grid.element.removeClass('column-resizing');
  19296. resizeOverlay.remove();
  19297. // Resize the column
  19298. x = (event.changedTouches ? event.changedTouches[0] : event).clientX - gridLeft;
  19299. var xDiff = x - startX;
  19300. if (xDiff === 0) {
  19301. // no movement, so just reset event handlers, including turning back on both
  19302. // down events - we turned one off when this event started
  19303. offAllEvents();
  19304. onDownEvents();
  19305. return;
  19306. }
  19307. var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier);
  19308. // Don't resize if it's disabled on this column
  19309. if (col.colDef.enableColumnResizing === false) {
  19310. return;
  19311. }
  19312. // Get the new width
  19313. var newWidth = parseInt(col.drawnWidth + xDiff * rtlMultiplier, 10);
  19314. // check we're not outside the allowable bounds for this column
  19315. col.width = constrainWidth(col, newWidth);
  19316. col.hasCustomWidth = true;
  19317. refreshCanvas(xDiff);
  19318. uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff);
  19319. // stop listening of up and move events - wait for next down
  19320. // reset the down events - we will have turned one off when this event started
  19321. offAllEvents();
  19322. onDownEvents();
  19323. }
  19324. var downFunction = function(event, args) {
  19325. if (event.originalEvent) { event = event.originalEvent; }
  19326. event.stopPropagation();
  19327. // Get the left offset of the grid
  19328. // gridLeft = uiGridCtrl.grid.element[0].offsetLeft;
  19329. gridLeft = uiGridCtrl.grid.element[0].getBoundingClientRect().left;
  19330. // Get the starting X position, which is the X coordinate of the click minus the grid's offset
  19331. startX = (event.targetTouches ? event.targetTouches[0] : event).clientX - gridLeft;
  19332. // Append the resizer overlay
  19333. uiGridCtrl.grid.element.append(resizeOverlay);
  19334. // Place the resizer overlay at the start position
  19335. resizeOverlay.css({ left: startX });
  19336. // Add handlers for move and up events - if we were mousedown then we listen for mousemove and mouseup, if
  19337. // we were touchdown then we listen for touchmove and touchup. Also remove the handler for the equivalent
  19338. // down event - so if we're touchdown, then remove the mousedown handler until this event is over, if we're
  19339. // mousedown then remove the touchdown handler until this event is over, this avoids processing duplicate events
  19340. if (event.type === 'touchstart') {
  19341. $document.on('touchend', upFunction);
  19342. $document.on('touchmove', moveFunction);
  19343. $elm.off('mousedown', downFunction);
  19344. } else {
  19345. $document.on('mouseup', upFunction);
  19346. $document.on('mousemove', moveFunction);
  19347. $elm.off('touchstart', downFunction);
  19348. }
  19349. };
  19350. var onDownEvents = function() {
  19351. $elm.on('mousedown', downFunction);
  19352. $elm.on('touchstart', downFunction);
  19353. };
  19354. var offAllEvents = function() {
  19355. $document.off('mouseup', upFunction);
  19356. $document.off('touchend', upFunction);
  19357. $document.off('mousemove', moveFunction);
  19358. $document.off('touchmove', moveFunction);
  19359. $elm.off('mousedown', downFunction);
  19360. $elm.off('touchstart', downFunction);
  19361. };
  19362. onDownEvents();
  19363. // On doubleclick, resize to fit all rendered cells
  19364. var dblClickFn = function(event, args) {
  19365. event.stopPropagation();
  19366. var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier);
  19367. // Don't resize if it's disabled on this column
  19368. if (col.colDef.enableColumnResizing === false) {
  19369. return;
  19370. }
  19371. // Go through the rendered rows and find out the max size for the data in this column
  19372. var maxWidth = 0;
  19373. var xDiff = 0;
  19374. // Get the parent render container element
  19375. var renderContainerElm = gridUtil.closestElm($elm, '.ui-grid-render-container');
  19376. // 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
  19377. var cells = renderContainerElm.querySelectorAll('.' + uiGridConstants.COL_CLASS_PREFIX + col.uid + ' .ui-grid-cell-contents');
  19378. Array.prototype.forEach.call(cells, function(cell) {
  19379. // Get the cell width
  19380. // gridUtil.logDebug('width', gridUtil.elementWidth(cell));
  19381. // Account for the menu button if it exists
  19382. var menuButton;
  19383. if (angular.element(cell).parent().hasClass('ui-grid-header-cell')) {
  19384. menuButton = angular.element(cell).parent()[0].querySelectorAll('.ui-grid-column-menu-button');
  19385. }
  19386. gridUtil.fakeElement(cell, {}, function(newElm) {
  19387. // Make the element float since it's a div and can expand to fill its container
  19388. var e = angular.element(newElm);
  19389. e.attr('style', 'float: left');
  19390. var width = gridUtil.elementWidth(e);
  19391. if (menuButton) {
  19392. var menuButtonWidth = gridUtil.elementWidth(menuButton);
  19393. width = width + menuButtonWidth;
  19394. }
  19395. if (width > maxWidth) {
  19396. maxWidth = width;
  19397. xDiff = maxWidth - width;
  19398. }
  19399. });
  19400. });
  19401. // check we're not outside the allowable bounds for this column
  19402. col.width = constrainWidth(col, maxWidth);
  19403. col.hasCustomWidth = true;
  19404. refreshCanvas(xDiff);
  19405. uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff);
  19406. };
  19407. $elm.on('dblclick', dblClickFn);
  19408. $elm.on('$destroy', function() {
  19409. $elm.off('dblclick', dblClickFn);
  19410. offAllEvents();
  19411. });
  19412. }
  19413. };
  19414. return resizer;
  19415. }]);
  19416. })();
  19417. (function() {
  19418. 'use strict';
  19419. /**
  19420. * @ngdoc overview
  19421. * @name ui.grid.rowEdit
  19422. * @description
  19423. *
  19424. * # ui.grid.rowEdit
  19425. *
  19426. * <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>
  19427. *
  19428. * This module extends the edit feature to provide tracking and saving of rows
  19429. * of data. The tutorial provides more information on how this feature is best
  19430. * used {@link tutorial/205_row_editable here}.
  19431. * <br/>
  19432. * This feature depends on usage of the ui-grid-edit feature, and also benefits
  19433. * from use of ui-grid-cellNav to provide the full spreadsheet-like editing
  19434. * experience
  19435. *
  19436. */
  19437. var module = angular.module('ui.grid.rowEdit', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav']);
  19438. /**
  19439. * @ngdoc object
  19440. * @name ui.grid.rowEdit.constant:uiGridRowEditConstants
  19441. *
  19442. * @description constants available in row edit module
  19443. */
  19444. module.constant('uiGridRowEditConstants', {});
  19445. /**
  19446. * @ngdoc service
  19447. * @name ui.grid.rowEdit.service:uiGridRowEditService
  19448. *
  19449. * @description Services for row editing features
  19450. */
  19451. module.service('uiGridRowEditService', ['$interval', '$q', 'uiGridConstants', 'uiGridRowEditConstants', 'gridUtil',
  19452. function($interval, $q, uiGridConstants, uiGridRowEditConstants, gridUtil) {
  19453. var service = {
  19454. initializeGrid: function(scope, grid) {
  19455. /**
  19456. * @ngdoc object
  19457. * @name ui.grid.rowEdit.api:PublicApi
  19458. *
  19459. * @description Public Api for rowEdit feature
  19460. */
  19461. grid.rowEdit = {};
  19462. var publicApi = {
  19463. events: {
  19464. rowEdit: {
  19465. /**
  19466. * @ngdoc event
  19467. * @eventOf ui.grid.rowEdit.api:PublicApi
  19468. * @name saveRow
  19469. * @description raised when a row is ready for saving. Once your
  19470. * row has saved you may need to use angular.extend to update the
  19471. * data entity with any changed data from your save (for example,
  19472. * lock version information if you're using optimistic locking,
  19473. * or last update time/user information).
  19474. *
  19475. * Your method should call setSavePromise somewhere in the body before
  19476. * returning control. The feature will then wait, with the gridRow greyed out
  19477. * whilst this promise is being resolved.
  19478. *
  19479. * <pre>
  19480. * gridApi.rowEdit.on.saveRow(scope,function(rowEntity){})
  19481. * </pre>
  19482. * and somewhere within the event handler:
  19483. * <pre>
  19484. * gridApi.rowEdit.setSavePromise( rowEntity, savePromise)
  19485. * </pre>
  19486. * @param {object} rowEntity the options.data element that was edited
  19487. * @returns {promise} Your saveRow method should return a promise, the
  19488. * promise should either be resolved (implying successful save), or
  19489. * rejected (implying an error).
  19490. */
  19491. saveRow: function(rowEntity) {}
  19492. }
  19493. },
  19494. methods: {
  19495. rowEdit: {
  19496. /**
  19497. * @ngdoc method
  19498. * @methodOf ui.grid.rowEdit.api:PublicApi
  19499. * @name setSavePromise
  19500. * @description Sets the promise associated with the row save, mandatory that
  19501. * the saveRow event handler calls this method somewhere before returning.
  19502. * <pre>
  19503. * gridApi.rowEdit.setSavePromise(rowEntity, savePromise)
  19504. * </pre>
  19505. * @param {object} rowEntity a data row from the grid for which a save has
  19506. * been initiated
  19507. * @param {promise} savePromise the promise that will be resolved when the
  19508. * save is successful, or rejected if the save fails
  19509. *
  19510. */
  19511. setSavePromise: function(rowEntity, savePromise) {
  19512. service.setSavePromise(grid, rowEntity, savePromise);
  19513. },
  19514. /**
  19515. * @ngdoc method
  19516. * @methodOf ui.grid.rowEdit.api:PublicApi
  19517. * @name getDirtyRows
  19518. * @description Returns all currently dirty rows
  19519. * <pre>
  19520. * gridApi.rowEdit.getDirtyRows(grid)
  19521. * </pre>
  19522. * @returns {array} An array of gridRows that are currently dirty
  19523. *
  19524. */
  19525. getDirtyRows: function() {
  19526. return grid.rowEdit.dirtyRows ? grid.rowEdit.dirtyRows : [];
  19527. },
  19528. /**
  19529. * @ngdoc method
  19530. * @methodOf ui.grid.rowEdit.api:PublicApi
  19531. * @name getErrorRows
  19532. * @description Returns all currently errored rows
  19533. * <pre>
  19534. * gridApi.rowEdit.getErrorRows(grid)
  19535. * </pre>
  19536. * @returns {array} An array of gridRows that are currently in error
  19537. *
  19538. */
  19539. getErrorRows: function() {
  19540. return grid.rowEdit.errorRows ? grid.rowEdit.errorRows : [];
  19541. },
  19542. /**
  19543. * @ngdoc method
  19544. * @methodOf ui.grid.rowEdit.api:PublicApi
  19545. * @name flushDirtyRows
  19546. * @description Triggers a save event for all currently dirty rows, could
  19547. * be used where user presses a save button or navigates away from the page
  19548. * <pre>
  19549. * gridApi.rowEdit.flushDirtyRows(grid)
  19550. * </pre>
  19551. * @returns {promise} a promise that represents the aggregate of all
  19552. * of the individual save promises - i.e. it will be resolved when all
  19553. * the individual save promises have been resolved.
  19554. *
  19555. */
  19556. flushDirtyRows: function() {
  19557. return service.flushDirtyRows(grid);
  19558. },
  19559. /**
  19560. * @ngdoc method
  19561. * @methodOf ui.grid.rowEdit.api:PublicApi
  19562. * @name setRowsDirty
  19563. * @description Sets each of the rows passed in dataRows
  19564. * to be dirty. note that if you have only just inserted the
  19565. * rows into your data you will need to wait for a $digest cycle
  19566. * before the gridRows are present - so often you would wrap this
  19567. * call in a $interval or $timeout
  19568. * <pre>
  19569. * $interval( function() {
  19570. * gridApi.rowEdit.setRowsDirty(myDataRows);
  19571. * }, 0, 1);
  19572. * </pre>
  19573. * @param {array} dataRows the data entities for which the gridRows
  19574. * should be set dirty.
  19575. *
  19576. */
  19577. setRowsDirty: function(dataRows) {
  19578. service.setRowsDirty(grid, dataRows);
  19579. },
  19580. /**
  19581. * @ngdoc method
  19582. * @methodOf ui.grid.rowEdit.api:PublicApi
  19583. * @name setRowsClean
  19584. * @description Sets each of the rows passed in dataRows
  19585. * to be clean, removing them from the dirty cache and the error cache,
  19586. * and clearing the error flag and the dirty flag
  19587. * <pre>
  19588. * var gridRows = $scope.gridApi.rowEdit.getDirtyRows();
  19589. * var dataRows = gridRows.map( function( gridRow ) { return gridRow.entity; });
  19590. * $scope.gridApi.rowEdit.setRowsClean( dataRows );
  19591. * </pre>
  19592. * @param {array} dataRows the data entities for which the gridRows
  19593. * should be set clean.
  19594. *
  19595. */
  19596. setRowsClean: function(dataRows) {
  19597. service.setRowsClean(grid, dataRows);
  19598. }
  19599. }
  19600. }
  19601. };
  19602. grid.api.registerEventsFromObject(publicApi.events);
  19603. grid.api.registerMethodsFromObject(publicApi.methods);
  19604. grid.api.core.on.renderingComplete(scope, function(gridApi) {
  19605. grid.api.edit.on.afterCellEdit(scope, service.endEditCell);
  19606. grid.api.edit.on.beginCellEdit(scope, service.beginEditCell);
  19607. grid.api.edit.on.cancelCellEdit(scope, service.cancelEditCell);
  19608. if (grid.api.cellNav) {
  19609. grid.api.cellNav.on.navigate(scope, service.navigate);
  19610. }
  19611. });
  19612. },
  19613. defaultGridOptions: function(gridOptions) {
  19614. /**
  19615. * @ngdoc object
  19616. * @name ui.grid.rowEdit.api:GridOptions
  19617. *
  19618. * @description Options for configuring the rowEdit feature, these are available to be
  19619. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  19620. */
  19621. },
  19622. /**
  19623. * @ngdoc method
  19624. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19625. * @name saveRow
  19626. * @description Returns a function that saves the specified row from the grid,
  19627. * and returns a promise
  19628. * @param {object} grid the grid for which dirty rows should be flushed
  19629. * @param {GridRow} gridRow the row that should be saved
  19630. * @returns {function} the saveRow function returns a function. That function
  19631. * in turn, when called, returns a promise relating to the save callback
  19632. */
  19633. saveRow: function(grid, gridRow) {
  19634. var self = this;
  19635. return function() {
  19636. gridRow.isSaving = true;
  19637. if (gridRow.rowEditSavePromise) {
  19638. // don't save the row again if it's already saving - that causes stale object exceptions
  19639. return gridRow.rowEditSavePromise;
  19640. }
  19641. var promise = grid.api.rowEdit.raise.saveRow(gridRow.entity);
  19642. if (gridRow.rowEditSavePromise) {
  19643. gridRow.rowEditSavePromise.then(self.processSuccessPromise(grid, gridRow), self.processErrorPromise(grid, gridRow));
  19644. } else {
  19645. 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');
  19646. }
  19647. return promise;
  19648. };
  19649. },
  19650. /**
  19651. * @ngdoc method
  19652. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19653. * @name setSavePromise
  19654. * @description Sets the promise associated with the row save, mandatory that
  19655. * the saveRow event handler calls this method somewhere before returning.
  19656. * <pre>
  19657. * gridApi.rowEdit.setSavePromise(grid, rowEntity)
  19658. * </pre>
  19659. * @param {object} grid the grid for which dirty rows should be returned
  19660. * @param {object} rowEntity a data row from the grid for which a save has
  19661. * been initiated
  19662. * @param {promise} savePromise the promise that will be resolved when the
  19663. * save is successful, or rejected if the save fails
  19664. *
  19665. */
  19666. setSavePromise: function(grid, rowEntity, savePromise) {
  19667. var gridRow = grid.getRow(rowEntity);
  19668. gridRow.rowEditSavePromise = savePromise;
  19669. },
  19670. /**
  19671. * @ngdoc method
  19672. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19673. * @name processSuccessPromise
  19674. * @description Returns a function that processes the successful
  19675. * resolution of a save promise
  19676. * @param {object} grid the grid for which the promise should be processed
  19677. * @param {GridRow} gridRow the row that has been saved
  19678. * @returns {function} the success handling function
  19679. */
  19680. processSuccessPromise: function(grid, gridRow) {
  19681. var self = this;
  19682. return function() {
  19683. delete gridRow.isSaving;
  19684. delete gridRow.isDirty;
  19685. delete gridRow.isError;
  19686. delete gridRow.rowEditSaveTimer;
  19687. delete gridRow.rowEditSavePromise;
  19688. self.removeRow(grid.rowEdit.errorRows, gridRow);
  19689. self.removeRow(grid.rowEdit.dirtyRows, gridRow);
  19690. };
  19691. },
  19692. /**
  19693. * @ngdoc method
  19694. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19695. * @name processErrorPromise
  19696. * @description Returns a function that processes the failed
  19697. * resolution of a save promise
  19698. * @param {object} grid the grid for which the promise should be processed
  19699. * @param {GridRow} gridRow the row that is now in error
  19700. * @returns {function} the error handling function
  19701. */
  19702. processErrorPromise: function(grid, gridRow) {
  19703. return function() {
  19704. delete gridRow.isSaving;
  19705. delete gridRow.rowEditSaveTimer;
  19706. delete gridRow.rowEditSavePromise;
  19707. gridRow.isError = true;
  19708. if (!grid.rowEdit.errorRows) {
  19709. grid.rowEdit.errorRows = [];
  19710. }
  19711. if (!service.isRowPresent(grid.rowEdit.errorRows, gridRow)) {
  19712. grid.rowEdit.errorRows.push(gridRow);
  19713. }
  19714. };
  19715. },
  19716. /**
  19717. * @ngdoc method
  19718. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19719. * @name removeRow
  19720. * @description Removes a row from a cache of rows - either
  19721. * grid.rowEdit.errorRows or grid.rowEdit.dirtyRows. If the row
  19722. * is not present silently does nothing.
  19723. * @param {array} rowArray the array from which to remove the row
  19724. * @param {GridRow} gridRow the row that should be removed
  19725. */
  19726. removeRow: function(rowArray, removeGridRow) {
  19727. if (typeof(rowArray) === 'undefined' || rowArray === null) {
  19728. return;
  19729. }
  19730. rowArray.forEach(function(gridRow, index) {
  19731. if (gridRow.uid === removeGridRow.uid) {
  19732. rowArray.splice(index, 1);
  19733. }
  19734. });
  19735. },
  19736. /**
  19737. * @ngdoc method
  19738. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19739. * @name isRowPresent
  19740. * @description Checks whether a row is already present
  19741. * in the given array
  19742. * @param {array} rowArray the array in which to look for the row
  19743. * @param {GridRow} gridRow the row that should be looked for
  19744. */
  19745. isRowPresent: function(rowArray, removeGridRow) {
  19746. var present = false;
  19747. rowArray.forEach(function(gridRow, index) {
  19748. if (gridRow.uid === removeGridRow.uid) {
  19749. present = true;
  19750. }
  19751. });
  19752. return present;
  19753. },
  19754. /**
  19755. * @ngdoc method
  19756. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19757. * @name flushDirtyRows
  19758. * @description Triggers a save event for all currently dirty rows, could
  19759. * be used where user presses a save button or navigates away from the page
  19760. * <pre>
  19761. * gridApi.rowEdit.flushDirtyRows(grid)
  19762. * </pre>
  19763. * @param {object} grid the grid for which dirty rows should be flushed
  19764. * @returns {promise} a promise that represents the aggregate of all
  19765. * of the individual save promises - i.e. it will be resolved when all
  19766. * the individual save promises have been resolved.
  19767. *
  19768. */
  19769. flushDirtyRows: function(grid) {
  19770. var promises = [];
  19771. grid.api.rowEdit.getDirtyRows().forEach(function(gridRow) {
  19772. service.saveRow(grid, gridRow)();
  19773. promises.push(gridRow.rowEditSavePromise);
  19774. });
  19775. return $q.all(promises);
  19776. },
  19777. /**
  19778. * @ngdoc method
  19779. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19780. * @name endEditCell
  19781. * @description Receives an afterCellEdit event from the edit function,
  19782. * and sets flags as appropriate. Only the rowEntity parameter
  19783. * is processed, although other params are available. Grid
  19784. * is automatically provided by the gridApi.
  19785. * @param {object} rowEntity the data entity for which the cell
  19786. * was edited
  19787. */
  19788. endEditCell: function(rowEntity, colDef, newValue, previousValue) {
  19789. var grid = this.grid;
  19790. var gridRow = grid.getRow(rowEntity);
  19791. if (!gridRow) { gridUtil.logError('Unable to find rowEntity in grid data, dirty flag cannot be set'); return; }
  19792. if (newValue !== previousValue || gridRow.isDirty) {
  19793. if (!grid.rowEdit.dirtyRows) {
  19794. grid.rowEdit.dirtyRows = [];
  19795. }
  19796. if (!gridRow.isDirty) {
  19797. gridRow.isDirty = true;
  19798. grid.rowEdit.dirtyRows.push(gridRow);
  19799. }
  19800. delete gridRow.isError;
  19801. service.considerSetTimer(grid, gridRow);
  19802. }
  19803. },
  19804. /**
  19805. * @ngdoc method
  19806. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19807. * @name beginEditCell
  19808. * @description Receives a beginCellEdit event from the edit function,
  19809. * and cancels any rowEditSaveTimers if present, as the user is still editing
  19810. * this row. Only the rowEntity parameter
  19811. * is processed, although other params are available. Grid
  19812. * is automatically provided by the gridApi.
  19813. * @param {object} rowEntity the data entity for which the cell
  19814. * editing has commenced
  19815. */
  19816. beginEditCell: function(rowEntity, colDef) {
  19817. var grid = this.grid;
  19818. var gridRow = grid.getRow(rowEntity);
  19819. if (!gridRow) { gridUtil.logError('Unable to find rowEntity in grid data, timer cannot be cancelled'); return; }
  19820. service.cancelTimer(grid, gridRow);
  19821. },
  19822. /**
  19823. * @ngdoc method
  19824. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19825. * @name cancelEditCell
  19826. * @description Receives a cancelCellEdit event from the edit function,
  19827. * and if the row was already dirty, restarts the save timer. If the row
  19828. * was not already dirty, then it's not dirty now either and does nothing.
  19829. *
  19830. * Only the rowEntity parameter
  19831. * is processed, although other params are available. Grid
  19832. * is automatically provided by the gridApi.
  19833. *
  19834. * @param {object} rowEntity the data entity for which the cell
  19835. * editing was cancelled
  19836. */
  19837. cancelEditCell: function(rowEntity, colDef) {
  19838. var grid = this.grid;
  19839. var gridRow = grid.getRow(rowEntity);
  19840. if (!gridRow) { gridUtil.logError('Unable to find rowEntity in grid data, timer cannot be set'); return; }
  19841. service.considerSetTimer(grid, gridRow);
  19842. },
  19843. /**
  19844. * @ngdoc method
  19845. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19846. * @name navigate
  19847. * @description cellNav tells us that the selected cell has changed. If
  19848. * the new row had a timer running, then stop it similar to in a beginCellEdit
  19849. * call. If the old row is dirty and not the same as the new row, then
  19850. * start a timer on it.
  19851. * @param {object} newRowCol the row and column that were selected
  19852. * @param {object} oldRowCol the row and column that was left
  19853. *
  19854. */
  19855. navigate: function(newRowCol, oldRowCol) {
  19856. var grid = this.grid;
  19857. if (newRowCol.row.rowEditSaveTimer) {
  19858. service.cancelTimer(grid, newRowCol.row);
  19859. }
  19860. if (oldRowCol && oldRowCol.row && oldRowCol.row !== newRowCol.row) {
  19861. service.considerSetTimer(grid, oldRowCol.row);
  19862. }
  19863. },
  19864. /**
  19865. * @ngdoc property
  19866. * @propertyOf ui.grid.rowEdit.api:GridOptions
  19867. * @name rowEditWaitInterval
  19868. * @description How long the grid should wait for another change on this row
  19869. * before triggering a save (in milliseconds). If set to -1, then saves are
  19870. * never triggered by timer (implying that the user will call flushDirtyRows()
  19871. * manually)
  19872. *
  19873. * @example
  19874. * Setting the wait interval to 4 seconds
  19875. * <pre>
  19876. * $scope.gridOptions = { rowEditWaitInterval: 4000 }
  19877. * </pre>
  19878. *
  19879. */
  19880. /**
  19881. * @ngdoc method
  19882. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19883. * @name considerSetTimer
  19884. * @description Consider setting a timer on this row (if it is dirty). if there is a timer running
  19885. * on the row and the row isn't currently saving, cancel it, using cancelTimer, then if the row is
  19886. * dirty and not currently saving then set a new timer
  19887. * @param {object} grid the grid for which we are processing
  19888. * @param {GridRow} gridRow the row for which the timer should be adjusted
  19889. *
  19890. */
  19891. considerSetTimer: function(grid, gridRow) {
  19892. service.cancelTimer(grid, gridRow);
  19893. if (gridRow.isDirty && !gridRow.isSaving) {
  19894. if (grid.options.rowEditWaitInterval !== -1) {
  19895. var waitTime = grid.options.rowEditWaitInterval ? grid.options.rowEditWaitInterval : 2000;
  19896. gridRow.rowEditSaveTimer = $interval(service.saveRow(grid, gridRow), waitTime, 1);
  19897. }
  19898. }
  19899. },
  19900. /**
  19901. * @ngdoc method
  19902. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19903. * @name cancelTimer
  19904. * @description cancel the $interval for any timer running on this row
  19905. * then delete the timer itself
  19906. * @param {object} grid the grid for which we are processing
  19907. * @param {GridRow} gridRow the row for which the timer should be adjusted
  19908. *
  19909. */
  19910. cancelTimer: function(grid, gridRow) {
  19911. if (gridRow.rowEditSaveTimer && !gridRow.isSaving) {
  19912. $interval.cancel(gridRow.rowEditSaveTimer);
  19913. delete gridRow.rowEditSaveTimer;
  19914. }
  19915. },
  19916. /**
  19917. * @ngdoc method
  19918. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19919. * @name setRowsDirty
  19920. * @description Sets each of the rows passed in dataRows
  19921. * to be dirty. note that if you have only just inserted the
  19922. * rows into your data you will need to wait for a $digest cycle
  19923. * before the gridRows are present - so often you would wrap this
  19924. * call in a $interval or $timeout
  19925. * <pre>
  19926. * $interval( function() {
  19927. * gridApi.rowEdit.setRowsDirty( myDataRows);
  19928. * }, 0, 1);
  19929. * </pre>
  19930. * @param {object} grid the grid for which rows should be set dirty
  19931. * @param {array} dataRows the data entities for which the gridRows
  19932. * should be set dirty.
  19933. *
  19934. */
  19935. setRowsDirty: function(grid, myDataRows) {
  19936. var gridRow;
  19937. myDataRows.forEach(function(value, index) {
  19938. gridRow = grid.getRow(value);
  19939. if (gridRow) {
  19940. if (!grid.rowEdit.dirtyRows) {
  19941. grid.rowEdit.dirtyRows = [];
  19942. }
  19943. if (!gridRow.isDirty) {
  19944. gridRow.isDirty = true;
  19945. grid.rowEdit.dirtyRows.push(gridRow);
  19946. }
  19947. delete gridRow.isError;
  19948. service.considerSetTimer(grid, gridRow);
  19949. } else {
  19950. gridUtil.logError("requested row not found in rowEdit.setRowsDirty, row was: " + value);
  19951. }
  19952. });
  19953. },
  19954. /**
  19955. * @ngdoc method
  19956. * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
  19957. * @name setRowsClean
  19958. * @description Sets each of the rows passed in dataRows
  19959. * to be clean, clearing the dirty flag and the error flag, and removing
  19960. * the rows from the dirty and error caches.
  19961. * @param {object} grid the grid for which rows should be set clean
  19962. * @param {array} dataRows the data entities for which the gridRows
  19963. * should be set clean.
  19964. *
  19965. */
  19966. setRowsClean: function(grid, myDataRows) {
  19967. var gridRow;
  19968. myDataRows.forEach(function(value, index) {
  19969. gridRow = grid.getRow(value);
  19970. if (gridRow) {
  19971. delete gridRow.isDirty;
  19972. service.removeRow(grid.rowEdit.dirtyRows, gridRow);
  19973. service.cancelTimer(grid, gridRow);
  19974. delete gridRow.isError;
  19975. service.removeRow(grid.rowEdit.errorRows, gridRow);
  19976. } else {
  19977. gridUtil.logError("requested row not found in rowEdit.setRowsClean, row was: " + value);
  19978. }
  19979. });
  19980. }
  19981. };
  19982. return service;
  19983. }
  19984. ]);
  19985. /**
  19986. * @ngdoc directive
  19987. * @name ui.grid.rowEdit.directive:uiGridEdit
  19988. * @element div
  19989. * @restrict A
  19990. *
  19991. * @description Adds row editing features to the ui-grid-edit directive.
  19992. *
  19993. */
  19994. module.directive('uiGridRowEdit', ['gridUtil', 'uiGridRowEditService', 'uiGridEditConstants',
  19995. function(gridUtil, uiGridRowEditService, uiGridEditConstants) {
  19996. return {
  19997. replace: true,
  19998. priority: 0,
  19999. require: '^uiGrid',
  20000. scope: false,
  20001. compile: function() {
  20002. return {
  20003. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  20004. uiGridRowEditService.initializeGrid($scope, uiGridCtrl.grid);
  20005. },
  20006. post: function($scope, $elm, $attrs, uiGridCtrl) {}
  20007. };
  20008. }
  20009. };
  20010. }
  20011. ]);
  20012. /**
  20013. * @ngdoc directive
  20014. * @name ui.grid.rowEdit.directive:uiGridViewport
  20015. * @element div
  20016. *
  20017. * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used
  20018. * for the grid row to allow coloring of saving and error rows
  20019. */
  20020. module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'gridUtil', '$parse',
  20021. function($compile, uiGridConstants, gridUtil, $parse) {
  20022. return {
  20023. priority: -200, // run after default directive
  20024. scope: false,
  20025. compile: function($elm, $attrs) {
  20026. var rowRepeatDiv = angular.element($elm.children().children()[0]);
  20027. var existingNgClass = rowRepeatDiv.attr("ng-class");
  20028. var newNgClass = '';
  20029. if (existingNgClass) {
  20030. newNgClass = existingNgClass.slice(0, -1) + ", 'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}";
  20031. } else {
  20032. newNgClass = "{'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}";
  20033. }
  20034. rowRepeatDiv.attr("ng-class", newNgClass);
  20035. return {
  20036. pre: function($scope, $elm, $attrs, controllers) {
  20037. },
  20038. post: function($scope, $elm, $attrs, controllers) {}
  20039. };
  20040. }
  20041. };
  20042. }
  20043. ]);
  20044. })();
  20045. (function() {
  20046. 'use strict';
  20047. /**
  20048. * @ngdoc overview
  20049. * @name ui.grid.saveState
  20050. * @description
  20051. *
  20052. * # ui.grid.saveState
  20053. *
  20054. * <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>
  20055. *
  20056. * This module provides the ability to save the grid state, and restore
  20057. * it when the user returns to the page.
  20058. *
  20059. * No UI is provided, the caller should provide their own UI/buttons
  20060. * as appropriate. Usually the navigate events would be used to save
  20061. * the grid state and restore it.
  20062. *
  20063. * <br/>
  20064. * <br/>
  20065. *
  20066. * <div doc-module-components="ui.grid.save-state"></div>
  20067. */
  20068. var module = angular.module('ui.grid.saveState', ['ui.grid', 'ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.grouping', 'ui.grid.pinning', 'ui.grid.treeView']);
  20069. /**
  20070. * @ngdoc object
  20071. * @name ui.grid.saveState.constant:uiGridSaveStateConstants
  20072. *
  20073. * @description constants available in save state module
  20074. */
  20075. module.constant('uiGridSaveStateConstants', {
  20076. featureName: 'saveState'
  20077. });
  20078. /**
  20079. * @ngdoc service
  20080. * @name ui.grid.saveState.service:uiGridSaveStateService
  20081. *
  20082. * @description Services for saveState feature
  20083. */
  20084. module.service('uiGridSaveStateService', ['$q', 'uiGridSaveStateConstants', 'gridUtil', '$compile', '$interval', 'uiGridConstants',
  20085. function($q, uiGridSaveStateConstants, gridUtil, $compile, $interval, uiGridConstants) {
  20086. var service = {
  20087. initializeGrid: function(grid) {
  20088. //add feature namespace and any properties to grid for needed state
  20089. grid.saveState = {};
  20090. this.defaultGridOptions(grid.options);
  20091. /**
  20092. * @ngdoc object
  20093. * @name ui.grid.saveState.api:PublicApi
  20094. *
  20095. * @description Public Api for saveState feature
  20096. */
  20097. var publicApi = {
  20098. events: {
  20099. saveState: {}
  20100. },
  20101. methods: {
  20102. saveState: {
  20103. /**
  20104. * @ngdoc function
  20105. * @name save
  20106. * @methodOf ui.grid.saveState.api:PublicApi
  20107. * @description Packages the current state of the grid into
  20108. * an object, and provides it to the user for saving
  20109. * @returns {object} the state as a javascript object that can be saved
  20110. */
  20111. save: function() {
  20112. return service.save(grid);
  20113. },
  20114. /**
  20115. * @ngdoc function
  20116. * @name restore
  20117. * @methodOf ui.grid.saveState.api:PublicApi
  20118. * @description Restores the provided state into the grid
  20119. * @param {scope} $scope a scope that we can broadcast on
  20120. * @param {object} state the state that should be restored into the grid
  20121. */
  20122. restore: function($scope, state) {
  20123. service.restore(grid, $scope, state);
  20124. }
  20125. }
  20126. }
  20127. };
  20128. grid.api.registerEventsFromObject(publicApi.events);
  20129. grid.api.registerMethodsFromObject(publicApi.methods);
  20130. },
  20131. defaultGridOptions: function(gridOptions) {
  20132. //default option to true unless it was explicitly set to false
  20133. /**
  20134. * @ngdoc object
  20135. * @name ui.grid.saveState.api:GridOptions
  20136. *
  20137. * @description GridOptions for saveState feature, these are available to be
  20138. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  20139. */
  20140. /**
  20141. * @ngdoc object
  20142. * @name saveWidths
  20143. * @propertyOf ui.grid.saveState.api:GridOptions
  20144. * @description Save the current column widths. Note that unless
  20145. * you've provided the user with some way to resize their columns (say
  20146. * the resize columns feature), then this makes little sense.
  20147. * <br/>Defaults to true
  20148. */
  20149. gridOptions.saveWidths = gridOptions.saveWidths !== false;
  20150. /**
  20151. * @ngdoc object
  20152. * @name saveOrder
  20153. * @propertyOf ui.grid.saveState.api:GridOptions
  20154. * @description Restore the current column order. Note that unless
  20155. * you've provided the user with some way to reorder their columns (for
  20156. * example the move columns feature), this makes little sense.
  20157. * <br/>Defaults to true
  20158. */
  20159. gridOptions.saveOrder = gridOptions.saveOrder !== false;
  20160. /**
  20161. * @ngdoc object
  20162. * @name saveScroll
  20163. * @propertyOf ui.grid.saveState.api:GridOptions
  20164. * @description Save the current scroll position. Note that this
  20165. * is saved as the percentage of the grid scrolled - so if your
  20166. * user returns to a grid with a significantly different number of
  20167. * rows (perhaps some data has been deleted) then the scroll won't
  20168. * actually show the same rows as before. If you want to scroll to
  20169. * a specific row then you should instead use the saveFocus option, which
  20170. * is the default.
  20171. *
  20172. * Note that this element will only be saved if the cellNav feature is
  20173. * enabled
  20174. * <br/>Defaults to false
  20175. */
  20176. gridOptions.saveScroll = gridOptions.saveScroll === true;
  20177. /**
  20178. * @ngdoc object
  20179. * @name saveFocus
  20180. * @propertyOf ui.grid.saveState.api:GridOptions
  20181. * @description Save the current focused cell. On returning
  20182. * to this focused cell we'll also scroll. This option is
  20183. * preferred to the saveScroll option, so is set to true by
  20184. * default. If saveScroll is set to true then this option will
  20185. * be disabled.
  20186. *
  20187. * By default this option saves the current row number and column
  20188. * number, and returns to that row and column. However, if you define
  20189. * a saveRowIdentity function, then it will return you to the currently
  20190. * selected column within that row (in a business sense - so if some
  20191. * rows have been deleted, it will still find the same data, presuming it
  20192. * still exists in the list. If it isn't in the list then it will instead
  20193. * return to the same row number - i.e. scroll percentage)
  20194. *
  20195. * Note that this option will do nothing if the cellNav
  20196. * feature is not enabled.
  20197. *
  20198. * <br/>Defaults to true (unless saveScroll is true)
  20199. */
  20200. gridOptions.saveFocus = gridOptions.saveScroll !== true && gridOptions.saveFocus !== false;
  20201. /**
  20202. * @ngdoc object
  20203. * @name saveRowIdentity
  20204. * @propertyOf ui.grid.saveState.api:GridOptions
  20205. * @description A function that can be called, passing in a rowEntity,
  20206. * and that will return a unique id for that row. This might simply
  20207. * return the `id` field from that row (if you have one), or it might
  20208. * concatenate some fields within the row to make a unique value.
  20209. *
  20210. * This value will be used to find the same row again and set the focus
  20211. * to it, if it exists when we return.
  20212. *
  20213. * <br/>Defaults to undefined
  20214. */
  20215. /**
  20216. * @ngdoc object
  20217. * @name saveVisible
  20218. * @propertyOf ui.grid.saveState.api:GridOptions
  20219. * @description Save whether or not columns are visible.
  20220. *
  20221. * <br/>Defaults to true
  20222. */
  20223. gridOptions.saveVisible = gridOptions.saveVisible !== false;
  20224. /**
  20225. * @ngdoc object
  20226. * @name saveSort
  20227. * @propertyOf ui.grid.saveState.api:GridOptions
  20228. * @description Save the current sort state for each column
  20229. *
  20230. * <br/>Defaults to true
  20231. */
  20232. gridOptions.saveSort = gridOptions.saveSort !== false;
  20233. /**
  20234. * @ngdoc object
  20235. * @name saveFilter
  20236. * @propertyOf ui.grid.saveState.api:GridOptions
  20237. * @description Save the current filter state for each column
  20238. *
  20239. * <br/>Defaults to true
  20240. */
  20241. gridOptions.saveFilter = gridOptions.saveFilter !== false;
  20242. /**
  20243. * @ngdoc object
  20244. * @name saveSelection
  20245. * @propertyOf ui.grid.saveState.api:GridOptions
  20246. * @description Save the currently selected rows. If the `saveRowIdentity` callback
  20247. * is defined, then it will save the id of the row and select that. If not, then
  20248. * it will attempt to select the rows by row number, which will give the wrong results
  20249. * if the data set has changed in the mean-time.
  20250. *
  20251. * Note that this option only does anything
  20252. * if the selection feature is enabled.
  20253. *
  20254. * <br/>Defaults to true
  20255. */
  20256. gridOptions.saveSelection = gridOptions.saveSelection !== false;
  20257. /**
  20258. * @ngdoc object
  20259. * @name saveGrouping
  20260. * @propertyOf ui.grid.saveState.api:GridOptions
  20261. * @description Save the grouping configuration. If set to true and the
  20262. * grouping feature is not enabled then does nothing.
  20263. *
  20264. * <br/>Defaults to true
  20265. */
  20266. gridOptions.saveGrouping = gridOptions.saveGrouping !== false;
  20267. /**
  20268. * @ngdoc object
  20269. * @name saveGroupingExpandedStates
  20270. * @propertyOf ui.grid.saveState.api:GridOptions
  20271. * @description Save the grouping row expanded states. If set to true and the
  20272. * grouping feature is not enabled then does nothing.
  20273. *
  20274. * This can be quite a bit of data, in many cases you wouldn't want to save this
  20275. * information.
  20276. *
  20277. * <br/>Defaults to false
  20278. */
  20279. gridOptions.saveGroupingExpandedStates = gridOptions.saveGroupingExpandedStates === true;
  20280. /**
  20281. * @ngdoc object
  20282. * @name savePinning
  20283. * @propertyOf ui.grid.saveState.api:GridOptions
  20284. * @description Save pinning state for columns.
  20285. *
  20286. * <br/>Defaults to true
  20287. */
  20288. gridOptions.savePinning = gridOptions.savePinning !== false;
  20289. /**
  20290. * @ngdoc object
  20291. * @name saveTreeView
  20292. * @propertyOf ui.grid.saveState.api:GridOptions
  20293. * @description Save the treeView configuration. If set to true and the
  20294. * treeView feature is not enabled then does nothing.
  20295. *
  20296. * <br/>Defaults to true
  20297. */
  20298. gridOptions.saveTreeView = gridOptions.saveTreeView !== false;
  20299. },
  20300. /**
  20301. * @ngdoc function
  20302. * @name save
  20303. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20304. * @description Saves the current grid state into an object, and
  20305. * passes that object back to the caller
  20306. * @param {Grid} grid the grid whose state we'd like to save
  20307. * @returns {object} the state ready to be saved
  20308. */
  20309. save: function(grid) {
  20310. var savedState = {};
  20311. savedState.columns = service.saveColumns(grid);
  20312. savedState.scrollFocus = service.saveScrollFocus(grid);
  20313. savedState.selection = service.saveSelection(grid);
  20314. savedState.grouping = service.saveGrouping(grid);
  20315. savedState.treeView = service.saveTreeView(grid);
  20316. return savedState;
  20317. },
  20318. /**
  20319. * @ngdoc function
  20320. * @name restore
  20321. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20322. * @description Applies the provided state to the grid
  20323. *
  20324. * @param {Grid} grid the grid whose state we'd like to restore
  20325. * @param {scope} $scope a scope that we can broadcast on
  20326. * @param {object} state the state we'd like to restore
  20327. */
  20328. restore: function(grid, $scope, state) {
  20329. if (state.columns) {
  20330. service.restoreColumns(grid, state.columns);
  20331. }
  20332. if (state.scrollFocus) {
  20333. service.restoreScrollFocus(grid, $scope, state.scrollFocus);
  20334. }
  20335. if (state.selection) {
  20336. service.restoreSelection(grid, state.selection);
  20337. }
  20338. if (state.grouping) {
  20339. service.restoreGrouping(grid, state.grouping);
  20340. }
  20341. if (state.treeView) {
  20342. service.restoreTreeView(grid, state.treeView);
  20343. }
  20344. grid.refresh();
  20345. },
  20346. /**
  20347. * @ngdoc function
  20348. * @name saveColumns
  20349. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20350. * @description Saves the column setup, including sort, filters, ordering,
  20351. * pinning and column widths.
  20352. *
  20353. * Works through the current columns, storing them in order. Stores the
  20354. * column name, then the visible flag, width, sort and filters for each column.
  20355. *
  20356. * @param {Grid} grid the grid whose state we'd like to save
  20357. * @returns {array} the columns state ready to be saved
  20358. */
  20359. saveColumns: function(grid) {
  20360. var columns = [];
  20361. grid.getOnlyDataColumns().forEach(function(column) {
  20362. var savedColumn = {};
  20363. savedColumn.name = column.name;
  20364. if (grid.options.saveVisible) {
  20365. savedColumn.visible = column.visible;
  20366. }
  20367. if (grid.options.saveWidths) {
  20368. savedColumn.width = column.width;
  20369. }
  20370. // these two must be copied, not just pointed too - otherwise our saved state is pointing to the same object as current state
  20371. if (grid.options.saveSort) {
  20372. savedColumn.sort = angular.copy(column.sort);
  20373. }
  20374. if (grid.options.saveFilter) {
  20375. savedColumn.filters = [];
  20376. column.filters.forEach(function(filter) {
  20377. var copiedFilter = {};
  20378. angular.forEach(filter, function(value, key) {
  20379. if (key !== 'condition' && key !== '$$hashKey' && key !== 'placeholder') {
  20380. copiedFilter[key] = value;
  20381. }
  20382. });
  20383. savedColumn.filters.push(copiedFilter);
  20384. });
  20385. }
  20386. if (!!grid.api.pinning && grid.options.savePinning) {
  20387. savedColumn.pinned = column.renderContainer ? column.renderContainer : '';
  20388. }
  20389. columns.push(savedColumn);
  20390. });
  20391. return columns;
  20392. },
  20393. /**
  20394. * @ngdoc function
  20395. * @name saveScrollFocus
  20396. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20397. * @description Saves the currently scroll or focus.
  20398. *
  20399. * If cellNav isn't present then does nothing - we can't return
  20400. * to the scroll position without cellNav anyway.
  20401. *
  20402. * If the cellNav module is present, and saveFocus is true, then
  20403. * it saves the currently focused cell. If rowIdentity is present
  20404. * then saves using rowIdentity, otherwise saves visibleRowNum.
  20405. *
  20406. * If the cellNav module is not present, and saveScroll is true, then
  20407. * it approximates the current scroll row and column, and saves that.
  20408. *
  20409. * @param {Grid} grid the grid whose state we'd like to save
  20410. * @returns {object} the selection state ready to be saved
  20411. */
  20412. saveScrollFocus: function(grid) {
  20413. if (!grid.api.cellNav) {
  20414. return {};
  20415. }
  20416. var scrollFocus = {};
  20417. if (grid.options.saveFocus) {
  20418. scrollFocus.focus = true;
  20419. var rowCol = grid.api.cellNav.getFocusedCell();
  20420. if (rowCol !== null) {
  20421. if (rowCol.col !== null) {
  20422. scrollFocus.colName = rowCol.col.colDef.name;
  20423. }
  20424. if (rowCol.row !== null) {
  20425. scrollFocus.rowVal = service.getRowVal(grid, rowCol.row);
  20426. }
  20427. }
  20428. }
  20429. if (grid.options.saveScroll || grid.options.saveFocus && !scrollFocus.colName && !scrollFocus.rowVal) {
  20430. scrollFocus.focus = false;
  20431. if (grid.renderContainers.body.prevRowScrollIndex) {
  20432. scrollFocus.rowVal = service.getRowVal(grid, grid.renderContainers.body.visibleRowCache[grid.renderContainers.body.prevRowScrollIndex]);
  20433. }
  20434. if (grid.renderContainers.body.prevColScrollIndex) {
  20435. scrollFocus.colName = grid.renderContainers.body.visibleColumnCache[grid.renderContainers.body.prevColScrollIndex].name;
  20436. }
  20437. }
  20438. return scrollFocus;
  20439. },
  20440. /**
  20441. * @ngdoc function
  20442. * @name saveSelection
  20443. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20444. * @description Saves the currently selected rows, if the selection feature is enabled
  20445. * @param {Grid} grid the grid whose state we'd like to save
  20446. * @returns {array} the selection state ready to be saved
  20447. */
  20448. saveSelection: function(grid) {
  20449. if (!grid.api.selection || !grid.options.saveSelection) {
  20450. return [];
  20451. }
  20452. var selection = grid.api.selection.getSelectedGridRows().map(function(gridRow) {
  20453. return service.getRowVal(grid, gridRow);
  20454. });
  20455. return selection;
  20456. },
  20457. /**
  20458. * @ngdoc function
  20459. * @name saveGrouping
  20460. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20461. * @description Saves the grouping state, if the grouping feature is enabled
  20462. * @param {Grid} grid the grid whose state we'd like to save
  20463. * @returns {object} the grouping state ready to be saved
  20464. */
  20465. saveGrouping: function(grid) {
  20466. if (!grid.api.grouping || !grid.options.saveGrouping) {
  20467. return {};
  20468. }
  20469. return grid.api.grouping.getGrouping(grid.options.saveGroupingExpandedStates);
  20470. },
  20471. /**
  20472. * @ngdoc function
  20473. * @name saveTreeView
  20474. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20475. * @description Saves the tree view state, if the tree feature is enabled
  20476. * @param {Grid} grid the grid whose state we'd like to save
  20477. * @returns {object} the tree view state ready to be saved
  20478. */
  20479. saveTreeView: function(grid) {
  20480. if (!grid.api.treeView || !grid.options.saveTreeView) {
  20481. return {};
  20482. }
  20483. return grid.api.treeView.getTreeView();
  20484. },
  20485. /**
  20486. * @ngdoc function
  20487. * @name getRowVal
  20488. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20489. * @description Helper function that gets either the rowNum or
  20490. * the saveRowIdentity, given a gridRow
  20491. * @param {Grid} grid the grid the row is in
  20492. * @param {GridRow} gridRow the row we want the rowNum for
  20493. * @returns {object} an object containing { identity: true/false, row: rowNumber/rowIdentity }
  20494. *
  20495. */
  20496. getRowVal: function(grid, gridRow) {
  20497. if (!gridRow) {
  20498. return null;
  20499. }
  20500. var rowVal = {};
  20501. if (grid.options.saveRowIdentity) {
  20502. rowVal.identity = true;
  20503. rowVal.row = grid.options.saveRowIdentity(gridRow.entity);
  20504. } else {
  20505. rowVal.identity = false;
  20506. rowVal.row = grid.renderContainers.body.visibleRowCache.indexOf(gridRow);
  20507. }
  20508. return rowVal;
  20509. },
  20510. /**
  20511. * @ngdoc function
  20512. * @name restoreColumns
  20513. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20514. * @description Restores the columns, including order, visible, width,
  20515. * pinning, sort and filters.
  20516. *
  20517. * @param {Grid} grid the grid whose state we'd like to restore
  20518. * @param {object} columnsState the list of columns we had before, with their state
  20519. */
  20520. restoreColumns: function(grid, columnsState) {
  20521. var isSortChanged = false;
  20522. columnsState.forEach(function(columnState, index) {
  20523. var currentCol = grid.getColumn(columnState.name);
  20524. if (currentCol && !grid.isRowHeaderColumn(currentCol)) {
  20525. if (grid.options.saveVisible &&
  20526. (currentCol.visible !== columnState.visible ||
  20527. currentCol.colDef.visible !== columnState.visible)) {
  20528. currentCol.visible = columnState.visible;
  20529. currentCol.colDef.visible = columnState.visible;
  20530. grid.api.core.raise.columnVisibilityChanged(currentCol);
  20531. }
  20532. if (grid.options.saveWidths) {
  20533. currentCol.width = columnState.width;
  20534. }
  20535. if (grid.options.saveSort &&
  20536. !angular.equals(currentCol.sort, columnState.sort) &&
  20537. !(currentCol.sort === undefined && angular.isEmpty(columnState.sort))) {
  20538. currentCol.sort = angular.copy(columnState.sort);
  20539. isSortChanged = true;
  20540. }
  20541. if (grid.options.saveFilter &&
  20542. !angular.equals(currentCol.filters, columnState.filters)) {
  20543. columnState.filters.forEach(function(filter, index) {
  20544. angular.extend(currentCol.filters[index], filter);
  20545. if (typeof(filter.term) === 'undefined' || filter.term === null) {
  20546. delete currentCol.filters[index].term;
  20547. }
  20548. });
  20549. grid.api.core.raise.filterChanged();
  20550. }
  20551. if (!!grid.api.pinning && grid.options.savePinning && currentCol.renderContainer !== columnState.pinned) {
  20552. grid.api.pinning.pinColumn(currentCol, columnState.pinned);
  20553. }
  20554. var currentIndex = grid.getOnlyDataColumns().indexOf(currentCol);
  20555. if (currentIndex !== -1) {
  20556. if (grid.options.saveOrder && currentIndex !== index) {
  20557. var column = grid.columns.splice(currentIndex + grid.rowHeaderColumns.length, 1)[0];
  20558. grid.columns.splice(index + grid.rowHeaderColumns.length, 0, column);
  20559. }
  20560. }
  20561. }
  20562. });
  20563. if (isSortChanged) {
  20564. grid.api.core.raise.sortChanged(grid, grid.getColumnSorting());
  20565. }
  20566. },
  20567. /**
  20568. * @ngdoc function
  20569. * @name restoreScrollFocus
  20570. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20571. * @description Scrolls to the position that was saved. If focus is true, then
  20572. * sets focus to the specified row/col. If focus is false, then scrolls to the
  20573. * specified row/col.
  20574. *
  20575. * @param {Grid} grid the grid whose state we'd like to restore
  20576. * @param {scope} $scope a scope that we can broadcast on
  20577. * @param {object} scrollFocusState the scroll/focus state ready to be restored
  20578. */
  20579. restoreScrollFocus: function(grid, $scope, scrollFocusState) {
  20580. if (!grid.api.cellNav) {
  20581. return;
  20582. }
  20583. var colDef, row;
  20584. if (scrollFocusState.colName) {
  20585. var colDefs = grid.options.columnDefs.filter(function(colDef) { return colDef.name === scrollFocusState.colName; });
  20586. if (colDefs.length > 0) {
  20587. colDef = colDefs[0];
  20588. }
  20589. }
  20590. if (scrollFocusState.rowVal && scrollFocusState.rowVal.row) {
  20591. if (scrollFocusState.rowVal.identity) {
  20592. row = service.findRowByIdentity(grid, scrollFocusState.rowVal);
  20593. } else {
  20594. row = grid.renderContainers.body.visibleRowCache[scrollFocusState.rowVal.row];
  20595. }
  20596. }
  20597. var entity = row && row.entity ? row.entity : null;
  20598. if (colDef || entity) {
  20599. if (scrollFocusState.focus) {
  20600. grid.api.cellNav.scrollToFocus(entity, colDef);
  20601. } else {
  20602. grid.scrollTo(entity, colDef);
  20603. }
  20604. }
  20605. },
  20606. /**
  20607. * @ngdoc function
  20608. * @name restoreSelection
  20609. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20610. * @description Selects the rows that are provided in the selection
  20611. * state. If you are using `saveRowIdentity` and more than one row matches the identity
  20612. * function then only the first is selected.
  20613. * @param {Grid} grid the grid whose state we'd like to restore
  20614. * @param {object} selectionState the selection state ready to be restored
  20615. */
  20616. restoreSelection: function(grid, selectionState) {
  20617. if (!grid.api.selection) {
  20618. return;
  20619. }
  20620. grid.api.selection.clearSelectedRows();
  20621. selectionState.forEach(function(rowVal) {
  20622. if (rowVal.identity) {
  20623. var foundRow = service.findRowByIdentity(grid, rowVal);
  20624. if (foundRow) {
  20625. grid.api.selection.selectRow(foundRow.entity);
  20626. }
  20627. } else {
  20628. grid.api.selection.selectRowByVisibleIndex(rowVal.row);
  20629. }
  20630. });
  20631. },
  20632. /**
  20633. * @ngdoc function
  20634. * @name restoreGrouping
  20635. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20636. * @description Restores the grouping configuration, if the grouping feature
  20637. * is enabled.
  20638. * @param {Grid} grid the grid whose state we'd like to restore
  20639. * @param {object} groupingState the grouping state ready to be restored
  20640. */
  20641. restoreGrouping: function(grid, groupingState) {
  20642. if (!grid.api.grouping || typeof(groupingState) === 'undefined' || groupingState === null || angular.equals(groupingState, {})) {
  20643. return;
  20644. }
  20645. grid.api.grouping.setGrouping(groupingState);
  20646. },
  20647. /**
  20648. * @ngdoc function
  20649. * @name restoreTreeView
  20650. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20651. * @description Restores the tree view configuration, if the tree view feature
  20652. * is enabled.
  20653. * @param {Grid} grid the grid whose state we'd like to restore
  20654. * @param {object} treeViewState the tree view state ready to be restored
  20655. */
  20656. restoreTreeView: function(grid, treeViewState) {
  20657. if (!grid.api.treeView || typeof(treeViewState) === 'undefined' || treeViewState === null || angular.equals(treeViewState, {})) {
  20658. return;
  20659. }
  20660. grid.api.treeView.setTreeView(treeViewState);
  20661. },
  20662. /**
  20663. * @ngdoc function
  20664. * @name findRowByIdentity
  20665. * @methodOf ui.grid.saveState.service:uiGridSaveStateService
  20666. * @description Finds a row given it's identity value, returns the first found row
  20667. * if any are found, otherwise returns null if no rows are found.
  20668. * @param {Grid} grid the grid whose state we'd like to restore
  20669. * @param {object} rowVal the row we'd like to find
  20670. * @returns {gridRow} the found row, or null if none found
  20671. */
  20672. findRowByIdentity: function(grid, rowVal) {
  20673. if (!grid.options.saveRowIdentity) {
  20674. return null;
  20675. }
  20676. var filteredRows = grid.rows.filter(function(gridRow) {
  20677. if (grid.options.saveRowIdentity(gridRow.entity) === rowVal.row) {
  20678. return true;
  20679. } else {
  20680. return false;
  20681. }
  20682. });
  20683. if (filteredRows.length > 0) {
  20684. return filteredRows[0];
  20685. } else {
  20686. return null;
  20687. }
  20688. }
  20689. };
  20690. return service;
  20691. }
  20692. ]);
  20693. /**
  20694. * @ngdoc directive
  20695. * @name ui.grid.saveState.directive:uiGridSaveState
  20696. * @element div
  20697. * @restrict A
  20698. *
  20699. * @description Adds saveState features to grid
  20700. *
  20701. * @example
  20702. <example module="app">
  20703. <file name="app.js">
  20704. var app = angular.module('app', ['ui.grid', 'ui.grid.saveState']);
  20705. app.controller('MainCtrl', ['$scope', function ($scope) {
  20706. $scope.data = [
  20707. { name: 'Bob', title: 'CEO' },
  20708. { name: 'Frank', title: 'Lowly Developer' }
  20709. ];
  20710. $scope.gridOptions = {
  20711. columnDefs: [
  20712. {name: 'name'},
  20713. {name: 'title', enableCellEdit: true}
  20714. ],
  20715. data: $scope.data
  20716. };
  20717. }]);
  20718. </file>
  20719. <file name="index.html">
  20720. <div ng-controller="MainCtrl">
  20721. <div ui-grid="gridOptions" ui-grid-save-state></div>
  20722. </div>
  20723. </file>
  20724. </example>
  20725. */
  20726. module.directive('uiGridSaveState', ['uiGridSaveStateConstants', 'uiGridSaveStateService', 'gridUtil', '$compile',
  20727. function(uiGridSaveStateConstants, uiGridSaveStateService, gridUtil, $compile) {
  20728. return {
  20729. replace: true,
  20730. priority: 0,
  20731. require: '^uiGrid',
  20732. scope: false,
  20733. link: function($scope, $elm, $attrs, uiGridCtrl) {
  20734. uiGridSaveStateService.initializeGrid(uiGridCtrl.grid);
  20735. }
  20736. };
  20737. }
  20738. ]);
  20739. })();
  20740. (function() {
  20741. 'use strict';
  20742. /**
  20743. * @ngdoc overview
  20744. * @name ui.grid.selection
  20745. * @description
  20746. *
  20747. * # ui.grid.selection
  20748. * This module provides row selection
  20749. *
  20750. * <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>
  20751. *
  20752. * <div doc-module-components="ui.grid.selection"></div>
  20753. */
  20754. var module = angular.module('ui.grid.selection', ['ui.grid']);
  20755. /**
  20756. * @ngdoc object
  20757. * @name ui.grid.selection.constant:uiGridSelectionConstants
  20758. *
  20759. * @description constants available in selection module
  20760. */
  20761. module.constant('uiGridSelectionConstants', {
  20762. featureName: "selection",
  20763. selectionRowHeaderColName: 'selectionRowHeaderCol'
  20764. });
  20765. //add methods to GridRow
  20766. angular.module('ui.grid').config(['$provide', function($provide) {
  20767. $provide.decorator('GridRow', ['$delegate', function($delegate) {
  20768. /**
  20769. * @ngdoc object
  20770. * @name ui.grid.selection.api:GridRow
  20771. *
  20772. * @description GridRow prototype functions added for selection
  20773. */
  20774. /**
  20775. * @ngdoc object
  20776. * @name enableSelection
  20777. * @propertyOf ui.grid.selection.api:GridRow
  20778. * @description Enable row selection for this row, only settable by internal code.
  20779. *
  20780. * The grouping feature, for example, might set group header rows to not be selectable.
  20781. * <br/>Defaults to true
  20782. */
  20783. /**
  20784. * @ngdoc object
  20785. * @name isSelected
  20786. * @propertyOf ui.grid.selection.api:GridRow
  20787. * @description Selected state of row. Should be readonly. Make any changes to selected state using setSelected().
  20788. * <br/>Defaults to false
  20789. */
  20790. /**
  20791. * @ngdoc function
  20792. * @name setSelected
  20793. * @methodOf ui.grid.selection.api:GridRow
  20794. * @description Sets the isSelected property and updates the selectedCount
  20795. * Changes to isSelected state should only be made via this function
  20796. * @param {bool} selected value to set
  20797. */
  20798. $delegate.prototype.setSelected = function(selected) {
  20799. this.isSelected = selected;
  20800. if (selected) {
  20801. this.grid.selection.selectedCount++;
  20802. } else {
  20803. this.grid.selection.selectedCount--;
  20804. }
  20805. };
  20806. return $delegate;
  20807. }]);
  20808. }]);
  20809. /**
  20810. * @ngdoc service
  20811. * @name ui.grid.selection.service:uiGridSelectionService
  20812. *
  20813. * @description Services for selection features
  20814. */
  20815. module.service('uiGridSelectionService', ['$q', '$templateCache', 'uiGridSelectionConstants', 'gridUtil',
  20816. function($q, $templateCache, uiGridSelectionConstants, gridUtil) {
  20817. var service = {
  20818. initializeGrid: function(grid) {
  20819. //add feature namespace and any properties to grid for needed
  20820. /**
  20821. * @ngdoc object
  20822. * @name ui.grid.selection.grid:selection
  20823. *
  20824. * @description Grid properties and functions added for selection
  20825. */
  20826. grid.selection = {};
  20827. grid.selection.lastSelectedRow = null;
  20828. grid.selection.selectAll = false;
  20829. /**
  20830. * @ngdoc object
  20831. * @name selectedCount
  20832. * @propertyOf ui.grid.selection.grid:selection
  20833. * @description Current count of selected rows
  20834. * @example
  20835. * var count = grid.selection.selectedCount
  20836. */
  20837. grid.selection.selectedCount = 0;
  20838. service.defaultGridOptions(grid.options);
  20839. /**
  20840. * @ngdoc object
  20841. * @name ui.grid.selection.api:PublicApi
  20842. *
  20843. * @description Public Api for selection feature
  20844. */
  20845. var publicApi = {
  20846. events: {
  20847. selection: {
  20848. /**
  20849. * @ngdoc event
  20850. * @name rowSelectionChanged
  20851. * @eventOf ui.grid.selection.api:PublicApi
  20852. * @description is raised after the row.isSelected state is changed
  20853. * @param {GridRow} row the row that was selected/deselected
  20854. * @param {Event} event object if raised from an event
  20855. */
  20856. rowSelectionChanged: function(scope, row, evt) {},
  20857. /**
  20858. * @ngdoc event
  20859. * @name rowSelectionChangedBatch
  20860. * @eventOf ui.grid.selection.api:PublicApi
  20861. * @description is raised after the row.isSelected state is changed
  20862. * in bulk, if the `enableSelectionBatchEvent` option is set to true
  20863. * (which it is by default). This allows more efficient processing
  20864. * of bulk events.
  20865. * @param {array} rows the rows that were selected/deselected
  20866. * @param {Event} event object if raised from an event
  20867. */
  20868. rowSelectionChangedBatch: function(scope, rows, evt) {}
  20869. }
  20870. },
  20871. methods: {
  20872. selection: {
  20873. /**
  20874. * @ngdoc function
  20875. * @name toggleRowSelection
  20876. * @methodOf ui.grid.selection.api:PublicApi
  20877. * @description Toggles data row as selected or unselected
  20878. * @param {object} rowEntity gridOptions.data[] array instance
  20879. * @param {Event} event object if raised from an event
  20880. */
  20881. toggleRowSelection: function(rowEntity, evt) {
  20882. var row = grid.getRow(rowEntity);
  20883. if (row !== null) {
  20884. service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
  20885. }
  20886. },
  20887. /**
  20888. * @ngdoc function
  20889. * @name selectRow
  20890. * @methodOf ui.grid.selection.api:PublicApi
  20891. * @description Select the data row
  20892. * @param {object} rowEntity gridOptions.data[] array instance
  20893. * @param {Event} event object if raised from an event
  20894. */
  20895. selectRow: function(rowEntity, evt) {
  20896. var row = grid.getRow(rowEntity);
  20897. if (row !== null && !row.isSelected) {
  20898. service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
  20899. }
  20900. },
  20901. /**
  20902. * @ngdoc function
  20903. * @name selectRowByVisibleIndex
  20904. * @methodOf ui.grid.selection.api:PublicApi
  20905. * @description Select the specified row by visible index (i.e. if you
  20906. * specify row 0 you'll get the first visible row selected). In this context
  20907. * visible means of those rows that are theoretically visible (i.e. not filtered),
  20908. * rather than rows currently rendered on the screen.
  20909. * @param {number} index index within the rowsVisible array
  20910. * @param {Event} event object if raised from an event
  20911. */
  20912. selectRowByVisibleIndex: function(rowNum, evt) {
  20913. var row = grid.renderContainers.body.visibleRowCache[rowNum];
  20914. if (row !== null && typeof(row) !== 'undefined' && !row.isSelected) {
  20915. service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
  20916. }
  20917. },
  20918. /**
  20919. * @ngdoc function
  20920. * @name unSelectRow
  20921. * @methodOf ui.grid.selection.api:PublicApi
  20922. * @description UnSelect the data row
  20923. * @param {object} rowEntity gridOptions.data[] array instance
  20924. * @param {Event} event object if raised from an event
  20925. */
  20926. unSelectRow: function(rowEntity, evt) {
  20927. var row = grid.getRow(rowEntity);
  20928. if (row !== null && row.isSelected) {
  20929. service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
  20930. }
  20931. },
  20932. /**
  20933. * @ngdoc function
  20934. * @name selectAllRows
  20935. * @methodOf ui.grid.selection.api:PublicApi
  20936. * @description Selects all rows. Does nothing if multiSelect = false
  20937. * @param {Event} event object if raised from an event
  20938. */
  20939. selectAllRows: function(evt) {
  20940. if (grid.options.multiSelect === false) {
  20941. return;
  20942. }
  20943. var changedRows = [];
  20944. grid.rows.forEach(function(row) {
  20945. if (!row.isSelected && row.enableSelection !== false) {
  20946. row.setSelected(true);
  20947. service.decideRaiseSelectionEvent(grid, row, changedRows, evt);
  20948. }
  20949. });
  20950. service.decideRaiseSelectionBatchEvent(grid, changedRows, evt);
  20951. grid.selection.selectAll = true;
  20952. },
  20953. /**
  20954. * @ngdoc function
  20955. * @name selectAllVisibleRows
  20956. * @methodOf ui.grid.selection.api:PublicApi
  20957. * @description Selects all visible rows. Does nothing if multiSelect = false
  20958. * @param {Event} event object if raised from an event
  20959. */
  20960. selectAllVisibleRows: function(evt) {
  20961. if (grid.options.multiSelect === false) {
  20962. return;
  20963. }
  20964. var changedRows = [];
  20965. grid.rows.forEach(function(row) {
  20966. if (row.visible) {
  20967. if (!row.isSelected && row.enableSelection !== false) {
  20968. row.setSelected(true);
  20969. service.decideRaiseSelectionEvent(grid, row, changedRows, evt);
  20970. }
  20971. } else {
  20972. if (row.isSelected) {
  20973. row.setSelected(false);
  20974. service.decideRaiseSelectionEvent(grid, row, changedRows, evt);
  20975. }
  20976. }
  20977. });
  20978. service.decideRaiseSelectionBatchEvent(grid, changedRows, evt);
  20979. grid.selection.selectAll = true;
  20980. },
  20981. /**
  20982. * @ngdoc function
  20983. * @name clearSelectedRows
  20984. * @methodOf ui.grid.selection.api:PublicApi
  20985. * @description Unselects all rows
  20986. * @param {Event} event object if raised from an event
  20987. */
  20988. clearSelectedRows: function(evt) {
  20989. service.clearSelectedRows(grid, evt);
  20990. },
  20991. /**
  20992. * @ngdoc function
  20993. * @name getSelectedRows
  20994. * @methodOf ui.grid.selection.api:PublicApi
  20995. * @description returns all selectedRow's entity references
  20996. */
  20997. getSelectedRows: function() {
  20998. return service.getSelectedRows(grid).map(function(gridRow) {
  20999. return gridRow.entity;
  21000. });
  21001. },
  21002. /**
  21003. * @ngdoc function
  21004. * @name getSelectedGridRows
  21005. * @methodOf ui.grid.selection.api:PublicApi
  21006. * @description returns all selectedRow's as gridRows
  21007. */
  21008. getSelectedGridRows: function() {
  21009. return service.getSelectedRows(grid);
  21010. },
  21011. /**
  21012. * @ngdoc function
  21013. * @name setMultiSelect
  21014. * @methodOf ui.grid.selection.api:PublicApi
  21015. * @description Sets the current gridOption.multiSelect to true or false
  21016. * @param {bool} multiSelect true to allow multiple rows
  21017. */
  21018. setMultiSelect: function(multiSelect) {
  21019. grid.options.multiSelect = multiSelect;
  21020. },
  21021. /**
  21022. * @ngdoc function
  21023. * @name setModifierKeysToMultiSelect
  21024. * @methodOf ui.grid.selection.api:PublicApi
  21025. * @description Sets the current gridOption.modifierKeysToMultiSelect to true or false
  21026. * @param {bool} modifierKeysToMultiSelect true to only allow multiple rows when using ctrlKey or shiftKey is used
  21027. */
  21028. setModifierKeysToMultiSelect: function(modifierKeysToMultiSelect) {
  21029. grid.options.modifierKeysToMultiSelect = modifierKeysToMultiSelect;
  21030. },
  21031. /**
  21032. * @ngdoc function
  21033. * @name getSelectAllState
  21034. * @methodOf ui.grid.selection.api:PublicApi
  21035. * @description Returns whether or not the selectAll checkbox is currently ticked. The
  21036. * grid doesn't automatically select rows when you add extra data - so when you add data
  21037. * you need to explicitly check whether the selectAll is set, and then call setVisible rows
  21038. * if it is
  21039. */
  21040. getSelectAllState: function() {
  21041. return grid.selection.selectAll;
  21042. }
  21043. }
  21044. }
  21045. };
  21046. grid.api.registerEventsFromObject(publicApi.events);
  21047. grid.api.registerMethodsFromObject(publicApi.methods);
  21048. },
  21049. defaultGridOptions: function(gridOptions) {
  21050. //default option to true unless it was explicitly set to false
  21051. /**
  21052. * @ngdoc object
  21053. * @name ui.grid.selection.api:GridOptions
  21054. *
  21055. * @description GridOptions for selection feature, these are available to be
  21056. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  21057. */
  21058. /**
  21059. * @ngdoc object
  21060. * @name enableRowSelection
  21061. * @propertyOf ui.grid.selection.api:GridOptions
  21062. * @description Enable row selection for entire grid.
  21063. * <br/>Defaults to true
  21064. */
  21065. gridOptions.enableRowSelection = gridOptions.enableRowSelection !== false;
  21066. /**
  21067. * @ngdoc object
  21068. * @name multiSelect
  21069. * @propertyOf ui.grid.selection.api:GridOptions
  21070. * @description Enable multiple row selection for entire grid
  21071. * <br/>Defaults to true
  21072. */
  21073. gridOptions.multiSelect = gridOptions.multiSelect !== false;
  21074. /**
  21075. * @ngdoc object
  21076. * @name noUnselect
  21077. * @propertyOf ui.grid.selection.api:GridOptions
  21078. * @description Prevent a row from being unselected. Works in conjunction
  21079. * with `multiselect = false` and `gridApi.selection.selectRow()` to allow
  21080. * you to create a single selection only grid - a row is always selected, you
  21081. * can only select different rows, you can't unselect the row.
  21082. * <br/>Defaults to false
  21083. */
  21084. gridOptions.noUnselect = gridOptions.noUnselect === true;
  21085. /**
  21086. * @ngdoc object
  21087. * @name modifierKeysToMultiSelect
  21088. * @propertyOf ui.grid.selection.api:GridOptions
  21089. * @description Enable multiple row selection only when using the ctrlKey or shiftKey. Requires multiSelect to be true.
  21090. * <br/>Defaults to false
  21091. */
  21092. gridOptions.modifierKeysToMultiSelect = gridOptions.modifierKeysToMultiSelect === true;
  21093. /**
  21094. * @ngdoc object
  21095. * @name enableRowHeaderSelection
  21096. * @propertyOf ui.grid.selection.api:GridOptions
  21097. * @description Enable a row header to be used for selection
  21098. * <br/>Defaults to true
  21099. */
  21100. gridOptions.enableRowHeaderSelection = gridOptions.enableRowHeaderSelection !== false;
  21101. /**
  21102. * @ngdoc object
  21103. * @name enableFullRowSelection
  21104. * @propertyOf ui.grid.selection.api:GridOptions
  21105. * @description Enable selection by clicking anywhere on the row. Defaults to
  21106. * false if `enableRowHeaderSelection` is true, otherwise defaults to false.
  21107. */
  21108. if (typeof(gridOptions.enableFullRowSelection) === 'undefined') {
  21109. gridOptions.enableFullRowSelection = !gridOptions.enableRowHeaderSelection;
  21110. }
  21111. /**
  21112. * @ngdoc object
  21113. * @name enableSelectAll
  21114. * @propertyOf ui.grid.selection.api:GridOptions
  21115. * @description Enable the select all checkbox at the top of the selectionRowHeader
  21116. * <br/>Defaults to true
  21117. */
  21118. gridOptions.enableSelectAll = gridOptions.enableSelectAll !== false;
  21119. /**
  21120. * @ngdoc object
  21121. * @name enableSelectionBatchEvent
  21122. * @propertyOf ui.grid.selection.api:GridOptions
  21123. * @description If selected rows are changed in bulk, either via the API or
  21124. * via the selectAll checkbox, then a separate event is fired. Setting this
  21125. * option to false will cause the rowSelectionChanged event to be called multiple times
  21126. * instead
  21127. * <br/>Defaults to true
  21128. */
  21129. gridOptions.enableSelectionBatchEvent = gridOptions.enableSelectionBatchEvent !== false;
  21130. /**
  21131. * @ngdoc object
  21132. * @name selectionRowHeaderWidth
  21133. * @propertyOf ui.grid.selection.api:GridOptions
  21134. * @description can be used to set a custom width for the row header selection column
  21135. * <br/>Defaults to 30px
  21136. */
  21137. gridOptions.selectionRowHeaderWidth = angular.isDefined(gridOptions.selectionRowHeaderWidth) ? gridOptions.selectionRowHeaderWidth : 34;
  21138. /**
  21139. * @ngdoc object
  21140. * @name enableFooterTotalSelected
  21141. * @propertyOf ui.grid.selection.api:GridOptions
  21142. * @description Shows the total number of selected items in footer if true.
  21143. * <br/>Defaults to true.
  21144. * <br/>GridOptions.showGridFooter must also be set to true.
  21145. */
  21146. gridOptions.enableFooterTotalSelected = gridOptions.enableFooterTotalSelected !== false;
  21147. /**
  21148. * @ngdoc object
  21149. * @name isRowSelectable
  21150. * @propertyOf ui.grid.selection.api:GridOptions
  21151. * @description Makes it possible to specify a method that evaluates for each row and sets its "enableSelection" property.
  21152. */
  21153. gridOptions.isRowSelectable = angular.isDefined(gridOptions.isRowSelectable) ? gridOptions.isRowSelectable : angular.noop;
  21154. },
  21155. /**
  21156. * @ngdoc function
  21157. * @name toggleRowSelection
  21158. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21159. * @description Toggles row as selected or unselected
  21160. * @param {Grid} grid grid object
  21161. * @param {GridRow} row row to select or deselect
  21162. * @param {Event} event object if resulting from event
  21163. * @param {bool} multiSelect if false, only one row at time can be selected
  21164. * @param {bool} noUnselect if true then rows cannot be unselected
  21165. */
  21166. toggleRowSelection: function(grid, row, evt, multiSelect, noUnselect) {
  21167. var selected = row.isSelected;
  21168. if (row.enableSelection === false && !selected) {
  21169. return;
  21170. }
  21171. if (!multiSelect && !selected) {
  21172. service.clearSelectedRows(grid, evt);
  21173. } else if (!multiSelect && selected) {
  21174. var selectedRows = service.getSelectedRows(grid);
  21175. if (selectedRows.length > 1) {
  21176. selected = false; // Enable reselect of the row
  21177. service.clearSelectedRows(grid, evt);
  21178. }
  21179. }
  21180. if (selected && noUnselect) {
  21181. // don't deselect the row
  21182. } else {
  21183. row.setSelected(!selected);
  21184. if (row.isSelected === true) {
  21185. grid.selection.lastSelectedRow = row;
  21186. } else {
  21187. grid.selection.selectAll = false;
  21188. }
  21189. grid.api.selection.raise.rowSelectionChanged(row, evt);
  21190. }
  21191. },
  21192. /**
  21193. * @ngdoc function
  21194. * @name shiftSelect
  21195. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21196. * @description selects a group of rows from the last selected row using the shift key
  21197. * @param {Grid} grid grid object
  21198. * @param {GridRow} clicked row
  21199. * @param {Event} event object if raised from an event
  21200. * @param {bool} multiSelect if false, does nothing this is for multiSelect only
  21201. */
  21202. shiftSelect: function(grid, row, evt, multiSelect) {
  21203. if (!multiSelect) {
  21204. return;
  21205. }
  21206. var selectedRows = service.getSelectedRows(grid);
  21207. var fromRow = selectedRows.length > 0 ? grid.renderContainers.body.visibleRowCache.indexOf(grid.selection.lastSelectedRow) : 0;
  21208. var toRow = grid.renderContainers.body.visibleRowCache.indexOf(row);
  21209. //reverse select direction
  21210. if (fromRow > toRow) {
  21211. var tmp = fromRow;
  21212. fromRow = toRow;
  21213. toRow = tmp;
  21214. }
  21215. var changedRows = [];
  21216. for (var i = fromRow; i <= toRow; i++) {
  21217. var rowToSelect = grid.renderContainers.body.visibleRowCache[i];
  21218. if (rowToSelect) {
  21219. if (!rowToSelect.isSelected && rowToSelect.enableSelection !== false) {
  21220. rowToSelect.setSelected(true);
  21221. grid.selection.lastSelectedRow = rowToSelect;
  21222. service.decideRaiseSelectionEvent(grid, rowToSelect, changedRows, evt);
  21223. }
  21224. }
  21225. }
  21226. service.decideRaiseSelectionBatchEvent(grid, changedRows, evt);
  21227. },
  21228. /**
  21229. * @ngdoc function
  21230. * @name getSelectedRows
  21231. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21232. * @description Returns all the selected rows
  21233. * @param {Grid} grid grid object
  21234. */
  21235. getSelectedRows: function(grid) {
  21236. return grid.rows.filter(function(row) {
  21237. return row.isSelected;
  21238. });
  21239. },
  21240. /**
  21241. * @ngdoc function
  21242. * @name clearSelectedRows
  21243. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21244. * @description Clears all selected rows
  21245. * @param {Grid} grid grid object
  21246. * @param {Event} event object if raised from an event
  21247. */
  21248. clearSelectedRows: function(grid, evt) {
  21249. var changedRows = [];
  21250. service.getSelectedRows(grid).forEach(function(row) {
  21251. if (row.isSelected) {
  21252. row.setSelected(false);
  21253. service.decideRaiseSelectionEvent(grid, row, changedRows, evt);
  21254. }
  21255. });
  21256. service.decideRaiseSelectionBatchEvent(grid, changedRows, evt);
  21257. grid.selection.selectAll = false;
  21258. },
  21259. /**
  21260. * @ngdoc function
  21261. * @name decideRaiseSelectionEvent
  21262. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21263. * @description Decides whether to raise a single event or a batch event
  21264. * @param {Grid} grid grid object
  21265. * @param {GridRow} row row that has changed
  21266. * @param {array} changedRows an array to which we can append the changed
  21267. * @param {Event} event object if raised from an event
  21268. * row if we're doing batch events
  21269. */
  21270. decideRaiseSelectionEvent: function(grid, row, changedRows, evt) {
  21271. if (!grid.options.enableSelectionBatchEvent) {
  21272. grid.api.selection.raise.rowSelectionChanged(row, evt);
  21273. } else {
  21274. changedRows.push(row);
  21275. }
  21276. },
  21277. /**
  21278. * @ngdoc function
  21279. * @name raiseSelectionEvent
  21280. * @methodOf ui.grid.selection.service:uiGridSelectionService
  21281. * @description Decides whether we need to raise a batch event, and
  21282. * raises it if we do.
  21283. * @param {Grid} grid grid object
  21284. * @param {array} changedRows an array of changed rows, only populated
  21285. * @param {Event} event object if raised from an event
  21286. * if we're doing batch events
  21287. */
  21288. decideRaiseSelectionBatchEvent: function(grid, changedRows, evt) {
  21289. if (changedRows.length > 0) {
  21290. grid.api.selection.raise.rowSelectionChangedBatch(changedRows, evt);
  21291. }
  21292. }
  21293. };
  21294. return service;
  21295. }
  21296. ]);
  21297. /**
  21298. * @ngdoc directive
  21299. * @name ui.grid.selection.directive:uiGridSelection
  21300. * @element div
  21301. * @restrict A
  21302. *
  21303. * @description Adds selection features to grid
  21304. *
  21305. * @example
  21306. <example module="app">
  21307. <file name="app.js">
  21308. var app = angular.module('app', ['ui.grid', 'ui.grid.selection']);
  21309. app.controller('MainCtrl', ['$scope', function ($scope) {
  21310. $scope.data = [
  21311. { name: 'Bob', title: 'CEO' },
  21312. { name: 'Frank', title: 'Lowly Developer' }
  21313. ];
  21314. $scope.columnDefs = [
  21315. {name: 'name', enableCellEdit: true},
  21316. {name: 'title', enableCellEdit: true}
  21317. ];
  21318. }]);
  21319. </file>
  21320. <file name="index.html">
  21321. <div ng-controller="MainCtrl">
  21322. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-selection></div>
  21323. </div>
  21324. </file>
  21325. </example>
  21326. */
  21327. module.directive('uiGridSelection', ['uiGridSelectionConstants', 'uiGridSelectionService', '$templateCache', 'uiGridConstants',
  21328. function(uiGridSelectionConstants, uiGridSelectionService, $templateCache, uiGridConstants) {
  21329. return {
  21330. replace: true,
  21331. priority: 0,
  21332. require: '^uiGrid',
  21333. scope: false,
  21334. compile: function() {
  21335. return {
  21336. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  21337. uiGridSelectionService.initializeGrid(uiGridCtrl.grid);
  21338. if (uiGridCtrl.grid.options.enableRowHeaderSelection) {
  21339. var selectionRowHeaderDef = {
  21340. name: uiGridSelectionConstants.selectionRowHeaderColName,
  21341. displayName: '',
  21342. width: uiGridCtrl.grid.options.selectionRowHeaderWidth,
  21343. minWidth: 10,
  21344. cellTemplate: 'ui-grid/selectionRowHeader',
  21345. headerCellTemplate: 'ui-grid/selectionHeaderCell',
  21346. enableColumnResizing: false,
  21347. enableColumnMenu: false,
  21348. exporterSuppressExport: true,
  21349. allowCellFocus: true
  21350. };
  21351. uiGridCtrl.grid.addRowHeaderColumn(selectionRowHeaderDef);
  21352. }
  21353. var processorSet = false;
  21354. var processSelectableRows = function(rows) {
  21355. rows.forEach(function(row) {
  21356. row.enableSelection = uiGridCtrl.grid.options.isRowSelectable(row);
  21357. });
  21358. return rows;
  21359. };
  21360. var updateOptions = function() {
  21361. if (uiGridCtrl.grid.options.isRowSelectable !== angular.noop && processorSet !== true) {
  21362. uiGridCtrl.grid.registerRowsProcessor(processSelectableRows, 500);
  21363. processorSet = true;
  21364. }
  21365. };
  21366. updateOptions();
  21367. var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback(updateOptions, [uiGridConstants.dataChange.OPTIONS]);
  21368. $scope.$on('$destroy', dataChangeDereg);
  21369. },
  21370. post: function($scope, $elm, $attrs, uiGridCtrl) {
  21371. }
  21372. };
  21373. }
  21374. };
  21375. }
  21376. ]);
  21377. module.directive('uiGridSelectionRowHeaderButtons', ['$templateCache', 'uiGridSelectionService', 'gridUtil',
  21378. function($templateCache, uiGridSelectionService, gridUtil) {
  21379. return {
  21380. replace: true,
  21381. restrict: 'E',
  21382. template: $templateCache.get('ui-grid/selectionRowHeaderButtons'),
  21383. scope: false,
  21384. require: '^uiGrid',
  21385. link: function($scope, $elm, $attrs, uiGridCtrl) {
  21386. var self = uiGridCtrl.grid;
  21387. $scope.selectButtonClick = selectButtonClick;
  21388. self.appScope.selectButtonClick = selectButtonClick;
  21389. // $scope.row = { isSelected: false };
  21390. if (self.appScope.selected.items) {
  21391. for (var i = 0; i < self.appScope.selected.items.length; i++) {
  21392. if ($scope.row.entity.id == self.appScope.selected.items[i].id) {
  21393. for (var j = 0; j < self.rows.length; j++) {
  21394. if (self.rows[j].entity.id == $scope.row.entity.id) {
  21395. self.rows[j].isSelected = true;
  21396. }
  21397. }
  21398. $scope.row['isSelected'] = true;
  21399. }
  21400. }
  21401. }
  21402. // On IE, prevent mousedowns on the select button from starting a selection.
  21403. // If this is not done and you shift+click on another row, the browser will select a big chunk of text
  21404. if (gridUtil.detectBrowser() === 'ie') {
  21405. $elm.on('mousedown', selectButtonMouseDown);
  21406. }
  21407. function selectButtonClick(row, evt) {
  21408. evt.stopPropagation();
  21409. if (evt.shiftKey) {
  21410. uiGridSelectionService.shiftSelect(self, row, evt, self.options.multiSelect);
  21411. } else if (evt.ctrlKey || evt.metaKey) {
  21412. uiGridSelectionService.toggleRowSelection(self, row, evt, self.options.multiSelect, self.options.noUnselect);
  21413. } else {
  21414. uiGridSelectionService.toggleRowSelection(self, row, evt, (self.options.multiSelect && !self.options.modifierKeysToMultiSelect), self.options.noUnselect);
  21415. }
  21416. }
  21417. function selectButtonMouseDown(evt) {
  21418. if (evt.ctrlKey || evt.shiftKey) {
  21419. evt.target.onselectstart = function() { return false; };
  21420. window.setTimeout(function() { evt.target.onselectstart = null; }, 0);
  21421. }
  21422. }
  21423. }
  21424. };
  21425. }
  21426. ]);
  21427. module.directive('uiGridSelectionSelectAllButtons', ['$templateCache', 'uiGridSelectionService',
  21428. function($templateCache, uiGridSelectionService) {
  21429. return {
  21430. replace: true,
  21431. restrict: 'E',
  21432. template: $templateCache.get('ui-grid/selectionSelectAllButtons'),
  21433. scope: false,
  21434. link: function($scope, $elm, $attrs, uiGridCtrl) {
  21435. var self = $scope.col.grid;
  21436. $scope.headerButtonClick = function(row, evt) {
  21437. if (self.selection.selectAll) {
  21438. for (var i = 0; i < self.rows.length; i++) {
  21439. self.rows[i].isSelected = true;
  21440. }
  21441. uiGridSelectionService.clearSelectedRows(self, evt);
  21442. if (self.options.noUnselect) {
  21443. self.api.selection.selectRowByVisibleIndex(0, evt);
  21444. }
  21445. self.selection.selectAll = false;
  21446. } else {
  21447. if (self.options.multiSelect) {
  21448. self.api.selection.selectAllVisibleRows(evt);
  21449. self.selection.selectAll = true;
  21450. }
  21451. }
  21452. };
  21453. }
  21454. };
  21455. }
  21456. ]);
  21457. /**
  21458. * @ngdoc directive
  21459. * @name ui.grid.selection.directive:uiGridViewport
  21460. * @element div
  21461. *
  21462. * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used
  21463. * for the grid row
  21464. */
  21465. module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'uiGridSelectionConstants', 'gridUtil', '$parse', 'uiGridSelectionService',
  21466. function($compile, uiGridConstants, uiGridSelectionConstants, gridUtil, $parse, uiGridSelectionService) {
  21467. return {
  21468. priority: -200, // run after default directive
  21469. scope: false,
  21470. compile: function($elm, $attrs) {
  21471. var rowRepeatDiv = angular.element($elm.children().children()[0]);
  21472. var existingNgClass = rowRepeatDiv.attr("ng-class");
  21473. var newNgClass = '';
  21474. if (existingNgClass) {
  21475. newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-row-selected': row.isSelected}";
  21476. } else {
  21477. newNgClass = "{'ui-grid-row-selected': row.isSelected}";
  21478. }
  21479. rowRepeatDiv.attr("ng-class", newNgClass);
  21480. return {
  21481. pre: function($scope, $elm, $attrs, controllers) {
  21482. },
  21483. post: function($scope, $elm, $attrs, controllers) {}
  21484. };
  21485. }
  21486. };
  21487. }
  21488. ]);
  21489. /**
  21490. * @ngdoc directive
  21491. * @name ui.grid.selection.directive:uiGridCell
  21492. * @element div
  21493. * @restrict A
  21494. *
  21495. * @description Stacks on top of ui.grid.uiGridCell to provide selection feature
  21496. */
  21497. module.directive('uiGridCell', ['$compile', 'uiGridConstants', 'uiGridSelectionConstants', 'gridUtil', '$parse', 'uiGridSelectionService', '$timeout',
  21498. function($compile, uiGridConstants, uiGridSelectionConstants, gridUtil, $parse, uiGridSelectionService, $timeout) {
  21499. return {
  21500. priority: -200, // run after default uiGridCell directive
  21501. restrict: 'A',
  21502. require: '?^uiGrid',
  21503. scope: false,
  21504. link: function($scope, $elm, $attrs, uiGridCtrl) {
  21505. var touchStartTime = 0;
  21506. var touchTimeout = 300;
  21507. // Bind to keydown events in the render container
  21508. if (uiGridCtrl.grid.api.cellNav) {
  21509. uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function(evt, rowCol) {
  21510. if (rowCol === null ||
  21511. rowCol.row !== $scope.row ||
  21512. rowCol.col !== $scope.col) {
  21513. return;
  21514. }
  21515. if (evt.keyCode === 32 && $scope.col.colDef.name === "selectionRowHeaderCol") {
  21516. uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect);
  21517. $scope.$apply();
  21518. }
  21519. // uiGridCellNavService.scrollToIfNecessary(uiGridCtrl.grid, rowCol.row, rowCol.col);
  21520. });
  21521. }
  21522. //$elm.bind('keydown', function (evt) {
  21523. // if (evt.keyCode === 32 && $scope.col.colDef.name === "selectionRowHeaderCol") {
  21524. // uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect);
  21525. // $scope.$apply();
  21526. // }
  21527. //});
  21528. var selectCells = function(evt) {
  21529. // if we get a click, then stop listening for touchend
  21530. $elm.off('touchend', touchEnd);
  21531. if (evt.shiftKey) {
  21532. uiGridSelectionService.shiftSelect($scope.grid, $scope.row, evt, $scope.grid.options.multiSelect);
  21533. } else if (evt.ctrlKey || evt.metaKey) {
  21534. uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, $scope.grid.options.multiSelect, $scope.grid.options.noUnselect);
  21535. } else {
  21536. uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect);
  21537. }
  21538. $scope.$apply();
  21539. // don't re-enable the touchend handler for a little while - some devices generate both, and it will
  21540. // take a little while to move your hand from the mouse to the screen if you have both modes of input
  21541. $timeout(function() {
  21542. $elm.on('touchend', touchEnd);
  21543. }, touchTimeout);
  21544. };
  21545. var touchStart = function(evt) {
  21546. touchStartTime = (new Date()).getTime();
  21547. // if we get a touch event, then stop listening for click
  21548. $elm.off('click', selectCells);
  21549. };
  21550. var touchEnd = function(evt) {
  21551. var touchEndTime = (new Date()).getTime();
  21552. var touchTime = touchEndTime - touchStartTime;
  21553. if (touchTime < touchTimeout) {
  21554. // short touch
  21555. selectCells(evt);
  21556. }
  21557. // don't re-enable the click handler for a little while - some devices generate both, and it will
  21558. // take a little while to move your hand from the screen to the mouse if you have both modes of input
  21559. $timeout(function() {
  21560. $elm.on('click', selectCells);
  21561. }, touchTimeout);
  21562. };
  21563. function registerRowSelectionEvents() {
  21564. if ($scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection) {
  21565. $elm.addClass('ui-grid-disable-selection');
  21566. $elm.on('touchstart', touchStart);
  21567. $elm.on('touchend', touchEnd);
  21568. $elm.on('click', selectCells);
  21569. $scope.registered = true;
  21570. }
  21571. }
  21572. function deregisterRowSelectionEvents() {
  21573. if ($scope.registered) {
  21574. $elm.removeClass('ui-grid-disable-selection');
  21575. $elm.off('touchstart', touchStart);
  21576. $elm.off('touchend', touchEnd);
  21577. $elm.off('click', selectCells);
  21578. $scope.registered = false;
  21579. }
  21580. }
  21581. registerRowSelectionEvents();
  21582. // register a dataChange callback so that we can change the selection configuration dynamically
  21583. // if the user changes the options
  21584. var dataChangeDereg = $scope.grid.registerDataChangeCallback(function() {
  21585. if ($scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection &&
  21586. !$scope.registered) {
  21587. registerRowSelectionEvents();
  21588. } else if ((!$scope.grid.options.enableRowSelection || !$scope.grid.options.enableFullRowSelection) &&
  21589. $scope.registered) {
  21590. deregisterRowSelectionEvents();
  21591. }
  21592. }, [uiGridConstants.dataChange.OPTIONS]);
  21593. $elm.on('$destroy', dataChangeDereg);
  21594. }
  21595. };
  21596. }
  21597. ]);
  21598. module.directive('uiGridGridFooter', ['$compile', 'uiGridConstants', 'gridUtil', function($compile, uiGridConstants, gridUtil) {
  21599. return {
  21600. restrict: 'EA',
  21601. replace: true,
  21602. priority: -1000,
  21603. require: '^uiGrid',
  21604. scope: true,
  21605. compile: function($elm, $attrs) {
  21606. return {
  21607. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  21608. if (!uiGridCtrl.grid.options.showGridFooter) {
  21609. return;
  21610. }
  21611. gridUtil.getTemplate('ui-grid/gridFooterSelectedItems')
  21612. .then(function(contents) {
  21613. var template = angular.element(contents);
  21614. var newElm = $compile(template)($scope);
  21615. angular.element($elm[0].getElementsByClassName('ui-grid-grid-footer')[0]).append(newElm);
  21616. });
  21617. },
  21618. post: function($scope, $elm, $attrs, controllers) {
  21619. }
  21620. };
  21621. }
  21622. };
  21623. }]);
  21624. })();
  21625. (function() {
  21626. 'use strict';
  21627. /**
  21628. * @ngdoc overview
  21629. * @name ui.grid.treeBase
  21630. * @description
  21631. *
  21632. * # ui.grid.treeBase
  21633. *
  21634. * <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>
  21635. *
  21636. * This module provides base tree handling functions that are shared by other features, notably grouping
  21637. * and treeView. It provides a tree view of the data, with nodes in that
  21638. * tree and leaves.
  21639. *
  21640. * Design information:
  21641. * -------------------
  21642. *
  21643. * The raw data that is provided must come with a $$treeLevel on any non-leaf node. Grouping will create
  21644. * these on all the group header rows, treeView will expect these to be set in the raw data by the user.
  21645. * TreeBase will run a rowsProcessor that:
  21646. * - builds `treeBase.tree` out of the provided rows
  21647. * - permits a recursive sort of the tree
  21648. * - maintains the expand/collapse state of each node
  21649. * - provides the expand/collapse all button and the expand/collapse buttons
  21650. * - maintains the count of children for each node
  21651. *
  21652. * Each row is updated with a link to the tree node that represents it. Refer {@link ui.grid.treeBase.grid:treeBase.tree tree documentation}
  21653. * for information.
  21654. *
  21655. * TreeBase adds information to the rows
  21656. * - treeLevel: if present and > -1 tells us the level (level 0 is the top level)
  21657. * - treeNode: pointer to the node in the grid.treeBase.tree that refers
  21658. * to this row, allowing us to manipulate the state
  21659. *
  21660. * Since the logic is baked into the rowsProcessors, it should get triggered whenever
  21661. * row order or filtering or anything like that is changed. We recall the expanded state
  21662. * across invocations of the rowsProcessors by the reference to the treeNode on the individual
  21663. * rows. We rebuild the tree itself quite frequently, when we do this we use the saved treeNodes to
  21664. * get the state, but we overwrite the other data in that treeNode.
  21665. *
  21666. * By default rows are collapsed, which means all data rows have their visible property
  21667. * set to false, and only level 0 group rows are set to visible.
  21668. *
  21669. * We rely on the rowsProcessors to do the actual expanding and collapsing, so we set the flags we want into
  21670. * grid.treeBase.tree, then call refresh. This is because we can't easily change the visible
  21671. * row cache without calling the processors, and once we've built the logic into the rowProcessors we may as
  21672. * well use it all the time.
  21673. *
  21674. * Tree base provides sorting (on non-grouped columns).
  21675. *
  21676. * Sorting works in two passes. The standard sorting is performed for any columns that are important to building
  21677. * the tree (for example, any grouped columns). Then after the tree is built, a recursive tree sort is performed
  21678. * for the remaining sort columns (including the original sort) - these columns are sorted within each tree level
  21679. * (so all the level 1 nodes are sorted, then all the level 2 nodes within each level 1 node etc).
  21680. *
  21681. * To achieve this we make use of the `ignoreSort` property on the sort configuration. The parent feature (treeView or grouping)
  21682. * must provide a rowsProcessor that runs with very low priority (typically in the 60-65 range), and that sets
  21683. * the `ignoreSort`on any sort that it wants to run on the tree. TreeBase will clear the ignoreSort on all sorts - so it
  21684. * will turn on any sorts that haven't run. It will then call a recursive sort on the tree.
  21685. *
  21686. * Tree base provides treeAggregation. It checks the treeAggregation configuration on each column, and aggregates based on
  21687. * the logic provided as it builds the tree. Footer aggregation from the uiGrid core should not be used with treeBase aggregation,
  21688. * since it operates on all visible rows, as opposed to to leaf nodes only. Setting `showColumnFooter: true` will show the
  21689. * treeAggregations in the column footer. Aggregation information will be collected in the format:
  21690. *
  21691. * ```
  21692. * {
  21693. * type: 'count',
  21694. * value: 4,
  21695. * label: 'count: ',
  21696. * rendered: 'count: 4'
  21697. * }
  21698. * ```
  21699. *
  21700. * A callback is provided to format the value once it is finalised (aka a valueFilter).
  21701. *
  21702. * <br/>
  21703. * <br/>
  21704. *
  21705. * <div doc-module-components="ui.grid.treeBase"></div>
  21706. */
  21707. var module = angular.module('ui.grid.treeBase', ['ui.grid']);
  21708. /**
  21709. * @ngdoc object
  21710. * @name ui.grid.treeBase.constant:uiGridTreeBaseConstants
  21711. *
  21712. * @description constants available in treeBase module.
  21713. *
  21714. * These constants are manually copied into grouping and treeView,
  21715. * as I haven't found a way to simply include them, and it's not worth
  21716. * investing time in for something that changes very infrequently.
  21717. *
  21718. */
  21719. module.constant('uiGridTreeBaseConstants', {
  21720. featureName: "treeBase",
  21721. rowHeaderColName: 'treeBaseRowHeaderCol',
  21722. EXPANDED: 'expanded',
  21723. COLLAPSED: 'collapsed',
  21724. aggregation: {
  21725. COUNT: 'count',
  21726. SUM: 'sum',
  21727. MAX: 'max',
  21728. MIN: 'min',
  21729. AVG: 'avg'
  21730. }
  21731. });
  21732. /**
  21733. * @ngdoc service
  21734. * @name ui.grid.treeBase.service:uiGridTreeBaseService
  21735. *
  21736. * @description Services for treeBase feature
  21737. */
  21738. /**
  21739. * @ngdoc object
  21740. * @name ui.grid.treeBase.api:ColumnDef
  21741. *
  21742. * @description ColumnDef for tree feature, these are available to be
  21743. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  21744. */
  21745. module.service('uiGridTreeBaseService', ['$q', 'uiGridTreeBaseConstants', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'rowSorter',
  21746. function($q, uiGridTreeBaseConstants, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants, rowSorter) {
  21747. var service = {
  21748. initializeGrid: function(grid, $scope) {
  21749. //add feature namespace and any properties to grid for needed
  21750. /**
  21751. * @ngdoc object
  21752. * @name ui.grid.treeBase.grid:treeBase
  21753. *
  21754. * @description Grid properties and functions added for treeBase
  21755. */
  21756. grid.treeBase = {};
  21757. /**
  21758. * @ngdoc property
  21759. * @propertyOf ui.grid.treeBase.grid:treeBase
  21760. * @name numberLevels
  21761. *
  21762. * @description Total number of tree levels currently used, calculated by the rowsProcessor by
  21763. * retaining the highest tree level it sees
  21764. */
  21765. grid.treeBase.numberLevels = 0;
  21766. /**
  21767. * @ngdoc property
  21768. * @propertyOf ui.grid.treeBase.grid:treeBase
  21769. * @name expandAll
  21770. *
  21771. * @description Whether or not the expandAll box is selected
  21772. */
  21773. grid.treeBase.expandAll = false;
  21774. /**
  21775. * @ngdoc property
  21776. * @propertyOf ui.grid.treeBase.grid:treeBase
  21777. * @name tree
  21778. *
  21779. * @description Tree represented as a nested array that holds the state of each node, along with a
  21780. * pointer to the row. The array order is material - we will display the children in the order
  21781. * they are stored in the array
  21782. *
  21783. * Each node stores:
  21784. *
  21785. * - the state of this node
  21786. * - an array of children of this node
  21787. * - a pointer to the parent of this node (reverse pointer, allowing us to walk up the tree)
  21788. * - the number of children of this node
  21789. * - aggregation information calculated from the nodes
  21790. *
  21791. * ```
  21792. * [{
  21793. * state: 'expanded',
  21794. * row: <reference to row>,
  21795. * parentRow: null,
  21796. * aggregations: [{
  21797. * type: 'count',
  21798. * col: <gridCol>,
  21799. * value: 2,
  21800. * label: 'count: ',
  21801. * rendered: 'count: 2'
  21802. * }],
  21803. * children: [
  21804. * {
  21805. * state: 'expanded',
  21806. * row: <reference to row>,
  21807. * parentRow: <reference to row>,
  21808. * aggregations: [{
  21809. * type: 'count',
  21810. * col: '<gridCol>,
  21811. * value: 4,
  21812. * label: 'count: ',
  21813. * rendered: 'count: 4'
  21814. * }],
  21815. * children: [
  21816. * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
  21817. * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> },
  21818. * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
  21819. * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }
  21820. * ]
  21821. * },
  21822. * {
  21823. * state: 'collapsed',
  21824. * row: <reference to row>,
  21825. * parentRow: <reference to row>,
  21826. * aggregations: [{
  21827. * type: 'count',
  21828. * col: <gridCol>,
  21829. * value: 3,
  21830. * label: 'count: ',
  21831. * rendered: 'count: 3'
  21832. * }],
  21833. * children: [
  21834. * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> },
  21835. * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> },
  21836. * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }
  21837. * ]
  21838. * }
  21839. * ]
  21840. * }, {<another level 0 node maybe>} ]
  21841. * ```
  21842. * Missing state values are false - meaning they aren't expanded.
  21843. *
  21844. * This is used because the rowProcessors run every time the grid is refreshed, so
  21845. * we'd lose the expanded state every time the grid was refreshed. This instead gives
  21846. * us a reliable lookup that persists across rowProcessors.
  21847. *
  21848. * This tree is rebuilt every time we run the rowsProcessors. Since each row holds a pointer
  21849. * to it's tree node we can persist expand/collapse state across calls to rowsProcessor, we discard
  21850. * all transient information on the tree (children, childCount) and recalculate it
  21851. *
  21852. */
  21853. grid.treeBase.tree = {};
  21854. service.defaultGridOptions(grid.options);
  21855. grid.registerRowsProcessor(service.treeRows, 410);
  21856. grid.registerColumnBuilder(service.treeBaseColumnBuilder);
  21857. service.createRowHeader(grid);
  21858. /**
  21859. * @ngdoc object
  21860. * @name ui.grid.treeBase.api:PublicApi
  21861. *
  21862. * @description Public Api for treeBase feature
  21863. */
  21864. var publicApi = {
  21865. events: {
  21866. treeBase: {
  21867. /**
  21868. * @ngdoc event
  21869. * @eventOf ui.grid.treeBase.api:PublicApi
  21870. * @name rowExpanded
  21871. * @description raised whenever a row is expanded. If you are dynamically
  21872. * rendering your tree you can listen to this event, and then retrieve
  21873. * the children of this row and load them into the grid data.
  21874. *
  21875. * When the data is loaded the grid will automatically refresh to show these new rows
  21876. *
  21877. * <pre>
  21878. * gridApi.treeBase.on.rowExpanded(scope,function(row){})
  21879. * </pre>
  21880. * @param {gridRow} row the row that was expanded. You can also
  21881. * retrieve the grid from this row with row.grid
  21882. */
  21883. rowExpanded: {},
  21884. /**
  21885. * @ngdoc event
  21886. * @eventOf ui.grid.treeBase.api:PublicApi
  21887. * @name rowCollapsed
  21888. * @description raised whenever a row is collapsed. Doesn't really have
  21889. * a purpose at the moment, included for symmetry
  21890. *
  21891. * <pre>
  21892. * gridApi.treeBase.on.rowCollapsed(scope,function(row){})
  21893. * </pre>
  21894. * @param {gridRow} row the row that was collapsed. You can also
  21895. * retrieve the grid from this row with row.grid
  21896. */
  21897. rowCollapsed: {}
  21898. }
  21899. },
  21900. methods: {
  21901. treeBase: {
  21902. /**
  21903. * @ngdoc function
  21904. * @name expandAllRows
  21905. * @methodOf ui.grid.treeBase.api:PublicApi
  21906. * @description Expands all tree rows
  21907. */
  21908. expandAllRows: function() {
  21909. service.expandAllRows(grid);
  21910. },
  21911. /**
  21912. * @ngdoc function
  21913. * @name collapseAllRows
  21914. * @methodOf ui.grid.treeBase.api:PublicApi
  21915. * @description collapse all tree rows
  21916. */
  21917. collapseAllRows: function() {
  21918. service.collapseAllRows(grid);
  21919. },
  21920. /**
  21921. * @ngdoc function
  21922. * @name toggleRowTreeState
  21923. * @methodOf ui.grid.treeBase.api:PublicApi
  21924. * @description call expand if the row is collapsed, collapse if it is expanded
  21925. * @param {gridRow} row the row you wish to toggle
  21926. */
  21927. toggleRowTreeState: function(row) {
  21928. service.toggleRowTreeState(grid, row);
  21929. },
  21930. /**
  21931. * @ngdoc function
  21932. * @name expandRow
  21933. * @methodOf ui.grid.treeBase.api:PublicApi
  21934. * @description expand the immediate children of the specified row
  21935. * @param {gridRow} row the row you wish to expand
  21936. */
  21937. expandRow: function(row) {
  21938. service.expandRow(grid, row);
  21939. },
  21940. /**
  21941. * @ngdoc function
  21942. * @name expandRowChildren
  21943. * @methodOf ui.grid.treeBase.api:PublicApi
  21944. * @description expand all children of the specified row
  21945. * @param {gridRow} row the row you wish to expand
  21946. */
  21947. expandRowChildren: function(row) {
  21948. service.expandRowChildren(grid, row);
  21949. },
  21950. /**
  21951. * @ngdoc function
  21952. * @name collapseRow
  21953. * @methodOf ui.grid.treeBase.api:PublicApi
  21954. * @description collapse the specified row. When
  21955. * you expand the row again, all grandchildren will retain their state
  21956. * @param {gridRow} row the row you wish to collapse
  21957. */
  21958. collapseRow: function(row) {
  21959. service.collapseRow(grid, row);
  21960. },
  21961. /**
  21962. * @ngdoc function
  21963. * @name collapseRowChildren
  21964. * @methodOf ui.grid.treeBase.api:PublicApi
  21965. * @description collapse all children of the specified row. When
  21966. * you expand the row again, all grandchildren will be collapsed
  21967. * @param {gridRow} row the row you wish to collapse children for
  21968. */
  21969. collapseRowChildren: function(row) {
  21970. service.collapseRowChildren(grid, row);
  21971. },
  21972. /**
  21973. * @ngdoc function
  21974. * @name getTreeState
  21975. * @methodOf ui.grid.treeBase.api:PublicApi
  21976. * @description Get the tree state for this grid,
  21977. * used by the saveState feature
  21978. * Returned treeState as an object
  21979. * `{ expandedState: { uid: 'expanded', uid: 'collapsed' } }`
  21980. * where expandedState is a hash of row uid and the current expanded state
  21981. *
  21982. * @returns {object} tree state
  21983. *
  21984. * TODO - this needs work - we need an identifier that persists across instantiations,
  21985. * not uid. This really means we need a row identity defined, but that won't work for
  21986. * grouping. Perhaps this needs to be moved up to treeView and grouping, rather than
  21987. * being in base.
  21988. */
  21989. getTreeExpandedState: function() {
  21990. return { expandedState: service.getTreeState(grid) };
  21991. },
  21992. /**
  21993. * @ngdoc function
  21994. * @name setTreeState
  21995. * @methodOf ui.grid.treeBase.api:PublicApi
  21996. * @description Set the expanded states of the tree
  21997. * @param {object} config the config you want to apply, in the format
  21998. * provided by getTreeState
  21999. */
  22000. setTreeState: function(config) {
  22001. service.setTreeState(grid, config);
  22002. },
  22003. /**
  22004. * @ngdoc function
  22005. * @name getRowChildren
  22006. * @methodOf ui.grid.treeBase.api:PublicApi
  22007. * @description Get the children of the specified row
  22008. * @param {GridRow} row the row you want the children of
  22009. * @returns {Array} array of children of this row, the children
  22010. * are all gridRows
  22011. */
  22012. getRowChildren: function(row) {
  22013. return row.treeNode.children.map(function(childNode) {
  22014. return childNode.row;
  22015. });
  22016. }
  22017. }
  22018. }
  22019. };
  22020. grid.api.registerEventsFromObject(publicApi.events);
  22021. grid.api.registerMethodsFromObject(publicApi.methods);
  22022. },
  22023. defaultGridOptions: function(gridOptions) {
  22024. //default option to true unless it was explicitly set to false
  22025. /**
  22026. * @ngdoc object
  22027. * @name ui.grid.treeBase.api:GridOptions
  22028. *
  22029. * @description GridOptions for treeBase feature, these are available to be
  22030. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  22031. */
  22032. /**
  22033. * @ngdoc object
  22034. * @name treeRowHeaderBaseWidth
  22035. * @propertyOf ui.grid.treeBase.api:GridOptions
  22036. * @description Base width of the tree header, provides for a single level of tree. This
  22037. * is incremented by `treeIndent` for each extra level
  22038. * <br/>Defaults to 30
  22039. */
  22040. gridOptions.treeRowHeaderBaseWidth = gridOptions.treeRowHeaderBaseWidth || 34;
  22041. /**
  22042. * @ngdoc object
  22043. * @name treeIndent
  22044. * @propertyOf ui.grid.treeBase.api:GridOptions
  22045. * @description Number of pixels of indent for the icon at each tree level, wider indents are visually more pleasing,
  22046. * but will make the tree row header wider
  22047. * <br/>Defaults to 10
  22048. */
  22049. gridOptions.treeIndent = gridOptions.treeIndent || 10;
  22050. /**
  22051. * @ngdoc object
  22052. * @name showTreeRowHeader
  22053. * @propertyOf ui.grid.treeBase.api:GridOptions
  22054. * @description If set to false, don't create the row header. Youll need to programatically control the expand
  22055. * states
  22056. * <br/>Defaults to true
  22057. */
  22058. gridOptions.showTreeRowHeader = gridOptions.showTreeRowHeader !== false;
  22059. /**
  22060. * @ngdoc object
  22061. * @name showTreeExpandNoChildren
  22062. * @propertyOf ui.grid.treeBase.api:GridOptions
  22063. * @description If set to true, show the expand/collapse button even if there are no
  22064. * children of a node. You'd use this if you're planning to dynamically load the children
  22065. *
  22066. * <br/>Defaults to true, grouping overrides to false
  22067. */
  22068. gridOptions.showTreeExpandNoChildren = gridOptions.showTreeExpandNoChildren !== false;
  22069. /**
  22070. * @ngdoc object
  22071. * @name treeRowHeaderAlwaysVisible
  22072. * @propertyOf ui.grid.treeBase.api:GridOptions
  22073. * @description If set to true, row header even if there are no tree nodes
  22074. *
  22075. * <br/>Defaults to true
  22076. */
  22077. gridOptions.treeRowHeaderAlwaysVisible = gridOptions.treeRowHeaderAlwaysVisible !== false;
  22078. /**
  22079. * @ngdoc object
  22080. * @name treeCustomAggregations
  22081. * @propertyOf ui.grid.treeBase.api:GridOptions
  22082. * @description Define custom aggregation functions. The properties of this object will be
  22083. * aggregation types available for use on columnDef with {@link ui.grid.treeBase.api:ColumnDef treeAggregationType} or through the column menu.
  22084. * If a function defined here uses the same name as one of the native aggregations, this one will take precedence.
  22085. * The object format is:
  22086. *
  22087. * <pre>
  22088. * {
  22089. * aggregationName: {
  22090. * label: (optional) string,
  22091. * aggregationFn: function( aggregation, fieldValue, numValue, row ){...},
  22092. * finalizerFn: (optional) function( aggregation ){...}
  22093. * },
  22094. * mean: {
  22095. * label: 'mean',
  22096. * aggregationFn: function( aggregation, fieldValue, numValue ){
  22097. * aggregation.count = (aggregation.count || 1) + 1;
  22098. * aggregation.sum = (aggregation.sum || 0) + numValue;
  22099. * },
  22100. * finalizerFn: function( aggregation ){
  22101. * aggregation.value = aggregation.sum / aggregation.count
  22102. * }
  22103. * }
  22104. * }
  22105. * </pre>
  22106. *
  22107. * <br/>The `finalizerFn` may be used to manipulate the value before rendering, or to
  22108. * apply a custom rendered value. If `aggregation.rendered` is left undefined, the value will be
  22109. * rendered. Note that the native aggregation functions use an `finalizerFn` to concatenate
  22110. * the label and the value.
  22111. *
  22112. * <br/>Defaults to {}
  22113. */
  22114. gridOptions.treeCustomAggregations = gridOptions.treeCustomAggregations || {};
  22115. },
  22116. /**
  22117. * @ngdoc function
  22118. * @name treeBaseColumnBuilder
  22119. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22120. * @description Sets the tree defaults based on the columnDefs
  22121. *
  22122. * @param {object} colDef columnDef we're basing on
  22123. * @param {GridCol} col the column we're to update
  22124. * @param {object} gridOptions the options we should use
  22125. * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved
  22126. */
  22127. treeBaseColumnBuilder: function(colDef, col, gridOptions) {
  22128. /**
  22129. * @ngdoc object
  22130. * @name customTreeAggregationFn
  22131. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22132. * @description A custom function that aggregates rows into some form of
  22133. * total. Aggregations run row-by-row, the function needs to be capable of
  22134. * creating a running total.
  22135. *
  22136. * The function will be provided the aggregation item (in which you can store running
  22137. * totals), the row value that is to be aggregated, and that same row value converted to
  22138. * a number (most aggregations work on numbers)
  22139. * @example
  22140. * <pre>
  22141. * customTreeAggregationFn = function ( aggregation, fieldValue, numValue, row ){
  22142. * // calculates the average of the squares of the values
  22143. * if ( typeof(aggregation.count) === 'undefined' ){
  22144. * aggregation.count = 0;
  22145. * }
  22146. * aggregation.count++;
  22147. *
  22148. * if ( !isNaN(numValue) ){
  22149. * if ( typeof(aggregation.total) === 'undefined' ){
  22150. * aggregation.total = 0;
  22151. * }
  22152. * aggregation.total = aggregation.total + numValue * numValue;
  22153. * }
  22154. *
  22155. * aggregation.value = aggregation.total / aggregation.count;
  22156. * }
  22157. * </pre>
  22158. * <br/>Defaults to undefined. May be overwritten by treeAggregationType, the two options should not be used together.
  22159. */
  22160. if (typeof(colDef.customTreeAggregationFn) !== 'undefined') {
  22161. col.treeAggregationFn = colDef.customTreeAggregationFn;
  22162. }
  22163. /**
  22164. * @ngdoc object
  22165. * @name treeAggregationType
  22166. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22167. * @description Use one of the native or grid-level aggregation methods for calculating aggregations on this column.
  22168. * Native method are in the constants file and include: SUM, COUNT, MIN, MAX, AVG. This may also be the property the
  22169. * name of an aggregation function defined with {@link ui.grid.treeBase.api:GridOptions treeCustomAggregations}.
  22170. *
  22171. * <pre>
  22172. * treeAggregationType = uiGridTreeBaseConstants.aggregation.SUM,
  22173. * }
  22174. * </pre>
  22175. *
  22176. * If you are using aggregations you should either:
  22177. *
  22178. * - also use grouping, in which case the aggregations are displayed in the group header, OR
  22179. * - use treeView, in which case you can set `treeAggregationUpdateEntity: true` in the colDef, and
  22180. * treeBase will store the aggregation information in the entity, or you can set `treeAggregationUpdateEntity: false`
  22181. * in the colDef, and you need to manual retrieve the calculated aggregations from the row.treeNode.aggregations
  22182. *
  22183. * <br/>Takes precendence over a treeAggregationFn, the two options should not be used together.
  22184. * <br/>Defaults to undefined.
  22185. */
  22186. if (typeof(colDef.treeAggregationType) !== 'undefined') {
  22187. col.treeAggregation = { type: colDef.treeAggregationType };
  22188. if (typeof(gridOptions.treeCustomAggregations[colDef.treeAggregationType]) !== 'undefined') {
  22189. col.treeAggregationFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].aggregationFn;
  22190. col.treeAggregationFinalizerFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].finalizerFn;
  22191. col.treeAggregation.label = gridOptions.treeCustomAggregations[colDef.treeAggregationType].label;
  22192. } else if (typeof(service.nativeAggregations()[colDef.treeAggregationType]) !== 'undefined') {
  22193. col.treeAggregationFn = service.nativeAggregations()[colDef.treeAggregationType].aggregationFn;
  22194. col.treeAggregation.label = service.nativeAggregations()[colDef.treeAggregationType].label;
  22195. }
  22196. }
  22197. /**
  22198. * @ngdoc object
  22199. * @name treeAggregationLabel
  22200. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22201. * @description A custom label to use for this aggregation. If provided we don't use native i18n.
  22202. */
  22203. if (typeof(colDef.treeAggregationLabel) !== 'undefined') {
  22204. if (typeof(col.treeAggregation) === 'undefined') {
  22205. col.treeAggregation = {};
  22206. }
  22207. col.treeAggregation.label = colDef.treeAggregationLabel;
  22208. }
  22209. /**
  22210. * @ngdoc object
  22211. * @name treeAggregationUpdateEntity
  22212. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22213. * @description Store calculated aggregations into the entity, allowing them
  22214. * to be displayed in the grid using a standard cellTemplate. This defaults to true,
  22215. * if you are using grouping then you shouldn't set it to false, as then the aggregations won't
  22216. * display.
  22217. *
  22218. * If you are using treeView in most cases you'll want to set this to true. This will result in
  22219. * getCellValue returning the aggregation rather than whatever was stored in the cell attribute on
  22220. * the entity. If you want to render the underlying entity value (and do something else with the aggregation)
  22221. * then you could use a custom cellTemplate to display `row.entity.myAttribute`, rather than using getCellValue.
  22222. *
  22223. * <br/>Defaults to true
  22224. *
  22225. * @example
  22226. * <pre>
  22227. * gridOptions.columns = [{
  22228. * name: 'myCol',
  22229. * treeAggregation: { type: uiGridTreeBaseConstants.aggregation.SUM },
  22230. * treeAggregationUpdateEntity: true
  22231. * cellTemplate: '<div>{{row.entity.myCol + " " + row.treeNode.aggregations[0].rendered}}</div>'
  22232. * }];
  22233. * </pre>
  22234. */
  22235. col.treeAggregationUpdateEntity = colDef.treeAggregationUpdateEntity !== false;
  22236. /**
  22237. * @ngdoc object
  22238. * @name customTreeAggregationFinalizerFn
  22239. * @propertyOf ui.grid.treeBase.api:ColumnDef
  22240. * @description A custom function that populates aggregation.rendered, this is called when
  22241. * a particular aggregation has been fully calculated, and we want to render the value.
  22242. *
  22243. * With the native aggregation options we just concatenate `aggregation.label` and
  22244. * `aggregation.value`, but if you wanted to apply a filter or otherwise manipulate the label
  22245. * or the value, you can do so with this function. This function will be called after the
  22246. * the default `finalizerFn`.
  22247. *
  22248. * @example
  22249. * <pre>
  22250. * customTreeAggregationFinalizerFn = function ( aggregation ){
  22251. * aggregation.rendered = aggregation.label + aggregation.value / 100 + '%';
  22252. * }
  22253. * </pre>
  22254. * <br/>Defaults to undefined.
  22255. */
  22256. if (typeof(col.customTreeAggregationFinalizerFn) === 'undefined') {
  22257. col.customTreeAggregationFinalizerFn = colDef.customTreeAggregationFinalizerFn;
  22258. }
  22259. },
  22260. /**
  22261. * @ngdoc function
  22262. * @name createRowHeader
  22263. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22264. * @description Create the rowHeader. If treeRowHeaderAlwaysVisible then
  22265. * set it to visible, otherwise set it to invisible
  22266. *
  22267. * @param {Grid} grid grid object
  22268. */
  22269. createRowHeader: function(grid) {
  22270. var rowHeaderColumnDef = {
  22271. name: uiGridTreeBaseConstants.rowHeaderColName,
  22272. displayName: '',
  22273. width: grid.options.treeRowHeaderBaseWidth,
  22274. minWidth: 10,
  22275. cellTemplate: 'ui-grid/treeBaseRowHeader',
  22276. headerCellTemplate: 'ui-grid/treeBaseHeaderCell',
  22277. enableColumnResizing: false,
  22278. enableColumnMenu: false,
  22279. exporterSuppressExport: true,
  22280. allowCellFocus: true
  22281. };
  22282. rowHeaderColumnDef.visible = grid.options.treeRowHeaderAlwaysVisible;
  22283. grid.addRowHeaderColumn(rowHeaderColumnDef);
  22284. },
  22285. /**
  22286. * @ngdoc function
  22287. * @name expandAllRows
  22288. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22289. * @description Expands all nodes in the tree
  22290. *
  22291. * @param {Grid} grid grid object
  22292. */
  22293. expandAllRows: function(grid) {
  22294. grid.treeBase.tree.forEach(function(node) {
  22295. service.setAllNodes(grid, node, uiGridTreeBaseConstants.EXPANDED);
  22296. });
  22297. grid.treeBase.expandAll = true;
  22298. grid.queueGridRefresh();
  22299. },
  22300. /**
  22301. * @ngdoc function
  22302. * @name collapseAllRows
  22303. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22304. * @description Collapses all nodes in the tree
  22305. *
  22306. * @param {Grid} grid grid object
  22307. */
  22308. collapseAllRows: function(grid) {
  22309. grid.treeBase.tree.forEach(function(node) {
  22310. service.setAllNodes(grid, node, uiGridTreeBaseConstants.COLLAPSED);
  22311. });
  22312. grid.treeBase.expandAll = false;
  22313. grid.queueGridRefresh();
  22314. },
  22315. /**
  22316. * @ngdoc function
  22317. * @name setAllNodes
  22318. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22319. * @description Works through a subset of grid.treeBase.rowExpandedStates, setting
  22320. * all child nodes (and their descendents) of the provided node to the given state.
  22321. *
  22322. * Calls itself recursively on all nodes so as to achieve this.
  22323. *
  22324. * @param {Grid} grid the grid we're operating on (so we can raise events)
  22325. * @param {object} treeNode a node in the tree that we want to update
  22326. * @param {string} targetState the state we want to set it to
  22327. */
  22328. setAllNodes: function(grid, treeNode, targetState) {
  22329. if (typeof(treeNode.state) !== 'undefined' && treeNode.state !== targetState) {
  22330. treeNode.state = targetState;
  22331. if (targetState === uiGridTreeBaseConstants.EXPANDED) {
  22332. grid.api.treeBase.raise.rowExpanded(treeNode.row);
  22333. } else {
  22334. grid.api.treeBase.raise.rowCollapsed(treeNode.row);
  22335. }
  22336. }
  22337. // set all child nodes
  22338. if (treeNode.children) {
  22339. treeNode.children.forEach(function(childNode) {
  22340. service.setAllNodes(grid, childNode, targetState);
  22341. });
  22342. }
  22343. },
  22344. /**
  22345. * @ngdoc function
  22346. * @name toggleRowTreeState
  22347. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22348. * @description Toggles the expand or collapse state of this grouped row, if
  22349. * it's a parent row
  22350. *
  22351. * @param {Grid} grid grid object
  22352. * @param {GridRow} row the row we want to toggle
  22353. */
  22354. toggleRowTreeState: function(grid, row) {
  22355. if (typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0) {
  22356. return;
  22357. }
  22358. if (row.treeNode.state === uiGridTreeBaseConstants.EXPANDED) {
  22359. service.collapseRow(grid, row);
  22360. } else {
  22361. service.expandRow(grid, row);
  22362. }
  22363. grid.queueGridRefresh();
  22364. },
  22365. /**
  22366. * @ngdoc function
  22367. * @name expandRow
  22368. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22369. * @description Expands this specific row, showing only immediate children.
  22370. *
  22371. * @param {Grid} grid grid object
  22372. * @param {GridRow} row the row we want to expand
  22373. */
  22374. expandRow: function(grid, row) {
  22375. if (typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0) {
  22376. return;
  22377. }
  22378. if (row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED) {
  22379. row.treeNode.state = uiGridTreeBaseConstants.EXPANDED;
  22380. grid.api.treeBase.raise.rowExpanded(row);
  22381. grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
  22382. grid.queueGridRefresh();
  22383. }
  22384. },
  22385. /**
  22386. * @ngdoc function
  22387. * @name expandRowChildren
  22388. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22389. * @description Expands this specific row, showing all children.
  22390. *
  22391. * @param {Grid} grid grid object
  22392. * @param {GridRow} row the row we want to expand
  22393. */
  22394. expandRowChildren: function(grid, row) {
  22395. if (typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0) {
  22396. return;
  22397. }
  22398. service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.EXPANDED);
  22399. grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
  22400. grid.queueGridRefresh();
  22401. },
  22402. /**
  22403. * @ngdoc function
  22404. * @name collapseRow
  22405. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22406. * @description Collapses this specific row
  22407. *
  22408. * @param {Grid} grid grid object
  22409. * @param {GridRow} row the row we want to collapse
  22410. */
  22411. collapseRow: function(grid, row) {
  22412. if (typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0) {
  22413. return;
  22414. }
  22415. if (row.treeNode.state !== uiGridTreeBaseConstants.COLLAPSED) {
  22416. row.treeNode.state = uiGridTreeBaseConstants.COLLAPSED;
  22417. grid.treeBase.expandAll = false;
  22418. grid.api.treeBase.raise.rowCollapsed(row);
  22419. grid.queueGridRefresh();
  22420. }
  22421. },
  22422. /**
  22423. * @ngdoc function
  22424. * @name collapseRowChildren
  22425. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22426. * @description Collapses this specific row and all children
  22427. *
  22428. * @param {Grid} grid grid object
  22429. * @param {GridRow} row the row we want to collapse
  22430. */
  22431. collapseRowChildren: function(grid, row) {
  22432. if (typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0) {
  22433. return;
  22434. }
  22435. service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.COLLAPSED);
  22436. grid.treeBase.expandAll = false;
  22437. grid.queueGridRefresh();
  22438. },
  22439. /**
  22440. * @ngdoc function
  22441. * @name allExpanded
  22442. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22443. * @description Returns true if all rows are expanded, false
  22444. * if they're not. Walks the tree to determine this. Used
  22445. * to set the expandAll state.
  22446. *
  22447. * If the node has no children, then return true (it's immaterial
  22448. * whether it is expanded). If the node has children, then return
  22449. * false if this node is collapsed, or if any child node is not all expanded
  22450. *
  22451. * @param {object} tree the grid to check
  22452. * @returns {boolean} whether or not the tree is all expanded
  22453. */
  22454. allExpanded: function(tree) {
  22455. var allExpanded = true;
  22456. tree.forEach(function(node) {
  22457. if (!service.allExpandedInternal(node)) {
  22458. allExpanded = false;
  22459. }
  22460. });
  22461. return allExpanded;
  22462. },
  22463. allExpandedInternal: function(treeNode) {
  22464. if (treeNode.children && treeNode.children.length > 0) {
  22465. if (treeNode.state === uiGridTreeBaseConstants.COLLAPSED) {
  22466. return false;
  22467. }
  22468. var allExpanded = true;
  22469. treeNode.children.forEach(function(node) {
  22470. if (!service.allExpandedInternal(node)) {
  22471. allExpanded = false;
  22472. }
  22473. });
  22474. return allExpanded;
  22475. } else {
  22476. return true;
  22477. }
  22478. },
  22479. /**
  22480. * @ngdoc function
  22481. * @name treeRows
  22482. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22483. * @description The rowProcessor that adds the nodes to the tree, and sets the visible
  22484. * state of each row based on it's parent state
  22485. *
  22486. * Assumes it is always called after the sorting processor, and the grouping processor if there is one.
  22487. * Performs any tree sorts itself after having built the tree
  22488. *
  22489. * Processes all the rows in order, setting the group level based on the $$treeLevel in the associated
  22490. * entity, and setting the visible state based on the parent's state.
  22491. *
  22492. * Calculates the deepest level of tree whilst it goes, and updates that so that the header column can be correctly
  22493. * sized.
  22494. *
  22495. * Aggregates if necessary along the way.
  22496. *
  22497. * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor
  22498. * @returns {array} the updated rows
  22499. */
  22500. treeRows: function(renderableRows) {
  22501. if (renderableRows.length === 0) {
  22502. return renderableRows;
  22503. }
  22504. var grid = this;
  22505. var currentLevel = 0;
  22506. var currentState = uiGridTreeBaseConstants.EXPANDED;
  22507. var parents = [];
  22508. grid.treeBase.tree = service.createTree(grid, renderableRows);
  22509. service.updateRowHeaderWidth(grid);
  22510. service.sortTree(grid);
  22511. service.fixFilter(grid);
  22512. return service.renderTree(grid.treeBase.tree);
  22513. },
  22514. /**
  22515. * @ngdoc function
  22516. * @name createOrUpdateRowHeaderWidth
  22517. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22518. * @description Calculates the rowHeader width.
  22519. *
  22520. * If rowHeader is always present, updates the width.
  22521. *
  22522. * If rowHeader is only sometimes present (`treeRowHeaderAlwaysVisible: false`), determines whether there
  22523. * should be one, then creates or removes it as appropriate, with the created rowHeader having the
  22524. * right width.
  22525. *
  22526. * If there's never a rowHeader then never creates one: `showTreeRowHeader: false`
  22527. *
  22528. * @param {Grid} grid the grid we want to set the row header on
  22529. */
  22530. updateRowHeaderWidth: function(grid) {
  22531. var rowHeader = grid.getColumn(uiGridTreeBaseConstants.rowHeaderColName);
  22532. var newWidth = grid.options.treeRowHeaderBaseWidth + grid.options.treeIndent * Math.max(grid.treeBase.numberLevels - 1, 0);
  22533. if (rowHeader && newWidth !== rowHeader.width) {
  22534. rowHeader.width = newWidth;
  22535. grid.queueRefresh();
  22536. }
  22537. var newVisibility = true;
  22538. if (grid.options.showTreeRowHeader === false) {
  22539. newVisibility = false;
  22540. }
  22541. if (grid.options.treeRowHeaderAlwaysVisible === false && grid.treeBase.numberLevels <= 0) {
  22542. newVisibility = false;
  22543. }
  22544. if (rowHeader.visible !== newVisibility) {
  22545. rowHeader.visible = newVisibility;
  22546. rowHeader.colDef.visible = newVisibility;
  22547. grid.queueGridRefresh();
  22548. }
  22549. },
  22550. /**
  22551. * @ngdoc function
  22552. * @name renderTree
  22553. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22554. * @description Creates an array of rows based on the tree, exporting only
  22555. * the visible nodes and leaves
  22556. *
  22557. * @param {array} nodeList the list of nodes - can be grid.treeBase.tree, or can be node.children when
  22558. * we're calling recursively
  22559. * @returns {array} renderable rows
  22560. */
  22561. renderTree: function(nodeList) {
  22562. var renderableRows = [];
  22563. nodeList.forEach(function(node) {
  22564. if (node.row.visible) {
  22565. renderableRows.push(node.row);
  22566. }
  22567. if (node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0) {
  22568. renderableRows = renderableRows.concat(service.renderTree(node.children));
  22569. }
  22570. });
  22571. return renderableRows;
  22572. },
  22573. /**
  22574. * @ngdoc function
  22575. * @name createTree
  22576. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22577. * @description Creates a tree from the renderableRows
  22578. *
  22579. * @param {Grid} grid the grid
  22580. * @param {array} renderableRows the rows we want to create a tree from
  22581. * @returns {object} the tree we've build
  22582. */
  22583. createTree: function(grid, renderableRows) {
  22584. var currentLevel = -1;
  22585. var parents = [];
  22586. var currentState;
  22587. grid.treeBase.tree = [];
  22588. grid.treeBase.numberLevels = 0;
  22589. var aggregations = service.getAggregations(grid);
  22590. var createNode = function(row) {
  22591. if (typeof(row.entity.$$treeLevel) !== 'undefined' && row.treeLevel !== row.entity.$$treeLevel) {
  22592. row.treeLevel = row.entity.$$treeLevel;
  22593. }
  22594. if (row.treeLevel <= currentLevel) {
  22595. // pop any levels that aren't parents of this level, formatting the aggregation at the same time
  22596. while (row.treeLevel <= currentLevel) {
  22597. var lastParent = parents.pop();
  22598. service.finaliseAggregations(lastParent);
  22599. currentLevel--;
  22600. }
  22601. // reset our current state based on the new parent, set to expanded if this is a level 0 node
  22602. if (parents.length > 0) {
  22603. currentState = service.setCurrentState(parents);
  22604. } else {
  22605. currentState = uiGridTreeBaseConstants.EXPANDED;
  22606. }
  22607. }
  22608. // aggregate if this is a leaf node
  22609. if ((typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0) && row.visible) {
  22610. service.aggregate(grid, row, parents);
  22611. }
  22612. // add this node to the tree
  22613. service.addOrUseNode(grid, row, parents, aggregations);
  22614. if (typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0) {
  22615. parents.push(row);
  22616. currentLevel++;
  22617. currentState = service.setCurrentState(parents);
  22618. }
  22619. // update the tree number of levels, so we can set header width if we need to
  22620. if (grid.treeBase.numberLevels < row.treeLevel + 1) {
  22621. grid.treeBase.numberLevels = row.treeLevel + 1;
  22622. }
  22623. };
  22624. renderableRows.forEach(createNode);
  22625. // finalise remaining aggregations
  22626. while (parents.length > 0) {
  22627. var lastParent = parents.pop();
  22628. service.finaliseAggregations(lastParent);
  22629. }
  22630. return grid.treeBase.tree;
  22631. },
  22632. /**
  22633. * @ngdoc function
  22634. * @name addOrUseNode
  22635. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22636. * @description Creates a tree node for this row. If this row already has a treeNode
  22637. * recorded against it, preserves the state, but otherwise overwrites the data.
  22638. *
  22639. * @param {grid} grid the grid we're operating on
  22640. * @param {gridRow} row the row we want to set
  22641. * @param {array} parents an array of the parents this row should have
  22642. * @param {array} aggregationBase empty aggregation information
  22643. * @returns {undefined} updates the parents array, updates the row to have a treeNode, and updates the
  22644. * grid.treeBase.tree
  22645. */
  22646. addOrUseNode: function(grid, row, parents, aggregationBase) {
  22647. var newAggregations = [];
  22648. aggregationBase.forEach(function(aggregation) {
  22649. newAggregations.push(service.buildAggregationObject(aggregation.col));
  22650. });
  22651. var newNode = { state: uiGridTreeBaseConstants.COLLAPSED, row: row, parentRow: null, aggregations: newAggregations, children: [] };
  22652. if (row.treeNode) {
  22653. newNode.state = row.treeNode.state;
  22654. }
  22655. if (parents.length > 0) {
  22656. newNode.parentRow = parents[parents.length - 1];
  22657. }
  22658. row.treeNode = newNode;
  22659. if (parents.length === 0) {
  22660. grid.treeBase.tree.push(newNode);
  22661. } else {
  22662. parents[parents.length - 1].treeNode.children.push(newNode);
  22663. }
  22664. },
  22665. /**
  22666. * @ngdoc function
  22667. * @name setCurrentState
  22668. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22669. * @description Looks at the parents array to determine our current state.
  22670. * If any node in the hierarchy is collapsed, then return collapsed, otherwise return
  22671. * expanded.
  22672. *
  22673. * @param {array} parents an array of the parents this row should have
  22674. * @returns {string} the state we should be setting to any nodes we see
  22675. */
  22676. setCurrentState: function(parents) {
  22677. var currentState = uiGridTreeBaseConstants.EXPANDED;
  22678. parents.forEach(function(parent) {
  22679. if (parent.treeNode.state === uiGridTreeBaseConstants.COLLAPSED) {
  22680. currentState = uiGridTreeBaseConstants.COLLAPSED;
  22681. }
  22682. });
  22683. return currentState;
  22684. },
  22685. /**
  22686. * @ngdoc function
  22687. * @name sortTree
  22688. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22689. * @description Performs a recursive sort on the tree nodes, sorting the
  22690. * children of each node and putting them back into the children array.
  22691. *
  22692. * Before doing this it turns back on all the sortIgnore - things that were previously
  22693. * ignored we process now. Since we're sorting within the nodes, presumably anything
  22694. * that was already sorted is how we derived the nodes, we can keep those sorts too.
  22695. *
  22696. * We only sort tree nodes that are expanded - no point in wasting effort sorting collapsed
  22697. * nodes
  22698. *
  22699. * @param {Grid} grid the grid to get the aggregation information from
  22700. * @returns {array} the aggregation information
  22701. */
  22702. sortTree: function(grid) {
  22703. grid.columns.forEach(function(column) {
  22704. if (column.sort && column.sort.ignoreSort) {
  22705. delete column.sort.ignoreSort;
  22706. }
  22707. });
  22708. grid.treeBase.tree = service.sortInternal(grid, grid.treeBase.tree);
  22709. },
  22710. sortInternal: function(grid, treeList) {
  22711. var rows = treeList.map(function(node) {
  22712. return node.row;
  22713. });
  22714. rows = rowSorter.sort(grid, rows, grid.columns);
  22715. var treeNodes = rows.map(function(row) {
  22716. return row.treeNode;
  22717. });
  22718. treeNodes.forEach(function(node) {
  22719. if (node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0) {
  22720. node.children = service.sortInternal(grid, node.children);
  22721. }
  22722. });
  22723. return treeNodes;
  22724. },
  22725. /**
  22726. * @ngdoc function
  22727. * @name fixFilter
  22728. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22729. * @description After filtering has run, we need to go back through the tree
  22730. * and make sure the parent rows are always visible if any of the child rows
  22731. * are visible (filtering may make a child visible, but the parent may not
  22732. * match the filter criteria)
  22733. *
  22734. * This has a risk of being computationally expensive, we do it by walking
  22735. * the tree and remembering whether there are any invisible nodes on the
  22736. * way down.
  22737. *
  22738. * @param {Grid} grid the grid to fix filters on
  22739. */
  22740. fixFilter: function(grid) {
  22741. var parentsVisible;
  22742. grid.treeBase.tree.forEach(function(node) {
  22743. if (node.children && node.children.length > 0) {
  22744. parentsVisible = node.row.visible;
  22745. service.fixFilterInternal(node.children, parentsVisible);
  22746. }
  22747. });
  22748. },
  22749. fixFilterInternal: function(nodes, parentsVisible) {
  22750. nodes.forEach(function(node) {
  22751. if (node.row.visible && !parentsVisible) {
  22752. service.setParentsVisible(node);
  22753. parentsVisible = true;
  22754. }
  22755. if (node.children && node.children.length > 0) {
  22756. if (service.fixFilterInternal(node.children, (parentsVisible && node.row.visible))) {
  22757. parentsVisible = true;
  22758. }
  22759. }
  22760. });
  22761. return parentsVisible;
  22762. },
  22763. setParentsVisible: function(node) {
  22764. while (node.parentRow) {
  22765. node.parentRow.visible = true;
  22766. node = node.parentRow.treeNode;
  22767. }
  22768. },
  22769. /**
  22770. * @ngdoc function
  22771. * @name buildAggregationObject
  22772. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22773. * @description Build the object which is stored on the column for holding meta-data about the aggregation.
  22774. * This method should only be called with columns which have an aggregation.
  22775. *
  22776. * @param {Column} the column which this object relates to
  22777. * @returns {object} {col: Column object, label: string, type: string (optional)}
  22778. */
  22779. buildAggregationObject: function(column) {
  22780. var newAggregation = { col: column };
  22781. if (column.treeAggregation && column.treeAggregation.type) {
  22782. newAggregation.type = column.treeAggregation.type;
  22783. }
  22784. if (column.treeAggregation && column.treeAggregation.label) {
  22785. newAggregation.label = column.treeAggregation.label;
  22786. }
  22787. return newAggregation;
  22788. },
  22789. /**
  22790. * @ngdoc function
  22791. * @name getAggregations
  22792. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22793. * @description Looks through the grid columns to find those with aggregations,
  22794. * and collates the aggregation information into an array, returns that array
  22795. *
  22796. * @param {Grid} grid the grid to get the aggregation information from
  22797. * @returns {array} the aggregation information
  22798. */
  22799. getAggregations: function(grid) {
  22800. var aggregateArray = [];
  22801. grid.columns.forEach(function(column) {
  22802. if (typeof(column.treeAggregationFn) !== 'undefined') {
  22803. aggregateArray.push(service.buildAggregationObject(column));
  22804. if (grid.options.showColumnFooter && typeof(column.colDef.aggregationType) === 'undefined' && column.treeAggregation) {
  22805. // Add aggregation object for footer
  22806. column.treeFooterAggregation = service.buildAggregationObject(column);
  22807. column.aggregationType = service.treeFooterAggregationType;
  22808. }
  22809. }
  22810. });
  22811. return aggregateArray;
  22812. },
  22813. /**
  22814. * @ngdoc function
  22815. * @name aggregate
  22816. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22817. * @description Accumulate the data from this row onto the aggregations for each parent
  22818. *
  22819. * Iterate over the parents, then iterate over the aggregations for each of those parents,
  22820. * and perform the aggregation for each individual aggregation
  22821. *
  22822. * @param {Grid} grid grid object
  22823. * @param {GridRow} row the row we want to set grouping visibility on
  22824. * @param {array} parents the parents that we would want to aggregate onto
  22825. */
  22826. aggregate: function(grid, row, parents) {
  22827. if (parents.length === 0 && row.treeNode && row.treeNode.aggregations) {
  22828. row.treeNode.aggregations.forEach(function(aggregation) {
  22829. // Calculate aggregations for footer even if there are no grouped rows
  22830. if (typeof(aggregation.col.treeFooterAggregation) !== 'undefined') {
  22831. var fieldValue = grid.getCellValue(row, aggregation.col);
  22832. var numValue = Number(fieldValue);
  22833. aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row);
  22834. }
  22835. });
  22836. }
  22837. parents.forEach(function(parent, index) {
  22838. if (parent.treeNode.aggregations) {
  22839. parent.treeNode.aggregations.forEach(function(aggregation) {
  22840. var fieldValue = grid.getCellValue(row, aggregation.col);
  22841. var numValue = Number(fieldValue);
  22842. aggregation.col.treeAggregationFn(aggregation, fieldValue, numValue, row);
  22843. if (index === 0 && typeof(aggregation.col.treeFooterAggregation) !== 'undefined') {
  22844. aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row);
  22845. }
  22846. });
  22847. }
  22848. });
  22849. },
  22850. // Aggregation routines - no doco needed as self evident
  22851. nativeAggregations: function() {
  22852. var nativeAggregations = {
  22853. count: {
  22854. label: i18nService.get().aggregation.count,
  22855. menuTitle: i18nService.get().grouping.aggregate_count,
  22856. aggregationFn: function(aggregation, fieldValue, numValue) {
  22857. if (typeof(aggregation.value) === 'undefined') {
  22858. aggregation.value = 1;
  22859. } else {
  22860. aggregation.value++;
  22861. }
  22862. }
  22863. },
  22864. sum: {
  22865. label: i18nService.get().aggregation.sum,
  22866. menuTitle: i18nService.get().grouping.aggregate_sum,
  22867. aggregationFn: function(aggregation, fieldValue, numValue) {
  22868. if (!isNaN(numValue)) {
  22869. if (typeof(aggregation.value) === 'undefined') {
  22870. aggregation.value = numValue;
  22871. } else {
  22872. aggregation.value += numValue;
  22873. }
  22874. }
  22875. }
  22876. },
  22877. min: {
  22878. label: i18nService.get().aggregation.min,
  22879. menuTitle: i18nService.get().grouping.aggregate_min,
  22880. aggregationFn: function(aggregation, fieldValue, numValue) {
  22881. if (typeof(aggregation.value) === 'undefined') {
  22882. aggregation.value = fieldValue;
  22883. } else {
  22884. if (typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue < aggregation.value || aggregation.value === null)) {
  22885. aggregation.value = fieldValue;
  22886. }
  22887. }
  22888. }
  22889. },
  22890. max: {
  22891. label: i18nService.get().aggregation.max,
  22892. menuTitle: i18nService.get().grouping.aggregate_max,
  22893. aggregationFn: function(aggregation, fieldValue, numValue) {
  22894. if (typeof(aggregation.value) === 'undefined') {
  22895. aggregation.value = fieldValue;
  22896. } else {
  22897. if (typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue > aggregation.value || aggregation.value === null)) {
  22898. aggregation.value = fieldValue;
  22899. }
  22900. }
  22901. }
  22902. },
  22903. avg: {
  22904. label: i18nService.get().aggregation.avg,
  22905. menuTitle: i18nService.get().grouping.aggregate_avg,
  22906. aggregationFn: function(aggregation, fieldValue, numValue) {
  22907. if (typeof(aggregation.count) === 'undefined') {
  22908. aggregation.count = 1;
  22909. } else {
  22910. aggregation.count++;
  22911. }
  22912. if (isNaN(numValue)) {
  22913. return;
  22914. }
  22915. if (typeof(aggregation.value) === 'undefined' || typeof(aggregation.sum) === 'undefined') {
  22916. aggregation.value = numValue;
  22917. aggregation.sum = numValue;
  22918. } else {
  22919. aggregation.sum += numValue;
  22920. aggregation.value = aggregation.sum / aggregation.count;
  22921. }
  22922. }
  22923. }
  22924. };
  22925. return nativeAggregations;
  22926. },
  22927. /**
  22928. * @ngdoc function
  22929. * @name finaliseAggregation
  22930. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22931. * @description Helper function used to finalize aggregation nodes and footer cells
  22932. *
  22933. * @param {gridRow} row the parent we're finalising
  22934. * @param {aggregation} the aggregation object manipulated by the aggregationFn
  22935. */
  22936. finaliseAggregation: function(row, aggregation) {
  22937. if (aggregation.col.treeAggregationUpdateEntity && typeof(row) !== 'undefined' && typeof(row.entity['$$' + aggregation.col.uid]) !== 'undefined') {
  22938. angular.extend(aggregation, row.entity['$$' + aggregation.col.uid]);
  22939. }
  22940. if (typeof(aggregation.col.treeAggregationFinalizerFn) === 'function') {
  22941. aggregation.col.treeAggregationFinalizerFn(aggregation);
  22942. }
  22943. if (typeof(aggregation.col.customTreeAggregationFinalizerFn) === 'function') {
  22944. aggregation.col.customTreeAggregationFinalizerFn(aggregation);
  22945. }
  22946. if (typeof(aggregation.rendered) === 'undefined') {
  22947. aggregation.rendered = aggregation.label ? aggregation.label + aggregation.value : aggregation.value;
  22948. }
  22949. },
  22950. /**
  22951. * @ngdoc function
  22952. * @name finaliseAggregations
  22953. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22954. * @description Format the data from the aggregation into the rendered text
  22955. * e.g. if we had label: 'sum: ' and value: 25, we'd create 'sum: 25'.
  22956. *
  22957. * As part of this we call any formatting callback routines we've been provided.
  22958. *
  22959. * We write our aggregation out to the row.entity if treeAggregationUpdateEntity is
  22960. * set on the column - we don't overwrite any information that's already there, we append
  22961. * to it so that grouping can have set the groupVal beforehand without us overwriting it.
  22962. *
  22963. * We need to copy the data from the row.entity first before we finalise the aggregation,
  22964. * we need that information for the finaliserFn
  22965. *
  22966. * @param {gridRow} row the parent we're finalising
  22967. */
  22968. finaliseAggregations: function(row) {
  22969. if (typeof(row.treeNode.aggregations) === 'undefined') {
  22970. return;
  22971. }
  22972. row.treeNode.aggregations.forEach(function(aggregation) {
  22973. service.finaliseAggregation(row, aggregation);
  22974. if (aggregation.col.treeAggregationUpdateEntity) {
  22975. var aggregationCopy = {};
  22976. angular.forEach(aggregation, function(value, key) {
  22977. if (aggregation.hasOwnProperty(key) && key !== 'col') {
  22978. aggregationCopy[key] = value;
  22979. }
  22980. });
  22981. row.entity['$$' + aggregation.col.uid] = aggregationCopy;
  22982. }
  22983. });
  22984. },
  22985. /**
  22986. * @ngdoc function
  22987. * @name treeFooterAggregationType
  22988. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  22989. * @description Uses the tree aggregation functions and finalizers to set the
  22990. * column footer aggregations.
  22991. *
  22992. * @param {rows} visible rows. not used, but accepted to match signature of GridColumn.aggregationType
  22993. * @param {gridColumn} the column we are finalizing
  22994. */
  22995. treeFooterAggregationType: function(rows, column) {
  22996. service.finaliseAggregation(undefined, column.treeFooterAggregation);
  22997. if (typeof(column.treeFooterAggregation.value) === 'undefined' || column.treeFooterAggregation.rendered === null) {
  22998. // The was apparently no aggregation performed (perhaps this is a grouped column
  22999. return '';
  23000. }
  23001. return column.treeFooterAggregation.rendered;
  23002. }
  23003. };
  23004. return service;
  23005. }
  23006. ]);
  23007. /**
  23008. * @ngdoc directive
  23009. * @name ui.grid.treeBase.directive:uiGridTreeRowHeaderButtons
  23010. * @element div
  23011. *
  23012. * @description Provides the expand/collapse button on rows
  23013. */
  23014. module.directive('uiGridTreeBaseRowHeaderButtons', ['$templateCache', 'uiGridTreeBaseService',
  23015. function($templateCache, uiGridTreeBaseService) {
  23016. return {
  23017. replace: true,
  23018. restrict: 'E',
  23019. template: $templateCache.get('ui-grid/treeBaseRowHeaderButtons'),
  23020. scope: true,
  23021. require: '^uiGrid',
  23022. link: function($scope, $elm, $attrs, uiGridCtrl) {
  23023. var self = uiGridCtrl.grid;
  23024. $scope.treeButtonClick = function(row, evt) {
  23025. uiGridTreeBaseService.toggleRowTreeState(self, row, evt);
  23026. };
  23027. }
  23028. };
  23029. }
  23030. ]);
  23031. /**
  23032. * @ngdoc directive
  23033. * @name ui.grid.treeBase.directive:uiGridTreeBaseExpandAllButtons
  23034. * @element div
  23035. *
  23036. * @description Provides the expand/collapse all button
  23037. */
  23038. module.directive('uiGridTreeBaseExpandAllButtons', ['$templateCache', 'uiGridTreeBaseService',
  23039. function($templateCache, uiGridTreeBaseService) {
  23040. return {
  23041. replace: true,
  23042. restrict: 'E',
  23043. template: $templateCache.get('ui-grid/treeBaseExpandAllButtons'),
  23044. scope: false,
  23045. link: function($scope, $elm, $attrs, uiGridCtrl) {
  23046. var self = $scope.col.grid;
  23047. $scope.headerButtonClick = function(row, evt) {
  23048. if (self.treeBase.expandAll) {
  23049. uiGridTreeBaseService.collapseAllRows(self, evt);
  23050. } else {
  23051. uiGridTreeBaseService.expandAllRows(self, evt);
  23052. }
  23053. };
  23054. }
  23055. };
  23056. }
  23057. ]);
  23058. /**
  23059. * @ngdoc directive
  23060. * @name ui.grid.treeBase.directive:uiGridViewport
  23061. * @element div
  23062. *
  23063. * @description Stacks on top of ui.grid.uiGridViewport to set formatting on a tree header row
  23064. */
  23065. module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'gridUtil', '$parse',
  23066. function($compile, uiGridConstants, gridUtil, $parse) {
  23067. return {
  23068. priority: -200, // run after default directive
  23069. scope: false,
  23070. compile: function($elm, $attrs) {
  23071. var rowRepeatDiv = angular.element($elm.children().children()[0]);
  23072. var existingNgClass = rowRepeatDiv.attr("ng-class");
  23073. var newNgClass = '';
  23074. if (existingNgClass) {
  23075. newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-tree-header-row': row.treeLevel > -1}";
  23076. } else {
  23077. newNgClass = "{'ui-grid-tree-header-row': row.treeLevel > -1}";
  23078. }
  23079. rowRepeatDiv.attr("ng-class", newNgClass);
  23080. return {
  23081. pre: function($scope, $elm, $attrs, controllers) {
  23082. },
  23083. post: function($scope, $elm, $attrs, controllers) {}
  23084. };
  23085. }
  23086. };
  23087. }
  23088. ]);
  23089. })();
  23090. (function() {
  23091. 'use strict';
  23092. /**
  23093. * @ngdoc overview
  23094. * @name ui.grid.treeView
  23095. * @description
  23096. *
  23097. * # ui.grid.treeView
  23098. *
  23099. * <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>
  23100. *
  23101. * This module provides a tree view of the data that it is provided, with nodes in that
  23102. * tree and leaves. Unlike grouping, the tree is an inherent property of the data and must
  23103. * be provided with your data array.
  23104. *
  23105. * Design information:
  23106. * -------------------
  23107. *
  23108. * TreeView uses treeBase for the underlying functionality, and is a very thin wrapper around
  23109. * that logic. Most of the design information has now moved to treebase.
  23110. * <br/>
  23111. * <br/>
  23112. *
  23113. * <div doc-module-components="ui.grid.treeView"></div>
  23114. */
  23115. var module = angular.module('ui.grid.treeView', ['ui.grid', 'ui.grid.treeBase']);
  23116. /**
  23117. * @ngdoc object
  23118. * @name ui.grid.treeView.constant:uiGridTreeViewConstants
  23119. *
  23120. * @description constants available in treeView module, this includes
  23121. * all the constants declared in the treeBase module (these are manually copied
  23122. * as there isn't an easy way to include constants in another constants file, and
  23123. * we don't want to make users include treeBase)
  23124. *
  23125. */
  23126. module.constant('uiGridTreeViewConstants', {
  23127. featureName: "treeView",
  23128. rowHeaderColName: 'treeBaseRowHeaderCol',
  23129. EXPANDED: 'expanded',
  23130. COLLAPSED: 'collapsed',
  23131. aggregation: {
  23132. COUNT: 'count',
  23133. SUM: 'sum',
  23134. MAX: 'max',
  23135. MIN: 'min',
  23136. AVG: 'avg'
  23137. }
  23138. });
  23139. /**
  23140. * @ngdoc service
  23141. * @name ui.grid.treeView.service:uiGridTreeViewService
  23142. *
  23143. * @description Services for treeView features
  23144. */
  23145. module.service('uiGridTreeViewService', ['$q', 'uiGridTreeViewConstants', 'uiGridTreeBaseConstants', 'uiGridTreeBaseService', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants',
  23146. function($q, uiGridTreeViewConstants, uiGridTreeBaseConstants, uiGridTreeBaseService, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants) {
  23147. var service = {
  23148. initializeGrid: function(grid, $scope) {
  23149. uiGridTreeBaseService.initializeGrid(grid, $scope);
  23150. /**
  23151. * @ngdoc object
  23152. * @name ui.grid.treeView.grid:treeView
  23153. *
  23154. * @description Grid properties and functions added for treeView
  23155. */
  23156. grid.treeView = {};
  23157. grid.registerRowsProcessor(service.adjustSorting, 60);
  23158. /**
  23159. * @ngdoc object
  23160. * @name ui.grid.treeView.api:PublicApi
  23161. *
  23162. * @description Public Api for treeView feature
  23163. */
  23164. var publicApi = {
  23165. events: {
  23166. treeView: {}
  23167. },
  23168. methods: {
  23169. treeView: {}
  23170. }
  23171. };
  23172. grid.api.registerEventsFromObject(publicApi.events);
  23173. grid.api.registerMethodsFromObject(publicApi.methods);
  23174. },
  23175. defaultGridOptions: function(gridOptions) {
  23176. //default option to true unless it was explicitly set to false
  23177. /**
  23178. * @ngdoc object
  23179. * @name ui.grid.treeView.api:GridOptions
  23180. *
  23181. * @description GridOptions for treeView feature, these are available to be
  23182. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  23183. *
  23184. * Many tree options are set on treeBase, make sure to look at that feature in
  23185. * conjunction with these options.
  23186. */
  23187. /**
  23188. * @ngdoc object
  23189. * @name enableTreeView
  23190. * @propertyOf ui.grid.treeView.api:GridOptions
  23191. * @description Enable row tree view for entire grid.
  23192. * <br/>Defaults to true
  23193. */
  23194. gridOptions.enableTreeView = gridOptions.enableTreeView !== false;
  23195. },
  23196. /**
  23197. * @ngdoc function
  23198. * @name adjustSorting
  23199. * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
  23200. * @description Trees cannot be sorted the same as flat lists of rows -
  23201. * trees are sorted recursively within each level - so the children of each
  23202. * node are sorted, but not the full set of rows.
  23203. *
  23204. * To achieve this, we suppress the normal sorting by setting ignoreSort on
  23205. * each of the sort columns. When the treeBase rowsProcessor runs it will then
  23206. * unignore these, and will perform a recursive sort against the tree that it builds.
  23207. *
  23208. * @param {array} renderableRows the rows that we need to pass on through
  23209. * @returns {array} renderableRows that we passed on through
  23210. */
  23211. adjustSorting: function(renderableRows) {
  23212. var grid = this;
  23213. grid.columns.forEach(function(column) {
  23214. if (column.sort) {
  23215. column.sort.ignoreSort = true;
  23216. }
  23217. });
  23218. return renderableRows;
  23219. }
  23220. };
  23221. return service;
  23222. }
  23223. ]);
  23224. /**
  23225. * @ngdoc directive
  23226. * @name ui.grid.treeView.directive:uiGridTreeView
  23227. * @element div
  23228. * @restrict A
  23229. *
  23230. * @description Adds treeView features to grid
  23231. *
  23232. * @example
  23233. <example module="app">
  23234. <file name="app.js">
  23235. var app = angular.module('app', ['ui.grid', 'ui.grid.treeView']);
  23236. app.controller('MainCtrl', ['$scope', function ($scope) {
  23237. $scope.data = [
  23238. { name: 'Bob', title: 'CEO' },
  23239. { name: 'Frank', title: 'Lowly Developer' }
  23240. ];
  23241. $scope.columnDefs = [
  23242. {name: 'name', enableCellEdit: true},
  23243. {name: 'title', enableCellEdit: true}
  23244. ];
  23245. $scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data };
  23246. }]);
  23247. </file>
  23248. <file name="index.html">
  23249. <div ng-controller="MainCtrl">
  23250. <div ui-grid="gridOptions" ui-grid-tree-view></div>
  23251. </div>
  23252. </file>
  23253. </example>
  23254. */
  23255. module.directive('uiGridTreeView', ['uiGridTreeViewConstants', 'uiGridTreeViewService', '$templateCache',
  23256. function(uiGridTreeViewConstants, uiGridTreeViewService, $templateCache) {
  23257. return {
  23258. replace: true,
  23259. priority: 0,
  23260. require: '^uiGrid',
  23261. scope: false,
  23262. compile: function() {
  23263. return {
  23264. pre: function($scope, $elm, $attrs, uiGridCtrl) {
  23265. if (uiGridCtrl.grid.options.enableTreeView !== false) {
  23266. uiGridTreeViewService.initializeGrid(uiGridCtrl.grid, $scope);
  23267. }
  23268. },
  23269. post: function($scope, $elm, $attrs, uiGridCtrl) {
  23270. }
  23271. };
  23272. }
  23273. };
  23274. }
  23275. ]);
  23276. })();
  23277. angular.module('ui.grid').run(['$templateCache', function($templateCache) {
  23278. 'use strict';
  23279. $templateCache.put('ui-grid/ui-grid-filter',
  23280. "<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>"
  23281. );
  23282. $templateCache.put('ui-grid/ui-grid-footer',
  23283. "<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>"
  23284. );
  23285. $templateCache.put('ui-grid/ui-grid-grid-footer',
  23286. "<div class=\"ui-grid-footer-info ui-grid-grid-footer\"><span class='margin-right-15'>{{'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>"
  23287. );
  23288. $templateCache.put('ui-grid/ui-grid-group-panel',
  23289. "<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>"
  23290. );
  23291. $templateCache.put('ui-grid/ui-grid-header',
  23292. "<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>"
  23293. );
  23294. $templateCache.put('ui-grid/ui-grid-menu-button',
  23295. "<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>"
  23296. );
  23297. $templateCache.put('ui-grid/ui-grid-no-header',
  23298. "<div class=\"ui-grid-top-panel\"></div>"
  23299. );
  23300. $templateCache.put('ui-grid/ui-grid-row',
  23301. "<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>"
  23302. );
  23303. $templateCache.put('ui-grid/ui-grid',
  23304. "<div ui-i18n=\"zh-cn\" class=\"ui-grid\"><!-- TODO (c0bra): add \"scoped\" attr here, eventually? --><style ui-grid-style>.grid{{ grid.id }} {\n" +
  23305. " /* Styles for the grid */\n" +
  23306. " }\n" +
  23307. "\n" +
  23308. " .grid{{ grid.id }} .ui-grid-row, .grid{{ grid.id }} .ui-grid-cell, .grid{{ grid.id }} .ui-grid-cell .ui-grid-vertical-bar {\n" +
  23309. " height: {{ grid.options.rowHeight }}px;\n" +
  23310. " }\n" +
  23311. "\n" +
  23312. " .grid{{ grid.id }} .ui-grid-row:last-child .ui-grid-cell {\n" +
  23313. " border-bottom-width: {{ ((grid.getTotalRowHeight() < grid.getViewportHeight()) && '1') || '0' }}px;\n" +
  23314. " }\n" +
  23315. "\n" +
  23316. " {{ grid.verticalScrollbarStyles }}\n" +
  23317. " {{ grid.horizontalScrollbarStyles }}\n" +
  23318. "\n" +
  23319. " /*\n" +
  23320. " .ui-grid[dir=rtl] .ui-grid-viewport {\n" +
  23321. " padding-left: {{ grid.verticalScrollbarWidth }}px;\n" +
  23322. " }\n" +
  23323. " */\n" +
  23324. "\n" +
  23325. " {{ 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 ui-grid-column-menu ng-if=\"grid.options.enableColumnMenus\"></div><div ng-transclude></div></div></div>"
  23326. );
  23327. $templateCache.put('ui-grid/uiGridCell',
  23328. "<div class=\"ui-grid-cell-contents\" title=\"TOOLTIP\">{{COL_FIELD CUSTOM_FILTERS}}</div>"
  23329. );
  23330. $templateCache.put('ui-grid/uiGridColumnMenu',
  23331. "<div class=\"ui-grid-column-menu\"><div ui-grid-menu menu-items=\"menuItems\"><!-- <div class=\"ui-grid-column-menu\">\n" +
  23332. " <div class=\"inner\" ng-show=\"menuShown\">\n" +
  23333. " <ul>\n" +
  23334. " <div ng-show=\"grid.options.enableSorting\">\n" +
  23335. " <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" +
  23336. " <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" +
  23337. " <li ng-show=\"col.sort.direction\" ng-click=\"unsortColumn()\"><i class=\"ui-grid-icon-cancel\"></i> Remove Sort</li>\n" +
  23338. " </div>\n" +
  23339. " </ul>\n" +
  23340. " </div>\n" +
  23341. " </div> --></div></div>"
  23342. );
  23343. $templateCache.put('ui-grid/uiGridFooterCell',
  23344. "<div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><div>{{ col.getAggregationText() + ( col.getAggregationValue() CUSTOM_FILTERS ) }}</div></div>"
  23345. );
  23346. $templateCache.put('ui-grid/uiGridHeaderCell',
  23347. "<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>"
  23348. );
  23349. $templateCache.put('ui-grid/uiGridMenu',
  23350. "<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>"
  23351. );
  23352. $templateCache.put('ui-grid/uiGridMenuItem',
  23353. "<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>"
  23354. );
  23355. $templateCache.put('ui-grid/uiGridRenderContainer',
  23356. "<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>"
  23357. );
  23358. $templateCache.put('ui-grid/uiGridViewport',
  23359. "<div role=\"rowgroup\" class=\"ui-grid-viewport\" ><!-- tbody --><div class=\"ui-grid-canvas\"><div ng-dblclick=\"grid.appScope.onDblClick(row,$event)\" 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>"
  23360. );
  23361. $templateCache.put('ui-grid/cellEditor',
  23362. "<div><form name=\"inputForm\"><input type=\"INPUT_TYPE\" ng-class=\"'colt' + col.uid\" ui-grid-editor ng-model=\"MODEL_COL_FIELD\"></form></div>"
  23363. );
  23364. $templateCache.put('ui-grid/dropdownEditor',
  23365. "<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>"
  23366. );
  23367. $templateCache.put('ui-grid/fileChooserEditor',
  23368. "<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>"
  23369. );
  23370. $templateCache.put('ui-grid/expandableRow',
  23371. "<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>"
  23372. );
  23373. $templateCache.put('ui-grid/expandableRowHeader',
  23374. "<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>"
  23375. );
  23376. $templateCache.put('ui-grid/expandableScrollFiller',
  23377. "<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>"
  23378. );
  23379. $templateCache.put('ui-grid/expandableTopRowHeader',
  23380. "<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>"
  23381. );
  23382. $templateCache.put('ui-grid/csvLink',
  23383. "<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>"
  23384. );
  23385. $templateCache.put('ui-grid/importerMenuItem',
  23386. "<li class=\"ui-grid-menu-item\"><form><input class=\"ui-grid-importer-file-chooser\" type=\"file\" id=\"files\" name=\"files[]\"></form></li>"
  23387. );
  23388. $templateCache.put('ui-grid/importerMenuItemContainer',
  23389. "<div ui-grid-importer-menu-item></div>"
  23390. );
  23391. $templateCache.put('ui-grid/pagination',
  23392. "<div role=\"contentinfo\" class=\"ui-grid-pager-panel\" ui-grid-pager ng-show=\"grid.options.enablePaginationControls\"><div ui-grid-grid-footer ></div><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></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>"
  23393. );
  23394. $templateCache.put('ui-grid/columnResizer',
  23395. "<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>"
  23396. );
  23397. $templateCache.put('ui-grid/gridFooterSelectedItems',
  23398. "<span ng-if=\"grid.selection.selectedCount !== 0 && grid.options.enableFooterTotalSelected\">({{\"search.selectedItems\" | t}} {{grid.selection.selectedCount}})</span>"
  23399. );
  23400. $templateCache.put('ui-grid/selectionHeaderCell',
  23401. "<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>"
  23402. );
  23403. $templateCache.put('ui-grid/selectionRowHeader',
  23404. "<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>"
  23405. );
  23406. $templateCache.put('ui-grid/selectionRowHeaderButtons',
  23407. "<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>"
  23408. );
  23409. $templateCache.put('ui-grid/selectionSelectAllButtons',
  23410. "<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>"
  23411. );
  23412. $templateCache.put('ui-grid/treeBaseExpandAllButtons',
  23413. "<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>"
  23414. );
  23415. $templateCache.put('ui-grid/treeBaseHeaderCell',
  23416. "<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>"
  23417. );
  23418. $templateCache.put('ui-grid/treeBaseRowHeader',
  23419. "<div class=\"ui-grid-cell-contents\"><ui-grid-tree-base-row-header-buttons></ui-grid-tree-base-row-header-buttons></div>"
  23420. );
  23421. $templateCache.put('ui-grid/treeBaseRowHeaderButtons',
  23422. "<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>"
  23423. );
  23424. }]);