jsonform.js 196 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766
  1. (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /* Copyright (c) 2012 Joshfire - MIT license */
  3. /**
  4. * @fileoverview Core of the JSON Form client-side library.
  5. *
  6. * Generates an HTML form from a structured data model and a layout description.
  7. *
  8. * The library may also validate inputs entered by the user against the data model
  9. * upon form submission and create the structured data object initialized with the
  10. * values that were submitted.
  11. *
  12. * The library depends on:
  13. * - jQuery
  14. * - the underscore library
  15. * - a JSON parser/serializer. Nothing to worry about in modern browsers.
  16. * - the JSONFormValidation library (in jsv.js) for validation purpose
  17. *
  18. * See documentation at:
  19. * http://developer.joshfire.com/doc/dev/ref/jsonform
  20. *
  21. * The library creates and maintains an internal data tree along with the DOM.
  22. * That structure is necessary to handle arrays (and nested arrays!) that are
  23. * dynamic by essence.
  24. */
  25. /*global window*/
  26. (function(serverside, global, $, _, JSON) {
  27. if (serverside && !_) {
  28. _ = require('underscore');
  29. }
  30. /**
  31. * Regular expressions used to extract array indexes in input field names
  32. */
  33. var reArray = /\[([0-9]*)\](?=\[|\.|$)/g;
  34. /**
  35. * Template settings for form views
  36. */
  37. var fieldTemplateSettings = {
  38. evaluate : /<%([\s\S]+?)%>/g,
  39. interpolate : /<%=([\s\S]+?)%>/g
  40. };
  41. /**
  42. * Template settings for value replacement
  43. */
  44. var valueTemplateSettings = {
  45. evaluate : /\{\[([\s\S]+?)\]\}/g,
  46. interpolate : /\{\{([\s\S]+?)\}\}/g
  47. };
  48. /**
  49. * Returns true if given value is neither "undefined" nor null
  50. */
  51. var isSet = function (value) {
  52. return !(_.isUndefined(value) || _.isNull(value));
  53. };
  54. /**
  55. * Returns true if given property is directly property of an object
  56. */
  57. var hasOwnProperty = function (obj, prop) {
  58. return typeof obj === 'object' && obj.hasOwnProperty(prop);
  59. }
  60. /**
  61. * The jsonform object whose methods will be exposed to the window object
  62. */
  63. var jsonform = {util:{}};
  64. // From backbonejs
  65. var escapeHTML = function (string) {
  66. if (!isSet(string)) {
  67. return '';
  68. }
  69. string = '' + string;
  70. if (!string) {
  71. return '';
  72. }
  73. return string
  74. .replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;')
  75. .replace(/</g, '&lt;')
  76. .replace(/>/g, '&gt;')
  77. .replace(/"/g, '&quot;')
  78. .replace(/'/g, '&#x27;')
  79. .replace(/\//g, '&#x2F;');
  80. };
  81. /**
  82. * Escapes selector name for use with jQuery
  83. *
  84. * All meta-characters listed in jQuery doc are escaped:
  85. * http://api.jquery.com/category/selectors/
  86. *
  87. * @function
  88. * @param {String} selector The jQuery selector to escape
  89. * @return {String} The escaped selector.
  90. */
  91. var escapeSelector = function (selector) {
  92. return selector.replace(/([ \!\"\#\$\%\&\'\(\)\*\+\,\.\/\:\;<\=\>\?\@\[\\\]\^\`\{\|\}\~])/g, '\\$1');
  93. };
  94. /**
  95. *
  96. * Slugifies a string by replacing spaces with _. Used to create
  97. * valid classnames and ids for the form.
  98. *
  99. * @function
  100. * @param {String} str The string to slugify
  101. * @return {String} The slugified string.
  102. */
  103. var slugify = function(str) {
  104. return str.replace(/\ /g, '_');
  105. }
  106. /**
  107. * Initializes tabular sections in forms. Such sections are generated by the
  108. * 'selectfieldset' type of elements in JSON Form.
  109. *
  110. * Input fields that are not visible are automatically disabled
  111. * not to appear in the submitted form. That's on purpose, as tabs
  112. * are meant to convey an alternative (and not a sequence of steps).
  113. *
  114. * The tabs menu is not rendered as tabs but rather as a select field because
  115. * it's easier to grasp that it's an alternative.
  116. *
  117. * Code based on bootstrap-tabs.js, updated to:
  118. * - react to option selection instead of tab click
  119. * - disable input fields in non visible tabs
  120. * - disable the possibility to have dropdown menus (no meaning here)
  121. * - act as a regular function instead of as a jQuery plug-in.
  122. *
  123. * @function
  124. * @param {Object} tabs jQuery object that contains the tabular sections
  125. * to initialize. The object may reference more than one element.
  126. */
  127. var initializeTabs = function (tabs) {
  128. var activate = function (element, container) {
  129. container
  130. .find('> .active')
  131. .removeClass('active');
  132. element.addClass('active');
  133. };
  134. var enableFields = function ($target, targetIndex) {
  135. // Enable all fields in the targeted tab
  136. $target.find('input, textarea, select').removeAttr('disabled');
  137. // Disable all fields in other tabs
  138. $target.parent()
  139. .children(':not([data-idx=' + targetIndex + '])')
  140. .find('input, textarea, select')
  141. .attr('disabled', 'disabled');
  142. };
  143. var optionSelected = function (e) {
  144. var $option = $("option:selected", $(this)),
  145. $select = $(this),
  146. // do not use .attr() as it sometimes unexplicably fails
  147. targetIdx = $option.get(0).getAttribute('data-idx') || $option.attr('value'),
  148. $target;
  149. e.preventDefault();
  150. if ($option.hasClass('active')) {
  151. return;
  152. }
  153. $target = $(this).parents('.tabbable').eq(0).find('> .tab-content > [data-idx=' + targetIdx + ']');
  154. activate($option, $select);
  155. activate($target, $target.parent());
  156. enableFields($target, targetIdx);
  157. };
  158. var tabClicked = function (e) {
  159. var $a = $('a', $(this));
  160. var $content = $(this).parents('.tabbable').first()
  161. .find('.tab-content').first();
  162. var targetIdx = $(this).index();
  163. // The `>` here is to prevent activating selectfieldsets inside a tabarray
  164. var $target = $content.find('> [data-idx=' + targetIdx + ']');
  165. e.preventDefault();
  166. activate($(this), $(this).parent());
  167. activate($target, $target.parent());
  168. if ($(this).parent().hasClass('jsonform-alternative')) {
  169. enableFields($target, targetIdx);
  170. }
  171. };
  172. tabs.each(function () {
  173. $(this).delegate('select.nav', 'change', optionSelected);
  174. $(this).find('select.nav').each(function () {
  175. $(this).val($(this).find('.active').attr('value'));
  176. // do not use .attr() as it sometimes unexplicably fails
  177. var targetIdx = $(this).find('option:selected').get(0).getAttribute('data-idx') ||
  178. $(this).find('option:selected').attr('value');
  179. var $target = $(this).parents('.tabbable').eq(0).find('> .tab-content > [data-idx=' + targetIdx + ']');
  180. enableFields($target, targetIdx);
  181. });
  182. $(this).delegate('ul.nav li', 'click', tabClicked);
  183. $(this).find('ul.nav li.active').click();
  184. });
  185. };
  186. // Twitter bootstrap-friendly HTML boilerplate for standard inputs
  187. jsonform.fieldTemplate = function(inner) {
  188. return '<div ' +
  189. '<% for(var key in elt.htmlMetaData) {%>' +
  190. '<%= key %>="<%= elt.htmlMetaData[key] %>" ' +
  191. '<% }%>' +
  192. 'class="form-group jsonform-error-<%= keydash %>' +
  193. '<%= elt.htmlClass ? " " + elt.htmlClass : "" %>' +
  194. '<%= (node.schemaElement && node.schemaElement.required && (node.schemaElement.type !== "boolean") ? " jsonform-required" : "") %>' +
  195. '<%= (node.readOnly ? " jsonform-readonly" : "") %>' +
  196. '<%= (node.disabled ? " jsonform-disabled" : "") %>' +
  197. '">' +
  198. '<% if (!elt.notitle) { %>' +
  199. '<label for="<%= node.id %>"><%= node.title ? node.title : node.name %></label>' +
  200. '<% } %>' +
  201. '<div class="controls">' +
  202. '<% if (node.prepend || node.append) { %>' +
  203. '<div class="<% if (node.prepend) { %>input-group<% } %>' +
  204. '<% if (node.append) { %> input-group<% } %>">' +
  205. '<% if (node.prepend) { %>' +
  206. '<span class="input-group-addon"><%= node.prepend %></span>' +
  207. '<% } %>' +
  208. '<% } %>' +
  209. inner +
  210. '<% if (node.append) { %>' +
  211. '<span class="input-group-addon"><%= node.append %></span>' +
  212. '<% } %>' +
  213. '<% if (node.prepend || node.append) { %>' +
  214. '</div>' +
  215. '<% } %>' +
  216. '<% if (node.description) { %>' +
  217. '<span class="help-block"><%= node.description %></span>' +
  218. '<% } %>' +
  219. '<span class="help-block jsonform-errortext" style="display:none;"></span>' +
  220. '</div></div>';
  221. };
  222. var fileDisplayTemplate = '<div class="_jsonform-preview">' +
  223. '<% if (value.type=="image") { %>' +
  224. '<img class="jsonform-preview" id="jsonformpreview-<%= id %>" src="<%= value.url %>" />' +
  225. '<% } else { %>' +
  226. '<a href="<%= value.url %>"><%= value.name %></a> (<%= Math.ceil(value.size/1024) %>kB)' +
  227. '<% } %>' +
  228. '</div>' +
  229. '<a href="#" class="btn btn-default _jsonform-delete"><i class="glyphicon glyphicon-remove" title="Remove"></i></a> ';
  230. var inputFieldTemplate = function (type) {
  231. return {
  232. 'template': '<input type="' + type + '" ' +
  233. 'class=\'form-control<%= (fieldHtmlClass ? " " + fieldHtmlClass : "") %>\'' +
  234. 'name="<%= node.name %>" value="<%= escape(value) %>" id="<%= id %>"' +
  235. '<%= (node.disabled? " disabled" : "")%>' +
  236. '<%= (node.readOnly ? " readonly=\'readonly\'" : "") %>' +
  237. '<%= (node.schemaElement && (node.schemaElement.step > 0 || node.schemaElement.step == "any") ? " step=\'" + node.schemaElement.step + "\'" : "") %>' +
  238. '<%= (node.schemaElement && node.schemaElement.maxLength ? " maxlength=\'" + node.schemaElement.maxLength + "\'" : "") %>' +
  239. '<%= (node.schemaElement && node.schemaElement.required && (node.schemaElement.type !== "boolean") ? " required=\'required\'" : "") %>' +
  240. '<%= (node.placeholder? " placeholder=" + \'"\' + escape(node.placeholder) + \'"\' : "")%>' +
  241. ' />',
  242. 'fieldtemplate': true,
  243. 'inputfield': true
  244. }
  245. };
  246. jsonform.elementTypes = {
  247. 'none': {
  248. 'template': ''
  249. },
  250. 'root': {
  251. 'template': '<div><%= children %></div>'
  252. },
  253. 'text': inputFieldTemplate('text'),
  254. 'password': inputFieldTemplate('password'),
  255. 'date': inputFieldTemplate('date'),
  256. 'datetime': inputFieldTemplate('datetime'),
  257. 'datetime-local': inputFieldTemplate('datetime-local'),
  258. 'email': inputFieldTemplate('email'),
  259. 'month': inputFieldTemplate('month'),
  260. 'number': inputFieldTemplate('number'),
  261. 'search': inputFieldTemplate('search'),
  262. 'tel': inputFieldTemplate('tel'),
  263. 'time': inputFieldTemplate('time'),
  264. 'url': inputFieldTemplate('url'),
  265. 'week': inputFieldTemplate('week'),
  266. 'range': {
  267. 'template': '<input type="range" ' +
  268. '<%= (fieldHtmlClass ? "class=\'" + fieldHtmlClass + "\' " : "") %>' +
  269. 'name="<%= node.name %>" value="<%= escape(value) %>" id="<%= id %>"' +
  270. '<%= (node.disabled? " disabled" : "")%>' +
  271. ' min=<%= range.min %>' +
  272. ' max=<%= range.max %>' +
  273. ' step=<%= range.step %>' +
  274. '<%= (node.schemaElement && node.schemaElement.required ? " required=\'required\'" : "") %>' +
  275. ' />',
  276. 'fieldtemplate': true,
  277. 'inputfield': true,
  278. 'onBeforeRender': function (data, node) {
  279. data.range = {
  280. min: 1,
  281. max: 100,
  282. step: 1
  283. };
  284. if (!node || !node.schemaElement) return;
  285. if (node.formElement && node.formElement.step) {
  286. data.range.step = node.formElement.step;
  287. }
  288. if (typeof node.schemaElement.minimum !== 'undefined') {
  289. if (node.schemaElement.exclusiveMinimum) {
  290. data.range.min = node.schemaElement.minimum + data.range.step;
  291. }
  292. else {
  293. data.range.min = node.schemaElement.minimum;
  294. }
  295. }
  296. if (typeof node.schemaElement.maximum !== 'undefined') {
  297. if (node.schemaElement.exclusiveMaximum) {
  298. data.range.max = node.schemaElement.maximum - data.range.step;
  299. }
  300. else {
  301. data.range.max = node.schemaElement.maximum;
  302. }
  303. }
  304. }
  305. },
  306. 'color':{
  307. 'template':'<input type="text" ' +
  308. '<%= (fieldHtmlClass ? "class=\'" + fieldHtmlClass + "\' " : "") %>' +
  309. 'name="<%= node.name %>" value="<%= escape(value) %>" id="<%= id %>"' +
  310. '<%= (node.disabled? " disabled" : "")%>' +
  311. '<%= (node.schemaElement && node.schemaElement.required ? " required=\'required\'" : "") %>' +
  312. ' />',
  313. 'fieldtemplate': true,
  314. 'inputfield': true,
  315. 'onInsert': function(evt, node) {
  316. $(node.el).find('#' + escapeSelector(node.id)).spectrum({
  317. preferredFormat: "hex",
  318. showInput: true
  319. });
  320. }
  321. },
  322. 'textarea':{
  323. 'template':'<textarea id="<%= id %>" name="<%= node.name %>" ' +
  324. '<%= (fieldHtmlClass ? "class=\'" + fieldHtmlClass + "\' " : "") %>' +
  325. 'style="height:<%= elt.height || "150px" %>;width:<%= elt.width || "100%" %>;"' +
  326. '<%= (node.disabled? " disabled" : "")%>' +
  327. '<%= (node.readOnly ? " readonly=\'readonly\'" : "") %>' +
  328. '<%= (node.schemaElement && node.schemaElement.maxLength ? " maxlength=\'" + node.schemaElement.maxLength + "\'" : "") %>' +
  329. '<%= (node.schemaElement && node.schemaElement.required ? " required=\'required\'" : "") %>' +
  330. '<%= (node.placeholder? " placeholder=" + \'"\' + escape(node.placeholder) + \'"\' : "")%>' +
  331. '><%= value %></textarea>',
  332. 'fieldtemplate': true,
  333. 'inputfield': true
  334. },
  335. 'wysihtml5':{
  336. 'template':'<textarea id="<%= id %>" name="<%= node.name %>" style="height:<%= elt.height || "300px" %>;width:<%= elt.width || "100%" %>;"' +
  337. '<%= (fieldHtmlClass ? "class=\'" + fieldHtmlClass + "\' " : "") %>' +
  338. '<%= (node.disabled? " disabled" : "")%>' +
  339. '<%= (node.readOnly ? " readonly=\'readonly\'" : "") %>' +
  340. '<%= (node.schemaElement && node.schemaElement.maxLength ? " maxlength=\'" + node.schemaElement.maxLength + "\'" : "") %>' +
  341. '<%= (node.schemaElement && node.schemaElement.required ? " required=\'required\'" : "") %>' +
  342. '<%= (node.placeholder? " placeholder=" + \'"\' + escape(node.placeholder) + \'"\' : "")%>' +
  343. '><%= value %></textarea>',
  344. 'fieldtemplate': true,
  345. 'inputfield': true,
  346. 'onInsert': function (evt, node) {
  347. var setup = function () {
  348. //protect from double init
  349. if ($(node.el).data("wysihtml5")) return;
  350. $(node.el).data("wysihtml5_loaded",true);
  351. $(node.el).find('#' + escapeSelector(node.id)).wysihtml5({
  352. "html": true,
  353. "link": true,
  354. "font-styles":true,
  355. "image": false,
  356. "events": {
  357. "load": function () {
  358. // In chrome, if an element is required and hidden, it leads to
  359. // the error 'An invalid form control with name='' is not focusable'
  360. // See http://stackoverflow.com/questions/7168645/invalid-form-control-only-in-google-chrome
  361. $(this.textareaElement).removeAttr('required');
  362. }
  363. }
  364. });
  365. };
  366. // Is there a setup hook?
  367. if (window.jsonform_wysihtml5_setup) {
  368. window.jsonform_wysihtml5_setup(setup);
  369. return;
  370. }
  371. // Wait until wysihtml5 is loaded
  372. var itv = window.setInterval(function() {
  373. if (window.wysihtml5) {
  374. window.clearInterval(itv);
  375. setup();
  376. }
  377. },1000);
  378. }
  379. },
  380. 'ace':{
  381. 'template':'<div id="<%= id %>" style="position:relative;height:<%= elt.height || "300px" %>;"><div id="<%= id %>__ace" style="width:<%= elt.width || "100%" %>;height:<%= elt.height || "300px" %>;"></div><input type="hidden" name="<%= node.name %>" id="<%= id %>__hidden" value="<%= escape(value) %>"/></div>',
  382. 'fieldtemplate': true,
  383. 'inputfield': true,
  384. 'onInsert': function (evt, node) {
  385. var setup = function () {
  386. var formElement = node.formElement || {};
  387. var ace = window.ace;
  388. var editor = ace.edit($(node.el).find('#' + escapeSelector(node.id) + '__ace').get(0));
  389. var idSelector = '#' + escapeSelector(node.id) + '__hidden';
  390. // Force editor to use "\n" for new lines, not to bump into ACE "\r" conversion issue
  391. // (ACE is ok with "\r" on pasting but fails to return "\r" when value is extracted)
  392. editor.getSession().setNewLineMode('unix');
  393. editor.renderer.setShowPrintMargin(false);
  394. editor.setTheme("ace/theme/"+(formElement.aceTheme||"twilight"));
  395. if (formElement.aceMode) {
  396. editor.getSession().setMode("ace/mode/"+formElement.aceMode);
  397. }
  398. editor.getSession().setTabSize(2);
  399. // Set the contents of the initial manifest file
  400. editor.getSession().setValue(node.value||"");
  401. //TODO this is clearly sub-optimal
  402. // 'Lazily' bind to the onchange 'ace' event to give
  403. // priority to user edits
  404. var lazyChanged = _.debounce(function () {
  405. $(node.el).find(idSelector).val(editor.getSession().getValue());
  406. $(node.el).find(idSelector).change();
  407. }, 600);
  408. editor.getSession().on('change', lazyChanged);
  409. editor.on('blur', function() {
  410. $(node.el).find(idSelector).change();
  411. $(node.el).find(idSelector).trigger("blur");
  412. });
  413. editor.on('focus', function() {
  414. $(node.el).find(idSelector).trigger("focus");
  415. });
  416. };
  417. // Is there a setup hook?
  418. if (window.jsonform_ace_setup) {
  419. window.jsonform_ace_setup(setup);
  420. return;
  421. }
  422. // Wait until ACE is loaded
  423. var itv = window.setInterval(function() {
  424. if (window.ace) {
  425. window.clearInterval(itv);
  426. setup();
  427. }
  428. },1000);
  429. }
  430. },
  431. 'checkbox':{
  432. 'template': '<div class="checkbox"><label><input type="checkbox" id="<%= id %>" ' +
  433. '<%= (fieldHtmlClass ? " class=\'" + fieldHtmlClass + "\'": "") %>' +
  434. 'name="<%= node.name %>" value="1" <% if (value) {%>checked<% } %>' +
  435. '<%= (node.disabled? " disabled" : "")%>' +
  436. '<%= (node.schemaElement && node.schemaElement.required && (node.schemaElement.type !== "boolean") ? " required=\'required\'" : "") %>' +
  437. ' /><%= node.inlinetitle || "" %>' +
  438. '</label></div>',
  439. 'fieldtemplate': true,
  440. 'inputfield': true,
  441. 'getElement': function (el) {
  442. return $(el).parent().get(0);
  443. }
  444. },
  445. 'file':{
  446. 'template':'<input class="input-file" id="<%= id %>" name="<%= node.name %>" type="file" ' +
  447. '<%= (node.schemaElement && node.schemaElement.required ? " required=\'required\'" : "") %>' +
  448. '/>',
  449. 'fieldtemplate': true,
  450. 'inputfield': true
  451. },
  452. 'file-hosted-public':{
  453. 'template':'<span><% if (value && (value.type||value.url)) { %>'+fileDisplayTemplate+'<% } %><input class="input-file" id="_transloadit_<%= id %>" type="file" name="<%= transloaditname %>" /><input data-transloadit-name="_transloadit_<%= transloaditname %>" type="hidden" id="<%= id %>" name="<%= node.name %>" value=\'<%= escape(JSON.stringify(node.value)) %>\' /></span>',
  454. 'fieldtemplate': true,
  455. 'inputfield': true,
  456. 'getElement': function (el) {
  457. return $(el).parent().get(0);
  458. },
  459. 'onBeforeRender': function (data, node) {
  460. if (!node.ownerTree._transloadit_generic_public_index) {
  461. node.ownerTree._transloadit_generic_public_index=1;
  462. } else {
  463. node.ownerTree._transloadit_generic_public_index++;
  464. }
  465. data.transloaditname = "_transloadit_jsonform_genericupload_public_"+node.ownerTree._transloadit_generic_public_index;
  466. if (!node.ownerTree._transloadit_generic_elts) node.ownerTree._transloadit_generic_elts = {};
  467. node.ownerTree._transloadit_generic_elts[data.transloaditname] = node;
  468. },
  469. 'onChange': function(evt,elt) {
  470. // The "transloadit" function should be called only once to enable
  471. // the service when the form is submitted. Has it already been done?
  472. if (elt.ownerTree._transloadit_bound) {
  473. return false;
  474. }
  475. elt.ownerTree._transloadit_bound = true;
  476. // Call the "transloadit" function on the form element
  477. var formElt = $(elt.ownerTree.domRoot);
  478. formElt.transloadit({
  479. autoSubmit: false,
  480. wait: true,
  481. onSuccess: function (assembly) {
  482. // Image has been uploaded. Check the "results" property that
  483. // contains the list of files that Transloadit produced. There
  484. // should be one image per file input in the form at most.
  485. // console.log(assembly.results);
  486. var results = _.values(assembly.results);
  487. results = _.flatten(results);
  488. _.each(results, function (result) {
  489. // Save the assembly result in the right hidden input field
  490. var id = elt.ownerTree._transloadit_generic_elts[result.field].id;
  491. var input = formElt.find('#' + escapeSelector(id));
  492. var nonEmptyKeys = _.filter(_.keys(result.meta), function (key) {
  493. return !!isSet(result.meta[key]);
  494. });
  495. result.meta = _.pick(result.meta, nonEmptyKeys);
  496. input.val(JSON.stringify(result));
  497. });
  498. // Unbind transloadit from the form
  499. elt.ownerTree._transloadit_bound = false;
  500. formElt.unbind('submit.transloadit');
  501. // Submit the form on next tick
  502. _.delay(function () {
  503. console.log('submit form');
  504. elt.ownerTree.submit();
  505. }, 10);
  506. },
  507. onError: function (assembly) {
  508. // TODO: report the error to the user
  509. console.log('assembly error', assembly);
  510. }
  511. });
  512. },
  513. 'onInsert': function (evt, node) {
  514. $(node.el).find('a._jsonform-delete').on('click', function (evt) {
  515. $(node.el).find('._jsonform-preview').remove();
  516. $(node.el).find('a._jsonform-delete').remove();
  517. $(node.el).find('#' + escapeSelector(node.id)).val('');
  518. evt.preventDefault();
  519. return false;
  520. });
  521. },
  522. 'onSubmit':function(evt, elt) {
  523. if (elt.ownerTree._transloadit_bound) {
  524. return false;
  525. }
  526. return true;
  527. }
  528. },
  529. 'file-transloadit': {
  530. 'template': '<span><% if (value && (value.type||value.url)) { %>'+fileDisplayTemplate+'<% } %><input class="input-file" id="_transloadit_<%= id %>" type="file" name="_transloadit_<%= node.name %>" /><input type="hidden" id="<%= id %>" name="<%= node.name %>" value=\'<%= escape(JSON.stringify(node.value)) %>\' /></span>',
  531. 'fieldtemplate': true,
  532. 'inputfield': true,
  533. 'getElement': function (el) {
  534. return $(el).parent().get(0);
  535. },
  536. 'onChange': function (evt, elt) {
  537. // The "transloadit" function should be called only once to enable
  538. // the service when the form is submitted. Has it already been done?
  539. if (elt.ownerTree._transloadit_bound) {
  540. return false;
  541. }
  542. elt.ownerTree._transloadit_bound = true;
  543. // Call the "transloadit" function on the form element
  544. var formElt = $(elt.ownerTree.domRoot);
  545. formElt.transloadit({
  546. autoSubmit: false,
  547. wait: true,
  548. onSuccess: function (assembly) {
  549. // Image has been uploaded. Check the "results" property that
  550. // contains the list of files that Transloadit produced. Note
  551. // JSONForm only supports 1-to-1 associations, meaning it
  552. // expects the "results" property to contain only one image
  553. // per file input in the form.
  554. // console.log(assembly.results);
  555. var results = _.values(assembly.results);
  556. results = _.flatten(results);
  557. _.each(results, function (result) {
  558. // Save the assembly result in the right hidden input field
  559. var input = formElt.find('input[name="' +
  560. result.field.replace(/^_transloadit_/, '') +
  561. '"]');
  562. var nonEmptyKeys = _.filter(_.keys(result.meta), function (key) {
  563. return !!isSet(result.meta[key]);
  564. });
  565. result.meta = _.pick(result.meta, nonEmptyKeys);
  566. input.val(JSON.stringify(result));
  567. });
  568. // Unbind transloadit from the form
  569. elt.ownerTree._transloadit_bound = false;
  570. formElt.unbind('submit.transloadit');
  571. // Submit the form on next tick
  572. _.delay(function () {
  573. console.log('submit form');
  574. elt.ownerTree.submit();
  575. }, 10);
  576. },
  577. onError: function (assembly) {
  578. // TODO: report the error to the user
  579. console.log('assembly error', assembly);
  580. }
  581. });
  582. },
  583. 'onInsert': function (evt, node) {
  584. $(node.el).find('a._jsonform-delete').on('click', function (evt) {
  585. $(node.el).find('._jsonform-preview').remove();
  586. $(node.el).find('a._jsonform-delete').remove();
  587. $(node.el).find('#' + escapeSelector(node.id)).val('');
  588. evt.preventDefault();
  589. return false;
  590. });
  591. },
  592. 'onSubmit': function (evt, elt) {
  593. if (elt.ownerTree._transloadit_bound) {
  594. return false;
  595. }
  596. return true;
  597. }
  598. },
  599. 'select':{
  600. 'template':'<select name="<%= node.name %>" id="<%= id %>"' +
  601. 'class=\'form-control<%= (fieldHtmlClass ? " " + fieldHtmlClass : "") %>\'' +
  602. '<%= (node.schemaElement && node.schemaElement.disabled? " disabled" : "")%>' +
  603. '<%= (node.schemaElement && node.schemaElement.required ? " required=\'required\'" : "") %>' +
  604. '> ' +
  605. '<% _.each(node.options, function(key, val) { if(key instanceof Object) { if (value === key.value) { %> <option selected value="<%= key.value %>"><%= key.title %></option> <% } else { %> <option value="<%= key.value %>"><%= key.title %></option> <% }} else { if (value === key) { %> <option selected value="<%= key %>"><%= key %></option> <% } else { %><option value="<%= key %>"><%= key %></option> <% }}}); %> ' +
  606. '</select>',
  607. 'fieldtemplate': true,
  608. 'inputfield': true
  609. },
  610. 'imageselect': {
  611. 'template': '<div>' +
  612. '<input type="hidden" name="<%= node.name %>" id="<%= node.id %>" value="<%= value %>" />' +
  613. '<div class="dropdown">' +
  614. '<a class="btn<% if (buttonClass && node.value) { %> <%= buttonClass %><% } else { %> btn-default<% } %>" data-toggle="dropdown" href="#"<% if (node.value) { %> style="max-width:<%= width %>px;max-height:<%= height %>px"<% } %>>' +
  615. '<% if (node.value) { %><img src="<% if (!node.value.match(/^https?:/)) { %><%= prefix %><% } %><%= node.value %><%= suffix %>" alt="" /><% } else { %><%= buttonTitle %><% } %>' +
  616. '</a>' +
  617. '<div class="dropdown-menu navbar" id="<%= node.id %>_dropdown">' +
  618. '<div>' +
  619. '<% _.each(node.options, function(key, idx) { if ((idx > 0) && ((idx % columns) === 0)) { %></div><div><% } %><a class="btn<% if (buttonClass) { %> <%= buttonClass %><% } else { %> btn-default<% } %>" style="max-width:<%= width %>px;max-height:<%= height %>px"><% if (key instanceof Object) { %><img src="<% if (!key.value.match(/^https?:/)) { %><%= prefix %><% } %><%= key.value %><%= suffix %>" alt="<%= key.title %>" /></a><% } else { %><img src="<% if (!key.match(/^https?:/)) { %><%= prefix %><% } %><%= key %><%= suffix %>" alt="" /><% } %></a> <% }); %>' +
  620. '</div>' +
  621. '<div class="pagination-right"><a class="btn btn-default">Reset</a></div>' +
  622. '</div>' +
  623. '</div>' +
  624. '</div>',
  625. 'fieldtemplate': true,
  626. 'inputfield': true,
  627. 'onBeforeRender': function (data, node) {
  628. var elt = node.formElement || {};
  629. var nbRows = null;
  630. var maxColumns = elt.imageSelectorColumns || 5;
  631. data.buttonTitle = elt.imageSelectorTitle || 'Select...';
  632. data.prefix = elt.imagePrefix || '';
  633. data.suffix = elt.imageSuffix || '';
  634. data.width = elt.imageWidth || 32;
  635. data.height = elt.imageHeight || 32;
  636. data.buttonClass = elt.imageButtonClass || false;
  637. if (node.options.length > maxColumns) {
  638. nbRows = Math.ceil(node.options.length / maxColumns);
  639. data.columns = Math.ceil(node.options.length / nbRows);
  640. }
  641. else {
  642. data.columns = maxColumns;
  643. }
  644. },
  645. 'getElement': function (el) {
  646. return $(el).parent().get(0);
  647. },
  648. 'onInsert': function (evt, node) {
  649. $(node.el).on('click', '.dropdown-menu a', function (evt) {
  650. evt.preventDefault();
  651. evt.stopPropagation();
  652. var img = (evt.target.nodeName.toLowerCase() === 'img') ?
  653. $(evt.target) :
  654. $(evt.target).find('img');
  655. var value = img.attr('src');
  656. var elt = node.formElement || {};
  657. var prefix = elt.imagePrefix || '';
  658. var suffix = elt.imageSuffix || '';
  659. var width = elt.imageWidth || 32;
  660. var height = elt.imageHeight || 32;
  661. if (value) {
  662. if (value.indexOf(prefix) === 0) {
  663. value = value.substring(prefix.length);
  664. }
  665. value = value.substring(0, value.length - suffix.length);
  666. $(node.el).find('input').attr('value', value);
  667. $(node.el).find('a[data-toggle="dropdown"]')
  668. .addClass(elt.imageButtonClass)
  669. .attr('style', 'max-width:' + width + 'px;max-height:' + height + 'px')
  670. .html('<img src="' + (!value.match(/^https?:/) ? prefix : '') + value + suffix + '" alt="" />');
  671. }
  672. else {
  673. $(node.el).find('input').attr('value', '');
  674. $(node.el).find('a[data-toggle="dropdown"]')
  675. .removeClass(elt.imageButtonClass)
  676. .removeAttr('style')
  677. .html(elt.imageSelectorTitle || 'Select...');
  678. }
  679. });
  680. }
  681. },
  682. 'iconselect': {
  683. 'template': '<div>' +
  684. '<input type="hidden" name="<%= node.name %>" id="<%= node.id %>" value="<%= value %>" />' +
  685. '<div class="dropdown">' +
  686. '<a class="btn<% if (buttonClass && node.value) { %> <%= buttonClass %><% } %>" data-toggle="dropdown" href="#"<% if (node.value) { %> style="max-width:<%= width %>px;max-height:<%= height %>px"<% } %>>' +
  687. '<% if (node.value) { %><i class="icon-<%= node.value %>" /><% } else { %><%= buttonTitle %><% } %>' +
  688. '</a>' +
  689. '<div class="dropdown-menu navbar" id="<%= node.id %>_dropdown">' +
  690. '<div>' +
  691. '<% _.each(node.options, function(key, idx) { if ((idx > 0) && ((idx % columns) === 0)) { %></div><div><% } %><a class="btn<% if (buttonClass) { %> <%= buttonClass %><% } %>" ><% if (key instanceof Object) { %><i class="icon-<%= key.value %>" alt="<%= key.title %>" /></a><% } else { %><i class="icon-<%= key %>" alt="" /><% } %></a> <% }); %>' +
  692. '</div>' +
  693. '<div class="pagination-right"><a class="btn">Reset</a></div>' +
  694. '</div>' +
  695. '</div>' +
  696. '</div>',
  697. 'fieldtemplate': true,
  698. 'inputfield': true,
  699. 'onBeforeRender': function (data, node) {
  700. var elt = node.formElement || {};
  701. var nbRows = null;
  702. var maxColumns = elt.imageSelectorColumns || 5;
  703. data.buttonTitle = elt.imageSelectorTitle || 'Select...';
  704. data.buttonClass = elt.imageButtonClass || false;
  705. if (node.options.length > maxColumns) {
  706. nbRows = Math.ceil(node.options.length / maxColumns);
  707. data.columns = Math.ceil(node.options.length / nbRows);
  708. }
  709. else {
  710. data.columns = maxColumns;
  711. }
  712. },
  713. 'getElement': function (el) {
  714. return $(el).parent().get(0);
  715. },
  716. 'onInsert': function (evt, node) {
  717. $(node.el).on('click', '.dropdown-menu a', function (evt) {
  718. evt.preventDefault();
  719. evt.stopPropagation();
  720. var i = (evt.target.nodeName.toLowerCase() === 'i') ?
  721. $(evt.target) :
  722. $(evt.target).find('i');
  723. var value = i.attr('class');
  724. var elt = node.formElement || {};
  725. if (value) {
  726. value = value;
  727. $(node.el).find('input').attr('value', value);
  728. $(node.el).find('a[data-toggle="dropdown"]')
  729. .addClass(elt.imageButtonClass)
  730. .html('<i class="'+ value +'" alt="" />');
  731. }
  732. else {
  733. $(node.el).find('input').attr('value', '');
  734. $(node.el).find('a[data-toggle="dropdown"]')
  735. .removeClass(elt.imageButtonClass)
  736. .html(elt.imageSelectorTitle || 'Select...');
  737. }
  738. });
  739. }
  740. },
  741. 'radios':{
  742. 'template': '<div id="<%= node.id %>"><% _.each(node.options, function(key, val) { %><div class="radio"><label><input<%= (fieldHtmlClass ? " class=\'" + fieldHtmlClass + "\'": "") %> type="radio" <% if (((key instanceof Object) && (value === key.value)) || (value === key)) { %> checked="checked" <% } %> name="<%= node.name %>" value="<%= (key instanceof Object ? key.value : key) %>"' +
  743. '<%= (node.disabled? " disabled" : "")%>' +
  744. '<%= (node.schemaElement && node.schemaElement.required ? " required=\'required\'" : "") %>' +
  745. '/><%= (key instanceof Object ? key.title : key) %></label></div> <% }); %></div>',
  746. 'fieldtemplate': true,
  747. 'inputfield': true
  748. },
  749. 'radiobuttons': {
  750. 'template': '<div id="<%= node.id %>">' +
  751. '<% _.each(node.options, function(key, val) { %>' +
  752. '<label class="btn btn-default">' +
  753. '<input<%= (fieldHtmlClass ? " class=\'" + fieldHtmlClass + "\'": "") %> type="radio" style="position:absolute;left:-9999px;" ' +
  754. '<% if (((key instanceof Object) && (value === key.value)) || (value === key)) { %> checked="checked" <% } %> name="<%= node.name %>" value="<%= (key instanceof Object ? key.value : key) %>" />' +
  755. '<span><%= (key instanceof Object ? key.title : key) %></span></label> ' +
  756. '<% }); %>' +
  757. '</div>',
  758. 'fieldtemplate': true,
  759. 'inputfield': true,
  760. 'onInsert': function (evt, node) {
  761. var activeClass = 'active';
  762. var elt = node.formElement || {};
  763. if (elt.activeClass) {
  764. activeClass += ' ' + elt.activeClass;
  765. }
  766. $(node.el).find('label').on('click', function () {
  767. $(this).parent().find('label').removeClass(activeClass);
  768. $(this).addClass(activeClass);
  769. });
  770. }
  771. },
  772. 'checkboxes':{
  773. 'template': '<div><%= choiceshtml %></div>',
  774. 'fieldtemplate': true,
  775. 'inputfield': true,
  776. 'onBeforeRender': function (data, node) {
  777. // Build up choices from the enumeration list
  778. var choices = null;
  779. var choiceshtml = null;
  780. var template = '<div class="checkbox"><label>' +
  781. '<input type="checkbox" <% if (value) { %> checked="checked" <% } %> name="<%= name %>" value="1"' +
  782. '<%= (node.disabled? " disabled" : "")%>' +
  783. '/><%= title %></label></div>';
  784. if (!node || !node.schemaElement) return;
  785. if (node.schemaElement.items) {
  786. choices =
  787. node.schemaElement.items["enum"] ||
  788. node.schemaElement.items[0]["enum"];
  789. } else {
  790. choices = node.schemaElement["enum"];
  791. }
  792. if (!choices) return;
  793. choiceshtml = '';
  794. _.each(choices, function (choice, idx) {
  795. choiceshtml += _.template(template, fieldTemplateSettings)({
  796. name: node.key + '[' + idx + ']',
  797. value: _.include(node.value, choice),
  798. title: hasOwnProperty(node.formElement.titleMap, choice) ? node.formElement.titleMap[choice] : choice,
  799. node: node
  800. });
  801. });
  802. data.choiceshtml = choiceshtml;
  803. }
  804. },
  805. 'array': {
  806. 'template': '<div id="<%= id %>"><ul class="_jsonform-array-ul" style="list-style-type:none;"><%= children %></ul>' +
  807. '<span class="_jsonform-array-buttons">' +
  808. '<a href="#" class="btn btn-default _jsonform-array-addmore"><i class="glyphicon glyphicon-plus-sign" title="Add new"></i></a> ' +
  809. '<a href="#" class="btn btn-default _jsonform-array-deletelast"><i class="glyphicon glyphicon-minus-sign" title="Delete last"></i></a>' +
  810. '</span>' +
  811. '</div>',
  812. 'fieldtemplate': true,
  813. 'array': true,
  814. 'childTemplate': function (inner) {
  815. if ($('').sortable) {
  816. // Insert a "draggable" icon
  817. // floating to the left of the main element
  818. return '<li data-idx="<%= node.childPos %>">' +
  819. '<span class="draggable line"><i class="glyphicon glyphicon-list" title="Move item"></i></span>' +
  820. inner +
  821. '</li>';
  822. }
  823. else {
  824. return '<li data-idx="<%= node.childPos %>">' +
  825. inner +
  826. '</li>';
  827. }
  828. },
  829. 'onInsert': function (evt, node) {
  830. var $nodeid = $(node.el).find('#' + escapeSelector(node.id));
  831. var boundaries = node.getArrayBoundaries();
  832. // Switch two nodes in an array
  833. var moveNodeTo = function (fromIdx, toIdx) {
  834. // Note "switchValuesWith" extracts values from the DOM since field
  835. // values are not synchronized with the tree data structure, so calls
  836. // to render are needed at each step to force values down to the DOM
  837. // before next move.
  838. // TODO: synchronize field values and data structure completely and
  839. // call render only once to improve efficiency.
  840. if (fromIdx === toIdx) return;
  841. var incr = (fromIdx < toIdx) ? 1: -1;
  842. var i = 0;
  843. var parentEl = $('> ul', $nodeid);
  844. for (i = fromIdx; i !== toIdx; i += incr) {
  845. node.children[i].switchValuesWith(node.children[i + incr]);
  846. node.children[i].render(parentEl.get(0));
  847. node.children[i + incr].render(parentEl.get(0));
  848. }
  849. // No simple way to prevent DOM reordering with jQuery UI Sortable,
  850. // so we're going to need to move sorted DOM elements back to their
  851. // origin position in the DOM ourselves (we switched values but not
  852. // DOM elements)
  853. var fromEl = $(node.children[fromIdx].el);
  854. var toEl = $(node.children[toIdx].el);
  855. fromEl.detach();
  856. toEl.detach();
  857. if (fromIdx < toIdx) {
  858. if (fromIdx === 0) parentEl.prepend(fromEl);
  859. else $(node.children[fromIdx-1].el).after(fromEl);
  860. $(node.children[toIdx-1].el).after(toEl);
  861. }
  862. else {
  863. if (toIdx === 0) parentEl.prepend(toEl);
  864. else $(node.children[toIdx-1].el).after(toEl);
  865. $(node.children[fromIdx-1].el).after(fromEl);
  866. }
  867. };
  868. $('> span > a._jsonform-array-addmore', $nodeid).click(function (evt) {
  869. evt.preventDefault();
  870. evt.stopPropagation();
  871. var idx = node.children.length;
  872. if (boundaries.maxItems >= 0) {
  873. if (node.children.length > boundaries.maxItems - 2) {
  874. $nodeid.find('> span > a._jsonform-array-addmore')
  875. .addClass('disabled');
  876. }
  877. if (node.children.length > boundaries.maxItems - 1) {
  878. return false;
  879. }
  880. }
  881. node.insertArrayItem(idx, $('> ul', $nodeid).get(0));
  882. if ((boundaries.minItems <= 0) ||
  883. ((boundaries.minItems > 0) &&
  884. (node.children.length > boundaries.minItems - 1))) {
  885. $nodeid.find('> span > a._jsonform-array-deletelast')
  886. .removeClass('disabled');
  887. }
  888. });
  889. //Simulate Users click to setup the form with its minItems
  890. var curItems = $('> ul > li', $nodeid).length;
  891. if ((boundaries.minItems > 0) &&
  892. (curItems < boundaries.minItems)) {
  893. for (var i = 0; i < (boundaries.minItems - 1) && ($nodeid.find('> ul > li').length < boundaries.minItems); i++) {
  894. //console.log('Calling click: ',$nodeid);
  895. //$('> span > a._jsonform-array-addmore', $nodeid).click();
  896. node.insertArrayItem(curItems, $nodeid.find('> ul').get(0));
  897. }
  898. }
  899. if ((boundaries.minItems > 0) &&
  900. (node.children.length <= boundaries.minItems)) {
  901. $nodeid.find('> span > a._jsonform-array-deletelast')
  902. .addClass('disabled');
  903. }
  904. $('> span > a._jsonform-array-deletelast', $nodeid).click(function (evt) {
  905. var idx = node.children.length - 1;
  906. evt.preventDefault();
  907. evt.stopPropagation();
  908. if (boundaries.minItems > 0) {
  909. if (node.children.length < boundaries.minItems + 2) {
  910. $nodeid.find('> span > a._jsonform-array-deletelast')
  911. .addClass('disabled');
  912. }
  913. if (node.children.length <= boundaries.minItems) {
  914. return false;
  915. }
  916. }
  917. else if (node.children.length === 1) {
  918. $nodeid.find('> span > a._jsonform-array-deletelast')
  919. .addClass('disabled');
  920. }
  921. node.deleteArrayItem(idx);
  922. if ((boundaries.maxItems >= 0) && (idx <= boundaries.maxItems - 1)) {
  923. $nodeid.find('> span > a._jsonform-array-addmore')
  924. .removeClass('disabled');
  925. }
  926. });
  927. if ($(node.el).sortable) {
  928. $('> ul', $nodeid).sortable();
  929. $('> ul', $nodeid).bind('sortstop', function (event, ui) {
  930. var idx = $(ui.item).data('idx');
  931. var newIdx = $(ui.item).index();
  932. moveNodeTo(idx, newIdx);
  933. });
  934. }
  935. }
  936. },
  937. 'tabarray': {
  938. 'template': '<div id="<%= id %>"><div class="tabbable tabs-left">' +
  939. '<ul class="nav nav-tabs">' +
  940. '<%= tabs %>' +
  941. '</ul>' +
  942. '<div class="tab-content">' +
  943. '<%= children %>' +
  944. '</div>' +
  945. '</div>' +
  946. '<a href="#" class="btn btn-default _jsonform-array-addmore"><i class="glyphicon glyphicon-plus-sign" title="Add new"></i></a> ' +
  947. '<a href="#" class="btn btn-default _jsonform-array-deleteitem"><i class="glyphicon glyphicon-minus-sign" title="Delete item"></i></a></div>',
  948. 'fieldtemplate': true,
  949. 'array': true,
  950. 'childTemplate': function (inner) {
  951. return '<div data-idx="<%= node.childPos %>" class="tab-pane">' +
  952. inner +
  953. '</div>';
  954. },
  955. 'onBeforeRender': function (data, node) {
  956. // Generate the initial 'tabs' from the children
  957. var tabs = '';
  958. _.each(node.children, function (child, idx) {
  959. var title = child.legend ||
  960. child.title ||
  961. ('Item ' + (idx+1));
  962. tabs += '<li data-idx="' + idx + '"' +
  963. ((idx === 0) ? ' class="active"' : '') +
  964. '><a class="draggable tab" data-toggle="tab">' +
  965. escapeHTML(title) +
  966. '</a></li>';
  967. });
  968. data.tabs = tabs;
  969. },
  970. 'onInsert': function (evt, node) {
  971. var $nodeid = $(node.el).find('#' + escapeSelector(node.id));
  972. var boundaries = node.getArrayBoundaries();
  973. var moveNodeTo = function (fromIdx, toIdx) {
  974. // Note "switchValuesWith" extracts values from the DOM since field
  975. // values are not synchronized with the tree data structure, so calls
  976. // to render are needed at each step to force values down to the DOM
  977. // before next move.
  978. // TODO: synchronize field values and data structure completely and
  979. // call render only once to improve efficiency.
  980. if (fromIdx === toIdx) return;
  981. var incr = (fromIdx < toIdx) ? 1: -1;
  982. var i = 0;
  983. var tabEl = $('> .tabbable > .tab-content', $nodeid).get(0);
  984. for (i = fromIdx; i !== toIdx; i += incr) {
  985. node.children[i].switchValuesWith(node.children[i + incr]);
  986. node.children[i].render(tabEl);
  987. node.children[i + incr].render(tabEl);
  988. }
  989. };
  990. // Refreshes the list of tabs
  991. var updateTabs = function (selIdx) {
  992. var tabs = '';
  993. var activateFirstTab = false;
  994. if (selIdx === undefined) {
  995. selIdx = $('> .tabbable > .nav-tabs .active', $nodeid).data('idx');
  996. if (selIdx) {
  997. selIdx = parseInt(selIdx, 10);
  998. }
  999. else {
  1000. activateFirstTab = true;
  1001. selIdx = 0;
  1002. }
  1003. }
  1004. if (selIdx >= node.children.length) {
  1005. selIdx = node.children.length - 1;
  1006. }
  1007. _.each(node.children, function (child, idx) {
  1008. $('> .tabbable > .tab-content > [data-idx="' + idx + '"] > fieldset > legend', $nodeid).html(child.legend);
  1009. var title = child.legend || child.title || ('Item ' + (idx+1));
  1010. tabs += '<li data-idx="' + idx + '">' +
  1011. '<a class="draggable tab" data-toggle="tab">' +
  1012. escapeHTML(title) +
  1013. '</a></li>';
  1014. });
  1015. $('> .tabbable > .nav-tabs', $nodeid).html(tabs);
  1016. if (activateFirstTab) {
  1017. $('> .tabbable > .nav-tabs [data-idx="0"]', $nodeid).addClass('active');
  1018. }
  1019. $('> .tabbable > .nav-tabs [data-toggle="tab"]', $nodeid).eq(selIdx).click();
  1020. };
  1021. $('> a._jsonform-array-deleteitem', $nodeid).click(function (evt) {
  1022. var idx = $('> .tabbable > .nav-tabs .active', $nodeid).data('idx');
  1023. evt.preventDefault();
  1024. evt.stopPropagation();
  1025. if (boundaries.minItems > 0) {
  1026. if (node.children.length < boundaries.minItems + 1) {
  1027. $nodeid.find('> a._jsonform-array-deleteitem')
  1028. .addClass('disabled');
  1029. }
  1030. if (node.children.length <= boundaries.minItems) return false;
  1031. }
  1032. node.deleteArrayItem(idx);
  1033. updateTabs();
  1034. if ((node.children.length < boundaries.minItems + 1) ||
  1035. (node.children.length === 0)) {
  1036. $nodeid.find('> a._jsonform-array-deleteitem').addClass('disabled');
  1037. }
  1038. if ((boundaries.maxItems >= 0) &&
  1039. (node.children.length <= boundaries.maxItems)) {
  1040. $nodeid.find('> a._jsonform-array-addmore').removeClass('disabled');
  1041. }
  1042. });
  1043. $('> a._jsonform-array-addmore', $nodeid).click(function (evt) {
  1044. var idx = node.children.length;
  1045. if (boundaries.maxItems>=0) {
  1046. if (node.children.length>boundaries.maxItems-2) {
  1047. $('> a._jsonform-array-addmore', $nodeid).addClass("disabled");
  1048. }
  1049. if (node.children.length > boundaries.maxItems - 1) {
  1050. return false;
  1051. }
  1052. }
  1053. evt.preventDefault();
  1054. evt.stopPropagation();
  1055. node.insertArrayItem(idx,
  1056. $nodeid.find('> .tabbable > .tab-content').get(0));
  1057. updateTabs(idx);
  1058. if ((boundaries.minItems <= 0) ||
  1059. ((boundaries.minItems > 0) && (idx > boundaries.minItems - 1))) {
  1060. $nodeid.find('> a._jsonform-array-deleteitem').removeClass('disabled');
  1061. }
  1062. });
  1063. $(node.el).on('legendUpdated', function (evt) {
  1064. updateTabs();
  1065. evt.preventDefault();
  1066. evt.stopPropagation();
  1067. });
  1068. if ($(node.el).sortable) {
  1069. $('> .tabbable > .nav-tabs', $nodeid).sortable({
  1070. containment: node.el,
  1071. tolerance: 'pointer'
  1072. });
  1073. $('> .tabbable > .nav-tabs', $nodeid).bind('sortstop', function (event, ui) {
  1074. var idx = $(ui.item).data('idx');
  1075. var newIdx = $(ui.item).index();
  1076. moveNodeTo(idx, newIdx);
  1077. updateTabs(newIdx);
  1078. });
  1079. }
  1080. // Simulate User's click to setup the form with its minItems
  1081. if ((boundaries.minItems >= 0) &&
  1082. (node.children.length <= boundaries.minItems)) {
  1083. for (var i = 0; i < (boundaries.minItems - 1); i++) {
  1084. $nodeid.find('> a._jsonform-array-addmore').click();
  1085. }
  1086. $nodeid.find('> a._jsonform-array-deleteitem').addClass('disabled');
  1087. updateTabs();
  1088. }
  1089. if ((boundaries.maxItems >= 0) &&
  1090. (node.children.length >= boundaries.maxItems)) {
  1091. $nodeid.find('> a._jsonform-array-addmore').addClass('disabled');
  1092. }
  1093. if ((boundaries.minItems >= 0) &&
  1094. (node.children.length <= boundaries.minItems)) {
  1095. $nodeid.find('> a._jsonform-array-deleteitem').addClass('disabled');
  1096. }
  1097. }
  1098. },
  1099. 'help': {
  1100. 'template':'<span class="help-block" style="padding-top:5px"><%= elt.helpvalue %></span>',
  1101. 'fieldtemplate': true
  1102. },
  1103. 'msg': {
  1104. 'template': '<%= elt.msg %>'
  1105. },
  1106. 'fieldset': {
  1107. 'template': '<fieldset class="form-group jsonform-error-<%= keydash %> <% if (elt.expandable) { %>expandable<% } %> <%= elt.htmlClass?elt.htmlClass:"" %>" ' +
  1108. '<% if (id) { %> id="<%= id %>"<% } %>' +
  1109. '>' +
  1110. '<% if (node.title || node.legend) { %><legend><%= node.title || node.legend %></legend><% } %>' +
  1111. '<% if (elt.expandable) { %><div class="form-group"><% } %>' +
  1112. '<%= children %>' +
  1113. '<% if (elt.expandable) { %></div><% } %>' +
  1114. '</fieldset>',
  1115. onInsert: function (evt, node) {
  1116. $('.expandable > div, .expandable > fieldset', node.el).hide();
  1117. // See #233
  1118. $(".expandable", node.el).removeClass("expanded");
  1119. }
  1120. },
  1121. 'advancedfieldset': {
  1122. 'template': '<fieldset' +
  1123. '<% if (id) { %> id="<%= id %>"<% } %>' +
  1124. ' class="expandable <%= elt.htmlClass?elt.htmlClass:"" %>">' +
  1125. '<legend><%= (node.title || node.legend) ? (node.title || node.legend) : "Advanced options" %></legend>' +
  1126. '<div class="form-group">' +
  1127. '<%= children %>' +
  1128. '</div>' +
  1129. '</fieldset>',
  1130. onInsert: function (evt, node) {
  1131. $('.expandable > div, .expandable > fieldset', node.el).hide();
  1132. // See #233
  1133. $(".expandable", node.el).removeClass("expanded");
  1134. }
  1135. },
  1136. 'authfieldset': {
  1137. 'template': '<fieldset' +
  1138. '<% if (id) { %> id="<%= id %>"<% } %>' +
  1139. ' class="expandable <%= elt.htmlClass?elt.htmlClass:"" %>">' +
  1140. '<legend><%= (node.title || node.legend) ? (node.title || node.legend) : "Authentication settings" %></legend>' +
  1141. '<div class="form-group">' +
  1142. '<%= children %>' +
  1143. '</div>' +
  1144. '</fieldset>',
  1145. onInsert: function (evt, node) {
  1146. $('.expandable > div, .expandable > fieldset', node.el).hide();
  1147. // See #233
  1148. $(".expandable", node.el).removeClass("expanded");
  1149. }
  1150. },
  1151. 'submit':{
  1152. 'template':'<input type="submit" <% if (id) { %> id="<%= id %>" <% } %> class="btn btn-primary <%= elt.htmlClass?elt.htmlClass:"" %>" value="<%= value || node.title %>"<%= (node.disabled? " disabled" : "")%>/>'
  1153. },
  1154. 'button':{
  1155. 'template':' <button type="button" <% if (id) { %> id="<%= id %>" <% } %> class="btn btn-default <%= elt.htmlClass?elt.htmlClass:"" %>"><%= node.title %></button> '
  1156. },
  1157. 'actions':{
  1158. 'template':'<div class="<%= elt.htmlClass?elt.htmlClass:"" %>"><%= children %></div>'
  1159. },
  1160. 'hidden':{
  1161. 'template':'<input type="hidden" id="<%= id %>" name="<%= node.name %>" value="<%= escape(value) %>" />',
  1162. 'inputfield': true
  1163. },
  1164. 'selectfieldset': {
  1165. 'template': '<fieldset class="tab-container <%= elt.htmlClass?elt.htmlClass:"" %>">' +
  1166. '<% if (node.legend) { %><legend><%= node.legend %></legend><% } %>' +
  1167. '<% if (node.formElement.key) { %><input type="hidden" id="<%= node.id %>" name="<%= node.name %>" value="<%= escape(value) %>" /><% } else { %>' +
  1168. '<a id="<%= node.id %>"></a><% } %>' +
  1169. '<div class="tabbable">' +
  1170. '<div class="form-group<%= node.formElement.hideMenu ? " hide" : "" %>">' +
  1171. '<% if (!elt.notitle) { %><label for="<%= node.id %>"><%= node.title ? node.title : node.name %></label><% } %>' +
  1172. '<div class="controls"><%= tabs %></div>' +
  1173. '</div>' +
  1174. '<div class="tab-content">' +
  1175. '<%= children %>' +
  1176. '</div>' +
  1177. '</div>' +
  1178. '</fieldset>',
  1179. 'inputfield': true,
  1180. 'getElement': function (el) {
  1181. return $(el).parent().get(0);
  1182. },
  1183. 'childTemplate': function (inner) {
  1184. return '<div data-idx="<%= node.childPos %>" class="tab-pane' +
  1185. '<% if (node.active) { %> active<% } %>">' +
  1186. inner +
  1187. '</div>';
  1188. },
  1189. 'onBeforeRender': function (data, node) {
  1190. // Before rendering, this function ensures that:
  1191. // 1. direct children have IDs (used to show/hide the tabs contents)
  1192. // 2. the tab to active is flagged accordingly. The active tab is
  1193. // the first one, except if form values are available, in which case
  1194. // it's the first tab for which there is some value available (or back
  1195. // to the first one if there are none)
  1196. // 3. the HTML of the select field used to select tabs is exposed in the
  1197. // HTML template data as "tabs"
  1198. var children = null;
  1199. var choices = [];
  1200. if (node.schemaElement) {
  1201. choices = node.schemaElement['enum'] || [];
  1202. }
  1203. if (node.options) {
  1204. children = _.map(node.options, function (option, idx) {
  1205. var child = node.children[idx];
  1206. child.childPos = idx; // When nested the childPos is always 0.
  1207. if (option instanceof Object) {
  1208. option = _.extend({ node: child }, option);
  1209. option.title = option.title ||
  1210. child.legend ||
  1211. child.title ||
  1212. ('Option ' + (child.childPos+1));
  1213. option.value = isSet(option.value) ? option.value :
  1214. isSet(choices[idx]) ? choices[idx] : idx;
  1215. return option;
  1216. }
  1217. else {
  1218. return {
  1219. title: option,
  1220. value: isSet(choices[child.childPos]) ?
  1221. choices[child.childPos] :
  1222. child.childPos,
  1223. node: child
  1224. };
  1225. }
  1226. });
  1227. }
  1228. else {
  1229. children = _.map(node.children, function (child, idx) {
  1230. child.childPos = idx; // When nested the childPos is always 0.
  1231. return {
  1232. title: child.legend || child.title || ('Option ' + (child.childPos+1)),
  1233. value: choices[child.childPos] || child.childPos,
  1234. node: child
  1235. };
  1236. });
  1237. }
  1238. // Reset each children to inactive so that they are not shown on insert
  1239. // The active one will then be shown later one. This is useful when sorting
  1240. // arrays with selectfieldset, otherwise both fields could be active at the
  1241. // same time.
  1242. _.each(children, function (child, idx) {
  1243. child.node.active = false
  1244. });
  1245. var activeChild = null;
  1246. if (data.value) {
  1247. activeChild = _.find(children, function (child) {
  1248. return (child.value === node.value);
  1249. });
  1250. }
  1251. if (!activeChild) {
  1252. activeChild = _.find(children, function (child) {
  1253. return child.node.hasNonDefaultValue();
  1254. });
  1255. }
  1256. if (!activeChild) {
  1257. activeChild = children[0];
  1258. }
  1259. activeChild.node.active = true;
  1260. data.value = activeChild.value;
  1261. var elt = node.formElement;
  1262. var tabs = '<select class="nav"' +
  1263. (node.disabled ? ' disabled' : '') +
  1264. '>';
  1265. _.each(children, function (child, idx) {
  1266. tabs += '<option data-idx="' + idx + '" value="' + child.value + '"' +
  1267. (child.node.active ? ' selected="selected" class="active"' : '') +
  1268. '>' +
  1269. escapeHTML(child.title) +
  1270. '</option>';
  1271. });
  1272. tabs += '</select>';
  1273. data.tabs = tabs;
  1274. return data;
  1275. },
  1276. 'onInsert': function (evt, node) {
  1277. $(node.el).find('select.nav').first().on('change', function (evt) {
  1278. var $option = $(this).find('option:selected');
  1279. $(node.el).find('input[type="hidden"]').first().val($option.attr('value'));
  1280. });
  1281. }
  1282. },
  1283. 'optionfieldset': {
  1284. 'template': '<div' +
  1285. '<% if (node.id) { %> id="<%= node.id %>"<% } %>' +
  1286. '>' +
  1287. '<%= children %>' +
  1288. '</div>'
  1289. },
  1290. 'section': {
  1291. 'template': '<div' +
  1292. '<% if (elt.htmlClass) { %> class="<%= elt.htmlClass %>"<% } %>' +
  1293. '<% if (node.id) { %> id="<%= node.id %>"<% } %>' +
  1294. '><%= children %></div>'
  1295. },
  1296. /**
  1297. * A "questions" field renders a series of question fields and binds the
  1298. * result to the value of a schema key.
  1299. */
  1300. 'questions': {
  1301. 'template': '<div>' +
  1302. '<input type="hidden" id="<%= node.id %>" name="<%= node.name %>" value="<%= escape(value) %>" />' +
  1303. '<%= children %>' +
  1304. '</div>',
  1305. 'fieldtemplate': true,
  1306. 'inputfield': true,
  1307. 'getElement': function (el) {
  1308. return $(el).parent().get(0);
  1309. },
  1310. 'onInsert': function (evt, node) {
  1311. if (!node.children || (node.children.length === 0)) return;
  1312. _.each(node.children, function (child) {
  1313. $(child.el).hide();
  1314. });
  1315. $(node.children[0].el).show();
  1316. }
  1317. },
  1318. /**
  1319. * A "question" field lets user choose a response among possible choices.
  1320. * The field is not associated with any schema key. A question should be
  1321. * part of a "questions" field that binds a series of questions to a
  1322. * schema key.
  1323. */
  1324. 'question': {
  1325. 'template': '<div id="<%= node.id %>"><% _.each(node.options, function(key, val) { %><label class="<%= (node.formElement.optionsType === "radiobuttons") ? "btn btn-default" : "" %><%= ((key instanceof Object && key.htmlClass) ? " " + key.htmlClass : "") %>"><input type="radio" <% if (node.formElement.optionsType === "radiobuttons") { %> style="position:absolute;left:-9999px;" <% } %>name="<%= node.id %>" value="<%= val %>"<%= (node.disabled? " disabled" : "")%>/><span><%= (key instanceof Object ? key.title : key) %></span></label> <% }); %></div>',
  1326. 'fieldtemplate': true,
  1327. 'onInsert': function (evt, node) {
  1328. var activeClass = 'active';
  1329. var elt = node.formElement || {};
  1330. if (elt.activeClass) {
  1331. activeClass += ' ' + elt.activeClass;
  1332. }
  1333. // Bind to change events on radio buttons
  1334. $(node.el).find('input[type="radio"]').on('change', function (evt) {
  1335. var questionNode = null;
  1336. var option = node.options[$(this).val()];
  1337. if (!node.parentNode || !node.parentNode.el) return;
  1338. $(this).parent().parent().find('label').removeClass(activeClass);
  1339. $(this).parent().addClass(activeClass);
  1340. $(node.el).nextAll().hide();
  1341. $(node.el).nextAll().find('input[type="radio"]').prop('checked', false);
  1342. // Execute possible actions (set key value, form submission, open link,
  1343. // move on to next question)
  1344. if (option.value) {
  1345. // Set the key of the 'Questions' parent
  1346. $(node.parentNode.el).find('input[type="hidden"]').val(option.value);
  1347. }
  1348. if (option.next) {
  1349. questionNode = _.find(node.parentNode.children, function (child) {
  1350. return (child.formElement && (child.formElement.qid === option.next));
  1351. });
  1352. $(questionNode.el).show();
  1353. $(questionNode.el).nextAll().hide();
  1354. $(questionNode.el).nextAll().find('input[type="radio"]').prop('checked', false);
  1355. }
  1356. if (option.href) {
  1357. if (option.target) {
  1358. window.open(option.href, option.target);
  1359. }
  1360. else {
  1361. window.location = option.href;
  1362. }
  1363. }
  1364. if (option.submit) {
  1365. setTimeout(function () {
  1366. node.ownerTree.submit();
  1367. }, 0);
  1368. }
  1369. });
  1370. }
  1371. }
  1372. };
  1373. //Allow to access subproperties by splitting "."
  1374. /**
  1375. * Retrieves the key identified by a path selector in the structured object.
  1376. *
  1377. * Levels in the path are separated by a dot. Array items are marked
  1378. * with [x]. For instance:
  1379. * foo.bar[3].baz
  1380. *
  1381. * @function
  1382. * @param {Object} obj Structured object to parse
  1383. * @param {String} key Path to the key to retrieve
  1384. * @param {boolean} ignoreArrays True to use first element in an array when
  1385. * stucked on a property. This parameter is basically only useful when
  1386. * parsing a JSON schema for which the "items" property may either be an
  1387. * object or an array with one object (only one because JSON form does not
  1388. * support mix of items for arrays).
  1389. * @return {Object} The key's value.
  1390. */
  1391. jsonform.util.getObjKey = function (obj, key, ignoreArrays) {
  1392. var innerobj = obj;
  1393. var keyparts = key.split(".");
  1394. var subkey = null;
  1395. var arrayMatch = null;
  1396. var prop = null;
  1397. for (var i = 0; i < keyparts.length; i++) {
  1398. if ((innerobj === null) || (typeof innerobj !== "object")) return null;
  1399. subkey = keyparts[i];
  1400. prop = subkey.replace(reArray, '');
  1401. reArray.lastIndex = 0;
  1402. arrayMatch = reArray.exec(subkey);
  1403. if (arrayMatch) {
  1404. while (true) {
  1405. if (prop && !_.isArray(innerobj[prop])) return null;
  1406. innerobj = prop ? innerobj[prop][parseInt(arrayMatch[1])] : innerobj[parseInt(arrayMatch[1])];
  1407. arrayMatch = reArray.exec(subkey);
  1408. if (!arrayMatch) break;
  1409. // In the case of multidimensional arrays,
  1410. // we should not take innerobj[prop][0] anymore,
  1411. // but innerobj[0] directly
  1412. prop = null;
  1413. }
  1414. } else if (ignoreArrays &&
  1415. !innerobj[prop] &&
  1416. _.isArray(innerobj) &&
  1417. innerobj[0]) {
  1418. innerobj = innerobj[0][prop];
  1419. } else {
  1420. innerobj = innerobj[prop];
  1421. }
  1422. }
  1423. if (ignoreArrays && _.isArray(innerobj) && innerobj[0]) {
  1424. return innerobj[0];
  1425. } else {
  1426. return innerobj;
  1427. }
  1428. };
  1429. /**
  1430. * Sets the key identified by a path selector to the given value.
  1431. *
  1432. * Levels in the path are separated by a dot. Array items are marked
  1433. * with [x]. For instance:
  1434. * foo.bar[3].baz
  1435. *
  1436. * The hierarchy is automatically created if it does not exist yet.
  1437. *
  1438. * @function
  1439. * @param {Object} obj The object to build
  1440. * @param {String} key The path to the key to set where each level
  1441. * is separated by a dot, and array items are flagged with [x].
  1442. * @param {Object} value The value to set, may be of any type.
  1443. */
  1444. jsonform.util.setObjKey = function(obj,key,value) {
  1445. var innerobj = obj;
  1446. var keyparts = key.split(".");
  1447. var subkey = null;
  1448. var arrayMatch = null;
  1449. var prop = null;
  1450. for (var i = 0; i < keyparts.length-1; i++) {
  1451. subkey = keyparts[i];
  1452. prop = subkey.replace(reArray, '');
  1453. reArray.lastIndex = 0;
  1454. arrayMatch = reArray.exec(subkey);
  1455. if (arrayMatch) {
  1456. // Subkey is part of an array
  1457. while (true) {
  1458. if (!_.isArray(innerobj[prop])) {
  1459. innerobj[prop] = [];
  1460. }
  1461. innerobj = innerobj[prop];
  1462. prop = parseInt(arrayMatch[1], 10);
  1463. arrayMatch = reArray.exec(subkey);
  1464. if (!arrayMatch) break;
  1465. }
  1466. if ((typeof innerobj[prop] !== 'object') ||
  1467. (innerobj[prop] === null)) {
  1468. innerobj[prop] = {};
  1469. }
  1470. innerobj = innerobj[prop];
  1471. }
  1472. else {
  1473. // "Normal" subkey
  1474. if ((typeof innerobj[prop] !== 'object') ||
  1475. (innerobj[prop] === null)) {
  1476. innerobj[prop] = {};
  1477. }
  1478. innerobj = innerobj[prop];
  1479. }
  1480. }
  1481. // Set the final value
  1482. subkey = keyparts[keyparts.length - 1];
  1483. prop = subkey.replace(reArray, '');
  1484. reArray.lastIndex = 0;
  1485. arrayMatch = reArray.exec(subkey);
  1486. if (arrayMatch) {
  1487. while (true) {
  1488. if (!_.isArray(innerobj[prop])) {
  1489. innerobj[prop] = [];
  1490. }
  1491. innerobj = innerobj[prop];
  1492. prop = parseInt(arrayMatch[1], 10);
  1493. arrayMatch = reArray.exec(subkey);
  1494. if (!arrayMatch) break;
  1495. }
  1496. innerobj[prop] = value;
  1497. }
  1498. else {
  1499. innerobj[prop] = value;
  1500. }
  1501. };
  1502. /**
  1503. * Retrieves the key definition from the given schema.
  1504. *
  1505. * The key is identified by the path that leads to the key in the
  1506. * structured object that the schema would generate. Each level is
  1507. * separated by a '.'. Array levels are marked with []. For instance:
  1508. * foo.bar[].baz
  1509. * ... to retrieve the definition of the key at the following location
  1510. * in the JSON schema (using a dotted path notation):
  1511. * foo.properties.bar.items.properties.baz
  1512. *
  1513. * @function
  1514. * @param {Object} schema The JSON schema to retrieve the key from
  1515. * @param {String} key The path to the key, each level being separated
  1516. * by a dot and array items being flagged with [].
  1517. * @return {Object} The key definition in the schema, null if not found.
  1518. */
  1519. var getSchemaKey = function(schema,key) {
  1520. var schemaKey = key
  1521. .replace(/\./g, '.properties.')
  1522. .replace(/\[[0-9]*\]/g, '.items');
  1523. var schemaDef = jsonform.util.getObjKey(schema, schemaKey, true);
  1524. if (schemaDef && schemaDef.$ref) {
  1525. throw new Error('JSONForm does not yet support schemas that use the ' +
  1526. '$ref keyword. See: https://github.com/joshfire/jsonform/issues/54');
  1527. }
  1528. return schemaDef;
  1529. };
  1530. /**
  1531. * Truncates the key path to the requested depth.
  1532. *
  1533. * For instance, if the key path is:
  1534. * foo.bar[].baz.toto[].truc[].bidule
  1535. * and the requested depth is 1, the returned key will be:
  1536. * foo.bar[].baz.toto
  1537. *
  1538. * Note the function includes the path up to the next depth level.
  1539. *
  1540. * @function
  1541. * @param {String} key The path to the key in the schema, each level being
  1542. * separated by a dot and array items being flagged with [].
  1543. * @param {Number} depth The array depth
  1544. * @return {String} The path to the key truncated to the given depth.
  1545. */
  1546. var truncateToArrayDepth = function (key, arrayDepth) {
  1547. var depth = 0;
  1548. var pos = 0;
  1549. if (!key) return null;
  1550. if (arrayDepth > 0) {
  1551. while (depth < arrayDepth) {
  1552. pos = key.indexOf('[]', pos);
  1553. if (pos === -1) {
  1554. // Key path is not "deep" enough, simply return the full key
  1555. return key;
  1556. }
  1557. pos = pos + 2;
  1558. depth += 1;
  1559. }
  1560. }
  1561. // Move one step further to the right without including the final []
  1562. pos = key.indexOf('[]', pos);
  1563. if (pos === -1) return key;
  1564. else return key.substring(0, pos);
  1565. };
  1566. /**
  1567. * Applies the array path to the key path.
  1568. *
  1569. * For instance, if the key path is:
  1570. * foo.bar[].baz.toto[].truc[].bidule
  1571. * and the arrayPath [4, 2], the returned key will be:
  1572. * foo.bar[4].baz.toto[2].truc[].bidule
  1573. *
  1574. * @function
  1575. * @param {String} key The path to the key in the schema, each level being
  1576. * separated by a dot and array items being flagged with [].
  1577. * @param {Array(Number)} arrayPath The array path to apply, e.g. [4, 2]
  1578. * @return {String} The path to the key that matches the array path.
  1579. */
  1580. var applyArrayPath = function (key, arrayPath) {
  1581. var depth = 0;
  1582. if (!key) return null;
  1583. if (!arrayPath || (arrayPath.length === 0)) return key;
  1584. var newKey = key.replace(reArray, function (str, p1) {
  1585. // Note this function gets called as many times as there are [x] in the ID,
  1586. // from left to right in the string. The goal is to replace the [x] with
  1587. // the appropriate index in the new array path, if defined.
  1588. var newIndex = str;
  1589. if (isSet(arrayPath[depth])) {
  1590. newIndex = '[' + arrayPath[depth] + ']';
  1591. }
  1592. depth += 1;
  1593. return newIndex;
  1594. });
  1595. return newKey;
  1596. };
  1597. /**
  1598. * Returns the initial value that a field identified by its key
  1599. * should take.
  1600. *
  1601. * The "initial" value is defined as:
  1602. * 1. the previously submitted value if already submitted
  1603. * 2. the default value defined in the layout of the form
  1604. * 3. the default value defined in the schema
  1605. *
  1606. * The "value" returned is intended for rendering purpose,
  1607. * meaning that, for fields that define a titleMap property,
  1608. * the function returns the label, and not the intrinsic value.
  1609. *
  1610. * The function handles values that contains template strings,
  1611. * e.g. {{values.foo[].bar}} or {{idx}}.
  1612. *
  1613. * When the form is a string, the function truncates the resulting string
  1614. * to meet a potential "maxLength" constraint defined in the schema, using
  1615. * "..." to mark the truncation. Note it does not validate the resulting
  1616. * string against other constraints (e.g. minLength, pattern) as it would
  1617. * be hard to come up with an automated course of action to "fix" the value.
  1618. *
  1619. * @function
  1620. * @param {Object} formObject The JSON Form object
  1621. * @param {String} key The generic key path (e.g. foo[].bar.baz[])
  1622. * @param {Array(Number)} arrayPath The array path that identifies
  1623. * the unique value in the submitted form (e.g. [1, 3])
  1624. * @param {Object} tpldata Template data object
  1625. * @param {Boolean} usePreviousValues true to use previously submitted values
  1626. * if defined.
  1627. */
  1628. var getInitialValue = function (formObject, key, arrayPath, tpldata, usePreviousValues) {
  1629. var value = null;
  1630. // Complete template data for template function
  1631. tpldata = tpldata || {};
  1632. tpldata.idx = tpldata.idx ||
  1633. (arrayPath ? arrayPath[arrayPath.length-1] : 1);
  1634. tpldata.value = isSet(tpldata.value) ? tpldata.value : '';
  1635. tpldata.getValue = tpldata.getValue || function (key) {
  1636. return getInitialValue(formObject, key, arrayPath, tpldata, usePreviousValues);
  1637. };
  1638. // Helper function that returns the form element that explicitly
  1639. // references the given key in the schema.
  1640. var getFormElement = function (elements, key) {
  1641. var formElement = null;
  1642. if (!elements || !elements.length) return null;
  1643. _.each(elements, function (elt) {
  1644. if (formElement) return;
  1645. if (elt === key) {
  1646. formElement = { key: elt };
  1647. return;
  1648. }
  1649. if (_.isString(elt)) return;
  1650. if (elt.key === key) {
  1651. formElement = elt;
  1652. }
  1653. else if (elt.items) {
  1654. formElement = getFormElement(elt.items, key);
  1655. }
  1656. });
  1657. return formElement;
  1658. };
  1659. var formElement = getFormElement(formObject.form || [], key);
  1660. var schemaElement = getSchemaKey(formObject.schema.properties, key);
  1661. if (usePreviousValues && formObject.value) {
  1662. // If values were previously submitted, use them directly if defined
  1663. value = jsonform.util.getObjKey(formObject.value, applyArrayPath(key, arrayPath));
  1664. }
  1665. if (!isSet(value)) {
  1666. if (formElement && (typeof formElement['value'] !== 'undefined')) {
  1667. // Extract the definition of the form field associated with
  1668. // the key as it may override the schema's default value
  1669. // (note a "null" value overrides a schema default value as well)
  1670. value = formElement['value'];
  1671. }
  1672. else if (schemaElement) {
  1673. // Simply extract the default value from the schema
  1674. if (isSet(schemaElement['default'])) {
  1675. value = schemaElement['default'];
  1676. }
  1677. }
  1678. if (value && value.indexOf('{{values.') !== -1) {
  1679. // This label wants to use the value of another input field.
  1680. // Convert that construct into {{getValue(key)}} for
  1681. // Underscore to call the appropriate function of formData
  1682. // when template gets called (note calling a function is not
  1683. // exactly Mustache-friendly but is supported by Underscore).
  1684. value = value.replace(
  1685. /\{\{values\.([^\}]+)\}\}/g,
  1686. '{{getValue("$1")}}');
  1687. }
  1688. if (value) {
  1689. value = _.template(value, valueTemplateSettings)(tpldata);
  1690. }
  1691. }
  1692. // TODO: handle on the formElement.options, because user can setup it too.
  1693. // Apply titleMap if needed
  1694. if (isSet(value) && formElement && hasOwnProperty(formElement.titleMap, value)) {
  1695. value = _.template(formElement.titleMap[value], valueTemplateSettings)(tpldata);
  1696. }
  1697. // Check maximum length of a string
  1698. if (value && _.isString(value) &&
  1699. schemaElement && schemaElement.maxLength) {
  1700. if (value.length > schemaElement.maxLength) {
  1701. // Truncate value to maximum length, adding continuation dots
  1702. value = value.substr(0, schemaElement.maxLength - 1) + '…';
  1703. }
  1704. }
  1705. if (!isSet(value)) {
  1706. return null;
  1707. }
  1708. else {
  1709. return value;
  1710. }
  1711. };
  1712. /**
  1713. * Represents a node in the form.
  1714. *
  1715. * Nodes that have an ID are linked to the corresponding DOM element
  1716. * when rendered
  1717. *
  1718. * Note the form element and the schema elements that gave birth to the
  1719. * node may be shared among multiple nodes (in the case of arrays).
  1720. *
  1721. * @class
  1722. */
  1723. var formNode = function () {
  1724. /**
  1725. * The node's ID (may not be set)
  1726. */
  1727. this.id = null;
  1728. /**
  1729. * The node's key path (may not be set)
  1730. */
  1731. this.key = null;
  1732. /**
  1733. * DOM element associated witht the form element.
  1734. *
  1735. * The DOM element is set when the form element is rendered.
  1736. */
  1737. this.el = null;
  1738. /**
  1739. * Link to the form element that describes the node's layout
  1740. * (note the form element is shared among nodes in arrays)
  1741. */
  1742. this.formElement = null;
  1743. /**
  1744. * Link to the schema element that describes the node's value constraints
  1745. * (note the schema element is shared among nodes in arrays)
  1746. */
  1747. this.schemaElement = null;
  1748. /**
  1749. * Pointer to the "view" associated with the node, typically the right
  1750. * object in jsonform.elementTypes
  1751. */
  1752. this.view = null;
  1753. /**
  1754. * Node's subtree (if one is defined)
  1755. */
  1756. this.children = [];
  1757. /**
  1758. * A pointer to the form tree the node is attached to
  1759. */
  1760. this.ownerTree = null;
  1761. /**
  1762. * A pointer to the parent node of the node in the tree
  1763. */
  1764. this.parentNode = null;
  1765. /**
  1766. * Child template for array-like nodes.
  1767. *
  1768. * The child template gets cloned to create new array items.
  1769. */
  1770. this.childTemplate = null;
  1771. /**
  1772. * Direct children of array-like containers may use the value of a
  1773. * specific input field in their subtree as legend. The link to the
  1774. * legend child is kept here and initialized in computeInitialValues
  1775. * when a child sets "valueInLegend"
  1776. */
  1777. this.legendChild = null;
  1778. /**
  1779. * The path of indexes that lead to the current node when the
  1780. * form element is not at the root array level.
  1781. *
  1782. * Note a form element may well be nested element and still be
  1783. * at the root array level. That's typically the case for "fieldset"
  1784. * elements. An array level only gets created when a form element
  1785. * is of type "array" (or a derivated type such as "tabarray").
  1786. *
  1787. * The array path of a form element linked to the foo[2].bar.baz[3].toto
  1788. * element in the submitted values is [2, 3] for instance.
  1789. *
  1790. * The array path is typically used to compute the right ID for input
  1791. * fields. It is also used to update positions when an array item is
  1792. * created, moved around or suppressed.
  1793. *
  1794. * @type {Array(Number)}
  1795. */
  1796. this.arrayPath = [];
  1797. /**
  1798. * Position of the node in the list of children of its parents
  1799. */
  1800. this.childPos = 0;
  1801. };
  1802. /**
  1803. * Clones a node
  1804. *
  1805. * @function
  1806. * @param {formNode} New parent node to attach the node to
  1807. * @return {formNode} Cloned node
  1808. */
  1809. formNode.prototype.clone = function (parentNode) {
  1810. var node = new formNode();
  1811. node.arrayPath = _.clone(this.arrayPath);
  1812. node.ownerTree = this.ownerTree;
  1813. node.parentNode = parentNode || this.parentNode;
  1814. node.formElement = this.formElement;
  1815. node.schemaElement = this.schemaElement;
  1816. node.view = this.view;
  1817. node.children = _.map(this.children, function (child) {
  1818. return child.clone(node);
  1819. });
  1820. if (this.childTemplate) {
  1821. node.childTemplate = this.childTemplate.clone(node);
  1822. }
  1823. return node;
  1824. };
  1825. /**
  1826. * Returns true if the subtree that starts at the current node
  1827. * has some non empty value attached to it
  1828. */
  1829. formNode.prototype.hasNonDefaultValue = function () {
  1830. // hidden elements don't count because they could make the wrong selectfieldset element active
  1831. if (this.formElement && this.formElement.type=="hidden") {
  1832. return false;
  1833. }
  1834. if (this.value && !this.defaultValue) {
  1835. return true;
  1836. }
  1837. var child = _.find(this.children, function (child) {
  1838. return child.hasNonDefaultValue();
  1839. });
  1840. return !!child;
  1841. };
  1842. /**
  1843. * Attaches a child node to the current node.
  1844. *
  1845. * The child node is appended to the end of the list.
  1846. *
  1847. * @function
  1848. * @param {formNode} node The child node to append
  1849. * @return {formNode} The inserted node (same as the one given as parameter)
  1850. */
  1851. formNode.prototype.appendChild = function (node) {
  1852. node.parentNode = this;
  1853. node.childPos = this.children.length;
  1854. this.children.push(node);
  1855. return node;
  1856. };
  1857. /**
  1858. * Removes the last child of the node.
  1859. *
  1860. * @function
  1861. */
  1862. formNode.prototype.removeChild = function () {
  1863. var child = this.children[this.children.length-1];
  1864. if (!child) return;
  1865. // Remove the child from the DOM
  1866. $(child.el).remove();
  1867. // Remove the child from the array
  1868. return this.children.pop();
  1869. };
  1870. /**
  1871. * Moves the user entered values set in the current node's subtree to the
  1872. * given node's subtree.
  1873. *
  1874. * The target node must follow the same structure as the current node
  1875. * (typically, they should have been generated from the same node template)
  1876. *
  1877. * The current node MUST be rendered in the DOM.
  1878. *
  1879. * TODO: when current node is not in the DOM, extract values from formNode.value
  1880. * properties, so that the function be available even when current node is not
  1881. * in the DOM.
  1882. *
  1883. * Moving values around allows to insert/remove array items at arbitrary
  1884. * positions.
  1885. *
  1886. * @function
  1887. * @param {formNode} node Target node.
  1888. */
  1889. formNode.prototype.moveValuesTo = function (node) {
  1890. var values = this.getFormValues(node.arrayPath);
  1891. node.resetValues();
  1892. node.computeInitialValues(values, true);
  1893. };
  1894. /**
  1895. * Switches nodes user entered values.
  1896. *
  1897. * The target node must follow the same structure as the current node
  1898. * (typically, they should have been generated from the same node template)
  1899. *
  1900. * Both nodes MUST be rendered in the DOM.
  1901. *
  1902. * TODO: update getFormValues to work even if node is not rendered, using
  1903. * formNode's "value" property.
  1904. *
  1905. * @function
  1906. * @param {formNode} node Target node
  1907. */
  1908. formNode.prototype.switchValuesWith = function (node) {
  1909. var values = this.getFormValues(node.arrayPath);
  1910. var nodeValues = node.getFormValues(this.arrayPath);
  1911. node.resetValues();
  1912. node.computeInitialValues(values, true);
  1913. this.resetValues();
  1914. this.computeInitialValues(nodeValues, true);
  1915. };
  1916. /**
  1917. * Resets all DOM values in the node's subtree.
  1918. *
  1919. * This operation also drops all array item nodes.
  1920. * Note values are not reset to their default values, they are rather removed!
  1921. *
  1922. * @function
  1923. */
  1924. formNode.prototype.resetValues = function () {
  1925. var params = null;
  1926. var idx = 0;
  1927. // Reset value
  1928. this.value = null;
  1929. // Propagate the array path from the parent node
  1930. // (adding the position of the child for nodes that are direct
  1931. // children of array-like nodes)
  1932. if (this.parentNode) {
  1933. this.arrayPath = _.clone(this.parentNode.arrayPath);
  1934. if (this.parentNode.view && this.parentNode.view.array) {
  1935. this.arrayPath.push(this.childPos);
  1936. }
  1937. }
  1938. else {
  1939. this.arrayPath = [];
  1940. }
  1941. if (this.view && this.view.inputfield) {
  1942. // Simple input field, extract the value from the origin,
  1943. // set the target value and reset the origin value
  1944. params = $(':input', this.el).serializeArray();
  1945. _.each(params, function (param) {
  1946. // TODO: check this, there may exist corner cases with this approach
  1947. // (with multiple checkboxes for instance)
  1948. $('[name="' + escapeSelector(param.name) + '"]', $(this.el)).val('');
  1949. }, this);
  1950. }
  1951. else if (this.view && this.view.array) {
  1952. // The current node is an array, drop all children
  1953. while (this.children.length > 0) {
  1954. this.removeChild();
  1955. }
  1956. }
  1957. // Recurse down the tree
  1958. _.each(this.children, function (child) {
  1959. child.resetValues();
  1960. });
  1961. };
  1962. /**
  1963. * Sets the child template node for the current node.
  1964. *
  1965. * The child template node is used to create additional children
  1966. * in an array-like form element. The template is never rendered.
  1967. *
  1968. * @function
  1969. * @param {formNode} node The child template node to set
  1970. */
  1971. formNode.prototype.setChildTemplate = function (node) {
  1972. this.childTemplate = node;
  1973. node.parentNode = this;
  1974. };
  1975. /**
  1976. * Recursively sets values to all nodes of the current subtree
  1977. * based on previously submitted values, or based on default
  1978. * values when the submitted values are not enough
  1979. *
  1980. * The function should be called once in the lifetime of a node
  1981. * in the tree. It expects its parent's arrayPath to be up to date.
  1982. *
  1983. * Three cases may arise:
  1984. * 1. if the form element is a simple input field, the value is
  1985. * extracted from previously submitted values of from default values
  1986. * defined in the schema.
  1987. * 2. if the form element is an array-like node, the child template
  1988. * is used to create as many children as possible (and at least one).
  1989. * 3. the function simply recurses down the node's subtree otherwise
  1990. * (this happens when the form element is a fieldset-like element).
  1991. *
  1992. * @function
  1993. * @param {Object} values Previously submitted values for the form
  1994. * @param {Boolean} ignoreDefaultValues Ignore default values defined in the
  1995. * schema when set.
  1996. */
  1997. formNode.prototype.computeInitialValues = function (values, ignoreDefaultValues) {
  1998. var self = this;
  1999. var node = null;
  2000. var nbChildren = 1;
  2001. var i = 0;
  2002. var formData = this.ownerTree.formDesc.tpldata || {};
  2003. // Propagate the array path from the parent node
  2004. // (adding the position of the child for nodes that are direct
  2005. // children of array-like nodes)
  2006. if (this.parentNode) {
  2007. this.arrayPath = _.clone(this.parentNode.arrayPath);
  2008. if (this.parentNode.view && this.parentNode.view.array) {
  2009. this.arrayPath.push(this.childPos);
  2010. }
  2011. }
  2012. else {
  2013. this.arrayPath = [];
  2014. }
  2015. // Prepare special data param "idx" for templated values
  2016. // (is is the index of the child in its wrapping array, starting
  2017. // at 1 since that's more human-friendly than a zero-based index)
  2018. formData.idx = (this.arrayPath.length > 0) ?
  2019. this.arrayPath[this.arrayPath.length-1] + 1 :
  2020. this.childPos + 1;
  2021. // Prepare special data param "value" for templated values
  2022. formData.value = '';
  2023. // Prepare special function to compute the value of another field
  2024. formData.getValue = function (key) {
  2025. if (!values) {
  2026. return '';
  2027. }
  2028. var returnValue = values;
  2029. var listKey = key.split('[].');
  2030. var i;
  2031. for (i = 0; i < listKey.length - 1; i++) {
  2032. returnValue = returnValue[listKey[i]][self.arrayPath[i]];
  2033. }
  2034. return returnValue[listKey[i]];
  2035. };
  2036. if (this.formElement) {
  2037. // Compute the ID of the field (if needed)
  2038. if (this.formElement.id) {
  2039. this.id = applyArrayPath(this.formElement.id, this.arrayPath);
  2040. }
  2041. else if (this.view && this.view.array) {
  2042. this.id = escapeSelector(this.ownerTree.formDesc.prefix) +
  2043. '-elt-counter-' + _.uniqueId();
  2044. }
  2045. else if (this.parentNode && this.parentNode.view &&
  2046. this.parentNode.view.array) {
  2047. // Array items need an array to associate the right DOM element
  2048. // to the form node when the parent is rendered.
  2049. this.id = escapeSelector(this.ownerTree.formDesc.prefix) +
  2050. '-elt-counter-' + _.uniqueId();
  2051. }
  2052. else if ((this.formElement.type === 'button') ||
  2053. (this.formElement.type === 'selectfieldset') ||
  2054. (this.formElement.type === 'question') ||
  2055. (this.formElement.type === 'buttonquestion')) {
  2056. // Buttons do need an id for "onClick" purpose
  2057. this.id = escapeSelector(this.ownerTree.formDesc.prefix) +
  2058. '-elt-counter-' + _.uniqueId();
  2059. }
  2060. // Compute the actual key (the form element's key is index-free,
  2061. // i.e. it looks like foo[].bar.baz[].truc, so we need to apply
  2062. // the array path of the node to get foo[4].bar.baz[2].truc)
  2063. if (this.formElement.key) {
  2064. this.key = applyArrayPath(this.formElement.key, this.arrayPath);
  2065. this.keydash = slugify(this.key.replace(/\./g, '---'));
  2066. }
  2067. // Same idea for the field's name
  2068. this.name = applyArrayPath(this.formElement.name, this.arrayPath);
  2069. // Consider that label values are template values and apply the
  2070. // form's data appropriately (note we also apply the array path
  2071. // although that probably doesn't make much sense for labels...)
  2072. _.each([
  2073. 'title',
  2074. 'legend',
  2075. 'description',
  2076. 'append',
  2077. 'prepend',
  2078. 'inlinetitle',
  2079. 'helpvalue',
  2080. 'value',
  2081. 'disabled',
  2082. 'placeholder',
  2083. 'readOnly'
  2084. ], function (prop) {
  2085. if (_.isString(this.formElement[prop])) {
  2086. if (this.formElement[prop].indexOf('{{values.') !== -1) {
  2087. // This label wants to use the value of another input field.
  2088. // Convert that construct into {{jsonform.getValue(key)}} for
  2089. // Underscore to call the appropriate function of formData
  2090. // when template gets called (note calling a function is not
  2091. // exactly Mustache-friendly but is supported by Underscore).
  2092. this[prop] = this.formElement[prop].replace(
  2093. /\{\{values\.([^\}]+)\}\}/g,
  2094. '{{getValue("$1")}}');
  2095. }
  2096. else {
  2097. // Note applying the array path probably doesn't make any sense,
  2098. // but some geek might want to have a label "foo[].bar[].baz",
  2099. // with the [] replaced by the appropriate array path.
  2100. this[prop] = applyArrayPath(this.formElement[prop], this.arrayPath);
  2101. }
  2102. if (this[prop]) {
  2103. this[prop] = _.template(this[prop], valueTemplateSettings)(formData);
  2104. }
  2105. }
  2106. else {
  2107. this[prop] = this.formElement[prop];
  2108. }
  2109. }, this);
  2110. // Apply templating to options created with "titleMap" as well
  2111. if (this.formElement.options) {
  2112. this.options = _.map(this.formElement.options, function (option) {
  2113. var title = null;
  2114. if (_.isObject(option) && option.title) {
  2115. // See a few lines above for more details about templating
  2116. // preparation here.
  2117. if (option.title.indexOf('{{values.') !== -1) {
  2118. title = option.title.replace(
  2119. /\{\{values\.([^\}]+)\}\}/g,
  2120. '{{getValue("$1")}}');
  2121. }
  2122. else {
  2123. title = applyArrayPath(option.title, self.arrayPath);
  2124. }
  2125. return _.extend({}, option, {
  2126. value: (isSet(option.value) ? option.value : ''),
  2127. title: _.template(title, valueTemplateSettings)(formData)
  2128. });
  2129. }
  2130. else {
  2131. return option;
  2132. }
  2133. });
  2134. }
  2135. }
  2136. if (this.view && this.view.inputfield && this.schemaElement) {
  2137. // Case 1: simple input field
  2138. if (values) {
  2139. // Form has already been submitted, use former value if defined.
  2140. // Note we won't set the field to its default value otherwise
  2141. // (since the user has already rejected it)
  2142. if (isSet(jsonform.util.getObjKey(values, this.key))) {
  2143. this.value = jsonform.util.getObjKey(values, this.key);
  2144. }
  2145. }
  2146. else if (!ignoreDefaultValues) {
  2147. // No previously submitted form result, use default value
  2148. // defined in the schema if it's available and not already
  2149. // defined in the form element
  2150. if (!isSet(this.value) && isSet(this.schemaElement['default'])) {
  2151. this.value = this.schemaElement['default'];
  2152. if (_.isString(this.value)) {
  2153. if (this.value.indexOf('{{values.') !== -1) {
  2154. // This label wants to use the value of another input field.
  2155. // Convert that construct into {{jsonform.getValue(key)}} for
  2156. // Underscore to call the appropriate function of formData
  2157. // when template gets called (note calling a function is not
  2158. // exactly Mustache-friendly but is supported by Underscore).
  2159. this.value = this.value.replace(
  2160. /\{\{values\.([^\}]+)\}\}/g,
  2161. '{{getValue("$1")}}');
  2162. }
  2163. else {
  2164. // Note applying the array path probably doesn't make any sense,
  2165. // but some geek might want to have a label "foo[].bar[].baz",
  2166. // with the [] replaced by the appropriate array path.
  2167. this.value = applyArrayPath(this.value, this.arrayPath);
  2168. }
  2169. if (this.value) {
  2170. this.value = _.template(this.value, valueTemplateSettings)(formData);
  2171. }
  2172. }
  2173. this.defaultValue = true;
  2174. }
  2175. }
  2176. }
  2177. else if (this.view && this.view.array) {
  2178. // Case 2: array-like node
  2179. nbChildren = 0;
  2180. if (values) {
  2181. nbChildren = this.getPreviousNumberOfItems(values, this.arrayPath);
  2182. }
  2183. // TODO: use default values at the array level when form has not been
  2184. // submitted before. Note it's not that easy because each value may
  2185. // be a complex structure that needs to be pushed down the subtree.
  2186. // The easiest way is probably to generate a "values" object and
  2187. // compute initial values from that object
  2188. /*
  2189. else if (this.schemaElement['default']) {
  2190. nbChildren = this.schemaElement['default'].length;
  2191. }
  2192. */
  2193. else if (nbChildren === 0) {
  2194. // If form has already been submitted with no children, the array
  2195. // needs to be rendered without children. If there are no previously
  2196. // submitted values, the array gets rendered with one empty item as
  2197. // it's more natural from a user experience perspective. That item can
  2198. // be removed with a click on the "-" button.
  2199. nbChildren = 1;
  2200. }
  2201. for (i = 0; i < nbChildren; i++) {
  2202. this.appendChild(this.childTemplate.clone());
  2203. }
  2204. }
  2205. // Case 3 and in any case: recurse through the list of children
  2206. _.each(this.children, function (child) {
  2207. child.computeInitialValues(values, ignoreDefaultValues);
  2208. });
  2209. // If the node's value is to be used as legend for its "container"
  2210. // (typically the array the node belongs to), ensure that the container
  2211. // has a direct link to the node for the corresponding tab.
  2212. if (this.formElement && this.formElement.valueInLegend) {
  2213. node = this;
  2214. while (node) {
  2215. if (node.parentNode &&
  2216. node.parentNode.view &&
  2217. node.parentNode.view.array) {
  2218. node.legendChild = this;
  2219. if (node.formElement && node.formElement.legend) {
  2220. node.legend = applyArrayPath(node.formElement.legend, node.arrayPath);
  2221. formData.idx = (node.arrayPath.length > 0) ?
  2222. node.arrayPath[node.arrayPath.length-1] + 1 :
  2223. node.childPos + 1;
  2224. formData.value = isSet(this.value) ? this.value : '';
  2225. node.legend = _.template(node.legend, valueTemplateSettings)(formData);
  2226. break;
  2227. }
  2228. }
  2229. node = node.parentNode;
  2230. }
  2231. }
  2232. };
  2233. /**
  2234. * Returns the number of items that the array node should have based on
  2235. * previously submitted values.
  2236. *
  2237. * The whole difficulty is that values may be hidden deep in the subtree
  2238. * of the node and may actually target different arrays in the JSON schema.
  2239. *
  2240. * @function
  2241. * @param {Object} values Previously submitted values
  2242. * @param {Array(Number)} arrayPath the array path we're interested in
  2243. * @return {Number} The number of items in the array
  2244. */
  2245. formNode.prototype.getPreviousNumberOfItems = function (values, arrayPath) {
  2246. var key = null;
  2247. var arrayValue = null;
  2248. var childNumbers = null;
  2249. var idx = 0;
  2250. if (!values) {
  2251. // No previously submitted values, no need to go any further
  2252. return 0;
  2253. }
  2254. if (this.view.inputfield && this.schemaElement) {
  2255. // Case 1: node is a simple input field that links to a key in the schema.
  2256. // The schema key looks typically like:
  2257. // foo.bar[].baz.toto[].truc[].bidule
  2258. // The goal is to apply the array path and truncate the key to the last
  2259. // array we're interested in, e.g. with an arrayPath [4, 2]:
  2260. // foo.bar[4].baz.toto[2]
  2261. key = truncateToArrayDepth(this.formElement.key, arrayPath.length);
  2262. key = applyArrayPath(key, arrayPath);
  2263. arrayValue = jsonform.util.getObjKey(values, key);
  2264. if (!arrayValue) {
  2265. // No key? That means this field had been left empty
  2266. // in previous submit
  2267. return 0;
  2268. }
  2269. childNumbers = _.map(this.children, function (child) {
  2270. return child.getPreviousNumberOfItems(values, arrayPath);
  2271. });
  2272. return _.max([_.max(childNumbers) || 0, arrayValue.length]);
  2273. }
  2274. else if (this.view.array) {
  2275. // Case 2: node is an array-like node, look for input fields
  2276. // in its child template
  2277. return this.childTemplate.getPreviousNumberOfItems(values, arrayPath);
  2278. }
  2279. else {
  2280. // Case 3: node is a leaf or a container,
  2281. // recurse through the list of children and return the maximum
  2282. // number of items found in each subtree
  2283. childNumbers = _.map(this.children, function (child) {
  2284. return child.getPreviousNumberOfItems(values, arrayPath);
  2285. });
  2286. return _.max(childNumbers) || 0;
  2287. }
  2288. };
  2289. /**
  2290. * Returns the structured object that corresponds to the form values entered
  2291. * by the user for the node's subtree.
  2292. *
  2293. * The returned object follows the structure of the JSON schema that gave
  2294. * birth to the form.
  2295. *
  2296. * Obviously, the node must have been rendered before that function may
  2297. * be called.
  2298. *
  2299. * @function
  2300. * @param {Array(Number)} updateArrayPath Array path to use to pretend that
  2301. * the entered values were actually entered for another item in an array
  2302. * (this is used to move values around when an item is inserted/removed/moved
  2303. * in an array)
  2304. * @return {Object} The object that follows the data schema and matches the
  2305. * values entered by the user.
  2306. */
  2307. formNode.prototype.getFormValues = function (updateArrayPath) {
  2308. // The values object that will be returned
  2309. var values = {};
  2310. if (!this.el) {
  2311. throw new Error('formNode.getFormValues can only be called on nodes that are associated with a DOM element in the tree');
  2312. }
  2313. // Form fields values
  2314. var formArray = $(':input', this.el).serializeArray();
  2315. // Set values to false for unset checkboxes and radio buttons
  2316. // because serializeArray() ignores them
  2317. formArray = formArray.concat(
  2318. $(':input[type=checkbox]:not(:disabled):not(:checked)', this.el).map( function() {
  2319. return {"name": this.name, "value": this.checked}
  2320. }).get()
  2321. );
  2322. if (updateArrayPath) {
  2323. _.each(formArray, function (param) {
  2324. param.name = applyArrayPath(param.name, updateArrayPath);
  2325. });
  2326. }
  2327. // The underlying data schema
  2328. var formSchema = this.ownerTree.formDesc.schema;
  2329. for (var i = 0; i < formArray.length; i++) {
  2330. // Retrieve the key definition from the data schema
  2331. var name = formArray[i].name;
  2332. var eltSchema = getSchemaKey(formSchema.properties, name);
  2333. var arrayMatch = null;
  2334. var cval = null;
  2335. // Skip the input field if it's not part of the schema
  2336. if (!eltSchema) continue;
  2337. // Handle multiple checkboxes separately as the idea is to generate
  2338. // an array that contains the list of enumeration items that the user
  2339. // selected.
  2340. if (eltSchema._jsonform_checkboxes_as_array) {
  2341. arrayMatch = name.match(/\[([0-9]*)\]$/);
  2342. if (arrayMatch) {
  2343. name = name.replace(/\[([0-9]*)\]$/, '');
  2344. cval = jsonform.util.getObjKey(values, name) || [];
  2345. if (formArray[i].value === '1') {
  2346. // Value selected, push the corresponding enumeration item
  2347. // to the data result
  2348. cval.push(eltSchema['enum'][parseInt(arrayMatch[1],10)]);
  2349. }
  2350. jsonform.util.setObjKey(values, name, cval);
  2351. continue;
  2352. }
  2353. }
  2354. // Type casting
  2355. if (eltSchema.type === 'boolean') {
  2356. if (formArray[i].value === '0') {
  2357. formArray[i].value = false;
  2358. } else {
  2359. formArray[i].value = !!formArray[i].value;
  2360. }
  2361. }
  2362. if ((eltSchema.type === 'number') ||
  2363. (eltSchema.type === 'integer')) {
  2364. if (_.isString(formArray[i].value)) {
  2365. if (!formArray[i].value.length) {
  2366. formArray[i].value = null;
  2367. } else if (!isNaN(Number(formArray[i].value))) {
  2368. formArray[i].value = Number(formArray[i].value);
  2369. }
  2370. }
  2371. }
  2372. if ((eltSchema.type === 'string') &&
  2373. (formArray[i].value === '') &&
  2374. !eltSchema._jsonform_allowEmpty) {
  2375. formArray[i].value=null;
  2376. }
  2377. if ((eltSchema.type === 'object') &&
  2378. _.isString(formArray[i].value) &&
  2379. (formArray[i].value.substring(0,1) === '{')) {
  2380. try {
  2381. formArray[i].value = JSON.parse(formArray[i].value);
  2382. } catch (e) {
  2383. formArray[i].value = {};
  2384. }
  2385. }
  2386. //TODO is this due to a serialization bug?
  2387. if ((eltSchema.type === 'object') &&
  2388. (formArray[i].value === 'null' || formArray[i].value === '')) {
  2389. formArray[i].value = null;
  2390. }
  2391. if (formArray[i].name && (formArray[i].value !== null)) {
  2392. jsonform.util.setObjKey(values, formArray[i].name, formArray[i].value);
  2393. }
  2394. }
  2395. // console.log("Form value",values);
  2396. return values;
  2397. };
  2398. /**
  2399. * Renders the node.
  2400. *
  2401. * Rendering is done in three steps: HTML generation, DOM element creation
  2402. * and insertion, and an enhance step to bind event handlers.
  2403. *
  2404. * @function
  2405. * @param {Node} el The DOM element where the node is to be rendered. The
  2406. * node is inserted at the right position based on its "childPos" property.
  2407. */
  2408. formNode.prototype.render = function (el) {
  2409. var html = this.generate();
  2410. this.setContent(html, el);
  2411. this.enhance();
  2412. };
  2413. /**
  2414. * Inserts/Updates the HTML content of the node in the DOM.
  2415. *
  2416. * If the HTML is an update, the new HTML content replaces the old one.
  2417. * The new HTML content is not moved around in the DOM in particular.
  2418. *
  2419. * The HTML is inserted at the right position in its parent's DOM subtree
  2420. * otherwise (well, provided there are enough children, but that should always
  2421. * be the case).
  2422. *
  2423. * @function
  2424. * @param {string} html The HTML content to render
  2425. * @param {Node} parentEl The DOM element that is to contain the DOM node.
  2426. * This parameter is optional (the node's parent is used otherwise) and
  2427. * is ignored if the node to render is already in the DOM tree.
  2428. */
  2429. formNode.prototype.setContent = function (html, parentEl) {
  2430. var node = $(html);
  2431. var parentNode = parentEl ||
  2432. (this.parentNode ? this.parentNode.el : this.ownerTree.domRoot);
  2433. var nextSibling = null;
  2434. if (this.el) {
  2435. // Replace the contents of the DOM element if the node is already in the tree
  2436. $(this.el).replaceWith(node);
  2437. }
  2438. else {
  2439. // Insert the node in the DOM if it's not already there
  2440. nextSibling = $(parentNode).children().get(this.childPos);
  2441. if (nextSibling) {
  2442. $(nextSibling).before(node);
  2443. }
  2444. else {
  2445. $(parentNode).append(node);
  2446. }
  2447. }
  2448. // Save the link between the form node and the generated HTML
  2449. this.el = node;
  2450. // Update the node's subtree, extracting DOM elements that match the nodes
  2451. // from the generated HTML
  2452. this.updateElement(this.el);
  2453. };
  2454. /**
  2455. * Updates the DOM element associated with the node.
  2456. *
  2457. * Only nodes that have ID are directly associated with a DOM element.
  2458. *
  2459. * @function
  2460. */
  2461. formNode.prototype.updateElement = function (domNode) {
  2462. if (this.id) {
  2463. this.el = $('#' + escapeSelector(this.id), domNode).get(0);
  2464. if (this.view && this.view.getElement) {
  2465. this.el = this.view.getElement(this.el);
  2466. }
  2467. if ((this.fieldtemplate !== false) &&
  2468. this.view && this.view.fieldtemplate) {
  2469. // The field template wraps the element two or three level deep
  2470. // in the DOM tree, depending on whether there is anything prepended
  2471. // or appended to the input field
  2472. this.el = $(this.el).parent().parent();
  2473. if (this.prepend || this.prepend) {
  2474. this.el = this.el.parent();
  2475. }
  2476. this.el = this.el.get(0);
  2477. }
  2478. if (this.parentNode && this.parentNode.view &&
  2479. this.parentNode.view.childTemplate) {
  2480. // TODO: the child template may introduce more than one level,
  2481. // so the number of levels introduced should rather be exposed
  2482. // somehow in jsonform.fieldtemplate.
  2483. this.el = $(this.el).parent().get(0);
  2484. }
  2485. }
  2486. _.each(this.children, function (child) {
  2487. child.updateElement(this.el || domNode);
  2488. });
  2489. };
  2490. /**
  2491. * Generates the view's HTML content for the underlying model.
  2492. *
  2493. * @function
  2494. */
  2495. formNode.prototype.generate = function () {
  2496. var data = {
  2497. id: this.id,
  2498. keydash: this.keydash,
  2499. elt: this.formElement,
  2500. schema: this.schemaElement,
  2501. node: this,
  2502. value: isSet(this.value) ? this.value : '',
  2503. escape: escapeHTML
  2504. };
  2505. var template = null;
  2506. var html = '';
  2507. // Complete the data context if needed
  2508. if (this.ownerTree.formDesc.onBeforeRender) {
  2509. this.ownerTree.formDesc.onBeforeRender(data, this);
  2510. }
  2511. if (this.view.onBeforeRender) {
  2512. this.view.onBeforeRender(data, this);
  2513. }
  2514. // Use the template that 'onBeforeRender' may have set,
  2515. // falling back to that of the form element otherwise
  2516. if (this.template) {
  2517. template = this.template;
  2518. }
  2519. else if (this.formElement && this.formElement.template) {
  2520. template = this.formElement.template;
  2521. }
  2522. else {
  2523. template = this.view.template;
  2524. }
  2525. // Wrap the view template in the generic field template
  2526. // (note the strict equality to 'false', needed as we fallback
  2527. // to the view's setting otherwise)
  2528. if ((this.fieldtemplate !== false) &&
  2529. (this.fieldtemplate || this.view.fieldtemplate)) {
  2530. template = jsonform.fieldTemplate(template);
  2531. }
  2532. // Wrap the content in the child template of its parent if necessary.
  2533. if (this.parentNode && this.parentNode.view &&
  2534. this.parentNode.view.childTemplate) {
  2535. template = this.parentNode.view.childTemplate(template);
  2536. }
  2537. // Prepare the HTML of the children
  2538. var childrenhtml = '';
  2539. _.each(this.children, function (child) {
  2540. childrenhtml += child.generate();
  2541. });
  2542. data.children = childrenhtml;
  2543. data.fieldHtmlClass = '';
  2544. if (this.ownerTree &&
  2545. this.ownerTree.formDesc &&
  2546. this.ownerTree.formDesc.params &&
  2547. this.ownerTree.formDesc.params.fieldHtmlClass) {
  2548. data.fieldHtmlClass = this.ownerTree.formDesc.params.fieldHtmlClass;
  2549. }
  2550. if (this.formElement &&
  2551. (typeof this.formElement.fieldHtmlClass !== 'undefined')) {
  2552. data.fieldHtmlClass = this.formElement.fieldHtmlClass;
  2553. }
  2554. // Apply the HTML template
  2555. html = _.template(template, fieldTemplateSettings)(data);
  2556. return html;
  2557. };
  2558. /**
  2559. * Enhances the view with additional logic, binding event handlers
  2560. * in particular.
  2561. *
  2562. * The function also runs the "insert" event handler of the view and
  2563. * form element if they exist (starting with that of the view)
  2564. *
  2565. * @function
  2566. */
  2567. formNode.prototype.enhance = function () {
  2568. var node = this;
  2569. var handlers = null;
  2570. var handler = null;
  2571. var formData = _.clone(this.ownerTree.formDesc.tpldata) || {};
  2572. if (this.formElement) {
  2573. // Check the view associated with the node as it may define an "onInsert"
  2574. // event handler to be run right away
  2575. if (this.view.onInsert) {
  2576. this.view.onInsert({ target: $(this.el) }, this);
  2577. }
  2578. handlers = this.handlers || this.formElement.handlers;
  2579. // Trigger the "insert" event handler
  2580. handler = this.onInsert || this.formElement.onInsert;
  2581. if (handler) {
  2582. handler({ target: $(this.el) }, this);
  2583. }
  2584. if (handlers) {
  2585. _.each(handlers, function (handler, onevent) {
  2586. if (onevent === 'insert') {
  2587. handler({ target: $(this.el) }, this);
  2588. }
  2589. }, this);
  2590. }
  2591. // No way to register event handlers if the DOM element is unknown
  2592. // TODO: find some way to register event handlers even when this.el is not set.
  2593. if (this.el) {
  2594. // Register specific event handlers
  2595. // TODO: Add support for other event handlers
  2596. if (this.onChange)
  2597. $(this.el).bind('change', function(evt) { node.onChange(evt, node); });
  2598. if (this.view.onChange)
  2599. $(this.el).bind('change', function(evt) { node.view.onChange(evt, node); });
  2600. if (this.formElement.onChange)
  2601. $(this.el).bind('change', function(evt) { node.formElement.onChange(evt, node); });
  2602. if (this.onClick)
  2603. $(this.el).bind('click', function(evt) { node.onClick(evt, node); });
  2604. if (this.view.onClick)
  2605. $(this.el).bind('click', function(evt) { node.view.onClick(evt, node); });
  2606. if (this.formElement.onClick)
  2607. $(this.el).bind('click', function(evt) { node.formElement.onClick(evt, node); });
  2608. if (this.onKeyUp)
  2609. $(this.el).bind('keyup', function(evt) { node.onKeyUp(evt, node); });
  2610. if (this.view.onKeyUp)
  2611. $(this.el).bind('keyup', function(evt) { node.view.onKeyUp(evt, node); });
  2612. if (this.formElement.onKeyUp)
  2613. $(this.el).bind('keyup', function(evt) { node.formElement.onKeyUp(evt, node); });
  2614. if (handlers) {
  2615. _.each(handlers, function (handler, onevent) {
  2616. if (onevent !== 'insert') {
  2617. $(this.el).bind(onevent, function(evt) { handler(evt, node); });
  2618. }
  2619. }, this);
  2620. }
  2621. }
  2622. // Auto-update legend based on the input field that's associated with it
  2623. if (this.legendChild && this.legendChild.formElement) {
  2624. var onChangeHandler = function (evt) {
  2625. if (node.formElement && node.formElement.legend && node.parentNode) {
  2626. node.legend = applyArrayPath(node.formElement.legend, node.arrayPath);
  2627. formData.idx = (node.arrayPath.length > 0) ?
  2628. node.arrayPath[node.arrayPath.length - 1] + 1 :
  2629. node.childPos + 1;
  2630. formData.value = $(evt.target).val();
  2631. node.legend = _.template(node.legend, valueTemplateSettings)(formData);
  2632. $(node.parentNode.el).trigger('legendUpdated');
  2633. }
  2634. };
  2635. $(this.legendChild.el).bind('change', onChangeHandler);
  2636. $(this.legendChild.el).bind('keyup', onChangeHandler);
  2637. }
  2638. }
  2639. // Recurse down the tree to enhance children
  2640. _.each(this.children, function (child) {
  2641. child.enhance();
  2642. });
  2643. };
  2644. /**
  2645. * Inserts an item in the array at the requested position and renders the item.
  2646. *
  2647. * @function
  2648. * @param {Number} idx Insertion index
  2649. */
  2650. formNode.prototype.insertArrayItem = function (idx, domElement) {
  2651. var i = 0;
  2652. // Insert element at the end of the array if index is not given
  2653. if (idx === undefined) {
  2654. idx = this.children.length;
  2655. }
  2656. // Create the additional array item at the end of the list,
  2657. // using the item template created when tree was initialized
  2658. // (the call to resetValues ensures that 'arrayPath' is correctly set)
  2659. var child = this.childTemplate.clone();
  2660. this.appendChild(child);
  2661. child.resetValues();
  2662. // To create a blank array item at the requested position,
  2663. // shift values down starting at the requested position
  2664. // one to insert (note we start with the end of the array on purpose)
  2665. for (i = this.children.length-2; i >= idx; i--) {
  2666. this.children[i].moveValuesTo(this.children[i+1]);
  2667. }
  2668. // Initialize the blank node we've created with default values
  2669. this.children[idx].resetValues();
  2670. this.children[idx].computeInitialValues();
  2671. // Re-render all children that have changed
  2672. for (i = idx; i < this.children.length; i++) {
  2673. this.children[i].render(domElement);
  2674. }
  2675. };
  2676. /**
  2677. * Remove an item from an array
  2678. *
  2679. * @function
  2680. * @param {Number} idx The index number of the item to remove
  2681. */
  2682. formNode.prototype.deleteArrayItem = function (idx) {
  2683. var i = 0;
  2684. var child = null;
  2685. // Delete last item if no index is given
  2686. if (idx === undefined) {
  2687. idx = this.children.length - 1;
  2688. }
  2689. // Move values up in the array
  2690. for (i = idx; i < this.children.length-1; i++) {
  2691. this.children[i+1].moveValuesTo(this.children[i]);
  2692. this.children[i].render();
  2693. }
  2694. // Remove the last array item from the DOM tree and from the form tree
  2695. this.removeChild();
  2696. };
  2697. /**
  2698. * Returns the minimum/maximum number of items that an array field
  2699. * is allowed to have according to the schema definition of the fields
  2700. * it contains.
  2701. *
  2702. * The function parses the schema definitions of the array items that
  2703. * compose the current "array" node and returns the minimum value of
  2704. * "maxItems" it encounters as the maximum number of items, and the
  2705. * maximum value of "minItems" as the minimum number of items.
  2706. *
  2707. * The function reports a -1 for either of the boundaries if the schema
  2708. * does not put any constraint on the number of elements the current
  2709. * array may have of if the current node is not an array.
  2710. *
  2711. * Note that array boundaries should be defined in the JSON Schema using
  2712. * "minItems" and "maxItems". The code also supports "minLength" and
  2713. * "maxLength" as a fallback, mostly because it used to by mistake (see #22)
  2714. * and because other people could make the same mistake.
  2715. *
  2716. * @function
  2717. * @return {Object} An object with properties "minItems" and "maxItems"
  2718. * that reports the corresponding number of items that the array may
  2719. * have (value is -1 when there is no constraint for that boundary)
  2720. */
  2721. formNode.prototype.getArrayBoundaries = function () {
  2722. var boundaries = {
  2723. minItems: -1,
  2724. maxItems: -1
  2725. };
  2726. if (!this.view || !this.view.array) return boundaries;
  2727. var getNodeBoundaries = function (node, initialNode) {
  2728. var schemaKey = null;
  2729. var arrayKey = null;
  2730. var boundaries = {
  2731. minItems: -1,
  2732. maxItems: -1
  2733. };
  2734. initialNode = initialNode || node;
  2735. if (node.view && node.view.array && (node !== initialNode)) {
  2736. // New array level not linked to an array in the schema,
  2737. // so no size constraints
  2738. return boundaries;
  2739. }
  2740. if (node.key) {
  2741. // Note the conversion to target the actual array definition in the
  2742. // schema where minItems/maxItems may be defined. If we're still looking
  2743. // at the initial node, the goal is to convert from:
  2744. // foo[0].bar[3].baz to foo[].bar[].baz
  2745. // If we're not looking at the initial node, the goal is to look at the
  2746. // closest array parent:
  2747. // foo[0].bar[3].baz to foo[].bar
  2748. arrayKey = node.key.replace(/\[[0-9]+\]/g, '[]');
  2749. if (node !== initialNode) {
  2750. arrayKey = arrayKey.replace(/\[\][^\[\]]*$/, '');
  2751. }
  2752. schemaKey = getSchemaKey(
  2753. node.ownerTree.formDesc.schema.properties,
  2754. arrayKey
  2755. );
  2756. if (!schemaKey) return boundaries;
  2757. return {
  2758. minItems: schemaKey.minItems || schemaKey.minLength || -1,
  2759. maxItems: schemaKey.maxItems || schemaKey.maxLength || -1
  2760. };
  2761. }
  2762. else {
  2763. _.each(node.children, function (child) {
  2764. var subBoundaries = getNodeBoundaries(child, initialNode);
  2765. if (subBoundaries.minItems !== -1) {
  2766. if (boundaries.minItems !== -1) {
  2767. boundaries.minItems = Math.max(
  2768. boundaries.minItems,
  2769. subBoundaries.minItems
  2770. );
  2771. }
  2772. else {
  2773. boundaries.minItems = subBoundaries.minItems;
  2774. }
  2775. }
  2776. if (subBoundaries.maxItems !== -1) {
  2777. if (boundaries.maxItems !== -1) {
  2778. boundaries.maxItems = Math.min(
  2779. boundaries.maxItems,
  2780. subBoundaries.maxItems
  2781. );
  2782. }
  2783. else {
  2784. boundaries.maxItems = subBoundaries.maxItems;
  2785. }
  2786. }
  2787. });
  2788. }
  2789. return boundaries;
  2790. };
  2791. return getNodeBoundaries(this);
  2792. };
  2793. /**
  2794. * Form tree class.
  2795. *
  2796. * Holds the internal representation of the form.
  2797. * The tree is always in sync with the rendered form, this allows to parse
  2798. * it easily.
  2799. *
  2800. * @class
  2801. */
  2802. var formTree = function () {
  2803. this.eventhandlers = [];
  2804. this.root = null;
  2805. this.formDesc = null;
  2806. };
  2807. /**
  2808. * Initializes the form tree structure from the JSONForm object
  2809. *
  2810. * This function is the main entry point of the JSONForm library.
  2811. *
  2812. * Initialization steps:
  2813. * 1. the internal tree structure that matches the JSONForm object
  2814. * gets created (call to buildTree)
  2815. * 2. initial values are computed from previously submitted values
  2816. * or from the default values defined in the JSON schema.
  2817. *
  2818. * When the function returns, the tree is ready to be rendered through
  2819. * a call to "render".
  2820. *
  2821. * @function
  2822. */
  2823. formTree.prototype.initialize = function (formDesc) {
  2824. formDesc = formDesc || {};
  2825. // Keep a pointer to the initial JSONForm
  2826. // (note clone returns a shallow copy, only first-level is cloned)
  2827. this.formDesc = _.clone(formDesc);
  2828. // Compute form prefix if no prefix is given.
  2829. this.formDesc.prefix = this.formDesc.prefix ||
  2830. 'jsonform-' + _.uniqueId();
  2831. // JSON schema shorthand
  2832. if (this.formDesc.schema && !this.formDesc.schema.properties) {
  2833. this.formDesc.schema = {
  2834. properties: this.formDesc.schema
  2835. };
  2836. }
  2837. // Ensure layout is set
  2838. this.formDesc.form = this.formDesc.form || [
  2839. '*',
  2840. {
  2841. type: 'actions',
  2842. items: [
  2843. {
  2844. type: 'submit',
  2845. value: 'Submit'
  2846. }
  2847. ]
  2848. }
  2849. ];
  2850. this.formDesc.form = (_.isArray(this.formDesc.form) ?
  2851. this.formDesc.form :
  2852. [this.formDesc.form]);
  2853. this.formDesc.params = this.formDesc.params || {};
  2854. // Create the root of the tree
  2855. this.root = new formNode();
  2856. this.root.ownerTree = this;
  2857. this.root.view = jsonform.elementTypes['root'];
  2858. // Generate the tree from the form description
  2859. this.buildTree();
  2860. // Compute the values associated with each node
  2861. // (for arrays, the computation actually creates the form nodes)
  2862. this.computeInitialValues();
  2863. };
  2864. /**
  2865. * Constructs the tree from the form description.
  2866. *
  2867. * The function must be called once when the tree is first created.
  2868. *
  2869. * @function
  2870. */
  2871. formTree.prototype.buildTree = function () {
  2872. // Parse and generate the form structure based on the elements encountered:
  2873. // - '*' means "generate all possible fields using default layout"
  2874. // - a key reference to target a specific data element
  2875. // - a more complex object to generate specific form sections
  2876. _.each(this.formDesc.form, function (formElement) {
  2877. if (formElement === '*') {
  2878. _.each(this.formDesc.schema.properties, function (element, key) {
  2879. this.root.appendChild(this.buildFromLayout({
  2880. key: key
  2881. }));
  2882. }, this);
  2883. }
  2884. else {
  2885. if (_.isString(formElement)) {
  2886. formElement = {
  2887. key: formElement
  2888. };
  2889. }
  2890. this.root.appendChild(this.buildFromLayout(formElement));
  2891. }
  2892. }, this);
  2893. };
  2894. /**
  2895. * Builds the internal form tree representation from the requested layout.
  2896. *
  2897. * The function is recursive, generating the node children as necessary.
  2898. * The function extracts the values from the previously submitted values
  2899. * (this.formDesc.value) or from default values defined in the schema.
  2900. *
  2901. * @function
  2902. * @param {Object} formElement JSONForm element to render
  2903. * @param {Object} context The parsing context (the array depth in particular)
  2904. * @return {Object} The node that matches the element.
  2905. */
  2906. formTree.prototype.buildFromLayout = function (formElement, context) {
  2907. var schemaElement = null;
  2908. var node = new formNode();
  2909. var view = null;
  2910. var key = null;
  2911. // The form element parameter directly comes from the initial
  2912. // JSONForm object. We'll make a shallow copy of it and of its children
  2913. // not to pollute the original object.
  2914. // (note JSON.parse(JSON.stringify()) cannot be used since there may be
  2915. // event handlers in there!)
  2916. formElement = _.clone(formElement);
  2917. if (formElement.items) {
  2918. if (_.isArray(formElement.items)) {
  2919. formElement.items = _.map(formElement.items, _.clone);
  2920. }
  2921. else {
  2922. formElement.items = [ _.clone(formElement.items) ];
  2923. }
  2924. }
  2925. if (formElement.key) {
  2926. // The form element is directly linked to an element in the JSON
  2927. // schema. The properties of the form element override those of the
  2928. // element in the JSON schema. Properties from the JSON schema complete
  2929. // those of the form element otherwise.
  2930. // Retrieve the element from the JSON schema
  2931. schemaElement = getSchemaKey(
  2932. this.formDesc.schema.properties,
  2933. formElement.key);
  2934. if (!schemaElement) {
  2935. // The JSON Form is invalid!
  2936. throw new Error('The JSONForm object references the schema key "' +
  2937. formElement.key + '" but that key does not exist in the JSON schema');
  2938. }
  2939. // Schema element has just been found, let's trigger the
  2940. // "onElementSchema" event
  2941. // (tidoust: not sure what the use case for this is, keeping the
  2942. // code for backward compatibility)
  2943. if (this.formDesc.onElementSchema) {
  2944. this.formDesc.onElementSchema(formElement, schemaElement);
  2945. }
  2946. formElement.name =
  2947. formElement.name ||
  2948. formElement.key;
  2949. formElement.title =
  2950. formElement.title ||
  2951. schemaElement.title;
  2952. formElement.description =
  2953. formElement.description ||
  2954. schemaElement.description;
  2955. formElement.readOnly =
  2956. formElement.readOnly ||
  2957. schemaElement.readOnly ||
  2958. formElement.readonly ||
  2959. schemaElement.readonly;
  2960. // Compute the ID of the input field
  2961. if (!formElement.id) {
  2962. formElement.id = escapeSelector(this.formDesc.prefix) +
  2963. '-elt-' + slugify(formElement.key);
  2964. }
  2965. // Should empty strings be included in the final value?
  2966. // TODO: it's rather unclean to pass it through the schema.
  2967. if (formElement.allowEmpty) {
  2968. schemaElement._jsonform_allowEmpty = true;
  2969. }
  2970. // If the form element does not define its type, use the type of
  2971. // the schema element.
  2972. if (!formElement.type) {
  2973. // If schema type is an array containing only a type and "null",
  2974. // remove null and make the element non-required
  2975. if (_.isArray(schemaElement.type)) {
  2976. if (_.contains(schemaElement.type, "null")) {
  2977. schemaElement.type = _.without(schemaElement.type, "null");
  2978. schemaElement.required = false;
  2979. }
  2980. if (schemaElement.type.length > 1) {
  2981. throw new Error("Cannot process schema element with multiple types.");
  2982. }
  2983. schemaElement.type = _.first(schemaElement.type);
  2984. }
  2985. if ((schemaElement.type === 'string') &&
  2986. (schemaElement.format === 'color')) {
  2987. formElement.type = 'color';
  2988. } else if ((schemaElement.type === 'number' ||
  2989. schemaElement.type === 'integer') &&
  2990. !schemaElement['enum']) {
  2991. formElement.type = 'number';
  2992. if (schemaElement.type === 'number') schemaElement.step = 'any';
  2993. } else if ((schemaElement.type === 'string' ||
  2994. schemaElement.type === 'any') &&
  2995. !schemaElement['enum']) {
  2996. formElement.type = 'text';
  2997. } else if (schemaElement.type === 'boolean') {
  2998. formElement.type = 'checkbox';
  2999. } else if (schemaElement.type === 'object') {
  3000. if (schemaElement.properties) {
  3001. formElement.type = 'fieldset';
  3002. } else {
  3003. formElement.type = 'textarea';
  3004. }
  3005. } else if (!_.isUndefined(schemaElement['enum'])) {
  3006. formElement.type = 'select';
  3007. } else {
  3008. formElement.type = schemaElement.type;
  3009. }
  3010. }
  3011. // Unless overridden in the definition of the form element (or unless
  3012. // there's a titleMap defined), use the enumeration list defined in
  3013. // the schema
  3014. if (!formElement.options && schemaElement['enum']) {
  3015. if (formElement.titleMap) {
  3016. formElement.options = _.map(schemaElement['enum'], function (value) {
  3017. return {
  3018. value: value,
  3019. title: hasOwnProperty(formElement.titleMap, value) ? formElement.titleMap[value] : value
  3020. };
  3021. });
  3022. }
  3023. else {
  3024. formElement.options = schemaElement['enum'];
  3025. }
  3026. }
  3027. // Flag a list of checkboxes with multiple choices
  3028. if ((formElement.type === 'checkboxes') && schemaElement.items) {
  3029. var itemsEnum = schemaElement.items['enum'];
  3030. if (itemsEnum) {
  3031. schemaElement.items._jsonform_checkboxes_as_array = true;
  3032. }
  3033. if (!itemsEnum && schemaElement.items[0]) {
  3034. itemsEnum = schemaElement.items[0]['enum'];
  3035. if (itemsEnum) {
  3036. schemaElement.items[0]._jsonform_checkboxes_as_array = true;
  3037. }
  3038. }
  3039. }
  3040. // If the form element targets an "object" in the JSON schema,
  3041. // we need to recurse through the list of children to create an
  3042. // input field per child property of the object in the JSON schema
  3043. if (schemaElement.type === 'object') {
  3044. _.each(schemaElement.properties, function (prop, propName) {
  3045. node.appendChild(this.buildFromLayout({
  3046. key: formElement.key + '.' + propName
  3047. }));
  3048. }, this);
  3049. }
  3050. }
  3051. if (!formElement.type) {
  3052. formElement.type = 'none';
  3053. }
  3054. view = jsonform.elementTypes[formElement.type];
  3055. if (!view) {
  3056. throw new Error('The JSONForm contains an element whose type is unknown: "' +
  3057. formElement.type + '"');
  3058. }
  3059. if (schemaElement) {
  3060. // The form element is linked to an element in the schema.
  3061. // Let's make sure the types are compatible.
  3062. // In particular, the element must not be a "container"
  3063. // (or must be an "object" or "array" container)
  3064. if (!view.inputfield && !view.array &&
  3065. (formElement.type !== 'selectfieldset') &&
  3066. (schemaElement.type !== 'object')) {
  3067. throw new Error('The JSONForm contains an element that links to an ' +
  3068. 'element in the JSON schema (key: "' + formElement.key + '") ' +
  3069. 'and that should not based on its type ("' + formElement.type + '")');
  3070. }
  3071. }
  3072. else {
  3073. // The form element is not linked to an element in the schema.
  3074. // This means the form element must be a "container" element,
  3075. // and must not define an input field.
  3076. if (view.inputfield && (formElement.type !== 'selectfieldset')) {
  3077. throw new Error('The JSONForm defines an element of type ' +
  3078. '"' + formElement.type + '" ' +
  3079. 'but no "key" property to link the input field to the JSON schema');
  3080. }
  3081. }
  3082. // A few characters need to be escaped to use the ID as jQuery selector
  3083. formElement.iddot = escapeSelector(formElement.id || '');
  3084. // Initialize the form node from the form element and schema element
  3085. node.formElement = formElement;
  3086. node.schemaElement = schemaElement;
  3087. node.view = view;
  3088. node.ownerTree = this;
  3089. // Set event handlers
  3090. if (!formElement.handlers) {
  3091. formElement.handlers = {};
  3092. }
  3093. // Parse children recursively
  3094. if (node.view.array) {
  3095. // The form element is an array. The number of items in an array
  3096. // is by definition dynamic, up to the form user (through "Add more",
  3097. // "Delete" commands). The positions of the items in the array may
  3098. // also change over time (through "Move up", "Move down" commands).
  3099. //
  3100. // The form node stores a "template" node that serves as basis for
  3101. // the creation of an item in the array.
  3102. //
  3103. // Array items may be complex forms themselves, allowing for nesting.
  3104. //
  3105. // The initial values set the initial number of items in the array.
  3106. // Note a form element contains at least one item when it is rendered.
  3107. if (formElement.items) {
  3108. key = formElement.items[0] || formElement.items;
  3109. }
  3110. else {
  3111. key = formElement.key + '[]';
  3112. }
  3113. if (_.isString(key)) {
  3114. key = { key: key };
  3115. }
  3116. node.setChildTemplate(this.buildFromLayout(key));
  3117. }
  3118. else if (formElement.items) {
  3119. // The form element defines children elements
  3120. _.each(formElement.items, function (item) {
  3121. if (_.isString(item)) {
  3122. item = { key: item };
  3123. }
  3124. node.appendChild(this.buildFromLayout(item));
  3125. }, this);
  3126. }
  3127. return node;
  3128. };
  3129. /**
  3130. * Computes the values associated with each input field in the tree based
  3131. * on previously submitted values or default values in the JSON schema.
  3132. *
  3133. * For arrays, the function actually creates and inserts additional
  3134. * nodes in the tree based on previously submitted values (also ensuring
  3135. * that the array has at least one item).
  3136. *
  3137. * The function sets the array path on all nodes.
  3138. * It should be called once in the lifetime of a form tree right after
  3139. * the tree structure has been created.
  3140. *
  3141. * @function
  3142. */
  3143. formTree.prototype.computeInitialValues = function () {
  3144. this.root.computeInitialValues(this.formDesc.value);
  3145. };
  3146. /**
  3147. * Renders the form tree
  3148. *
  3149. * @function
  3150. * @param {Node} domRoot The "form" element in the DOM tree that serves as
  3151. * root for the form
  3152. */
  3153. formTree.prototype.render = function (domRoot) {
  3154. if (!domRoot) return;
  3155. this.domRoot = domRoot;
  3156. this.root.render();
  3157. // If the schema defines required fields, flag the form with the
  3158. // "jsonform-hasrequired" class for styling purpose
  3159. // (typically so that users may display a legend)
  3160. if (this.hasRequiredField()) {
  3161. $(domRoot).addClass('jsonform-hasrequired');
  3162. }
  3163. };
  3164. /**
  3165. * Walks down the element tree with a callback
  3166. *
  3167. * @function
  3168. * @param {Function} callback The callback to call on each element
  3169. */
  3170. formTree.prototype.forEachElement = function (callback) {
  3171. var f = function(root) {
  3172. for (var i=0;i<root.children.length;i++) {
  3173. callback(root.children[i]);
  3174. f(root.children[i]);
  3175. }
  3176. };
  3177. f(this.root);
  3178. };
  3179. formTree.prototype.validate = function(noErrorDisplay) {
  3180. var values = jsonform.getFormValue(this.domRoot);
  3181. var errors = false;
  3182. var options = this.formDesc;
  3183. if (options.validate!==false) {
  3184. var validator = false;
  3185. if (typeof options.validate!="object") {
  3186. if (global.JSONFormValidator) {
  3187. validator = global.JSONFormValidator.createEnvironment("json-schema-draft-03");
  3188. }
  3189. } else {
  3190. validator = options.validate;
  3191. }
  3192. if (validator) {
  3193. var v = validator.validate(values, this.formDesc.schema);
  3194. $(this.domRoot).jsonFormErrors(false,options);
  3195. if (v.errors.length) {
  3196. if (!errors) errors = [];
  3197. errors = errors.concat(v.errors);
  3198. }
  3199. }
  3200. }
  3201. if (errors && !noErrorDisplay) {
  3202. if (options.displayErrors) {
  3203. options.displayErrors(errors,this.domRoot);
  3204. } else {
  3205. $(this.domRoot).jsonFormErrors(errors,options);
  3206. }
  3207. }
  3208. return {"errors":errors}
  3209. }
  3210. formTree.prototype.submit = function(evt) {
  3211. var stopEvent = function() {
  3212. if (evt) {
  3213. evt.preventDefault();
  3214. evt.stopPropagation();
  3215. }
  3216. return false;
  3217. };
  3218. var values = jsonform.getFormValue(this.domRoot);
  3219. var options = this.formDesc;
  3220. var brk=false;
  3221. this.forEachElement(function(elt) {
  3222. if (brk) return;
  3223. if (elt.view.onSubmit) {
  3224. brk = !elt.view.onSubmit(evt, elt); //may be called multiple times!!
  3225. }
  3226. });
  3227. if (brk) return stopEvent();
  3228. var validated = this.validate();
  3229. if (options.onSubmit && !options.onSubmit(validated.errors,values)) {
  3230. return stopEvent();
  3231. }
  3232. if (validated.errors) return stopEvent();
  3233. if (options.onSubmitValid && !options.onSubmitValid(values)) {
  3234. return stopEvent();
  3235. }
  3236. return false;
  3237. };
  3238. /**
  3239. * Returns true if the form displays a "required" field.
  3240. *
  3241. * To keep things simple, the function parses the form's schema and returns
  3242. * true as soon as it finds a "required" flag even though, in theory, that
  3243. * schema key may not appear in the final form.
  3244. *
  3245. * Note that a "required" constraint on a boolean type is always enforced,
  3246. * the code skips such definitions.
  3247. *
  3248. * @function
  3249. * @return {boolean} True when the form has some required field,
  3250. * false otherwise.
  3251. */
  3252. formTree.prototype.hasRequiredField = function () {
  3253. var parseElement = function (element) {
  3254. if (!element) return null;
  3255. if (element.required && (element.type !== 'boolean')) {
  3256. return element;
  3257. }
  3258. var prop = _.find(element.properties, function (property) {
  3259. return parseElement(property);
  3260. });
  3261. if (prop) {
  3262. return prop;
  3263. }
  3264. if (element.items) {
  3265. if (_.isArray(element.items)) {
  3266. prop = _.find(element.items, function (item) {
  3267. return parseElement(item);
  3268. });
  3269. }
  3270. else {
  3271. prop = parseElement(element.items);
  3272. }
  3273. if (prop) {
  3274. return prop;
  3275. }
  3276. }
  3277. };
  3278. return parseElement(this.formDesc.schema);
  3279. };
  3280. /**
  3281. * Returns the structured object that corresponds to the form values entered
  3282. * by the use for the given form.
  3283. *
  3284. * The form must have been previously rendered through a call to jsonform.
  3285. *
  3286. * @function
  3287. * @param {Node} The <form> tag in the DOM
  3288. * @return {Object} The object that follows the data schema and matches the
  3289. * values entered by the user.
  3290. */
  3291. jsonform.getFormValue = function (formelt) {
  3292. var form = $(formelt).data('jsonform-tree');
  3293. if (!form) return null;
  3294. return form.root.getFormValues();
  3295. };
  3296. /**
  3297. * Highlights errors reported by the JSON schema validator in the document.
  3298. *
  3299. * @function
  3300. * @param {Object} errors List of errors reported by the JSON schema validator
  3301. * @param {Object} options The JSON Form object that describes the form
  3302. * (unused for the time being, could be useful to store example values or
  3303. * specific error messages)
  3304. */
  3305. $.fn.jsonFormErrors = function(errors, options) {
  3306. $(".error", this).removeClass("error");
  3307. $(".warning", this).removeClass("warning");
  3308. $(".jsonform-errortext", this).hide();
  3309. if (!errors) return;
  3310. var errorSelectors = [];
  3311. for (var i = 0; i < errors.length; i++) {
  3312. // Compute the address of the input field in the form from the URI
  3313. // returned by the JSON schema validator.
  3314. // These URIs typically look like:
  3315. // urn:uuid:cccc265e-ffdd-4e40-8c97-977f7a512853#/pictures/1/thumbnail
  3316. // What we need from that is the path in the value object:
  3317. // pictures[1].thumbnail
  3318. // ... and the jQuery-friendly class selector of the input field:
  3319. // .jsonform-error-pictures\[1\]---thumbnail
  3320. var key = errors[i].uri
  3321. .replace(/.*#\//, '')
  3322. .replace(/\//g, '.')
  3323. .replace(/\.([0-9]+)(?=\.|$)/g, '[$1]');
  3324. var errormarkerclass = ".jsonform-error-" +
  3325. escapeSelector(key.replace(/\./g,"---"));
  3326. errorSelectors.push(errormarkerclass);
  3327. var errorType = errors[i].type || "error";
  3328. $(errormarkerclass, this).addClass(errorType);
  3329. $(errormarkerclass + " .jsonform-errortext", this).html(errors[i].message).show();
  3330. }
  3331. // Look for the first error in the DOM and ensure the element
  3332. // is visible so that the user understands that something went wrong
  3333. errorSelectors = errorSelectors.join(',');
  3334. var firstError = $(errorSelectors).get(0);
  3335. if (firstError && firstError.scrollIntoView) {
  3336. firstError.scrollIntoView(true, {
  3337. behavior: 'smooth'
  3338. });
  3339. }
  3340. };
  3341. /**
  3342. * Generates the HTML form from the given JSON Form object and renders the form.
  3343. *
  3344. * Main entry point of the library. Defined as a jQuery function that typically
  3345. * needs to be applied to a <form> element in the document.
  3346. *
  3347. * The function handles the following properties for the JSON Form object it
  3348. * receives as parameter:
  3349. * - schema (required): The JSON Schema that describes the form to render
  3350. * - form: The options form layout description, overrides default layout
  3351. * - prefix: String to use to prefix computed IDs. Default is an empty string.
  3352. * Use this option if JSON Form is used multiple times in an application with
  3353. * schemas that have overlapping parameter names to avoid running into multiple
  3354. * IDs issues. Default value is "jsonform-[counter]".
  3355. * - transloadit: Transloadit parameters when transloadit is used
  3356. * - validate: Validates form against schema upon submission. Uses the value
  3357. * of the "validate" property as validator if it is an object.
  3358. * - displayErrors: Function to call with errors upon form submission.
  3359. * Default is to render the errors next to the input fields.
  3360. * - submitEvent: Name of the form submission event to bind to.
  3361. * Default is "submit". Set this option to false to avoid event binding.
  3362. * - onSubmit: Callback function to call when form is submitted
  3363. * - onSubmitValid: Callback function to call when form is submitted without
  3364. * errors.
  3365. *
  3366. * @function
  3367. * @param {Object} options The JSON Form object to use as basis for the form
  3368. */
  3369. $.fn.jsonForm = function(options) {
  3370. var formElt = this;
  3371. options = _.defaults({}, options, {submitEvent: 'submit'});
  3372. var form = new formTree();
  3373. form.initialize(options);
  3374. form.render(formElt.get(0));
  3375. // TODO: move that to formTree.render
  3376. if (options.transloadit) {
  3377. formElt.append('<input type="hidden" name="params" value=\'' +
  3378. escapeHTML(JSON.stringify(options.transloadit.params)) +
  3379. '\'>');
  3380. }
  3381. // Keep a direct pointer to the JSON schema for form submission purpose
  3382. formElt.data("jsonform-tree", form);
  3383. if (options.submitEvent) {
  3384. formElt.unbind((options.submitEvent)+'.jsonform');
  3385. formElt.bind((options.submitEvent)+'.jsonform', function(evt) {
  3386. form.submit(evt);
  3387. });
  3388. }
  3389. // Initialize tabs sections, if any
  3390. initializeTabs(formElt);
  3391. // Initialize expandable sections, if any
  3392. $('.expandable > div, .expandable > fieldset', formElt).hide();
  3393. formElt.on('click', '.expandable > legend', function () {
  3394. var parent = $(this).parent();
  3395. parent.toggleClass('expanded');
  3396. $('> div', parent).slideToggle(100);
  3397. });
  3398. return form;
  3399. };
  3400. /**
  3401. * Retrieves the structured values object generated from the values
  3402. * entered by the user and the data schema that gave birth to the form.
  3403. *
  3404. * Defined as a jQuery function that typically needs to be applied to
  3405. * a <form> element whose content has previously been generated by a
  3406. * call to "jsonForm".
  3407. *
  3408. * Unless explicitly disabled, the values are automatically validated
  3409. * against the constraints expressed in the schema.
  3410. *
  3411. * @function
  3412. * @return {Object} Structured values object that matches the user inputs
  3413. * and the data schema.
  3414. */
  3415. $.fn.jsonFormValue = function() {
  3416. return jsonform.getFormValue(this);
  3417. };
  3418. // Expose the getFormValue method to the global object
  3419. // (other methods exposed as jQuery functions)
  3420. global.JSONForm = global.JSONForm || {util:{}};
  3421. global.JSONForm.getFormValue = jsonform.getFormValue;
  3422. global.JSONForm.fieldTemplate = jsonform.fieldTemplate;
  3423. global.JSONForm.fieldTypes = jsonform.elementTypes;
  3424. global.JSONForm.getInitialValue = getInitialValue;
  3425. global.JSONForm.util.getObjKey = jsonform.util.getObjKey;
  3426. global.JSONForm.util.setObjKey = jsonform.util.setObjKey;
  3427. })((typeof exports !== 'undefined'),
  3428. ((typeof exports !== 'undefined') ? exports : window),
  3429. ((typeof jQuery !== 'undefined') ? jQuery : { fn: {} }),
  3430. ((typeof _ !== 'undefined') ? _ : null),
  3431. JSON);
  3432. },{"underscore":2}],2:[function(require,module,exports){
  3433. (function (global){(function (){
  3434. (function (global, factory) {
  3435. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3436. typeof define === 'function' && define.amd ? define('underscore', factory) :
  3437. (global = global || self, (function () {
  3438. var current = global._;
  3439. var exports = global._ = factory();
  3440. exports.noConflict = function () { global._ = current; return exports; };
  3441. }()));
  3442. }(this, (function () {
  3443. // Underscore.js 1.12.0
  3444. // https://underscorejs.org
  3445. // (c) 2009-2020 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  3446. // Underscore may be freely distributed under the MIT license.
  3447. // Current version.
  3448. var VERSION = '1.12.0';
  3449. // Establish the root object, `window` (`self`) in the browser, `global`
  3450. // on the server, or `this` in some virtual machines. We use `self`
  3451. // instead of `window` for `WebWorker` support.
  3452. var root = typeof self == 'object' && self.self === self && self ||
  3453. typeof global == 'object' && global.global === global && global ||
  3454. Function('return this')() ||
  3455. {};
  3456. // Save bytes in the minified (but not gzipped) version:
  3457. var ArrayProto = Array.prototype, ObjProto = Object.prototype;
  3458. var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
  3459. // Create quick reference variables for speed access to core prototypes.
  3460. var push = ArrayProto.push,
  3461. slice = ArrayProto.slice,
  3462. toString = ObjProto.toString,
  3463. hasOwnProperty = ObjProto.hasOwnProperty;
  3464. // Modern feature detection.
  3465. var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
  3466. supportsDataView = typeof DataView !== 'undefined';
  3467. // All **ECMAScript 5+** native function implementations that we hope to use
  3468. // are declared here.
  3469. var nativeIsArray = Array.isArray,
  3470. nativeKeys = Object.keys,
  3471. nativeCreate = Object.create,
  3472. nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;
  3473. // Create references to these builtin functions because we override them.
  3474. var _isNaN = isNaN,
  3475. _isFinite = isFinite;
  3476. // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  3477. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
  3478. var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
  3479. 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
  3480. // The largest integer that can be represented exactly.
  3481. var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
  3482. // Some functions take a variable number of arguments, or a few expected
  3483. // arguments at the beginning and then a variable number of values to operate
  3484. // on. This helper accumulates all remaining arguments past the function’s
  3485. // argument length (or an explicit `startIndex`), into an array that becomes
  3486. // the last argument. Similar to ES6’s "rest parameter".
  3487. function restArguments(func, startIndex) {
  3488. startIndex = startIndex == null ? func.length - 1 : +startIndex;
  3489. return function() {
  3490. var length = Math.max(arguments.length - startIndex, 0),
  3491. rest = Array(length),
  3492. index = 0;
  3493. for (; index < length; index++) {
  3494. rest[index] = arguments[index + startIndex];
  3495. }
  3496. switch (startIndex) {
  3497. case 0: return func.call(this, rest);
  3498. case 1: return func.call(this, arguments[0], rest);
  3499. case 2: return func.call(this, arguments[0], arguments[1], rest);
  3500. }
  3501. var args = Array(startIndex + 1);
  3502. for (index = 0; index < startIndex; index++) {
  3503. args[index] = arguments[index];
  3504. }
  3505. args[startIndex] = rest;
  3506. return func.apply(this, args);
  3507. };
  3508. }
  3509. // Is a given variable an object?
  3510. function isObject(obj) {
  3511. var type = typeof obj;
  3512. return type === 'function' || type === 'object' && !!obj;
  3513. }
  3514. // Is a given value equal to null?
  3515. function isNull(obj) {
  3516. return obj === null;
  3517. }
  3518. // Is a given variable undefined?
  3519. function isUndefined(obj) {
  3520. return obj === void 0;
  3521. }
  3522. // Is a given value a boolean?
  3523. function isBoolean(obj) {
  3524. return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  3525. }
  3526. // Is a given value a DOM element?
  3527. function isElement(obj) {
  3528. return !!(obj && obj.nodeType === 1);
  3529. }
  3530. // Internal function for creating a `toString`-based type tester.
  3531. function tagTester(name) {
  3532. var tag = '[object ' + name + ']';
  3533. return function(obj) {
  3534. return toString.call(obj) === tag;
  3535. };
  3536. }
  3537. var isString = tagTester('String');
  3538. var isNumber = tagTester('Number');
  3539. var isDate = tagTester('Date');
  3540. var isRegExp = tagTester('RegExp');
  3541. var isError = tagTester('Error');
  3542. var isSymbol = tagTester('Symbol');
  3543. var isArrayBuffer = tagTester('ArrayBuffer');
  3544. var isFunction = tagTester('Function');
  3545. // Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
  3546. // v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
  3547. var nodelist = root.document && root.document.childNodes;
  3548. if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
  3549. isFunction = function(obj) {
  3550. return typeof obj == 'function' || false;
  3551. };
  3552. }
  3553. var isFunction$1 = isFunction;
  3554. var hasObjectTag = tagTester('Object');
  3555. // In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
  3556. // In IE 11, the most common among them, this problem also applies to
  3557. // `Map`, `WeakMap` and `Set`.
  3558. var hasStringTagBug = (
  3559. supportsDataView && hasObjectTag(new DataView(new ArrayBuffer(8)))
  3560. ),
  3561. isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map));
  3562. var isDataView = tagTester('DataView');
  3563. // In IE 10 - Edge 13, we need a different heuristic
  3564. // to determine whether an object is a `DataView`.
  3565. function ie10IsDataView(obj) {
  3566. return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer);
  3567. }
  3568. var isDataView$1 = (hasStringTagBug ? ie10IsDataView : isDataView);
  3569. // Is a given value an array?
  3570. // Delegates to ECMA5's native `Array.isArray`.
  3571. var isArray = nativeIsArray || tagTester('Array');
  3572. // Internal function to check whether `key` is an own property name of `obj`.
  3573. function has(obj, key) {
  3574. return obj != null && hasOwnProperty.call(obj, key);
  3575. }
  3576. var isArguments = tagTester('Arguments');
  3577. // Define a fallback version of the method in browsers (ahem, IE < 9), where
  3578. // there isn't any inspectable "Arguments" type.
  3579. (function() {
  3580. if (!isArguments(arguments)) {
  3581. isArguments = function(obj) {
  3582. return has(obj, 'callee');
  3583. };
  3584. }
  3585. }());
  3586. var isArguments$1 = isArguments;
  3587. // Is a given object a finite number?
  3588. function isFinite$1(obj) {
  3589. return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj));
  3590. }
  3591. // Is the given value `NaN`?
  3592. function isNaN$1(obj) {
  3593. return isNumber(obj) && _isNaN(obj);
  3594. }
  3595. // Predicate-generating function. Often useful outside of Underscore.
  3596. function constant(value) {
  3597. return function() {
  3598. return value;
  3599. };
  3600. }
  3601. // Common internal logic for `isArrayLike` and `isBufferLike`.
  3602. function createSizePropertyCheck(getSizeProperty) {
  3603. return function(collection) {
  3604. var sizeProperty = getSizeProperty(collection);
  3605. return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX;
  3606. }
  3607. }
  3608. // Internal helper to generate a function to obtain property `key` from `obj`.
  3609. function shallowProperty(key) {
  3610. return function(obj) {
  3611. return obj == null ? void 0 : obj[key];
  3612. };
  3613. }
  3614. // Internal helper to obtain the `byteLength` property of an object.
  3615. var getByteLength = shallowProperty('byteLength');
  3616. // Internal helper to determine whether we should spend extensive checks against
  3617. // `ArrayBuffer` et al.
  3618. var isBufferLike = createSizePropertyCheck(getByteLength);
  3619. // Is a given value a typed array?
  3620. var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
  3621. function isTypedArray(obj) {
  3622. // `ArrayBuffer.isView` is the most future-proof, so use it when available.
  3623. // Otherwise, fall back on the above regular expression.
  3624. return nativeIsView ? (nativeIsView(obj) && !isDataView$1(obj)) :
  3625. isBufferLike(obj) && typedArrayPattern.test(toString.call(obj));
  3626. }
  3627. var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false);
  3628. // Internal helper to obtain the `length` property of an object.
  3629. var getLength = shallowProperty('length');
  3630. // Internal helper to create a simple lookup structure.
  3631. // `collectNonEnumProps` used to depend on `_.contains`, but this led to
  3632. // circular imports. `emulatedSet` is a one-off solution that only works for
  3633. // arrays of strings.
  3634. function emulatedSet(keys) {
  3635. var hash = {};
  3636. for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
  3637. return {
  3638. contains: function(key) { return hash[key]; },
  3639. push: function(key) {
  3640. hash[key] = true;
  3641. return keys.push(key);
  3642. }
  3643. };
  3644. }
  3645. // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
  3646. // be iterated by `for key in ...` and thus missed. Extends `keys` in place if
  3647. // needed.
  3648. function collectNonEnumProps(obj, keys) {
  3649. keys = emulatedSet(keys);
  3650. var nonEnumIdx = nonEnumerableProps.length;
  3651. var constructor = obj.constructor;
  3652. var proto = isFunction$1(constructor) && constructor.prototype || ObjProto;
  3653. // Constructor is a special case.
  3654. var prop = 'constructor';
  3655. if (has(obj, prop) && !keys.contains(prop)) keys.push(prop);
  3656. while (nonEnumIdx--) {
  3657. prop = nonEnumerableProps[nonEnumIdx];
  3658. if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
  3659. keys.push(prop);
  3660. }
  3661. }
  3662. }
  3663. // Retrieve the names of an object's own properties.
  3664. // Delegates to **ECMAScript 5**'s native `Object.keys`.
  3665. function keys(obj) {
  3666. if (!isObject(obj)) return [];
  3667. if (nativeKeys) return nativeKeys(obj);
  3668. var keys = [];
  3669. for (var key in obj) if (has(obj, key)) keys.push(key);
  3670. // Ahem, IE < 9.
  3671. if (hasEnumBug) collectNonEnumProps(obj, keys);
  3672. return keys;
  3673. }
  3674. // Is a given array, string, or object empty?
  3675. // An "empty" object has no enumerable own-properties.
  3676. function isEmpty(obj) {
  3677. if (obj == null) return true;
  3678. // Skip the more expensive `toString`-based type checks if `obj` has no
  3679. // `.length`.
  3680. var length = getLength(obj);
  3681. if (typeof length == 'number' && (
  3682. isArray(obj) || isString(obj) || isArguments$1(obj)
  3683. )) return length === 0;
  3684. return getLength(keys(obj)) === 0;
  3685. }
  3686. // Returns whether an object has a given set of `key:value` pairs.
  3687. function isMatch(object, attrs) {
  3688. var _keys = keys(attrs), length = _keys.length;
  3689. if (object == null) return !length;
  3690. var obj = Object(object);
  3691. for (var i = 0; i < length; i++) {
  3692. var key = _keys[i];
  3693. if (attrs[key] !== obj[key] || !(key in obj)) return false;
  3694. }
  3695. return true;
  3696. }
  3697. // If Underscore is called as a function, it returns a wrapped object that can
  3698. // be used OO-style. This wrapper holds altered versions of all functions added
  3699. // through `_.mixin`. Wrapped objects may be chained.
  3700. function _(obj) {
  3701. if (obj instanceof _) return obj;
  3702. if (!(this instanceof _)) return new _(obj);
  3703. this._wrapped = obj;
  3704. }
  3705. _.VERSION = VERSION;
  3706. // Extracts the result from a wrapped and chained object.
  3707. _.prototype.value = function() {
  3708. return this._wrapped;
  3709. };
  3710. // Provide unwrapping proxies for some methods used in engine operations
  3711. // such as arithmetic and JSON stringification.
  3712. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
  3713. _.prototype.toString = function() {
  3714. return String(this._wrapped);
  3715. };
  3716. // Internal function to wrap or shallow-copy an ArrayBuffer,
  3717. // typed array or DataView to a new view, reusing the buffer.
  3718. function toBufferView(bufferSource) {
  3719. return new Uint8Array(
  3720. bufferSource.buffer || bufferSource,
  3721. bufferSource.byteOffset || 0,
  3722. getByteLength(bufferSource)
  3723. );
  3724. }
  3725. // We use this string twice, so give it a name for minification.
  3726. var tagDataView = '[object DataView]';
  3727. // Internal recursive comparison function for `_.isEqual`.
  3728. function eq(a, b, aStack, bStack) {
  3729. // Identical objects are equal. `0 === -0`, but they aren't identical.
  3730. // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
  3731. if (a === b) return a !== 0 || 1 / a === 1 / b;
  3732. // `null` or `undefined` only equal to itself (strict comparison).
  3733. if (a == null || b == null) return false;
  3734. // `NaN`s are equivalent, but non-reflexive.
  3735. if (a !== a) return b !== b;
  3736. // Exhaust primitive checks
  3737. var type = typeof a;
  3738. if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
  3739. return deepEq(a, b, aStack, bStack);
  3740. }
  3741. // Internal recursive comparison function for `_.isEqual`.
  3742. function deepEq(a, b, aStack, bStack) {
  3743. // Unwrap any wrapped objects.
  3744. if (a instanceof _) a = a._wrapped;
  3745. if (b instanceof _) b = b._wrapped;
  3746. // Compare `[[Class]]` names.
  3747. var className = toString.call(a);
  3748. if (className !== toString.call(b)) return false;
  3749. // Work around a bug in IE 10 - Edge 13.
  3750. if (hasStringTagBug && className == '[object Object]' && isDataView$1(a)) {
  3751. if (!isDataView$1(b)) return false;
  3752. className = tagDataView;
  3753. }
  3754. switch (className) {
  3755. // These types are compared by value.
  3756. case '[object RegExp]':
  3757. // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
  3758. case '[object String]':
  3759. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  3760. // equivalent to `new String("5")`.
  3761. return '' + a === '' + b;
  3762. case '[object Number]':
  3763. // `NaN`s are equivalent, but non-reflexive.
  3764. // Object(NaN) is equivalent to NaN.
  3765. if (+a !== +a) return +b !== +b;
  3766. // An `egal` comparison is performed for other numeric values.
  3767. return +a === 0 ? 1 / +a === 1 / b : +a === +b;
  3768. case '[object Date]':
  3769. case '[object Boolean]':
  3770. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  3771. // millisecond representations. Note that invalid dates with millisecond representations
  3772. // of `NaN` are not equivalent.
  3773. return +a === +b;
  3774. case '[object Symbol]':
  3775. return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
  3776. case '[object ArrayBuffer]':
  3777. case tagDataView:
  3778. // Coerce to typed array so we can fall through.
  3779. return deepEq(toBufferView(a), toBufferView(b), aStack, bStack);
  3780. }
  3781. var areArrays = className === '[object Array]';
  3782. if (!areArrays && isTypedArray$1(a)) {
  3783. var byteLength = getByteLength(a);
  3784. if (byteLength !== getByteLength(b)) return false;
  3785. if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true;
  3786. areArrays = true;
  3787. }
  3788. if (!areArrays) {
  3789. if (typeof a != 'object' || typeof b != 'object') return false;
  3790. // Objects with different constructors are not equivalent, but `Object`s or `Array`s
  3791. // from different frames are.
  3792. var aCtor = a.constructor, bCtor = b.constructor;
  3793. if (aCtor !== bCtor && !(isFunction$1(aCtor) && aCtor instanceof aCtor &&
  3794. isFunction$1(bCtor) && bCtor instanceof bCtor)
  3795. && ('constructor' in a && 'constructor' in b)) {
  3796. return false;
  3797. }
  3798. }
  3799. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  3800. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  3801. // Initializing stack of traversed objects.
  3802. // It's done here since we only need them for objects and arrays comparison.
  3803. aStack = aStack || [];
  3804. bStack = bStack || [];
  3805. var length = aStack.length;
  3806. while (length--) {
  3807. // Linear search. Performance is inversely proportional to the number of
  3808. // unique nested structures.
  3809. if (aStack[length] === a) return bStack[length] === b;
  3810. }
  3811. // Add the first object to the stack of traversed objects.
  3812. aStack.push(a);
  3813. bStack.push(b);
  3814. // Recursively compare objects and arrays.
  3815. if (areArrays) {
  3816. // Compare array lengths to determine if a deep comparison is necessary.
  3817. length = a.length;
  3818. if (length !== b.length) return false;
  3819. // Deep compare the contents, ignoring non-numeric properties.
  3820. while (length--) {
  3821. if (!eq(a[length], b[length], aStack, bStack)) return false;
  3822. }
  3823. } else {
  3824. // Deep compare objects.
  3825. var _keys = keys(a), key;
  3826. length = _keys.length;
  3827. // Ensure that both objects contain the same number of properties before comparing deep equality.
  3828. if (keys(b).length !== length) return false;
  3829. while (length--) {
  3830. // Deep compare each member
  3831. key = _keys[length];
  3832. if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
  3833. }
  3834. }
  3835. // Remove the first object from the stack of traversed objects.
  3836. aStack.pop();
  3837. bStack.pop();
  3838. return true;
  3839. }
  3840. // Perform a deep comparison to check if two objects are equal.
  3841. function isEqual(a, b) {
  3842. return eq(a, b);
  3843. }
  3844. // Retrieve all the enumerable property names of an object.
  3845. function allKeys(obj) {
  3846. if (!isObject(obj)) return [];
  3847. var keys = [];
  3848. for (var key in obj) keys.push(key);
  3849. // Ahem, IE < 9.
  3850. if (hasEnumBug) collectNonEnumProps(obj, keys);
  3851. return keys;
  3852. }
  3853. // Since the regular `Object.prototype.toString` type tests don't work for
  3854. // some types in IE 11, we use a fingerprinting heuristic instead, based
  3855. // on the methods. It's not great, but it's the best we got.
  3856. // The fingerprint method lists are defined below.
  3857. function ie11fingerprint(methods) {
  3858. var length = getLength(methods);
  3859. return function(obj) {
  3860. if (obj == null) return false;
  3861. // `Map`, `WeakMap` and `Set` have no enumerable keys.
  3862. var keys = allKeys(obj);
  3863. if (getLength(keys)) return false;
  3864. for (var i = 0; i < length; i++) {
  3865. if (!isFunction$1(obj[methods[i]])) return false;
  3866. }
  3867. // If we are testing against `WeakMap`, we need to ensure that
  3868. // `obj` doesn't have a `forEach` method in order to distinguish
  3869. // it from a regular `Map`.
  3870. return methods !== weakMapMethods || !isFunction$1(obj[forEachName]);
  3871. };
  3872. }
  3873. // In the interest of compact minification, we write
  3874. // each string in the fingerprints only once.
  3875. var forEachName = 'forEach',
  3876. hasName = 'has',
  3877. commonInit = ['clear', 'delete'],
  3878. mapTail = ['get', hasName, 'set'];
  3879. // `Map`, `WeakMap` and `Set` each have slightly different
  3880. // combinations of the above sublists.
  3881. var mapMethods = commonInit.concat(forEachName, mapTail),
  3882. weakMapMethods = commonInit.concat(mapTail),
  3883. setMethods = ['add'].concat(commonInit, forEachName, hasName);
  3884. var isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map');
  3885. var isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap');
  3886. var isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set');
  3887. var isWeakSet = tagTester('WeakSet');
  3888. // Retrieve the values of an object's properties.
  3889. function values(obj) {
  3890. var _keys = keys(obj);
  3891. var length = _keys.length;
  3892. var values = Array(length);
  3893. for (var i = 0; i < length; i++) {
  3894. values[i] = obj[_keys[i]];
  3895. }
  3896. return values;
  3897. }
  3898. // Convert an object into a list of `[key, value]` pairs.
  3899. // The opposite of `_.object` with one argument.
  3900. function pairs(obj) {
  3901. var _keys = keys(obj);
  3902. var length = _keys.length;
  3903. var pairs = Array(length);
  3904. for (var i = 0; i < length; i++) {
  3905. pairs[i] = [_keys[i], obj[_keys[i]]];
  3906. }
  3907. return pairs;
  3908. }
  3909. // Invert the keys and values of an object. The values must be serializable.
  3910. function invert(obj) {
  3911. var result = {};
  3912. var _keys = keys(obj);
  3913. for (var i = 0, length = _keys.length; i < length; i++) {
  3914. result[obj[_keys[i]]] = _keys[i];
  3915. }
  3916. return result;
  3917. }
  3918. // Return a sorted list of the function names available on the object.
  3919. function functions(obj) {
  3920. var names = [];
  3921. for (var key in obj) {
  3922. if (isFunction$1(obj[key])) names.push(key);
  3923. }
  3924. return names.sort();
  3925. }
  3926. // An internal function for creating assigner functions.
  3927. function createAssigner(keysFunc, defaults) {
  3928. return function(obj) {
  3929. var length = arguments.length;
  3930. if (defaults) obj = Object(obj);
  3931. if (length < 2 || obj == null) return obj;
  3932. for (var index = 1; index < length; index++) {
  3933. var source = arguments[index],
  3934. keys = keysFunc(source),
  3935. l = keys.length;
  3936. for (var i = 0; i < l; i++) {
  3937. var key = keys[i];
  3938. if (!defaults || obj[key] === void 0) obj[key] = source[key];
  3939. }
  3940. }
  3941. return obj;
  3942. };
  3943. }
  3944. // Extend a given object with all the properties in passed-in object(s).
  3945. var extend = createAssigner(allKeys);
  3946. // Assigns a given object with all the own properties in the passed-in
  3947. // object(s).
  3948. // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  3949. var extendOwn = createAssigner(keys);
  3950. // Fill in a given object with default properties.
  3951. var defaults = createAssigner(allKeys, true);
  3952. // Create a naked function reference for surrogate-prototype-swapping.
  3953. function ctor() {
  3954. return function(){};
  3955. }
  3956. // An internal function for creating a new object that inherits from another.
  3957. function baseCreate(prototype) {
  3958. if (!isObject(prototype)) return {};
  3959. if (nativeCreate) return nativeCreate(prototype);
  3960. var Ctor = ctor();
  3961. Ctor.prototype = prototype;
  3962. var result = new Ctor;
  3963. Ctor.prototype = null;
  3964. return result;
  3965. }
  3966. // Creates an object that inherits from the given prototype object.
  3967. // If additional properties are provided then they will be added to the
  3968. // created object.
  3969. function create(prototype, props) {
  3970. var result = baseCreate(prototype);
  3971. if (props) extendOwn(result, props);
  3972. return result;
  3973. }
  3974. // Create a (shallow-cloned) duplicate of an object.
  3975. function clone(obj) {
  3976. if (!isObject(obj)) return obj;
  3977. return isArray(obj) ? obj.slice() : extend({}, obj);
  3978. }
  3979. // Invokes `interceptor` with the `obj` and then returns `obj`.
  3980. // The primary purpose of this method is to "tap into" a method chain, in
  3981. // order to perform operations on intermediate results within the chain.
  3982. function tap(obj, interceptor) {
  3983. interceptor(obj);
  3984. return obj;
  3985. }
  3986. // Normalize a (deep) property `path` to array.
  3987. // Like `_.iteratee`, this function can be customized.
  3988. function toPath(path) {
  3989. return isArray(path) ? path : [path];
  3990. }
  3991. _.toPath = toPath;
  3992. // Internal wrapper for `_.toPath` to enable minification.
  3993. // Similar to `cb` for `_.iteratee`.
  3994. function toPath$1(path) {
  3995. return _.toPath(path);
  3996. }
  3997. // Internal function to obtain a nested property in `obj` along `path`.
  3998. function deepGet(obj, path) {
  3999. var length = path.length;
  4000. for (var i = 0; i < length; i++) {
  4001. if (obj == null) return void 0;
  4002. obj = obj[path[i]];
  4003. }
  4004. return length ? obj : void 0;
  4005. }
  4006. // Get the value of the (deep) property on `path` from `object`.
  4007. // If any property in `path` does not exist or if the value is
  4008. // `undefined`, return `defaultValue` instead.
  4009. // The `path` is normalized through `_.toPath`.
  4010. function get(object, path, defaultValue) {
  4011. var value = deepGet(object, toPath$1(path));
  4012. return isUndefined(value) ? defaultValue : value;
  4013. }
  4014. // Shortcut function for checking if an object has a given property directly on
  4015. // itself (in other words, not on a prototype). Unlike the internal `has`
  4016. // function, this public version can also traverse nested properties.
  4017. function has$1(obj, path) {
  4018. path = toPath$1(path);
  4019. var length = path.length;
  4020. for (var i = 0; i < length; i++) {
  4021. var key = path[i];
  4022. if (!has(obj, key)) return false;
  4023. obj = obj[key];
  4024. }
  4025. return !!length;
  4026. }
  4027. // Keep the identity function around for default iteratees.
  4028. function identity(value) {
  4029. return value;
  4030. }
  4031. // Returns a predicate for checking whether an object has a given set of
  4032. // `key:value` pairs.
  4033. function matcher(attrs) {
  4034. attrs = extendOwn({}, attrs);
  4035. return function(obj) {
  4036. return isMatch(obj, attrs);
  4037. };
  4038. }
  4039. // Creates a function that, when passed an object, will traverse that object’s
  4040. // properties down the given `path`, specified as an array of keys or indices.
  4041. function property(path) {
  4042. path = toPath$1(path);
  4043. return function(obj) {
  4044. return deepGet(obj, path);
  4045. };
  4046. }
  4047. // Internal function that returns an efficient (for current engines) version
  4048. // of the passed-in callback, to be repeatedly applied in other Underscore
  4049. // functions.
  4050. function optimizeCb(func, context, argCount) {
  4051. if (context === void 0) return func;
  4052. switch (argCount == null ? 3 : argCount) {
  4053. case 1: return function(value) {
  4054. return func.call(context, value);
  4055. };
  4056. // The 2-argument case is omitted because we’re not using it.
  4057. case 3: return function(value, index, collection) {
  4058. return func.call(context, value, index, collection);
  4059. };
  4060. case 4: return function(accumulator, value, index, collection) {
  4061. return func.call(context, accumulator, value, index, collection);
  4062. };
  4063. }
  4064. return function() {
  4065. return func.apply(context, arguments);
  4066. };
  4067. }
  4068. // An internal function to generate callbacks that can be applied to each
  4069. // element in a collection, returning the desired result — either `_.identity`,
  4070. // an arbitrary callback, a property matcher, or a property accessor.
  4071. function baseIteratee(value, context, argCount) {
  4072. if (value == null) return identity;
  4073. if (isFunction$1(value)) return optimizeCb(value, context, argCount);
  4074. if (isObject(value) && !isArray(value)) return matcher(value);
  4075. return property(value);
  4076. }
  4077. // External wrapper for our callback generator. Users may customize
  4078. // `_.iteratee` if they want additional predicate/iteratee shorthand styles.
  4079. // This abstraction hides the internal-only `argCount` argument.
  4080. function iteratee(value, context) {
  4081. return baseIteratee(value, context, Infinity);
  4082. }
  4083. _.iteratee = iteratee;
  4084. // The function we call internally to generate a callback. It invokes
  4085. // `_.iteratee` if overridden, otherwise `baseIteratee`.
  4086. function cb(value, context, argCount) {
  4087. if (_.iteratee !== iteratee) return _.iteratee(value, context);
  4088. return baseIteratee(value, context, argCount);
  4089. }
  4090. // Returns the results of applying the `iteratee` to each element of `obj`.
  4091. // In contrast to `_.map` it returns an object.
  4092. function mapObject(obj, iteratee, context) {
  4093. iteratee = cb(iteratee, context);
  4094. var _keys = keys(obj),
  4095. length = _keys.length,
  4096. results = {};
  4097. for (var index = 0; index < length; index++) {
  4098. var currentKey = _keys[index];
  4099. results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
  4100. }
  4101. return results;
  4102. }
  4103. // Predicate-generating function. Often useful outside of Underscore.
  4104. function noop(){}
  4105. // Generates a function for a given object that returns a given property.
  4106. function propertyOf(obj) {
  4107. if (obj == null) return noop;
  4108. return function(path) {
  4109. return get(obj, path);
  4110. };
  4111. }
  4112. // Run a function **n** times.
  4113. function times(n, iteratee, context) {
  4114. var accum = Array(Math.max(0, n));
  4115. iteratee = optimizeCb(iteratee, context, 1);
  4116. for (var i = 0; i < n; i++) accum[i] = iteratee(i);
  4117. return accum;
  4118. }
  4119. // Return a random integer between `min` and `max` (inclusive).
  4120. function random(min, max) {
  4121. if (max == null) {
  4122. max = min;
  4123. min = 0;
  4124. }
  4125. return min + Math.floor(Math.random() * (max - min + 1));
  4126. }
  4127. // A (possibly faster) way to get the current timestamp as an integer.
  4128. var now = Date.now || function() {
  4129. return new Date().getTime();
  4130. };
  4131. // Internal helper to generate functions for escaping and unescaping strings
  4132. // to/from HTML interpolation.
  4133. function createEscaper(map) {
  4134. var escaper = function(match) {
  4135. return map[match];
  4136. };
  4137. // Regexes for identifying a key that needs to be escaped.
  4138. var source = '(?:' + keys(map).join('|') + ')';
  4139. var testRegexp = RegExp(source);
  4140. var replaceRegexp = RegExp(source, 'g');
  4141. return function(string) {
  4142. string = string == null ? '' : '' + string;
  4143. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  4144. };
  4145. }
  4146. // Internal list of HTML entities for escaping.
  4147. var escapeMap = {
  4148. '&': '&amp;',
  4149. '<': '&lt;',
  4150. '>': '&gt;',
  4151. '"': '&quot;',
  4152. "'": '&#x27;',
  4153. '`': '&#x60;'
  4154. };
  4155. // Function for escaping strings to HTML interpolation.
  4156. var _escape = createEscaper(escapeMap);
  4157. // Internal list of HTML entities for unescaping.
  4158. var unescapeMap = invert(escapeMap);
  4159. // Function for unescaping strings from HTML interpolation.
  4160. var _unescape = createEscaper(unescapeMap);
  4161. // By default, Underscore uses ERB-style template delimiters. Change the
  4162. // following template settings to use alternative delimiters.
  4163. var templateSettings = _.templateSettings = {
  4164. evaluate: /<%([\s\S]+?)%>/g,
  4165. interpolate: /<%=([\s\S]+?)%>/g,
  4166. escape: /<%-([\s\S]+?)%>/g
  4167. };
  4168. // When customizing `_.templateSettings`, if you don't want to define an
  4169. // interpolation, evaluation or escaping regex, we need one that is
  4170. // guaranteed not to match.
  4171. var noMatch = /(.)^/;
  4172. // Certain characters need to be escaped so that they can be put into a
  4173. // string literal.
  4174. var escapes = {
  4175. "'": "'",
  4176. '\\': '\\',
  4177. '\r': 'r',
  4178. '\n': 'n',
  4179. '\u2028': 'u2028',
  4180. '\u2029': 'u2029'
  4181. };
  4182. var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
  4183. function escapeChar(match) {
  4184. return '\\' + escapes[match];
  4185. }
  4186. // JavaScript micro-templating, similar to John Resig's implementation.
  4187. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  4188. // and correctly escapes quotes within interpolated code.
  4189. // NB: `oldSettings` only exists for backwards compatibility.
  4190. function template(text, settings, oldSettings) {
  4191. if (!settings && oldSettings) settings = oldSettings;
  4192. settings = defaults({}, settings, _.templateSettings);
  4193. // Combine delimiters into one regular expression via alternation.
  4194. var matcher = RegExp([
  4195. (settings.escape || noMatch).source,
  4196. (settings.interpolate || noMatch).source,
  4197. (settings.evaluate || noMatch).source
  4198. ].join('|') + '|$', 'g');
  4199. // Compile the template source, escaping string literals appropriately.
  4200. var index = 0;
  4201. var source = "__p+='";
  4202. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  4203. source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
  4204. index = offset + match.length;
  4205. if (escape) {
  4206. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  4207. } else if (interpolate) {
  4208. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  4209. } else if (evaluate) {
  4210. source += "';\n" + evaluate + "\n__p+='";
  4211. }
  4212. // Adobe VMs need the match returned to produce the correct offset.
  4213. return match;
  4214. });
  4215. source += "';\n";
  4216. // If a variable is not specified, place data values in local scope.
  4217. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  4218. source = "var __t,__p='',__j=Array.prototype.join," +
  4219. "print=function(){__p+=__j.call(arguments,'');};\n" +
  4220. source + 'return __p;\n';
  4221. var render;
  4222. try {
  4223. render = new Function(settings.variable || 'obj', '_', source);
  4224. } catch (e) {
  4225. e.source = source;
  4226. throw e;
  4227. }
  4228. var template = function(data) {
  4229. return render.call(this, data, _);
  4230. };
  4231. // Provide the compiled source as a convenience for precompilation.
  4232. var argument = settings.variable || 'obj';
  4233. template.source = 'function(' + argument + '){\n' + source + '}';
  4234. return template;
  4235. }
  4236. // Traverses the children of `obj` along `path`. If a child is a function, it
  4237. // is invoked with its parent as context. Returns the value of the final
  4238. // child, or `fallback` if any child is undefined.
  4239. function result(obj, path, fallback) {
  4240. path = toPath$1(path);
  4241. var length = path.length;
  4242. if (!length) {
  4243. return isFunction$1(fallback) ? fallback.call(obj) : fallback;
  4244. }
  4245. for (var i = 0; i < length; i++) {
  4246. var prop = obj == null ? void 0 : obj[path[i]];
  4247. if (prop === void 0) {
  4248. prop = fallback;
  4249. i = length; // Ensure we don't continue iterating.
  4250. }
  4251. obj = isFunction$1(prop) ? prop.call(obj) : prop;
  4252. }
  4253. return obj;
  4254. }
  4255. // Generate a unique integer id (unique within the entire client session).
  4256. // Useful for temporary DOM ids.
  4257. var idCounter = 0;
  4258. function uniqueId(prefix) {
  4259. var id = ++idCounter + '';
  4260. return prefix ? prefix + id : id;
  4261. }
  4262. // Start chaining a wrapped Underscore object.
  4263. function chain(obj) {
  4264. var instance = _(obj);
  4265. instance._chain = true;
  4266. return instance;
  4267. }
  4268. // Internal function to execute `sourceFunc` bound to `context` with optional
  4269. // `args`. Determines whether to execute a function as a constructor or as a
  4270. // normal function.
  4271. function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
  4272. if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
  4273. var self = baseCreate(sourceFunc.prototype);
  4274. var result = sourceFunc.apply(self, args);
  4275. if (isObject(result)) return result;
  4276. return self;
  4277. }
  4278. // Partially apply a function by creating a version that has had some of its
  4279. // arguments pre-filled, without changing its dynamic `this` context. `_` acts
  4280. // as a placeholder by default, allowing any combination of arguments to be
  4281. // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
  4282. var partial = restArguments(function(func, boundArgs) {
  4283. var placeholder = partial.placeholder;
  4284. var bound = function() {
  4285. var position = 0, length = boundArgs.length;
  4286. var args = Array(length);
  4287. for (var i = 0; i < length; i++) {
  4288. args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
  4289. }
  4290. while (position < arguments.length) args.push(arguments[position++]);
  4291. return executeBound(func, bound, this, this, args);
  4292. };
  4293. return bound;
  4294. });
  4295. partial.placeholder = _;
  4296. // Create a function bound to a given object (assigning `this`, and arguments,
  4297. // optionally).
  4298. var bind = restArguments(function(func, context, args) {
  4299. if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function');
  4300. var bound = restArguments(function(callArgs) {
  4301. return executeBound(func, bound, context, this, args.concat(callArgs));
  4302. });
  4303. return bound;
  4304. });
  4305. // Internal helper for collection methods to determine whether a collection
  4306. // should be iterated as an array or as an object.
  4307. // Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  4308. // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  4309. var isArrayLike = createSizePropertyCheck(getLength);
  4310. // Internal implementation of a recursive `flatten` function.
  4311. function flatten(input, depth, strict, output) {
  4312. output = output || [];
  4313. if (!depth && depth !== 0) {
  4314. depth = Infinity;
  4315. } else if (depth <= 0) {
  4316. return output.concat(input);
  4317. }
  4318. var idx = output.length;
  4319. for (var i = 0, length = getLength(input); i < length; i++) {
  4320. var value = input[i];
  4321. if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) {
  4322. // Flatten current level of array or arguments object.
  4323. if (depth > 1) {
  4324. flatten(value, depth - 1, strict, output);
  4325. idx = output.length;
  4326. } else {
  4327. var j = 0, len = value.length;
  4328. while (j < len) output[idx++] = value[j++];
  4329. }
  4330. } else if (!strict) {
  4331. output[idx++] = value;
  4332. }
  4333. }
  4334. return output;
  4335. }
  4336. // Bind a number of an object's methods to that object. Remaining arguments
  4337. // are the method names to be bound. Useful for ensuring that all callbacks
  4338. // defined on an object belong to it.
  4339. var bindAll = restArguments(function(obj, keys) {
  4340. keys = flatten(keys, false, false);
  4341. var index = keys.length;
  4342. if (index < 1) throw new Error('bindAll must be passed function names');
  4343. while (index--) {
  4344. var key = keys[index];
  4345. obj[key] = bind(obj[key], obj);
  4346. }
  4347. return obj;
  4348. });
  4349. // Memoize an expensive function by storing its results.
  4350. function memoize(func, hasher) {
  4351. var memoize = function(key) {
  4352. var cache = memoize.cache;
  4353. var address = '' + (hasher ? hasher.apply(this, arguments) : key);
  4354. if (!has(cache, address)) cache[address] = func.apply(this, arguments);
  4355. return cache[address];
  4356. };
  4357. memoize.cache = {};
  4358. return memoize;
  4359. }
  4360. // Delays a function for the given number of milliseconds, and then calls
  4361. // it with the arguments supplied.
  4362. var delay = restArguments(function(func, wait, args) {
  4363. return setTimeout(function() {
  4364. return func.apply(null, args);
  4365. }, wait);
  4366. });
  4367. // Defers a function, scheduling it to run after the current call stack has
  4368. // cleared.
  4369. var defer = partial(delay, _, 1);
  4370. // Returns a function, that, when invoked, will only be triggered at most once
  4371. // during a given window of time. Normally, the throttled function will run
  4372. // as much as it can, without ever going more than once per `wait` duration;
  4373. // but if you'd like to disable the execution on the leading edge, pass
  4374. // `{leading: false}`. To disable execution on the trailing edge, ditto.
  4375. function throttle(func, wait, options) {
  4376. var timeout, context, args, result;
  4377. var previous = 0;
  4378. if (!options) options = {};
  4379. var later = function() {
  4380. previous = options.leading === false ? 0 : now();
  4381. timeout = null;
  4382. result = func.apply(context, args);
  4383. if (!timeout) context = args = null;
  4384. };
  4385. var throttled = function() {
  4386. var _now = now();
  4387. if (!previous && options.leading === false) previous = _now;
  4388. var remaining = wait - (_now - previous);
  4389. context = this;
  4390. args = arguments;
  4391. if (remaining <= 0 || remaining > wait) {
  4392. if (timeout) {
  4393. clearTimeout(timeout);
  4394. timeout = null;
  4395. }
  4396. previous = _now;
  4397. result = func.apply(context, args);
  4398. if (!timeout) context = args = null;
  4399. } else if (!timeout && options.trailing !== false) {
  4400. timeout = setTimeout(later, remaining);
  4401. }
  4402. return result;
  4403. };
  4404. throttled.cancel = function() {
  4405. clearTimeout(timeout);
  4406. previous = 0;
  4407. timeout = context = args = null;
  4408. };
  4409. return throttled;
  4410. }
  4411. // When a sequence of calls of the returned function ends, the argument
  4412. // function is triggered. The end of a sequence is defined by the `wait`
  4413. // parameter. If `immediate` is passed, the argument function will be
  4414. // triggered at the beginning of the sequence instead of at the end.
  4415. function debounce(func, wait, immediate) {
  4416. var timeout, result;
  4417. var later = function(context, args) {
  4418. timeout = null;
  4419. if (args) result = func.apply(context, args);
  4420. };
  4421. var debounced = restArguments(function(args) {
  4422. if (timeout) clearTimeout(timeout);
  4423. if (immediate) {
  4424. var callNow = !timeout;
  4425. timeout = setTimeout(later, wait);
  4426. if (callNow) result = func.apply(this, args);
  4427. } else {
  4428. timeout = delay(later, wait, this, args);
  4429. }
  4430. return result;
  4431. });
  4432. debounced.cancel = function() {
  4433. clearTimeout(timeout);
  4434. timeout = null;
  4435. };
  4436. return debounced;
  4437. }
  4438. // Returns the first function passed as an argument to the second,
  4439. // allowing you to adjust arguments, run code before and after, and
  4440. // conditionally execute the original function.
  4441. function wrap(func, wrapper) {
  4442. return partial(wrapper, func);
  4443. }
  4444. // Returns a negated version of the passed-in predicate.
  4445. function negate(predicate) {
  4446. return function() {
  4447. return !predicate.apply(this, arguments);
  4448. };
  4449. }
  4450. // Returns a function that is the composition of a list of functions, each
  4451. // consuming the return value of the function that follows.
  4452. function compose() {
  4453. var args = arguments;
  4454. var start = args.length - 1;
  4455. return function() {
  4456. var i = start;
  4457. var result = args[start].apply(this, arguments);
  4458. while (i--) result = args[i].call(this, result);
  4459. return result;
  4460. };
  4461. }
  4462. // Returns a function that will only be executed on and after the Nth call.
  4463. function after(times, func) {
  4464. return function() {
  4465. if (--times < 1) {
  4466. return func.apply(this, arguments);
  4467. }
  4468. };
  4469. }
  4470. // Returns a function that will only be executed up to (but not including) the
  4471. // Nth call.
  4472. function before(times, func) {
  4473. var memo;
  4474. return function() {
  4475. if (--times > 0) {
  4476. memo = func.apply(this, arguments);
  4477. }
  4478. if (times <= 1) func = null;
  4479. return memo;
  4480. };
  4481. }
  4482. // Returns a function that will be executed at most one time, no matter how
  4483. // often you call it. Useful for lazy initialization.
  4484. var once = partial(before, 2);
  4485. // Returns the first key on an object that passes a truth test.
  4486. function findKey(obj, predicate, context) {
  4487. predicate = cb(predicate, context);
  4488. var _keys = keys(obj), key;
  4489. for (var i = 0, length = _keys.length; i < length; i++) {
  4490. key = _keys[i];
  4491. if (predicate(obj[key], key, obj)) return key;
  4492. }
  4493. }
  4494. // Internal function to generate `_.findIndex` and `_.findLastIndex`.
  4495. function createPredicateIndexFinder(dir) {
  4496. return function(array, predicate, context) {
  4497. predicate = cb(predicate, context);
  4498. var length = getLength(array);
  4499. var index = dir > 0 ? 0 : length - 1;
  4500. for (; index >= 0 && index < length; index += dir) {
  4501. if (predicate(array[index], index, array)) return index;
  4502. }
  4503. return -1;
  4504. };
  4505. }
  4506. // Returns the first index on an array-like that passes a truth test.
  4507. var findIndex = createPredicateIndexFinder(1);
  4508. // Returns the last index on an array-like that passes a truth test.
  4509. var findLastIndex = createPredicateIndexFinder(-1);
  4510. // Use a comparator function to figure out the smallest index at which
  4511. // an object should be inserted so as to maintain order. Uses binary search.
  4512. function sortedIndex(array, obj, iteratee, context) {
  4513. iteratee = cb(iteratee, context, 1);
  4514. var value = iteratee(obj);
  4515. var low = 0, high = getLength(array);
  4516. while (low < high) {
  4517. var mid = Math.floor((low + high) / 2);
  4518. if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
  4519. }
  4520. return low;
  4521. }
  4522. // Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions.
  4523. function createIndexFinder(dir, predicateFind, sortedIndex) {
  4524. return function(array, item, idx) {
  4525. var i = 0, length = getLength(array);
  4526. if (typeof idx == 'number') {
  4527. if (dir > 0) {
  4528. i = idx >= 0 ? idx : Math.max(idx + length, i);
  4529. } else {
  4530. length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
  4531. }
  4532. } else if (sortedIndex && idx && length) {
  4533. idx = sortedIndex(array, item);
  4534. return array[idx] === item ? idx : -1;
  4535. }
  4536. if (item !== item) {
  4537. idx = predicateFind(slice.call(array, i, length), isNaN$1);
  4538. return idx >= 0 ? idx + i : -1;
  4539. }
  4540. for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
  4541. if (array[idx] === item) return idx;
  4542. }
  4543. return -1;
  4544. };
  4545. }
  4546. // Return the position of the first occurrence of an item in an array,
  4547. // or -1 if the item is not included in the array.
  4548. // If the array is large and already in sort order, pass `true`
  4549. // for **isSorted** to use binary search.
  4550. var indexOf = createIndexFinder(1, findIndex, sortedIndex);
  4551. // Return the position of the last occurrence of an item in an array,
  4552. // or -1 if the item is not included in the array.
  4553. var lastIndexOf = createIndexFinder(-1, findLastIndex);
  4554. // Return the first value which passes a truth test.
  4555. function find(obj, predicate, context) {
  4556. var keyFinder = isArrayLike(obj) ? findIndex : findKey;
  4557. var key = keyFinder(obj, predicate, context);
  4558. if (key !== void 0 && key !== -1) return obj[key];
  4559. }
  4560. // Convenience version of a common use case of `_.find`: getting the first
  4561. // object containing specific `key:value` pairs.
  4562. function findWhere(obj, attrs) {
  4563. return find(obj, matcher(attrs));
  4564. }
  4565. // The cornerstone for collection functions, an `each`
  4566. // implementation, aka `forEach`.
  4567. // Handles raw objects in addition to array-likes. Treats all
  4568. // sparse array-likes as if they were dense.
  4569. function each(obj, iteratee, context) {
  4570. iteratee = optimizeCb(iteratee, context);
  4571. var i, length;
  4572. if (isArrayLike(obj)) {
  4573. for (i = 0, length = obj.length; i < length; i++) {
  4574. iteratee(obj[i], i, obj);
  4575. }
  4576. } else {
  4577. var _keys = keys(obj);
  4578. for (i = 0, length = _keys.length; i < length; i++) {
  4579. iteratee(obj[_keys[i]], _keys[i], obj);
  4580. }
  4581. }
  4582. return obj;
  4583. }
  4584. // Return the results of applying the iteratee to each element.
  4585. function map(obj, iteratee, context) {
  4586. iteratee = cb(iteratee, context);
  4587. var _keys = !isArrayLike(obj) && keys(obj),
  4588. length = (_keys || obj).length,
  4589. results = Array(length);
  4590. for (var index = 0; index < length; index++) {
  4591. var currentKey = _keys ? _keys[index] : index;
  4592. results[index] = iteratee(obj[currentKey], currentKey, obj);
  4593. }
  4594. return results;
  4595. }
  4596. // Internal helper to create a reducing function, iterating left or right.
  4597. function createReduce(dir) {
  4598. // Wrap code that reassigns argument variables in a separate function than
  4599. // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
  4600. var reducer = function(obj, iteratee, memo, initial) {
  4601. var _keys = !isArrayLike(obj) && keys(obj),
  4602. length = (_keys || obj).length,
  4603. index = dir > 0 ? 0 : length - 1;
  4604. if (!initial) {
  4605. memo = obj[_keys ? _keys[index] : index];
  4606. index += dir;
  4607. }
  4608. for (; index >= 0 && index < length; index += dir) {
  4609. var currentKey = _keys ? _keys[index] : index;
  4610. memo = iteratee(memo, obj[currentKey], currentKey, obj);
  4611. }
  4612. return memo;
  4613. };
  4614. return function(obj, iteratee, memo, context) {
  4615. var initial = arguments.length >= 3;
  4616. return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
  4617. };
  4618. }
  4619. // **Reduce** builds up a single result from a list of values, aka `inject`,
  4620. // or `foldl`.
  4621. var reduce = createReduce(1);
  4622. // The right-associative version of reduce, also known as `foldr`.
  4623. var reduceRight = createReduce(-1);
  4624. // Return all the elements that pass a truth test.
  4625. function filter(obj, predicate, context) {
  4626. var results = [];
  4627. predicate = cb(predicate, context);
  4628. each(obj, function(value, index, list) {
  4629. if (predicate(value, index, list)) results.push(value);
  4630. });
  4631. return results;
  4632. }
  4633. // Return all the elements for which a truth test fails.
  4634. function reject(obj, predicate, context) {
  4635. return filter(obj, negate(cb(predicate)), context);
  4636. }
  4637. // Determine whether all of the elements pass a truth test.
  4638. function every(obj, predicate, context) {
  4639. predicate = cb(predicate, context);
  4640. var _keys = !isArrayLike(obj) && keys(obj),
  4641. length = (_keys || obj).length;
  4642. for (var index = 0; index < length; index++) {
  4643. var currentKey = _keys ? _keys[index] : index;
  4644. if (!predicate(obj[currentKey], currentKey, obj)) return false;
  4645. }
  4646. return true;
  4647. }
  4648. // Determine if at least one element in the object passes a truth test.
  4649. function some(obj, predicate, context) {
  4650. predicate = cb(predicate, context);
  4651. var _keys = !isArrayLike(obj) && keys(obj),
  4652. length = (_keys || obj).length;
  4653. for (var index = 0; index < length; index++) {
  4654. var currentKey = _keys ? _keys[index] : index;
  4655. if (predicate(obj[currentKey], currentKey, obj)) return true;
  4656. }
  4657. return false;
  4658. }
  4659. // Determine if the array or object contains a given item (using `===`).
  4660. function contains(obj, item, fromIndex, guard) {
  4661. if (!isArrayLike(obj)) obj = values(obj);
  4662. if (typeof fromIndex != 'number' || guard) fromIndex = 0;
  4663. return indexOf(obj, item, fromIndex) >= 0;
  4664. }
  4665. // Invoke a method (with arguments) on every item in a collection.
  4666. var invoke = restArguments(function(obj, path, args) {
  4667. var contextPath, func;
  4668. if (isFunction$1(path)) {
  4669. func = path;
  4670. } else {
  4671. path = toPath$1(path);
  4672. contextPath = path.slice(0, -1);
  4673. path = path[path.length - 1];
  4674. }
  4675. return map(obj, function(context) {
  4676. var method = func;
  4677. if (!method) {
  4678. if (contextPath && contextPath.length) {
  4679. context = deepGet(context, contextPath);
  4680. }
  4681. if (context == null) return void 0;
  4682. method = context[path];
  4683. }
  4684. return method == null ? method : method.apply(context, args);
  4685. });
  4686. });
  4687. // Convenience version of a common use case of `_.map`: fetching a property.
  4688. function pluck(obj, key) {
  4689. return map(obj, property(key));
  4690. }
  4691. // Convenience version of a common use case of `_.filter`: selecting only
  4692. // objects containing specific `key:value` pairs.
  4693. function where(obj, attrs) {
  4694. return filter(obj, matcher(attrs));
  4695. }
  4696. // Return the maximum element (or element-based computation).
  4697. function max(obj, iteratee, context) {
  4698. var result = -Infinity, lastComputed = -Infinity,
  4699. value, computed;
  4700. if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
  4701. obj = isArrayLike(obj) ? obj : values(obj);
  4702. for (var i = 0, length = obj.length; i < length; i++) {
  4703. value = obj[i];
  4704. if (value != null && value > result) {
  4705. result = value;
  4706. }
  4707. }
  4708. } else {
  4709. iteratee = cb(iteratee, context);
  4710. each(obj, function(v, index, list) {
  4711. computed = iteratee(v, index, list);
  4712. if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
  4713. result = v;
  4714. lastComputed = computed;
  4715. }
  4716. });
  4717. }
  4718. return result;
  4719. }
  4720. // Return the minimum element (or element-based computation).
  4721. function min(obj, iteratee, context) {
  4722. var result = Infinity, lastComputed = Infinity,
  4723. value, computed;
  4724. if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
  4725. obj = isArrayLike(obj) ? obj : values(obj);
  4726. for (var i = 0, length = obj.length; i < length; i++) {
  4727. value = obj[i];
  4728. if (value != null && value < result) {
  4729. result = value;
  4730. }
  4731. }
  4732. } else {
  4733. iteratee = cb(iteratee, context);
  4734. each(obj, function(v, index, list) {
  4735. computed = iteratee(v, index, list);
  4736. if (computed < lastComputed || computed === Infinity && result === Infinity) {
  4737. result = v;
  4738. lastComputed = computed;
  4739. }
  4740. });
  4741. }
  4742. return result;
  4743. }
  4744. // Sample **n** random values from a collection using the modern version of the
  4745. // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  4746. // If **n** is not specified, returns a single random element.
  4747. // The internal `guard` argument allows it to work with `_.map`.
  4748. function sample(obj, n, guard) {
  4749. if (n == null || guard) {
  4750. if (!isArrayLike(obj)) obj = values(obj);
  4751. return obj[random(obj.length - 1)];
  4752. }
  4753. var sample = isArrayLike(obj) ? clone(obj) : values(obj);
  4754. var length = getLength(sample);
  4755. n = Math.max(Math.min(n, length), 0);
  4756. var last = length - 1;
  4757. for (var index = 0; index < n; index++) {
  4758. var rand = random(index, last);
  4759. var temp = sample[index];
  4760. sample[index] = sample[rand];
  4761. sample[rand] = temp;
  4762. }
  4763. return sample.slice(0, n);
  4764. }
  4765. // Shuffle a collection.
  4766. function shuffle(obj) {
  4767. return sample(obj, Infinity);
  4768. }
  4769. // Sort the object's values by a criterion produced by an iteratee.
  4770. function sortBy(obj, iteratee, context) {
  4771. var index = 0;
  4772. iteratee = cb(iteratee, context);
  4773. return pluck(map(obj, function(value, key, list) {
  4774. return {
  4775. value: value,
  4776. index: index++,
  4777. criteria: iteratee(value, key, list)
  4778. };
  4779. }).sort(function(left, right) {
  4780. var a = left.criteria;
  4781. var b = right.criteria;
  4782. if (a !== b) {
  4783. if (a > b || a === void 0) return 1;
  4784. if (a < b || b === void 0) return -1;
  4785. }
  4786. return left.index - right.index;
  4787. }), 'value');
  4788. }
  4789. // An internal function used for aggregate "group by" operations.
  4790. function group(behavior, partition) {
  4791. return function(obj, iteratee, context) {
  4792. var result = partition ? [[], []] : {};
  4793. iteratee = cb(iteratee, context);
  4794. each(obj, function(value, index) {
  4795. var key = iteratee(value, index, obj);
  4796. behavior(result, value, key);
  4797. });
  4798. return result;
  4799. };
  4800. }
  4801. // Groups the object's values by a criterion. Pass either a string attribute
  4802. // to group by, or a function that returns the criterion.
  4803. var groupBy = group(function(result, value, key) {
  4804. if (has(result, key)) result[key].push(value); else result[key] = [value];
  4805. });
  4806. // Indexes the object's values by a criterion, similar to `_.groupBy`, but for
  4807. // when you know that your index values will be unique.
  4808. var indexBy = group(function(result, value, key) {
  4809. result[key] = value;
  4810. });
  4811. // Counts instances of an object that group by a certain criterion. Pass
  4812. // either a string attribute to count by, or a function that returns the
  4813. // criterion.
  4814. var countBy = group(function(result, value, key) {
  4815. if (has(result, key)) result[key]++; else result[key] = 1;
  4816. });
  4817. // Split a collection into two arrays: one whose elements all pass the given
  4818. // truth test, and one whose elements all do not pass the truth test.
  4819. var partition = group(function(result, value, pass) {
  4820. result[pass ? 0 : 1].push(value);
  4821. }, true);
  4822. // Safely create a real, live array from anything iterable.
  4823. var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
  4824. function toArray(obj) {
  4825. if (!obj) return [];
  4826. if (isArray(obj)) return slice.call(obj);
  4827. if (isString(obj)) {
  4828. // Keep surrogate pair characters together.
  4829. return obj.match(reStrSymbol);
  4830. }
  4831. if (isArrayLike(obj)) return map(obj, identity);
  4832. return values(obj);
  4833. }
  4834. // Return the number of elements in a collection.
  4835. function size(obj) {
  4836. if (obj == null) return 0;
  4837. return isArrayLike(obj) ? obj.length : keys(obj).length;
  4838. }
  4839. // Internal `_.pick` helper function to determine whether `key` is an enumerable
  4840. // property name of `obj`.
  4841. function keyInObj(value, key, obj) {
  4842. return key in obj;
  4843. }
  4844. // Return a copy of the object only containing the allowed properties.
  4845. var pick = restArguments(function(obj, keys) {
  4846. var result = {}, iteratee = keys[0];
  4847. if (obj == null) return result;
  4848. if (isFunction$1(iteratee)) {
  4849. if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
  4850. keys = allKeys(obj);
  4851. } else {
  4852. iteratee = keyInObj;
  4853. keys = flatten(keys, false, false);
  4854. obj = Object(obj);
  4855. }
  4856. for (var i = 0, length = keys.length; i < length; i++) {
  4857. var key = keys[i];
  4858. var value = obj[key];
  4859. if (iteratee(value, key, obj)) result[key] = value;
  4860. }
  4861. return result;
  4862. });
  4863. // Return a copy of the object without the disallowed properties.
  4864. var omit = restArguments(function(obj, keys) {
  4865. var iteratee = keys[0], context;
  4866. if (isFunction$1(iteratee)) {
  4867. iteratee = negate(iteratee);
  4868. if (keys.length > 1) context = keys[1];
  4869. } else {
  4870. keys = map(flatten(keys, false, false), String);
  4871. iteratee = function(value, key) {
  4872. return !contains(keys, key);
  4873. };
  4874. }
  4875. return pick(obj, iteratee, context);
  4876. });
  4877. // Returns everything but the last entry of the array. Especially useful on
  4878. // the arguments object. Passing **n** will return all the values in
  4879. // the array, excluding the last N.
  4880. function initial(array, n, guard) {
  4881. return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  4882. }
  4883. // Get the first element of an array. Passing **n** will return the first N
  4884. // values in the array. The **guard** check allows it to work with `_.map`.
  4885. function first(array, n, guard) {
  4886. if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
  4887. if (n == null || guard) return array[0];
  4888. return initial(array, array.length - n);
  4889. }
  4890. // Returns everything but the first entry of the `array`. Especially useful on
  4891. // the `arguments` object. Passing an **n** will return the rest N values in the
  4892. // `array`.
  4893. function rest(array, n, guard) {
  4894. return slice.call(array, n == null || guard ? 1 : n);
  4895. }
  4896. // Get the last element of an array. Passing **n** will return the last N
  4897. // values in the array.
  4898. function last(array, n, guard) {
  4899. if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
  4900. if (n == null || guard) return array[array.length - 1];
  4901. return rest(array, Math.max(0, array.length - n));
  4902. }
  4903. // Trim out all falsy values from an array.
  4904. function compact(array) {
  4905. return filter(array, Boolean);
  4906. }
  4907. // Flatten out an array, either recursively (by default), or up to `depth`.
  4908. // Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
  4909. function flatten$1(array, depth) {
  4910. return flatten(array, depth, false);
  4911. }
  4912. // Take the difference between one array and a number of other arrays.
  4913. // Only the elements present in just the first array will remain.
  4914. var difference = restArguments(function(array, rest) {
  4915. rest = flatten(rest, true, true);
  4916. return filter(array, function(value){
  4917. return !contains(rest, value);
  4918. });
  4919. });
  4920. // Return a version of the array that does not contain the specified value(s).
  4921. var without = restArguments(function(array, otherArrays) {
  4922. return difference(array, otherArrays);
  4923. });
  4924. // Produce a duplicate-free version of the array. If the array has already
  4925. // been sorted, you have the option of using a faster algorithm.
  4926. // The faster algorithm will not work with an iteratee if the iteratee
  4927. // is not a one-to-one function, so providing an iteratee will disable
  4928. // the faster algorithm.
  4929. function uniq(array, isSorted, iteratee, context) {
  4930. if (!isBoolean(isSorted)) {
  4931. context = iteratee;
  4932. iteratee = isSorted;
  4933. isSorted = false;
  4934. }
  4935. if (iteratee != null) iteratee = cb(iteratee, context);
  4936. var result = [];
  4937. var seen = [];
  4938. for (var i = 0, length = getLength(array); i < length; i++) {
  4939. var value = array[i],
  4940. computed = iteratee ? iteratee(value, i, array) : value;
  4941. if (isSorted && !iteratee) {
  4942. if (!i || seen !== computed) result.push(value);
  4943. seen = computed;
  4944. } else if (iteratee) {
  4945. if (!contains(seen, computed)) {
  4946. seen.push(computed);
  4947. result.push(value);
  4948. }
  4949. } else if (!contains(result, value)) {
  4950. result.push(value);
  4951. }
  4952. }
  4953. return result;
  4954. }
  4955. // Produce an array that contains the union: each distinct element from all of
  4956. // the passed-in arrays.
  4957. var union = restArguments(function(arrays) {
  4958. return uniq(flatten(arrays, true, true));
  4959. });
  4960. // Produce an array that contains every item shared between all the
  4961. // passed-in arrays.
  4962. function intersection(array) {
  4963. var result = [];
  4964. var argsLength = arguments.length;
  4965. for (var i = 0, length = getLength(array); i < length; i++) {
  4966. var item = array[i];
  4967. if (contains(result, item)) continue;
  4968. var j;
  4969. for (j = 1; j < argsLength; j++) {
  4970. if (!contains(arguments[j], item)) break;
  4971. }
  4972. if (j === argsLength) result.push(item);
  4973. }
  4974. return result;
  4975. }
  4976. // Complement of zip. Unzip accepts an array of arrays and groups
  4977. // each array's elements on shared indices.
  4978. function unzip(array) {
  4979. var length = array && max(array, getLength).length || 0;
  4980. var result = Array(length);
  4981. for (var index = 0; index < length; index++) {
  4982. result[index] = pluck(array, index);
  4983. }
  4984. return result;
  4985. }
  4986. // Zip together multiple lists into a single array -- elements that share
  4987. // an index go together.
  4988. var zip = restArguments(unzip);
  4989. // Converts lists into objects. Pass either a single array of `[key, value]`
  4990. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  4991. // the corresponding values. Passing by pairs is the reverse of `_.pairs`.
  4992. function object(list, values) {
  4993. var result = {};
  4994. for (var i = 0, length = getLength(list); i < length; i++) {
  4995. if (values) {
  4996. result[list[i]] = values[i];
  4997. } else {
  4998. result[list[i][0]] = list[i][1];
  4999. }
  5000. }
  5001. return result;
  5002. }
  5003. // Generate an integer Array containing an arithmetic progression. A port of
  5004. // the native Python `range()` function. See
  5005. // [the Python documentation](https://docs.python.org/library/functions.html#range).
  5006. function range(start, stop, step) {
  5007. if (stop == null) {
  5008. stop = start || 0;
  5009. start = 0;
  5010. }
  5011. if (!step) {
  5012. step = stop < start ? -1 : 1;
  5013. }
  5014. var length = Math.max(Math.ceil((stop - start) / step), 0);
  5015. var range = Array(length);
  5016. for (var idx = 0; idx < length; idx++, start += step) {
  5017. range[idx] = start;
  5018. }
  5019. return range;
  5020. }
  5021. // Chunk a single array into multiple arrays, each containing `count` or fewer
  5022. // items.
  5023. function chunk(array, count) {
  5024. if (count == null || count < 1) return [];
  5025. var result = [];
  5026. var i = 0, length = array.length;
  5027. while (i < length) {
  5028. result.push(slice.call(array, i, i += count));
  5029. }
  5030. return result;
  5031. }
  5032. // Helper function to continue chaining intermediate results.
  5033. function chainResult(instance, obj) {
  5034. return instance._chain ? _(obj).chain() : obj;
  5035. }
  5036. // Add your own custom functions to the Underscore object.
  5037. function mixin(obj) {
  5038. each(functions(obj), function(name) {
  5039. var func = _[name] = obj[name];
  5040. _.prototype[name] = function() {
  5041. var args = [this._wrapped];
  5042. push.apply(args, arguments);
  5043. return chainResult(this, func.apply(_, args));
  5044. };
  5045. });
  5046. return _;
  5047. }
  5048. // Add all mutator `Array` functions to the wrapper.
  5049. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  5050. var method = ArrayProto[name];
  5051. _.prototype[name] = function() {
  5052. var obj = this._wrapped;
  5053. if (obj != null) {
  5054. method.apply(obj, arguments);
  5055. if ((name === 'shift' || name === 'splice') && obj.length === 0) {
  5056. delete obj[0];
  5057. }
  5058. }
  5059. return chainResult(this, obj);
  5060. };
  5061. });
  5062. // Add all accessor `Array` functions to the wrapper.
  5063. each(['concat', 'join', 'slice'], function(name) {
  5064. var method = ArrayProto[name];
  5065. _.prototype[name] = function() {
  5066. var obj = this._wrapped;
  5067. if (obj != null) obj = method.apply(obj, arguments);
  5068. return chainResult(this, obj);
  5069. };
  5070. });
  5071. // Named Exports
  5072. var allExports = {
  5073. __proto__: null,
  5074. VERSION: VERSION,
  5075. restArguments: restArguments,
  5076. isObject: isObject,
  5077. isNull: isNull,
  5078. isUndefined: isUndefined,
  5079. isBoolean: isBoolean,
  5080. isElement: isElement,
  5081. isString: isString,
  5082. isNumber: isNumber,
  5083. isDate: isDate,
  5084. isRegExp: isRegExp,
  5085. isError: isError,
  5086. isSymbol: isSymbol,
  5087. isArrayBuffer: isArrayBuffer,
  5088. isDataView: isDataView$1,
  5089. isArray: isArray,
  5090. isFunction: isFunction$1,
  5091. isArguments: isArguments$1,
  5092. isFinite: isFinite$1,
  5093. isNaN: isNaN$1,
  5094. isTypedArray: isTypedArray$1,
  5095. isEmpty: isEmpty,
  5096. isMatch: isMatch,
  5097. isEqual: isEqual,
  5098. isMap: isMap,
  5099. isWeakMap: isWeakMap,
  5100. isSet: isSet,
  5101. isWeakSet: isWeakSet,
  5102. keys: keys,
  5103. allKeys: allKeys,
  5104. values: values,
  5105. pairs: pairs,
  5106. invert: invert,
  5107. functions: functions,
  5108. methods: functions,
  5109. extend: extend,
  5110. extendOwn: extendOwn,
  5111. assign: extendOwn,
  5112. defaults: defaults,
  5113. create: create,
  5114. clone: clone,
  5115. tap: tap,
  5116. get: get,
  5117. has: has$1,
  5118. mapObject: mapObject,
  5119. identity: identity,
  5120. constant: constant,
  5121. noop: noop,
  5122. toPath: toPath,
  5123. property: property,
  5124. propertyOf: propertyOf,
  5125. matcher: matcher,
  5126. matches: matcher,
  5127. times: times,
  5128. random: random,
  5129. now: now,
  5130. escape: _escape,
  5131. unescape: _unescape,
  5132. templateSettings: templateSettings,
  5133. template: template,
  5134. result: result,
  5135. uniqueId: uniqueId,
  5136. chain: chain,
  5137. iteratee: iteratee,
  5138. partial: partial,
  5139. bind: bind,
  5140. bindAll: bindAll,
  5141. memoize: memoize,
  5142. delay: delay,
  5143. defer: defer,
  5144. throttle: throttle,
  5145. debounce: debounce,
  5146. wrap: wrap,
  5147. negate: negate,
  5148. compose: compose,
  5149. after: after,
  5150. before: before,
  5151. once: once,
  5152. findKey: findKey,
  5153. findIndex: findIndex,
  5154. findLastIndex: findLastIndex,
  5155. sortedIndex: sortedIndex,
  5156. indexOf: indexOf,
  5157. lastIndexOf: lastIndexOf,
  5158. find: find,
  5159. detect: find,
  5160. findWhere: findWhere,
  5161. each: each,
  5162. forEach: each,
  5163. map: map,
  5164. collect: map,
  5165. reduce: reduce,
  5166. foldl: reduce,
  5167. inject: reduce,
  5168. reduceRight: reduceRight,
  5169. foldr: reduceRight,
  5170. filter: filter,
  5171. select: filter,
  5172. reject: reject,
  5173. every: every,
  5174. all: every,
  5175. some: some,
  5176. any: some,
  5177. contains: contains,
  5178. includes: contains,
  5179. include: contains,
  5180. invoke: invoke,
  5181. pluck: pluck,
  5182. where: where,
  5183. max: max,
  5184. min: min,
  5185. shuffle: shuffle,
  5186. sample: sample,
  5187. sortBy: sortBy,
  5188. groupBy: groupBy,
  5189. indexBy: indexBy,
  5190. countBy: countBy,
  5191. partition: partition,
  5192. toArray: toArray,
  5193. size: size,
  5194. pick: pick,
  5195. omit: omit,
  5196. first: first,
  5197. head: first,
  5198. take: first,
  5199. initial: initial,
  5200. last: last,
  5201. rest: rest,
  5202. tail: rest,
  5203. drop: rest,
  5204. compact: compact,
  5205. flatten: flatten$1,
  5206. without: without,
  5207. uniq: uniq,
  5208. unique: uniq,
  5209. union: union,
  5210. intersection: intersection,
  5211. difference: difference,
  5212. unzip: unzip,
  5213. transpose: unzip,
  5214. zip: zip,
  5215. object: object,
  5216. range: range,
  5217. chunk: chunk,
  5218. mixin: mixin,
  5219. 'default': _
  5220. };
  5221. // Default Export
  5222. // Add all of the Underscore functions to the wrapper object.
  5223. var _$1 = mixin(allExports);
  5224. // Legacy Node.js API.
  5225. _$1._ = _$1;
  5226. return _$1;
  5227. })));
  5228. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5229. },{}],3:[function(require,module,exports){
  5230. require('jsonform');
  5231. },{"jsonform":1}]},{},[3]);